{
    "file_diffs": [
        {
            "old_file_content": "import abc\nimport asyncio\nimport binascii\nimport collections\nimport mimetypes\nimport cgi\nimport http.cookies\nimport io\nimport json\nimport re\nimport os\n\nfrom urllib.parse import urlsplit, parse_qsl, urlencode, unquote\n\nfrom .abc import AbstractRouter, AbstractMatchInfo\nfrom .helpers import reify\nfrom .log import web_logger\nfrom .multidict import (CaseInsensitiveMultiDict,\n                        CaseInsensitiveMutableMultiDict,\n                        MultiDict,\n                        MutableMultiDict)\nfrom .protocol import Response as ResponseImpl, HttpVersion, HttpVersion11\nfrom .server import ServerHttpProtocol\nfrom .streams import EOF_MARKER\nfrom .websocket import do_handshake, MSG_BINARY, MSG_CLOSE, MSG_PING, MSG_TEXT\nfrom .errors import HttpProcessingError, WebSocketDisconnectedError\n\n\n__all__ = [\n    'WebSocketDisconnectedError',\n    'Application',\n    'HttpVersion',\n    'RequestHandler',\n    'RequestHandlerFactory',\n    'Request',\n    'StreamResponse',\n    'Response',\n    'WebSocketResponse',\n    'UrlDispatcher',\n    'UrlMappingMatchInfo',\n    'HTTPException',\n    'HTTPError',\n    'HTTPRedirection',\n    'HTTPSuccessful',\n    'HTTPOk',\n    'HTTPCreated',\n    'HTTPAccepted',\n    'HTTPNonAuthoritativeInformation',\n    'HTTPNoContent',\n    'HTTPResetContent',\n    'HTTPPartialContent',\n    'HTTPMultipleChoices',\n    'HTTPMovedPermanently',\n    'HTTPFound',\n    'HTTPSeeOther',\n    'HTTPNotModified',\n    'HTTPUseProxy',\n    'HTTPTemporaryRedirect',\n    'HTTPClientError',\n    'HTTPBadRequest',\n    'HTTPUnauthorized',\n    'HTTPPaymentRequired',\n    'HTTPForbidden',\n    'HTTPNotFound',\n    'HTTPMethodNotAllowed',\n    'HTTPNotAcceptable',\n    'HTTPProxyAuthenticationRequired',\n    'HTTPRequestTimeout',\n    'HTTPConflict',\n    'HTTPGone',\n    'HTTPLengthRequired',\n    'HTTPPreconditionFailed',\n    'HTTPRequestEntityTooLarge',\n    'HTTPRequestURITooLong',\n    'HTTPUnsupportedMediaType',\n    'HTTPRequestRangeNotSatisfiable',\n    'HTTPExpectationFailed',\n    'HTTPServerError',\n    'HTTPInternalServerError',\n    'HTTPNotImplemented',\n    'HTTPBadGateway',\n    'HTTPServiceUnavailable',\n    'HTTPGatewayTimeout',\n    'HTTPVersionNotSupported',\n]\n\n\nsentinel = object()\n\n\nclass HeadersMixin:\n\n    _content_type = None\n    _content_dict = None\n    _stored_content_type = sentinel\n\n    def _parse_content_type(self, raw):\n        self._stored_content_type = raw\n        if raw is None:\n            # default value according to RFC 2616\n            self._content_type = 'application/octet-stream'\n            self._content_dict = {}\n        else:\n            self._content_type, self._content_dict = cgi.parse_header(raw)\n\n    @property\n    def content_type(self):\n        \"\"\"The value of content part for Content-Type HTTP header.\"\"\"\n        raw = self.headers.get('Content-Type')\n        if self._stored_content_type != raw:\n            self._parse_content_type(raw)\n        return self._content_type\n\n    @property\n    def charset(self):\n        \"\"\"The value of charset part for Content-Type HTTP header.\"\"\"\n        raw = self.headers.get('Content-Type')\n        if self._stored_content_type != raw:\n            self._parse_content_type(raw)\n        return self._content_dict.get('charset')\n\n    @property\n    def content_length(self):\n        \"\"\"The value of Content-Length HTTP header.\"\"\"\n        l = self.headers.get('Content-Length')\n        if l is None:\n            return None\n        else:\n            return int(l)\n\n\nFileField = collections.namedtuple('Field', 'name filename file content_type')\n\n\n############################################################\n# HTTP Request\n############################################################\n\n\nclass Request(HeadersMixin):\n\n    def __init__(self, app, message, payload, transport, reader, writer,\n                 keep_alive_timeout):\n        self._app = app\n        self._version = message.version\n        self._transport = transport\n        self._reader = reader\n        self._writer = writer\n        self._method = message.method\n        self._host = message.headers.get('HOST')\n        self._path_qs = message.path\n        res = urlsplit(message.path)\n        self._path = unquote(res.path)\n        self._query_string = res.query\n        self._post = None\n        self._post_files_cache = None\n        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(\n            message.headers)\n\n        if self._version < HttpVersion11:\n            self._keep_alive = False\n        elif message.should_close:\n            self._keep_alive = False\n        else:\n            self._keep_alive = bool(keep_alive_timeout)\n\n        # matchdict, route_name, handler\n        # or information about traversal lookup\n        self._match_info = None  # initialized after route resolving\n\n        self._payload = payload\n        self._cookies = None\n\n    @property\n    def method(self):\n        \"\"\"Read only property for getting HTTP method.\n\n        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.\n        \"\"\"\n        return self._method\n\n    @property\n    def version(self):\n        \"\"\"Read only property for getting HTTP version of request.\n\n        Returns aiohttp.protocol.HttpVersion instance.\n        \"\"\"\n        return self._version\n\n    @property\n    def host(self):\n        \"\"\"Read only property for getting *HOST* header of request.\n\n        Returns str or None if HTTP request has no HOST header.\n        \"\"\"\n        return self._host\n\n    @property\n    def path_qs(self):\n        \"\"\"The URL including PATH_INFO and the query string.\n\n        E.g, /app/blog?id=10\n        \"\"\"\n        return self._path_qs\n\n    @property\n    def path(self):\n        \"\"\"The URL including *PATH INFO* without the host or scheme.\n\n        E.g., ``/app/blog``\n        \"\"\"\n        return self._path\n\n    @property\n    def query_string(self):\n        \"\"\"The query string in the URL.\n\n        E.g., id=10\n        \"\"\"\n        return self._query_string\n\n    @reify\n    def GET(self):\n        \"\"\"A multidict with all the variables in the query string.\n\n        Lazy property.\n        \"\"\"\n        return MultiDict(parse_qsl(self._query_string))\n\n    @reify\n    def POST(self):\n        \"\"\"A multidict with all the variables in the POST parameters.\n\n        post() methods has to be called before using this attribute.\n        \"\"\"\n        if self._post is None:\n            raise RuntimeError(\"POST is not available before post()\")\n        return self._post\n\n    @property\n    def headers(self):\n        \"\"\"A case-insensitive multidict with all headers.\n\n        Lazy property.\n        \"\"\"\n        return self._headers\n\n    @property\n    def keep_alive(self):\n        \"\"\"Is keepalive enabled by client?\"\"\"\n        return self._keep_alive\n\n    @property\n    def match_info(self):\n        \"\"\"Result of route resolving.\"\"\"\n        return self._match_info\n\n    @property\n    def app(self):\n        \"\"\"Application instance.\"\"\"\n        return self._app\n\n    @property\n    def transport(self):\n        \"\"\"Transport used for request processing.\"\"\"\n        return self._transport\n\n    @property\n    def cookies(self):\n        \"\"\"Return request cookies.\n\n        A read-only dictionary-like object.\n        \"\"\"\n        if self._cookies is None:\n            raw = self.headers.get('COOKIE', '')\n            parsed = http.cookies.SimpleCookie(raw)\n            self._cookies = MultiDict({key: val.value\n                                       for key, val in parsed.items()})\n        return self._cookies\n\n    @property\n    def payload(self):\n        \"\"\"Return raw paiload stream.\"\"\"\n        return self._payload\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Release request.\n\n        Eat unread part of HTTP BODY if present.\n        \"\"\"\n        chunk = yield from self._payload.readany()\n        while chunk is not EOF_MARKER or chunk:\n            chunk = yield from self._payload.readany()\n\n    @asyncio.coroutine\n    def read(self):\n        \"\"\"Read request body if present.\n\n        Returns bytes object with full request content.\n        \"\"\"\n        body = bytearray()\n        while True:\n            chunk = yield from self._payload.readany()\n            body.extend(chunk)\n            if chunk is EOF_MARKER:\n                break\n        return bytes(body)\n\n    @asyncio.coroutine\n    def text(self):\n        \"\"\"Return BODY as text using encoding from .charset.\"\"\"\n        bytes_body = yield from self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, loader=json.loads):\n        \"\"\"Return BODY as JSON.\"\"\"\n        body = yield from self.text()\n        return loader(body)\n\n    @asyncio.coroutine\n    def post(self):\n        \"\"\"Return POST parameters.\"\"\"\n        if self._post is not None:\n            return self._post\n        if self.method not in ('POST', 'PUT', 'PATCH'):\n            self._post = MultiDict()\n            return self._post\n\n        content_type = self.content_type\n        if (content_type not in ('',\n                                 'application/x-www-form-urlencoded',\n                                 'multipart/form-data')):\n            self._post = MultiDict()\n            return self._post\n\n        body = yield from self.read()\n        content_charset = self.charset or 'utf-8'\n\n        environ = {'REQUEST_METHOD': self.method,\n                   'CONTENT_LENGTH': str(len(body)),\n                   'QUERY_STRING': '',\n                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}\n\n        fs = cgi.FieldStorage(fp=io.BytesIO(body),\n                              environ=environ,\n                              keep_blank_values=True,\n                              encoding=content_charset)\n\n        supported_tranfer_encoding = {\n            'base64': binascii.a2b_base64,\n            'quoted-printable': binascii.a2b_qp\n        }\n\n        out = MutableMultiDict()\n        for field in fs.list or ():\n            transfer_encoding = field.headers.get(\n                'Content-Transfer-Encoding', None)\n            if field.filename:\n                ff = FileField(field.name,\n                               field.filename,\n                               field.file,  # N.B. file closed error\n                               field.type)\n                if self._post_files_cache is None:\n                    self._post_files_cache = {}\n                self._post_files_cache[field.name] = field\n                out.add(field.name, ff)\n            else:\n                value = field.value\n                if transfer_encoding in supported_tranfer_encoding:\n                    # binascii accepts bytes\n                    value = value.encode('utf-8')\n                    value = supported_tranfer_encoding[\n                        transfer_encoding](value)\n                out.add(field.name, value)\n\n        self._post = MultiDict(out.items(getall=True))\n        return self._post\n\n\n############################################################\n# HTTP Response classes\n############################################################\n\n\nclass StreamResponse(HeadersMixin):\n\n    def __init__(self, *, status=200, reason=None):\n        self._body = None\n        self._keep_alive = None\n        self._headers = CaseInsensitiveMutableMultiDict()\n        self._cookies = http.cookies.SimpleCookie()\n        self.set_status(status, reason)\n\n        self._req = None\n        self._resp_impl = None\n        self._eof_sent = False\n\n    def _copy_cookies(self):\n        for cookie in self._cookies.values():\n            value = cookie.output(header='')[1:]\n            self.headers.add('Set-Cookie', value)\n\n    @property\n    def started(self):\n        return self._resp_impl is not None\n\n    @property\n    def status(self):\n        return self._status\n\n    @property\n    def reason(self):\n        return self._reason\n\n    def set_status(self, status, reason=None):\n        self._status = int(status)\n        if reason is None:\n            reason = ResponseImpl.calc_reason(status)\n        self._reason = reason\n\n    @property\n    def keep_alive(self):\n        return self._keep_alive\n\n    def force_close(self):\n        self._keep_alive = False\n\n    @property\n    def headers(self):\n        return self._headers\n\n    @property\n    def cookies(self):\n        return self._cookies\n\n    def set_cookie(self, name, value, *, expires=None,\n                   domain=None, max_age=None, path=None,\n                   secure=None, httponly=None, version=None):\n        \"\"\"Set or update response cookie.\n\n        Sets new cookie or updates existent with new value.\n        Also updates only those params which are not None.\n        \"\"\"\n\n        old = self._cookies.get(name)\n        if old is not None and old.coded_value == '':\n            # deleted cookie\n            self._cookies.pop(name, None)\n\n        self._cookies[name] = value\n        c = self._cookies[name]\n        if expires is not None:\n            c['expires'] = expires\n        if domain is not None:\n            c['domain'] = domain\n        if max_age is not None:\n            c['max-age'] = max_age\n        if path is not None:\n            c['path'] = path\n        if secure is not None:\n            c['secure'] = secure\n        if httponly is not None:\n            c['httponly'] = httponly\n        if version is not None:\n            c['version'] = version\n\n    def del_cookie(self, name, *, domain=None, path=None):\n        \"\"\"Delete cookie.\n\n        Creates new empty expired cookie.\n        \"\"\"\n        # TODO: do we need domain/path here?\n        self._cookies.pop(name, None)\n        self.set_cookie(name, '', max_age=0, domain=domain, path=path)\n\n    @property\n    def content_length(self):\n        # Just a placeholder for adding setter\n        return super().content_length\n\n    @content_length.setter\n    def content_length(self, value):\n        if value is not None:\n            value = int(value)\n            # TODO: raise error if chunked enabled\n            self.headers['Content-Length'] = str(value)\n        elif 'Content-Length' in self.headers:\n            del self.headers['Content-Length']\n\n    @property\n    def content_type(self):\n        # Just a placeholder for adding setter\n        return super().content_type\n\n    @content_type.setter\n    def content_type(self, value):\n        self.content_type  # read header values if needed\n        self._content_type = str(value)\n        self._generate_content_type_header()\n\n    @property\n    def charset(self):\n        # Just a placeholder for adding setter\n        return super().charset\n\n    @charset.setter\n    def charset(self, value):\n        ctype = self.content_type  # read header values if needed\n        if ctype == 'application/octet-stream':\n            raise RuntimeError(\"Setting charset for application/octet-stream \"\n                               \"doesn't make sense, setup content_type first\")\n        if value is None:\n            self._content_dict.pop('charset', None)\n        else:\n            self._content_dict['charset'] = str(value).lower()\n        self._generate_content_type_header()\n\n    def _generate_content_type_header(self):\n        params = '; '.join(\"%s=%s\" % i for i in self._content_dict.items())\n        if params:\n            ctype = self._content_type + '; ' + params\n        else:\n            ctype = self._content_type\n        self.headers['Content-Type'] = ctype\n\n    def _start_pre_check(self, request):\n        if self._resp_impl is not None:\n            if self._req is not request:\n                raise RuntimeError(\n                    'Response has been started with different request.')\n            else:\n                return self._resp_impl\n        else:\n            return None\n\n    def start(self, request):\n        resp_impl = self._start_pre_check(request)\n        if resp_impl is not None:\n            return resp_impl\n\n        self._req = request\n        keep_alive = self._keep_alive\n        if keep_alive is None:\n            keep_alive = request.keep_alive\n        self._keep_alive = keep_alive\n\n        resp_impl = self._resp_impl = ResponseImpl(\n            request._writer,\n            self._status,\n            request.version,\n            not keep_alive,\n            self._reason)\n\n        self._copy_cookies()\n\n        headers = self.headers.items(getall=True)\n        for key, val in headers:\n            resp_impl.add_header(key, val)\n\n        resp_impl.send_headers()\n        return resp_impl\n\n    def write(self, data):\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError('data argument must be byte-ish (%r)',\n                            type(data))\n\n        if self._eof_sent:\n            raise RuntimeError(\"Cannot call write() after write_eof()\")\n        if self._resp_impl is None:\n            raise RuntimeError(\"Cannot call write() before start()\")\n\n        if data:\n            return self._resp_impl.write(data)\n        else:\n            return ()\n\n    @asyncio.coroutine\n    def drain(self):\n        if self._resp_impl is None:\n            raise RuntimeError(\"Response has not been started\")\n        yield from self._resp_impl.transport.drain()\n\n    @asyncio.coroutine\n    def write_eof(self):\n        if self._eof_sent:\n            return\n        if self._resp_impl is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        yield from self._resp_impl.write_eof()\n        self._eof_sent = True\n\n\nclass Response(StreamResponse):\n\n    def __init__(self, *, body=None, status=200,\n                 reason=None, headers=None,\n                 text=None, content_type=None):\n        super().__init__(status=status, reason=reason)\n\n        if headers is not None:\n            self.headers.extend(headers)\n        if content_type:\n            self.content_type = content_type\n\n        if body is not None and text is not None:\n            raise ValueError(\"body and text are not allowed together.\")\n        elif body is not None:\n            self.body = body\n        elif text is not None:\n            self.text = text\n        else:\n            self.body = None\n\n    @property\n    def body(self):\n        return self._body\n\n    @body.setter\n    def body(self, body):\n        if body is not None and not isinstance(body, bytes):\n            raise TypeError('body argument must be bytes (%r)', type(body))\n        self._body = body\n        if body is not None:\n            self.content_length = len(body)\n        else:\n            self.content_length = 0\n\n    @property\n    def text(self):\n        return self._body.decode(self.charset or 'utf-8')\n\n    @text.setter\n    def text(self, text):\n        if text is not None and not isinstance(text, str):\n            raise TypeError('text argument must be str (%r)', type(text))\n\n        if self.content_type == 'application/octet-stream':\n            self.content_type = 'text/plain'\n        if self.charset is None:\n            self.charset = 'utf-8'\n\n        self.body = text.encode(self.charset)\n\n    @asyncio.coroutine\n    def write_eof(self):\n        body = self._body\n        if body is not None:\n            self.write(body)\n        yield from super().write_eof()\n\n\nclass WebSocketResponse(StreamResponse):\n\n    def __init__(self, *, protocols=()):\n        super().__init__(status=101)\n        self._protocols = protocols\n        self._protocol = None\n        self._writer = None\n        self._reader = None\n        self._closing = False\n        self._loop = None\n        self._closing_fut = None\n\n    def start(self, request):\n        # make pre-check to don't hide it by do_handshake() exceptions\n        resp_impl = self._start_pre_check(request)\n        if resp_impl is not None:\n            return resp_impl\n\n        try:\n            status, headers, parser, writer, protocol = do_handshake(\n                request.method, request.headers, request.transport,\n                self._protocols)\n        except HttpProcessingError as err:\n            if err.code == 405:\n                raise HTTPMethodNotAllowed(request.method, ['GET'])\n            elif err.code == 400:\n                raise HTTPBadRequest(text=err.message)\n            else:  # pragma: no cover\n                raise HTTPInternalServerError() from err\n\n        if self.status != status:\n            self.set_status(status)\n        for k, v in headers:\n            self.headers[k] = v\n        self.force_close()\n\n        resp_impl = super().start(request)\n\n        self._reader = request._reader.set_parser(parser)\n        self._writer = writer\n        self._protocol = protocol\n        self._loop = request.app.loop\n        self._closing_fut = asyncio.Future(loop=self._loop)\n\n        return resp_impl\n\n    def can_start(self, request):\n        if self._writer is not None:\n            raise RuntimeError('Already started')\n        try:\n            _, _, _, _, protocol = do_handshake(\n                request.method, request.headers, request.transport,\n                self._protocols)\n        except HttpProcessingError:\n            return False, None\n        else:\n            return True, protocol\n\n    @property\n    def closing(self):\n        return self._closing\n\n    @property\n    def protocol(self):\n        return self._protocol\n\n    def ping(self):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if self._closing:\n            raise RuntimeError('websocket connection is closing')\n        self._writer.ping()\n\n    def send_str(self, data):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if self._closing:\n            raise RuntimeError('websocket connection is closing')\n        if not isinstance(data, str):\n            raise TypeError('data argument must be str (%r)', type(data))\n        self._writer.send(data, binary=False)\n\n    def send_bytes(self, data):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if self._closing:\n            raise RuntimeError('websocket connection is closing')\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError('data argument must be byte-ish (%r)',\n                            type(data))\n        self._writer.send(data, binary=True)\n\n    def close(self, *, code=1000, message=b''):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if not self._closing:\n            self._closing = True\n            self._writer.close(code, message)\n        else:\n            raise RuntimeError('Already closing')\n\n    @asyncio.coroutine\n    def wait_closed(self):\n        if self._closing_fut is None:\n            raise RuntimeError('Call .start() first')\n        yield from self._closing_fut\n\n    @asyncio.coroutine\n    def receive(self):\n        if self._reader is None:\n            raise RuntimeError('Call .start() first')\n        while True:\n            msg = yield from self._reader.read()\n\n            if msg.tp == MSG_CLOSE:\n                if self._closing:\n                    exc = WebSocketDisconnectedError(msg.data, msg.extra)\n                    self._closing_fut.set_exception(exc)\n                    raise exc\n                else:\n                    self._closing = True\n                    self._writer.close(msg.data, msg.extra)\n                    yield from self.drain()\n                    exc = WebSocketDisconnectedError(msg.data, msg.extra)\n                    self._closing_fut.set_exception(exc)\n                    raise exc\n            elif not self._closing:\n                if msg.tp == MSG_PING:\n                    self._writer.pong()\n                elif msg.tp == MSG_TEXT:\n                    return msg.data\n                elif msg.tp == MSG_BINARY:\n                    return msg.data\n\n    def write(self, data):\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n\n############################################################\n# HTTP Exceptions\n############################################################\n\nclass HTTPException(Response, Exception):\n\n    # You should set in subclasses:\n    # status = 200\n\n    status_code = None\n\n    def __init__(self, *, headers=None, reason=None,\n                 body=None, text=None, content_type=None):\n        Response.__init__(self, status=self.status_code,\n                          headers=headers, reason=reason,\n                          body=body, text=text, content_type=content_type)\n        Exception.__init__(self, self.reason)\n        if self.body is None:\n            self.text = \"{}: {}\".format(self.status, self.reason)\n\n\nclass HTTPError(HTTPException):\n    \"\"\"Base class for exceptions with status codes in the 400s and 500s.\"\"\"\n\n\nclass HTTPRedirection(HTTPException):\n    \"\"\"Base class for exceptions with status codes in the 300s.\"\"\"\n\n\nclass HTTPSuccessful(HTTPException):\n    \"\"\"Base class for exceptions with status codes in the 200s.\"\"\"\n\n\nclass HTTPOk(HTTPSuccessful):\n    status_code = 200\n\n\nclass HTTPCreated(HTTPSuccessful):\n    status_code = 201\n\n\nclass HTTPAccepted(HTTPSuccessful):\n    status_code = 202\n\n\nclass HTTPNonAuthoritativeInformation(HTTPSuccessful):\n    status_code = 203\n\n\nclass HTTPNoContent(HTTPSuccessful):\n    status_code = 204\n\n\nclass HTTPResetContent(HTTPSuccessful):\n    status_code = 205\n\n\nclass HTTPPartialContent(HTTPSuccessful):\n    status_code = 206\n\n\n############################################################\n# 3xx redirection\n############################################################\n\n\nclass _HTTPMove(HTTPRedirection):\n\n    def __init__(self, location, *, headers=None, reason=None,\n                 body=None, text=None, content_type=None):\n        if not location:\n            raise ValueError(\"HTTP redirects need a location to redirect to.\")\n        super().__init__(headers=headers, reason=reason,\n                         body=body, text=text, content_type=content_type)\n        self.headers['Location'] = location\n        self.location = location\n\n\nclass HTTPMultipleChoices(_HTTPMove):\n    status_code = 300\n\n\nclass HTTPMovedPermanently(_HTTPMove):\n    status_code = 301\n\n\nclass HTTPFound(_HTTPMove):\n    status_code = 302\n\n\n# This one is safe after a POST (the redirected location will be\n# retrieved with GET):\nclass HTTPSeeOther(_HTTPMove):\n    status_code = 303\n\n\nclass HTTPNotModified(HTTPRedirection):\n    # FIXME: this should include a date or etag header\n    status_code = 304\n\n\nclass HTTPUseProxy(_HTTPMove):\n    # Not a move, but looks a little like one\n    status_code = 305\n\n\nclass HTTPTemporaryRedirect(_HTTPMove):\n    status_code = 307\n\n\n############################################################\n# 4xx client error\n############################################################\n\n\nclass HTTPClientError(HTTPError):\n    pass\n\n\nclass HTTPBadRequest(HTTPClientError):\n    status_code = 400\n\n\nclass HTTPUnauthorized(HTTPClientError):\n    status_code = 401\n\n\nclass HTTPPaymentRequired(HTTPClientError):\n    status_code = 402\n\n\nclass HTTPForbidden(HTTPClientError):\n    status_code = 403\n\n\nclass HTTPNotFound(HTTPClientError):\n    status_code = 404\n\n\nclass HTTPMethodNotAllowed(HTTPClientError):\n    status_code = 405\n\n    def __init__(self, method, allowed_methods, *, headers=None, reason=None,\n                 body=None, text=None, content_type=None):\n        allow = ','.join(sorted(allowed_methods))\n        super().__init__(headers=headers, reason=reason,\n                         body=body, text=text, content_type=content_type)\n        self.headers['Allow'] = allow\n        self.allowed_methods = allowed_methods\n        self.method = method.upper()\n\n\nclass HTTPNotAcceptable(HTTPClientError):\n    status_code = 406\n\n\nclass HTTPProxyAuthenticationRequired(HTTPClientError):\n    status_code = 407\n\n\nclass HTTPRequestTimeout(HTTPClientError):\n    status_code = 408\n\n\nclass HTTPConflict(HTTPClientError):\n    status_code = 409\n\n\nclass HTTPGone(HTTPClientError):\n    status_code = 410\n\n\nclass HTTPLengthRequired(HTTPClientError):\n    status_code = 411\n\n\nclass HTTPPreconditionFailed(HTTPClientError):\n    status_code = 412\n\n\nclass HTTPRequestEntityTooLarge(HTTPClientError):\n    status_code = 413\n\n\nclass HTTPRequestURITooLong(HTTPClientError):\n    status_code = 414\n\n\nclass HTTPUnsupportedMediaType(HTTPClientError):\n    status_code = 415\n\n\nclass HTTPRequestRangeNotSatisfiable(HTTPClientError):\n    status_code = 416\n\n\nclass HTTPExpectationFailed(HTTPClientError):\n    status_code = 417\n\n\n############################################################\n# 5xx Server Error\n############################################################\n#  Response status codes beginning with the digit \"5\" indicate cases in\n#  which the server is aware that it has erred or is incapable of\n#  performing the request. Except when responding to a HEAD request, the\n#  server SHOULD include an entity containing an explanation of the error\n#  situation, and whether it is a temporary or permanent condition. User\n#  agents SHOULD display any included entity to the user. These response\n#  codes are applicable to any request method.\n\n\nclass HTTPServerError(HTTPError):\n    pass\n\n\nclass HTTPInternalServerError(HTTPServerError):\n    status_code = 500\n\n\nclass HTTPNotImplemented(HTTPServerError):\n    status_code = 501\n\n\nclass HTTPBadGateway(HTTPServerError):\n    status_code = 502\n\n\nclass HTTPServiceUnavailable(HTTPServerError):\n    status_code = 503\n\n\nclass HTTPGatewayTimeout(HTTPServerError):\n    status_code = 504\n\n\nclass HTTPVersionNotSupported(HTTPServerError):\n    status_code = 505\n\n\n############################################################\n# UrlDispatcher implementation\n############################################################\n\n\nclass UrlMappingMatchInfo(dict, AbstractMatchInfo):\n\n    def __init__(self, match_dict, route):\n        super().__init__(match_dict)\n        self._route = route\n\n    @property\n    def handler(self):\n        return self._route.handler\n\n    @property\n    def route(self):\n        return self._route\n\n\nclass Route(metaclass=abc.ABCMeta):\n\n    def __init__(self, method, handler, name):\n        self._method = method\n        self._handler = handler\n        self._name = name\n\n    @property\n    def method(self):\n        return self._method\n\n    @property\n    def handler(self):\n        return self._handler\n\n    @property\n    def name(self):\n        return self._name\n\n    @abc.abstractmethod\n    def match(self, path):\n        \"\"\"Return dict with info for given path or\n        None if route cannot process path.\"\"\"\n\n    @abc.abstractmethod\n    def url(self, **kwargs):\n        \"\"\"Construct url for route with additional params.\"\"\"\n\n    @staticmethod\n    def _append_query(url, query):\n        if query is not None:\n            return url + \"?\" + urlencode(query)\n        else:\n            return url\n\n\nclass PlainRoute(Route):\n\n    def __init__(self, method, handler, name, path):\n        super().__init__(method, handler, name)\n        self._path = path\n\n    def match(self, path):\n        # string comparsion about 10 times faster than regexp matching\n        if self._path == path:\n            return {}\n        else:\n            return None\n\n    def url(self, *, query=None):\n        return self._append_query(self._path, query)\n\n    def __repr__(self):\n        name = \"'\" + self.name + \"' \" if self.name is not None else \"\"\n        return \"<PlainRoute {name}[{method}] {path} -> {handler!r}\".format(\n            name=name, method=self.method, path=self._path,\n            handler=self.handler)\n\n\nclass DynamicRoute(Route):\n\n    def __init__(self, method, handler, name, pattern, formatter):\n        super().__init__(method, handler, name)\n        self._pattern = pattern\n        self._formatter = formatter\n\n    def match(self, path):\n        match = self._pattern.match(path)\n        if match is None:\n            return None\n        else:\n            return match.groupdict()\n\n    def url(self, *, parts, query=None):\n        url = self._formatter.format_map(parts)\n        return self._append_query(url, query)\n\n    def __repr__(self):\n        name = \"'\" + self.name + \"' \" if self.name is not None else \"\"\n        return (\"<DynamicRoute {name}[{method}] {formatter} -> {handler!r}\"\n                .format(name=name, method=self.method,\n                        formatter=self._formatter, handler=self.handler))\n\n\nclass StaticRoute(Route):\n\n    def __init__(self, name, prefix, directory):\n        assert prefix.startswith('/'), prefix\n        assert prefix.endswith('/'), prefix\n        super().__init__('GET', self.handle, name)\n        self._prefix = prefix\n        self._prefix_len = len(self._prefix)\n        self._directory = directory\n\n    def match(self, path):\n        if not path.startswith(self._prefix):\n            return None\n        return {'filename': path[self._prefix_len:]}\n\n    def url(self, *, filename, query=None):\n        while filename.startswith('/'):\n            filename = filename[1:]\n        url = self._prefix + filename\n        return self._append_query(url, query)\n\n    @asyncio.coroutine\n    def handle(self, request):\n        resp = StreamResponse()\n        filename = request.match_info['filename']\n        filepath = os.path.join(self._directory, filename)\n        if '..' in filename:\n            raise HTTPNotFound()\n        if not os.path.exists(filepath) or not os.path.isfile(filepath):\n            raise HTTPNotFound()\n\n        ct = mimetypes.guess_type(filename)[0]\n        if not ct:\n            ct = 'application/octet-stream'\n        resp.content_type = ct\n\n        resp.headers['transfer-encoding'] = 'chunked'\n        resp.start(request)\n\n        with open(filepath, 'rb') as f:\n            chunk = f.read(8192)\n            while chunk:\n                resp.write(chunk)\n                chunk = f.read(8192)\n\n        yield from resp.write_eof()\n        return resp\n\n    def __repr__(self):\n        name = \"'\" + self.name + \"' \" if self.name is not None else \"\"\n        return \"<StaticRoute {name}[{method}] {path} -> {directory!r}\".format(\n            name=name, method=self.method, path=self._prefix,\n            directory=self._directory)\n\n\nclass UrlDispatcher(AbstractRouter, collections.abc.Mapping):\n\n    DYN = re.compile(r'^\\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*)\\}$')\n    DYN_WITH_RE = re.compile(\n        r'^\\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*):(?P<re>.+)\\}$')\n    GOOD = r'[^{}/]+'\n    PLAIN = re.compile('^' + GOOD + '$')\n\n    METHODS = {'POST', 'GET', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'}\n\n    def __init__(self):\n        super().__init__()\n        self._urls = []\n        self._routes = {}\n\n    @asyncio.coroutine\n    def resolve(self, request):\n        path = request.path\n        method = request.method\n        allowed_methods = set()\n        for route in self._urls:\n            match_dict = route.match(path)\n            if match_dict is None:\n                continue\n            route_method = route.method\n            if route_method != method:\n                allowed_methods.add(route_method)\n            else:\n                return UrlMappingMatchInfo(match_dict, route)\n        else:\n            if allowed_methods:\n                raise HTTPMethodNotAllowed(method, allowed_methods)\n            else:\n                raise HTTPNotFound()\n\n    def __iter__(self):\n        return iter(self._routes)\n\n    def __len__(self):\n        return len(self._routes)\n\n    def __contains__(self, name):\n        return name in self._routes\n\n    def __getitem__(self, name):\n        return self._routes[name]\n\n    def _register_endpoint(self, route):\n        name = route.name\n        if name is not None:\n            if name in self._routes:\n                raise ValueError('Duplicate {!r}, '\n                                 'already handled by {!r}'\n                                 .format(name, self._routes[name]))\n            else:\n                self._routes[name] = route\n        self._urls.append(route)\n\n    def add_route(self, method, path, handler, *, name=None):\n        assert path.startswith('/')\n        assert callable(handler), handler\n        if not asyncio.iscoroutinefunction(handler):\n            handler = asyncio.coroutine(handler)\n        method = method.upper()\n        assert method in self.METHODS, method\n        parts = []\n        factory = PlainRoute\n        for part in path.split('/'):\n            if not part:\n                continue\n            match = self.DYN.match(part)\n            if match:\n                parts.append('(?P<' + match.group('var') + '>' +\n                             self.GOOD + ')')\n                factory = DynamicRoute\n                continue\n\n            match = self.DYN_WITH_RE.match(part)\n            if match:\n                parts.append('(?P<' + match.group('var') + '>' +\n                             match.group('re') + ')')\n                factory = DynamicRoute\n                continue\n            if self.PLAIN.match(part):\n                parts.append(re.escape(part))\n                continue\n            raise ValueError(\"Invalid path '{}'['{}']\".format(path, part))\n        if factory is PlainRoute:\n            route = PlainRoute(method, handler, name, path)\n        else:\n            pattern = '/' + '/'.join(parts)\n            if path.endswith('/') and pattern != '/':\n                pattern += '/'\n            try:\n                compiled = re.compile('^' + pattern + '$')\n            except re.error as exc:\n                raise ValueError(\n                    \"Bad pattern '{}': {}\".format(pattern, exc)) from None\n            route = DynamicRoute(method, handler, name, compiled, path)\n        self._register_endpoint(route)\n        return route\n\n    def add_static(self, prefix, path, *, name=None):\n        \"\"\"\n        Adds static files view\n        :param prefix - url prefix\n        :param path - folder with files\n        \"\"\"\n        assert prefix.startswith('/')\n        assert os.path.isdir(path), 'Path does not directory %s' % path\n        path = os.path.abspath(path)\n        if not prefix.endswith('/'):\n            prefix += '/'\n        route = StaticRoute(name, prefix, path)\n        self._register_endpoint(route)\n        return route\n\n\n############################################################\n# Application implementation\n############################################################\n\n\nclass RequestHandler(ServerHttpProtocol):\n\n    def __init__(self, manager, app, router, **kwargs):\n        super().__init__(**kwargs)\n\n        self._manager = manager\n        self._app = app\n        self._router = router\n        self._middlewares = app.middlewares\n\n    def connection_made(self, transport):\n        super().connection_made(transport)\n\n        self._manager.connection_made(self, transport)\n\n    def connection_lost(self, exc):\n        self._manager.connection_lost(self, exc)\n\n        super().connection_lost(exc)\n\n    @asyncio.coroutine\n    def handle_request(self, message, payload):\n        now = self._loop.time()\n\n        app = self._app\n        request = Request(app, message, payload,\n                          self.transport, self.reader, self.writer,\n                          self.keep_alive_timeout)\n        try:\n            match_info = yield from self._router.resolve(request)\n\n            assert isinstance(match_info, AbstractMatchInfo), match_info\n\n            request._match_info = match_info\n            handler = match_info.handler\n\n            for factory in reversed(self._middlewares):\n                handler = yield from factory(app, handler)\n            resp = yield from handler(request)\n\n            if not isinstance(resp, StreamResponse):\n                raise RuntimeError(\n                    (\"Handler {!r} should return response instance, \"\n                     \"got {!r} [middlewares {!r}]\").format(\n                         match_info.handler,\n                         type(resp),\n                         self._middlewares))\n        except HTTPException as exc:\n            resp = exc\n\n        resp_msg = resp.start(request)\n        yield from resp.write_eof()\n\n        # notify server about keep-alive\n        self.keep_alive(resp_msg.keep_alive())\n\n        # log access\n        self.log_access(message, None, resp_msg, self._loop.time() - now)\n\n\nclass RequestHandlerFactory:\n\n    def __init__(self, app, router, *,\n                 handler=RequestHandler, loop=None, **kwargs):\n        self._app = app\n        self._router = router\n        self._handler = handler\n        self._loop = loop\n        self._connections = {}\n        self._kwargs = kwargs\n        self._kwargs.setdefault('logger', app.logger)\n\n    @property\n    def connections(self):\n        return list(self._connections.keys())\n\n    def connection_made(self, handler, transport):\n        self._connections[handler] = transport\n\n    def connection_lost(self, handler, exc=None):\n        if handler in self._connections:\n            del self._connections[handler]\n\n    @asyncio.coroutine\n    def finish_connections(self, timeout=None):\n        for handler in self._connections.keys():\n            handler.closing()\n\n        def cleanup():\n            sleep = 0.05\n            while self._connections:\n                yield from asyncio.sleep(sleep, loop=self._loop)\n                if sleep < 5:\n                    sleep = sleep * 2\n\n        if timeout:\n            try:\n                yield from asyncio.wait_for(\n                    cleanup(), timeout, loop=self._loop)\n            except asyncio.TimeoutError:\n                self._app.logger.warning(\n                    \"Not all connections are closed (pending: %d)\",\n                    len(self._connections))\n\n        for transport in self._connections.values():\n            transport.close()\n\n        self._connections.clear()\n\n    def __call__(self):\n        return self._handler(\n            self, self._app, self._router, loop=self._loop, **self._kwargs)\n\n\nclass Application(dict):\n\n    def __init__(self, *, logger=web_logger, loop=None,\n                 router=None, handler_factory=RequestHandlerFactory,\n                 middlewares=(), **kwargs):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n        if router is None:\n            router = UrlDispatcher()\n        assert isinstance(router, AbstractRouter), router\n\n        self._router = router\n        self._handler_factory = handler_factory\n        self._finish_callbacks = []\n        self._loop = loop\n        self.logger = logger\n\n        self.update(**kwargs)\n        for factory in middlewares:\n            assert asyncio.iscoroutinefunction(factory), factory\n        self._middlewares = tuple(middlewares)\n\n    @property\n    def router(self):\n        return self._router\n\n    @property\n    def loop(self):\n        return self._loop\n\n    @property\n    def middlewares(self):\n        return self._middlewares\n\n    def make_handler(self, **kwargs):\n        return self._handler_factory(\n            self, self.router, loop=self.loop, **kwargs)\n\n    @asyncio.coroutine\n    def finish(self):\n        callbacks = self._finish_callbacks\n        self._finish_callbacks = []\n\n        for (cb, args, kwargs) in callbacks:\n            try:\n                res = cb(self, *args, **kwargs)\n                if (asyncio.iscoroutine(res) or\n                        isinstance(res, asyncio.Future)):\n                    yield from res\n            except Exception as exc:\n                self._loop.call_exception_handler({\n                    'message': \"Error in finish callback\",\n                    'exception': exc,\n                    'application': self,\n                })\n\n    def register_on_finish(self, func, *args, **kwargs):\n        self._finish_callbacks.insert(0, (func, args, kwargs))\n",
            "new_file_content": "import abc\nimport asyncio\nimport binascii\nimport collections\nimport mimetypes\nimport cgi\nimport http.cookies\nimport io\nimport json\nimport re\nimport os\n\nfrom urllib.parse import urlsplit, parse_qsl, urlencode, unquote\n\nfrom .abc import AbstractRouter, AbstractMatchInfo\nfrom .helpers import reify\nfrom .log import web_logger\nfrom .multidict import (CaseInsensitiveMultiDict,\n                        CaseInsensitiveMutableMultiDict,\n                        MultiDict,\n                        MutableMultiDict)\nfrom .protocol import Response as ResponseImpl, HttpVersion, HttpVersion11\nfrom .server import ServerHttpProtocol\nfrom .streams import EOF_MARKER\nfrom .websocket import do_handshake, MSG_BINARY, MSG_CLOSE, MSG_PING, MSG_TEXT\nfrom .errors import HttpProcessingError, WebSocketDisconnectedError\n\n\n__all__ = [\n    'WebSocketDisconnectedError',\n    'Application',\n    'HttpVersion',\n    'RequestHandler',\n    'RequestHandlerFactory',\n    'Request',\n    'StreamResponse',\n    'Response',\n    'WebSocketResponse',\n    'UrlDispatcher',\n    'UrlMappingMatchInfo',\n    'HTTPException',\n    'HTTPError',\n    'HTTPRedirection',\n    'HTTPSuccessful',\n    'HTTPOk',\n    'HTTPCreated',\n    'HTTPAccepted',\n    'HTTPNonAuthoritativeInformation',\n    'HTTPNoContent',\n    'HTTPResetContent',\n    'HTTPPartialContent',\n    'HTTPMultipleChoices',\n    'HTTPMovedPermanently',\n    'HTTPFound',\n    'HTTPSeeOther',\n    'HTTPNotModified',\n    'HTTPUseProxy',\n    'HTTPTemporaryRedirect',\n    'HTTPClientError',\n    'HTTPBadRequest',\n    'HTTPUnauthorized',\n    'HTTPPaymentRequired',\n    'HTTPForbidden',\n    'HTTPNotFound',\n    'HTTPMethodNotAllowed',\n    'HTTPNotAcceptable',\n    'HTTPProxyAuthenticationRequired',\n    'HTTPRequestTimeout',\n    'HTTPConflict',\n    'HTTPGone',\n    'HTTPLengthRequired',\n    'HTTPPreconditionFailed',\n    'HTTPRequestEntityTooLarge',\n    'HTTPRequestURITooLong',\n    'HTTPUnsupportedMediaType',\n    'HTTPRequestRangeNotSatisfiable',\n    'HTTPExpectationFailed',\n    'HTTPServerError',\n    'HTTPInternalServerError',\n    'HTTPNotImplemented',\n    'HTTPBadGateway',\n    'HTTPServiceUnavailable',\n    'HTTPGatewayTimeout',\n    'HTTPVersionNotSupported',\n]\n\n\nsentinel = object()\n\n\nclass HeadersMixin:\n\n    _content_type = None\n    _content_dict = None\n    _stored_content_type = sentinel\n\n    def _parse_content_type(self, raw):\n        self._stored_content_type = raw\n        if raw is None:\n            # default value according to RFC 2616\n            self._content_type = 'application/octet-stream'\n            self._content_dict = {}\n        else:\n            self._content_type, self._content_dict = cgi.parse_header(raw)\n\n    @property\n    def content_type(self):\n        \"\"\"The value of content part for Content-Type HTTP header.\"\"\"\n        raw = self.headers.get('Content-Type')\n        if self._stored_content_type != raw:\n            self._parse_content_type(raw)\n        return self._content_type\n\n    @property\n    def charset(self):\n        \"\"\"The value of charset part for Content-Type HTTP header.\"\"\"\n        raw = self.headers.get('Content-Type')\n        if self._stored_content_type != raw:\n            self._parse_content_type(raw)\n        return self._content_dict.get('charset')\n\n    @property\n    def content_length(self):\n        \"\"\"The value of Content-Length HTTP header.\"\"\"\n        l = self.headers.get('Content-Length')\n        if l is None:\n            return None\n        else:\n            return int(l)\n\n\nFileField = collections.namedtuple('Field', 'name filename file content_type')\n\n\n############################################################\n# HTTP Request\n############################################################\n\n\nclass Request(HeadersMixin):\n\n    def __init__(self, app, message, payload, transport, reader, writer):\n        self._app = app\n        self._version = message.version\n        self._transport = transport\n        self._reader = reader\n        self._writer = writer\n        self._method = message.method\n        self._host = message.headers.get('HOST')\n        self._path_qs = message.path\n        res = urlsplit(message.path)\n        self._path = unquote(res.path)\n        self._query_string = res.query\n        self._post = None\n        self._post_files_cache = None\n        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(\n            message.headers)\n\n        if self._version < HttpVersion11:\n            self._keep_alive = False\n        elif message.should_close:\n            self._keep_alive = False\n        else:\n            self._keep_alive = True\n\n        # matchdict, route_name, handler\n        # or information about traversal lookup\n        self._match_info = None  # initialized after route resolving\n\n        self._payload = payload\n        self._cookies = None\n\n    @property\n    def method(self):\n        \"\"\"Read only property for getting HTTP method.\n\n        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.\n        \"\"\"\n        return self._method\n\n    @property\n    def version(self):\n        \"\"\"Read only property for getting HTTP version of request.\n\n        Returns aiohttp.protocol.HttpVersion instance.\n        \"\"\"\n        return self._version\n\n    @property\n    def host(self):\n        \"\"\"Read only property for getting *HOST* header of request.\n\n        Returns str or None if HTTP request has no HOST header.\n        \"\"\"\n        return self._host\n\n    @property\n    def path_qs(self):\n        \"\"\"The URL including PATH_INFO and the query string.\n\n        E.g, /app/blog?id=10\n        \"\"\"\n        return self._path_qs\n\n    @property\n    def path(self):\n        \"\"\"The URL including *PATH INFO* without the host or scheme.\n\n        E.g., ``/app/blog``\n        \"\"\"\n        return self._path\n\n    @property\n    def query_string(self):\n        \"\"\"The query string in the URL.\n\n        E.g., id=10\n        \"\"\"\n        return self._query_string\n\n    @reify\n    def GET(self):\n        \"\"\"A multidict with all the variables in the query string.\n\n        Lazy property.\n        \"\"\"\n        return MultiDict(parse_qsl(self._query_string))\n\n    @reify\n    def POST(self):\n        \"\"\"A multidict with all the variables in the POST parameters.\n\n        post() methods has to be called before using this attribute.\n        \"\"\"\n        if self._post is None:\n            raise RuntimeError(\"POST is not available before post()\")\n        return self._post\n\n    @property\n    def headers(self):\n        \"\"\"A case-insensitive multidict with all headers.\n\n        Lazy property.\n        \"\"\"\n        return self._headers\n\n    @property\n    def keep_alive(self):\n        \"\"\"Is keepalive enabled by client?\"\"\"\n        return self._keep_alive\n\n    @property\n    def match_info(self):\n        \"\"\"Result of route resolving.\"\"\"\n        return self._match_info\n\n    @property\n    def app(self):\n        \"\"\"Application instance.\"\"\"\n        return self._app\n\n    @property\n    def transport(self):\n        \"\"\"Transport used for request processing.\"\"\"\n        return self._transport\n\n    @property\n    def cookies(self):\n        \"\"\"Return request cookies.\n\n        A read-only dictionary-like object.\n        \"\"\"\n        if self._cookies is None:\n            raw = self.headers.get('COOKIE', '')\n            parsed = http.cookies.SimpleCookie(raw)\n            self._cookies = MultiDict({key: val.value\n                                       for key, val in parsed.items()})\n        return self._cookies\n\n    @property\n    def payload(self):\n        \"\"\"Return raw paiload stream.\"\"\"\n        return self._payload\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Release request.\n\n        Eat unread part of HTTP BODY if present.\n        \"\"\"\n        chunk = yield from self._payload.readany()\n        while chunk is not EOF_MARKER or chunk:\n            chunk = yield from self._payload.readany()\n\n    @asyncio.coroutine\n    def read(self):\n        \"\"\"Read request body if present.\n\n        Returns bytes object with full request content.\n        \"\"\"\n        body = bytearray()\n        while True:\n            chunk = yield from self._payload.readany()\n            body.extend(chunk)\n            if chunk is EOF_MARKER:\n                break\n        return bytes(body)\n\n    @asyncio.coroutine\n    def text(self):\n        \"\"\"Return BODY as text using encoding from .charset.\"\"\"\n        bytes_body = yield from self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, loader=json.loads):\n        \"\"\"Return BODY as JSON.\"\"\"\n        body = yield from self.text()\n        return loader(body)\n\n    @asyncio.coroutine\n    def post(self):\n        \"\"\"Return POST parameters.\"\"\"\n        if self._post is not None:\n            return self._post\n        if self.method not in ('POST', 'PUT', 'PATCH'):\n            self._post = MultiDict()\n            return self._post\n\n        content_type = self.content_type\n        if (content_type not in ('',\n                                 'application/x-www-form-urlencoded',\n                                 'multipart/form-data')):\n            self._post = MultiDict()\n            return self._post\n\n        body = yield from self.read()\n        content_charset = self.charset or 'utf-8'\n\n        environ = {'REQUEST_METHOD': self.method,\n                   'CONTENT_LENGTH': str(len(body)),\n                   'QUERY_STRING': '',\n                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}\n\n        fs = cgi.FieldStorage(fp=io.BytesIO(body),\n                              environ=environ,\n                              keep_blank_values=True,\n                              encoding=content_charset)\n\n        supported_tranfer_encoding = {\n            'base64': binascii.a2b_base64,\n            'quoted-printable': binascii.a2b_qp\n        }\n\n        out = MutableMultiDict()\n        for field in fs.list or ():\n            transfer_encoding = field.headers.get(\n                'Content-Transfer-Encoding', None)\n            if field.filename:\n                ff = FileField(field.name,\n                               field.filename,\n                               field.file,  # N.B. file closed error\n                               field.type)\n                if self._post_files_cache is None:\n                    self._post_files_cache = {}\n                self._post_files_cache[field.name] = field\n                out.add(field.name, ff)\n            else:\n                value = field.value\n                if transfer_encoding in supported_tranfer_encoding:\n                    # binascii accepts bytes\n                    value = value.encode('utf-8')\n                    value = supported_tranfer_encoding[\n                        transfer_encoding](value)\n                out.add(field.name, value)\n\n        self._post = MultiDict(out.items(getall=True))\n        return self._post\n\n\n############################################################\n# HTTP Response classes\n############################################################\n\n\nclass StreamResponse(HeadersMixin):\n\n    def __init__(self, *, status=200, reason=None):\n        self._body = None\n        self._keep_alive = None\n        self._headers = CaseInsensitiveMutableMultiDict()\n        self._cookies = http.cookies.SimpleCookie()\n        self.set_status(status, reason)\n\n        self._req = None\n        self._resp_impl = None\n        self._eof_sent = False\n\n    def _copy_cookies(self):\n        for cookie in self._cookies.values():\n            value = cookie.output(header='')[1:]\n            self.headers.add('Set-Cookie', value)\n\n    @property\n    def started(self):\n        return self._resp_impl is not None\n\n    @property\n    def status(self):\n        return self._status\n\n    @property\n    def reason(self):\n        return self._reason\n\n    def set_status(self, status, reason=None):\n        self._status = int(status)\n        if reason is None:\n            reason = ResponseImpl.calc_reason(status)\n        self._reason = reason\n\n    @property\n    def keep_alive(self):\n        return self._keep_alive\n\n    def force_close(self):\n        self._keep_alive = False\n\n    @property\n    def headers(self):\n        return self._headers\n\n    @property\n    def cookies(self):\n        return self._cookies\n\n    def set_cookie(self, name, value, *, expires=None,\n                   domain=None, max_age=None, path=None,\n                   secure=None, httponly=None, version=None):\n        \"\"\"Set or update response cookie.\n\n        Sets new cookie or updates existent with new value.\n        Also updates only those params which are not None.\n        \"\"\"\n\n        old = self._cookies.get(name)\n        if old is not None and old.coded_value == '':\n            # deleted cookie\n            self._cookies.pop(name, None)\n\n        self._cookies[name] = value\n        c = self._cookies[name]\n        if expires is not None:\n            c['expires'] = expires\n        if domain is not None:\n            c['domain'] = domain\n        if max_age is not None:\n            c['max-age'] = max_age\n        if path is not None:\n            c['path'] = path\n        if secure is not None:\n            c['secure'] = secure\n        if httponly is not None:\n            c['httponly'] = httponly\n        if version is not None:\n            c['version'] = version\n\n    def del_cookie(self, name, *, domain=None, path=None):\n        \"\"\"Delete cookie.\n\n        Creates new empty expired cookie.\n        \"\"\"\n        # TODO: do we need domain/path here?\n        self._cookies.pop(name, None)\n        self.set_cookie(name, '', max_age=0, domain=domain, path=path)\n\n    @property\n    def content_length(self):\n        # Just a placeholder for adding setter\n        return super().content_length\n\n    @content_length.setter\n    def content_length(self, value):\n        if value is not None:\n            value = int(value)\n            # TODO: raise error if chunked enabled\n            self.headers['Content-Length'] = str(value)\n        elif 'Content-Length' in self.headers:\n            del self.headers['Content-Length']\n\n    @property\n    def content_type(self):\n        # Just a placeholder for adding setter\n        return super().content_type\n\n    @content_type.setter\n    def content_type(self, value):\n        self.content_type  # read header values if needed\n        self._content_type = str(value)\n        self._generate_content_type_header()\n\n    @property\n    def charset(self):\n        # Just a placeholder for adding setter\n        return super().charset\n\n    @charset.setter\n    def charset(self, value):\n        ctype = self.content_type  # read header values if needed\n        if ctype == 'application/octet-stream':\n            raise RuntimeError(\"Setting charset for application/octet-stream \"\n                               \"doesn't make sense, setup content_type first\")\n        if value is None:\n            self._content_dict.pop('charset', None)\n        else:\n            self._content_dict['charset'] = str(value).lower()\n        self._generate_content_type_header()\n\n    def _generate_content_type_header(self):\n        params = '; '.join(\"%s=%s\" % i for i in self._content_dict.items())\n        if params:\n            ctype = self._content_type + '; ' + params\n        else:\n            ctype = self._content_type\n        self.headers['Content-Type'] = ctype\n\n    def _start_pre_check(self, request):\n        if self._resp_impl is not None:\n            if self._req is not request:\n                raise RuntimeError(\n                    'Response has been started with different request.')\n            else:\n                return self._resp_impl\n        else:\n            return None\n\n    def start(self, request):\n        resp_impl = self._start_pre_check(request)\n        if resp_impl is not None:\n            return resp_impl\n\n        self._req = request\n        keep_alive = self._keep_alive\n        if keep_alive is None:\n            keep_alive = request.keep_alive\n        self._keep_alive = keep_alive\n\n        resp_impl = self._resp_impl = ResponseImpl(\n            request._writer,\n            self._status,\n            request.version,\n            not keep_alive,\n            self._reason)\n\n        self._copy_cookies()\n\n        headers = self.headers.items(getall=True)\n        for key, val in headers:\n            resp_impl.add_header(key, val)\n\n        resp_impl.send_headers()\n        return resp_impl\n\n    def write(self, data):\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError('data argument must be byte-ish (%r)',\n                            type(data))\n\n        if self._eof_sent:\n            raise RuntimeError(\"Cannot call write() after write_eof()\")\n        if self._resp_impl is None:\n            raise RuntimeError(\"Cannot call write() before start()\")\n\n        if data:\n            return self._resp_impl.write(data)\n        else:\n            return ()\n\n    @asyncio.coroutine\n    def drain(self):\n        if self._resp_impl is None:\n            raise RuntimeError(\"Response has not been started\")\n        yield from self._resp_impl.transport.drain()\n\n    @asyncio.coroutine\n    def write_eof(self):\n        if self._eof_sent:\n            return\n        if self._resp_impl is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        yield from self._resp_impl.write_eof()\n        self._eof_sent = True\n\n\nclass Response(StreamResponse):\n\n    def __init__(self, *, body=None, status=200,\n                 reason=None, headers=None,\n                 text=None, content_type=None):\n        super().__init__(status=status, reason=reason)\n\n        if headers is not None:\n            self.headers.extend(headers)\n        if content_type:\n            self.content_type = content_type\n\n        if body is not None and text is not None:\n            raise ValueError(\"body and text are not allowed together.\")\n        elif body is not None:\n            self.body = body\n        elif text is not None:\n            self.text = text\n        else:\n            self.body = None\n\n    @property\n    def body(self):\n        return self._body\n\n    @body.setter\n    def body(self, body):\n        if body is not None and not isinstance(body, bytes):\n            raise TypeError('body argument must be bytes (%r)', type(body))\n        self._body = body\n        if body is not None:\n            self.content_length = len(body)\n        else:\n            self.content_length = 0\n\n    @property\n    def text(self):\n        return self._body.decode(self.charset or 'utf-8')\n\n    @text.setter\n    def text(self, text):\n        if text is not None and not isinstance(text, str):\n            raise TypeError('text argument must be str (%r)', type(text))\n\n        if self.content_type == 'application/octet-stream':\n            self.content_type = 'text/plain'\n        if self.charset is None:\n            self.charset = 'utf-8'\n\n        self.body = text.encode(self.charset)\n\n    @asyncio.coroutine\n    def write_eof(self):\n        body = self._body\n        if body is not None:\n            self.write(body)\n        yield from super().write_eof()\n\n\nclass WebSocketResponse(StreamResponse):\n\n    def __init__(self, *, protocols=()):\n        super().__init__(status=101)\n        self._protocols = protocols\n        self._protocol = None\n        self._writer = None\n        self._reader = None\n        self._closing = False\n        self._loop = None\n        self._closing_fut = None\n\n    def start(self, request):\n        # make pre-check to don't hide it by do_handshake() exceptions\n        resp_impl = self._start_pre_check(request)\n        if resp_impl is not None:\n            return resp_impl\n\n        try:\n            status, headers, parser, writer, protocol = do_handshake(\n                request.method, request.headers, request.transport,\n                self._protocols)\n        except HttpProcessingError as err:\n            if err.code == 405:\n                raise HTTPMethodNotAllowed(request.method, ['GET'])\n            elif err.code == 400:\n                raise HTTPBadRequest(text=err.message)\n            else:  # pragma: no cover\n                raise HTTPInternalServerError() from err\n\n        if self.status != status:\n            self.set_status(status)\n        for k, v in headers:\n            self.headers[k] = v\n        self.force_close()\n\n        resp_impl = super().start(request)\n\n        self._reader = request._reader.set_parser(parser)\n        self._writer = writer\n        self._protocol = protocol\n        self._loop = request.app.loop\n        self._closing_fut = asyncio.Future(loop=self._loop)\n\n        return resp_impl\n\n    def can_start(self, request):\n        if self._writer is not None:\n            raise RuntimeError('Already started')\n        try:\n            _, _, _, _, protocol = do_handshake(\n                request.method, request.headers, request.transport,\n                self._protocols)\n        except HttpProcessingError:\n            return False, None\n        else:\n            return True, protocol\n\n    @property\n    def closing(self):\n        return self._closing\n\n    @property\n    def protocol(self):\n        return self._protocol\n\n    def ping(self):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if self._closing:\n            raise RuntimeError('websocket connection is closing')\n        self._writer.ping()\n\n    def send_str(self, data):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if self._closing:\n            raise RuntimeError('websocket connection is closing')\n        if not isinstance(data, str):\n            raise TypeError('data argument must be str (%r)', type(data))\n        self._writer.send(data, binary=False)\n\n    def send_bytes(self, data):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if self._closing:\n            raise RuntimeError('websocket connection is closing')\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError('data argument must be byte-ish (%r)',\n                            type(data))\n        self._writer.send(data, binary=True)\n\n    def close(self, *, code=1000, message=b''):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if not self._closing:\n            self._closing = True\n            self._writer.close(code, message)\n        else:\n            raise RuntimeError('Already closing')\n\n    @asyncio.coroutine\n    def wait_closed(self):\n        if self._closing_fut is None:\n            raise RuntimeError('Call .start() first')\n        yield from self._closing_fut\n\n    @asyncio.coroutine\n    def receive(self):\n        if self._reader is None:\n            raise RuntimeError('Call .start() first')\n        while True:\n            msg = yield from self._reader.read()\n\n            if msg.tp == MSG_CLOSE:\n                if self._closing:\n                    exc = WebSocketDisconnectedError(msg.data, msg.extra)\n                    self._closing_fut.set_exception(exc)\n                    raise exc\n                else:\n                    self._closing = True\n                    self._writer.close(msg.data, msg.extra)\n                    yield from self.drain()\n                    exc = WebSocketDisconnectedError(msg.data, msg.extra)\n                    self._closing_fut.set_exception(exc)\n                    raise exc\n            elif not self._closing:\n                if msg.tp == MSG_PING:\n                    self._writer.pong()\n                elif msg.tp == MSG_TEXT:\n                    return msg.data\n                elif msg.tp == MSG_BINARY:\n                    return msg.data\n\n    def write(self, data):\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n\n############################################################\n# HTTP Exceptions\n############################################################\n\nclass HTTPException(Response, Exception):\n\n    # You should set in subclasses:\n    # status = 200\n\n    status_code = None\n\n    def __init__(self, *, headers=None, reason=None,\n                 body=None, text=None, content_type=None):\n        Response.__init__(self, status=self.status_code,\n                          headers=headers, reason=reason,\n                          body=body, text=text, content_type=content_type)\n        Exception.__init__(self, self.reason)\n        if self.body is None:\n            self.text = \"{}: {}\".format(self.status, self.reason)\n\n\nclass HTTPError(HTTPException):\n    \"\"\"Base class for exceptions with status codes in the 400s and 500s.\"\"\"\n\n\nclass HTTPRedirection(HTTPException):\n    \"\"\"Base class for exceptions with status codes in the 300s.\"\"\"\n\n\nclass HTTPSuccessful(HTTPException):\n    \"\"\"Base class for exceptions with status codes in the 200s.\"\"\"\n\n\nclass HTTPOk(HTTPSuccessful):\n    status_code = 200\n\n\nclass HTTPCreated(HTTPSuccessful):\n    status_code = 201\n\n\nclass HTTPAccepted(HTTPSuccessful):\n    status_code = 202\n\n\nclass HTTPNonAuthoritativeInformation(HTTPSuccessful):\n    status_code = 203\n\n\nclass HTTPNoContent(HTTPSuccessful):\n    status_code = 204\n\n\nclass HTTPResetContent(HTTPSuccessful):\n    status_code = 205\n\n\nclass HTTPPartialContent(HTTPSuccessful):\n    status_code = 206\n\n\n############################################################\n# 3xx redirection\n############################################################\n\n\nclass _HTTPMove(HTTPRedirection):\n\n    def __init__(self, location, *, headers=None, reason=None,\n                 body=None, text=None, content_type=None):\n        if not location:\n            raise ValueError(\"HTTP redirects need a location to redirect to.\")\n        super().__init__(headers=headers, reason=reason,\n                         body=body, text=text, content_type=content_type)\n        self.headers['Location'] = location\n        self.location = location\n\n\nclass HTTPMultipleChoices(_HTTPMove):\n    status_code = 300\n\n\nclass HTTPMovedPermanently(_HTTPMove):\n    status_code = 301\n\n\nclass HTTPFound(_HTTPMove):\n    status_code = 302\n\n\n# This one is safe after a POST (the redirected location will be\n# retrieved with GET):\nclass HTTPSeeOther(_HTTPMove):\n    status_code = 303\n\n\nclass HTTPNotModified(HTTPRedirection):\n    # FIXME: this should include a date or etag header\n    status_code = 304\n\n\nclass HTTPUseProxy(_HTTPMove):\n    # Not a move, but looks a little like one\n    status_code = 305\n\n\nclass HTTPTemporaryRedirect(_HTTPMove):\n    status_code = 307\n\n\n############################################################\n# 4xx client error\n############################################################\n\n\nclass HTTPClientError(HTTPError):\n    pass\n\n\nclass HTTPBadRequest(HTTPClientError):\n    status_code = 400\n\n\nclass HTTPUnauthorized(HTTPClientError):\n    status_code = 401\n\n\nclass HTTPPaymentRequired(HTTPClientError):\n    status_code = 402\n\n\nclass HTTPForbidden(HTTPClientError):\n    status_code = 403\n\n\nclass HTTPNotFound(HTTPClientError):\n    status_code = 404\n\n\nclass HTTPMethodNotAllowed(HTTPClientError):\n    status_code = 405\n\n    def __init__(self, method, allowed_methods, *, headers=None, reason=None,\n                 body=None, text=None, content_type=None):\n        allow = ','.join(sorted(allowed_methods))\n        super().__init__(headers=headers, reason=reason,\n                         body=body, text=text, content_type=content_type)\n        self.headers['Allow'] = allow\n        self.allowed_methods = allowed_methods\n        self.method = method.upper()\n\n\nclass HTTPNotAcceptable(HTTPClientError):\n    status_code = 406\n\n\nclass HTTPProxyAuthenticationRequired(HTTPClientError):\n    status_code = 407\n\n\nclass HTTPRequestTimeout(HTTPClientError):\n    status_code = 408\n\n\nclass HTTPConflict(HTTPClientError):\n    status_code = 409\n\n\nclass HTTPGone(HTTPClientError):\n    status_code = 410\n\n\nclass HTTPLengthRequired(HTTPClientError):\n    status_code = 411\n\n\nclass HTTPPreconditionFailed(HTTPClientError):\n    status_code = 412\n\n\nclass HTTPRequestEntityTooLarge(HTTPClientError):\n    status_code = 413\n\n\nclass HTTPRequestURITooLong(HTTPClientError):\n    status_code = 414\n\n\nclass HTTPUnsupportedMediaType(HTTPClientError):\n    status_code = 415\n\n\nclass HTTPRequestRangeNotSatisfiable(HTTPClientError):\n    status_code = 416\n\n\nclass HTTPExpectationFailed(HTTPClientError):\n    status_code = 417\n\n\n############################################################\n# 5xx Server Error\n############################################################\n#  Response status codes beginning with the digit \"5\" indicate cases in\n#  which the server is aware that it has erred or is incapable of\n#  performing the request. Except when responding to a HEAD request, the\n#  server SHOULD include an entity containing an explanation of the error\n#  situation, and whether it is a temporary or permanent condition. User\n#  agents SHOULD display any included entity to the user. These response\n#  codes are applicable to any request method.\n\n\nclass HTTPServerError(HTTPError):\n    pass\n\n\nclass HTTPInternalServerError(HTTPServerError):\n    status_code = 500\n\n\nclass HTTPNotImplemented(HTTPServerError):\n    status_code = 501\n\n\nclass HTTPBadGateway(HTTPServerError):\n    status_code = 502\n\n\nclass HTTPServiceUnavailable(HTTPServerError):\n    status_code = 503\n\n\nclass HTTPGatewayTimeout(HTTPServerError):\n    status_code = 504\n\n\nclass HTTPVersionNotSupported(HTTPServerError):\n    status_code = 505\n\n\n############################################################\n# UrlDispatcher implementation\n############################################################\n\n\nclass UrlMappingMatchInfo(dict, AbstractMatchInfo):\n\n    def __init__(self, match_dict, route):\n        super().__init__(match_dict)\n        self._route = route\n\n    @property\n    def handler(self):\n        return self._route.handler\n\n    @property\n    def route(self):\n        return self._route\n\n\nclass Route(metaclass=abc.ABCMeta):\n\n    def __init__(self, method, handler, name):\n        self._method = method\n        self._handler = handler\n        self._name = name\n\n    @property\n    def method(self):\n        return self._method\n\n    @property\n    def handler(self):\n        return self._handler\n\n    @property\n    def name(self):\n        return self._name\n\n    @abc.abstractmethod\n    def match(self, path):\n        \"\"\"Return dict with info for given path or\n        None if route cannot process path.\"\"\"\n\n    @abc.abstractmethod\n    def url(self, **kwargs):\n        \"\"\"Construct url for route with additional params.\"\"\"\n\n    @staticmethod\n    def _append_query(url, query):\n        if query is not None:\n            return url + \"?\" + urlencode(query)\n        else:\n            return url\n\n\nclass PlainRoute(Route):\n\n    def __init__(self, method, handler, name, path):\n        super().__init__(method, handler, name)\n        self._path = path\n\n    def match(self, path):\n        # string comparsion about 10 times faster than regexp matching\n        if self._path == path:\n            return {}\n        else:\n            return None\n\n    def url(self, *, query=None):\n        return self._append_query(self._path, query)\n\n    def __repr__(self):\n        name = \"'\" + self.name + \"' \" if self.name is not None else \"\"\n        return \"<PlainRoute {name}[{method}] {path} -> {handler!r}\".format(\n            name=name, method=self.method, path=self._path,\n            handler=self.handler)\n\n\nclass DynamicRoute(Route):\n\n    def __init__(self, method, handler, name, pattern, formatter):\n        super().__init__(method, handler, name)\n        self._pattern = pattern\n        self._formatter = formatter\n\n    def match(self, path):\n        match = self._pattern.match(path)\n        if match is None:\n            return None\n        else:\n            return match.groupdict()\n\n    def url(self, *, parts, query=None):\n        url = self._formatter.format_map(parts)\n        return self._append_query(url, query)\n\n    def __repr__(self):\n        name = \"'\" + self.name + \"' \" if self.name is not None else \"\"\n        return (\"<DynamicRoute {name}[{method}] {formatter} -> {handler!r}\"\n                .format(name=name, method=self.method,\n                        formatter=self._formatter, handler=self.handler))\n\n\nclass StaticRoute(Route):\n\n    def __init__(self, name, prefix, directory):\n        assert prefix.startswith('/'), prefix\n        assert prefix.endswith('/'), prefix\n        super().__init__('GET', self.handle, name)\n        self._prefix = prefix\n        self._prefix_len = len(self._prefix)\n        self._directory = directory\n\n    def match(self, path):\n        if not path.startswith(self._prefix):\n            return None\n        return {'filename': path[self._prefix_len:]}\n\n    def url(self, *, filename, query=None):\n        while filename.startswith('/'):\n            filename = filename[1:]\n        url = self._prefix + filename\n        return self._append_query(url, query)\n\n    @asyncio.coroutine\n    def handle(self, request):\n        resp = StreamResponse()\n        filename = request.match_info['filename']\n        filepath = os.path.join(self._directory, filename)\n        if '..' in filename:\n            raise HTTPNotFound()\n        if not os.path.exists(filepath) or not os.path.isfile(filepath):\n            raise HTTPNotFound()\n\n        ct = mimetypes.guess_type(filename)[0]\n        if not ct:\n            ct = 'application/octet-stream'\n        resp.content_type = ct\n\n        resp.headers['transfer-encoding'] = 'chunked'\n        resp.start(request)\n\n        with open(filepath, 'rb') as f:\n            chunk = f.read(8192)\n            while chunk:\n                resp.write(chunk)\n                chunk = f.read(8192)\n\n        yield from resp.write_eof()\n        return resp\n\n    def __repr__(self):\n        name = \"'\" + self.name + \"' \" if self.name is not None else \"\"\n        return \"<StaticRoute {name}[{method}] {path} -> {directory!r}\".format(\n            name=name, method=self.method, path=self._prefix,\n            directory=self._directory)\n\n\nclass UrlDispatcher(AbstractRouter, collections.abc.Mapping):\n\n    DYN = re.compile(r'^\\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*)\\}$')\n    DYN_WITH_RE = re.compile(\n        r'^\\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*):(?P<re>.+)\\}$')\n    GOOD = r'[^{}/]+'\n    PLAIN = re.compile('^' + GOOD + '$')\n\n    METHODS = {'POST', 'GET', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'}\n\n    def __init__(self):\n        super().__init__()\n        self._urls = []\n        self._routes = {}\n\n    @asyncio.coroutine\n    def resolve(self, request):\n        path = request.path\n        method = request.method\n        allowed_methods = set()\n        for route in self._urls:\n            match_dict = route.match(path)\n            if match_dict is None:\n                continue\n            route_method = route.method\n            if route_method != method:\n                allowed_methods.add(route_method)\n            else:\n                return UrlMappingMatchInfo(match_dict, route)\n        else:\n            if allowed_methods:\n                raise HTTPMethodNotAllowed(method, allowed_methods)\n            else:\n                raise HTTPNotFound()\n\n    def __iter__(self):\n        return iter(self._routes)\n\n    def __len__(self):\n        return len(self._routes)\n\n    def __contains__(self, name):\n        return name in self._routes\n\n    def __getitem__(self, name):\n        return self._routes[name]\n\n    def _register_endpoint(self, route):\n        name = route.name\n        if name is not None:\n            if name in self._routes:\n                raise ValueError('Duplicate {!r}, '\n                                 'already handled by {!r}'\n                                 .format(name, self._routes[name]))\n            else:\n                self._routes[name] = route\n        self._urls.append(route)\n\n    def add_route(self, method, path, handler, *, name=None):\n        assert path.startswith('/')\n        assert callable(handler), handler\n        if not asyncio.iscoroutinefunction(handler):\n            handler = asyncio.coroutine(handler)\n        method = method.upper()\n        assert method in self.METHODS, method\n        parts = []\n        factory = PlainRoute\n        for part in path.split('/'):\n            if not part:\n                continue\n            match = self.DYN.match(part)\n            if match:\n                parts.append('(?P<' + match.group('var') + '>' +\n                             self.GOOD + ')')\n                factory = DynamicRoute\n                continue\n\n            match = self.DYN_WITH_RE.match(part)\n            if match:\n                parts.append('(?P<' + match.group('var') + '>' +\n                             match.group('re') + ')')\n                factory = DynamicRoute\n                continue\n            if self.PLAIN.match(part):\n                parts.append(re.escape(part))\n                continue\n            raise ValueError(\"Invalid path '{}'['{}']\".format(path, part))\n        if factory is PlainRoute:\n            route = PlainRoute(method, handler, name, path)\n        else:\n            pattern = '/' + '/'.join(parts)\n            if path.endswith('/') and pattern != '/':\n                pattern += '/'\n            try:\n                compiled = re.compile('^' + pattern + '$')\n            except re.error as exc:\n                raise ValueError(\n                    \"Bad pattern '{}': {}\".format(pattern, exc)) from None\n            route = DynamicRoute(method, handler, name, compiled, path)\n        self._register_endpoint(route)\n        return route\n\n    def add_static(self, prefix, path, *, name=None):\n        \"\"\"\n        Adds static files view\n        :param prefix - url prefix\n        :param path - folder with files\n        \"\"\"\n        assert prefix.startswith('/')\n        assert os.path.isdir(path), 'Path does not directory %s' % path\n        path = os.path.abspath(path)\n        if not prefix.endswith('/'):\n            prefix += '/'\n        route = StaticRoute(name, prefix, path)\n        self._register_endpoint(route)\n        return route\n\n\n############################################################\n# Application implementation\n############################################################\n\n\nclass RequestHandler(ServerHttpProtocol):\n\n    def __init__(self, manager, app, router, **kwargs):\n        super().__init__(**kwargs)\n\n        self._manager = manager\n        self._app = app\n        self._router = router\n        self._middlewares = app.middlewares\n\n    def connection_made(self, transport):\n        super().connection_made(transport)\n\n        self._manager.connection_made(self, transport)\n\n    def connection_lost(self, exc):\n        self._manager.connection_lost(self, exc)\n\n        super().connection_lost(exc)\n\n    @asyncio.coroutine\n    def handle_request(self, message, payload):\n        now = self._loop.time()\n\n        app = self._app\n        request = Request(app, message, payload,\n                          self.transport, self.reader, self.writer)\n        try:\n            match_info = yield from self._router.resolve(request)\n\n            assert isinstance(match_info, AbstractMatchInfo), match_info\n\n            request._match_info = match_info\n            handler = match_info.handler\n\n            for factory in reversed(self._middlewares):\n                handler = yield from factory(app, handler)\n            resp = yield from handler(request)\n\n            if not isinstance(resp, StreamResponse):\n                raise RuntimeError(\n                    (\"Handler {!r} should return response instance, \"\n                     \"got {!r} [middlewares {!r}]\").format(\n                         match_info.handler,\n                         type(resp),\n                         self._middlewares))\n        except HTTPException as exc:\n            resp = exc\n\n        resp_msg = resp.start(request)\n        yield from resp.write_eof()\n\n        # notify server about keep-alive\n        self.keep_alive(resp_msg.keep_alive())\n\n        # log access\n        self.log_access(message, None, resp_msg, self._loop.time() - now)\n\n\nclass RequestHandlerFactory:\n\n    def __init__(self, app, router, *,\n                 handler=RequestHandler, loop=None, **kwargs):\n        self._app = app\n        self._router = router\n        self._handler = handler\n        self._loop = loop\n        self._connections = {}\n        self._kwargs = kwargs\n        self._kwargs.setdefault('logger', app.logger)\n\n    @property\n    def connections(self):\n        return list(self._connections.keys())\n\n    def connection_made(self, handler, transport):\n        self._connections[handler] = transport\n\n    def connection_lost(self, handler, exc=None):\n        if handler in self._connections:\n            del self._connections[handler]\n\n    @asyncio.coroutine\n    def finish_connections(self, timeout=None):\n        for handler in self._connections.keys():\n            handler.closing()\n\n        def cleanup():\n            sleep = 0.05\n            while self._connections:\n                yield from asyncio.sleep(sleep, loop=self._loop)\n                if sleep < 5:\n                    sleep = sleep * 2\n\n        if timeout:\n            try:\n                yield from asyncio.wait_for(\n                    cleanup(), timeout, loop=self._loop)\n            except asyncio.TimeoutError:\n                self._app.logger.warning(\n                    \"Not all connections are closed (pending: %d)\",\n                    len(self._connections))\n\n        for transport in self._connections.values():\n            transport.close()\n\n        self._connections.clear()\n\n    def __call__(self):\n        return self._handler(\n            self, self._app, self._router, loop=self._loop, **self._kwargs)\n\n\nclass Application(dict):\n\n    def __init__(self, *, logger=web_logger, loop=None,\n                 router=None, handler_factory=RequestHandlerFactory,\n                 middlewares=(), **kwargs):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n        if router is None:\n            router = UrlDispatcher()\n        assert isinstance(router, AbstractRouter), router\n\n        self._router = router\n        self._handler_factory = handler_factory\n        self._finish_callbacks = []\n        self._loop = loop\n        self.logger = logger\n\n        self.update(**kwargs)\n        for factory in middlewares:\n            assert asyncio.iscoroutinefunction(factory), factory\n        self._middlewares = tuple(middlewares)\n\n    @property\n    def router(self):\n        return self._router\n\n    @property\n    def loop(self):\n        return self._loop\n\n    @property\n    def middlewares(self):\n        return self._middlewares\n\n    def make_handler(self, **kwargs):\n        return self._handler_factory(\n            self, self.router, loop=self.loop, **kwargs)\n\n    @asyncio.coroutine\n    def finish(self):\n        callbacks = self._finish_callbacks\n        self._finish_callbacks = []\n\n        for (cb, args, kwargs) in callbacks:\n            try:\n                res = cb(self, *args, **kwargs)\n                if (asyncio.iscoroutine(res) or\n                        isinstance(res, asyncio.Future)):\n                    yield from res\n            except Exception as exc:\n                self._loop.call_exception_handler({\n                    'message': \"Error in finish callback\",\n                    'exception': exc,\n                    'application': self,\n                })\n\n    def register_on_finish(self, func, *args, **kwargs):\n        self._finish_callbacks.insert(0, (func, args, kwargs))\n",
            "header": {
                "file": {
                    "path": "aiohttp/web.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "78e4d747",
                "new_commit_hash": "af40a470",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/aiohttp/web.py"
            },
            "plus_file": {
                "path": "b/aiohttp/web.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 139,
                            "length": 8
                        },
                        "new_range": {
                            "start": 139,
                            "length": 7
                        },
                        "section": "FileField = collections.namedtuple('Field', 'name filename file content_type')"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class Request(HeadersMixin):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def __init__(self, app, message, payload, transport, reader, writer,",
                                "type": "deleted"
                            },
                            {
                                "content": "                 keep_alive_timeout):",
                                "type": "deleted"
                            },
                            {
                                "content": "    def __init__(self, app, message, payload, transport, reader, writer):",
                                "type": "added"
                            },
                            {
                                "content": "        self._app = app",
                                "type": "context"
                            },
                            {
                                "content": "        self._version = message.version",
                                "type": "context"
                            },
                            {
                                "content": "        self._transport = transport",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/web.py",
                            "type": "method",
                            "name": "Request.__init__",
                            "content": "class Request(HeadersMixin):\n\n    def __init__(self, app, message, payload, transport, reader, writer,\n                 keep_alive_timeout):\n        self._app = app\n        self._version = message.version\n        self._transport = transport\n        self._reader = reader\n        self._writer = writer\n        self._method = message.method\n        self._host = message.headers.get('HOST')\n        self._path_qs = message.path\n        res = urlsplit(message.path)\n        self._path = unquote(res.path)\n        self._query_string = res.query\n        self._post = None\n        self._post_files_cache = None\n        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(\n            message.headers)\n\n        if self._version < HttpVersion11:\n            self._keep_alive = False\n        elif message.should_close:\n            self._keep_alive = False\n        else:\n            self._keep_alive = bool(keep_alive_timeout)\n\n        # matchdict, route_name, handler\n        # or information about traversal lookup\n        self._match_info = None  # initialized after route resolving\n\n        self._payload = payload\n        self._cookies = None\n\n    @property\n    def method(self):\n        \"\"\"Read only property for getting HTTP method.\n\n        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.\n        \"\"\"\n        return self._method\n\n    @property\n    def version(self):\n        \"\"\"Read only property for getting HTTP version of request.\n\n        Returns aiohttp.protocol.HttpVersion instance.\n        \"\"\"\n        return self._version\n\n    @property\n    def host(self):\n        \"\"\"Read only property for getting *HOST* header of request.\n\n        Returns str or None if HTTP request has no HOST header.\n        \"\"\"\n        return self._host\n\n    @property\n    def path_qs(self):\n        \"\"\"The URL including PATH_INFO and the query string.\n\n        E.g, /app/blog?id=10\n        \"\"\"\n        return self._path_qs\n\n    @property\n    def path(self):\n        \"\"\"The URL including *PATH INFO* without the host or scheme.\n\n        E.g., ``/app/blog``\n        \"\"\"\n        return self._path\n\n    @property\n    def query_string(self):\n        \"\"\"The query string in the URL.\n\n        E.g., id=10\n        \"\"\"\n        return self._query_string\n\n    @reify\n    def GET(self):\n        \"\"\"A multidict with all the variables in the query string.\n\n        Lazy property.\n        \"\"\"\n        return MultiDict(parse_qsl(self._query_string))\n\n    @reify\n    def POST(self):\n        \"\"\"A multidict with all the variables in the POST parameters.\n\n        post() methods has to be called before using this attribute.\n        \"\"\"\n        if self._post is None:\n            raise RuntimeError(\"POST is not available before post()\")\n        return self._post\n\n    @property\n    def headers(self):\n        \"\"\"A case-insensitive multidict with all headers.\n\n        Lazy property.\n        \"\"\"\n        return self._headers\n\n    @property\n    def keep_alive(self):\n        \"\"\"Is keepalive enabled by client?\"\"\"\n        return self._keep_alive\n\n    @property\n    def match_info(self):\n        \"\"\"Result of route resolving.\"\"\"\n        return self._match_info\n\n    @property\n    def app(self):\n        \"\"\"Application instance.\"\"\"\n        return self._app\n\n    @property\n    def transport(self):\n        \"\"\"Transport used for request processing.\"\"\"\n        return self._transport\n\n    @property\n    def cookies(self):\n        \"\"\"Return request cookies.\n\n        A read-only dictionary-like object.\n        \"\"\"\n        if self._cookies is None:\n            raw = self.headers.get('COOKIE', '')\n            parsed = http.cookies.SimpleCookie(raw)\n            self._cookies = MultiDict({key: val.value\n                                       for key, val in parsed.items()})\n        return self._cookies\n\n    @property\n    def payload(self):\n        \"\"\"Return raw paiload stream.\"\"\"\n        return self._payload\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Release request.\n\n        Eat unread part of HTTP BODY if present.\n        \"\"\"\n        chunk = yield from self._payload.readany()\n        while chunk is not EOF_MARKER or chunk:\n            chunk = yield from self._payload.readany()\n\n    @asyncio.coroutine\n    def read(self):\n        \"\"\"Read request body if present.\n\n        Returns bytes object with full request content.\n        \"\"\"\n        body = bytearray()\n        while True:\n            chunk = yield from self._payload.readany()\n            body.extend(chunk)\n            if chunk is EOF_MARKER:\n                break\n        return bytes(body)\n\n    @asyncio.coroutine\n    def text(self):\n        \"\"\"Return BODY as text using encoding from .charset.\"\"\"\n        bytes_body = yield from self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, loader=json.loads):\n        \"\"\"Return BODY as JSON.\"\"\"\n        body = yield from self.text()\n        return loader(body)\n\n    @asyncio.coroutine\n    def post(self):\n        \"\"\"Return POST parameters.\"\"\"\n        if self._post is not None:\n            return self._post\n        if self.method not in ('POST', 'PUT', 'PATCH'):\n            self._post = MultiDict()\n            return self._post\n\n        content_type = self.content_type\n        if (content_type not in ('',\n                                 'application/x-www-form-urlencoded',\n                                 'multipart/form-data')):\n            self._post = MultiDict()\n            return self._post\n\n        body = yield from self.read()\n        content_charset = self.charset or 'utf-8'\n\n        environ = {'REQUEST_METHOD': self.method,\n                   'CONTENT_LENGTH': str(len(body)),\n                   'QUERY_STRING': '',\n                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}\n\n        fs = cgi.FieldStorage(fp=io.BytesIO(body),\n                              environ=environ,\n                              keep_blank_values=True,\n                              encoding=content_charset)\n\n        supported_tranfer_encoding = {\n            'base64': binascii.a2b_base64,\n            'quoted-printable': binascii.a2b_qp\n        }\n\n        out = MutableMultiDict()\n        for field in fs.list or ():\n            transfer_encoding = field.headers.get(\n                'Content-Transfer-Encoding', None)\n            if field.filename:\n                ff = FileField(field.name,\n                               field.filename,\n                               field.file,  # N.B. file closed error\n                               field.type)\n                if self._post_files_cache is None:\n                    self._post_files_cache = {}\n                self._post_files_cache[field.name] = field\n                out.add(field.name, ff)\n            else:\n                value = field.value\n                if transfer_encoding in supported_tranfer_encoding:\n                    # binascii accepts bytes\n                    value = value.encode('utf-8')\n                    value = supported_tranfer_encoding[\n                        transfer_encoding](value)\n                out.add(field.name, value)\n\n        self._post = MultiDict(out.items(getall=True))\n        return self._post",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 142,
                            "end_lineno": 172,
                            "parent": {
                                "file_name": "aiohttp/web.py",
                                "type": "class",
                                "name": "Request",
                                "content": "class Request(HeadersMixin):\n\n    def __init__(self, app, message, payload, transport, reader, writer,\n                 keep_alive_timeout):\n        self._app = app\n        self._version = message.version\n        self._transport = transport\n        self._reader = reader\n        self._writer = writer\n        self._method = message.method\n        self._host = message.headers.get('HOST')\n        self._path_qs = message.path\n        res = urlsplit(message.path)\n        self._path = unquote(res.path)\n        self._query_string = res.query\n        self._post = None\n        self._post_files_cache = None\n        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(\n            message.headers)\n\n        if self._version < HttpVersion11:\n            self._keep_alive = False\n        elif message.should_close:\n            self._keep_alive = False\n        else:\n            self._keep_alive = bool(keep_alive_timeout)\n\n        # matchdict, route_name, handler\n        # or information about traversal lookup\n        self._match_info = None  # initialized after route resolving\n\n        self._payload = payload\n        self._cookies = None\n\n    @property\n    def method(self):\n        \"\"\"Read only property for getting HTTP method.\n\n        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.\n        \"\"\"\n        return self._method\n\n    @property\n    def version(self):\n        \"\"\"Read only property for getting HTTP version of request.\n\n        Returns aiohttp.protocol.HttpVersion instance.\n        \"\"\"\n        return self._version\n\n    @property\n    def host(self):\n        \"\"\"Read only property for getting *HOST* header of request.\n\n        Returns str or None if HTTP request has no HOST header.\n        \"\"\"\n        return self._host\n\n    @property\n    def path_qs(self):\n        \"\"\"The URL including PATH_INFO and the query string.\n\n        E.g, /app/blog?id=10\n        \"\"\"\n        return self._path_qs\n\n    @property\n    def path(self):\n        \"\"\"The URL including *PATH INFO* without the host or scheme.\n\n        E.g., ``/app/blog``\n        \"\"\"\n        return self._path\n\n    @property\n    def query_string(self):\n        \"\"\"The query string in the URL.\n\n        E.g., id=10\n        \"\"\"\n        return self._query_string\n\n    @reify\n    def GET(self):\n        \"\"\"A multidict with all the variables in the query string.\n\n        Lazy property.\n        \"\"\"\n        return MultiDict(parse_qsl(self._query_string))\n\n    @reify\n    def POST(self):\n        \"\"\"A multidict with all the variables in the POST parameters.\n\n        post() methods has to be called before using this attribute.\n        \"\"\"\n        if self._post is None:\n            raise RuntimeError(\"POST is not available before post()\")\n        return self._post\n\n    @property\n    def headers(self):\n        \"\"\"A case-insensitive multidict with all headers.\n\n        Lazy property.\n        \"\"\"\n        return self._headers\n\n    @property\n    def keep_alive(self):\n        \"\"\"Is keepalive enabled by client?\"\"\"\n        return self._keep_alive\n\n    @property\n    def match_info(self):\n        \"\"\"Result of route resolving.\"\"\"\n        return self._match_info\n\n    @property\n    def app(self):\n        \"\"\"Application instance.\"\"\"\n        return self._app\n\n    @property\n    def transport(self):\n        \"\"\"Transport used for request processing.\"\"\"\n        return self._transport\n\n    @property\n    def cookies(self):\n        \"\"\"Return request cookies.\n\n        A read-only dictionary-like object.\n        \"\"\"\n        if self._cookies is None:\n            raw = self.headers.get('COOKIE', '')\n            parsed = http.cookies.SimpleCookie(raw)\n            self._cookies = MultiDict({key: val.value\n                                       for key, val in parsed.items()})\n        return self._cookies\n\n    @property\n    def payload(self):\n        \"\"\"Return raw paiload stream.\"\"\"\n        return self._payload\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Release request.\n\n        Eat unread part of HTTP BODY if present.\n        \"\"\"\n        chunk = yield from self._payload.readany()\n        while chunk is not EOF_MARKER or chunk:\n            chunk = yield from self._payload.readany()\n\n    @asyncio.coroutine\n    def read(self):\n        \"\"\"Read request body if present.\n\n        Returns bytes object with full request content.\n        \"\"\"\n        body = bytearray()\n        while True:\n            chunk = yield from self._payload.readany()\n            body.extend(chunk)\n            if chunk is EOF_MARKER:\n                break\n        return bytes(body)\n\n    @asyncio.coroutine\n    def text(self):\n        \"\"\"Return BODY as text using encoding from .charset.\"\"\"\n        bytes_body = yield from self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, loader=json.loads):\n        \"\"\"Return BODY as JSON.\"\"\"\n        body = yield from self.text()\n        return loader(body)\n\n    @asyncio.coroutine\n    def post(self):\n        \"\"\"Return POST parameters.\"\"\"\n        if self._post is not None:\n            return self._post\n        if self.method not in ('POST', 'PUT', 'PATCH'):\n            self._post = MultiDict()\n            return self._post\n\n        content_type = self.content_type\n        if (content_type not in ('',\n                                 'application/x-www-form-urlencoded',\n                                 'multipart/form-data')):\n            self._post = MultiDict()\n            return self._post\n\n        body = yield from self.read()\n        content_charset = self.charset or 'utf-8'\n\n        environ = {'REQUEST_METHOD': self.method,\n                   'CONTENT_LENGTH': str(len(body)),\n                   'QUERY_STRING': '',\n                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}\n\n        fs = cgi.FieldStorage(fp=io.BytesIO(body),\n                              environ=environ,\n                              keep_blank_values=True,\n                              encoding=content_charset)\n\n        supported_tranfer_encoding = {\n            'base64': binascii.a2b_base64,\n            'quoted-printable': binascii.a2b_qp\n        }\n\n        out = MutableMultiDict()\n        for field in fs.list or ():\n            transfer_encoding = field.headers.get(\n                'Content-Transfer-Encoding', None)\n            if field.filename:\n                ff = FileField(field.name,\n                               field.filename,\n                               field.file,  # N.B. file closed error\n                               field.type)\n                if self._post_files_cache is None:\n                    self._post_files_cache = {}\n                self._post_files_cache[field.name] = field\n                out.add(field.name, ff)\n            else:\n                value = field.value\n                if transfer_encoding in supported_tranfer_encoding:\n                    # binascii accepts bytes\n                    value = value.encode('utf-8')\n                    value = supported_tranfer_encoding[\n                        transfer_encoding](value)\n                out.add(field.name, value)\n\n        self._post = MultiDict(out.items(getall=True))\n        return self._post",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 140,
                                "end_lineno": 380,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "aiohttp/web.py",
                            "type": "class",
                            "name": "Request",
                            "content": "class Request(HeadersMixin):\n\n    def __init__(self, app, message, payload, transport, reader, writer,\n                 keep_alive_timeout):\n        self._app = app\n        self._version = message.version\n        self._transport = transport\n        self._reader = reader\n        self._writer = writer\n        self._method = message.method\n        self._host = message.headers.get('HOST')\n        self._path_qs = message.path\n        res = urlsplit(message.path)\n        self._path = unquote(res.path)\n        self._query_string = res.query\n        self._post = None\n        self._post_files_cache = None\n        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(\n            message.headers)\n\n        if self._version < HttpVersion11:\n            self._keep_alive = False\n        elif message.should_close:\n            self._keep_alive = False\n        else:\n            self._keep_alive = bool(keep_alive_timeout)\n\n        # matchdict, route_name, handler\n        # or information about traversal lookup\n        self._match_info = None  # initialized after route resolving\n\n        self._payload = payload\n        self._cookies = None\n\n    @property\n    def method(self):\n        \"\"\"Read only property for getting HTTP method.\n\n        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.\n        \"\"\"\n        return self._method\n\n    @property\n    def version(self):\n        \"\"\"Read only property for getting HTTP version of request.\n\n        Returns aiohttp.protocol.HttpVersion instance.\n        \"\"\"\n        return self._version\n\n    @property\n    def host(self):\n        \"\"\"Read only property for getting *HOST* header of request.\n\n        Returns str or None if HTTP request has no HOST header.\n        \"\"\"\n        return self._host\n\n    @property\n    def path_qs(self):\n        \"\"\"The URL including PATH_INFO and the query string.\n\n        E.g, /app/blog?id=10\n        \"\"\"\n        return self._path_qs\n\n    @property\n    def path(self):\n        \"\"\"The URL including *PATH INFO* without the host or scheme.\n\n        E.g., ``/app/blog``\n        \"\"\"\n        return self._path\n\n    @property\n    def query_string(self):\n        \"\"\"The query string in the URL.\n\n        E.g., id=10\n        \"\"\"\n        return self._query_string\n\n    @reify\n    def GET(self):\n        \"\"\"A multidict with all the variables in the query string.\n\n        Lazy property.\n        \"\"\"\n        return MultiDict(parse_qsl(self._query_string))\n\n    @reify\n    def POST(self):\n        \"\"\"A multidict with all the variables in the POST parameters.\n\n        post() methods has to be called before using this attribute.\n        \"\"\"\n        if self._post is None:\n            raise RuntimeError(\"POST is not available before post()\")\n        return self._post\n\n    @property\n    def headers(self):\n        \"\"\"A case-insensitive multidict with all headers.\n\n        Lazy property.\n        \"\"\"\n        return self._headers\n\n    @property\n    def keep_alive(self):\n        \"\"\"Is keepalive enabled by client?\"\"\"\n        return self._keep_alive\n\n    @property\n    def match_info(self):\n        \"\"\"Result of route resolving.\"\"\"\n        return self._match_info\n\n    @property\n    def app(self):\n        \"\"\"Application instance.\"\"\"\n        return self._app\n\n    @property\n    def transport(self):\n        \"\"\"Transport used for request processing.\"\"\"\n        return self._transport\n\n    @property\n    def cookies(self):\n        \"\"\"Return request cookies.\n\n        A read-only dictionary-like object.\n        \"\"\"\n        if self._cookies is None:\n            raw = self.headers.get('COOKIE', '')\n            parsed = http.cookies.SimpleCookie(raw)\n            self._cookies = MultiDict({key: val.value\n                                       for key, val in parsed.items()})\n        return self._cookies\n\n    @property\n    def payload(self):\n        \"\"\"Return raw paiload stream.\"\"\"\n        return self._payload\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Release request.\n\n        Eat unread part of HTTP BODY if present.\n        \"\"\"\n        chunk = yield from self._payload.readany()\n        while chunk is not EOF_MARKER or chunk:\n            chunk = yield from self._payload.readany()\n\n    @asyncio.coroutine\n    def read(self):\n        \"\"\"Read request body if present.\n\n        Returns bytes object with full request content.\n        \"\"\"\n        body = bytearray()\n        while True:\n            chunk = yield from self._payload.readany()\n            body.extend(chunk)\n            if chunk is EOF_MARKER:\n                break\n        return bytes(body)\n\n    @asyncio.coroutine\n    def text(self):\n        \"\"\"Return BODY as text using encoding from .charset.\"\"\"\n        bytes_body = yield from self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, loader=json.loads):\n        \"\"\"Return BODY as JSON.\"\"\"\n        body = yield from self.text()\n        return loader(body)\n\n    @asyncio.coroutine\n    def post(self):\n        \"\"\"Return POST parameters.\"\"\"\n        if self._post is not None:\n            return self._post\n        if self.method not in ('POST', 'PUT', 'PATCH'):\n            self._post = MultiDict()\n            return self._post\n\n        content_type = self.content_type\n        if (content_type not in ('',\n                                 'application/x-www-form-urlencoded',\n                                 'multipart/form-data')):\n            self._post = MultiDict()\n            return self._post\n\n        body = yield from self.read()\n        content_charset = self.charset or 'utf-8'\n\n        environ = {'REQUEST_METHOD': self.method,\n                   'CONTENT_LENGTH': str(len(body)),\n                   'QUERY_STRING': '',\n                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}\n\n        fs = cgi.FieldStorage(fp=io.BytesIO(body),\n                              environ=environ,\n                              keep_blank_values=True,\n                              encoding=content_charset)\n\n        supported_tranfer_encoding = {\n            'base64': binascii.a2b_base64,\n            'quoted-printable': binascii.a2b_qp\n        }\n\n        out = MutableMultiDict()\n        for field in fs.list or ():\n            transfer_encoding = field.headers.get(\n                'Content-Transfer-Encoding', None)\n            if field.filename:\n                ff = FileField(field.name,\n                               field.filename,\n                               field.file,  # N.B. file closed error\n                               field.type)\n                if self._post_files_cache is None:\n                    self._post_files_cache = {}\n                self._post_files_cache[field.name] = field\n                out.add(field.name, ff)\n            else:\n                value = field.value\n                if transfer_encoding in supported_tranfer_encoding:\n                    # binascii accepts bytes\n                    value = value.encode('utf-8')\n                    value = supported_tranfer_encoding[\n                        transfer_encoding](value)\n                out.add(field.name, value)\n\n        self._post = MultiDict(out.items(getall=True))\n        return self._post",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 140,
                            "end_lineno": 380,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 162,
                            "length": 7
                        },
                        "new_range": {
                            "start": 161,
                            "length": 7
                        },
                        "section": "class Request(HeadersMixin):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        elif message.should_close:",
                                "type": "context"
                            },
                            {
                                "content": "            self._keep_alive = False",
                                "type": "context"
                            },
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            self._keep_alive = bool(keep_alive_timeout)",
                                "type": "deleted"
                            },
                            {
                                "content": "            self._keep_alive = True",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        # matchdict, route_name, handler",
                                "type": "context"
                            },
                            {
                                "content": "        # or information about traversal lookup",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/web.py",
                            "type": "method",
                            "name": "Request.__init__",
                            "content": "class Request(HeadersMixin):\n\n    def __init__(self, app, message, payload, transport, reader, writer,\n                 keep_alive_timeout):\n        self._app = app\n        self._version = message.version\n        self._transport = transport\n        self._reader = reader\n        self._writer = writer\n        self._method = message.method\n        self._host = message.headers.get('HOST')\n        self._path_qs = message.path\n        res = urlsplit(message.path)\n        self._path = unquote(res.path)\n        self._query_string = res.query\n        self._post = None\n        self._post_files_cache = None\n        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(\n            message.headers)\n\n        if self._version < HttpVersion11:\n            self._keep_alive = False\n        elif message.should_close:\n            self._keep_alive = False\n        else:\n            self._keep_alive = bool(keep_alive_timeout)\n\n        # matchdict, route_name, handler\n        # or information about traversal lookup\n        self._match_info = None  # initialized after route resolving\n\n        self._payload = payload\n        self._cookies = None\n\n    @property\n    def method(self):\n        \"\"\"Read only property for getting HTTP method.\n\n        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.\n        \"\"\"\n        return self._method\n\n    @property\n    def version(self):\n        \"\"\"Read only property for getting HTTP version of request.\n\n        Returns aiohttp.protocol.HttpVersion instance.\n        \"\"\"\n        return self._version\n\n    @property\n    def host(self):\n        \"\"\"Read only property for getting *HOST* header of request.\n\n        Returns str or None if HTTP request has no HOST header.\n        \"\"\"\n        return self._host\n\n    @property\n    def path_qs(self):\n        \"\"\"The URL including PATH_INFO and the query string.\n\n        E.g, /app/blog?id=10\n        \"\"\"\n        return self._path_qs\n\n    @property\n    def path(self):\n        \"\"\"The URL including *PATH INFO* without the host or scheme.\n\n        E.g., ``/app/blog``\n        \"\"\"\n        return self._path\n\n    @property\n    def query_string(self):\n        \"\"\"The query string in the URL.\n\n        E.g., id=10\n        \"\"\"\n        return self._query_string\n\n    @reify\n    def GET(self):\n        \"\"\"A multidict with all the variables in the query string.\n\n        Lazy property.\n        \"\"\"\n        return MultiDict(parse_qsl(self._query_string))\n\n    @reify\n    def POST(self):\n        \"\"\"A multidict with all the variables in the POST parameters.\n\n        post() methods has to be called before using this attribute.\n        \"\"\"\n        if self._post is None:\n            raise RuntimeError(\"POST is not available before post()\")\n        return self._post\n\n    @property\n    def headers(self):\n        \"\"\"A case-insensitive multidict with all headers.\n\n        Lazy property.\n        \"\"\"\n        return self._headers\n\n    @property\n    def keep_alive(self):\n        \"\"\"Is keepalive enabled by client?\"\"\"\n        return self._keep_alive\n\n    @property\n    def match_info(self):\n        \"\"\"Result of route resolving.\"\"\"\n        return self._match_info\n\n    @property\n    def app(self):\n        \"\"\"Application instance.\"\"\"\n        return self._app\n\n    @property\n    def transport(self):\n        \"\"\"Transport used for request processing.\"\"\"\n        return self._transport\n\n    @property\n    def cookies(self):\n        \"\"\"Return request cookies.\n\n        A read-only dictionary-like object.\n        \"\"\"\n        if self._cookies is None:\n            raw = self.headers.get('COOKIE', '')\n            parsed = http.cookies.SimpleCookie(raw)\n            self._cookies = MultiDict({key: val.value\n                                       for key, val in parsed.items()})\n        return self._cookies\n\n    @property\n    def payload(self):\n        \"\"\"Return raw paiload stream.\"\"\"\n        return self._payload\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Release request.\n\n        Eat unread part of HTTP BODY if present.\n        \"\"\"\n        chunk = yield from self._payload.readany()\n        while chunk is not EOF_MARKER or chunk:\n            chunk = yield from self._payload.readany()\n\n    @asyncio.coroutine\n    def read(self):\n        \"\"\"Read request body if present.\n\n        Returns bytes object with full request content.\n        \"\"\"\n        body = bytearray()\n        while True:\n            chunk = yield from self._payload.readany()\n            body.extend(chunk)\n            if chunk is EOF_MARKER:\n                break\n        return bytes(body)\n\n    @asyncio.coroutine\n    def text(self):\n        \"\"\"Return BODY as text using encoding from .charset.\"\"\"\n        bytes_body = yield from self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, loader=json.loads):\n        \"\"\"Return BODY as JSON.\"\"\"\n        body = yield from self.text()\n        return loader(body)\n\n    @asyncio.coroutine\n    def post(self):\n        \"\"\"Return POST parameters.\"\"\"\n        if self._post is not None:\n            return self._post\n        if self.method not in ('POST', 'PUT', 'PATCH'):\n            self._post = MultiDict()\n            return self._post\n\n        content_type = self.content_type\n        if (content_type not in ('',\n                                 'application/x-www-form-urlencoded',\n                                 'multipart/form-data')):\n            self._post = MultiDict()\n            return self._post\n\n        body = yield from self.read()\n        content_charset = self.charset or 'utf-8'\n\n        environ = {'REQUEST_METHOD': self.method,\n                   'CONTENT_LENGTH': str(len(body)),\n                   'QUERY_STRING': '',\n                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}\n\n        fs = cgi.FieldStorage(fp=io.BytesIO(body),\n                              environ=environ,\n                              keep_blank_values=True,\n                              encoding=content_charset)\n\n        supported_tranfer_encoding = {\n            'base64': binascii.a2b_base64,\n            'quoted-printable': binascii.a2b_qp\n        }\n\n        out = MutableMultiDict()\n        for field in fs.list or ():\n            transfer_encoding = field.headers.get(\n                'Content-Transfer-Encoding', None)\n            if field.filename:\n                ff = FileField(field.name,\n                               field.filename,\n                               field.file,  # N.B. file closed error\n                               field.type)\n                if self._post_files_cache is None:\n                    self._post_files_cache = {}\n                self._post_files_cache[field.name] = field\n                out.add(field.name, ff)\n            else:\n                value = field.value\n                if transfer_encoding in supported_tranfer_encoding:\n                    # binascii accepts bytes\n                    value = value.encode('utf-8')\n                    value = supported_tranfer_encoding[\n                        transfer_encoding](value)\n                out.add(field.name, value)\n\n        self._post = MultiDict(out.items(getall=True))\n        return self._post",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 142,
                            "end_lineno": 172,
                            "parent": {
                                "file_name": "aiohttp/web.py",
                                "type": "class",
                                "name": "Request",
                                "content": "class Request(HeadersMixin):\n\n    def __init__(self, app, message, payload, transport, reader, writer,\n                 keep_alive_timeout):\n        self._app = app\n        self._version = message.version\n        self._transport = transport\n        self._reader = reader\n        self._writer = writer\n        self._method = message.method\n        self._host = message.headers.get('HOST')\n        self._path_qs = message.path\n        res = urlsplit(message.path)\n        self._path = unquote(res.path)\n        self._query_string = res.query\n        self._post = None\n        self._post_files_cache = None\n        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(\n            message.headers)\n\n        if self._version < HttpVersion11:\n            self._keep_alive = False\n        elif message.should_close:\n            self._keep_alive = False\n        else:\n            self._keep_alive = bool(keep_alive_timeout)\n\n        # matchdict, route_name, handler\n        # or information about traversal lookup\n        self._match_info = None  # initialized after route resolving\n\n        self._payload = payload\n        self._cookies = None\n\n    @property\n    def method(self):\n        \"\"\"Read only property for getting HTTP method.\n\n        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.\n        \"\"\"\n        return self._method\n\n    @property\n    def version(self):\n        \"\"\"Read only property for getting HTTP version of request.\n\n        Returns aiohttp.protocol.HttpVersion instance.\n        \"\"\"\n        return self._version\n\n    @property\n    def host(self):\n        \"\"\"Read only property for getting *HOST* header of request.\n\n        Returns str or None if HTTP request has no HOST header.\n        \"\"\"\n        return self._host\n\n    @property\n    def path_qs(self):\n        \"\"\"The URL including PATH_INFO and the query string.\n\n        E.g, /app/blog?id=10\n        \"\"\"\n        return self._path_qs\n\n    @property\n    def path(self):\n        \"\"\"The URL including *PATH INFO* without the host or scheme.\n\n        E.g., ``/app/blog``\n        \"\"\"\n        return self._path\n\n    @property\n    def query_string(self):\n        \"\"\"The query string in the URL.\n\n        E.g., id=10\n        \"\"\"\n        return self._query_string\n\n    @reify\n    def GET(self):\n        \"\"\"A multidict with all the variables in the query string.\n\n        Lazy property.\n        \"\"\"\n        return MultiDict(parse_qsl(self._query_string))\n\n    @reify\n    def POST(self):\n        \"\"\"A multidict with all the variables in the POST parameters.\n\n        post() methods has to be called before using this attribute.\n        \"\"\"\n        if self._post is None:\n            raise RuntimeError(\"POST is not available before post()\")\n        return self._post\n\n    @property\n    def headers(self):\n        \"\"\"A case-insensitive multidict with all headers.\n\n        Lazy property.\n        \"\"\"\n        return self._headers\n\n    @property\n    def keep_alive(self):\n        \"\"\"Is keepalive enabled by client?\"\"\"\n        return self._keep_alive\n\n    @property\n    def match_info(self):\n        \"\"\"Result of route resolving.\"\"\"\n        return self._match_info\n\n    @property\n    def app(self):\n        \"\"\"Application instance.\"\"\"\n        return self._app\n\n    @property\n    def transport(self):\n        \"\"\"Transport used for request processing.\"\"\"\n        return self._transport\n\n    @property\n    def cookies(self):\n        \"\"\"Return request cookies.\n\n        A read-only dictionary-like object.\n        \"\"\"\n        if self._cookies is None:\n            raw = self.headers.get('COOKIE', '')\n            parsed = http.cookies.SimpleCookie(raw)\n            self._cookies = MultiDict({key: val.value\n                                       for key, val in parsed.items()})\n        return self._cookies\n\n    @property\n    def payload(self):\n        \"\"\"Return raw paiload stream.\"\"\"\n        return self._payload\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Release request.\n\n        Eat unread part of HTTP BODY if present.\n        \"\"\"\n        chunk = yield from self._payload.readany()\n        while chunk is not EOF_MARKER or chunk:\n            chunk = yield from self._payload.readany()\n\n    @asyncio.coroutine\n    def read(self):\n        \"\"\"Read request body if present.\n\n        Returns bytes object with full request content.\n        \"\"\"\n        body = bytearray()\n        while True:\n            chunk = yield from self._payload.readany()\n            body.extend(chunk)\n            if chunk is EOF_MARKER:\n                break\n        return bytes(body)\n\n    @asyncio.coroutine\n    def text(self):\n        \"\"\"Return BODY as text using encoding from .charset.\"\"\"\n        bytes_body = yield from self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, loader=json.loads):\n        \"\"\"Return BODY as JSON.\"\"\"\n        body = yield from self.text()\n        return loader(body)\n\n    @asyncio.coroutine\n    def post(self):\n        \"\"\"Return POST parameters.\"\"\"\n        if self._post is not None:\n            return self._post\n        if self.method not in ('POST', 'PUT', 'PATCH'):\n            self._post = MultiDict()\n            return self._post\n\n        content_type = self.content_type\n        if (content_type not in ('',\n                                 'application/x-www-form-urlencoded',\n                                 'multipart/form-data')):\n            self._post = MultiDict()\n            return self._post\n\n        body = yield from self.read()\n        content_charset = self.charset or 'utf-8'\n\n        environ = {'REQUEST_METHOD': self.method,\n                   'CONTENT_LENGTH': str(len(body)),\n                   'QUERY_STRING': '',\n                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}\n\n        fs = cgi.FieldStorage(fp=io.BytesIO(body),\n                              environ=environ,\n                              keep_blank_values=True,\n                              encoding=content_charset)\n\n        supported_tranfer_encoding = {\n            'base64': binascii.a2b_base64,\n            'quoted-printable': binascii.a2b_qp\n        }\n\n        out = MutableMultiDict()\n        for field in fs.list or ():\n            transfer_encoding = field.headers.get(\n                'Content-Transfer-Encoding', None)\n            if field.filename:\n                ff = FileField(field.name,\n                               field.filename,\n                               field.file,  # N.B. file closed error\n                               field.type)\n                if self._post_files_cache is None:\n                    self._post_files_cache = {}\n                self._post_files_cache[field.name] = field\n                out.add(field.name, ff)\n            else:\n                value = field.value\n                if transfer_encoding in supported_tranfer_encoding:\n                    # binascii accepts bytes\n                    value = value.encode('utf-8')\n                    value = supported_tranfer_encoding[\n                        transfer_encoding](value)\n                out.add(field.name, value)\n\n        self._post = MultiDict(out.items(getall=True))\n        return self._post",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 140,
                                "end_lineno": 380,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "aiohttp/web.py",
                            "type": "class",
                            "name": "Request",
                            "content": "class Request(HeadersMixin):\n\n    def __init__(self, app, message, payload, transport, reader, writer,\n                 keep_alive_timeout):\n        self._app = app\n        self._version = message.version\n        self._transport = transport\n        self._reader = reader\n        self._writer = writer\n        self._method = message.method\n        self._host = message.headers.get('HOST')\n        self._path_qs = message.path\n        res = urlsplit(message.path)\n        self._path = unquote(res.path)\n        self._query_string = res.query\n        self._post = None\n        self._post_files_cache = None\n        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(\n            message.headers)\n\n        if self._version < HttpVersion11:\n            self._keep_alive = False\n        elif message.should_close:\n            self._keep_alive = False\n        else:\n            self._keep_alive = bool(keep_alive_timeout)\n\n        # matchdict, route_name, handler\n        # or information about traversal lookup\n        self._match_info = None  # initialized after route resolving\n\n        self._payload = payload\n        self._cookies = None\n\n    @property\n    def method(self):\n        \"\"\"Read only property for getting HTTP method.\n\n        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.\n        \"\"\"\n        return self._method\n\n    @property\n    def version(self):\n        \"\"\"Read only property for getting HTTP version of request.\n\n        Returns aiohttp.protocol.HttpVersion instance.\n        \"\"\"\n        return self._version\n\n    @property\n    def host(self):\n        \"\"\"Read only property for getting *HOST* header of request.\n\n        Returns str or None if HTTP request has no HOST header.\n        \"\"\"\n        return self._host\n\n    @property\n    def path_qs(self):\n        \"\"\"The URL including PATH_INFO and the query string.\n\n        E.g, /app/blog?id=10\n        \"\"\"\n        return self._path_qs\n\n    @property\n    def path(self):\n        \"\"\"The URL including *PATH INFO* without the host or scheme.\n\n        E.g., ``/app/blog``\n        \"\"\"\n        return self._path\n\n    @property\n    def query_string(self):\n        \"\"\"The query string in the URL.\n\n        E.g., id=10\n        \"\"\"\n        return self._query_string\n\n    @reify\n    def GET(self):\n        \"\"\"A multidict with all the variables in the query string.\n\n        Lazy property.\n        \"\"\"\n        return MultiDict(parse_qsl(self._query_string))\n\n    @reify\n    def POST(self):\n        \"\"\"A multidict with all the variables in the POST parameters.\n\n        post() methods has to be called before using this attribute.\n        \"\"\"\n        if self._post is None:\n            raise RuntimeError(\"POST is not available before post()\")\n        return self._post\n\n    @property\n    def headers(self):\n        \"\"\"A case-insensitive multidict with all headers.\n\n        Lazy property.\n        \"\"\"\n        return self._headers\n\n    @property\n    def keep_alive(self):\n        \"\"\"Is keepalive enabled by client?\"\"\"\n        return self._keep_alive\n\n    @property\n    def match_info(self):\n        \"\"\"Result of route resolving.\"\"\"\n        return self._match_info\n\n    @property\n    def app(self):\n        \"\"\"Application instance.\"\"\"\n        return self._app\n\n    @property\n    def transport(self):\n        \"\"\"Transport used for request processing.\"\"\"\n        return self._transport\n\n    @property\n    def cookies(self):\n        \"\"\"Return request cookies.\n\n        A read-only dictionary-like object.\n        \"\"\"\n        if self._cookies is None:\n            raw = self.headers.get('COOKIE', '')\n            parsed = http.cookies.SimpleCookie(raw)\n            self._cookies = MultiDict({key: val.value\n                                       for key, val in parsed.items()})\n        return self._cookies\n\n    @property\n    def payload(self):\n        \"\"\"Return raw paiload stream.\"\"\"\n        return self._payload\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Release request.\n\n        Eat unread part of HTTP BODY if present.\n        \"\"\"\n        chunk = yield from self._payload.readany()\n        while chunk is not EOF_MARKER or chunk:\n            chunk = yield from self._payload.readany()\n\n    @asyncio.coroutine\n    def read(self):\n        \"\"\"Read request body if present.\n\n        Returns bytes object with full request content.\n        \"\"\"\n        body = bytearray()\n        while True:\n            chunk = yield from self._payload.readany()\n            body.extend(chunk)\n            if chunk is EOF_MARKER:\n                break\n        return bytes(body)\n\n    @asyncio.coroutine\n    def text(self):\n        \"\"\"Return BODY as text using encoding from .charset.\"\"\"\n        bytes_body = yield from self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, loader=json.loads):\n        \"\"\"Return BODY as JSON.\"\"\"\n        body = yield from self.text()\n        return loader(body)\n\n    @asyncio.coroutine\n    def post(self):\n        \"\"\"Return POST parameters.\"\"\"\n        if self._post is not None:\n            return self._post\n        if self.method not in ('POST', 'PUT', 'PATCH'):\n            self._post = MultiDict()\n            return self._post\n\n        content_type = self.content_type\n        if (content_type not in ('',\n                                 'application/x-www-form-urlencoded',\n                                 'multipart/form-data')):\n            self._post = MultiDict()\n            return self._post\n\n        body = yield from self.read()\n        content_charset = self.charset or 'utf-8'\n\n        environ = {'REQUEST_METHOD': self.method,\n                   'CONTENT_LENGTH': str(len(body)),\n                   'QUERY_STRING': '',\n                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}\n\n        fs = cgi.FieldStorage(fp=io.BytesIO(body),\n                              environ=environ,\n                              keep_blank_values=True,\n                              encoding=content_charset)\n\n        supported_tranfer_encoding = {\n            'base64': binascii.a2b_base64,\n            'quoted-printable': binascii.a2b_qp\n        }\n\n        out = MutableMultiDict()\n        for field in fs.list or ():\n            transfer_encoding = field.headers.get(\n                'Content-Transfer-Encoding', None)\n            if field.filename:\n                ff = FileField(field.name,\n                               field.filename,\n                               field.file,  # N.B. file closed error\n                               field.type)\n                if self._post_files_cache is None:\n                    self._post_files_cache = {}\n                self._post_files_cache[field.name] = field\n                out.add(field.name, ff)\n            else:\n                value = field.value\n                if transfer_encoding in supported_tranfer_encoding:\n                    # binascii accepts bytes\n                    value = value.encode('utf-8')\n                    value = supported_tranfer_encoding[\n                        transfer_encoding](value)\n                out.add(field.name, value)\n\n        self._post = MultiDict(out.items(getall=True))\n        return self._post",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 140,
                            "end_lineno": 380,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1340,
                            "length": 8
                        },
                        "new_range": {
                            "start": 1339,
                            "length": 7
                        },
                        "section": "class RequestHandler(ServerHttpProtocol):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        app = self._app",
                                "type": "context"
                            },
                            {
                                "content": "        request = Request(app, message, payload,",
                                "type": "context"
                            },
                            {
                                "content": "                          self.transport, self.reader, self.writer,",
                                "type": "deleted"
                            },
                            {
                                "content": "                          self.keep_alive_timeout)",
                                "type": "deleted"
                            },
                            {
                                "content": "                          self.transport, self.reader, self.writer)",
                                "type": "added"
                            },
                            {
                                "content": "        try:",
                                "type": "context"
                            },
                            {
                                "content": "            match_info = yield from self._router.resolve(request)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/web.py",
                            "type": "method",
                            "name": "RequestHandler.handle_request",
                            "content": "class RequestHandler(ServerHttpProtocol):\n\n    def __init__(self, manager, app, router, **kwargs):\n        super().__init__(**kwargs)\n\n        self._manager = manager\n        self._app = app\n        self._router = router\n        self._middlewares = app.middlewares\n\n    def connection_made(self, transport):\n        super().connection_made(transport)\n\n        self._manager.connection_made(self, transport)\n\n    def connection_lost(self, exc):\n        self._manager.connection_lost(self, exc)\n\n        super().connection_lost(exc)\n\n    @asyncio.coroutine\n    def handle_request(self, message, payload):\n        now = self._loop.time()\n\n        app = self._app\n        request = Request(app, message, payload,\n                          self.transport, self.reader, self.writer,\n                          self.keep_alive_timeout)\n        try:\n            match_info = yield from self._router.resolve(request)\n\n            assert isinstance(match_info, AbstractMatchInfo), match_info\n\n            request._match_info = match_info\n            handler = match_info.handler\n\n            for factory in reversed(self._middlewares):\n                handler = yield from factory(app, handler)\n            resp = yield from handler(request)\n\n            if not isinstance(resp, StreamResponse):\n                raise RuntimeError(\n                    (\"Handler {!r} should return response instance, \"\n                     \"got {!r} [middlewares {!r}]\").format(\n                         match_info.handler,\n                         type(resp),\n                         self._middlewares))\n        except HTTPException as exc:\n            resp = exc\n\n        resp_msg = resp.start(request)\n        yield from resp.write_eof()\n\n        # notify server about keep-alive\n        self.keep_alive(resp_msg.keep_alive())\n\n        # log access\n        self.log_access(message, None, resp_msg, self._loop.time() - now)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1338,
                            "end_lineno": 1374,
                            "parent": {
                                "file_name": "aiohttp/web.py",
                                "type": "class",
                                "name": "RequestHandler",
                                "content": "class RequestHandler(ServerHttpProtocol):\n\n    def __init__(self, manager, app, router, **kwargs):\n        super().__init__(**kwargs)\n\n        self._manager = manager\n        self._app = app\n        self._router = router\n        self._middlewares = app.middlewares\n\n    def connection_made(self, transport):\n        super().connection_made(transport)\n\n        self._manager.connection_made(self, transport)\n\n    def connection_lost(self, exc):\n        self._manager.connection_lost(self, exc)\n\n        super().connection_lost(exc)\n\n    @asyncio.coroutine\n    def handle_request(self, message, payload):\n        now = self._loop.time()\n\n        app = self._app\n        request = Request(app, message, payload,\n                          self.transport, self.reader, self.writer,\n                          self.keep_alive_timeout)\n        try:\n            match_info = yield from self._router.resolve(request)\n\n            assert isinstance(match_info, AbstractMatchInfo), match_info\n\n            request._match_info = match_info\n            handler = match_info.handler\n\n            for factory in reversed(self._middlewares):\n                handler = yield from factory(app, handler)\n            resp = yield from handler(request)\n\n            if not isinstance(resp, StreamResponse):\n                raise RuntimeError(\n                    (\"Handler {!r} should return response instance, \"\n                     \"got {!r} [middlewares {!r}]\").format(\n                         match_info.handler,\n                         type(resp),\n                         self._middlewares))\n        except HTTPException as exc:\n            resp = exc\n\n        resp_msg = resp.start(request)\n        yield from resp.write_eof()\n\n        # notify server about keep-alive\n        self.keep_alive(resp_msg.keep_alive())\n\n        # log access\n        self.log_access(message, None, resp_msg, self._loop.time() - now)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1317,
                                "end_lineno": 1374,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "aiohttp/web.py",
                            "type": "class",
                            "name": "RequestHandler",
                            "content": "class RequestHandler(ServerHttpProtocol):\n\n    def __init__(self, manager, app, router, **kwargs):\n        super().__init__(**kwargs)\n\n        self._manager = manager\n        self._app = app\n        self._router = router\n        self._middlewares = app.middlewares\n\n    def connection_made(self, transport):\n        super().connection_made(transport)\n\n        self._manager.connection_made(self, transport)\n\n    def connection_lost(self, exc):\n        self._manager.connection_lost(self, exc)\n\n        super().connection_lost(exc)\n\n    @asyncio.coroutine\n    def handle_request(self, message, payload):\n        now = self._loop.time()\n\n        app = self._app\n        request = Request(app, message, payload,\n                          self.transport, self.reader, self.writer,\n                          self.keep_alive_timeout)\n        try:\n            match_info = yield from self._router.resolve(request)\n\n            assert isinstance(match_info, AbstractMatchInfo), match_info\n\n            request._match_info = match_info\n            handler = match_info.handler\n\n            for factory in reversed(self._middlewares):\n                handler = yield from factory(app, handler)\n            resp = yield from handler(request)\n\n            if not isinstance(resp, StreamResponse):\n                raise RuntimeError(\n                    (\"Handler {!r} should return response instance, \"\n                     \"got {!r} [middlewares {!r}]\").format(\n                         match_info.handler,\n                         type(resp),\n                         self._middlewares))\n        except HTTPException as exc:\n            resp = exc\n\n        resp_msg = resp.start(request)\n        yield from resp.write_eof()\n\n        # notify server about keep-alive\n        self.keep_alive(resp_msg.keep_alive())\n\n        # log access\n        self.log_access(message, None, resp_msg, self._loop.time() - now)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1317,
                            "end_lineno": 1374,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport os\nimport unittest\nfrom unittest import mock\nimport aiohttp.web\nfrom aiohttp.web import (UrlDispatcher, Request, Response,\n                         HTTPMethodNotAllowed, HTTPNotFound)\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.protocol import HttpVersion, RawRequestMessage\n\n\nclass TestUrlDispatcher(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.router = UrlDispatcher()\n\n    def tearDown(self):\n        self.loop.close()\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_add_route_root(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/', handler)\n        req = self.make_request('GET', '/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_route_simple(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path', handler)\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_matchdict(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/{to}', handler)\n        req = self.make_request('GET', '/handler/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 'tail'}, info)\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_name(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/handler/to/path', handler,\n                              name='name')\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual('name', info.route.name)\n\n    def test_add_with_tailing_slash(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path/', handler)\n        req = self.make_request('GET', '/handler/to/path/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler, info.handler)\n\n    def test_add_invalid_path(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('GET', '/{/', lambda req: None)\n\n    def test_add_url_invalid1(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id', lambda: None)\n\n    def test_add_url_invalid2(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}}', lambda: None)\n\n    def test_add_url_invalid3(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}', lambda: None)\n\n    def test_add_url_invalid4(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id\"}', lambda: None)\n\n    def test_add_url_invalid5(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post\"{id}', lambda: None)\n\n    def test_add_url_escaping(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/+$', handler)\n\n        req = self.make_request('GET', '/+$')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertIs(handler, info.handler)\n\n    def test_match_second_result_in_table(self):\n        handler1 = asyncio.coroutine(lambda req: Response(req))\n        handler2 = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/h1', handler1)\n        self.router.add_route('POST', '/h2', handler2)\n        req = self.make_request('POST', '/h2')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler2, info.handler)\n\n    def test_raise_method_not_allowed(self):\n        handler1 = lambda req: Response(req)\n        handler2 = lambda req: Response(req)\n        self.router.add_route('GET', '/', handler1)\n        self.router.add_route('POST', '/', handler2)\n        req = self.make_request('PUT', '/')\n\n        with self.assertRaises(HTTPMethodNotAllowed) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual('PUT', exc.method)\n        self.assertEqual(405, exc.status)\n        self.assertEqual({'POST', 'GET'}, exc.allowed_methods)\n\n    def test_raise_method_not_found(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/a', handler)\n        req = self.make_request('GET', '/b')\n\n        with self.assertRaises(HTTPNotFound) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual(404, exc.status)\n\n    def test_double_add_url_with_the_same_name(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        regexp = (\"Duplicate 'name', already handled by\")\n        with self.assertRaisesRegex(ValueError, regexp):\n            self.router.add_route('GET', '/get_other', lambda r: None,\n                                  name='name')\n\n    def test_route_plain(self):\n        route = self.router.add_route('GET', '/get', lambda r: None,\n                                      name='name')\n        route2 = self.router['name']\n        url = route2.url()\n        self.assertEqual('/get', url)\n        self.assertIs(route, route2)\n\n    def test_route_unknown_route_name(self):\n        with self.assertRaises(KeyError):\n            self.router['unknown']\n\n    def test_route_dynamic(self):\n        route = self.router.add_route('GET', '/get/{name}',\n                                      lambda r: None, name='name')\n\n        route2 = self.router['name']\n        url = route2.url(parts={'name': 'John'})\n        self.assertEqual('/get/John', url)\n        self.assertIs(route, route2)\n\n    def test_route_with_qs(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        url = self.router['name'].url(query=[('a', 'b'), ('c', 1)])\n        self.assertEqual('/get?a=b&c=1', url)\n\n    def test_add_static(self):\n        route = self.router.add_static('/st',\n                                       os.path.dirname(aiohttp.__file__),\n                                       name='static')\n        route2 = self.router['static']\n        url = route2.url(filename='/dir/a.txt')\n        self.assertEqual('/st/dir/a.txt', url)\n        self.assertIs(route, route2)\n\n    def test_plain_not_match(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_not_match(self):\n        self.router.add_route('GET', '/get/{name}',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_static_not_match(self):\n        self.router.add_static('/pre', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_with_trailing_slash(self):\n        self.router.add_route('GET', '/get/{name}/',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertEqual({'name': 'John'}, route.match('/get/John/'))\n\n    def test_len(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual(2, len(self.router))\n\n    def test_iter(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual({'name1', 'name2'}, set(iter(self.router)))\n\n    def test_contains(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertIn('name1', self.router)\n        self.assertNotIn('name3', self.router)\n\n    def test_plain_repr(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<PlainRoute 'name' \\[GET\\] /get/path\")\n\n    def test_dynamic_repr(self):\n        self.router.add_route('GET', '/get/{path}',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<DynamicRoute 'name' \\[GET\\] /get/{path}\")\n\n    def test_static_repr(self):\n        self.router.add_static('/get', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<StaticRoute 'name' \\[GET\\] /get/\")\n\n    def test_static_adds_slash(self):\n        route = self.router.add_static('/prefix',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_static_dont_add__double_slash(self):\n        route = self.router.add_static('/prefix/',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_add_route_with_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/1234')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': '1234'}, info)\n\n    def test_add_route_with_re_not_match(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/tail')\n        with self.assertRaises(HTTPNotFound):\n            self.loop.run_until_complete(self.router.resolve(req))\n\n    def test_add_route_with_re_including_slashes(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:.+}/tail', handler)\n\n        req = self.make_request('GET', '/handler/re/with/slashes/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 're/with/slashes'}, info)\n\n    def test_add_route_with_invalid_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        with self.assertRaises(ValueError) as ctx:\n            self.router.add_route('GET', r'/handler/{to:+++}', handler)\n        self.assertEqual(\n            \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\",\n            str(ctx.exception))\n        self.assertIsNone(ctx.exception.__cause__)\n",
            "new_file_content": "import asyncio\nimport os\nimport unittest\nfrom unittest import mock\nimport aiohttp.web\nfrom aiohttp.web import (UrlDispatcher, Request, Response,\n                         HTTPMethodNotAllowed, HTTPNotFound)\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.protocol import HttpVersion, RawRequestMessage\n\n\nclass TestUrlDispatcher(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.router = UrlDispatcher()\n\n    def tearDown(self):\n        self.loop.close()\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_add_route_root(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/', handler)\n        req = self.make_request('GET', '/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_route_simple(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path', handler)\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_matchdict(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/{to}', handler)\n        req = self.make_request('GET', '/handler/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 'tail'}, info)\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_name(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/handler/to/path', handler,\n                              name='name')\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual('name', info.route.name)\n\n    def test_add_with_tailing_slash(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path/', handler)\n        req = self.make_request('GET', '/handler/to/path/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler, info.handler)\n\n    def test_add_invalid_path(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('GET', '/{/', lambda req: None)\n\n    def test_add_url_invalid1(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id', lambda: None)\n\n    def test_add_url_invalid2(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}}', lambda: None)\n\n    def test_add_url_invalid3(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}', lambda: None)\n\n    def test_add_url_invalid4(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id\"}', lambda: None)\n\n    def test_add_url_invalid5(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post\"{id}', lambda: None)\n\n    def test_add_url_escaping(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/+$', handler)\n\n        req = self.make_request('GET', '/+$')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertIs(handler, info.handler)\n\n    def test_match_second_result_in_table(self):\n        handler1 = asyncio.coroutine(lambda req: Response(req))\n        handler2 = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/h1', handler1)\n        self.router.add_route('POST', '/h2', handler2)\n        req = self.make_request('POST', '/h2')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler2, info.handler)\n\n    def test_raise_method_not_allowed(self):\n        handler1 = lambda req: Response(req)\n        handler2 = lambda req: Response(req)\n        self.router.add_route('GET', '/', handler1)\n        self.router.add_route('POST', '/', handler2)\n        req = self.make_request('PUT', '/')\n\n        with self.assertRaises(HTTPMethodNotAllowed) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual('PUT', exc.method)\n        self.assertEqual(405, exc.status)\n        self.assertEqual({'POST', 'GET'}, exc.allowed_methods)\n\n    def test_raise_method_not_found(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/a', handler)\n        req = self.make_request('GET', '/b')\n\n        with self.assertRaises(HTTPNotFound) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual(404, exc.status)\n\n    def test_double_add_url_with_the_same_name(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        regexp = (\"Duplicate 'name', already handled by\")\n        with self.assertRaisesRegex(ValueError, regexp):\n            self.router.add_route('GET', '/get_other', lambda r: None,\n                                  name='name')\n\n    def test_route_plain(self):\n        route = self.router.add_route('GET', '/get', lambda r: None,\n                                      name='name')\n        route2 = self.router['name']\n        url = route2.url()\n        self.assertEqual('/get', url)\n        self.assertIs(route, route2)\n\n    def test_route_unknown_route_name(self):\n        with self.assertRaises(KeyError):\n            self.router['unknown']\n\n    def test_route_dynamic(self):\n        route = self.router.add_route('GET', '/get/{name}',\n                                      lambda r: None, name='name')\n\n        route2 = self.router['name']\n        url = route2.url(parts={'name': 'John'})\n        self.assertEqual('/get/John', url)\n        self.assertIs(route, route2)\n\n    def test_route_with_qs(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        url = self.router['name'].url(query=[('a', 'b'), ('c', 1)])\n        self.assertEqual('/get?a=b&c=1', url)\n\n    def test_add_static(self):\n        route = self.router.add_static('/st',\n                                       os.path.dirname(aiohttp.__file__),\n                                       name='static')\n        route2 = self.router['static']\n        url = route2.url(filename='/dir/a.txt')\n        self.assertEqual('/st/dir/a.txt', url)\n        self.assertIs(route, route2)\n\n    def test_plain_not_match(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_not_match(self):\n        self.router.add_route('GET', '/get/{name}',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_static_not_match(self):\n        self.router.add_static('/pre', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_with_trailing_slash(self):\n        self.router.add_route('GET', '/get/{name}/',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertEqual({'name': 'John'}, route.match('/get/John/'))\n\n    def test_len(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual(2, len(self.router))\n\n    def test_iter(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual({'name1', 'name2'}, set(iter(self.router)))\n\n    def test_contains(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertIn('name1', self.router)\n        self.assertNotIn('name3', self.router)\n\n    def test_plain_repr(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<PlainRoute 'name' \\[GET\\] /get/path\")\n\n    def test_dynamic_repr(self):\n        self.router.add_route('GET', '/get/{path}',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<DynamicRoute 'name' \\[GET\\] /get/{path}\")\n\n    def test_static_repr(self):\n        self.router.add_static('/get', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<StaticRoute 'name' \\[GET\\] /get/\")\n\n    def test_static_adds_slash(self):\n        route = self.router.add_static('/prefix',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_static_dont_add__double_slash(self):\n        route = self.router.add_static('/prefix/',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_add_route_with_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/1234')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': '1234'}, info)\n\n    def test_add_route_with_re_not_match(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/tail')\n        with self.assertRaises(HTTPNotFound):\n            self.loop.run_until_complete(self.router.resolve(req))\n\n    def test_add_route_with_re_including_slashes(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:.+}/tail', handler)\n\n        req = self.make_request('GET', '/handler/re/with/slashes/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 're/with/slashes'}, info)\n\n    def test_add_route_with_invalid_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        with self.assertRaises(ValueError) as ctx:\n            self.router.add_route('GET', r'/handler/{to:+++}', handler)\n        self.assertEqual(\n            \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\",\n            str(ctx.exception))\n        self.assertIsNone(ctx.exception.__cause__)\n",
            "header": {
                "file": {
                    "path": "tests/test_urldispatch.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "0564c4b5",
                "new_commit_hash": "3295f1db",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_urldispatch.py"
            },
            "plus_file": {
                "path": "b/tests/test_urldispatch.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 28,
                            "length": 7
                        },
                        "new_range": {
                            "start": 28,
                            "length": 7
                        },
                        "section": "class TestUrlDispatcher(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.reader = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        self.writer = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        req = Request(self.app, message, self.payload,",
                                "type": "context"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer, 15)",
                                "type": "deleted"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer)",
                                "type": "added"
                            },
                            {
                                "content": "        return req",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_add_route_root(self):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_urldispatch.py",
                            "type": "class",
                            "name": "TestUrlDispatcher",
                            "content": "class TestUrlDispatcher(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.router = UrlDispatcher()\n\n    def tearDown(self):\n        self.loop.close()\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_add_route_root(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/', handler)\n        req = self.make_request('GET', '/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_route_simple(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path', handler)\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_matchdict(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/{to}', handler)\n        req = self.make_request('GET', '/handler/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 'tail'}, info)\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_name(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/handler/to/path', handler,\n                              name='name')\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual('name', info.route.name)\n\n    def test_add_with_tailing_slash(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path/', handler)\n        req = self.make_request('GET', '/handler/to/path/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler, info.handler)\n\n    def test_add_invalid_path(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('GET', '/{/', lambda req: None)\n\n    def test_add_url_invalid1(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id', lambda: None)\n\n    def test_add_url_invalid2(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}}', lambda: None)\n\n    def test_add_url_invalid3(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}', lambda: None)\n\n    def test_add_url_invalid4(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id\"}', lambda: None)\n\n    def test_add_url_invalid5(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post\"{id}', lambda: None)\n\n    def test_add_url_escaping(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/+$', handler)\n\n        req = self.make_request('GET', '/+$')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertIs(handler, info.handler)\n\n    def test_match_second_result_in_table(self):\n        handler1 = asyncio.coroutine(lambda req: Response(req))\n        handler2 = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/h1', handler1)\n        self.router.add_route('POST', '/h2', handler2)\n        req = self.make_request('POST', '/h2')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler2, info.handler)\n\n    def test_raise_method_not_allowed(self):\n        handler1 = lambda req: Response(req)\n        handler2 = lambda req: Response(req)\n        self.router.add_route('GET', '/', handler1)\n        self.router.add_route('POST', '/', handler2)\n        req = self.make_request('PUT', '/')\n\n        with self.assertRaises(HTTPMethodNotAllowed) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual('PUT', exc.method)\n        self.assertEqual(405, exc.status)\n        self.assertEqual({'POST', 'GET'}, exc.allowed_methods)\n\n    def test_raise_method_not_found(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/a', handler)\n        req = self.make_request('GET', '/b')\n\n        with self.assertRaises(HTTPNotFound) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual(404, exc.status)\n\n    def test_double_add_url_with_the_same_name(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        regexp = (\"Duplicate 'name', already handled by\")\n        with self.assertRaisesRegex(ValueError, regexp):\n            self.router.add_route('GET', '/get_other', lambda r: None,\n                                  name='name')\n\n    def test_route_plain(self):\n        route = self.router.add_route('GET', '/get', lambda r: None,\n                                      name='name')\n        route2 = self.router['name']\n        url = route2.url()\n        self.assertEqual('/get', url)\n        self.assertIs(route, route2)\n\n    def test_route_unknown_route_name(self):\n        with self.assertRaises(KeyError):\n            self.router['unknown']\n\n    def test_route_dynamic(self):\n        route = self.router.add_route('GET', '/get/{name}',\n                                      lambda r: None, name='name')\n\n        route2 = self.router['name']\n        url = route2.url(parts={'name': 'John'})\n        self.assertEqual('/get/John', url)\n        self.assertIs(route, route2)\n\n    def test_route_with_qs(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        url = self.router['name'].url(query=[('a', 'b'), ('c', 1)])\n        self.assertEqual('/get?a=b&c=1', url)\n\n    def test_add_static(self):\n        route = self.router.add_static('/st',\n                                       os.path.dirname(aiohttp.__file__),\n                                       name='static')\n        route2 = self.router['static']\n        url = route2.url(filename='/dir/a.txt')\n        self.assertEqual('/st/dir/a.txt', url)\n        self.assertIs(route, route2)\n\n    def test_plain_not_match(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_not_match(self):\n        self.router.add_route('GET', '/get/{name}',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_static_not_match(self):\n        self.router.add_static('/pre', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_with_trailing_slash(self):\n        self.router.add_route('GET', '/get/{name}/',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertEqual({'name': 'John'}, route.match('/get/John/'))\n\n    def test_len(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual(2, len(self.router))\n\n    def test_iter(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual({'name1', 'name2'}, set(iter(self.router)))\n\n    def test_contains(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertIn('name1', self.router)\n        self.assertNotIn('name3', self.router)\n\n    def test_plain_repr(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<PlainRoute 'name' \\[GET\\] /get/path\")\n\n    def test_dynamic_repr(self):\n        self.router.add_route('GET', '/get/{path}',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<DynamicRoute 'name' \\[GET\\] /get/{path}\")\n\n    def test_static_repr(self):\n        self.router.add_static('/get', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<StaticRoute 'name' \\[GET\\] /get/\")\n\n    def test_static_adds_slash(self):\n        route = self.router.add_static('/prefix',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_static_dont_add__double_slash(self):\n        route = self.router.add_static('/prefix/',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_add_route_with_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/1234')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': '1234'}, info)\n\n    def test_add_route_with_re_not_match(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/tail')\n        with self.assertRaises(HTTPNotFound):\n            self.loop.run_until_complete(self.router.resolve(req))\n\n    def test_add_route_with_re_including_slashes(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:.+}/tail', handler)\n\n        req = self.make_request('GET', '/handler/re/with/slashes/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 're/with/slashes'}, info)\n\n    def test_add_route_with_invalid_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        with self.assertRaises(ValueError) as ctx:\n            self.router.add_route('GET', r'/handler/{to:+++}', handler)\n        self.assertEqual(\n            \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\",\n            str(ctx.exception))\n        self.assertIsNone(ctx.exception.__cause__)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 12,
                            "end_lineno": 303,
                            "parent": null
                        },
                        {
                            "file_name": "tests/test_urldispatch.py",
                            "type": "method",
                            "name": "TestUrlDispatcher.make_request",
                            "content": "class TestUrlDispatcher(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.router = UrlDispatcher()\n\n    def tearDown(self):\n        self.loop.close()\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_add_route_root(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/', handler)\n        req = self.make_request('GET', '/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_route_simple(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path', handler)\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_matchdict(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/{to}', handler)\n        req = self.make_request('GET', '/handler/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 'tail'}, info)\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_name(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/handler/to/path', handler,\n                              name='name')\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual('name', info.route.name)\n\n    def test_add_with_tailing_slash(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path/', handler)\n        req = self.make_request('GET', '/handler/to/path/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler, info.handler)\n\n    def test_add_invalid_path(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('GET', '/{/', lambda req: None)\n\n    def test_add_url_invalid1(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id', lambda: None)\n\n    def test_add_url_invalid2(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}}', lambda: None)\n\n    def test_add_url_invalid3(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}', lambda: None)\n\n    def test_add_url_invalid4(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id\"}', lambda: None)\n\n    def test_add_url_invalid5(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post\"{id}', lambda: None)\n\n    def test_add_url_escaping(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/+$', handler)\n\n        req = self.make_request('GET', '/+$')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertIs(handler, info.handler)\n\n    def test_match_second_result_in_table(self):\n        handler1 = asyncio.coroutine(lambda req: Response(req))\n        handler2 = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/h1', handler1)\n        self.router.add_route('POST', '/h2', handler2)\n        req = self.make_request('POST', '/h2')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler2, info.handler)\n\n    def test_raise_method_not_allowed(self):\n        handler1 = lambda req: Response(req)\n        handler2 = lambda req: Response(req)\n        self.router.add_route('GET', '/', handler1)\n        self.router.add_route('POST', '/', handler2)\n        req = self.make_request('PUT', '/')\n\n        with self.assertRaises(HTTPMethodNotAllowed) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual('PUT', exc.method)\n        self.assertEqual(405, exc.status)\n        self.assertEqual({'POST', 'GET'}, exc.allowed_methods)\n\n    def test_raise_method_not_found(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/a', handler)\n        req = self.make_request('GET', '/b')\n\n        with self.assertRaises(HTTPNotFound) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual(404, exc.status)\n\n    def test_double_add_url_with_the_same_name(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        regexp = (\"Duplicate 'name', already handled by\")\n        with self.assertRaisesRegex(ValueError, regexp):\n            self.router.add_route('GET', '/get_other', lambda r: None,\n                                  name='name')\n\n    def test_route_plain(self):\n        route = self.router.add_route('GET', '/get', lambda r: None,\n                                      name='name')\n        route2 = self.router['name']\n        url = route2.url()\n        self.assertEqual('/get', url)\n        self.assertIs(route, route2)\n\n    def test_route_unknown_route_name(self):\n        with self.assertRaises(KeyError):\n            self.router['unknown']\n\n    def test_route_dynamic(self):\n        route = self.router.add_route('GET', '/get/{name}',\n                                      lambda r: None, name='name')\n\n        route2 = self.router['name']\n        url = route2.url(parts={'name': 'John'})\n        self.assertEqual('/get/John', url)\n        self.assertIs(route, route2)\n\n    def test_route_with_qs(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        url = self.router['name'].url(query=[('a', 'b'), ('c', 1)])\n        self.assertEqual('/get?a=b&c=1', url)\n\n    def test_add_static(self):\n        route = self.router.add_static('/st',\n                                       os.path.dirname(aiohttp.__file__),\n                                       name='static')\n        route2 = self.router['static']\n        url = route2.url(filename='/dir/a.txt')\n        self.assertEqual('/st/dir/a.txt', url)\n        self.assertIs(route, route2)\n\n    def test_plain_not_match(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_not_match(self):\n        self.router.add_route('GET', '/get/{name}',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_static_not_match(self):\n        self.router.add_static('/pre', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_with_trailing_slash(self):\n        self.router.add_route('GET', '/get/{name}/',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertEqual({'name': 'John'}, route.match('/get/John/'))\n\n    def test_len(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual(2, len(self.router))\n\n    def test_iter(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual({'name1', 'name2'}, set(iter(self.router)))\n\n    def test_contains(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertIn('name1', self.router)\n        self.assertNotIn('name3', self.router)\n\n    def test_plain_repr(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<PlainRoute 'name' \\[GET\\] /get/path\")\n\n    def test_dynamic_repr(self):\n        self.router.add_route('GET', '/get/{path}',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<DynamicRoute 'name' \\[GET\\] /get/{path}\")\n\n    def test_static_repr(self):\n        self.router.add_static('/get', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<StaticRoute 'name' \\[GET\\] /get/\")\n\n    def test_static_adds_slash(self):\n        route = self.router.add_static('/prefix',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_static_dont_add__double_slash(self):\n        route = self.router.add_static('/prefix/',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_add_route_with_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/1234')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': '1234'}, info)\n\n    def test_add_route_with_re_not_match(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/tail')\n        with self.assertRaises(HTTPNotFound):\n            self.loop.run_until_complete(self.router.resolve(req))\n\n    def test_add_route_with_re_including_slashes(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:.+}/tail', handler)\n\n        req = self.make_request('GET', '/handler/re/with/slashes/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 're/with/slashes'}, info)\n\n    def test_add_route_with_invalid_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        with self.assertRaises(ValueError) as ctx:\n            self.router.add_route('GET', r'/handler/{to:+++}', handler)\n        self.assertEqual(\n            \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\",\n            str(ctx.exception))\n        self.assertIsNone(ctx.exception.__cause__)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 22,
                            "end_lineno": 32,
                            "parent": {
                                "file_name": "tests/test_urldispatch.py",
                                "type": "class",
                                "name": "TestUrlDispatcher",
                                "content": "class TestUrlDispatcher(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.router = UrlDispatcher()\n\n    def tearDown(self):\n        self.loop.close()\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_add_route_root(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/', handler)\n        req = self.make_request('GET', '/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_route_simple(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path', handler)\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_matchdict(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/{to}', handler)\n        req = self.make_request('GET', '/handler/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 'tail'}, info)\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_name(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/handler/to/path', handler,\n                              name='name')\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual('name', info.route.name)\n\n    def test_add_with_tailing_slash(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path/', handler)\n        req = self.make_request('GET', '/handler/to/path/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler, info.handler)\n\n    def test_add_invalid_path(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('GET', '/{/', lambda req: None)\n\n    def test_add_url_invalid1(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id', lambda: None)\n\n    def test_add_url_invalid2(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}}', lambda: None)\n\n    def test_add_url_invalid3(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}', lambda: None)\n\n    def test_add_url_invalid4(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id\"}', lambda: None)\n\n    def test_add_url_invalid5(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post\"{id}', lambda: None)\n\n    def test_add_url_escaping(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/+$', handler)\n\n        req = self.make_request('GET', '/+$')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertIs(handler, info.handler)\n\n    def test_match_second_result_in_table(self):\n        handler1 = asyncio.coroutine(lambda req: Response(req))\n        handler2 = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/h1', handler1)\n        self.router.add_route('POST', '/h2', handler2)\n        req = self.make_request('POST', '/h2')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler2, info.handler)\n\n    def test_raise_method_not_allowed(self):\n        handler1 = lambda req: Response(req)\n        handler2 = lambda req: Response(req)\n        self.router.add_route('GET', '/', handler1)\n        self.router.add_route('POST', '/', handler2)\n        req = self.make_request('PUT', '/')\n\n        with self.assertRaises(HTTPMethodNotAllowed) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual('PUT', exc.method)\n        self.assertEqual(405, exc.status)\n        self.assertEqual({'POST', 'GET'}, exc.allowed_methods)\n\n    def test_raise_method_not_found(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/a', handler)\n        req = self.make_request('GET', '/b')\n\n        with self.assertRaises(HTTPNotFound) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual(404, exc.status)\n\n    def test_double_add_url_with_the_same_name(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        regexp = (\"Duplicate 'name', already handled by\")\n        with self.assertRaisesRegex(ValueError, regexp):\n            self.router.add_route('GET', '/get_other', lambda r: None,\n                                  name='name')\n\n    def test_route_plain(self):\n        route = self.router.add_route('GET', '/get', lambda r: None,\n                                      name='name')\n        route2 = self.router['name']\n        url = route2.url()\n        self.assertEqual('/get', url)\n        self.assertIs(route, route2)\n\n    def test_route_unknown_route_name(self):\n        with self.assertRaises(KeyError):\n            self.router['unknown']\n\n    def test_route_dynamic(self):\n        route = self.router.add_route('GET', '/get/{name}',\n                                      lambda r: None, name='name')\n\n        route2 = self.router['name']\n        url = route2.url(parts={'name': 'John'})\n        self.assertEqual('/get/John', url)\n        self.assertIs(route, route2)\n\n    def test_route_with_qs(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        url = self.router['name'].url(query=[('a', 'b'), ('c', 1)])\n        self.assertEqual('/get?a=b&c=1', url)\n\n    def test_add_static(self):\n        route = self.router.add_static('/st',\n                                       os.path.dirname(aiohttp.__file__),\n                                       name='static')\n        route2 = self.router['static']\n        url = route2.url(filename='/dir/a.txt')\n        self.assertEqual('/st/dir/a.txt', url)\n        self.assertIs(route, route2)\n\n    def test_plain_not_match(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_not_match(self):\n        self.router.add_route('GET', '/get/{name}',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_static_not_match(self):\n        self.router.add_static('/pre', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_with_trailing_slash(self):\n        self.router.add_route('GET', '/get/{name}/',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertEqual({'name': 'John'}, route.match('/get/John/'))\n\n    def test_len(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual(2, len(self.router))\n\n    def test_iter(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual({'name1', 'name2'}, set(iter(self.router)))\n\n    def test_contains(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertIn('name1', self.router)\n        self.assertNotIn('name3', self.router)\n\n    def test_plain_repr(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<PlainRoute 'name' \\[GET\\] /get/path\")\n\n    def test_dynamic_repr(self):\n        self.router.add_route('GET', '/get/{path}',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<DynamicRoute 'name' \\[GET\\] /get/{path}\")\n\n    def test_static_repr(self):\n        self.router.add_static('/get', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<StaticRoute 'name' \\[GET\\] /get/\")\n\n    def test_static_adds_slash(self):\n        route = self.router.add_static('/prefix',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_static_dont_add__double_slash(self):\n        route = self.router.add_static('/prefix/',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_add_route_with_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/1234')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': '1234'}, info)\n\n    def test_add_route_with_re_not_match(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/tail')\n        with self.assertRaises(HTTPNotFound):\n            self.loop.run_until_complete(self.router.resolve(req))\n\n    def test_add_route_with_re_including_slashes(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:.+}/tail', handler)\n\n        req = self.make_request('GET', '/handler/re/with/slashes/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 're/with/slashes'}, info)\n\n    def test_add_route_with_invalid_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        with self.assertRaises(ValueError) as ctx:\n            self.router.add_route('GET', r'/handler/{to:+++}', handler)\n        self.assertEqual(\n            \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\",\n            str(ctx.exception))\n        self.assertIsNone(ctx.exception.__cause__)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 12,
                                "end_lineno": 303,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport collections\nimport unittest\nfrom unittest import mock\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.web import Request\nfrom aiohttp.protocol import RawRequestMessage, HttpVersion11\n\nfrom aiohttp import web\n\n\nclass TestHTTPExceptions(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        self.writer.drain.return_value = ()\n        self.buf = b''\n\n        self.writer.write.side_effect = self.append\n\n    def tearDown(self):\n        self.loop.close()\n\n    def append(self, data):\n        self.buf += data\n\n    def make_request(self, method='GET', path='/', headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_all_http_exceptions_exported(self):\n        self.assertIn('HTTPException', web.__all__)\n        for name in dir(web):\n            if name.startswith('_'):\n                continue\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                self.assertIn(name, web.__all__)\n\n    def test_HTTPOk(self):\n        req = self.make_request()\n        resp = web.HTTPOk()\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 200 OK\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 7\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '200: OK'))\n\n    def test_terminal_classes_has_status_code(self):\n        terminals = set()\n        for name in dir(web):\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                terminals.add(obj)\n\n        dup = frozenset(terminals)\n        for cls1 in dup:\n            for cls2 in dup:\n                if cls1 in cls2.__bases__:\n                    terminals.discard(cls1)\n\n        for cls in terminals:\n            self.assertIsNotNone(cls.status_code, cls)\n        codes = collections.Counter(cls.status_code for cls in terminals)\n        self.assertNotIn(None, codes)\n        self.assertEqual(1, codes.most_common(1)[0][1])\n\n    def test_HTTPFound(self):\n        req = self.make_request()\n        resp = web.HTTPFound(location='/redirect')\n        self.assertEqual('/redirect', resp.location)\n        self.assertEqual('/redirect', resp.headers['location'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 302 Found\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 10\\r\\n'\n                               'LOCATION: /redirect\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '302: Found'))\n\n    def test_HTTPFound_empty_location(self):\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location='')\n\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location=None)\n\n    def test_HTTPMethodNotAllowed(self):\n        req = self.make_request()\n        resp = web.HTTPMethodNotAllowed('get', ['POST', 'PUT'])\n        self.assertEqual('GET', resp.method)\n        self.assertEqual(['POST', 'PUT'], resp.allowed_methods)\n        self.assertEqual('POST,PUT', resp.headers['allow'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 405 Method Not Allowed\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 23\\r\\n'\n                               'ALLOW: POST,PUT\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '405: Method Not Allowed'))\n\n    def test_override_body_with_text(self):\n        resp = web.HTTPNotFound(text=\"Page not found\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(\"Page not found\".encode('utf-8'), resp.body)\n        self.assertEqual(\"Page not found\", resp.text)\n        self.assertEqual(\"text/plain\", resp.content_type)\n        self.assertEqual(\"utf-8\", resp.charset)\n\n    def test_override_body_with_binary(self):\n        txt = \"<html><body>Page not found</body></html>\"\n        resp = web.HTTPNotFound(body=txt.encode('utf-8'),\n                                content_type=\"text/html\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(txt.encode('utf-8'), resp.body)\n        self.assertEqual(txt, resp.text)\n        self.assertEqual(\"text/html\", resp.content_type)\n        self.assertIsNone(resp.charset)\n",
            "new_file_content": "import asyncio\nimport collections\nimport unittest\nfrom unittest import mock\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.web import Request\nfrom aiohttp.protocol import RawRequestMessage, HttpVersion11\n\nfrom aiohttp import web\n\n\nclass TestHTTPExceptions(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        self.writer.drain.return_value = ()\n        self.buf = b''\n\n        self.writer.write.side_effect = self.append\n\n    def tearDown(self):\n        self.loop.close()\n\n    def append(self, data):\n        self.buf += data\n\n    def make_request(self, method='GET', path='/', headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_all_http_exceptions_exported(self):\n        self.assertIn('HTTPException', web.__all__)\n        for name in dir(web):\n            if name.startswith('_'):\n                continue\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                self.assertIn(name, web.__all__)\n\n    def test_HTTPOk(self):\n        req = self.make_request()\n        resp = web.HTTPOk()\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 200 OK\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 7\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '200: OK'))\n\n    def test_terminal_classes_has_status_code(self):\n        terminals = set()\n        for name in dir(web):\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                terminals.add(obj)\n\n        dup = frozenset(terminals)\n        for cls1 in dup:\n            for cls2 in dup:\n                if cls1 in cls2.__bases__:\n                    terminals.discard(cls1)\n\n        for cls in terminals:\n            self.assertIsNotNone(cls.status_code, cls)\n        codes = collections.Counter(cls.status_code for cls in terminals)\n        self.assertNotIn(None, codes)\n        self.assertEqual(1, codes.most_common(1)[0][1])\n\n    def test_HTTPFound(self):\n        req = self.make_request()\n        resp = web.HTTPFound(location='/redirect')\n        self.assertEqual('/redirect', resp.location)\n        self.assertEqual('/redirect', resp.headers['location'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 302 Found\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 10\\r\\n'\n                               'LOCATION: /redirect\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '302: Found'))\n\n    def test_HTTPFound_empty_location(self):\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location='')\n\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location=None)\n\n    def test_HTTPMethodNotAllowed(self):\n        req = self.make_request()\n        resp = web.HTTPMethodNotAllowed('get', ['POST', 'PUT'])\n        self.assertEqual('GET', resp.method)\n        self.assertEqual(['POST', 'PUT'], resp.allowed_methods)\n        self.assertEqual('POST,PUT', resp.headers['allow'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 405 Method Not Allowed\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 23\\r\\n'\n                               'ALLOW: POST,PUT\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '405: Method Not Allowed'))\n\n    def test_override_body_with_text(self):\n        resp = web.HTTPNotFound(text=\"Page not found\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(\"Page not found\".encode('utf-8'), resp.body)\n        self.assertEqual(\"Page not found\", resp.text)\n        self.assertEqual(\"text/plain\", resp.content_type)\n        self.assertEqual(\"utf-8\", resp.charset)\n\n    def test_override_body_with_binary(self):\n        txt = \"<html><body>Page not found</body></html>\"\n        resp = web.HTTPNotFound(body=txt.encode('utf-8'),\n                                content_type=\"text/html\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(txt.encode('utf-8'), resp.body)\n        self.assertEqual(txt, resp.text)\n        self.assertEqual(\"text/html\", resp.content_type)\n        self.assertIsNone(resp.charset)\n",
            "header": {
                "file": {
                    "path": "tests/test_web_exceptions.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "3fa566ba",
                "new_commit_hash": "b5ff8ed9",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_web_exceptions.py"
            },
            "plus_file": {
                "path": "b/tests/test_web_exceptions.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 35,
                            "length": 7
                        },
                        "new_range": {
                            "start": 35,
                            "length": 7
                        },
                        "section": "class TestHTTPExceptions(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        message = RawRequestMessage(method, path, HttpVersion11, headers,",
                                "type": "context"
                            },
                            {
                                "content": "                                    False, False)",
                                "type": "context"
                            },
                            {
                                "content": "        req = Request(self.app, message, self.payload,",
                                "type": "context"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer, 15)",
                                "type": "deleted"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer)",
                                "type": "added"
                            },
                            {
                                "content": "        return req",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_all_http_exceptions_exported(self):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_web_exceptions.py",
                            "type": "class",
                            "name": "TestHTTPExceptions",
                            "content": "class TestHTTPExceptions(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        self.writer.drain.return_value = ()\n        self.buf = b''\n\n        self.writer.write.side_effect = self.append\n\n    def tearDown(self):\n        self.loop.close()\n\n    def append(self, data):\n        self.buf += data\n\n    def make_request(self, method='GET', path='/', headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_all_http_exceptions_exported(self):\n        self.assertIn('HTTPException', web.__all__)\n        for name in dir(web):\n            if name.startswith('_'):\n                continue\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                self.assertIn(name, web.__all__)\n\n    def test_HTTPOk(self):\n        req = self.make_request()\n        resp = web.HTTPOk()\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 200 OK\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 7\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '200: OK'))\n\n    def test_terminal_classes_has_status_code(self):\n        terminals = set()\n        for name in dir(web):\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                terminals.add(obj)\n\n        dup = frozenset(terminals)\n        for cls1 in dup:\n            for cls2 in dup:\n                if cls1 in cls2.__bases__:\n                    terminals.discard(cls1)\n\n        for cls in terminals:\n            self.assertIsNotNone(cls.status_code, cls)\n        codes = collections.Counter(cls.status_code for cls in terminals)\n        self.assertNotIn(None, codes)\n        self.assertEqual(1, codes.most_common(1)[0][1])\n\n    def test_HTTPFound(self):\n        req = self.make_request()\n        resp = web.HTTPFound(location='/redirect')\n        self.assertEqual('/redirect', resp.location)\n        self.assertEqual('/redirect', resp.headers['location'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 302 Found\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 10\\r\\n'\n                               'LOCATION: /redirect\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '302: Found'))\n\n    def test_HTTPFound_empty_location(self):\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location='')\n\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location=None)\n\n    def test_HTTPMethodNotAllowed(self):\n        req = self.make_request()\n        resp = web.HTTPMethodNotAllowed('get', ['POST', 'PUT'])\n        self.assertEqual('GET', resp.method)\n        self.assertEqual(['POST', 'PUT'], resp.allowed_methods)\n        self.assertEqual('POST,PUT', resp.headers['allow'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 405 Method Not Allowed\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 23\\r\\n'\n                               'ALLOW: POST,PUT\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '405: Method Not Allowed'))\n\n    def test_override_body_with_text(self):\n        resp = web.HTTPNotFound(text=\"Page not found\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(\"Page not found\".encode('utf-8'), resp.body)\n        self.assertEqual(\"Page not found\", resp.text)\n        self.assertEqual(\"text/plain\", resp.content_type)\n        self.assertEqual(\"utf-8\", resp.charset)\n\n    def test_override_body_with_binary(self):\n        txt = \"<html><body>Page not found</body></html>\"\n        resp = web.HTTPNotFound(body=txt.encode('utf-8'),\n                                content_type=\"text/html\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(txt.encode('utf-8'), resp.body)\n        self.assertEqual(txt, resp.text)\n        self.assertEqual(\"text/html\", resp.content_type)\n        self.assertIsNone(resp.charset)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 12,
                            "end_lineno": 141,
                            "parent": null
                        },
                        {
                            "file_name": "tests/test_web_exceptions.py",
                            "type": "method",
                            "name": "TestHTTPExceptions.make_request",
                            "content": "class TestHTTPExceptions(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        self.writer.drain.return_value = ()\n        self.buf = b''\n\n        self.writer.write.side_effect = self.append\n\n    def tearDown(self):\n        self.loop.close()\n\n    def append(self, data):\n        self.buf += data\n\n    def make_request(self, method='GET', path='/', headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_all_http_exceptions_exported(self):\n        self.assertIn('HTTPException', web.__all__)\n        for name in dir(web):\n            if name.startswith('_'):\n                continue\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                self.assertIn(name, web.__all__)\n\n    def test_HTTPOk(self):\n        req = self.make_request()\n        resp = web.HTTPOk()\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 200 OK\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 7\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '200: OK'))\n\n    def test_terminal_classes_has_status_code(self):\n        terminals = set()\n        for name in dir(web):\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                terminals.add(obj)\n\n        dup = frozenset(terminals)\n        for cls1 in dup:\n            for cls2 in dup:\n                if cls1 in cls2.__bases__:\n                    terminals.discard(cls1)\n\n        for cls in terminals:\n            self.assertIsNotNone(cls.status_code, cls)\n        codes = collections.Counter(cls.status_code for cls in terminals)\n        self.assertNotIn(None, codes)\n        self.assertEqual(1, codes.most_common(1)[0][1])\n\n    def test_HTTPFound(self):\n        req = self.make_request()\n        resp = web.HTTPFound(location='/redirect')\n        self.assertEqual('/redirect', resp.location)\n        self.assertEqual('/redirect', resp.headers['location'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 302 Found\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 10\\r\\n'\n                               'LOCATION: /redirect\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '302: Found'))\n\n    def test_HTTPFound_empty_location(self):\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location='')\n\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location=None)\n\n    def test_HTTPMethodNotAllowed(self):\n        req = self.make_request()\n        resp = web.HTTPMethodNotAllowed('get', ['POST', 'PUT'])\n        self.assertEqual('GET', resp.method)\n        self.assertEqual(['POST', 'PUT'], resp.allowed_methods)\n        self.assertEqual('POST,PUT', resp.headers['allow'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 405 Method Not Allowed\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 23\\r\\n'\n                               'ALLOW: POST,PUT\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '405: Method Not Allowed'))\n\n    def test_override_body_with_text(self):\n        resp = web.HTTPNotFound(text=\"Page not found\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(\"Page not found\".encode('utf-8'), resp.body)\n        self.assertEqual(\"Page not found\", resp.text)\n        self.assertEqual(\"text/plain\", resp.content_type)\n        self.assertEqual(\"utf-8\", resp.charset)\n\n    def test_override_body_with_binary(self):\n        txt = \"<html><body>Page not found</body></html>\"\n        resp = web.HTTPNotFound(body=txt.encode('utf-8'),\n                                content_type=\"text/html\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(txt.encode('utf-8'), resp.body)\n        self.assertEqual(txt, resp.text)\n        self.assertEqual(\"text/html\", resp.content_type)\n        self.assertIsNone(resp.charset)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 33,
                            "end_lineno": 39,
                            "parent": {
                                "file_name": "tests/test_web_exceptions.py",
                                "type": "class",
                                "name": "TestHTTPExceptions",
                                "content": "class TestHTTPExceptions(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        self.writer.drain.return_value = ()\n        self.buf = b''\n\n        self.writer.write.side_effect = self.append\n\n    def tearDown(self):\n        self.loop.close()\n\n    def append(self, data):\n        self.buf += data\n\n    def make_request(self, method='GET', path='/', headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_all_http_exceptions_exported(self):\n        self.assertIn('HTTPException', web.__all__)\n        for name in dir(web):\n            if name.startswith('_'):\n                continue\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                self.assertIn(name, web.__all__)\n\n    def test_HTTPOk(self):\n        req = self.make_request()\n        resp = web.HTTPOk()\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 200 OK\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 7\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '200: OK'))\n\n    def test_terminal_classes_has_status_code(self):\n        terminals = set()\n        for name in dir(web):\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                terminals.add(obj)\n\n        dup = frozenset(terminals)\n        for cls1 in dup:\n            for cls2 in dup:\n                if cls1 in cls2.__bases__:\n                    terminals.discard(cls1)\n\n        for cls in terminals:\n            self.assertIsNotNone(cls.status_code, cls)\n        codes = collections.Counter(cls.status_code for cls in terminals)\n        self.assertNotIn(None, codes)\n        self.assertEqual(1, codes.most_common(1)[0][1])\n\n    def test_HTTPFound(self):\n        req = self.make_request()\n        resp = web.HTTPFound(location='/redirect')\n        self.assertEqual('/redirect', resp.location)\n        self.assertEqual('/redirect', resp.headers['location'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 302 Found\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 10\\r\\n'\n                               'LOCATION: /redirect\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '302: Found'))\n\n    def test_HTTPFound_empty_location(self):\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location='')\n\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location=None)\n\n    def test_HTTPMethodNotAllowed(self):\n        req = self.make_request()\n        resp = web.HTTPMethodNotAllowed('get', ['POST', 'PUT'])\n        self.assertEqual('GET', resp.method)\n        self.assertEqual(['POST', 'PUT'], resp.allowed_methods)\n        self.assertEqual('POST,PUT', resp.headers['allow'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 405 Method Not Allowed\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 23\\r\\n'\n                               'ALLOW: POST,PUT\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '405: Method Not Allowed'))\n\n    def test_override_body_with_text(self):\n        resp = web.HTTPNotFound(text=\"Page not found\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(\"Page not found\".encode('utf-8'), resp.body)\n        self.assertEqual(\"Page not found\", resp.text)\n        self.assertEqual(\"text/plain\", resp.content_type)\n        self.assertEqual(\"utf-8\", resp.charset)\n\n    def test_override_body_with_binary(self):\n        txt = \"<html><body>Page not found</body></html>\"\n        resp = web.HTTPNotFound(body=txt.encode('utf-8'),\n                                content_type=\"text/html\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(txt.encode('utf-8'), resp.body)\n        self.assertEqual(txt, resp.text)\n        self.assertEqual(\"text/html\", resp.content_type)\n        self.assertIsNone(resp.charset)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 12,
                                "end_lineno": 141,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport unittest\nfrom unittest import mock\nfrom aiohttp.web import Request\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.protocol import HttpVersion\nfrom aiohttp.protocol import RawRequestMessage\n\n\nclass TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)\n",
            "new_file_content": "import asyncio\nimport unittest\nfrom unittest import mock\nfrom aiohttp.web import Request\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.protocol import HttpVersion\nfrom aiohttp.protocol import RawRequestMessage\n\n\nclass TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)\n",
            "header": {
                "file": {
                    "path": "tests/test_web_request.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "d6a938f3",
                "new_commit_hash": "e844e8be",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_web_request.py"
            },
            "plus_file": {
                "path": "b/tests/test_web_request.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 17,
                            "length": 8
                        },
                        "new_range": {
                            "start": 17,
                            "length": 7
                        },
                        "section": "class TestWebRequest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.loop.close()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def make_request(self, method, path, headers=MultiDict(), *,",
                                "type": "context"
                            },
                            {
                                "content": "                     version=HttpVersion(1, 1), closing=False,",
                                "type": "deleted"
                            },
                            {
                                "content": "                     keep_alive_timeout=15):",
                                "type": "deleted"
                            },
                            {
                                "content": "                     version=HttpVersion(1, 1), closing=False):",
                                "type": "added"
                            },
                            {
                                "content": "        self.app = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        message = RawRequestMessage(method, path, version, headers, closing,",
                                "type": "context"
                            },
                            {
                                "content": "                                    False)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_web_request.py",
                            "type": "class",
                            "name": "TestWebRequest",
                            "content": "class TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 10,
                            "end_lineno": 168,
                            "parent": null
                        },
                        {
                            "file_name": "tests/test_web_request.py",
                            "type": "method",
                            "name": "TestWebRequest.make_request",
                            "content": "class TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 19,
                            "end_lineno": 32,
                            "parent": {
                                "file_name": "tests/test_web_request.py",
                                "type": "class",
                                "name": "TestWebRequest",
                                "content": "class TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 10,
                                "end_lineno": 168,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 27,
                            "length": 8
                        },
                        "new_range": {
                            "start": 26,
                            "length": 7
                        },
                        "section": "class TestWebRequest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.writer = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        self.reader = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        req = Request(self.app, message, self.payload,",
                                "type": "context"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer,",
                                "type": "deleted"
                            },
                            {
                                "content": "                      keep_alive_timeout)",
                                "type": "deleted"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer)",
                                "type": "added"
                            },
                            {
                                "content": "        return req",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_ctor(self):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_web_request.py",
                            "type": "class",
                            "name": "TestWebRequest",
                            "content": "class TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 10,
                            "end_lineno": 168,
                            "parent": null
                        },
                        {
                            "file_name": "tests/test_web_request.py",
                            "type": "method",
                            "name": "TestWebRequest.make_request",
                            "content": "class TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 19,
                            "end_lineno": 32,
                            "parent": {
                                "file_name": "tests/test_web_request.py",
                                "type": "class",
                                "name": "TestWebRequest",
                                "content": "class TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 10,
                                "end_lineno": 168,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 109,
                            "length": 10
                        },
                        "new_range": {
                            "start": 107,
                            "length": 6
                        },
                        "section": "class TestWebRequest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        req = self.make_request('GET', '/', closing=True)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertFalse(req.keep_alive)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):",
                                "type": "deleted"
                            },
                            {
                                "content": "        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.assertFalse(req.keep_alive)",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "    def test_call_POST_on_GET_request(self):",
                                "type": "context"
                            },
                            {
                                "content": "        req = self.make_request('GET', '/')",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_web_request.py",
                            "type": "class",
                            "name": "TestWebRequest",
                            "content": "class TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 10,
                            "end_lineno": 168,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": [
                        {
                            "file_name": "tests/test_web_request.py",
                            "type": "method",
                            "name": "TestWebRequest.test_non_keepalive_on_server_protocol_without_keepalive_timeout",
                            "content": "class TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 112,
                            "end_lineno": 114,
                            "parent": {
                                "file_name": "tests/test_web_request.py",
                                "type": "class",
                                "name": "TestWebRequest",
                                "content": "class TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False,\n                     keep_alive_timeout=15):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer,\n                      keep_alive_timeout)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_server_protocol_without_keepalive_timeout(self):\n        req = self.make_request('GET', '/', closing=True, keep_alive_timeout=0)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 10,
                                "end_lineno": 168,
                                "parent": null
                            }
                        }
                    ]
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport unittest\nfrom unittest import mock\nfrom aiohttp.multidict import MultiDict, CaseInsensitiveMultiDict\nfrom aiohttp.web import Request, StreamResponse, Response\nfrom aiohttp.protocol import RawRequestMessage, HttpVersion11\n\n\nclass TestStreamResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_ctor(self):\n        resp = StreamResponse()\n        self.assertEqual(200, resp.status)\n        self.assertIsNone(resp.keep_alive)\n\n    def test_content_length(self):\n        resp = StreamResponse()\n        self.assertIsNone(resp.content_length)\n\n    def test_content_length_setter(self):\n        resp = StreamResponse()\n\n        resp.content_length = 234\n        self.assertEqual(234, resp.content_length)\n\n    def test_drop_content_length_header_on_setting_len_to_None(self):\n        resp = StreamResponse()\n\n        resp.content_length = 1\n        self.assertEqual(\"1\", resp.headers['Content-Length'])\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_set_content_length_to_None_on_non_set(self):\n        resp = StreamResponse()\n\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_setting_content_type(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        self.assertEqual('text/html', resp.headers['content-type'])\n\n    def test_setting_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        self.assertEqual('text/html; charset=koi8-r',\n                         resp.headers['content-type'])\n\n    def test_default_charset(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset_after_setting(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_charset_without_content_type(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.charset = 'koi8-r'\n\n    @mock.patch('aiohttp.web.ResponseImpl')\n    def test_start(self, ResponseImpl):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        self.assertIsNone(resp.keep_alive)\n\n        msg = resp.start(req)\n\n        self.assertTrue(msg.send_headers.called)\n        self.assertIs(msg, resp.start(req))\n\n        self.assertTrue(resp.keep_alive)\n\n        req2 = self.make_request('GET', '/')\n        with self.assertRaises(RuntimeError):\n            resp.start(req2)\n\n    def test_write_non_byteish(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        with self.assertRaises(TypeError):\n            resp.write(123)\n\n    def test_write_before_start(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'data')\n\n    def test_cannot_write_after_eof(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.writer.write.reset_mock()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'next data')\n        self.assertFalse(self.writer.write.called)\n\n    def test_cannot_write_eof_before_headers(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            self.loop.run_until_complete(resp.write_eof())\n\n    def test_cannot_write_eof_twice(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertTrue(self.writer.write.called)\n\n        self.writer.write.reset_mock()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertFalse(self.writer.write.called)\n\n    def test_write_returns_drain(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b'data'))\n\n    def test_write_returns_empty_tuple_on_empty_data(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b''))\n\n    def test_force_close(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.keep_alive)\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n    def test_response_cookies(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.set_cookie('name', 'value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=value')\n        resp.set_cookie('name', 'other_value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=other_value')\n\n        resp.cookies['name'] = 'another_other_value'\n        resp.cookies['name']['max-age'] = 10\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=another_other_value; Max-Age=10')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n        resp.set_cookie('name', 'value', domain='local.host')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Domain=local.host')\n\n    def test_response_cookie_path(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n\n        resp.set_cookie('name', 'value', path='/some/path')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Path=/some/path')\n        resp.set_cookie('name', 'value', expires='123')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; expires=123;'\n                         ' Path=/some/path')\n        resp.set_cookie('name', 'value', domain='example.com',\n                        path='/home', expires='123', max_age='10',\n                        secure=True, httponly=True, version='2.0')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; '\n                         'Domain=example.com; '\n                         'expires=123; '\n                         'httponly; '\n                         'Max-Age=10; '\n                         'Path=/home; '\n                         'secure; '\n                         'Version=2.0')\n\n    def test_response_cookie__issue_del_cookie(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n    def test_cookie_set_after_del(self):\n        resp = StreamResponse()\n\n        resp.del_cookie('name')\n        resp.set_cookie('name', 'val')\n        # check for Max-Age dropped\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=val')\n\n    def test_set_status_with_reason(self):\n        resp = StreamResponse()\n\n        resp.set_status(200, \"Everithing is fine!\")\n        self.assertEqual(200, resp.status)\n        self.assertEqual(\"Everithing is fine!\", resp.reason)\n\n    def test_start_force_close(self):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n        msg = resp.start(req)\n        self.assertFalse(resp.keep_alive)\n        self.assertTrue(msg.closing)\n\n\nclass TestResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_ctor(self):\n        resp = Response()\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertIsNone(resp.body)\n        self.assertEqual(0, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('CONTENT-LENGTH', '0')]),\n                         resp.headers)\n\n    def test_ctor_with_headers_and_status(self):\n        resp = Response(body=b'body', status=201, headers={'Age': '12'})\n\n        self.assertEqual(201, resp.status)\n        self.assertEqual(b'body', resp.body)\n        self.assertEqual(4, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('AGE', '12'),\n                                                   ('CONTENT-LENGTH', '4')]),\n                         resp.headers)\n\n    def test_ctor_content_type(self):\n        resp = Response(content_type='application/json')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict([('CONTENT-TYPE', 'application/json'),\n                                      ('CONTENT-LENGTH', '0')]),\n            resp.headers)\n\n    def test_ctor_text_body_combined(self):\n        with self.assertRaises(ValueError):\n            Response(body=b'123', text='test text')\n\n    def test_ctor_text(self):\n        resp = Response(text='test text')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict(\n                [('CONTENT-TYPE', 'text/plain; charset=utf-8'),\n                 ('CONTENT-LENGTH', '9')]),\n            resp.headers)\n\n        self.assertEqual(resp.body, b'test text')\n        self.assertEqual(resp.text, 'test text')\n\n    def test_assign_nonbyteish_body(self):\n        resp = Response(body=b'data')\n\n        with self.assertRaises(TypeError):\n            resp.body = 123\n        self.assertEqual(b'data', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_assign_nonstr_text(self):\n        resp = Response(text='test')\n\n        with self.assertRaises(TypeError):\n            resp.text = b'123'\n        self.assertEqual(b'test', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_send_headers_for_empty_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response()\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_render_with_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response(body=b'data')\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 4\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\ndata')\n\n    def test_send_set_cookie_header(self):\n        resp = Response()\n        resp.cookies['name'] = 'value'\n\n        req = self.make_request('GET', '/')\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'SET-COOKIE: name=value\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_set_text_with_content_type(self):\n        resp = Response()\n        resp.content_type = \"text/html\"\n        resp.text = \"text\"\n\n        self.assertEqual(\"text\", resp.text)\n        self.assertEqual(b\"text\", resp.body)\n        self.assertEqual(\"text/html\", resp.content_type)\n\n    def test_set_text_with_charset(self):\n        resp = Response()\n        resp.content_type = 'text/plain'\n        resp.charset = \"KOI8-R\"\n        resp.text = \"текст\"\n\n        self.assertEqual(\"текст\", resp.text)\n        self.assertEqual(\"текст\".encode('koi8-r'), resp.body)\n        self.assertEqual(\"koi8-r\", resp.charset)\n\n    def test_started_when_not_started(self):\n        resp = StreamResponse()\n        self.assertFalse(resp.started)\n\n    def test_started_when_started(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n        self.assertTrue(resp.started)\n\n    def test_drain_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            resp = StreamResponse()\n            with self.assertRaises(RuntimeError):\n                yield from resp.drain()\n\n        self.loop.run_until_complete(go())\n",
            "new_file_content": "import asyncio\nimport unittest\nfrom unittest import mock\nfrom aiohttp.multidict import MultiDict, CaseInsensitiveMultiDict\nfrom aiohttp.web import Request, StreamResponse, Response\nfrom aiohttp.protocol import RawRequestMessage, HttpVersion11\n\n\nclass TestStreamResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_ctor(self):\n        resp = StreamResponse()\n        self.assertEqual(200, resp.status)\n        self.assertIsNone(resp.keep_alive)\n\n    def test_content_length(self):\n        resp = StreamResponse()\n        self.assertIsNone(resp.content_length)\n\n    def test_content_length_setter(self):\n        resp = StreamResponse()\n\n        resp.content_length = 234\n        self.assertEqual(234, resp.content_length)\n\n    def test_drop_content_length_header_on_setting_len_to_None(self):\n        resp = StreamResponse()\n\n        resp.content_length = 1\n        self.assertEqual(\"1\", resp.headers['Content-Length'])\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_set_content_length_to_None_on_non_set(self):\n        resp = StreamResponse()\n\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_setting_content_type(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        self.assertEqual('text/html', resp.headers['content-type'])\n\n    def test_setting_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        self.assertEqual('text/html; charset=koi8-r',\n                         resp.headers['content-type'])\n\n    def test_default_charset(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset_after_setting(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_charset_without_content_type(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.charset = 'koi8-r'\n\n    @mock.patch('aiohttp.web.ResponseImpl')\n    def test_start(self, ResponseImpl):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        self.assertIsNone(resp.keep_alive)\n\n        msg = resp.start(req)\n\n        self.assertTrue(msg.send_headers.called)\n        self.assertIs(msg, resp.start(req))\n\n        self.assertTrue(resp.keep_alive)\n\n        req2 = self.make_request('GET', '/')\n        with self.assertRaises(RuntimeError):\n            resp.start(req2)\n\n    def test_write_non_byteish(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        with self.assertRaises(TypeError):\n            resp.write(123)\n\n    def test_write_before_start(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'data')\n\n    def test_cannot_write_after_eof(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.writer.write.reset_mock()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'next data')\n        self.assertFalse(self.writer.write.called)\n\n    def test_cannot_write_eof_before_headers(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            self.loop.run_until_complete(resp.write_eof())\n\n    def test_cannot_write_eof_twice(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertTrue(self.writer.write.called)\n\n        self.writer.write.reset_mock()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertFalse(self.writer.write.called)\n\n    def test_write_returns_drain(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b'data'))\n\n    def test_write_returns_empty_tuple_on_empty_data(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b''))\n\n    def test_force_close(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.keep_alive)\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n    def test_response_cookies(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.set_cookie('name', 'value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=value')\n        resp.set_cookie('name', 'other_value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=other_value')\n\n        resp.cookies['name'] = 'another_other_value'\n        resp.cookies['name']['max-age'] = 10\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=another_other_value; Max-Age=10')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n        resp.set_cookie('name', 'value', domain='local.host')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Domain=local.host')\n\n    def test_response_cookie_path(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n\n        resp.set_cookie('name', 'value', path='/some/path')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Path=/some/path')\n        resp.set_cookie('name', 'value', expires='123')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; expires=123;'\n                         ' Path=/some/path')\n        resp.set_cookie('name', 'value', domain='example.com',\n                        path='/home', expires='123', max_age='10',\n                        secure=True, httponly=True, version='2.0')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; '\n                         'Domain=example.com; '\n                         'expires=123; '\n                         'httponly; '\n                         'Max-Age=10; '\n                         'Path=/home; '\n                         'secure; '\n                         'Version=2.0')\n\n    def test_response_cookie__issue_del_cookie(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n    def test_cookie_set_after_del(self):\n        resp = StreamResponse()\n\n        resp.del_cookie('name')\n        resp.set_cookie('name', 'val')\n        # check for Max-Age dropped\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=val')\n\n    def test_set_status_with_reason(self):\n        resp = StreamResponse()\n\n        resp.set_status(200, \"Everithing is fine!\")\n        self.assertEqual(200, resp.status)\n        self.assertEqual(\"Everithing is fine!\", resp.reason)\n\n    def test_start_force_close(self):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n        msg = resp.start(req)\n        self.assertFalse(resp.keep_alive)\n        self.assertTrue(msg.closing)\n\n\nclass TestResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_ctor(self):\n        resp = Response()\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertIsNone(resp.body)\n        self.assertEqual(0, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('CONTENT-LENGTH', '0')]),\n                         resp.headers)\n\n    def test_ctor_with_headers_and_status(self):\n        resp = Response(body=b'body', status=201, headers={'Age': '12'})\n\n        self.assertEqual(201, resp.status)\n        self.assertEqual(b'body', resp.body)\n        self.assertEqual(4, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('AGE', '12'),\n                                                   ('CONTENT-LENGTH', '4')]),\n                         resp.headers)\n\n    def test_ctor_content_type(self):\n        resp = Response(content_type='application/json')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict([('CONTENT-TYPE', 'application/json'),\n                                      ('CONTENT-LENGTH', '0')]),\n            resp.headers)\n\n    def test_ctor_text_body_combined(self):\n        with self.assertRaises(ValueError):\n            Response(body=b'123', text='test text')\n\n    def test_ctor_text(self):\n        resp = Response(text='test text')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict(\n                [('CONTENT-TYPE', 'text/plain; charset=utf-8'),\n                 ('CONTENT-LENGTH', '9')]),\n            resp.headers)\n\n        self.assertEqual(resp.body, b'test text')\n        self.assertEqual(resp.text, 'test text')\n\n    def test_assign_nonbyteish_body(self):\n        resp = Response(body=b'data')\n\n        with self.assertRaises(TypeError):\n            resp.body = 123\n        self.assertEqual(b'data', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_assign_nonstr_text(self):\n        resp = Response(text='test')\n\n        with self.assertRaises(TypeError):\n            resp.text = b'123'\n        self.assertEqual(b'test', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_send_headers_for_empty_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response()\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_render_with_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response(body=b'data')\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 4\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\ndata')\n\n    def test_send_set_cookie_header(self):\n        resp = Response()\n        resp.cookies['name'] = 'value'\n\n        req = self.make_request('GET', '/')\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'SET-COOKIE: name=value\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_set_text_with_content_type(self):\n        resp = Response()\n        resp.content_type = \"text/html\"\n        resp.text = \"text\"\n\n        self.assertEqual(\"text\", resp.text)\n        self.assertEqual(b\"text\", resp.body)\n        self.assertEqual(\"text/html\", resp.content_type)\n\n    def test_set_text_with_charset(self):\n        resp = Response()\n        resp.content_type = 'text/plain'\n        resp.charset = \"KOI8-R\"\n        resp.text = \"текст\"\n\n        self.assertEqual(\"текст\", resp.text)\n        self.assertEqual(\"текст\".encode('koi8-r'), resp.body)\n        self.assertEqual(\"koi8-r\", resp.charset)\n\n    def test_started_when_not_started(self):\n        resp = StreamResponse()\n        self.assertFalse(resp.started)\n\n    def test_started_when_started(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n        self.assertTrue(resp.started)\n\n    def test_drain_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            resp = StreamResponse()\n            with self.assertRaises(RuntimeError):\n                yield from resp.drain()\n\n        self.loop.run_until_complete(go())\n",
            "header": {
                "file": {
                    "path": "tests/test_web_response.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "110230bb",
                "new_commit_hash": "9942d335",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_web_response.py"
            },
            "plus_file": {
                "path": "b/tests/test_web_response.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 24,
                            "length": 7
                        },
                        "new_range": {
                            "start": 24,
                            "length": 7
                        },
                        "section": "class TestStreamResponse(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.reader = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        self.writer = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        req = Request(self.app, message, self.payload,",
                                "type": "context"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer, 15)",
                                "type": "deleted"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer)",
                                "type": "added"
                            },
                            {
                                "content": "        return req",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_ctor(self):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_web_response.py",
                            "type": "method",
                            "name": "TestStreamResponse.make_request",
                            "content": "class TestStreamResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_ctor(self):\n        resp = StreamResponse()\n        self.assertEqual(200, resp.status)\n        self.assertIsNone(resp.keep_alive)\n\n    def test_content_length(self):\n        resp = StreamResponse()\n        self.assertIsNone(resp.content_length)\n\n    def test_content_length_setter(self):\n        resp = StreamResponse()\n\n        resp.content_length = 234\n        self.assertEqual(234, resp.content_length)\n\n    def test_drop_content_length_header_on_setting_len_to_None(self):\n        resp = StreamResponse()\n\n        resp.content_length = 1\n        self.assertEqual(\"1\", resp.headers['Content-Length'])\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_set_content_length_to_None_on_non_set(self):\n        resp = StreamResponse()\n\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_setting_content_type(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        self.assertEqual('text/html', resp.headers['content-type'])\n\n    def test_setting_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        self.assertEqual('text/html; charset=koi8-r',\n                         resp.headers['content-type'])\n\n    def test_default_charset(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset_after_setting(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_charset_without_content_type(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.charset = 'koi8-r'\n\n    @mock.patch('aiohttp.web.ResponseImpl')\n    def test_start(self, ResponseImpl):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        self.assertIsNone(resp.keep_alive)\n\n        msg = resp.start(req)\n\n        self.assertTrue(msg.send_headers.called)\n        self.assertIs(msg, resp.start(req))\n\n        self.assertTrue(resp.keep_alive)\n\n        req2 = self.make_request('GET', '/')\n        with self.assertRaises(RuntimeError):\n            resp.start(req2)\n\n    def test_write_non_byteish(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        with self.assertRaises(TypeError):\n            resp.write(123)\n\n    def test_write_before_start(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'data')\n\n    def test_cannot_write_after_eof(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.writer.write.reset_mock()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'next data')\n        self.assertFalse(self.writer.write.called)\n\n    def test_cannot_write_eof_before_headers(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            self.loop.run_until_complete(resp.write_eof())\n\n    def test_cannot_write_eof_twice(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertTrue(self.writer.write.called)\n\n        self.writer.write.reset_mock()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertFalse(self.writer.write.called)\n\n    def test_write_returns_drain(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b'data'))\n\n    def test_write_returns_empty_tuple_on_empty_data(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b''))\n\n    def test_force_close(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.keep_alive)\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n    def test_response_cookies(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.set_cookie('name', 'value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=value')\n        resp.set_cookie('name', 'other_value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=other_value')\n\n        resp.cookies['name'] = 'another_other_value'\n        resp.cookies['name']['max-age'] = 10\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=another_other_value; Max-Age=10')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n        resp.set_cookie('name', 'value', domain='local.host')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Domain=local.host')\n\n    def test_response_cookie_path(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n\n        resp.set_cookie('name', 'value', path='/some/path')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Path=/some/path')\n        resp.set_cookie('name', 'value', expires='123')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; expires=123;'\n                         ' Path=/some/path')\n        resp.set_cookie('name', 'value', domain='example.com',\n                        path='/home', expires='123', max_age='10',\n                        secure=True, httponly=True, version='2.0')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; '\n                         'Domain=example.com; '\n                         'expires=123; '\n                         'httponly; '\n                         'Max-Age=10; '\n                         'Path=/home; '\n                         'secure; '\n                         'Version=2.0')\n\n    def test_response_cookie__issue_del_cookie(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n    def test_cookie_set_after_del(self):\n        resp = StreamResponse()\n\n        resp.del_cookie('name')\n        resp.set_cookie('name', 'val')\n        # check for Max-Age dropped\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=val')\n\n    def test_set_status_with_reason(self):\n        resp = StreamResponse()\n\n        resp.set_status(200, \"Everithing is fine!\")\n        self.assertEqual(200, resp.status)\n        self.assertEqual(\"Everithing is fine!\", resp.reason)\n\n    def test_start_force_close(self):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n        msg = resp.start(req)\n        self.assertFalse(resp.keep_alive)\n        self.assertTrue(msg.closing)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 18,
                            "end_lineno": 28,
                            "parent": {
                                "file_name": "tests/test_web_response.py",
                                "type": "class",
                                "name": "TestStreamResponse",
                                "content": "class TestStreamResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_ctor(self):\n        resp = StreamResponse()\n        self.assertEqual(200, resp.status)\n        self.assertIsNone(resp.keep_alive)\n\n    def test_content_length(self):\n        resp = StreamResponse()\n        self.assertIsNone(resp.content_length)\n\n    def test_content_length_setter(self):\n        resp = StreamResponse()\n\n        resp.content_length = 234\n        self.assertEqual(234, resp.content_length)\n\n    def test_drop_content_length_header_on_setting_len_to_None(self):\n        resp = StreamResponse()\n\n        resp.content_length = 1\n        self.assertEqual(\"1\", resp.headers['Content-Length'])\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_set_content_length_to_None_on_non_set(self):\n        resp = StreamResponse()\n\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_setting_content_type(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        self.assertEqual('text/html', resp.headers['content-type'])\n\n    def test_setting_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        self.assertEqual('text/html; charset=koi8-r',\n                         resp.headers['content-type'])\n\n    def test_default_charset(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset_after_setting(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_charset_without_content_type(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.charset = 'koi8-r'\n\n    @mock.patch('aiohttp.web.ResponseImpl')\n    def test_start(self, ResponseImpl):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        self.assertIsNone(resp.keep_alive)\n\n        msg = resp.start(req)\n\n        self.assertTrue(msg.send_headers.called)\n        self.assertIs(msg, resp.start(req))\n\n        self.assertTrue(resp.keep_alive)\n\n        req2 = self.make_request('GET', '/')\n        with self.assertRaises(RuntimeError):\n            resp.start(req2)\n\n    def test_write_non_byteish(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        with self.assertRaises(TypeError):\n            resp.write(123)\n\n    def test_write_before_start(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'data')\n\n    def test_cannot_write_after_eof(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.writer.write.reset_mock()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'next data')\n        self.assertFalse(self.writer.write.called)\n\n    def test_cannot_write_eof_before_headers(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            self.loop.run_until_complete(resp.write_eof())\n\n    def test_cannot_write_eof_twice(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertTrue(self.writer.write.called)\n\n        self.writer.write.reset_mock()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertFalse(self.writer.write.called)\n\n    def test_write_returns_drain(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b'data'))\n\n    def test_write_returns_empty_tuple_on_empty_data(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b''))\n\n    def test_force_close(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.keep_alive)\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n    def test_response_cookies(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.set_cookie('name', 'value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=value')\n        resp.set_cookie('name', 'other_value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=other_value')\n\n        resp.cookies['name'] = 'another_other_value'\n        resp.cookies['name']['max-age'] = 10\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=another_other_value; Max-Age=10')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n        resp.set_cookie('name', 'value', domain='local.host')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Domain=local.host')\n\n    def test_response_cookie_path(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n\n        resp.set_cookie('name', 'value', path='/some/path')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Path=/some/path')\n        resp.set_cookie('name', 'value', expires='123')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; expires=123;'\n                         ' Path=/some/path')\n        resp.set_cookie('name', 'value', domain='example.com',\n                        path='/home', expires='123', max_age='10',\n                        secure=True, httponly=True, version='2.0')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; '\n                         'Domain=example.com; '\n                         'expires=123; '\n                         'httponly; '\n                         'Max-Age=10; '\n                         'Path=/home; '\n                         'secure; '\n                         'Version=2.0')\n\n    def test_response_cookie__issue_del_cookie(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n    def test_cookie_set_after_del(self):\n        resp = StreamResponse()\n\n        resp.del_cookie('name')\n        resp.set_cookie('name', 'val')\n        # check for Max-Age dropped\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=val')\n\n    def test_set_status_with_reason(self):\n        resp = StreamResponse()\n\n        resp.set_status(200, \"Everithing is fine!\")\n        self.assertEqual(200, resp.status)\n        self.assertEqual(\"Everithing is fine!\", resp.reason)\n\n    def test_start_force_close(self):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n        msg = resp.start(req)\n        self.assertFalse(resp.keep_alive)\n        self.assertTrue(msg.closing)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 9,
                                "end_lineno": 262,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tests/test_web_response.py",
                            "type": "class",
                            "name": "TestStreamResponse",
                            "content": "class TestStreamResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_ctor(self):\n        resp = StreamResponse()\n        self.assertEqual(200, resp.status)\n        self.assertIsNone(resp.keep_alive)\n\n    def test_content_length(self):\n        resp = StreamResponse()\n        self.assertIsNone(resp.content_length)\n\n    def test_content_length_setter(self):\n        resp = StreamResponse()\n\n        resp.content_length = 234\n        self.assertEqual(234, resp.content_length)\n\n    def test_drop_content_length_header_on_setting_len_to_None(self):\n        resp = StreamResponse()\n\n        resp.content_length = 1\n        self.assertEqual(\"1\", resp.headers['Content-Length'])\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_set_content_length_to_None_on_non_set(self):\n        resp = StreamResponse()\n\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_setting_content_type(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        self.assertEqual('text/html', resp.headers['content-type'])\n\n    def test_setting_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        self.assertEqual('text/html; charset=koi8-r',\n                         resp.headers['content-type'])\n\n    def test_default_charset(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset_after_setting(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_charset_without_content_type(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.charset = 'koi8-r'\n\n    @mock.patch('aiohttp.web.ResponseImpl')\n    def test_start(self, ResponseImpl):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        self.assertIsNone(resp.keep_alive)\n\n        msg = resp.start(req)\n\n        self.assertTrue(msg.send_headers.called)\n        self.assertIs(msg, resp.start(req))\n\n        self.assertTrue(resp.keep_alive)\n\n        req2 = self.make_request('GET', '/')\n        with self.assertRaises(RuntimeError):\n            resp.start(req2)\n\n    def test_write_non_byteish(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        with self.assertRaises(TypeError):\n            resp.write(123)\n\n    def test_write_before_start(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'data')\n\n    def test_cannot_write_after_eof(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.writer.write.reset_mock()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'next data')\n        self.assertFalse(self.writer.write.called)\n\n    def test_cannot_write_eof_before_headers(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            self.loop.run_until_complete(resp.write_eof())\n\n    def test_cannot_write_eof_twice(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertTrue(self.writer.write.called)\n\n        self.writer.write.reset_mock()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertFalse(self.writer.write.called)\n\n    def test_write_returns_drain(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b'data'))\n\n    def test_write_returns_empty_tuple_on_empty_data(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b''))\n\n    def test_force_close(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.keep_alive)\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n    def test_response_cookies(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.set_cookie('name', 'value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=value')\n        resp.set_cookie('name', 'other_value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=other_value')\n\n        resp.cookies['name'] = 'another_other_value'\n        resp.cookies['name']['max-age'] = 10\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=another_other_value; Max-Age=10')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n        resp.set_cookie('name', 'value', domain='local.host')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Domain=local.host')\n\n    def test_response_cookie_path(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n\n        resp.set_cookie('name', 'value', path='/some/path')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Path=/some/path')\n        resp.set_cookie('name', 'value', expires='123')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; expires=123;'\n                         ' Path=/some/path')\n        resp.set_cookie('name', 'value', domain='example.com',\n                        path='/home', expires='123', max_age='10',\n                        secure=True, httponly=True, version='2.0')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; '\n                         'Domain=example.com; '\n                         'expires=123; '\n                         'httponly; '\n                         'Max-Age=10; '\n                         'Path=/home; '\n                         'secure; '\n                         'Version=2.0')\n\n    def test_response_cookie__issue_del_cookie(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n    def test_cookie_set_after_del(self):\n        resp = StreamResponse()\n\n        resp.del_cookie('name')\n        resp.set_cookie('name', 'val')\n        # check for Max-Age dropped\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=val')\n\n    def test_set_status_with_reason(self):\n        resp = StreamResponse()\n\n        resp.set_status(200, \"Everithing is fine!\")\n        self.assertEqual(200, resp.status)\n        self.assertEqual(\"Everithing is fine!\", resp.reason)\n\n    def test_start_force_close(self):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n        msg = resp.start(req)\n        self.assertFalse(resp.keep_alive)\n        self.assertTrue(msg.closing)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 9,
                            "end_lineno": 262,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 280,
                            "length": 7
                        },
                        "new_range": {
                            "start": 280,
                            "length": 7
                        },
                        "section": "class TestResponse(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.reader = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        self.writer = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        req = Request(self.app, message, self.payload,",
                                "type": "context"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer, 15)",
                                "type": "deleted"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer)",
                                "type": "added"
                            },
                            {
                                "content": "        return req",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_ctor(self):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_web_response.py",
                            "type": "class",
                            "name": "TestResponse",
                            "content": "class TestResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_ctor(self):\n        resp = Response()\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertIsNone(resp.body)\n        self.assertEqual(0, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('CONTENT-LENGTH', '0')]),\n                         resp.headers)\n\n    def test_ctor_with_headers_and_status(self):\n        resp = Response(body=b'body', status=201, headers={'Age': '12'})\n\n        self.assertEqual(201, resp.status)\n        self.assertEqual(b'body', resp.body)\n        self.assertEqual(4, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('AGE', '12'),\n                                                   ('CONTENT-LENGTH', '4')]),\n                         resp.headers)\n\n    def test_ctor_content_type(self):\n        resp = Response(content_type='application/json')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict([('CONTENT-TYPE', 'application/json'),\n                                      ('CONTENT-LENGTH', '0')]),\n            resp.headers)\n\n    def test_ctor_text_body_combined(self):\n        with self.assertRaises(ValueError):\n            Response(body=b'123', text='test text')\n\n    def test_ctor_text(self):\n        resp = Response(text='test text')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict(\n                [('CONTENT-TYPE', 'text/plain; charset=utf-8'),\n                 ('CONTENT-LENGTH', '9')]),\n            resp.headers)\n\n        self.assertEqual(resp.body, b'test text')\n        self.assertEqual(resp.text, 'test text')\n\n    def test_assign_nonbyteish_body(self):\n        resp = Response(body=b'data')\n\n        with self.assertRaises(TypeError):\n            resp.body = 123\n        self.assertEqual(b'data', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_assign_nonstr_text(self):\n        resp = Response(text='test')\n\n        with self.assertRaises(TypeError):\n            resp.text = b'123'\n        self.assertEqual(b'test', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_send_headers_for_empty_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response()\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_render_with_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response(body=b'data')\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 4\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\ndata')\n\n    def test_send_set_cookie_header(self):\n        resp = Response()\n        resp.cookies['name'] = 'value'\n\n        req = self.make_request('GET', '/')\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'SET-COOKIE: name=value\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_set_text_with_content_type(self):\n        resp = Response()\n        resp.content_type = \"text/html\"\n        resp.text = \"text\"\n\n        self.assertEqual(\"text\", resp.text)\n        self.assertEqual(b\"text\", resp.body)\n        self.assertEqual(\"text/html\", resp.content_type)\n\n    def test_set_text_with_charset(self):\n        resp = Response()\n        resp.content_type = 'text/plain'\n        resp.charset = \"KOI8-R\"\n        resp.text = \"текст\"\n\n        self.assertEqual(\"текст\", resp.text)\n        self.assertEqual(\"текст\".encode('koi8-r'), resp.body)\n        self.assertEqual(\"koi8-r\", resp.charset)\n\n    def test_started_when_not_started(self):\n        resp = StreamResponse()\n        self.assertFalse(resp.started)\n\n    def test_started_when_started(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n        self.assertTrue(resp.started)\n\n    def test_drain_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            resp = StreamResponse()\n            with self.assertRaises(RuntimeError):\n                yield from resp.drain()\n\n        self.loop.run_until_complete(go())",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 265,
                            "end_lineno": 448,
                            "parent": null
                        },
                        {
                            "file_name": "tests/test_web_response.py",
                            "type": "method",
                            "name": "TestResponse.make_request",
                            "content": "class TestResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_ctor(self):\n        resp = Response()\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertIsNone(resp.body)\n        self.assertEqual(0, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('CONTENT-LENGTH', '0')]),\n                         resp.headers)\n\n    def test_ctor_with_headers_and_status(self):\n        resp = Response(body=b'body', status=201, headers={'Age': '12'})\n\n        self.assertEqual(201, resp.status)\n        self.assertEqual(b'body', resp.body)\n        self.assertEqual(4, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('AGE', '12'),\n                                                   ('CONTENT-LENGTH', '4')]),\n                         resp.headers)\n\n    def test_ctor_content_type(self):\n        resp = Response(content_type='application/json')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict([('CONTENT-TYPE', 'application/json'),\n                                      ('CONTENT-LENGTH', '0')]),\n            resp.headers)\n\n    def test_ctor_text_body_combined(self):\n        with self.assertRaises(ValueError):\n            Response(body=b'123', text='test text')\n\n    def test_ctor_text(self):\n        resp = Response(text='test text')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict(\n                [('CONTENT-TYPE', 'text/plain; charset=utf-8'),\n                 ('CONTENT-LENGTH', '9')]),\n            resp.headers)\n\n        self.assertEqual(resp.body, b'test text')\n        self.assertEqual(resp.text, 'test text')\n\n    def test_assign_nonbyteish_body(self):\n        resp = Response(body=b'data')\n\n        with self.assertRaises(TypeError):\n            resp.body = 123\n        self.assertEqual(b'data', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_assign_nonstr_text(self):\n        resp = Response(text='test')\n\n        with self.assertRaises(TypeError):\n            resp.text = b'123'\n        self.assertEqual(b'test', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_send_headers_for_empty_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response()\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_render_with_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response(body=b'data')\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 4\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\ndata')\n\n    def test_send_set_cookie_header(self):\n        resp = Response()\n        resp.cookies['name'] = 'value'\n\n        req = self.make_request('GET', '/')\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'SET-COOKIE: name=value\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_set_text_with_content_type(self):\n        resp = Response()\n        resp.content_type = \"text/html\"\n        resp.text = \"text\"\n\n        self.assertEqual(\"text\", resp.text)\n        self.assertEqual(b\"text\", resp.body)\n        self.assertEqual(\"text/html\", resp.content_type)\n\n    def test_set_text_with_charset(self):\n        resp = Response()\n        resp.content_type = 'text/plain'\n        resp.charset = \"KOI8-R\"\n        resp.text = \"текст\"\n\n        self.assertEqual(\"текст\", resp.text)\n        self.assertEqual(\"текст\".encode('koi8-r'), resp.body)\n        self.assertEqual(\"koi8-r\", resp.charset)\n\n    def test_started_when_not_started(self):\n        resp = StreamResponse()\n        self.assertFalse(resp.started)\n\n    def test_started_when_started(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n        self.assertTrue(resp.started)\n\n    def test_drain_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            resp = StreamResponse()\n            with self.assertRaises(RuntimeError):\n                yield from resp.drain()\n\n        self.loop.run_until_complete(go())",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 274,
                            "end_lineno": 284,
                            "parent": {
                                "file_name": "tests/test_web_response.py",
                                "type": "class",
                                "name": "TestResponse",
                                "content": "class TestResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_ctor(self):\n        resp = Response()\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertIsNone(resp.body)\n        self.assertEqual(0, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('CONTENT-LENGTH', '0')]),\n                         resp.headers)\n\n    def test_ctor_with_headers_and_status(self):\n        resp = Response(body=b'body', status=201, headers={'Age': '12'})\n\n        self.assertEqual(201, resp.status)\n        self.assertEqual(b'body', resp.body)\n        self.assertEqual(4, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('AGE', '12'),\n                                                   ('CONTENT-LENGTH', '4')]),\n                         resp.headers)\n\n    def test_ctor_content_type(self):\n        resp = Response(content_type='application/json')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict([('CONTENT-TYPE', 'application/json'),\n                                      ('CONTENT-LENGTH', '0')]),\n            resp.headers)\n\n    def test_ctor_text_body_combined(self):\n        with self.assertRaises(ValueError):\n            Response(body=b'123', text='test text')\n\n    def test_ctor_text(self):\n        resp = Response(text='test text')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict(\n                [('CONTENT-TYPE', 'text/plain; charset=utf-8'),\n                 ('CONTENT-LENGTH', '9')]),\n            resp.headers)\n\n        self.assertEqual(resp.body, b'test text')\n        self.assertEqual(resp.text, 'test text')\n\n    def test_assign_nonbyteish_body(self):\n        resp = Response(body=b'data')\n\n        with self.assertRaises(TypeError):\n            resp.body = 123\n        self.assertEqual(b'data', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_assign_nonstr_text(self):\n        resp = Response(text='test')\n\n        with self.assertRaises(TypeError):\n            resp.text = b'123'\n        self.assertEqual(b'test', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_send_headers_for_empty_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response()\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_render_with_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response(body=b'data')\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 4\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\ndata')\n\n    def test_send_set_cookie_header(self):\n        resp = Response()\n        resp.cookies['name'] = 'value'\n\n        req = self.make_request('GET', '/')\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'SET-COOKIE: name=value\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_set_text_with_content_type(self):\n        resp = Response()\n        resp.content_type = \"text/html\"\n        resp.text = \"text\"\n\n        self.assertEqual(\"text\", resp.text)\n        self.assertEqual(b\"text\", resp.body)\n        self.assertEqual(\"text/html\", resp.content_type)\n\n    def test_set_text_with_charset(self):\n        resp = Response()\n        resp.content_type = 'text/plain'\n        resp.charset = \"KOI8-R\"\n        resp.text = \"текст\"\n\n        self.assertEqual(\"текст\", resp.text)\n        self.assertEqual(\"текст\".encode('koi8-r'), resp.body)\n        self.assertEqual(\"koi8-r\", resp.charset)\n\n    def test_started_when_not_started(self):\n        resp = StreamResponse()\n        self.assertFalse(resp.started)\n\n    def test_started_when_started(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n        self.assertTrue(resp.started)\n\n    def test_drain_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            resp = StreamResponse()\n            with self.assertRaises(RuntimeError):\n                yield from resp.drain()\n\n        self.loop.run_until_complete(go())",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 265,
                                "end_lineno": 448,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport unittest\nfrom unittest import mock\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.web import (Request, WebSocketResponse,\n                         WebSocketDisconnectedError,\n                         HTTPMethodNotAllowed, HTTPBadRequest)\nfrom aiohttp.protocol import RawRequestMessage, HttpVersion11\n\n\nclass TestWebWebSocket(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        self.loop.close()\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_nonstarted_ping(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_nonstarted_send_str(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_nonstarted_send_bytes(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_nonstarted_close(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.close()\n\n    def test_nonstarted_receive(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.receive()\n\n        self.loop.run_until_complete(go())\n\n    def test_send_str_nonstring(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_str(b'bytes')\n\n    def test_send_bytes_nonbytes(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_bytes('string')\n\n    def test_write(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.write(b'data')\n\n    def test_nested_exception(self):\n\n        @asyncio.coroutine\n        def a():\n            raise WebSocketDisconnectedError()\n\n        @asyncio.coroutine\n        def b():\n            yield from a()\n\n        @asyncio.coroutine\n        def c():\n            yield from b()\n\n        with self.assertRaises(WebSocketDisconnectedError):\n            self.loop.run_until_complete(c())\n\n    def test_can_start_ok(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse(protocols=('chat',))\n        self.assertEqual((True, 'chat'), ws.can_start(req))\n\n    def test_can_start_unknown_protocol(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((True, None), ws.can_start(req))\n\n    def test_can_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_started(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaisesRegex(RuntimeError, 'Already started'):\n            ws.can_start(req)\n\n    def test_closing_after_ctor(self):\n        ws = WebSocketResponse()\n        self.assertFalse(ws.closing)\n\n    def test_send_str_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_send_bytes_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_ping_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_double_close(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        writer = mock.Mock()\n        ws._writer = writer\n        ws.close(code=1, message='message1')\n        self.assertTrue(ws.closing)\n        with self.assertRaisesRegex(RuntimeError, 'Already closing'):\n            ws.close(code=2, message='message2')\n        self.assertTrue(ws.closing)\n        writer.close.assert_called_once_with(1, 'message1')\n\n    def test_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPMethodNotAllowed):\n            ws.start(req)\n\n    def test_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPBadRequest):\n            ws.start(req)\n\n    def test_wait_closed_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.wait_closed()\n\n        self.loop.run_until_complete(go())\n",
            "new_file_content": "import asyncio\nimport unittest\nfrom unittest import mock\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.web import (Request, WebSocketResponse,\n                         WebSocketDisconnectedError,\n                         HTTPMethodNotAllowed, HTTPBadRequest)\nfrom aiohttp.protocol import RawRequestMessage, HttpVersion11\n\n\nclass TestWebWebSocket(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        self.loop.close()\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_nonstarted_ping(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_nonstarted_send_str(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_nonstarted_send_bytes(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_nonstarted_close(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.close()\n\n    def test_nonstarted_receive(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.receive()\n\n        self.loop.run_until_complete(go())\n\n    def test_send_str_nonstring(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_str(b'bytes')\n\n    def test_send_bytes_nonbytes(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_bytes('string')\n\n    def test_write(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.write(b'data')\n\n    def test_nested_exception(self):\n\n        @asyncio.coroutine\n        def a():\n            raise WebSocketDisconnectedError()\n\n        @asyncio.coroutine\n        def b():\n            yield from a()\n\n        @asyncio.coroutine\n        def c():\n            yield from b()\n\n        with self.assertRaises(WebSocketDisconnectedError):\n            self.loop.run_until_complete(c())\n\n    def test_can_start_ok(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse(protocols=('chat',))\n        self.assertEqual((True, 'chat'), ws.can_start(req))\n\n    def test_can_start_unknown_protocol(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((True, None), ws.can_start(req))\n\n    def test_can_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_started(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaisesRegex(RuntimeError, 'Already started'):\n            ws.can_start(req)\n\n    def test_closing_after_ctor(self):\n        ws = WebSocketResponse()\n        self.assertFalse(ws.closing)\n\n    def test_send_str_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_send_bytes_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_ping_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_double_close(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        writer = mock.Mock()\n        ws._writer = writer\n        ws.close(code=1, message='message1')\n        self.assertTrue(ws.closing)\n        with self.assertRaisesRegex(RuntimeError, 'Already closing'):\n            ws.close(code=2, message='message2')\n        self.assertTrue(ws.closing)\n        writer.close.assert_called_once_with(1, 'message1')\n\n    def test_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPMethodNotAllowed):\n            ws.start(req)\n\n    def test_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPBadRequest):\n            ws.start(req)\n\n    def test_wait_closed_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.wait_closed()\n\n        self.loop.run_until_complete(go())\n",
            "header": {
                "file": {
                    "path": "tests/test_web_websocket.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "44f1382e",
                "new_commit_hash": "0c2fa5e6",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_web_websocket.py"
            },
            "plus_file": {
                "path": "b/tests/test_web_websocket.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 35,
                            "length": 7
                        },
                        "new_range": {
                            "start": 35,
                            "length": 7
                        },
                        "section": "class TestWebWebSocket(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.reader = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        self.writer = mock.Mock()",
                                "type": "context"
                            },
                            {
                                "content": "        req = Request(self.app, message, self.payload,",
                                "type": "context"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer, 15)",
                                "type": "deleted"
                            },
                            {
                                "content": "                      self.transport, self.reader, self.writer)",
                                "type": "added"
                            },
                            {
                                "content": "        return req",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_nonstarted_ping(self):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_web_websocket.py",
                            "type": "method",
                            "name": "TestWebWebSocket.make_request",
                            "content": "class TestWebWebSocket(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        self.loop.close()\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_nonstarted_ping(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_nonstarted_send_str(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_nonstarted_send_bytes(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_nonstarted_close(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.close()\n\n    def test_nonstarted_receive(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.receive()\n\n        self.loop.run_until_complete(go())\n\n    def test_send_str_nonstring(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_str(b'bytes')\n\n    def test_send_bytes_nonbytes(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_bytes('string')\n\n    def test_write(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.write(b'data')\n\n    def test_nested_exception(self):\n\n        @asyncio.coroutine\n        def a():\n            raise WebSocketDisconnectedError()\n\n        @asyncio.coroutine\n        def b():\n            yield from a()\n\n        @asyncio.coroutine\n        def c():\n            yield from b()\n\n        with self.assertRaises(WebSocketDisconnectedError):\n            self.loop.run_until_complete(c())\n\n    def test_can_start_ok(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse(protocols=('chat',))\n        self.assertEqual((True, 'chat'), ws.can_start(req))\n\n    def test_can_start_unknown_protocol(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((True, None), ws.can_start(req))\n\n    def test_can_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_started(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaisesRegex(RuntimeError, 'Already started'):\n            ws.can_start(req)\n\n    def test_closing_after_ctor(self):\n        ws = WebSocketResponse()\n        self.assertFalse(ws.closing)\n\n    def test_send_str_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_send_bytes_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_ping_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_double_close(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        writer = mock.Mock()\n        ws._writer = writer\n        ws.close(code=1, message='message1')\n        self.assertTrue(ws.closing)\n        with self.assertRaisesRegex(RuntimeError, 'Already closing'):\n            ws.close(code=2, message='message2')\n        self.assertTrue(ws.closing)\n        writer.close.assert_called_once_with(1, 'message1')\n\n    def test_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPMethodNotAllowed):\n            ws.start(req)\n\n    def test_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPBadRequest):\n            ws.start(req)\n\n    def test_wait_closed_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.wait_closed()\n\n        self.loop.run_until_complete(go())",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 20,
                            "end_lineno": 39,
                            "parent": {
                                "file_name": "tests/test_web_websocket.py",
                                "type": "class",
                                "name": "TestWebWebSocket",
                                "content": "class TestWebWebSocket(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        self.loop.close()\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_nonstarted_ping(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_nonstarted_send_str(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_nonstarted_send_bytes(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_nonstarted_close(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.close()\n\n    def test_nonstarted_receive(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.receive()\n\n        self.loop.run_until_complete(go())\n\n    def test_send_str_nonstring(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_str(b'bytes')\n\n    def test_send_bytes_nonbytes(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_bytes('string')\n\n    def test_write(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.write(b'data')\n\n    def test_nested_exception(self):\n\n        @asyncio.coroutine\n        def a():\n            raise WebSocketDisconnectedError()\n\n        @asyncio.coroutine\n        def b():\n            yield from a()\n\n        @asyncio.coroutine\n        def c():\n            yield from b()\n\n        with self.assertRaises(WebSocketDisconnectedError):\n            self.loop.run_until_complete(c())\n\n    def test_can_start_ok(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse(protocols=('chat',))\n        self.assertEqual((True, 'chat'), ws.can_start(req))\n\n    def test_can_start_unknown_protocol(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((True, None), ws.can_start(req))\n\n    def test_can_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_started(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaisesRegex(RuntimeError, 'Already started'):\n            ws.can_start(req)\n\n    def test_closing_after_ctor(self):\n        ws = WebSocketResponse()\n        self.assertFalse(ws.closing)\n\n    def test_send_str_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_send_bytes_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_ping_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_double_close(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        writer = mock.Mock()\n        ws._writer = writer\n        ws.close(code=1, message='message1')\n        self.assertTrue(ws.closing)\n        with self.assertRaisesRegex(RuntimeError, 'Already closing'):\n            ws.close(code=2, message='message2')\n        self.assertTrue(ws.closing)\n        writer.close.assert_called_once_with(1, 'message1')\n\n    def test_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPMethodNotAllowed):\n            ws.start(req)\n\n    def test_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPBadRequest):\n            ws.start(req)\n\n    def test_wait_closed_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.wait_closed()\n\n        self.loop.run_until_complete(go())",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 11,
                                "end_lineno": 195,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tests/test_web_websocket.py",
                            "type": "class",
                            "name": "TestWebWebSocket",
                            "content": "class TestWebWebSocket(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        self.loop.close()\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer, 15)\n        return req\n\n    def test_nonstarted_ping(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_nonstarted_send_str(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_nonstarted_send_bytes(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_nonstarted_close(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.close()\n\n    def test_nonstarted_receive(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.receive()\n\n        self.loop.run_until_complete(go())\n\n    def test_send_str_nonstring(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_str(b'bytes')\n\n    def test_send_bytes_nonbytes(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_bytes('string')\n\n    def test_write(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.write(b'data')\n\n    def test_nested_exception(self):\n\n        @asyncio.coroutine\n        def a():\n            raise WebSocketDisconnectedError()\n\n        @asyncio.coroutine\n        def b():\n            yield from a()\n\n        @asyncio.coroutine\n        def c():\n            yield from b()\n\n        with self.assertRaises(WebSocketDisconnectedError):\n            self.loop.run_until_complete(c())\n\n    def test_can_start_ok(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse(protocols=('chat',))\n        self.assertEqual((True, 'chat'), ws.can_start(req))\n\n    def test_can_start_unknown_protocol(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((True, None), ws.can_start(req))\n\n    def test_can_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_started(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaisesRegex(RuntimeError, 'Already started'):\n            ws.can_start(req)\n\n    def test_closing_after_ctor(self):\n        ws = WebSocketResponse()\n        self.assertFalse(ws.closing)\n\n    def test_send_str_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_send_bytes_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_ping_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_double_close(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        writer = mock.Mock()\n        ws._writer = writer\n        ws.close(code=1, message='message1')\n        self.assertTrue(ws.closing)\n        with self.assertRaisesRegex(RuntimeError, 'Already closing'):\n            ws.close(code=2, message='message2')\n        self.assertTrue(ws.closing)\n        writer.close.assert_called_once_with(1, 'message1')\n\n    def test_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPMethodNotAllowed):\n            ws.start(req)\n\n    def test_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPBadRequest):\n            ws.start(req)\n\n    def test_wait_closed_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.wait_closed()\n\n        self.loop.run_until_complete(go())",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 11,
                            "end_lineno": 195,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "d2fbdefd269d4d79e54c703d636269bf52505bfb^",
    "new_commit_hash": "d2fbdefd269d4d79e54c703d636269bf52505bfb",
    "commit_message": "Merge branch 'master' of github.com:KeepSafe/aiohttp",
    "commit_date": "2015-01-04T21:53:46+02:00",
    "metadata": {}
}
{
    "repo_name": "aiohttp",
    "new_commit_hash": "d2fbdefd269d4d79e54c703d636269bf52505bfb",
    "test_file_codes": [
        "import asyncio\nimport unittest\nfrom unittest import mock\nfrom aiohttp.multidict import MultiDict, CaseInsensitiveMultiDict\nfrom aiohttp.web import Request, StreamResponse, Response\nfrom aiohttp.protocol import RawRequestMessage, HttpVersion11\n\n\nclass TestStreamResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_ctor(self):\n        resp = StreamResponse()\n        self.assertEqual(200, resp.status)\n        self.assertIsNone(resp.keep_alive)\n\n    def test_content_length(self):\n        resp = StreamResponse()\n        self.assertIsNone(resp.content_length)\n\n    def test_content_length_setter(self):\n        resp = StreamResponse()\n\n        resp.content_length = 234\n        self.assertEqual(234, resp.content_length)\n\n    def test_drop_content_length_header_on_setting_len_to_None(self):\n        resp = StreamResponse()\n\n        resp.content_length = 1\n        self.assertEqual(\"1\", resp.headers['Content-Length'])\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_set_content_length_to_None_on_non_set(self):\n        resp = StreamResponse()\n\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n        resp.content_length = None\n        self.assertNotIn('Content-Length', resp.headers)\n\n    def test_setting_content_type(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        self.assertEqual('text/html', resp.headers['content-type'])\n\n    def test_setting_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        self.assertEqual('text/html; charset=koi8-r',\n                         resp.headers['content-type'])\n\n    def test_default_charset(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_reset_charset_after_setting(self):\n        resp = StreamResponse()\n\n        resp.content_type = 'text/html'\n        resp.charset = 'koi8-r'\n        resp.charset = None\n        self.assertIsNone(resp.charset)\n\n    def test_charset_without_content_type(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.charset = 'koi8-r'\n\n    @mock.patch('aiohttp.web.ResponseImpl')\n    def test_start(self, ResponseImpl):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        self.assertIsNone(resp.keep_alive)\n\n        msg = resp.start(req)\n\n        self.assertTrue(msg.send_headers.called)\n        self.assertIs(msg, resp.start(req))\n\n        self.assertTrue(resp.keep_alive)\n\n        req2 = self.make_request('GET', '/')\n        with self.assertRaises(RuntimeError):\n            resp.start(req2)\n\n    def test_write_non_byteish(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        with self.assertRaises(TypeError):\n            resp.write(123)\n\n    def test_write_before_start(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'data')\n\n    def test_cannot_write_after_eof(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.writer.write.reset_mock()\n\n        with self.assertRaises(RuntimeError):\n            resp.write(b'next data')\n        self.assertFalse(self.writer.write.called)\n\n    def test_cannot_write_eof_before_headers(self):\n        resp = StreamResponse()\n\n        with self.assertRaises(RuntimeError):\n            self.loop.run_until_complete(resp.write_eof())\n\n    def test_cannot_write_eof_twice(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        resp.write(b'data')\n        self.writer.drain.return_value = ()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertTrue(self.writer.write.called)\n\n        self.writer.write.reset_mock()\n        self.loop.run_until_complete(resp.write_eof())\n        self.assertFalse(self.writer.write.called)\n\n    def test_write_returns_drain(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b'data'))\n\n    def test_write_returns_empty_tuple_on_empty_data(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n\n        self.assertEqual((), resp.write(b''))\n\n    def test_force_close(self):\n        resp = StreamResponse()\n\n        self.assertIsNone(resp.keep_alive)\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n    def test_response_cookies(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.set_cookie('name', 'value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=value')\n        resp.set_cookie('name', 'other_value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=other_value')\n\n        resp.cookies['name'] = 'another_other_value'\n        resp.cookies['name']['max-age'] = 10\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=another_other_value; Max-Age=10')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n        resp.set_cookie('name', 'value', domain='local.host')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Domain=local.host')\n\n    def test_response_cookie_path(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n\n        resp.set_cookie('name', 'value', path='/some/path')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Path=/some/path')\n        resp.set_cookie('name', 'value', expires='123')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; expires=123;'\n                         ' Path=/some/path')\n        resp.set_cookie('name', 'value', domain='example.com',\n                        path='/home', expires='123', max_age='10',\n                        secure=True, httponly=True, version='2.0')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; '\n                         'Domain=example.com; '\n                         'expires=123; '\n                         'httponly; '\n                         'Max-Age=10; '\n                         'Path=/home; '\n                         'secure; '\n                         'Version=2.0')\n\n    def test_response_cookie__issue_del_cookie(self):\n        resp = StreamResponse()\n\n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n\n        resp.del_cookie('name')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\n\n    def test_cookie_set_after_del(self):\n        resp = StreamResponse()\n\n        resp.del_cookie('name')\n        resp.set_cookie('name', 'val')\n        # check for Max-Age dropped\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=val')\n\n    def test_set_status_with_reason(self):\n        resp = StreamResponse()\n\n        resp.set_status(200, \"Everithing is fine!\")\n        self.assertEqual(200, resp.status)\n        self.assertEqual(\"Everithing is fine!\", resp.reason)\n\n    def test_start_force_close(self):\n        req = self.make_request('GET', '/')\n        resp = StreamResponse()\n        resp.force_close()\n        self.assertFalse(resp.keep_alive)\n\n        msg = resp.start(req)\n        self.assertFalse(resp.keep_alive)\n        self.assertTrue(msg.closing)\n\n\nclass TestResponse(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_ctor(self):\n        resp = Response()\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertIsNone(resp.body)\n        self.assertEqual(0, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('CONTENT-LENGTH', '0')]),\n                         resp.headers)\n\n    def test_ctor_with_headers_and_status(self):\n        resp = Response(body=b'body', status=201, headers={'Age': '12'})\n\n        self.assertEqual(201, resp.status)\n        self.assertEqual(b'body', resp.body)\n        self.assertEqual(4, resp.content_length)\n        self.assertEqual(CaseInsensitiveMultiDict([('AGE', '12'),\n                                                   ('CONTENT-LENGTH', '4')]),\n                         resp.headers)\n\n    def test_ctor_content_type(self):\n        resp = Response(content_type='application/json')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict([('CONTENT-TYPE', 'application/json'),\n                                      ('CONTENT-LENGTH', '0')]),\n            resp.headers)\n\n    def test_ctor_text_body_combined(self):\n        with self.assertRaises(ValueError):\n            Response(body=b'123', text='test text')\n\n    def test_ctor_text(self):\n        resp = Response(text='test text')\n\n        self.assertEqual(200, resp.status)\n        self.assertEqual('OK', resp.reason)\n        self.assertEqual(\n            CaseInsensitiveMultiDict(\n                [('CONTENT-TYPE', 'text/plain; charset=utf-8'),\n                 ('CONTENT-LENGTH', '9')]),\n            resp.headers)\n\n        self.assertEqual(resp.body, b'test text')\n        self.assertEqual(resp.text, 'test text')\n\n    def test_assign_nonbyteish_body(self):\n        resp = Response(body=b'data')\n\n        with self.assertRaises(TypeError):\n            resp.body = 123\n        self.assertEqual(b'data', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_assign_nonstr_text(self):\n        resp = Response(text='test')\n\n        with self.assertRaises(TypeError):\n            resp.text = b'123'\n        self.assertEqual(b'test', resp.body)\n        self.assertEqual(4, resp.content_length)\n\n    def test_send_headers_for_empty_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response()\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_render_with_body(self):\n        req = self.make_request('GET', '/')\n        resp = Response(body=b'data')\n\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 4\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\ndata')\n\n    def test_send_set_cookie_header(self):\n        resp = Response()\n        resp.cookies['name'] = 'value'\n\n        req = self.make_request('GET', '/')\n        self.writer.drain.return_value = ()\n        buf = b''\n\n        def append(data):\n            nonlocal buf\n            buf += data\n\n        self.writer.write.side_effect = append\n\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = buf.decode('utf8')\n        self.assertRegex(txt, 'HTTP/1.1 200 OK\\r\\nCONTENT-LENGTH: 0\\r\\n'\n                         'SET-COOKIE: name=value\\r\\n'\n                         'CONNECTION: keep-alive\\r\\n'\n                         'DATE: .+\\r\\nSERVER: .+\\r\\n\\r\\n')\n\n    def test_set_text_with_content_type(self):\n        resp = Response()\n        resp.content_type = \"text/html\"\n        resp.text = \"text\"\n\n        self.assertEqual(\"text\", resp.text)\n        self.assertEqual(b\"text\", resp.body)\n        self.assertEqual(\"text/html\", resp.content_type)\n\n    def test_set_text_with_charset(self):\n        resp = Response()\n        resp.content_type = 'text/plain'\n        resp.charset = \"KOI8-R\"\n        resp.text = \"текст\"\n\n        self.assertEqual(\"текст\", resp.text)\n        self.assertEqual(\"текст\".encode('koi8-r'), resp.body)\n        self.assertEqual(\"koi8-r\", resp.charset)\n\n    def test_started_when_not_started(self):\n        resp = StreamResponse()\n        self.assertFalse(resp.started)\n\n    def test_started_when_started(self):\n        resp = StreamResponse()\n        resp.start(self.make_request('GET', '/'))\n        self.assertTrue(resp.started)\n\n    def test_drain_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            resp = StreamResponse()\n            with self.assertRaises(RuntimeError):\n                yield from resp.drain()\n\n        self.loop.run_until_complete(go())\n",
        "import asyncio\nimport os\nimport unittest\nfrom unittest import mock\nimport aiohttp.web\nfrom aiohttp.web import (UrlDispatcher, Request, Response,\n                         HTTPMethodNotAllowed, HTTPNotFound)\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.protocol import HttpVersion, RawRequestMessage\n\n\nclass TestUrlDispatcher(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.router = UrlDispatcher()\n\n    def tearDown(self):\n        self.loop.close()\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_add_route_root(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/', handler)\n        req = self.make_request('GET', '/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_route_simple(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path', handler)\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual(0, len(info))\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_matchdict(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/{to}', handler)\n        req = self.make_request('GET', '/handler/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 'tail'}, info)\n        self.assertIs(handler, info.handler)\n        self.assertIsNone(info.route.name)\n\n    def test_add_with_name(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/handler/to/path', handler,\n                              name='name')\n        req = self.make_request('GET', '/handler/to/path')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual('name', info.route.name)\n\n    def test_add_with_tailing_slash(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path/', handler)\n        req = self.make_request('GET', '/handler/to/path/')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler, info.handler)\n\n    def test_add_invalid_path(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('GET', '/{/', lambda req: None)\n\n    def test_add_url_invalid1(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id', lambda: None)\n\n    def test_add_url_invalid2(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}}', lambda: None)\n\n    def test_add_url_invalid3(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id{}', lambda: None)\n\n    def test_add_url_invalid4(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post/{id\"}', lambda: None)\n\n    def test_add_url_invalid5(self):\n        with self.assertRaises(ValueError):\n            self.router.add_route('post', '/post\"{id}', lambda: None)\n\n    def test_add_url_escaping(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/+$', handler)\n\n        req = self.make_request('GET', '/+$')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertIs(handler, info.handler)\n\n    def test_match_second_result_in_table(self):\n        handler1 = asyncio.coroutine(lambda req: Response(req))\n        handler2 = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/h1', handler1)\n        self.router.add_route('POST', '/h2', handler2)\n        req = self.make_request('POST', '/h2')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({}, info)\n        self.assertIs(handler2, info.handler)\n\n    def test_raise_method_not_allowed(self):\n        handler1 = lambda req: Response(req)\n        handler2 = lambda req: Response(req)\n        self.router.add_route('GET', '/', handler1)\n        self.router.add_route('POST', '/', handler2)\n        req = self.make_request('PUT', '/')\n\n        with self.assertRaises(HTTPMethodNotAllowed) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual('PUT', exc.method)\n        self.assertEqual(405, exc.status)\n        self.assertEqual({'POST', 'GET'}, exc.allowed_methods)\n\n    def test_raise_method_not_found(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/a', handler)\n        req = self.make_request('GET', '/b')\n\n        with self.assertRaises(HTTPNotFound) as ctx:\n            self.loop.run_until_complete(self.router.resolve(req))\n\n        exc = ctx.exception\n        self.assertEqual(404, exc.status)\n\n    def test_double_add_url_with_the_same_name(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        regexp = (\"Duplicate 'name', already handled by\")\n        with self.assertRaisesRegex(ValueError, regexp):\n            self.router.add_route('GET', '/get_other', lambda r: None,\n                                  name='name')\n\n    def test_route_plain(self):\n        route = self.router.add_route('GET', '/get', lambda r: None,\n                                      name='name')\n        route2 = self.router['name']\n        url = route2.url()\n        self.assertEqual('/get', url)\n        self.assertIs(route, route2)\n\n    def test_route_unknown_route_name(self):\n        with self.assertRaises(KeyError):\n            self.router['unknown']\n\n    def test_route_dynamic(self):\n        route = self.router.add_route('GET', '/get/{name}',\n                                      lambda r: None, name='name')\n\n        route2 = self.router['name']\n        url = route2.url(parts={'name': 'John'})\n        self.assertEqual('/get/John', url)\n        self.assertIs(route, route2)\n\n    def test_route_with_qs(self):\n        self.router.add_route('GET', '/get', lambda r: None, name='name')\n\n        url = self.router['name'].url(query=[('a', 'b'), ('c', 1)])\n        self.assertEqual('/get?a=b&c=1', url)\n\n    def test_add_static(self):\n        route = self.router.add_static('/st',\n                                       os.path.dirname(aiohttp.__file__),\n                                       name='static')\n        route2 = self.router['static']\n        url = route2.url(filename='/dir/a.txt')\n        self.assertEqual('/st/dir/a.txt', url)\n        self.assertIs(route, route2)\n\n    def test_plain_not_match(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_not_match(self):\n        self.router.add_route('GET', '/get/{name}',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_static_not_match(self):\n        self.router.add_static('/pre', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        route = self.router['name']\n        self.assertIsNone(route.match('/another/path'))\n\n    def test_dynamic_with_trailing_slash(self):\n        self.router.add_route('GET', '/get/{name}/',\n                              lambda r: None, name='name')\n        route = self.router['name']\n        self.assertEqual({'name': 'John'}, route.match('/get/John/'))\n\n    def test_len(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual(2, len(self.router))\n\n    def test_iter(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertEqual({'name1', 'name2'}, set(iter(self.router)))\n\n    def test_contains(self):\n        self.router.add_route('GET', '/get1',\n                              lambda r: None, name='name1')\n        self.router.add_route('GET', '/get2',\n                              lambda r: None, name='name2')\n        self.assertIn('name1', self.router)\n        self.assertNotIn('name3', self.router)\n\n    def test_plain_repr(self):\n        self.router.add_route('GET', '/get/path',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<PlainRoute 'name' \\[GET\\] /get/path\")\n\n    def test_dynamic_repr(self):\n        self.router.add_route('GET', '/get/{path}',\n                              lambda r: None, name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<DynamicRoute 'name' \\[GET\\] /get/{path}\")\n\n    def test_static_repr(self):\n        self.router.add_static('/get', os.path.dirname(aiohttp.__file__),\n                               name='name')\n        self.assertRegex(repr(self.router['name']),\n                         r\"<StaticRoute 'name' \\[GET\\] /get/\")\n\n    def test_static_adds_slash(self):\n        route = self.router.add_static('/prefix',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_static_dont_add__double_slash(self):\n        route = self.router.add_static('/prefix/',\n                                       os.path.dirname(aiohttp.__file__))\n        self.assertEqual('/prefix/', route._prefix)\n\n    def test_add_route_with_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/1234')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': '1234'}, info)\n\n    def test_add_route_with_re_not_match(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n\n        req = self.make_request('GET', '/handler/tail')\n        with self.assertRaises(HTTPNotFound):\n            self.loop.run_until_complete(self.router.resolve(req))\n\n    def test_add_route_with_re_including_slashes(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:.+}/tail', handler)\n\n        req = self.make_request('GET', '/handler/re/with/slashes/tail')\n        info = self.loop.run_until_complete(self.router.resolve(req))\n        self.assertIsNotNone(info)\n        self.assertEqual({'to': 're/with/slashes'}, info)\n\n    def test_add_route_with_invalid_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        with self.assertRaises(ValueError) as ctx:\n            self.router.add_route('GET', r'/handler/{to:+++}', handler)\n        self.assertEqual(\n            \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\",\n            str(ctx.exception))\n        self.assertIsNone(ctx.exception.__cause__)\n",
        "import asyncio\nimport unittest\nfrom unittest import mock\nfrom aiohttp.web import Request\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.protocol import HttpVersion\nfrom aiohttp.protocol import RawRequestMessage\n\n\nclass TestWebRequest(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        self.loop.close()\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_ctor(self):\n        req = self.make_request('GET', '/path/to?a=1&b=2')\n\n        self.assertIs(self.app, req.app)\n        self.assertEqual('GET', req.method)\n        self.assertEqual(HttpVersion(1, 1), req.version)\n        self.assertEqual(None, req.host)\n        self.assertEqual('/path/to?a=1&b=2', req.path_qs)\n        self.assertEqual('/path/to', req.path)\n        self.assertEqual('a=1&b=2', req.query_string)\n\n        get = req.GET\n        self.assertEqual(MultiDict([('a', '1'), ('b', '2')]), get)\n        # second call should return the same object\n        self.assertIs(get, req.GET)\n\n        self.assertIs(self.payload, req.payload)\n        self.assertIs(self.transport, req.transport)\n        self.assertTrue(req.keep_alive)\n\n    def test_POST(self):\n        req = self.make_request('POST', '/')\n        with self.assertRaises(RuntimeError):\n            req.POST\n\n        marker = object()\n        req._post = marker\n        self.assertIs(req.POST, marker)\n        self.assertIs(req.POST, marker)\n\n    def test_content_type_not_specified(self):\n        req = self.make_request('Get', '/')\n        self.assertEqual('application/octet-stream', req.content_type)\n\n    def test_content_type_from_spec(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n        self.assertEqual('application/json', req.content_type)\n\n    def test_content_type_from_spec_with_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('text/html', req.content_type)\n        self.assertEqual('UTF-8', req.charset)\n\n    def test_calc_content_type_on_getting_charset(self):\n        req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n        self.assertEqual('UTF-8', req.charset)\n        self.assertEqual('text/html', req.content_type)\n\n    def test_urlencoded_querystring(self):\n        req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n        self.assertEqual({'text': 'текст'}, req.GET)\n\n    def test_non_ascii_path(self):\n        req = self.make_request('GET', '/путь')\n        self.assertEqual('/путь', req.path)\n\n    def test_content_length(self):\n        req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\n        self.assertEqual(123, req.content_length)\n\n    def test_non_keepalive_on_http10(self):\n        req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n        self.assertFalse(req.keep_alive)\n\n    def test_non_keepalive_on_closing(self):\n        req = self.make_request('GET', '/', closing=True)\n        self.assertFalse(req.keep_alive)\n\n    def test_call_POST_on_GET_request(self):\n        req = self.make_request('GET', '/')\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_on_weird_content_type(self):\n        req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\n        ret = self.loop.run_until_complete(req.post())\n        self.assertEqual(MultiDict(), ret)\n\n    def test_call_POST_twice(self):\n        req = self.make_request('GET', '/')\n\n        ret1 = self.loop.run_until_complete(req.post())\n        ret2 = self.loop.run_until_complete(req.post())\n        self.assertIs(ret1, ret2)\n\n    def test_no_request_cookies(self):\n        req = self.make_request('GET', '/')\n\n        self.assertEqual(req.cookies, {})\n\n        cookies = req.cookies\n        self.assertIs(cookies, req.cookies)\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {\n            'cookie1': 'value1',\n            'cookie2': 'value2',\n        })\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n        req = self.make_request('GET', '/', headers=headers)\n\n        self.assertEqual(req.cookies, {'name': 'value'})\n\n        with self.assertRaises(TypeError):\n            req.cookies['my'] = 'value'\n\n    def test_match_info(self):\n        req = self.make_request('GET', '/')\n        self.assertIsNone(req.match_info)\n        match = {'a': 'b'}\n        req._match_info = match\n        self.assertIs(match, req.match_info)\n",
        "import asyncio\nimport unittest\nfrom unittest import mock\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.web import (Request, WebSocketResponse,\n                         WebSocketDisconnectedError,\n                         HTTPMethodNotAllowed, HTTPBadRequest)\nfrom aiohttp.protocol import RawRequestMessage, HttpVersion11\n\n\nclass TestWebWebSocket(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        self.loop.close()\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_nonstarted_ping(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_nonstarted_send_str(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_nonstarted_send_bytes(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_nonstarted_close(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.close()\n\n    def test_nonstarted_receive(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.receive()\n\n        self.loop.run_until_complete(go())\n\n    def test_send_str_nonstring(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_str(b'bytes')\n\n    def test_send_bytes_nonbytes(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaises(TypeError):\n            ws.send_bytes('string')\n\n    def test_write(self):\n        ws = WebSocketResponse()\n        with self.assertRaises(RuntimeError):\n            ws.write(b'data')\n\n    def test_nested_exception(self):\n\n        @asyncio.coroutine\n        def a():\n            raise WebSocketDisconnectedError()\n\n        @asyncio.coroutine\n        def b():\n            yield from a()\n\n        @asyncio.coroutine\n        def c():\n            yield from b()\n\n        with self.assertRaises(WebSocketDisconnectedError):\n            self.loop.run_until_complete(c())\n\n    def test_can_start_ok(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse(protocols=('chat',))\n        self.assertEqual((True, 'chat'), ws.can_start(req))\n\n    def test_can_start_unknown_protocol(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((True, None), ws.can_start(req))\n\n    def test_can_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        self.assertEqual((False, None), ws.can_start(req))\n\n    def test_can_start_started(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        with self.assertRaisesRegex(RuntimeError, 'Already started'):\n            ws.can_start(req)\n\n    def test_closing_after_ctor(self):\n        ws = WebSocketResponse()\n        self.assertFalse(ws.closing)\n\n    def test_send_str_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_str('string')\n\n    def test_send_bytes_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.send_bytes(b'bytes')\n\n    def test_ping_closing(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        ws.close()\n        with self.assertRaises(RuntimeError):\n            ws.ping()\n\n    def test_double_close(self):\n        req = self.make_request('GET', '/')\n        ws = WebSocketResponse()\n        ws.start(req)\n        writer = mock.Mock()\n        ws._writer = writer\n        ws.close(code=1, message='message1')\n        self.assertTrue(ws.closing)\n        with self.assertRaisesRegex(RuntimeError, 'Already closing'):\n            ws.close(code=2, message='message2')\n        self.assertTrue(ws.closing)\n        writer.close.assert_called_once_with(1, 'message1')\n\n    def test_start_invalid_method(self):\n        req = self.make_request('POST', '/')\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPMethodNotAllowed):\n            ws.start(req)\n\n    def test_start_without_upgrade(self):\n        req = self.make_request('GET', '/', headers=MultiDict())\n        ws = WebSocketResponse()\n        with self.assertRaises(HTTPBadRequest):\n            ws.start(req)\n\n    def test_wait_closed_before_start(self):\n\n        @asyncio.coroutine\n        def go():\n            ws = WebSocketResponse()\n            with self.assertRaises(RuntimeError):\n                yield from ws.wait_closed()\n\n        self.loop.run_until_complete(go())\n",
        "import asyncio\nimport collections\nimport unittest\nfrom unittest import mock\nfrom aiohttp.multidict import MultiDict\nfrom aiohttp.web import Request\nfrom aiohttp.protocol import RawRequestMessage, HttpVersion11\n\nfrom aiohttp import web\n\n\nclass TestHTTPExceptions(unittest.TestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n        self.writer.drain.return_value = ()\n        self.buf = b''\n\n        self.writer.write.side_effect = self.append\n\n    def tearDown(self):\n        self.loop.close()\n\n    def append(self, data):\n        self.buf += data\n\n    def make_request(self, method='GET', path='/', headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\n        return req\n\n    def test_all_http_exceptions_exported(self):\n        self.assertIn('HTTPException', web.__all__)\n        for name in dir(web):\n            if name.startswith('_'):\n                continue\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                self.assertIn(name, web.__all__)\n\n    def test_HTTPOk(self):\n        req = self.make_request()\n        resp = web.HTTPOk()\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 200 OK\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 7\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '200: OK'))\n\n    def test_terminal_classes_has_status_code(self):\n        terminals = set()\n        for name in dir(web):\n            obj = getattr(web, name)\n            if isinstance(obj, type) and issubclass(obj, web.HTTPException):\n                terminals.add(obj)\n\n        dup = frozenset(terminals)\n        for cls1 in dup:\n            for cls2 in dup:\n                if cls1 in cls2.__bases__:\n                    terminals.discard(cls1)\n\n        for cls in terminals:\n            self.assertIsNotNone(cls.status_code, cls)\n        codes = collections.Counter(cls.status_code for cls in terminals)\n        self.assertNotIn(None, codes)\n        self.assertEqual(1, codes.most_common(1)[0][1])\n\n    def test_HTTPFound(self):\n        req = self.make_request()\n        resp = web.HTTPFound(location='/redirect')\n        self.assertEqual('/redirect', resp.location)\n        self.assertEqual('/redirect', resp.headers['location'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 302 Found\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 10\\r\\n'\n                               'LOCATION: /redirect\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '302: Found'))\n\n    def test_HTTPFound_empty_location(self):\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location='')\n\n        with self.assertRaises(ValueError):\n            web.HTTPFound(location=None)\n\n    def test_HTTPMethodNotAllowed(self):\n        req = self.make_request()\n        resp = web.HTTPMethodNotAllowed('get', ['POST', 'PUT'])\n        self.assertEqual('GET', resp.method)\n        self.assertEqual(['POST', 'PUT'], resp.allowed_methods)\n        self.assertEqual('POST,PUT', resp.headers['allow'])\n        resp.start(req)\n        self.loop.run_until_complete(resp.write_eof())\n        txt = self.buf.decode('utf8')\n        self.assertRegex(txt, ('HTTP/1.1 405 Method Not Allowed\\r\\n'\n                               'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n                               'CONTENT-LENGTH: 23\\r\\n'\n                               'ALLOW: POST,PUT\\r\\n'\n                               'CONNECTION: keep-alive\\r\\n'\n                               'DATE: .+\\r\\n'\n                               'SERVER: .+\\r\\n\\r\\n'\n                               '405: Method Not Allowed'))\n\n    def test_override_body_with_text(self):\n        resp = web.HTTPNotFound(text=\"Page not found\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(\"Page not found\".encode('utf-8'), resp.body)\n        self.assertEqual(\"Page not found\", resp.text)\n        self.assertEqual(\"text/plain\", resp.content_type)\n        self.assertEqual(\"utf-8\", resp.charset)\n\n    def test_override_body_with_binary(self):\n        txt = \"<html><body>Page not found</body></html>\"\n        resp = web.HTTPNotFound(body=txt.encode('utf-8'),\n                                content_type=\"text/html\")\n        self.assertEqual(404, resp.status)\n        self.assertEqual(txt.encode('utf-8'), resp.body)\n        self.assertEqual(txt, resp.text)\n        self.assertEqual(\"text/html\", resp.content_type)\n        self.assertIsNone(resp.charset)\n"
    ],
    "test_file_names": [
        "test_1.py",
        "test_2.py",
        "test_3.py",
        "test_4.py",
        "test_5.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 53ms\nInstalled 26 packages in 40ms\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.1\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_d2fbdefd269d4d79e54c703d636269bf52505bfb\nplugins: mock-3.14.0, asyncio-0.25.1, cov-6.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollected 126 items\n\nr2e_tests/test_1.py ......F......FFF.........................            [ 32%]\nr2e_tests/test_2.py ...F.................................                [ 61%]\nr2e_tests/test_3.py ..................                                   [ 76%]\nr2e_tests/test_4.py ......................                               [ 93%]\nr2e_tests/test_5.py ........                                             [100%]\n\n=================================== FAILURES ===================================\n_________________ TestStreamResponse.test_cookie_set_after_del _________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_cookie_set_after_del>\n\n    def test_cookie_set_after_del(self):\n        resp = StreamResponse()\n    \n        resp.del_cookie('name')\n        resp.set_cookie('name', 'val')\n        # check for Max-Age dropped\n>       self.assertEqual(str(resp.cookies), 'Set-Cookie: name=val')\nE       AssertionError: 'Set-Cookie: name=val; Max-Age=0' != 'Set-Cookie: name=val'\nE       - Set-Cookie: name=val; Max-Age=0\nE       ?                     -----------\nE       + Set-Cookie: name=val\n\nr2e_tests/test_1.py:245: AssertionError\n__________ TestStreamResponse.test_response_cookie__issue_del_cookie ___________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_response_cookie__issue_del_cookie>\n\n    def test_response_cookie__issue_del_cookie(self):\n        resp = StreamResponse()\n    \n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n    \n        resp.del_cookie('name')\n>       self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\nE       AssertionError: 'Set-Cookie: name=\"\"; Max-Age=0' != 'Set-Cookie: name=; Max-Age=0'\nE       - Set-Cookie: name=\"\"; Max-Age=0\nE       ?                  --\nE       + Set-Cookie: name=; Max-Age=0\n\nr2e_tests/test_1.py:237: AssertionError\n_________________ TestStreamResponse.test_response_cookie_path _________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_response_cookie_path>\n\n    def test_response_cookie_path(self):\n        resp = StreamResponse()\n    \n        self.assertEqual(resp.cookies, {})\n    \n        resp.set_cookie('name', 'value', path='/some/path')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Path=/some/path')\n        resp.set_cookie('name', 'value', expires='123')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; expires=123;'\n                         ' Path=/some/path')\n        resp.set_cookie('name', 'value', domain='example.com',\n                        path='/home', expires='123', max_age='10',\n                        secure=True, httponly=True, version='2.0')\n>       self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; '\n                         'Domain=example.com; '\n                         'expires=123; '\n                         'httponly; '\n                         'Max-Age=10; '\n                         'Path=/home; '\n                         'secure; '\n                         'Version=2.0')\nE       AssertionError: 'Set-[44 chars]res=123; HttpOnly; Max-Age=10; Path=/home; Secure; Version=2.0' != 'Set-[44 chars]res=123; httponly; Max-Age=10; Path=/home; secure; Version=2.0'\nE       - Set-Cookie: name=value; Domain=example.com; expires=123; HttpOnly; Max-Age=10; Path=/home; Secure; Version=2.0\nE       ?                                                          ^   ^                             ^\nE       + Set-Cookie: name=value; Domain=example.com; expires=123; httponly; Max-Age=10; Path=/home; secure; Version=2.0\nE       ?                                                          ^   ^                             ^\n\nr2e_tests/test_1.py:220: AssertionError\n___________________ TestStreamResponse.test_response_cookies ___________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_response_cookies>\n\n    def test_response_cookies(self):\n        resp = StreamResponse()\n    \n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n    \n        resp.set_cookie('name', 'value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=value')\n        resp.set_cookie('name', 'other_value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=other_value')\n    \n        resp.cookies['name'] = 'another_other_value'\n        resp.cookies['name']['max-age'] = 10\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=another_other_value; Max-Age=10')\n    \n        resp.del_cookie('name')\n>       self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\nE       AssertionError: 'Set-Cookie: name=\"\"; Max-Age=0' != 'Set-Cookie: name=; Max-Age=0'\nE       - Set-Cookie: name=\"\"; Max-Age=0\nE       ?                  --\nE       + Set-Cookie: name=; Max-Age=0\n\nr2e_tests/test_1.py:199: AssertionError\n_______________ TestUrlDispatcher.test_add_route_with_invalid_re _______________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_with_invalid_re>\n\n    def test_add_route_with_invalid_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        with self.assertRaises(ValueError) as ctx:\n            self.router.add_route('GET', r'/handler/{to:+++}', handler)\n>       self.assertEqual(\n            \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\",\n            str(ctx.exception))\nE       AssertionError: \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\" != \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat at position 17\"\nE       - Bad pattern '/handler/(?P<to>+++)': nothing to repeat\nE       + Bad pattern '/handler/(?P<to>+++)': nothing to repeat at position 17\nE       ?                                                      +++++++++++++++\n\nr2e_tests/test_2.py:300: AssertionError\n==================================== PASSES ====================================\n___________________ TestWebWebSocket.test_can_start_started ____________________\n------------------------------ Captured log call -------------------------------\nWARNING  aiohttp.websocket:websocket.py:225 Client protocols () don’t overlap server-known ones {'chat', 'superchat'}\n_______________ TestWebWebSocket.test_can_start_unknown_protocol _______________\n------------------------------ Captured log call -------------------------------\nWARNING  aiohttp.websocket:websocket.py:225 Client protocols () don’t overlap server-known ones {'chat', 'superchat'}\n______________________ TestWebWebSocket.test_double_close ______________________\n------------------------------ Captured log call -------------------------------\nWARNING  aiohttp.websocket:websocket.py:225 Client protocols () don’t overlap server-known ones {'chat', 'superchat'}\n______________________ TestWebWebSocket.test_ping_closing ______________________\n------------------------------ Captured log call -------------------------------\nWARNING  aiohttp.websocket:websocket.py:225 Client protocols () don’t overlap server-known ones {'chat', 'superchat'}\n___________________ TestWebWebSocket.test_send_bytes_closing ___________________\n------------------------------ Captured log call -------------------------------\nWARNING  aiohttp.websocket:websocket.py:225 Client protocols () don’t overlap server-known ones {'chat', 'superchat'}\n__________________ TestWebWebSocket.test_send_bytes_nonbytes ___________________\n------------------------------ Captured log call -------------------------------\nWARNING  aiohttp.websocket:websocket.py:225 Client protocols () don’t overlap server-known ones {'chat', 'superchat'}\n____________________ TestWebWebSocket.test_send_str_closing ____________________\n------------------------------ Captured log call -------------------------------\nWARNING  aiohttp.websocket:websocket.py:225 Client protocols () don’t overlap server-known ones {'chat', 'superchat'}\n___________________ TestWebWebSocket.test_send_str_nonstring ___________________\n------------------------------ Captured log call -------------------------------\nWARNING  aiohttp.websocket:websocket.py:225 Client protocols () don’t overlap server-known ones {'chat', 'superchat'}\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_cannot_write_after_eof\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_cannot_write_eof_before_headers\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_cannot_write_eof_twice\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_charset_without_content_type\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_content_length\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_content_length_setter\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_ctor\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_default_charset\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_drop_content_length_header_on_setting_len_to_None\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_force_close\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_reset_charset\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_reset_charset_after_setting\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_set_content_length_to_None_on_non_set\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_set_status_with_reason\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_setting_charset\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_setting_content_type\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_start\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_start_force_close\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_write_before_start\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_write_non_byteish\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_write_returns_drain\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_write_returns_empty_tuple_on_empty_data\nPASSED r2e_tests/test_1.py::TestResponse::test_assign_nonbyteish_body\nPASSED r2e_tests/test_1.py::TestResponse::test_assign_nonstr_text\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor_content_type\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor_text\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor_text_body_combined\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor_with_headers_and_status\nPASSED r2e_tests/test_1.py::TestResponse::test_drain_before_start\nPASSED r2e_tests/test_1.py::TestResponse::test_render_with_body\nPASSED r2e_tests/test_1.py::TestResponse::test_send_headers_for_empty_body\nPASSED r2e_tests/test_1.py::TestResponse::test_send_set_cookie_header\nPASSED r2e_tests/test_1.py::TestResponse::test_set_text_with_charset\nPASSED r2e_tests/test_1.py::TestResponse::test_set_text_with_content_type\nPASSED r2e_tests/test_1.py::TestResponse::test_started_when_not_started\nPASSED r2e_tests/test_1.py::TestResponse::test_started_when_started\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_invalid_path\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_root\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_simple\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_with_re\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_with_re_including_slashes\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_with_re_not_match\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_static\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_escaping\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid1\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid2\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid3\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid4\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid5\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_with_matchdict\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_with_name\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_with_tailing_slash\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_contains\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_double_add_url_with_the_same_name\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_dynamic_not_match\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_dynamic_repr\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_dynamic_with_trailing_slash\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_iter\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_len\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_match_second_result_in_table\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_plain_not_match\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_plain_repr\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_raise_method_not_allowed\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_raise_method_not_found\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_route_dynamic\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_route_plain\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_route_unknown_route_name\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_route_with_qs\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_static_adds_slash\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_static_dont_add__double_slash\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_static_not_match\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_static_repr\nPASSED r2e_tests/test_3.py::TestWebRequest::test_POST\nPASSED r2e_tests/test_3.py::TestWebRequest::test_calc_content_type_on_getting_charset\nPASSED r2e_tests/test_3.py::TestWebRequest::test_call_POST_on_GET_request\nPASSED r2e_tests/test_3.py::TestWebRequest::test_call_POST_on_weird_content_type\nPASSED r2e_tests/test_3.py::TestWebRequest::test_call_POST_twice\nPASSED r2e_tests/test_3.py::TestWebRequest::test_content_length\nPASSED r2e_tests/test_3.py::TestWebRequest::test_content_type_from_spec\nPASSED r2e_tests/test_3.py::TestWebRequest::test_content_type_from_spec_with_charset\nPASSED r2e_tests/test_3.py::TestWebRequest::test_content_type_not_specified\nPASSED r2e_tests/test_3.py::TestWebRequest::test_ctor\nPASSED r2e_tests/test_3.py::TestWebRequest::test_match_info\nPASSED r2e_tests/test_3.py::TestWebRequest::test_no_request_cookies\nPASSED r2e_tests/test_3.py::TestWebRequest::test_non_ascii_path\nPASSED r2e_tests/test_3.py::TestWebRequest::test_non_keepalive_on_closing\nPASSED r2e_tests/test_3.py::TestWebRequest::test_non_keepalive_on_http10\nPASSED r2e_tests/test_3.py::TestWebRequest::test_request_cookie\nPASSED r2e_tests/test_3.py::TestWebRequest::test_request_cookie__set_item\nPASSED r2e_tests/test_3.py::TestWebRequest::test_urlencoded_querystring\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_invalid_method\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_ok\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_started\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_unknown_protocol\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_without_upgrade\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_closing_after_ctor\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_double_close\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nested_exception\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_close\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_ping\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_receive\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_send_bytes\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_send_str\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_ping_closing\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_send_bytes_closing\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_send_bytes_nonbytes\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_send_str_closing\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_send_str_nonstring\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_start_invalid_method\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_start_without_upgrade\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_wait_closed_before_start\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_write\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_HTTPFound\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_HTTPFound_empty_location\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_HTTPMethodNotAllowed\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_HTTPOk\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_all_http_exceptions_exported\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_override_body_with_binary\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_override_body_with_text\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_terminal_classes_has_status_code\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_cookie_set_after_del - A...\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_response_cookie__issue_del_cookie\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_response_cookie_path - A...\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_response_cookies - Asser...\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_with_invalid_re\n======================== 5 failed, 121 passed in 0.79s =========================\n",
    "new_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d2fbdefd269d4d79e54c703d636269bf52505bfb/.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_d2fbdefd269d4d79e54c703d636269bf52505bfb\nplugins: mock-3.14.0, asyncio-0.25.1, cov-6.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollected 126 items\n\nr2e_tests/test_1.py F.F...F......FFF....FF.FFF........FFF...F            [ 32%]\nr2e_tests/test_2.py .FFFFFF.F.....FFF.......F..FF........                [ 61%]\nr2e_tests/test_3.py FFFFFFFFFFFFFFFFFF                                   [ 76%]\nr2e_tests/test_4.py FFFFF.F......FFFFFFF..                               [ 93%]\nr2e_tests/test_5.py F.FF....                                             [100%]\n\n=================================== FAILURES ===================================\n________________ TestStreamResponse.test_cannot_write_after_eof ________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_cannot_write_after_eof>\n\n    def test_cannot_write_after_eof(self):\n        resp = StreamResponse()\n>       resp.start(self.make_request('GET', '/'))\n\nr2e_tests/test_1.py:133: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_cannot_write_after_eof>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:26: TypeError\n________________ TestStreamResponse.test_cannot_write_eof_twice ________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_cannot_write_eof_twice>\n\n    def test_cannot_write_eof_twice(self):\n        resp = StreamResponse()\n>       resp.start(self.make_request('GET', '/'))\n\nr2e_tests/test_1.py:152: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_cannot_write_eof_twice>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:26: TypeError\n_________________ TestStreamResponse.test_cookie_set_after_del _________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_cookie_set_after_del>\n\n    def test_cookie_set_after_del(self):\n        resp = StreamResponse()\n    \n        resp.del_cookie('name')\n        resp.set_cookie('name', 'val')\n        # check for Max-Age dropped\n>       self.assertEqual(str(resp.cookies), 'Set-Cookie: name=val')\nE       AssertionError: 'Set-Cookie: name=val; Max-Age=0' != 'Set-Cookie: name=val'\nE       - Set-Cookie: name=val; Max-Age=0\nE       ?                     -----------\nE       + Set-Cookie: name=val\n\nr2e_tests/test_1.py:245: AssertionError\n__________ TestStreamResponse.test_response_cookie__issue_del_cookie ___________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_response_cookie__issue_del_cookie>\n\n    def test_response_cookie__issue_del_cookie(self):\n        resp = StreamResponse()\n    \n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n    \n        resp.del_cookie('name')\n>       self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\nE       AssertionError: 'Set-Cookie: name=\"\"; Max-Age=0' != 'Set-Cookie: name=; Max-Age=0'\nE       - Set-Cookie: name=\"\"; Max-Age=0\nE       ?                  --\nE       + Set-Cookie: name=; Max-Age=0\n\nr2e_tests/test_1.py:237: AssertionError\n_________________ TestStreamResponse.test_response_cookie_path _________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_response_cookie_path>\n\n    def test_response_cookie_path(self):\n        resp = StreamResponse()\n    \n        self.assertEqual(resp.cookies, {})\n    \n        resp.set_cookie('name', 'value', path='/some/path')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; Path=/some/path')\n        resp.set_cookie('name', 'value', expires='123')\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; expires=123;'\n                         ' Path=/some/path')\n        resp.set_cookie('name', 'value', domain='example.com',\n                        path='/home', expires='123', max_age='10',\n                        secure=True, httponly=True, version='2.0')\n>       self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=value; '\n                         'Domain=example.com; '\n                         'expires=123; '\n                         'httponly; '\n                         'Max-Age=10; '\n                         'Path=/home; '\n                         'secure; '\n                         'Version=2.0')\nE       AssertionError: 'Set-[44 chars]res=123; HttpOnly; Max-Age=10; Path=/home; Secure; Version=2.0' != 'Set-[44 chars]res=123; httponly; Max-Age=10; Path=/home; secure; Version=2.0'\nE       - Set-Cookie: name=value; Domain=example.com; expires=123; HttpOnly; Max-Age=10; Path=/home; Secure; Version=2.0\nE       ?                                                          ^   ^                             ^\nE       + Set-Cookie: name=value; Domain=example.com; expires=123; httponly; Max-Age=10; Path=/home; secure; Version=2.0\nE       ?                                                          ^   ^                             ^\n\nr2e_tests/test_1.py:220: AssertionError\n___________________ TestStreamResponse.test_response_cookies ___________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_response_cookies>\n\n    def test_response_cookies(self):\n        resp = StreamResponse()\n    \n        self.assertEqual(resp.cookies, {})\n        self.assertEqual(str(resp.cookies), '')\n    \n        resp.set_cookie('name', 'value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=value')\n        resp.set_cookie('name', 'other_value')\n        self.assertEqual(str(resp.cookies), 'Set-Cookie: name=other_value')\n    \n        resp.cookies['name'] = 'another_other_value'\n        resp.cookies['name']['max-age'] = 10\n        self.assertEqual(str(resp.cookies),\n                         'Set-Cookie: name=another_other_value; Max-Age=10')\n    \n        resp.del_cookie('name')\n>       self.assertEqual(str(resp.cookies), 'Set-Cookie: name=; Max-Age=0')\nE       AssertionError: 'Set-Cookie: name=\"\"; Max-Age=0' != 'Set-Cookie: name=; Max-Age=0'\nE       - Set-Cookie: name=\"\"; Max-Age=0\nE       ?                  --\nE       + Set-Cookie: name=; Max-Age=0\n\nr2e_tests/test_1.py:199: AssertionError\n________________________ TestStreamResponse.test_start _________________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_start>\nResponseImpl = <MagicMock name='ResponseImpl' id='124124067434752'>\n\n    @mock.patch('aiohttp.web.ResponseImpl')\n    def test_start(self, ResponseImpl):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_1.py:103: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_start>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:26: TypeError\n__________________ TestStreamResponse.test_start_force_close ___________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_start_force_close>\n\n    def test_start_force_close(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_1.py:255: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_start_force_close>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:26: TypeError\n__________________ TestStreamResponse.test_write_non_byteish ___________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_write_non_byteish>\n\n    def test_write_non_byteish(self):\n        resp = StreamResponse()\n>       resp.start(self.make_request('GET', '/'))\n\nr2e_tests/test_1.py:120: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_write_non_byteish>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:26: TypeError\n_________________ TestStreamResponse.test_write_returns_drain __________________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_write_returns_drain>\n\n    def test_write_returns_drain(self):\n        resp = StreamResponse()\n>       resp.start(self.make_request('GET', '/'))\n\nr2e_tests/test_1.py:165: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_write_returns_drain>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:26: TypeError\n_______ TestStreamResponse.test_write_returns_empty_tuple_on_empty_data ________\n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_write_returns_empty_tuple_on_empty_data>\n\n    def test_write_returns_empty_tuple_on_empty_data(self):\n        resp = StreamResponse()\n>       resp.start(self.make_request('GET', '/'))\n\nr2e_tests/test_1.py:171: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestStreamResponse testMethod=test_write_returns_empty_tuple_on_empty_data>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:26: TypeError\n______________________ TestResponse.test_render_with_body ______________________\n\nself = <r2e_tests.test_1.TestResponse testMethod=test_render_with_body>\n\n    def test_render_with_body(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_1.py:371: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestResponse testMethod=test_render_with_body>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:282: TypeError\n________________ TestResponse.test_send_headers_for_empty_body _________________\n\nself = <r2e_tests.test_1.TestResponse testMethod=test_send_headers_for_empty_body>\n\n    def test_send_headers_for_empty_body(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_1.py:351: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestResponse testMethod=test_send_headers_for_empty_body>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:282: TypeError\n___________________ TestResponse.test_send_set_cookie_header ___________________\n\nself = <r2e_tests.test_1.TestResponse testMethod=test_send_set_cookie_header>\n\n    def test_send_set_cookie_header(self):\n        resp = Response()\n        resp.cookies['name'] = 'value'\n    \n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_1.py:394: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestResponse testMethod=test_send_set_cookie_header>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:282: TypeError\n____________________ TestResponse.test_started_when_started ____________________\n\nself = <r2e_tests.test_1.TestResponse testMethod=test_started_when_started>\n\n    def test_started_when_started(self):\n        resp = StreamResponse()\n>       resp.start(self.make_request('GET', '/'))\n\nr2e_tests/test_1.py:437: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_1.TestResponse testMethod=test_started_when_started>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_1.py:282: TypeError\n____________________ TestUrlDispatcher.test_add_route_root _____________________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_root>\n\n    def test_add_route_root(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/', handler)\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_2.py:37: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_root>\nmethod = 'GET', path = '/'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n___________________ TestUrlDispatcher.test_add_route_simple ____________________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_simple>\n\n    def test_add_route_simple(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path', handler)\n>       req = self.make_request('GET', '/handler/to/path')\n\nr2e_tests/test_2.py:47: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_simple>\nmethod = 'GET', path = '/handler/to/path'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n_______________ TestUrlDispatcher.test_add_route_with_invalid_re _______________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_with_invalid_re>\n\n    def test_add_route_with_invalid_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        with self.assertRaises(ValueError) as ctx:\n            self.router.add_route('GET', r'/handler/{to:+++}', handler)\n>       self.assertEqual(\n            \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\",\n            str(ctx.exception))\nE       AssertionError: \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat\" != \"Bad pattern '/handler/(?P<to>+++)': nothing to repeat at position 17\"\nE       - Bad pattern '/handler/(?P<to>+++)': nothing to repeat\nE       + Bad pattern '/handler/(?P<to>+++)': nothing to repeat at position 17\nE       ?                                                      +++++++++++++++\n\nr2e_tests/test_2.py:300: AssertionError\n___________________ TestUrlDispatcher.test_add_route_with_re ___________________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_with_re>\n\n    def test_add_route_with_re(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n    \n>       req = self.make_request('GET', '/handler/1234')\n\nr2e_tests/test_2.py:274: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_with_re>\nmethod = 'GET', path = '/handler/1234'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n__________ TestUrlDispatcher.test_add_route_with_re_including_slashes __________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_with_re_including_slashes>\n\n    def test_add_route_with_re_including_slashes(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:.+}/tail', handler)\n    \n>       req = self.make_request('GET', '/handler/re/with/slashes/tail')\n\nr2e_tests/test_2.py:291: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_with_re_including_slashes>\nmethod = 'GET', path = '/handler/re/with/slashes/tail'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n______________ TestUrlDispatcher.test_add_route_with_re_not_match ______________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_with_re_not_match>\n\n    def test_add_route_with_re_not_match(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', r'/handler/{to:\\d+}', handler)\n    \n>       req = self.make_request('GET', '/handler/tail')\n\nr2e_tests/test_2.py:283: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_route_with_re_not_match>\nmethod = 'GET', path = '/handler/tail'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n___________________ TestUrlDispatcher.test_add_url_escaping ____________________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_url_escaping>\n\n    def test_add_url_escaping(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/+$', handler)\n    \n>       req = self.make_request('GET', '/+$')\n\nr2e_tests/test_2.py:110: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_url_escaping>\nmethod = 'GET', path = '/+$'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n__________________ TestUrlDispatcher.test_add_with_matchdict ___________________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_with_matchdict>\n\n    def test_add_with_matchdict(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/{to}', handler)\n>       req = self.make_request('GET', '/handler/tail')\n\nr2e_tests/test_2.py:57: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_with_matchdict>\nmethod = 'GET', path = '/handler/tail'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n_____________________ TestUrlDispatcher.test_add_with_name _____________________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_with_name>\n\n    def test_add_with_name(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/handler/to/path', handler,\n                              name='name')\n>       req = self.make_request('GET', '/handler/to/path')\n\nr2e_tests/test_2.py:68: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_with_name>\nmethod = 'GET', path = '/handler/to/path'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n________________ TestUrlDispatcher.test_add_with_tailing_slash _________________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_with_tailing_slash>\n\n    def test_add_with_tailing_slash(self):\n        handler = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/handler/to/path/', handler)\n>       req = self.make_request('GET', '/handler/to/path/')\n\nr2e_tests/test_2.py:76: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_add_with_tailing_slash>\nmethod = 'GET', path = '/handler/to/path/'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n_____________ TestUrlDispatcher.test_match_second_result_in_table ______________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_match_second_result_in_table>\n\n    def test_match_second_result_in_table(self):\n        handler1 = asyncio.coroutine(lambda req: Response(req))\n        handler2 = asyncio.coroutine(lambda req: Response(req))\n        self.router.add_route('GET', '/h1', handler1)\n        self.router.add_route('POST', '/h2', handler2)\n>       req = self.make_request('POST', '/h2')\n\nr2e_tests/test_2.py:120: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_match_second_result_in_table>\nmethod = 'POST', path = '/h2'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n_______________ TestUrlDispatcher.test_raise_method_not_allowed ________________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_raise_method_not_allowed>\n\n    def test_raise_method_not_allowed(self):\n        handler1 = lambda req: Response(req)\n        handler2 = lambda req: Response(req)\n        self.router.add_route('GET', '/', handler1)\n        self.router.add_route('POST', '/', handler2)\n>       req = self.make_request('PUT', '/')\n\nr2e_tests/test_2.py:131: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_raise_method_not_allowed>\nmethod = 'PUT', path = '/'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n________________ TestUrlDispatcher.test_raise_method_not_found _________________\n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_raise_method_not_found>\n\n    def test_raise_method_not_found(self):\n        handler = lambda req: Response(req)\n        self.router.add_route('GET', '/a', handler)\n>       req = self.make_request('GET', '/b')\n\nr2e_tests/test_2.py:144: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_2.TestUrlDispatcher testMethod=test_raise_method_not_found>\nmethod = 'GET', path = '/b'\n\n    def make_request(self, method, path):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion(1, 1),\n                                    MultiDict(), False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_2.py:30: TypeError\n___________________________ TestWebRequest.test_POST ___________________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_POST>\n\n    def test_POST(self):\n>       req = self.make_request('POST', '/')\n\nr2e_tests/test_3.py:53: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_POST>, method = 'POST'\npath = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n___________ TestWebRequest.test_calc_content_type_on_getting_charset ___________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_calc_content_type_on_getting_charset>\n\n    def test_calc_content_type_on_getting_charset(self):\n>       req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n\nr2e_tests/test_3.py:80: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_calc_content_type_on_getting_charset>\nmethod = 'Get', path = '/'\nheaders = <MultiDict>\n[('CONTENT-TYPE', 'text/html; charset=UTF-8')]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n_________________ TestWebRequest.test_call_POST_on_GET_request _________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_call_POST_on_GET_request>\n\n    def test_call_POST_on_GET_request(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_3.py:111: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_call_POST_on_GET_request>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n_____________ TestWebRequest.test_call_POST_on_weird_content_type ______________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_call_POST_on_weird_content_type>\n\n    def test_call_POST_on_weird_content_type(self):\n>       req = self.make_request(\n            'POST', '/',\n            headers=MultiDict({'CONTENT-TYPE': 'something/weird'}))\n\nr2e_tests/test_3.py:117: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_call_POST_on_weird_content_type>\nmethod = 'POST', path = '/'\nheaders = <MultiDict>\n[('CONTENT-TYPE', 'something/weird')]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n_____________________ TestWebRequest.test_call_POST_twice ______________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_call_POST_twice>\n\n    def test_call_POST_twice(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_3.py:125: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_call_POST_twice>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n______________________ TestWebRequest.test_content_length ______________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_content_length>\n\n    def test_content_length(self):\n>       req = self.make_request('Get', '/',\n                                MultiDict([('CONTENT-LENGTH', '123')]))\n\nr2e_tests/test_3.py:97: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_content_length>\nmethod = 'Get', path = '/', headers = <MultiDict>\n[('CONTENT-LENGTH', '123')]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n__________________ TestWebRequest.test_content_type_from_spec __________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_content_type_from_spec>\n\n    def test_content_type_from_spec(self):\n>       req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'application/json')]))\n\nr2e_tests/test_3.py:67: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_content_type_from_spec>\nmethod = 'Get', path = '/'\nheaders = <MultiDict>\n[('CONTENT-TYPE', 'application/json')]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n___________ TestWebRequest.test_content_type_from_spec_with_charset ____________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_content_type_from_spec_with_charset>\n\n    def test_content_type_from_spec_with_charset(self):\n>       req = self.make_request(\n            'Get', '/',\n            MultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')]))\n\nr2e_tests/test_3.py:73: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_content_type_from_spec_with_charset>\nmethod = 'Get', path = '/'\nheaders = <MultiDict>\n[('CONTENT-TYPE', 'text/html; charset=UTF-8')]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n________________ TestWebRequest.test_content_type_not_specified ________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_content_type_not_specified>\n\n    def test_content_type_not_specified(self):\n>       req = self.make_request('Get', '/')\n\nr2e_tests/test_3.py:63: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_content_type_not_specified>\nmethod = 'Get', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n___________________________ TestWebRequest.test_ctor ___________________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_ctor>\n\n    def test_ctor(self):\n>       req = self.make_request('GET', '/path/to?a=1&b=2')\n\nr2e_tests/test_3.py:33: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_ctor>, method = 'GET'\npath = '/path/to?a=1&b=2', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n________________________ TestWebRequest.test_match_info ________________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_match_info>\n\n    def test_match_info(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_3.py:158: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_match_info>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n____________________ TestWebRequest.test_no_request_cookies ____________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_no_request_cookies>\n\n    def test_no_request_cookies(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_3.py:132: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_no_request_cookies>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n______________________ TestWebRequest.test_non_ascii_path ______________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_non_ascii_path>\n\n    def test_non_ascii_path(self):\n>       req = self.make_request('GET', '/путь')\n\nr2e_tests/test_3.py:93: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_non_ascii_path>\nmethod = 'GET', path = '/путь', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n_________________ TestWebRequest.test_non_keepalive_on_closing _________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_non_keepalive_on_closing>\n\n    def test_non_keepalive_on_closing(self):\n>       req = self.make_request('GET', '/', closing=True)\n\nr2e_tests/test_3.py:107: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_non_keepalive_on_closing>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n_________________ TestWebRequest.test_non_keepalive_on_http10 __________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_non_keepalive_on_http10>\n\n    def test_non_keepalive_on_http10(self):\n>       req = self.make_request('GET', '/', version=HttpVersion(1, 0))\n\nr2e_tests/test_3.py:103: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_non_keepalive_on_http10>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n______________________ TestWebRequest.test_request_cookie ______________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_request_cookie>\n\n    def test_request_cookie(self):\n        headers = MultiDict(COOKIE='cookie1=value1; cookie2=value2')\n>       req = self.make_request('GET', '/', headers=headers)\n\nr2e_tests/test_3.py:141: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_request_cookie>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('COOKIE', 'cookie1=value1; cookie2=value2')]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n_________________ TestWebRequest.test_request_cookie__set_item _________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_request_cookie__set_item>\n\n    def test_request_cookie__set_item(self):\n        headers = MultiDict(COOKIE='name=value')\n>       req = self.make_request('GET', '/', headers=headers)\n\nr2e_tests/test_3.py:150: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_request_cookie__set_item>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[('COOKIE', 'name=value')]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n__________________ TestWebRequest.test_urlencoded_querystring __________________\n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_urlencoded_querystring>\n\n    def test_urlencoded_querystring(self):\n>       req = self.make_request(\n            'GET',\n            '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82')\n\nr2e_tests/test_3.py:87: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_3.TestWebRequest testMethod=test_urlencoded_querystring>\nmethod = 'GET', path = '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82'\nheaders = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=MultiDict(), *,\n                     version=HttpVersion(1, 1), closing=False):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, version, headers, closing,\n                                    False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.writer = mock.Mock()\n        self.reader = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_3.py:28: TypeError\n________________ TestWebWebSocket.test_can_start_invalid_method ________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_invalid_method>\n\n    def test_can_start_invalid_method(self):\n>       req = self.make_request('POST', '/')\n\nr2e_tests/test_4.py:118: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_invalid_method>\nmethod = 'POST', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n______________________ TestWebWebSocket.test_can_start_ok ______________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_ok>\n\n    def test_can_start_ok(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_4.py:108: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_ok>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n___________________ TestWebWebSocket.test_can_start_started ____________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_started>\n\n    def test_can_start_started(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_4.py:128: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_started>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n_______________ TestWebWebSocket.test_can_start_unknown_protocol _______________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_unknown_protocol>\n\n    def test_can_start_unknown_protocol(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_4.py:113: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_unknown_protocol>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n_______________ TestWebWebSocket.test_can_start_without_upgrade ________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_without_upgrade>\n\n    def test_can_start_without_upgrade(self):\n>       req = self.make_request('GET', '/', headers=MultiDict())\n\nr2e_tests/test_4.py:123: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_can_start_without_upgrade>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n______________________ TestWebWebSocket.test_double_close ______________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_double_close>\n\n    def test_double_close(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_4.py:163: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_double_close>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n______________________ TestWebWebSocket.test_ping_closing ______________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_ping_closing>\n\n    def test_ping_closing(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_4.py:155: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_ping_closing>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n___________________ TestWebWebSocket.test_send_bytes_closing ___________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_send_bytes_closing>\n\n    def test_send_bytes_closing(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_4.py:147: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_send_bytes_closing>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n__________________ TestWebWebSocket.test_send_bytes_nonbytes ___________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_send_bytes_nonbytes>\n\n    def test_send_bytes_nonbytes(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_4.py:79: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_send_bytes_nonbytes>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n____________________ TestWebWebSocket.test_send_str_closing ____________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_send_str_closing>\n\n    def test_send_str_closing(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_4.py:139: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_send_str_closing>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n___________________ TestWebWebSocket.test_send_str_nonstring ___________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_send_str_nonstring>\n\n    def test_send_str_nonstring(self):\n>       req = self.make_request('GET', '/')\n\nr2e_tests/test_4.py:72: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_send_str_nonstring>\nmethod = 'GET', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n__________________ TestWebWebSocket.test_start_invalid_method __________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_start_invalid_method>\n\n    def test_start_invalid_method(self):\n>       req = self.make_request('POST', '/')\n\nr2e_tests/test_4.py:176: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_start_invalid_method>\nmethod = 'POST', path = '/'\nheaders = <MultiDict>\n[('HOST', 'server.example.com'),\n ('UPGRADE', 'websocket'),\n ('CONNECTION', 'Upgrade'),\n ('SEC-WEBSOCKET-K...),\n ('ORIGIN', 'http://example.com'),\n ('SEC-WEBSOCKET-PROTOCOL', 'chat, superchat'),\n ('SEC-WEBSOCKET-VERSION', '13')]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n_________________ TestWebWebSocket.test_start_without_upgrade __________________\n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_start_without_upgrade>\n\n    def test_start_without_upgrade(self):\n>       req = self.make_request('GET', '/', headers=MultiDict())\n\nr2e_tests/test_4.py:182: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_4.TestWebWebSocket testMethod=test_start_without_upgrade>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method, path, headers=None):\n        self.app = mock.Mock()\n        if headers is None:\n            headers = MultiDict(\n                {'HOST': 'server.example.com',\n                 'UPGRADE': 'websocket',\n                 'CONNECTION': 'Upgrade',\n                 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==',\n                 'ORIGIN': 'http://example.com',\n                 'SEC-WEBSOCKET-PROTOCOL': 'chat, superchat',\n                 'SEC-WEBSOCKET-VERSION': '13'})\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n        self.payload = mock.Mock()\n        self.transport = mock.Mock()\n        self.reader = mock.Mock()\n        self.writer = mock.Mock()\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_4.py:37: TypeError\n______________________ TestHTTPExceptions.test_HTTPFound _______________________\n\nself = <r2e_tests.test_5.TestHTTPExceptions testMethod=test_HTTPFound>\n\n    def test_HTTPFound(self):\n>       req = self.make_request()\n\nr2e_tests/test_5.py:84: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_5.TestHTTPExceptions testMethod=test_HTTPFound>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method='GET', path='/', headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_5.py:37: TypeError\n_________________ TestHTTPExceptions.test_HTTPMethodNotAllowed _________________\n\nself = <r2e_tests.test_5.TestHTTPExceptions testMethod=test_HTTPMethodNotAllowed>\n\n    def test_HTTPMethodNotAllowed(self):\n>       req = self.make_request()\n\nr2e_tests/test_5.py:108: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_5.TestHTTPExceptions testMethod=test_HTTPMethodNotAllowed>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method='GET', path='/', headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_5.py:37: TypeError\n________________________ TestHTTPExceptions.test_HTTPOk ________________________\n\nself = <r2e_tests.test_5.TestHTTPExceptions testMethod=test_HTTPOk>\n\n    def test_HTTPOk(self):\n>       req = self.make_request()\n\nr2e_tests/test_5.py:51: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <r2e_tests.test_5.TestHTTPExceptions testMethod=test_HTTPOk>\nmethod = 'GET', path = '/', headers = <MultiDict>\n[]\n\n    def make_request(self, method='GET', path='/', headers=MultiDict()):\n        self.app = mock.Mock()\n        message = RawRequestMessage(method, path, HttpVersion11, headers,\n                                    False, False)\n>       req = Request(self.app, message, self.payload,\n                      self.transport, self.reader, self.writer)\nE       TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'\n\nr2e_tests/test_5.py:37: TypeError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_cannot_write_eof_before_headers\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_charset_without_content_type\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_content_length\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_content_length_setter\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_ctor\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_default_charset\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_drop_content_length_header_on_setting_len_to_None\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_force_close\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_reset_charset\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_reset_charset_after_setting\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_set_content_length_to_None_on_non_set\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_set_status_with_reason\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_setting_charset\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_setting_content_type\nPASSED r2e_tests/test_1.py::TestStreamResponse::test_write_before_start\nPASSED r2e_tests/test_1.py::TestResponse::test_assign_nonbyteish_body\nPASSED r2e_tests/test_1.py::TestResponse::test_assign_nonstr_text\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor_content_type\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor_text\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor_text_body_combined\nPASSED r2e_tests/test_1.py::TestResponse::test_ctor_with_headers_and_status\nPASSED r2e_tests/test_1.py::TestResponse::test_drain_before_start\nPASSED r2e_tests/test_1.py::TestResponse::test_set_text_with_charset\nPASSED r2e_tests/test_1.py::TestResponse::test_set_text_with_content_type\nPASSED r2e_tests/test_1.py::TestResponse::test_started_when_not_started\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_invalid_path\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_static\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid1\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid2\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid3\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid4\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_invalid5\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_contains\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_double_add_url_with_the_same_name\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_dynamic_not_match\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_dynamic_repr\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_dynamic_with_trailing_slash\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_iter\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_len\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_plain_not_match\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_plain_repr\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_route_dynamic\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_route_plain\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_route_unknown_route_name\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_route_with_qs\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_static_adds_slash\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_static_dont_add__double_slash\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_static_not_match\nPASSED r2e_tests/test_2.py::TestUrlDispatcher::test_static_repr\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_closing_after_ctor\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nested_exception\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_close\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_ping\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_receive\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_send_bytes\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_nonstarted_send_str\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_wait_closed_before_start\nPASSED r2e_tests/test_4.py::TestWebWebSocket::test_write\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_HTTPFound_empty_location\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_all_http_exceptions_exported\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_override_body_with_binary\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_override_body_with_text\nPASSED r2e_tests/test_5.py::TestHTTPExceptions::test_terminal_classes_has_status_code\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_cannot_write_after_eof\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_cannot_write_eof_twice\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_cookie_set_after_del - A...\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_response_cookie__issue_del_cookie\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_response_cookie_path - A...\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_response_cookies - Asser...\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_start - TypeError: __ini...\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_start_force_close - Type...\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_write_non_byteish - Type...\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_write_returns_drain - Ty...\nFAILED r2e_tests/test_1.py::TestStreamResponse::test_write_returns_empty_tuple_on_empty_data\nFAILED r2e_tests/test_1.py::TestResponse::test_render_with_body - TypeError: ...\nFAILED r2e_tests/test_1.py::TestResponse::test_send_headers_for_empty_body - ...\nFAILED r2e_tests/test_1.py::TestResponse::test_send_set_cookie_header - TypeE...\nFAILED r2e_tests/test_1.py::TestResponse::test_started_when_started - TypeErr...\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_root - TypeErro...\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_simple - TypeEr...\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_with_invalid_re\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_with_re - TypeE...\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_with_re_including_slashes\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_route_with_re_not_match\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_url_escaping - TypeEr...\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_with_matchdict - Type...\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_with_name - TypeError...\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_add_with_tailing_slash - ...\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_match_second_result_in_table\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_raise_method_not_allowed\nFAILED r2e_tests/test_2.py::TestUrlDispatcher::test_raise_method_not_found - ...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_POST - TypeError: __init__()...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_calc_content_type_on_getting_charset\nFAILED r2e_tests/test_3.py::TestWebRequest::test_call_POST_on_GET_request - T...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_call_POST_on_weird_content_type\nFAILED r2e_tests/test_3.py::TestWebRequest::test_call_POST_twice - TypeError:...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_content_length - TypeError: ...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_content_type_from_spec - Typ...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_content_type_from_spec_with_charset\nFAILED r2e_tests/test_3.py::TestWebRequest::test_content_type_not_specified\nFAILED r2e_tests/test_3.py::TestWebRequest::test_ctor - TypeError: __init__()...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_match_info - TypeError: __in...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_no_request_cookies - TypeErr...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_non_ascii_path - TypeError: ...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_non_keepalive_on_closing - T...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_non_keepalive_on_http10 - Ty...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_request_cookie - TypeError: ...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_request_cookie__set_item - T...\nFAILED r2e_tests/test_3.py::TestWebRequest::test_urlencoded_querystring - Typ...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_invalid_method\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_ok - TypeError: ...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_started - TypeEr...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_unknown_protocol\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_can_start_without_upgrade\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_double_close - TypeError: ...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_ping_closing - TypeError: ...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_send_bytes_closing - TypeE...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_send_bytes_nonbytes - Type...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_send_str_closing - TypeErr...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_send_str_nonstring - TypeE...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_start_invalid_method - Typ...\nFAILED r2e_tests/test_4.py::TestWebWebSocket::test_start_without_upgrade - Ty...\nFAILED r2e_tests/test_5.py::TestHTTPExceptions::test_HTTPFound - TypeError: _...\nFAILED r2e_tests/test_5.py::TestHTTPExceptions::test_HTTPMethodNotAllowed - T...\nFAILED r2e_tests/test_5.py::TestHTTPExceptions::test_HTTPOk - TypeError: __in...\n======================== 62 failed, 64 passed in 0.98s =========================\n",
    "old_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d2fbdefd269d4d79e54c703d636269bf52505bfb/.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/web.py tests/test_urldispatch.py tests/test_web_exceptions.py tests/test_web_request.py tests/test_web_response.py tests/test_web_websocket.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Request Constructor Fails with TypeError Due to Missing `keep_alive_timeout` Parameter

**Description:**
After recent changes, initializing a `Request` object without the `keep_alive_timeout` parameter results in a `TypeError`. The constructor no longer expects `keep_alive_timeout`, but existing code attempts to create `Request` instances without providing this argument, leading to failures.

**Example Code:**
```python
def make_request():
    req = Request(app, message, payload, transport, reader, writer)
    # Previously included keep_alive_timeout parameter
```

**Expected Behavior:**
`Request` objects should be instantiated without the need for the `keep_alive_timeout` parameter, aligning with the updated constructor definition.

**Actual Behavior:**
A `TypeError` is raised stating that `__init__()` is missing the required positional argument: `keep_alive_timeout`.
```
TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'
```
[/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/web.py
import abc
import asyncio
import binascii
import collections
import mimetypes
import cgi
import http.cookies
import io
import json
import re
import os

from urllib.parse import urlsplit, parse_qsl, urlencode, unquote

from .abc import AbstractRouter, AbstractMatchInfo
from .helpers import reify
from .log import web_logger
from .multidict import (CaseInsensitiveMultiDict,
                        CaseInsensitiveMutableMultiDict,
                        MultiDict,
                        MutableMultiDict)
from .protocol import Response as ResponseImpl, HttpVersion, HttpVersion11
from .server import ServerHttpProtocol
from .streams import EOF_MARKER
from .websocket import do_handshake, MSG_BINARY, MSG_CLOSE, MSG_PING, MSG_TEXT
from .errors import HttpProcessingError, WebSocketDisconnectedError


__all__ = [
    'WebSocketDisconnectedError',
    'Application',
    'HttpVersion',
    'RequestHandler',
    'RequestHandlerFactory',
    'Request',
    'StreamResponse',
    'Response',
    'WebSocketResponse',
    'UrlDispatcher',
    'UrlMappingMatchInfo',
    'HTTPException',
    'HTTPError',
    'HTTPRedirection',
    'HTTPSuccessful',
    'HTTPOk',
    'HTTPCreated',
    'HTTPAccepted',
    'HTTPNonAuthoritativeInformation',
    'HTTPNoContent',
    'HTTPResetContent',
    'HTTPPartialContent',
    'HTTPMultipleChoices',
    'HTTPMovedPermanently',
    'HTTPFound',
    'HTTPSeeOther',
    'HTTPNotModified',
    'HTTPUseProxy',
    'HTTPTemporaryRedirect',
    'HTTPClientError',
    'HTTPBadRequest',
    'HTTPUnauthorized',
    'HTTPPaymentRequired',
    'HTTPForbidden',
    'HTTPNotFound',
    'HTTPMethodNotAllowed',
    'HTTPNotAcceptable',
    'HTTPProxyAuthenticationRequired',
    'HTTPRequestTimeout',
    'HTTPConflict',
    'HTTPGone',
    'HTTPLengthRequired',
    'HTTPPreconditionFailed',
    'HTTPRequestEntityTooLarge',
    'HTTPRequestURITooLong',
    'HTTPUnsupportedMediaType',
    'HTTPRequestRangeNotSatisfiable',
    'HTTPExpectationFailed',
    'HTTPServerError',
    'HTTPInternalServerError',
    'HTTPNotImplemented',
    'HTTPBadGateway',
    'HTTPServiceUnavailable',
    'HTTPGatewayTimeout',
    'HTTPVersionNotSupported',
]


sentinel = object()


class HeadersMixin:

    _content_type = None
    _content_dict = None
    _stored_content_type = sentinel

    def _parse_content_type(self, raw):
        self._stored_content_type = raw
        if raw is None:
            # default value according to RFC 2616
            self._content_type = 'application/octet-stream'
            self._content_dict = {}
        else:
            self._content_type, self._content_dict = cgi.parse_header(raw)

    @property
    def content_type(self):
        """The value of content part for Content-Type HTTP header."""
        raw = self.headers.get('Content-Type')
        if self._stored_content_type != raw:
            self._parse_content_type(raw)
        return self._content_type

    @property
    def charset(self):
        """The value of charset part for Content-Type HTTP header."""
        raw = self.headers.get('Content-Type')
        if self._stored_content_type != raw:
            self._parse_content_type(raw)
        return self._content_dict.get('charset')

    @property
    def content_length(self):
        """The value of Content-Length HTTP header."""
        l = self.headers.get('Content-Length')
        if l is None:
            return None
        else:
            return int(l)


FileField = collections.namedtuple('Field', 'name filename file content_type')


############################################################
# HTTP Request
############################################################


class Request(HeadersMixin):

    def __init__(self, app, message, payload, transport, reader, writer,
                 keep_alive_timeout):
        self._app = app
        self._version = message.version
        self._transport = transport
        self._reader = reader
        self._writer = writer
        self._method = message.method
        self._host = message.headers.get('HOST')
        self._path_qs = message.path
        res = urlsplit(message.path)
        self._path = unquote(res.path)
        self._query_string = res.query
        self._post = None
        self._post_files_cache = None
        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(
            message.headers)

        if self._version < HttpVersion11:
            self._keep_alive = False
        elif message.should_close:
            self._keep_alive = False
        else:
            self._keep_alive = bool(keep_alive_timeout)

        # matchdict, route_name, handler
        # or information about traversal lookup
        self._match_info = None  # initialized after route resolving

        self._payload = payload
        self._cookies = None

    @property
    def method(self):
        """Read only property for getting HTTP method.

        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.
        """
        return self._method

    @property
    def version(self):
        """Read only property for getting HTTP version of request.

        Returns aiohttp.protocol.HttpVersion instance.
        """
        return self._version

    @property
    def host(self):
        """Read only property for getting *HOST* header of request.

        Returns str or None if HTTP request has no HOST header.
        """
        return self._host

    @property
    def path_qs(self):
        """The URL including PATH_INFO and the query string.

        E.g, /app/blog?id=10
        """
        return self._path_qs

    @property
    def path(self):
        """The URL including *PATH INFO* without the host or scheme.

        E.g., ``/app/blog``
        """
        return self._path

    @property
    def query_string(self):
        """The query string in the URL.

        E.g., id=10
        """
        return self._query_string

    @reify
    def GET(self):
        """A multidict with all the variables in the query string.

        Lazy property.
        """
        return MultiDict(parse_qsl(self._query_string))

    @reify
    def POST(self):
        """A multidict with all the variables in the POST parameters.

        post() methods has to be called before using this attribute.
        """
        if self._post is None:
            raise RuntimeError("POST is not available before post()")
        return self._post

    @property
    def headers(self):
        """A case-insensitive multidict with all headers.

        Lazy property.
        """
        return self._headers

    @property
    def keep_alive(self):
        """Is keepalive enabled by client?"""
        return self._keep_alive

    @property
    def match_info(self):
        """Result of route resolving."""
        return self._match_info

    @property
    def app(self):
        """Application instance."""
        return self._app

    @property
    def transport(self):
        """Transport used for request processing."""
        return self._transport

    @property
    def cookies(self):
        """Return request cookies.

        A read-only dictionary-like object.
        """
        if self._cookies is None:
            raw = self.headers.get('COOKIE', '')
            parsed = http.cookies.SimpleCookie(raw)
            self._cookies = MultiDict({key: val.value
                                       for key, val in parsed.items()})
        return self._cookies

    @property
    def payload(self):
        """Return raw paiload stream."""
        return self._payload

    @asyncio.coroutine
    def release(self):
        """Release request.

        Eat unread part of HTTP BODY if present.
        """
        chunk = yield from self._payload.readany()
        while chunk is not EOF_MARKER or chunk:
            chunk = yield from self._payload.readany()

    @asyncio.coroutine
    def read(self):
        """Read request body if present.

        Returns bytes object with full request content.
        """
        body = bytearray()
        while True:
            chunk = yield from self._payload.readany()
            body.extend(chunk)
            if chunk is EOF_MARKER:
                break
        return bytes(body)

    @asyncio.coroutine
    def text(self):
        """Return BODY as text using encoding from .charset."""
        bytes_body = yield from self.read()
        encoding = self.charset or 'utf-8'
        return bytes_body.decode(encoding)

    @asyncio.coroutine
    def json(self, *, loader=json.loads):
        """Return BODY as JSON."""
        body = yield from self.text()
        return loader(body)

    @asyncio.coroutine
    def post(self):
        """Return POST parameters."""
        if self._post is not None:
            return self._post
        if self.method not in ('POST', 'PUT', 'PATCH'):
            self._post = MultiDict()
            return self._post

        content_type = self.content_type
        if (content_type not in ('',
                                 'application/x-www-form-urlencoded',
                                 'multipart/form-data')):
            self._post = MultiDict()
            return self._post

        body = yield from self.read()
        content_charset = self.charset or 'utf-8'

        environ = {'REQUEST_METHOD': self.method,
                   'CONTENT_LENGTH': str(len(body)),
                   'QUERY_STRING': '',
                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}

        fs = cgi.FieldStorage(fp=io.BytesIO(body),
                              environ=environ,
                              keep_blank_values=True,
                              encoding=content_charset)

        supported_tranfer_encoding = {
            'base64': binascii.a2b_base64,
            'quoted-printable': binascii.a2b_qp
        }

        out = MutableMultiDict()
        for field in fs.list or ():
            transfer_encoding = field.headers.get(
                'Content-Transfer-Encoding', None)
            if field.filename:
                ff = FileField(field.name,
                               field.filename,
                               field.file,  # N.B. file closed error
                               field.type)
                if self._post_files_cache is None:
                    self._post_files_cache = {}
                self._post_files_cache[field.name] = field
                out.add(field.name, ff)
            else:
                value = field.value
                if transfer_encoding in supported_tranfer_encoding:
                    # binascii accepts bytes
                    value = value.encode('utf-8')
                    value = supported_tranfer_encoding[
                        transfer_encoding](value)
                out.add(field.name, value)

        self._post = MultiDict(out.items(getall=True))
        return self._post


############################################################
# HTTP Response classes
############################################################


class StreamResponse(HeadersMixin):

    def __init__(self, *, status=200, reason=None):
        self._body = None
        self._keep_alive = None
        self._headers = CaseInsensitiveMutableMultiDict()
        self._cookies = http.cookies.SimpleCookie()
        self.set_status(status, reason)

        self._req = None
        self._resp_impl = None
        self._eof_sent = False

    def _copy_cookies(self):
        for cookie in self._cookies.values():
            value = cookie.output(header='')[1:]
            self.headers.add('Set-Cookie', value)

    @property
    def started(self):
        return self._resp_impl is not None

    @property
    def status(self):
        return self._status

    @property
    def reason(self):
        return self._reason

    def set_status(self, status, reason=None):
        self._status = int(status)
        if reason is None:
            reason = ResponseImpl.calc_reason(status)
        self._reason = reason

    @property
    def keep_alive(self):
        return self._keep_alive

    def force_close(self):
        self._keep_alive = False

    @property
    def headers(self):
        return self._headers

    @property
    def cookies(self):
        return self._cookies

    def set_cookie(self, name, value, *, expires=None,
                   domain=None, max_age=None, path=None,
                   secure=None, httponly=None, version=None):
        """Set or update response cookie.

        Sets new cookie or updates existent with new value.
        Also updates only those params which are not None.
        """

        old = self._cookies.get(name)
        if old is not None and old.coded_value == '':
            # deleted cookie
            self._cookies.pop(name, None)

        self._cookies[name] = value
        c = self._cookies[name]
        if expires is not None:
            c['expires'] = expires
        if domain is not None:
            c['domain'] = domain
        if max_age is not None:
            c['max-age'] = max_age
        if path is not None:
            c['path'] = path
        if secure is not None:
            c['secure'] = secure
        if httponly is not None:
            c['httponly'] = httponly
        if version is not None:
            c['version'] = version

    def del_cookie(self, name, *, domain=None, path=None):
        """Delete cookie.

        Creates new empty expired cookie.
        """
        # TODO: do we need domain/path here?
        self._cookies.pop(name, None)
        self.set_cookie(name, '', max_age=0, domain=domain, path=path)

    @property
    def content_length(self):
        # Just a placeholder for adding setter
        return super().content_length

    @content_length.setter
    def content_length(self, value):
        if value is not None:
            value = int(value)
            # TODO: raise error if chunked enabled
            self.headers['Content-Length'] = str(value)
        elif 'Content-Length' in self.headers:
            del self.headers['Content-Length']

    @property
    def content_type(self):
        # Just a placeholder for adding setter
        return super().content_type

    @content_type.setter
    def content_type(self, value):
        self.content_type  # read header values if needed
        self._content_type = str(value)
        self._generate_content_type_header()

    @property
    def charset(self):
        # Just a placeholder for adding setter
        return super().charset

    @charset.setter
    def charset(self, value):
        ctype = self.content_type  # read header values if needed
        if ctype == 'application/octet-stream':
            raise RuntimeError("Setting charset for application/octet-stream "
                               "doesn't make sense, setup content_type first")
        if value is None:
            self._content_dict.pop('charset', None)
        else:
            self._content_dict['charset'] = str(value).lower()
        self._generate_content_type_header()

    def _generate_content_type_header(self):
        params = '; '.join("%s=%s" % i for i in self._content_dict.items())
        if params:
            ctype = self._content_type + '; ' + params
        else:
            ctype = self._content_type
        self.headers['Content-Type'] = ctype

    def _start_pre_check(self, request):
        if self._resp_impl is not None:
            if self._req is not request:
                raise RuntimeError(
                    'Response has been started with different request.')
            else:
                return self._resp_impl
        else:
            return None

    def start(self, request):
        resp_impl = self._start_pre_check(request)
        if resp_impl is not None:
            return resp_impl

        self._req = request
        keep_alive = self._keep_alive
        if keep_alive is None:
            keep_alive = request.keep_alive
        self._keep_alive = keep_alive

        resp_impl = self._resp_impl = ResponseImpl(
            request._writer,
            self._status,
            request.version,
            not keep_alive,
            self._reason)

        self._copy_cookies()

        headers = self.headers.items(getall=True)
        for key, val in headers:
            resp_impl.add_header(key, val)

        resp_impl.send_headers()
        return resp_impl

    def write(self, data):
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError('data argument must be byte-ish (%r)',
                            type(data))

        if self._eof_sent:
            raise RuntimeError("Cannot call write() after write_eof()")
        if self._resp_impl is None:
            raise RuntimeError("Cannot call write() before start()")

        if data:
            return self._resp_impl.write(data)
        else:
            return ()

    @asyncio.coroutine
    def drain(self):
        if self._resp_impl is None:
            raise RuntimeError("Response has not been started")
        yield from self._resp_impl.transport.drain()

    @asyncio.coroutine
    def write_eof(self):
        if self._eof_sent:
            return
        if self._resp_impl is None:
            raise RuntimeError("Response has not been started")

        yield from self._resp_impl.write_eof()
        self._eof_sent = True


class Response(StreamResponse):

    def __init__(self, *, body=None, status=200,
                 reason=None, headers=None,
                 text=None, content_type=None):
        super().__init__(status=status, reason=reason)

        if headers is not None:
            self.headers.extend(headers)
        if content_type:
            self.content_type = content_type

        if body is not None and text is not None:
            raise ValueError("body and text are not allowed together.")
        elif body is not None:
            self.body = body
        elif text is not None:
            self.text = text
        else:
            self.body = None

    @property
    def body(self):
        return self._body

    @body.setter
    def body(self, body):
        if body is not None and not isinstance(body, bytes):
            raise TypeError('body argument must be bytes (%r)', type(body))
        self._body = body
        if body is not None:
            self.content_length = len(body)
        else:
            self.content_length = 0

    @property
    def text(self):
        return self._body.decode(self.charset or 'utf-8')

    @text.setter
    def text(self, text):
        if text is not None and not isinstance(text, str):
            raise TypeError('text argument must be str (%r)', type(text))

        if self.content_type == 'application/octet-stream':
            self.content_type = 'text/plain'
        if self.charset is None:
            self.charset = 'utf-8'

        self.body = text.encode(self.charset)

    @asyncio.coroutine
    def write_eof(self):
        body = self._body
        if body is not None:
            self.write(body)
        yield from super().write_eof()


class WebSocketResponse(StreamResponse):

    def __init__(self, *, protocols=()):
        super().__init__(status=101)
        self._protocols = protocols
        self._protocol = None
        self._writer = None
        self._reader = None
        self._closing = False
        self._loop = None
        self._closing_fut = None

    def start(self, request):
        # make pre-check to don't hide it by do_handshake() exceptions
        resp_impl = self._start_pre_check(request)
        if resp_impl is not None:
            return resp_impl

        try:
            status, headers, parser, writer, protocol = do_handshake(
                request.method, request.headers, request.transport,
                self._protocols)
        except HttpProcessingError as err:
            if err.code == 405:
                raise HTTPMethodNotAllowed(request.method, ['GET'])
            elif err.code == 400:
                raise HTTPBadRequest(text=err.message)
            else:  # pragma: no cover
                raise HTTPInternalServerError() from err

        if self.status != status:
            self.set_status(status)
        for k, v in headers:
            self.headers[k] = v
        self.force_close()

        resp_impl = super().start(request)

        self._reader = request._reader.set_parser(parser)
        self._writer = writer
        self._protocol = protocol
        self._loop = request.app.loop
        self._closing_fut = asyncio.Future(loop=self._loop)

        return resp_impl

    def can_start(self, request):
        if self._writer is not None:
            raise RuntimeError('Already started')
        try:
            _, _, _, _, protocol = do_handshake(
                request.method, request.headers, request.transport,
                self._protocols)
        except HttpProcessingError:
            return False, None
        else:
            return True, protocol

    @property
    def closing(self):
        return self._closing

    @property
    def protocol(self):
        return self._protocol

    def ping(self):
        if self._writer is None:
            raise RuntimeError('Call .start() first')
        if self._closing:
            raise RuntimeError('websocket connection is closing')
        self._writer.ping()

    def send_str(self, data):
        if self._writer is None:
            raise RuntimeError('Call .start() first')
        if self._closing:
            raise RuntimeError('websocket connection is closing')
        if not isinstance(data, str):
            raise TypeError('data argument must be str (%r)', type(data))
        self._writer.send(data, binary=False)

    def send_bytes(self, data):
        if self._writer is None:
            raise RuntimeError('Call .start() first')
        if self._closing:
            raise RuntimeError('websocket connection is closing')
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError('data argument must be byte-ish (%r)',
                            type(data))
        self._writer.send(data, binary=True)

    def close(self, *, code=1000, message=b''):
        if self._writer is None:
            raise RuntimeError('Call .start() first')
        if not self._closing:
            self._closing = True
            self._writer.close(code, message)
        else:
            raise RuntimeError('Already closing')

    @asyncio.coroutine
    def wait_closed(self):
        if self._closing_fut is None:
            raise RuntimeError('Call .start() first')
        yield from self._closing_fut

    @asyncio.coroutine
    def receive(self):
        if self._reader is None:
            raise RuntimeError('Call .start() first')
        while True:
            msg = yield from self._reader.read()

            if msg.tp == MSG_CLOSE:
                if self._closing:
                    exc = WebSocketDisconnectedError(msg.data, msg.extra)
                    self._closing_fut.set_exception(exc)
                    raise exc
                else:
                    self._closing = True
                    self._writer.close(msg.data, msg.extra)
                    yield from self.drain()
                    exc = WebSocketDisconnectedError(msg.data, msg.extra)
                    self._closing_fut.set_exception(exc)
                    raise exc
            elif not self._closing:
                if msg.tp == MSG_PING:
                    self._writer.pong()
                elif msg.tp == MSG_TEXT:
                    return msg.data
                elif msg.tp == MSG_BINARY:
                    return msg.data

    def write(self, data):
        raise RuntimeError("Cannot call .write() for websocket")


############################################################
# HTTP Exceptions
############################################################

class HTTPException(Response, Exception):

    # You should set in subclasses:
    # status = 200

    status_code = None

    def __init__(self, *, headers=None, reason=None,
                 body=None, text=None, content_type=None):
        Response.__init__(self, status=self.status_code,
                          headers=headers, reason=reason,
                          body=body, text=text, content_type=content_type)
        Exception.__init__(self, self.reason)
        if self.body is None:
            self.text = "{}: {}".format(self.status, self.reason)


class HTTPError(HTTPException):
    """Base class for exceptions with status codes in the 400s and 500s."""


class HTTPRedirection(HTTPException):
    """Base class for exceptions with status codes in the 300s."""


class HTTPSuccessful(HTTPException):
    """Base class for exceptions with status codes in the 200s."""


class HTTPOk(HTTPSuccessful):
    status_code = 200


class HTTPCreated(HTTPSuccessful):
    status_code = 201


class HTTPAccepted(HTTPSuccessful):
    status_code = 202


class HTTPNonAuthoritativeInformation(HTTPSuccessful):
    status_code = 203


class HTTPNoContent(HTTPSuccessful):
    status_code = 204


class HTTPResetContent(HTTPSuccessful):
    status_code = 205


class HTTPPartialContent(HTTPSuccessful):
    status_code = 206


############################################################
# 3xx redirection
############################################################


class _HTTPMove(HTTPRedirection):

    def __init__(self, location, *, headers=None, reason=None,
                 body=None, text=None, content_type=None):
        if not location:
            raise ValueError("HTTP redirects need a location to redirect to.")
        super().__init__(headers=headers, reason=reason,
                         body=body, text=text, content_type=content_type)
        self.headers['Location'] = location
        self.location = location


class HTTPMultipleChoices(_HTTPMove):
    status_code = 300


class HTTPMovedPermanently(_HTTPMove):
    status_code = 301


class HTTPFound(_HTTPMove):
    status_code = 302


# This one is safe after a POST (the redirected location will be
# retrieved with GET):
class HTTPSeeOther(_HTTPMove):
    status_code = 303


class HTTPNotModified(HTTPRedirection):
    # FIXME: this should include a date or etag header
    status_code = 304


class HTTPUseProxy(_HTTPMove):
    # Not a move, but looks a little like one
    status_code = 305


class HTTPTemporaryRedirect(_HTTPMove):
    status_code = 307


############################################################
# 4xx client error
############################################################


class HTTPClientError(HTTPError):
    pass


class HTTPBadRequest(HTTPClientError):
    status_code = 400


class HTTPUnauthorized(HTTPClientError):
    status_code = 401


class HTTPPaymentRequired(HTTPClientError):
    status_code = 402


class HTTPForbidden(HTTPClientError):
    status_code = 403


class HTTPNotFound(HTTPClientError):
    status_code = 404


class HTTPMethodNotAllowed(HTTPClientError):
    status_code = 405

    def __init__(self, method, allowed_methods, *, headers=None, reason=None,
                 body=None, text=None, content_type=None):
        allow = ','.join(sorted(allowed_methods))
        super().__init__(headers=headers, reason=reason,
                         body=body, text=text, content_type=content_type)
        self.headers['Allow'] = allow
        self.allowed_methods = allowed_methods
        self.method = method.upper()


class HTTPNotAcceptable(HTTPClientError):
    status_code = 406


class HTTPProxyAuthenticationRequired(HTTPClientError):
    status_code = 407


class HTTPRequestTimeout(HTTPClientError):
    status_code = 408


class HTTPConflict(HTTPClientError):
    status_code = 409


class HTTPGone(HTTPClientError):
    status_code = 410


class HTTPLengthRequired(HTTPClientError):
    status_code = 411


class HTTPPreconditionFailed(HTTPClientError):
    status_code = 412


class HTTPRequestEntityTooLarge(HTTPClientError):
    status_code = 413


class HTTPRequestURITooLong(HTTPClientError):
    status_code = 414


class HTTPUnsupportedMediaType(HTTPClientError):
    status_code = 415


class HTTPRequestRangeNotSatisfiable(HTTPClientError):
    status_code = 416


class HTTPExpectationFailed(HTTPClientError):
    status_code = 417


############################################################
# 5xx Server Error
############################################################
#  Response status codes beginning with the digit "5" indicate cases in
#  which the server is aware that it has erred or is incapable of
#  performing the request. Except when responding to a HEAD request, the
#  server SHOULD include an entity containing an explanation of the error
#  situation, and whether it is a temporary or permanent condition. User
#  agents SHOULD display any included entity to the user. These response
#  codes are applicable to any request method.


class HTTPServerError(HTTPError):
    pass


class HTTPInternalServerError(HTTPServerError):
    status_code = 500


class HTTPNotImplemented(HTTPServerError):
    status_code = 501


class HTTPBadGateway(HTTPServerError):
    status_code = 502


class HTTPServiceUnavailable(HTTPServerError):
    status_code = 503


class HTTPGatewayTimeout(HTTPServerError):
    status_code = 504


class HTTPVersionNotSupported(HTTPServerError):
    status_code = 505


############################################################
# UrlDispatcher implementation
############################################################


class UrlMappingMatchInfo(dict, AbstractMatchInfo):

    def __init__(self, match_dict, route):
        super().__init__(match_dict)
        self._route = route

    @property
    def handler(self):
        return self._route.handler

    @property
    def route(self):
        return self._route


class Route(metaclass=abc.ABCMeta):

    def __init__(self, method, handler, name):
        self._method = method
        self._handler = handler
        self._name = name

    @property
    def method(self):
        return self._method

    @property
    def handler(self):
        return self._handler

    @property
    def name(self):
        return self._name

    @abc.abstractmethod
    def match(self, path):
        """Return dict with info for given path or
        None if route cannot process path."""

    @abc.abstractmethod
    def url(self, **kwargs):
        """Construct url for route with additional params."""

    @staticmethod
    def _append_query(url, query):
        if query is not None:
            return url + "?" + urlencode(query)
        else:
            return url


class PlainRoute(Route):

    def __init__(self, method, handler, name, path):
        super().__init__(method, handler, name)
        self._path = path

    def match(self, path):
        # string comparsion about 10 times faster than regexp matching
        if self._path == path:
            return {}
        else:
            return None

    def url(self, *, query=None):
        return self._append_query(self._path, query)

    def __repr__(self):
        name = "'" + self.name + "' " if self.name is not None else ""
        return "<PlainRoute {name}[{method}] {path} -> {handler!r}".format(
            name=name, method=self.method, path=self._path,
            handler=self.handler)


class DynamicRoute(Route):

    def __init__(self, method, handler, name, pattern, formatter):
        super().__init__(method, handler, name)
        self._pattern = pattern
        self._formatter = formatter

    def match(self, path):
        match = self._pattern.match(path)
        if match is None:
            return None
        else:
            return match.groupdict()

    def url(self, *, parts, query=None):
        url = self._formatter.format_map(parts)
        return self._append_query(url, query)

    def __repr__(self):
        name = "'" + self.name + "' " if self.name is not None else ""
        return ("<DynamicRoute {name}[{method}] {formatter} -> {handler!r}"
                .format(name=name, method=self.method,
                        formatter=self._formatter, handler=self.handler))


class StaticRoute(Route):

    def __init__(self, name, prefix, directory):
        assert prefix.startswith('/'), prefix
        assert prefix.endswith('/'), prefix
        super().__init__('GET', self.handle, name)
        self._prefix = prefix
        self._prefix_len = len(self._prefix)
        self._directory = directory

    def match(self, path):
        if not path.startswith(self._prefix):
            return None
        return {'filename': path[self._prefix_len:]}

    def url(self, *, filename, query=None):
        while filename.startswith('/'):
            filename = filename[1:]
        url = self._prefix + filename
        return self._append_query(url, query)

    @asyncio.coroutine
    def handle(self, request):
        resp = StreamResponse()
        filename = request.match_info['filename']
        filepath = os.path.join(self._directory, filename)
        if '..' in filename:
            raise HTTPNotFound()
        if not os.path.exists(filepath) or not os.path.isfile(filepath):
            raise HTTPNotFound()

        ct = mimetypes.guess_type(filename)[0]
        if not ct:
            ct = 'application/octet-stream'
        resp.content_type = ct

        resp.headers['transfer-encoding'] = 'chunked'
        resp.start(request)

        with open(filepath, 'rb') as f:
            chunk = f.read(8192)
            while chunk:
                resp.write(chunk)
                chunk = f.read(8192)

        yield from resp.write_eof()
        return resp

    def __repr__(self):
        name = "'" + self.name + "' " if self.name is not None else ""
        return "<StaticRoute {name}[{method}] {path} -> {directory!r}".format(
            name=name, method=self.method, path=self._prefix,
            directory=self._directory)


class UrlDispatcher(AbstractRouter, collections.abc.Mapping):

    DYN = re.compile(r'^\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*)\}$')
    DYN_WITH_RE = re.compile(
        r'^\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*):(?P<re>.+)\}$')
    GOOD = r'[^{}/]+'
    PLAIN = re.compile('^' + GOOD + '$')

    METHODS = {'POST', 'GET', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'}

    def __init__(self):
        super().__init__()
        self._urls = []
        self._routes = {}

    @asyncio.coroutine
    def resolve(self, request):
        path = request.path
        method = request.method
        allowed_methods = set()
        for route in self._urls:
            match_dict = route.match(path)
            if match_dict is None:
                continue
            route_method = route.method
            if route_method != method:
                allowed_methods.add(route_method)
            else:
                return UrlMappingMatchInfo(match_dict, route)
        else:
            if allowed_methods:
                raise HTTPMethodNotAllowed(method, allowed_methods)
            else:
                raise HTTPNotFound()

    def __iter__(self):
        return iter(self._routes)

    def __len__(self):
        return len(self._routes)

    def __contains__(self, name):
        return name in self._routes

    def __getitem__(self, name):
        return self._routes[name]

    def _register_endpoint(self, route):
        name = route.name
        if name is not None:
            if name in self._routes:
                raise ValueError('Duplicate {!r}, '
                                 'already handled by {!r}'
                                 .format(name, self._routes[name]))
            else:
                self._routes[name] = route
        self._urls.append(route)

    def add_route(self, method, path, handler, *, name=None):
        assert path.startswith('/')
        assert callable(handler), handler
        if not asyncio.iscoroutinefunction(handler):
            handler = asyncio.coroutine(handler)
        method = method.upper()
        assert method in self.METHODS, method
        parts = []
        factory = PlainRoute
        for part in path.split('/'):
            if not part:
                continue
            match = self.DYN.match(part)
            if match:
                parts.append('(?P<' + match.group('var') + '>' +
                             self.GOOD + ')')
                factory = DynamicRoute
                continue

            match = self.DYN_WITH_RE.match(part)
            if match:
                parts.append('(?P<' + match.group('var') + '>' +
                             match.group('re') + ')')
                factory = DynamicRoute
                continue
            if self.PLAIN.match(part):
                parts.append(re.escape(part))
                continue
            raise ValueError("Invalid path '{}'['{}']".format(path, part))
        if factory is PlainRoute:
            route = PlainRoute(method, handler, name, path)
        else:
            pattern = '/' + '/'.join(parts)
            if path.endswith('/') and pattern != '/':
                pattern += '/'
            try:
                compiled = re.compile('^' + pattern + '$')
            except re.error as exc:
                raise ValueError(
                    "Bad pattern '{}': {}".format(pattern, exc)) from None
            route = DynamicRoute(method, handler, name, compiled, path)
        self._register_endpoint(route)
        return route

    def add_static(self, prefix, path, *, name=None):
        """
        Adds static files view
        :param prefix - url prefix
        :param path - folder with files
        """
        assert prefix.startswith('/')
        assert os.path.isdir(path), 'Path does not directory %s' % path
        path = os.path.abspath(path)
        if not prefix.endswith('/'):
            prefix += '/'
        route = StaticRoute(name, prefix, path)
        self._register_endpoint(route)
        return route


############################################################
# Application implementation
############################################################


class RequestHandler(ServerHttpProtocol):

    def __init__(self, manager, app, router, **kwargs):
        super().__init__(**kwargs)

        self._manager = manager
        self._app = app
        self._router = router
        self._middlewares = app.middlewares

    def connection_made(self, transport):
        super().connection_made(transport)

        self._manager.connection_made(self, transport)

    def connection_lost(self, exc):
        self._manager.connection_lost(self, exc)

        super().connection_lost(exc)

    @asyncio.coroutine
    def handle_request(self, message, payload):
        now = self._loop.time()

        app = self._app
        request = Request(app, message, payload,
                          self.transport, self.reader, self.writer,
                          self.keep_alive_timeout)
        try:
            match_info = yield from self._router.resolve(request)

            assert isinstance(match_info, AbstractMatchInfo), match_info

            request._match_info = match_info
            handler = match_info.handler

            for factory in reversed(self._middlewares):
                handler = yield from factory(app, handler)
            resp = yield from handler(request)

            if not isinstance(resp, StreamResponse):
                raise RuntimeError(
                    ("Handler {!r} should return response instance, "
                     "got {!r} [middlewares {!r}]").format(
                         match_info.handler,
                         type(resp),
                         self._middlewares))
        except HTTPException as exc:
            resp = exc

        resp_msg = resp.start(request)
        yield from resp.write_eof()

        # notify server about keep-alive
        self.keep_alive(resp_msg.keep_alive())

        # log access
        self.log_access(message, None, resp_msg, self._loop.time() - now)


class RequestHandlerFactory:

    def __init__(self, app, router, *,
                 handler=RequestHandler, loop=None, **kwargs):
        self._app = app
        self._router = router
        self._handler = handler
        self._loop = loop
        self._connections = {}
        self._kwargs = kwargs
        self._kwargs.setdefault('logger', app.logger)

    @property
    def connections(self):
        return list(self._connections.keys())

    def connection_made(self, handler, transport):
        self._connections[handler] = transport

    def connection_lost(self, handler, exc=None):
        if handler in self._connections:
            del self._connections[handler]

    @asyncio.coroutine
    def finish_connections(self, timeout=None):
        for handler in self._connections.keys():
            handler.closing()

        def cleanup():
            sleep = 0.05
            while self._connections:
                yield from asyncio.sleep(sleep, loop=self._loop)
                if sleep < 5:
                    sleep = sleep * 2

        if timeout:
            try:
                yield from asyncio.wait_for(
                    cleanup(), timeout, loop=self._loop)
            except asyncio.TimeoutError:
                self._app.logger.warning(
                    "Not all connections are closed (pending: %d)",
                    len(self._connections))

        for transport in self._connections.values():
            transport.close()

        self._connections.clear()

    def __call__(self):
        return self._handler(
            self, self._app, self._router, loop=self._loop, **self._kwargs)


class Application(dict):

    def __init__(self, *, logger=web_logger, loop=None,
                 router=None, handler_factory=RequestHandlerFactory,
                 middlewares=(), **kwargs):
        if loop is None:
            loop = asyncio.get_event_loop()
        if router is None:
            router = UrlDispatcher()
        assert isinstance(router, AbstractRouter), router

        self._router = router
        self._handler_factory = handler_factory
        self._finish_callbacks = []
        self._loop = loop
        self.logger = logger

        self.update(**kwargs)
        for factory in middlewares:
            assert asyncio.iscoroutinefunction(factory), factory
        self._middlewares = tuple(middlewares)

    @property
    def router(self):
        return self._router

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

    @property
    def middlewares(self):
        return self._middlewares

    def make_handler(self, **kwargs):
        return self._handler_factory(
            self, self.router, loop=self.loop, **kwargs)

    @asyncio.coroutine
    def finish(self):
        callbacks = self._finish_callbacks
        self._finish_callbacks = []

        for (cb, args, kwargs) in callbacks:
            try:
                res = cb(self, *args, **kwargs)
                if (asyncio.iscoroutine(res) or
                        isinstance(res, asyncio.Future)):
                    yield from res
            except Exception as exc:
                self._loop.call_exception_handler({
                    'message': "Error in finish callback",
                    'exception': exc,
                    'application': self,
                })

    def register_on_finish(self, func, *args, **kwargs):
        self._finish_callbacks.insert(0, (func, args, kwargs))

```
--- 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:** Request Constructor Fails with TypeError Due to Missing `keep_alive_timeout` Parameter

**Description:**
After recent changes, initializing a `Request` object without the `keep_alive_timeout` parameter results in a `TypeError`. The constructor no longer expects `keep_alive_timeout`, but existing code attempts to create `Request` instances without providing this argument, leading to failures.

**Example Code:**
```python
def make_request():
    req = Request(app, message, payload, transport, reader, writer)
    # Previously included keep_alive_timeout parameter
```

**Expected Behavior:**
`Request` objects should be instantiated without the need for the `keep_alive_timeout` parameter, aligning with the updated constructor definition.

**Actual Behavior:**
A `TypeError` is raised stating that `__init__()` is missing the required positional argument: `keep_alive_timeout`.
```
TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'
```
[/ISSUE]
{
    "TestStreamResponse.test_cannot_write_after_eof": "PASSED",
    "TestStreamResponse.test_cannot_write_eof_before_headers": "PASSED",
    "TestStreamResponse.test_cannot_write_eof_twice": "PASSED",
    "TestStreamResponse.test_charset_without_content_type": "PASSED",
    "TestStreamResponse.test_content_length": "PASSED",
    "TestStreamResponse.test_content_length_setter": "PASSED",
    "TestStreamResponse.test_ctor": "PASSED",
    "TestStreamResponse.test_default_charset": "PASSED",
    "TestStreamResponse.test_drop_content_length_header_on_setting_len_to_None": "PASSED",
    "TestStreamResponse.test_force_close": "PASSED",
    "TestStreamResponse.test_reset_charset": "PASSED",
    "TestStreamResponse.test_reset_charset_after_setting": "PASSED",
    "TestStreamResponse.test_set_content_length_to_None_on_non_set": "PASSED",
    "TestStreamResponse.test_set_status_with_reason": "PASSED",
    "TestStreamResponse.test_setting_charset": "PASSED",
    "TestStreamResponse.test_setting_content_type": "PASSED",
    "TestStreamResponse.test_start": "PASSED",
    "TestStreamResponse.test_start_force_close": "PASSED",
    "TestStreamResponse.test_write_before_start": "PASSED",
    "TestStreamResponse.test_write_non_byteish": "PASSED",
    "TestStreamResponse.test_write_returns_drain": "PASSED",
    "TestStreamResponse.test_write_returns_empty_tuple_on_empty_data": "PASSED",
    "TestResponse.test_assign_nonbyteish_body": "PASSED",
    "TestResponse.test_assign_nonstr_text": "PASSED",
    "TestResponse.test_ctor": "PASSED",
    "TestResponse.test_ctor_content_type": "PASSED",
    "TestResponse.test_ctor_text": "PASSED",
    "TestResponse.test_ctor_text_body_combined": "PASSED",
    "TestResponse.test_ctor_with_headers_and_status": "PASSED",
    "TestResponse.test_drain_before_start": "PASSED",
    "TestResponse.test_render_with_body": "PASSED",
    "TestResponse.test_send_headers_for_empty_body": "PASSED",
    "TestResponse.test_send_set_cookie_header": "PASSED",
    "TestResponse.test_set_text_with_charset": "PASSED",
    "TestResponse.test_set_text_with_content_type": "PASSED",
    "TestResponse.test_started_when_not_started": "PASSED",
    "TestResponse.test_started_when_started": "PASSED",
    "TestUrlDispatcher.test_add_invalid_path": "PASSED",
    "TestUrlDispatcher.test_add_route_root": "PASSED",
    "TestUrlDispatcher.test_add_route_simple": "PASSED",
    "TestUrlDispatcher.test_add_route_with_re": "PASSED",
    "TestUrlDispatcher.test_add_route_with_re_including_slashes": "PASSED",
    "TestUrlDispatcher.test_add_route_with_re_not_match": "PASSED",
    "TestUrlDispatcher.test_add_static": "PASSED",
    "TestUrlDispatcher.test_add_url_escaping": "PASSED",
    "TestUrlDispatcher.test_add_url_invalid1": "PASSED",
    "TestUrlDispatcher.test_add_url_invalid2": "PASSED",
    "TestUrlDispatcher.test_add_url_invalid3": "PASSED",
    "TestUrlDispatcher.test_add_url_invalid4": "PASSED",
    "TestUrlDispatcher.test_add_url_invalid5": "PASSED",
    "TestUrlDispatcher.test_add_with_matchdict": "PASSED",
    "TestUrlDispatcher.test_add_with_name": "PASSED",
    "TestUrlDispatcher.test_add_with_tailing_slash": "PASSED",
    "TestUrlDispatcher.test_contains": "PASSED",
    "TestUrlDispatcher.test_double_add_url_with_the_same_name": "PASSED",
    "TestUrlDispatcher.test_dynamic_not_match": "PASSED",
    "TestUrlDispatcher.test_dynamic_repr": "PASSED",
    "TestUrlDispatcher.test_dynamic_with_trailing_slash": "PASSED",
    "TestUrlDispatcher.test_iter": "PASSED",
    "TestUrlDispatcher.test_len": "PASSED",
    "TestUrlDispatcher.test_match_second_result_in_table": "PASSED",
    "TestUrlDispatcher.test_plain_not_match": "PASSED",
    "TestUrlDispatcher.test_plain_repr": "PASSED",
    "TestUrlDispatcher.test_raise_method_not_allowed": "PASSED",
    "TestUrlDispatcher.test_raise_method_not_found": "PASSED",
    "TestUrlDispatcher.test_route_dynamic": "PASSED",
    "TestUrlDispatcher.test_route_plain": "PASSED",
    "TestUrlDispatcher.test_route_unknown_route_name": "PASSED",
    "TestUrlDispatcher.test_route_with_qs": "PASSED",
    "TestUrlDispatcher.test_static_adds_slash": "PASSED",
    "TestUrlDispatcher.test_static_dont_add__double_slash": "PASSED",
    "TestUrlDispatcher.test_static_not_match": "PASSED",
    "TestUrlDispatcher.test_static_repr": "PASSED",
    "TestWebRequest.test_POST": "PASSED",
    "TestWebRequest.test_calc_content_type_on_getting_charset": "PASSED",
    "TestWebRequest.test_call_POST_on_GET_request": "PASSED",
    "TestWebRequest.test_call_POST_on_weird_content_type": "PASSED",
    "TestWebRequest.test_call_POST_twice": "PASSED",
    "TestWebRequest.test_content_length": "PASSED",
    "TestWebRequest.test_content_type_from_spec": "PASSED",
    "TestWebRequest.test_content_type_from_spec_with_charset": "PASSED",
    "TestWebRequest.test_content_type_not_specified": "PASSED",
    "TestWebRequest.test_ctor": "PASSED",
    "TestWebRequest.test_match_info": "PASSED",
    "TestWebRequest.test_no_request_cookies": "PASSED",
    "TestWebRequest.test_non_ascii_path": "PASSED",
    "TestWebRequest.test_non_keepalive_on_closing": "PASSED",
    "TestWebRequest.test_non_keepalive_on_http10": "PASSED",
    "TestWebRequest.test_request_cookie": "PASSED",
    "TestWebRequest.test_request_cookie__set_item": "PASSED",
    "TestWebRequest.test_urlencoded_querystring": "PASSED",
    "TestWebWebSocket.test_can_start_invalid_method": "PASSED",
    "TestWebWebSocket.test_can_start_ok": "PASSED",
    "TestWebWebSocket.test_can_start_started": "PASSED",
    "TestWebWebSocket.test_can_start_unknown_protocol": "PASSED",
    "TestWebWebSocket.test_can_start_without_upgrade": "PASSED",
    "TestWebWebSocket.test_closing_after_ctor": "PASSED",
    "TestWebWebSocket.test_double_close": "PASSED",
    "TestWebWebSocket.test_nested_exception": "PASSED",
    "TestWebWebSocket.test_nonstarted_close": "PASSED",
    "TestWebWebSocket.test_nonstarted_ping": "PASSED",
    "TestWebWebSocket.test_nonstarted_receive": "PASSED",
    "TestWebWebSocket.test_nonstarted_send_bytes": "PASSED",
    "TestWebWebSocket.test_nonstarted_send_str": "PASSED",
    "TestWebWebSocket.test_ping_closing": "PASSED",
    "TestWebWebSocket.test_send_bytes_closing": "PASSED",
    "TestWebWebSocket.test_send_bytes_nonbytes": "PASSED",
    "TestWebWebSocket.test_send_str_closing": "PASSED",
    "TestWebWebSocket.test_send_str_nonstring": "PASSED",
    "TestWebWebSocket.test_start_invalid_method": "PASSED",
    "TestWebWebSocket.test_start_without_upgrade": "PASSED",
    "TestWebWebSocket.test_wait_closed_before_start": "PASSED",
    "TestWebWebSocket.test_write": "PASSED",
    "TestHTTPExceptions.test_HTTPFound": "PASSED",
    "TestHTTPExceptions.test_HTTPFound_empty_location": "PASSED",
    "TestHTTPExceptions.test_HTTPMethodNotAllowed": "PASSED",
    "TestHTTPExceptions.test_HTTPOk": "PASSED",
    "TestHTTPExceptions.test_all_http_exceptions_exported": "PASSED",
    "TestHTTPExceptions.test_override_body_with_binary": "PASSED",
    "TestHTTPExceptions.test_override_body_with_text": "PASSED",
    "TestHTTPExceptions.test_terminal_classes_has_status_code": "PASSED",
    "TestStreamResponse.test_cookie_set_after_del": "FAILED",
    "TestStreamResponse.test_response_cookie__issue_del_cookie": "FAILED",
    "TestStreamResponse.test_response_cookie_path": "FAILED",
    "TestStreamResponse.test_response_cookies": "FAILED",
    "TestUrlDispatcher.test_add_route_with_invalid_re": "FAILED"
}
diff --git a/aiohttp/web.py b/aiohttp/web.py
index 78e4d747..af40a470 100644
--- a/aiohttp/web.py
+++ b/aiohttp/web.py
@@ -139,8 +139,7 @@ FileField = collections.namedtuple('Field', 'name filename file content_type')
 
 class Request(HeadersMixin):
 
-    def __init__(self, app, message, payload, transport, reader, writer,
-                 keep_alive_timeout):
+    def __init__(self, app, message, payload, transport, reader, writer):
         self._app = app
         self._version = message.version
         self._transport = transport
@@ -162,7 +161,7 @@ class Request(HeadersMixin):
         elif message.should_close:
             self._keep_alive = False
         else:
-            self._keep_alive = bool(keep_alive_timeout)
+            self._keep_alive = True
 
         # matchdict, route_name, handler
         # or information about traversal lookup
@@ -1340,8 +1339,7 @@ class RequestHandler(ServerHttpProtocol):
 
         app = self._app
         request = Request(app, message, payload,
-                          self.transport, self.reader, self.writer,
-                          self.keep_alive_timeout)
+                          self.transport, self.reader, self.writer)
         try:
             match_info = yield from self._router.resolve(request)
 

{"aiohttp/web.py": "import abc\nimport asyncio\nimport binascii\nimport collections\nimport mimetypes\nimport cgi\nimport http.cookies\nimport io\nimport json\nimport re\nimport os\n\nfrom urllib.parse import urlsplit, parse_qsl, urlencode, unquote\n\nfrom .abc import AbstractRouter, AbstractMatchInfo\nfrom .helpers import reify\nfrom .log import web_logger\nfrom .multidict import (CaseInsensitiveMultiDict,\n                        CaseInsensitiveMutableMultiDict,\n                        MultiDict,\n                        MutableMultiDict)\nfrom .protocol import Response as ResponseImpl, HttpVersion, HttpVersion11\nfrom .server import ServerHttpProtocol\nfrom .streams import EOF_MARKER\nfrom .websocket import do_handshake, MSG_BINARY, MSG_CLOSE, MSG_PING, MSG_TEXT\nfrom .errors import HttpProcessingError, WebSocketDisconnectedError\n\n\n__all__ = [\n    'WebSocketDisconnectedError',\n    'Application',\n    'HttpVersion',\n    'RequestHandler',\n    'RequestHandlerFactory',\n    'Request',\n    'StreamResponse',\n    'Response',\n    'WebSocketResponse',\n    'UrlDispatcher',\n    'UrlMappingMatchInfo',\n    'HTTPException',\n    'HTTPError',\n    'HTTPRedirection',\n    'HTTPSuccessful',\n    'HTTPOk',\n    'HTTPCreated',\n    'HTTPAccepted',\n    'HTTPNonAuthoritativeInformation',\n    'HTTPNoContent',\n    'HTTPResetContent',\n    'HTTPPartialContent',\n    'HTTPMultipleChoices',\n    'HTTPMovedPermanently',\n    'HTTPFound',\n    'HTTPSeeOther',\n    'HTTPNotModified',\n    'HTTPUseProxy',\n    'HTTPTemporaryRedirect',\n    'HTTPClientError',\n    'HTTPBadRequest',\n    'HTTPUnauthorized',\n    'HTTPPaymentRequired',\n    'HTTPForbidden',\n    'HTTPNotFound',\n    'HTTPMethodNotAllowed',\n    'HTTPNotAcceptable',\n    'HTTPProxyAuthenticationRequired',\n    'HTTPRequestTimeout',\n    'HTTPConflict',\n    'HTTPGone',\n    'HTTPLengthRequired',\n    'HTTPPreconditionFailed',\n    'HTTPRequestEntityTooLarge',\n    'HTTPRequestURITooLong',\n    'HTTPUnsupportedMediaType',\n    'HTTPRequestRangeNotSatisfiable',\n    'HTTPExpectationFailed',\n    'HTTPServerError',\n    'HTTPInternalServerError',\n    'HTTPNotImplemented',\n    'HTTPBadGateway',\n    'HTTPServiceUnavailable',\n    'HTTPGatewayTimeout',\n    'HTTPVersionNotSupported',\n]\n\n\nsentinel = object()\n\n\nclass HeadersMixin:\n\n    _content_type = None\n    _content_dict = None\n    _stored_content_type = sentinel\n\n    def _parse_content_type(self, raw):\n        self._stored_content_type = raw\n        if raw is None:\n            # default value according to RFC 2616\n            self._content_type = 'application/octet-stream'\n            self._content_dict = {}\n        else:\n            self._content_type, self._content_dict = cgi.parse_header(raw)\n\n    @property\n    def content_type(self):\n        \"\"\"The value of content part for Content-Type HTTP header.\"\"\"\n        raw = self.headers.get('Content-Type')\n        if self._stored_content_type != raw:\n            self._parse_content_type(raw)\n        return self._content_type\n\n    @property\n    def charset(self):\n        \"\"\"The value of charset part for Content-Type HTTP header.\"\"\"\n        raw = self.headers.get('Content-Type')\n        if self._stored_content_type != raw:\n            self._parse_content_type(raw)\n        return self._content_dict.get('charset')\n\n    @property\n    def content_length(self):\n        \"\"\"The value of Content-Length HTTP header.\"\"\"\n        l = self.headers.get('Content-Length')\n        if l is None:\n            return None\n        else:\n            return int(l)\n\n\nFileField = collections.namedtuple('Field', 'name filename file content_type')\n\n\n############################################################\n# HTTP Request\n############################################################\n\n\nclass Request(HeadersMixin):\n\n    def __init__(self, app, message, payload, transport, reader, writer,\n                 keep_alive_timeout):\n        self._app = app\n        self._version = message.version\n        self._transport = transport\n        self._reader = reader\n        self._writer = writer\n        self._method = message.method\n        self._host = message.headers.get('HOST')\n        self._path_qs = message.path\n        res = urlsplit(message.path)\n        self._path = unquote(res.path)\n        self._query_string = res.query\n        self._post = None\n        self._post_files_cache = None\n        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(\n            message.headers)\n\n        if self._version < HttpVersion11:\n            self._keep_alive = False\n        elif message.should_close:\n            self._keep_alive = False\n        else:\n            self._keep_alive = bool(keep_alive_timeout)\n\n        # matchdict, route_name, handler\n        # or information about traversal lookup\n        self._match_info = None  # initialized after route resolving\n\n        self._payload = payload\n        self._cookies = None\n\n    @property\n    def method(self):\n        \"\"\"Read only property for getting HTTP method.\n\n        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.\n        \"\"\"\n        return self._method\n\n    @property\n    def version(self):\n        \"\"\"Read only property for getting HTTP version of request.\n\n        Returns aiohttp.protocol.HttpVersion instance.\n        \"\"\"\n        return self._version\n\n    @property\n    def host(self):\n        \"\"\"Read only property for getting *HOST* header of request.\n\n        Returns str or None if HTTP request has no HOST header.\n        \"\"\"\n        return self._host\n\n    @property\n    def path_qs(self):\n        \"\"\"The URL including PATH_INFO and the query string.\n\n        E.g, /app/blog?id=10\n        \"\"\"\n        return self._path_qs\n\n    @property\n    def path(self):\n        \"\"\"The URL including *PATH INFO* without the host or scheme.\n\n        E.g., ``/app/blog``\n        \"\"\"\n        return self._path\n\n    @property\n    def query_string(self):\n        \"\"\"The query string in the URL.\n\n        E.g., id=10\n        \"\"\"\n        return self._query_string\n\n    @reify\n    def GET(self):\n        \"\"\"A multidict with all the variables in the query string.\n\n        Lazy property.\n        \"\"\"\n        return MultiDict(parse_qsl(self._query_string))\n\n    @reify\n    def POST(self):\n        \"\"\"A multidict with all the variables in the POST parameters.\n\n        post() methods has to be called before using this attribute.\n        \"\"\"\n        if self._post is None:\n            raise RuntimeError(\"POST is not available before post()\")\n        return self._post\n\n    @property\n    def headers(self):\n        \"\"\"A case-insensitive multidict with all headers.\n\n        Lazy property.\n        \"\"\"\n        return self._headers\n\n    @property\n    def keep_alive(self):\n        \"\"\"Is keepalive enabled by client?\"\"\"\n        return self._keep_alive\n\n    @property\n    def match_info(self):\n        \"\"\"Result of route resolving.\"\"\"\n        return self._match_info\n\n    @property\n    def app(self):\n        \"\"\"Application instance.\"\"\"\n        return self._app\n\n    @property\n    def transport(self):\n        \"\"\"Transport used for request processing.\"\"\"\n        return self._transport\n\n    @property\n    def cookies(self):\n        \"\"\"Return request cookies.\n\n        A read-only dictionary-like object.\n        \"\"\"\n        if self._cookies is None:\n            raw = self.headers.get('COOKIE', '')\n            parsed = http.cookies.SimpleCookie(raw)\n            self._cookies = MultiDict({key: val.value\n                                       for key, val in parsed.items()})\n        return self._cookies\n\n    @property\n    def payload(self):\n        \"\"\"Return raw paiload stream.\"\"\"\n        return self._payload\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Release request.\n\n        Eat unread part of HTTP BODY if present.\n        \"\"\"\n        chunk = yield from self._payload.readany()\n        while chunk is not EOF_MARKER or chunk:\n            chunk = yield from self._payload.readany()\n\n    @asyncio.coroutine\n    def read(self):\n        \"\"\"Read request body if present.\n\n        Returns bytes object with full request content.\n        \"\"\"\n        body = bytearray()\n        while True:\n            chunk = yield from self._payload.readany()\n            body.extend(chunk)\n            if chunk is EOF_MARKER:\n                break\n        return bytes(body)\n\n    @asyncio.coroutine\n    def text(self):\n        \"\"\"Return BODY as text using encoding from .charset.\"\"\"\n        bytes_body = yield from self.read()\n        encoding = self.charset or 'utf-8'\n        return bytes_body.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, loader=json.loads):\n        \"\"\"Return BODY as JSON.\"\"\"\n        body = yield from self.text()\n        return loader(body)\n\n    @asyncio.coroutine\n    def post(self):\n        \"\"\"Return POST parameters.\"\"\"\n        if self._post is not None:\n            return self._post\n        if self.method not in ('POST', 'PUT', 'PATCH'):\n            self._post = MultiDict()\n            return self._post\n\n        content_type = self.content_type\n        if (content_type not in ('',\n                                 'application/x-www-form-urlencoded',\n                                 'multipart/form-data')):\n            self._post = MultiDict()\n            return self._post\n\n        body = yield from self.read()\n        content_charset = self.charset or 'utf-8'\n\n        environ = {'REQUEST_METHOD': self.method,\n                   'CONTENT_LENGTH': str(len(body)),\n                   'QUERY_STRING': '',\n                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}\n\n        fs = cgi.FieldStorage(fp=io.BytesIO(body),\n                              environ=environ,\n                              keep_blank_values=True,\n                              encoding=content_charset)\n\n        supported_tranfer_encoding = {\n            'base64': binascii.a2b_base64,\n            'quoted-printable': binascii.a2b_qp\n        }\n\n        out = MutableMultiDict()\n        for field in fs.list or ():\n            transfer_encoding = field.headers.get(\n                'Content-Transfer-Encoding', None)\n            if field.filename:\n                ff = FileField(field.name,\n                               field.filename,\n                               field.file,  # N.B. file closed error\n                               field.type)\n                if self._post_files_cache is None:\n                    self._post_files_cache = {}\n                self._post_files_cache[field.name] = field\n                out.add(field.name, ff)\n            else:\n                value = field.value\n                if transfer_encoding in supported_tranfer_encoding:\n                    # binascii accepts bytes\n                    value = value.encode('utf-8')\n                    value = supported_tranfer_encoding[\n                        transfer_encoding](value)\n                out.add(field.name, value)\n\n        self._post = MultiDict(out.items(getall=True))\n        return self._post\n\n\n############################################################\n# HTTP Response classes\n############################################################\n\n\nclass StreamResponse(HeadersMixin):\n\n    def __init__(self, *, status=200, reason=None):\n        self._body = None\n        self._keep_alive = None\n        self._headers = CaseInsensitiveMutableMultiDict()\n        self._cookies = http.cookies.SimpleCookie()\n        self.set_status(status, reason)\n\n        self._req = None\n        self._resp_impl = None\n        self._eof_sent = False\n\n    def _copy_cookies(self):\n        for cookie in self._cookies.values():\n            value = cookie.output(header='')[1:]\n            self.headers.add('Set-Cookie', value)\n\n    @property\n    def started(self):\n        return self._resp_impl is not None\n\n    @property\n    def status(self):\n        return self._status\n\n    @property\n    def reason(self):\n        return self._reason\n\n    def set_status(self, status, reason=None):\n        self._status = int(status)\n        if reason is None:\n            reason = ResponseImpl.calc_reason(status)\n        self._reason = reason\n\n    @property\n    def keep_alive(self):\n        return self._keep_alive\n\n    def force_close(self):\n        self._keep_alive = False\n\n    @property\n    def headers(self):\n        return self._headers\n\n    @property\n    def cookies(self):\n        return self._cookies\n\n    def set_cookie(self, name, value, *, expires=None,\n                   domain=None, max_age=None, path=None,\n                   secure=None, httponly=None, version=None):\n        \"\"\"Set or update response cookie.\n\n        Sets new cookie or updates existent with new value.\n        Also updates only those params which are not None.\n        \"\"\"\n\n        old = self._cookies.get(name)\n        if old is not None and old.coded_value == '':\n            # deleted cookie\n            self._cookies.pop(name, None)\n\n        self._cookies[name] = value\n        c = self._cookies[name]\n        if expires is not None:\n            c['expires'] = expires\n        if domain is not None:\n            c['domain'] = domain\n        if max_age is not None:\n            c['max-age'] = max_age\n        if path is not None:\n            c['path'] = path\n        if secure is not None:\n            c['secure'] = secure\n        if httponly is not None:\n            c['httponly'] = httponly\n        if version is not None:\n            c['version'] = version\n\n    def del_cookie(self, name, *, domain=None, path=None):\n        \"\"\"Delete cookie.\n\n        Creates new empty expired cookie.\n        \"\"\"\n        # TODO: do we need domain/path here?\n        self._cookies.pop(name, None)\n        self.set_cookie(name, '', max_age=0, domain=domain, path=path)\n\n    @property\n    def content_length(self):\n        # Just a placeholder for adding setter\n        return super().content_length\n\n    @content_length.setter\n    def content_length(self, value):\n        if value is not None:\n            value = int(value)\n            # TODO: raise error if chunked enabled\n            self.headers['Content-Length'] = str(value)\n        elif 'Content-Length' in self.headers:\n            del self.headers['Content-Length']\n\n    @property\n    def content_type(self):\n        # Just a placeholder for adding setter\n        return super().content_type\n\n    @content_type.setter\n    def content_type(self, value):\n        self.content_type  # read header values if needed\n        self._content_type = str(value)\n        self._generate_content_type_header()\n\n    @property\n    def charset(self):\n        # Just a placeholder for adding setter\n        return super().charset\n\n    @charset.setter\n    def charset(self, value):\n        ctype = self.content_type  # read header values if needed\n        if ctype == 'application/octet-stream':\n            raise RuntimeError(\"Setting charset for application/octet-stream \"\n                               \"doesn't make sense, setup content_type first\")\n        if value is None:\n            self._content_dict.pop('charset', None)\n        else:\n            self._content_dict['charset'] = str(value).lower()\n        self._generate_content_type_header()\n\n    def _generate_content_type_header(self):\n        params = '; '.join(\"%s=%s\" % i for i in self._content_dict.items())\n        if params:\n            ctype = self._content_type + '; ' + params\n        else:\n            ctype = self._content_type\n        self.headers['Content-Type'] = ctype\n\n    def _start_pre_check(self, request):\n        if self._resp_impl is not None:\n            if self._req is not request:\n                raise RuntimeError(\n                    'Response has been started with different request.')\n            else:\n                return self._resp_impl\n        else:\n            return None\n\n    def start(self, request):\n        resp_impl = self._start_pre_check(request)\n        if resp_impl is not None:\n            return resp_impl\n\n        self._req = request\n        keep_alive = self._keep_alive\n        if keep_alive is None:\n            keep_alive = request.keep_alive\n        self._keep_alive = keep_alive\n\n        resp_impl = self._resp_impl = ResponseImpl(\n            request._writer,\n            self._status,\n            request.version,\n            not keep_alive,\n            self._reason)\n\n        self._copy_cookies()\n\n        headers = self.headers.items(getall=True)\n        for key, val in headers:\n            resp_impl.add_header(key, val)\n\n        resp_impl.send_headers()\n        return resp_impl\n\n    def write(self, data):\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError('data argument must be byte-ish (%r)',\n                            type(data))\n\n        if self._eof_sent:\n            raise RuntimeError(\"Cannot call write() after write_eof()\")\n        if self._resp_impl is None:\n            raise RuntimeError(\"Cannot call write() before start()\")\n\n        if data:\n            return self._resp_impl.write(data)\n        else:\n            return ()\n\n    @asyncio.coroutine\n    def drain(self):\n        if self._resp_impl is None:\n            raise RuntimeError(\"Response has not been started\")\n        yield from self._resp_impl.transport.drain()\n\n    @asyncio.coroutine\n    def write_eof(self):\n        if self._eof_sent:\n            return\n        if self._resp_impl is None:\n            raise RuntimeError(\"Response has not been started\")\n\n        yield from self._resp_impl.write_eof()\n        self._eof_sent = True\n\n\nclass Response(StreamResponse):\n\n    def __init__(self, *, body=None, status=200,\n                 reason=None, headers=None,\n                 text=None, content_type=None):\n        super().__init__(status=status, reason=reason)\n\n        if headers is not None:\n            self.headers.extend(headers)\n        if content_type:\n            self.content_type = content_type\n\n        if body is not None and text is not None:\n            raise ValueError(\"body and text are not allowed together.\")\n        elif body is not None:\n            self.body = body\n        elif text is not None:\n            self.text = text\n        else:\n            self.body = None\n\n    @property\n    def body(self):\n        return self._body\n\n    @body.setter\n    def body(self, body):\n        if body is not None and not isinstance(body, bytes):\n            raise TypeError('body argument must be bytes (%r)', type(body))\n        self._body = body\n        if body is not None:\n            self.content_length = len(body)\n        else:\n            self.content_length = 0\n\n    @property\n    def text(self):\n        return self._body.decode(self.charset or 'utf-8')\n\n    @text.setter\n    def text(self, text):\n        if text is not None and not isinstance(text, str):\n            raise TypeError('text argument must be str (%r)', type(text))\n\n        if self.content_type == 'application/octet-stream':\n            self.content_type = 'text/plain'\n        if self.charset is None:\n            self.charset = 'utf-8'\n\n        self.body = text.encode(self.charset)\n\n    @asyncio.coroutine\n    def write_eof(self):\n        body = self._body\n        if body is not None:\n            self.write(body)\n        yield from super().write_eof()\n\n\nclass WebSocketResponse(StreamResponse):\n\n    def __init__(self, *, protocols=()):\n        super().__init__(status=101)\n        self._protocols = protocols\n        self._protocol = None\n        self._writer = None\n        self._reader = None\n        self._closing = False\n        self._loop = None\n        self._closing_fut = None\n\n    def start(self, request):\n        # make pre-check to don't hide it by do_handshake() exceptions\n        resp_impl = self._start_pre_check(request)\n        if resp_impl is not None:\n            return resp_impl\n\n        try:\n            status, headers, parser, writer, protocol = do_handshake(\n                request.method, request.headers, request.transport,\n                self._protocols)\n        except HttpProcessingError as err:\n            if err.code == 405:\n                raise HTTPMethodNotAllowed(request.method, ['GET'])\n            elif err.code == 400:\n                raise HTTPBadRequest(text=err.message)\n            else:  # pragma: no cover\n                raise HTTPInternalServerError() from err\n\n        if self.status != status:\n            self.set_status(status)\n        for k, v in headers:\n            self.headers[k] = v\n        self.force_close()\n\n        resp_impl = super().start(request)\n\n        self._reader = request._reader.set_parser(parser)\n        self._writer = writer\n        self._protocol = protocol\n        self._loop = request.app.loop\n        self._closing_fut = asyncio.Future(loop=self._loop)\n\n        return resp_impl\n\n    def can_start(self, request):\n        if self._writer is not None:\n            raise RuntimeError('Already started')\n        try:\n            _, _, _, _, protocol = do_handshake(\n                request.method, request.headers, request.transport,\n                self._protocols)\n        except HttpProcessingError:\n            return False, None\n        else:\n            return True, protocol\n\n    @property\n    def closing(self):\n        return self._closing\n\n    @property\n    def protocol(self):\n        return self._protocol\n\n    def ping(self):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if self._closing:\n            raise RuntimeError('websocket connection is closing')\n        self._writer.ping()\n\n    def send_str(self, data):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if self._closing:\n            raise RuntimeError('websocket connection is closing')\n        if not isinstance(data, str):\n            raise TypeError('data argument must be str (%r)', type(data))\n        self._writer.send(data, binary=False)\n\n    def send_bytes(self, data):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if self._closing:\n            raise RuntimeError('websocket connection is closing')\n        if not isinstance(data, (bytes, bytearray, memoryview)):\n            raise TypeError('data argument must be byte-ish (%r)',\n                            type(data))\n        self._writer.send(data, binary=True)\n\n    def close(self, *, code=1000, message=b''):\n        if self._writer is None:\n            raise RuntimeError('Call .start() first')\n        if not self._closing:\n            self._closing = True\n            self._writer.close(code, message)\n        else:\n            raise RuntimeError('Already closing')\n\n    @asyncio.coroutine\n    def wait_closed(self):\n        if self._closing_fut is None:\n            raise RuntimeError('Call .start() first')\n        yield from self._closing_fut\n\n    @asyncio.coroutine\n    def receive(self):\n        if self._reader is None:\n            raise RuntimeError('Call .start() first')\n        while True:\n            msg = yield from self._reader.read()\n\n            if msg.tp == MSG_CLOSE:\n                if self._closing:\n                    exc = WebSocketDisconnectedError(msg.data, msg.extra)\n                    self._closing_fut.set_exception(exc)\n                    raise exc\n                else:\n                    self._closing = True\n                    self._writer.close(msg.data, msg.extra)\n                    yield from self.drain()\n                    exc = WebSocketDisconnectedError(msg.data, msg.extra)\n                    self._closing_fut.set_exception(exc)\n                    raise exc\n            elif not self._closing:\n                if msg.tp == MSG_PING:\n                    self._writer.pong()\n                elif msg.tp == MSG_TEXT:\n                    return msg.data\n                elif msg.tp == MSG_BINARY:\n                    return msg.data\n\n    def write(self, data):\n        raise RuntimeError(\"Cannot call .write() for websocket\")\n\n\n############################################################\n# HTTP Exceptions\n############################################################\n\nclass HTTPException(Response, Exception):\n\n    # You should set in subclasses:\n    # status = 200\n\n    status_code = None\n\n    def __init__(self, *, headers=None, reason=None,\n                 body=None, text=None, content_type=None):\n        Response.__init__(self, status=self.status_code,\n                          headers=headers, reason=reason,\n                          body=body, text=text, content_type=content_type)\n        Exception.__init__(self, self.reason)\n        if self.body is None:\n            self.text = \"{}: {}\".format(self.status, self.reason)\n\n\nclass HTTPError(HTTPException):\n    \"\"\"Base class for exceptions with status codes in the 400s and 500s.\"\"\"\n\n\nclass HTTPRedirection(HTTPException):\n    \"\"\"Base class for exceptions with status codes in the 300s.\"\"\"\n\n\nclass HTTPSuccessful(HTTPException):\n    \"\"\"Base class for exceptions with status codes in the 200s.\"\"\"\n\n\nclass HTTPOk(HTTPSuccessful):\n    status_code = 200\n\n\nclass HTTPCreated(HTTPSuccessful):\n    status_code = 201\n\n\nclass HTTPAccepted(HTTPSuccessful):\n    status_code = 202\n\n\nclass HTTPNonAuthoritativeInformation(HTTPSuccessful):\n    status_code = 203\n\n\nclass HTTPNoContent(HTTPSuccessful):\n    status_code = 204\n\n\nclass HTTPResetContent(HTTPSuccessful):\n    status_code = 205\n\n\nclass HTTPPartialContent(HTTPSuccessful):\n    status_code = 206\n\n\n############################################################\n# 3xx redirection\n############################################################\n\n\nclass _HTTPMove(HTTPRedirection):\n\n    def __init__(self, location, *, headers=None, reason=None,\n                 body=None, text=None, content_type=None):\n        if not location:\n            raise ValueError(\"HTTP redirects need a location to redirect to.\")\n        super().__init__(headers=headers, reason=reason,\n                         body=body, text=text, content_type=content_type)\n        self.headers['Location'] = location\n        self.location = location\n\n\nclass HTTPMultipleChoices(_HTTPMove):\n    status_code = 300\n\n\nclass HTTPMovedPermanently(_HTTPMove):\n    status_code = 301\n\n\nclass HTTPFound(_HTTPMove):\n    status_code = 302\n\n\n# This one is safe after a POST (the redirected location will be\n# retrieved with GET):\nclass HTTPSeeOther(_HTTPMove):\n    status_code = 303\n\n\nclass HTTPNotModified(HTTPRedirection):\n    # FIXME: this should include a date or etag header\n    status_code = 304\n\n\nclass HTTPUseProxy(_HTTPMove):\n    # Not a move, but looks a little like one\n    status_code = 305\n\n\nclass HTTPTemporaryRedirect(_HTTPMove):\n    status_code = 307\n\n\n############################################################\n# 4xx client error\n############################################################\n\n\nclass HTTPClientError(HTTPError):\n    pass\n\n\nclass HTTPBadRequest(HTTPClientError):\n    status_code = 400\n\n\nclass HTTPUnauthorized(HTTPClientError):\n    status_code = 401\n\n\nclass HTTPPaymentRequired(HTTPClientError):\n    status_code = 402\n\n\nclass HTTPForbidden(HTTPClientError):\n    status_code = 403\n\n\nclass HTTPNotFound(HTTPClientError):\n    status_code = 404\n\n\nclass HTTPMethodNotAllowed(HTTPClientError):\n    status_code = 405\n\n    def __init__(self, method, allowed_methods, *, headers=None, reason=None,\n                 body=None, text=None, content_type=None):\n        allow = ','.join(sorted(allowed_methods))\n        super().__init__(headers=headers, reason=reason,\n                         body=body, text=text, content_type=content_type)\n        self.headers['Allow'] = allow\n        self.allowed_methods = allowed_methods\n        self.method = method.upper()\n\n\nclass HTTPNotAcceptable(HTTPClientError):\n    status_code = 406\n\n\nclass HTTPProxyAuthenticationRequired(HTTPClientError):\n    status_code = 407\n\n\nclass HTTPRequestTimeout(HTTPClientError):\n    status_code = 408\n\n\nclass HTTPConflict(HTTPClientError):\n    status_code = 409\n\n\nclass HTTPGone(HTTPClientError):\n    status_code = 410\n\n\nclass HTTPLengthRequired(HTTPClientError):\n    status_code = 411\n\n\nclass HTTPPreconditionFailed(HTTPClientError):\n    status_code = 412\n\n\nclass HTTPRequestEntityTooLarge(HTTPClientError):\n    status_code = 413\n\n\nclass HTTPRequestURITooLong(HTTPClientError):\n    status_code = 414\n\n\nclass HTTPUnsupportedMediaType(HTTPClientError):\n    status_code = 415\n\n\nclass HTTPRequestRangeNotSatisfiable(HTTPClientError):\n    status_code = 416\n\n\nclass HTTPExpectationFailed(HTTPClientError):\n    status_code = 417\n\n\n############################################################\n# 5xx Server Error\n############################################################\n#  Response status codes beginning with the digit \"5\" indicate cases in\n#  which the server is aware that it has erred or is incapable of\n#  performing the request. Except when responding to a HEAD request, the\n#  server SHOULD include an entity containing an explanation of the error\n#  situation, and whether it is a temporary or permanent condition. User\n#  agents SHOULD display any included entity to the user. These response\n#  codes are applicable to any request method.\n\n\nclass HTTPServerError(HTTPError):\n    pass\n\n\nclass HTTPInternalServerError(HTTPServerError):\n    status_code = 500\n\n\nclass HTTPNotImplemented(HTTPServerError):\n    status_code = 501\n\n\nclass HTTPBadGateway(HTTPServerError):\n    status_code = 502\n\n\nclass HTTPServiceUnavailable(HTTPServerError):\n    status_code = 503\n\n\nclass HTTPGatewayTimeout(HTTPServerError):\n    status_code = 504\n\n\nclass HTTPVersionNotSupported(HTTPServerError):\n    status_code = 505\n\n\n############################################################\n# UrlDispatcher implementation\n############################################################\n\n\nclass UrlMappingMatchInfo(dict, AbstractMatchInfo):\n\n    def __init__(self, match_dict, route):\n        super().__init__(match_dict)\n        self._route = route\n\n    @property\n    def handler(self):\n        return self._route.handler\n\n    @property\n    def route(self):\n        return self._route\n\n\nclass Route(metaclass=abc.ABCMeta):\n\n    def __init__(self, method, handler, name):\n        self._method = method\n        self._handler = handler\n        self._name = name\n\n    @property\n    def method(self):\n        return self._method\n\n    @property\n    def handler(self):\n        return self._handler\n\n    @property\n    def name(self):\n        return self._name\n\n    @abc.abstractmethod\n    def match(self, path):\n        \"\"\"Return dict with info for given path or\n        None if route cannot process path.\"\"\"\n\n    @abc.abstractmethod\n    def url(self, **kwargs):\n        \"\"\"Construct url for route with additional params.\"\"\"\n\n    @staticmethod\n    def _append_query(url, query):\n        if query is not None:\n            return url + \"?\" + urlencode(query)\n        else:\n            return url\n\n\nclass PlainRoute(Route):\n\n    def __init__(self, method, handler, name, path):\n        super().__init__(method, handler, name)\n        self._path = path\n\n    def match(self, path):\n        # string comparsion about 10 times faster than regexp matching\n        if self._path == path:\n            return {}\n        else:\n            return None\n\n    def url(self, *, query=None):\n        return self._append_query(self._path, query)\n\n    def __repr__(self):\n        name = \"'\" + self.name + \"' \" if self.name is not None else \"\"\n        return \"<PlainRoute {name}[{method}] {path} -> {handler!r}\".format(\n            name=name, method=self.method, path=self._path,\n            handler=self.handler)\n\n\nclass DynamicRoute(Route):\n\n    def __init__(self, method, handler, name, pattern, formatter):\n        super().__init__(method, handler, name)\n        self._pattern = pattern\n        self._formatter = formatter\n\n    def match(self, path):\n        match = self._pattern.match(path)\n        if match is None:\n            return None\n        else:\n            return match.groupdict()\n\n    def url(self, *, parts, query=None):\n        url = self._formatter.format_map(parts)\n        return self._append_query(url, query)\n\n    def __repr__(self):\n        name = \"'\" + self.name + \"' \" if self.name is not None else \"\"\n        return (\"<DynamicRoute {name}[{method}] {formatter} -> {handler!r}\"\n                .format(name=name, method=self.method,\n                        formatter=self._formatter, handler=self.handler))\n\n\nclass StaticRoute(Route):\n\n    def __init__(self, name, prefix, directory):\n        assert prefix.startswith('/'), prefix\n        assert prefix.endswith('/'), prefix\n        super().__init__('GET', self.handle, name)\n        self._prefix = prefix\n        self._prefix_len = len(self._prefix)\n        self._directory = directory\n\n    def match(self, path):\n        if not path.startswith(self._prefix):\n            return None\n        return {'filename': path[self._prefix_len:]}\n\n    def url(self, *, filename, query=None):\n        while filename.startswith('/'):\n            filename = filename[1:]\n        url = self._prefix + filename\n        return self._append_query(url, query)\n\n    @asyncio.coroutine\n    def handle(self, request):\n        resp = StreamResponse()\n        filename = request.match_info['filename']\n        filepath = os.path.join(self._directory, filename)\n        if '..' in filename:\n            raise HTTPNotFound()\n        if not os.path.exists(filepath) or not os.path.isfile(filepath):\n            raise HTTPNotFound()\n\n        ct = mimetypes.guess_type(filename)[0]\n        if not ct:\n            ct = 'application/octet-stream'\n        resp.content_type = ct\n\n        resp.headers['transfer-encoding'] = 'chunked'\n        resp.start(request)\n\n        with open(filepath, 'rb') as f:\n            chunk = f.read(8192)\n            while chunk:\n                resp.write(chunk)\n                chunk = f.read(8192)\n\n        yield from resp.write_eof()\n        return resp\n\n    def __repr__(self):\n        name = \"'\" + self.name + \"' \" if self.name is not None else \"\"\n        return \"<StaticRoute {name}[{method}] {path} -> {directory!r}\".format(\n            name=name, method=self.method, path=self._prefix,\n            directory=self._directory)\n\n\nclass UrlDispatcher(AbstractRouter, collections.abc.Mapping):\n\n    DYN = re.compile(r'^\\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*)\\}$')\n    DYN_WITH_RE = re.compile(\n        r'^\\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*):(?P<re>.+)\\}$')\n    GOOD = r'[^{}/]+'\n    PLAIN = re.compile('^' + GOOD + '$')\n\n    METHODS = {'POST', 'GET', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'}\n\n    def __init__(self):\n        super().__init__()\n        self._urls = []\n        self._routes = {}\n\n    @asyncio.coroutine\n    def resolve(self, request):\n        path = request.path\n        method = request.method\n        allowed_methods = set()\n        for route in self._urls:\n            match_dict = route.match(path)\n            if match_dict is None:\n                continue\n            route_method = route.method\n            if route_method != method:\n                allowed_methods.add(route_method)\n            else:\n                return UrlMappingMatchInfo(match_dict, route)\n        else:\n            if allowed_methods:\n                raise HTTPMethodNotAllowed(method, allowed_methods)\n            else:\n                raise HTTPNotFound()\n\n    def __iter__(self):\n        return iter(self._routes)\n\n    def __len__(self):\n        return len(self._routes)\n\n    def __contains__(self, name):\n        return name in self._routes\n\n    def __getitem__(self, name):\n        return self._routes[name]\n\n    def _register_endpoint(self, route):\n        name = route.name\n        if name is not None:\n            if name in self._routes:\n                raise ValueError('Duplicate {!r}, '\n                                 'already handled by {!r}'\n                                 .format(name, self._routes[name]))\n            else:\n                self._routes[name] = route\n        self._urls.append(route)\n\n    def add_route(self, method, path, handler, *, name=None):\n        assert path.startswith('/')\n        assert callable(handler), handler\n        if not asyncio.iscoroutinefunction(handler):\n            handler = asyncio.coroutine(handler)\n        method = method.upper()\n        assert method in self.METHODS, method\n        parts = []\n        factory = PlainRoute\n        for part in path.split('/'):\n            if not part:\n                continue\n            match = self.DYN.match(part)\n            if match:\n                parts.append('(?P<' + match.group('var') + '>' +\n                             self.GOOD + ')')\n                factory = DynamicRoute\n                continue\n\n            match = self.DYN_WITH_RE.match(part)\n            if match:\n                parts.append('(?P<' + match.group('var') + '>' +\n                             match.group('re') + ')')\n                factory = DynamicRoute\n                continue\n            if self.PLAIN.match(part):\n                parts.append(re.escape(part))\n                continue\n            raise ValueError(\"Invalid path '{}'['{}']\".format(path, part))\n        if factory is PlainRoute:\n            route = PlainRoute(method, handler, name, path)\n        else:\n            pattern = '/' + '/'.join(parts)\n            if path.endswith('/') and pattern != '/':\n                pattern += '/'\n            try:\n                compiled = re.compile('^' + pattern + '$')\n            except re.error as exc:\n                raise ValueError(\n                    \"Bad pattern '{}': {}\".format(pattern, exc)) from None\n            route = DynamicRoute(method, handler, name, compiled, path)\n        self._register_endpoint(route)\n        return route\n\n    def add_static(self, prefix, path, *, name=None):\n        \"\"\"\n        Adds static files view\n        :param prefix - url prefix\n        :param path - folder with files\n        \"\"\"\n        assert prefix.startswith('/')\n        assert os.path.isdir(path), 'Path does not directory %s' % path\n        path = os.path.abspath(path)\n        if not prefix.endswith('/'):\n            prefix += '/'\n        route = StaticRoute(name, prefix, path)\n        self._register_endpoint(route)\n        return route\n\n\n############################################################\n# Application implementation\n############################################################\n\n\nclass RequestHandler(ServerHttpProtocol):\n\n    def __init__(self, manager, app, router, **kwargs):\n        super().__init__(**kwargs)\n\n        self._manager = manager\n        self._app = app\n        self._router = router\n        self._middlewares = app.middlewares\n\n    def connection_made(self, transport):\n        super().connection_made(transport)\n\n        self._manager.connection_made(self, transport)\n\n    def connection_lost(self, exc):\n        self._manager.connection_lost(self, exc)\n\n        super().connection_lost(exc)\n\n    @asyncio.coroutine\n    def handle_request(self, message, payload):\n        now = self._loop.time()\n\n        app = self._app\n        request = Request(app, message, payload,\n                          self.transport, self.reader, self.writer,\n                          self.keep_alive_timeout)\n        try:\n            match_info = yield from self._router.resolve(request)\n\n            assert isinstance(match_info, AbstractMatchInfo), match_info\n\n            request._match_info = match_info\n            handler = match_info.handler\n\n            for factory in reversed(self._middlewares):\n                handler = yield from factory(app, handler)\n            resp = yield from handler(request)\n\n            if not isinstance(resp, StreamResponse):\n                raise RuntimeError(\n                    (\"Handler {!r} should return response instance, \"\n                     \"got {!r} [middlewares {!r}]\").format(\n                         match_info.handler,\n                         type(resp),\n                         self._middlewares))\n        except HTTPException as exc:\n            resp = exc\n\n        resp_msg = resp.start(request)\n        yield from resp.write_eof()\n\n        # notify server about keep-alive\n        self.keep_alive(resp_msg.keep_alive())\n\n        # log access\n        self.log_access(message, None, resp_msg, self._loop.time() - now)\n\n\nclass RequestHandlerFactory:\n\n    def __init__(self, app, router, *,\n                 handler=RequestHandler, loop=None, **kwargs):\n        self._app = app\n        self._router = router\n        self._handler = handler\n        self._loop = loop\n        self._connections = {}\n        self._kwargs = kwargs\n        self._kwargs.setdefault('logger', app.logger)\n\n    @property\n    def connections(self):\n        return list(self._connections.keys())\n\n    def connection_made(self, handler, transport):\n        self._connections[handler] = transport\n\n    def connection_lost(self, handler, exc=None):\n        if handler in self._connections:\n            del self._connections[handler]\n\n    @asyncio.coroutine\n    def finish_connections(self, timeout=None):\n        for handler in self._connections.keys():\n            handler.closing()\n\n        def cleanup():\n            sleep = 0.05\n            while self._connections:\n                yield from asyncio.sleep(sleep, loop=self._loop)\n                if sleep < 5:\n                    sleep = sleep * 2\n\n        if timeout:\n            try:\n                yield from asyncio.wait_for(\n                    cleanup(), timeout, loop=self._loop)\n            except asyncio.TimeoutError:\n                self._app.logger.warning(\n                    \"Not all connections are closed (pending: %d)\",\n                    len(self._connections))\n\n        for transport in self._connections.values():\n            transport.close()\n\n        self._connections.clear()\n\n    def __call__(self):\n        return self._handler(\n            self, self._app, self._router, loop=self._loop, **self._kwargs)\n\n\nclass Application(dict):\n\n    def __init__(self, *, logger=web_logger, loop=None,\n                 router=None, handler_factory=RequestHandlerFactory,\n                 middlewares=(), **kwargs):\n        if loop is None:\n            loop = asyncio.get_event_loop()\n        if router is None:\n            router = UrlDispatcher()\n        assert isinstance(router, AbstractRouter), router\n\n        self._router = router\n        self._handler_factory = handler_factory\n        self._finish_callbacks = []\n        self._loop = loop\n        self.logger = logger\n\n        self.update(**kwargs)\n        for factory in middlewares:\n            assert asyncio.iscoroutinefunction(factory), factory\n        self._middlewares = tuple(middlewares)\n\n    @property\n    def router(self):\n        return self._router\n\n    @property\n    def loop(self):\n        return self._loop\n\n    @property\n    def middlewares(self):\n        return self._middlewares\n\n    def make_handler(self, **kwargs):\n        return self._handler_factory(\n            self, self.router, loop=self.loop, **kwargs)\n\n    @asyncio.coroutine\n    def finish(self):\n        callbacks = self._finish_callbacks\n        self._finish_callbacks = []\n\n        for (cb, args, kwargs) in callbacks:\n            try:\n                res = cb(self, *args, **kwargs)\n                if (asyncio.iscoroutine(res) or\n                        isinstance(res, asyncio.Future)):\n                    yield from res\n            except Exception as exc:\n                self._loop.call_exception_handler({\n                    'message': \"Error in finish callback\",\n                    'exception': exc,\n                    'application': self,\n                })\n\n    def register_on_finish(self, func, *args, **kwargs):\n        self._finish_callbacks.insert(0, (func, args, kwargs))\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:** Request Constructor Fails with TypeError Due to Missing `keep_alive_timeout` Parameter

**Description:**
After recent changes, initializing a `Request` object without the `keep_alive_timeout` parameter results in a `TypeError`. The constructor no longer expects `keep_alive_timeout`, but existing code attempts to create `Request` instances without providing this argument, leading to failures.

**Example Code:**
```python
def make_request():
    req = Request(app, message, payload, transport, reader, writer)
    # Previously included keep_alive_timeout parameter
```

**Expected Behavior:**
`Request` objects should be instantiated without the need for the `keep_alive_timeout` parameter, aligning with the updated constructor definition.

**Actual Behavior:**
A `TypeError` is raised stating that `__init__()` is missing the required positional argument: `keep_alive_timeout`.
```
TypeError: __init__() missing 1 required positional argument: 'keep_alive_timeout'
```
[/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/web.py
import abc
import asyncio
import binascii
import collections
import mimetypes
import cgi
import http.cookies
import io
import json
import re
import os

from urllib.parse import urlsplit, parse_qsl, urlencode, unquote

from .abc import AbstractRouter, AbstractMatchInfo
from .helpers import reify
from .log import web_logger
from .multidict import (CaseInsensitiveMultiDict,
                        CaseInsensitiveMutableMultiDict,
                        MultiDict,
                        MutableMultiDict)
from .protocol import Response as ResponseImpl, HttpVersion, HttpVersion11
from .server import ServerHttpProtocol
from .streams import EOF_MARKER
from .websocket import do_handshake, MSG_BINARY, MSG_CLOSE, MSG_PING, MSG_TEXT
from .errors import HttpProcessingError, WebSocketDisconnectedError


__all__ = [
    'WebSocketDisconnectedError',
    'Application',
    'HttpVersion',
    'RequestHandler',
    'RequestHandlerFactory',
    'Request',
    'StreamResponse',
    'Response',
    'WebSocketResponse',
    'UrlDispatcher',
    'UrlMappingMatchInfo',
    'HTTPException',
    'HTTPError',
    'HTTPRedirection',
    'HTTPSuccessful',
    'HTTPOk',
    'HTTPCreated',
    'HTTPAccepted',
    'HTTPNonAuthoritativeInformation',
    'HTTPNoContent',
    'HTTPResetContent',
    'HTTPPartialContent',
    'HTTPMultipleChoices',
    'HTTPMovedPermanently',
    'HTTPFound',
    'HTTPSeeOther',
    'HTTPNotModified',
    'HTTPUseProxy',
    'HTTPTemporaryRedirect',
    'HTTPClientError',
    'HTTPBadRequest',
    'HTTPUnauthorized',
    'HTTPPaymentRequired',
    'HTTPForbidden',
    'HTTPNotFound',
    'HTTPMethodNotAllowed',
    'HTTPNotAcceptable',
    'HTTPProxyAuthenticationRequired',
    'HTTPRequestTimeout',
    'HTTPConflict',
    'HTTPGone',
    'HTTPLengthRequired',
    'HTTPPreconditionFailed',
    'HTTPRequestEntityTooLarge',
    'HTTPRequestURITooLong',
    'HTTPUnsupportedMediaType',
    'HTTPRequestRangeNotSatisfiable',
    'HTTPExpectationFailed',
    'HTTPServerError',
    'HTTPInternalServerError',
    'HTTPNotImplemented',
    'HTTPBadGateway',
    'HTTPServiceUnavailable',
    'HTTPGatewayTimeout',
    'HTTPVersionNotSupported',
]


sentinel = object()


class HeadersMixin:

    _content_type = None
    _content_dict = None
    _stored_content_type = sentinel

    def _parse_content_type(self, raw):
        self._stored_content_type = raw
        if raw is None:
            # default value according to RFC 2616
            self._content_type = 'application/octet-stream'
            self._content_dict = {}
        else:
            self._content_type, self._content_dict = cgi.parse_header(raw)

    @property
    def content_type(self):
        """The value of content part for Content-Type HTTP header."""
        raw = self.headers.get('Content-Type')
        if self._stored_content_type != raw:
            self._parse_content_type(raw)
        return self._content_type

    @property
    def charset(self):
        """The value of charset part for Content-Type HTTP header."""
        raw = self.headers.get('Content-Type')
        if self._stored_content_type != raw:
            self._parse_content_type(raw)
        return self._content_dict.get('charset')

    @property
    def content_length(self):
        """The value of Content-Length HTTP header."""
        l = self.headers.get('Content-Length')
        if l is None:
            return None
        else:
            return int(l)


FileField = collections.namedtuple('Field', 'name filename file content_type')


############################################################
# HTTP Request
############################################################


class Request(HeadersMixin):

    def __init__(self, app, message, payload, transport, reader, writer,
                 keep_alive_timeout):
        self._app = app
        self._version = message.version
        self._transport = transport
        self._reader = reader
        self._writer = writer
        self._method = message.method
        self._host = message.headers.get('HOST')
        self._path_qs = message.path
        res = urlsplit(message.path)
        self._path = unquote(res.path)
        self._query_string = res.query
        self._post = None
        self._post_files_cache = None
        self._headers = CaseInsensitiveMultiDict._from_uppercase_multidict(
            message.headers)

        if self._version < HttpVersion11:
            self._keep_alive = False
        elif message.should_close:
            self._keep_alive = False
        else:
            self._keep_alive = bool(keep_alive_timeout)

        # matchdict, route_name, handler
        # or information about traversal lookup
        self._match_info = None  # initialized after route resolving

        self._payload = payload
        self._cookies = None

    @property
    def method(self):
        """Read only property for getting HTTP method.

        The value is upper-cased str like 'GET', 'POST', 'PUT' etc.
        """
        return self._method

    @property
    def version(self):
        """Read only property for getting HTTP version of request.

        Returns aiohttp.protocol.HttpVersion instance.
        """
        return self._version

    @property
    def host(self):
        """Read only property for getting *HOST* header of request.

        Returns str or None if HTTP request has no HOST header.
        """
        return self._host

    @property
    def path_qs(self):
        """The URL including PATH_INFO and the query string.

        E.g, /app/blog?id=10
        """
        return self._path_qs

    @property
    def path(self):
        """The URL including *PATH INFO* without the host or scheme.

        E.g., ``/app/blog``
        """
        return self._path

    @property
    def query_string(self):
        """The query string in the URL.

        E.g., id=10
        """
        return self._query_string

    @reify
    def GET(self):
        """A multidict with all the variables in the query string.

        Lazy property.
        """
        return MultiDict(parse_qsl(self._query_string))

    @reify
    def POST(self):
        """A multidict with all the variables in the POST parameters.

        post() methods has to be called before using this attribute.
        """
        if self._post is None:
            raise RuntimeError("POST is not available before post()")
        return self._post

    @property
    def headers(self):
        """A case-insensitive multidict with all headers.

        Lazy property.
        """
        return self._headers

    @property
    def keep_alive(self):
        """Is keepalive enabled by client?"""
        return self._keep_alive

    @property
    def match_info(self):
        """Result of route resolving."""
        return self._match_info

    @property
    def app(self):
        """Application instance."""
        return self._app

    @property
    def transport(self):
        """Transport used for request processing."""
        return self._transport

    @property
    def cookies(self):
        """Return request cookies.

        A read-only dictionary-like object.
        """
        if self._cookies is None:
            raw = self.headers.get('COOKIE', '')
            parsed = http.cookies.SimpleCookie(raw)
            self._cookies = MultiDict({key: val.value
                                       for key, val in parsed.items()})
        return self._cookies

    @property
    def payload(self):
        """Return raw paiload stream."""
        return self._payload

    @asyncio.coroutine
    def release(self):
        """Release request.

        Eat unread part of HTTP BODY if present.
        """
        chunk = yield from self._payload.readany()
        while chunk is not EOF_MARKER or chunk:
            chunk = yield from self._payload.readany()

    @asyncio.coroutine
    def read(self):
        """Read request body if present.

        Returns bytes object with full request content.
        """
        body = bytearray()
        while True:
            chunk = yield from self._payload.readany()
            body.extend(chunk)
            if chunk is EOF_MARKER:
                break
        return bytes(body)

    @asyncio.coroutine
    def text(self):
        """Return BODY as text using encoding from .charset."""
        bytes_body = yield from self.read()
        encoding = self.charset or 'utf-8'
        return bytes_body.decode(encoding)

    @asyncio.coroutine
    def json(self, *, loader=json.loads):
        """Return BODY as JSON."""
        body = yield from self.text()
        return loader(body)

    @asyncio.coroutine
    def post(self):
        """Return POST parameters."""
        if self._post is not None:
            return self._post
        if self.method not in ('POST', 'PUT', 'PATCH'):
            self._post = MultiDict()
            return self._post

        content_type = self.content_type
        if (content_type not in ('',
                                 'application/x-www-form-urlencoded',
                                 'multipart/form-data')):
            self._post = MultiDict()
            return self._post

        body = yield from self.read()
        content_charset = self.charset or 'utf-8'

        environ = {'REQUEST_METHOD': self.method,
                   'CONTENT_LENGTH': str(len(body)),
                   'QUERY_STRING': '',
                   'CONTENT_TYPE': self.headers.get('CONTENT-TYPE')}

        fs = cgi.FieldStorage(fp=io.BytesIO(body),
                              environ=environ,
                              keep_blank_values=True,
                              encoding=content_charset)

        supported_tranfer_encoding = {
            'base64': binascii.a2b_base64,
            'quoted-printable': binascii.a2b_qp
        }

        out = MutableMultiDict()
        for field in fs.list or ():
            transfer_encoding = field.headers.get(
                'Content-Transfer-Encoding', None)
            if field.filename:
                ff = FileField(field.name,
                               field.filename,
                               field.file,  # N.B. file closed error
                               field.type)
                if self._post_files_cache is None:
                    self._post_files_cache = {}
                self._post_files_cache[field.name] = field
                out.add(field.name, ff)
            else:
                value = field.value
                if transfer_encoding in supported_tranfer_encoding:
                    # binascii accepts bytes
                    value = value.encode('utf-8')
                    value = supported_tranfer_encoding[
                        transfer_encoding](value)
                out.add(field.name, value)

        self._post = MultiDict(out.items(getall=True))
        return self._post


############################################################
# HTTP Response classes
############################################################


class StreamResponse(HeadersMixin):

    def __init__(self, *, status=200, reason=None):
        self._body = None
        self._keep_alive = None
        self._headers = CaseInsensitiveMutableMultiDict()
        self._cookies = http.cookies.SimpleCookie()
        self.set_status(status, reason)

        self._req = None
        self._resp_impl = None
        self._eof_sent = False

    def _copy_cookies(self):
        for cookie in self._cookies.values():
            value = cookie.output(header='')[1:]
            self.headers.add('Set-Cookie', value)

    @property
    def started(self):
        return self._resp_impl is not None

    @property
    def status(self):
        return self._status

    @property
    def reason(self):
        return self._reason

    def set_status(self, status, reason=None):
        self._status = int(status)
        if reason is None:
            reason = ResponseImpl.calc_reason(status)
        self._reason = reason

    @property
    def keep_alive(self):
        return self._keep_alive

    def force_close(self):
        self._keep_alive = False

    @property
    def headers(self):
        return self._headers

    @property
    def cookies(self):
        return self._cookies

    def set_cookie(self, name, value, *, expires=None,
                   domain=None, max_age=None, path=None,
                   secure=None, httponly=None, version=None):
        """Set or update response cookie.

        Sets new cookie or updates existent with new value.
        Also updates only those params which are not None.
        """

        old = self._cookies.get(name)
        if old is not None and old.coded_value == '':
            # deleted cookie
            self._cookies.pop(name, None)

        self._cookies[name] = value
        c = self._cookies[name]
        if expires is not None:
            c['expires'] = expires
        if domain is not None:
            c['domain'] = domain
        if max_age is not None:
            c['max-age'] = max_age
        if path is not None:
            c['path'] = path
        if secure is not None:
            c['secure'] = secure
        if httponly is not None:
            c['httponly'] = httponly
        if version is not None:
            c['version'] = version

    def del_cookie(self, name, *, domain=None, path=None):
        """Delete cookie.

        Creates new empty expired cookie.
        """
        # TODO: do we need domain/path here?
        self._cookies.pop(name, None)
        self.set_cookie(name, '', max_age=0, domain=domain, path=path)

    @property
    def content_length(self):
        # Just a placeholder for adding setter
        return super().content_length

    @content_length.setter
    def content_length(self, value):
        if value is not None:
            value = int(value)
            # TODO: raise error if chunked enabled
            self.headers['Content-Length'] = str(value)
        elif 'Content-Length' in self.headers:
            del self.headers['Content-Length']

    @property
    def content_type(self):
        # Just a placeholder for adding setter
        return super().content_type

    @content_type.setter
    def content_type(self, value):
        self.content_type  # read header values if needed
        self._content_type = str(value)
        self._generate_content_type_header()

    @property
    def charset(self):
        # Just a placeholder for adding setter
        return super().charset

    @charset.setter
    def charset(self, value):
        ctype = self.content_type  # read header values if needed
        if ctype == 'application/octet-stream':
            raise RuntimeError("Setting charset for application/octet-stream "
                               "doesn't make sense, setup content_type first")
        if value is None:
            self._content_dict.pop('charset', None)
        else:
            self._content_dict['charset'] = str(value).lower()
        self._generate_content_type_header()

    def _generate_content_type_header(self):
        params = '; '.join("%s=%s" % i for i in self._content_dict.items())
        if params:
            ctype = self._content_type + '; ' + params
        else:
            ctype = self._content_type
        self.headers['Content-Type'] = ctype

    def _start_pre_check(self, request):
        if self._resp_impl is not None:
            if self._req is not request:
                raise RuntimeError(
                    'Response has been started with different request.')
            else:
                return self._resp_impl
        else:
            return None

    def start(self, request):
        resp_impl = self._start_pre_check(request)
        if resp_impl is not None:
            return resp_impl

        self._req = request
        keep_alive = self._keep_alive
        if keep_alive is None:
            keep_alive = request.keep_alive
        self._keep_alive = keep_alive

        resp_impl = self._resp_impl = ResponseImpl(
            request._writer,
            self._status,
            request.version,
            not keep_alive,
            self._reason)

        self._copy_cookies()

        headers = self.headers.items(getall=True)
        for key, val in headers:
            resp_impl.add_header(key, val)

        resp_impl.send_headers()
        return resp_impl

    def write(self, data):
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError('data argument must be byte-ish (%r)',
                            type(data))

        if self._eof_sent:
            raise RuntimeError("Cannot call write() after write_eof()")
        if self._resp_impl is None:
            raise RuntimeError("Cannot call write() before start()")

        if data:
            return self._resp_impl.write(data)
        else:
            return ()

    @asyncio.coroutine
    def drain(self):
        if self._resp_impl is None:
            raise RuntimeError("Response has not been started")
        yield from self._resp_impl.transport.drain()

    @asyncio.coroutine
    def write_eof(self):
        if self._eof_sent:
            return
        if self._resp_impl is None:
            raise RuntimeError("Response has not been started")

        yield from self._resp_impl.write_eof()
        self._eof_sent = True


class Response(StreamResponse):

    def __init__(self, *, body=None, status=200,
                 reason=None, headers=None,
                 text=None, content_type=None):
        super().__init__(status=status, reason=reason)

        if headers is not None:
            self.headers.extend(headers)
        if content_type:
            self.content_type = content_type

        if body is not None and text is not None:
            raise ValueError("body and text are not allowed together.")
        elif body is not None:
            self.body = body
        elif text is not None:
            self.text = text
        else:
            self.body = None

    @property
    def body(self):
        return self._body

    @body.setter
    def body(self, body):
        if body is not None and not isinstance(body, bytes):
            raise TypeError('body argument must be bytes (%r)', type(body))
        self._body = body
        if body is not None:
            self.content_length = len(body)
        else:
            self.content_length = 0

    @property
    def text(self):
        return self._body.decode(self.charset or 'utf-8')

    @text.setter
    def text(self, text):
        if text is not None and not isinstance(text, str):
            raise TypeError('text argument must be str (%r)', type(text))

        if self.content_type == 'application/octet-stream':
            self.content_type = 'text/plain'
        if self.charset is None:
            self.charset = 'utf-8'

        self.body = text.encode(self.charset)

    @asyncio.coroutine
    def write_eof(self):
        body = self._body
        if body is not None:
            self.write(body)
        yield from super().write_eof()


class WebSocketResponse(StreamResponse):

    def __init__(self, *, protocols=()):
        super().__init__(status=101)
        self._protocols = protocols
        self._protocol = None
        self._writer = None
        self._reader = None
        self._closing = False
        self._loop = None
        self._closing_fut = None

    def start(self, request):
        # make pre-check to don't hide it by do_handshake() exceptions
        resp_impl = self._start_pre_check(request)
        if resp_impl is not None:
            return resp_impl

        try:
            status, headers, parser, writer, protocol = do_handshake(
                request.method, request.headers, request.transport,
                self._protocols)
        except HttpProcessingError as err:
            if err.code == 405:
                raise HTTPMethodNotAllowed(request.method, ['GET'])
            elif err.code == 400:
                raise HTTPBadRequest(text=err.message)
            else:  # pragma: no cover
                raise HTTPInternalServerError() from err

        if self.status != status:
            self.set_status(status)
        for k, v in headers:
            self.headers[k] = v
        self.force_close()

        resp_impl = super().start(request)

        self._reader = request._reader.set_parser(parser)
        self._writer = writer
        self._protocol = protocol
        self._loop = request.app.loop
        self._closing_fut = asyncio.Future(loop=self._loop)

        return resp_impl

    def can_start(self, request):
        if self._writer is not None:
            raise RuntimeError('Already started')
        try:
            _, _, _, _, protocol = do_handshake(
                request.method, request.headers, request.transport,
                self._protocols)
        except HttpProcessingError:
            return False, None
        else:
            return True, protocol

    @property
    def closing(self):
        return self._closing

    @property
    def protocol(self):
        return self._protocol

    def ping(self):
        if self._writer is None:
            raise RuntimeError('Call .start() first')
        if self._closing:
            raise RuntimeError('websocket connection is closing')
        self._writer.ping()

    def send_str(self, data):
        if self._writer is None:
            raise RuntimeError('Call .start() first')
        if self._closing:
            raise RuntimeError('websocket connection is closing')
        if not isinstance(data, str):
            raise TypeError('data argument must be str (%r)', type(data))
        self._writer.send(data, binary=False)

    def send_bytes(self, data):
        if self._writer is None:
            raise RuntimeError('Call .start() first')
        if self._closing:
            raise RuntimeError('websocket connection is closing')
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError('data argument must be byte-ish (%r)',
                            type(data))
        self._writer.send(data, binary=True)

    def close(self, *, code=1000, message=b''):
        if self._writer is None:
            raise RuntimeError('Call .start() first')
        if not self._closing:
            self._closing = True
            self._writer.close(code, message)
        else:
            raise RuntimeError('Already closing')

    @asyncio.coroutine
    def wait_closed(self):
        if self._closing_fut is None:
            raise RuntimeError('Call .start() first')
        yield from self._closing_fut

    @asyncio.coroutine
    def receive(self):
        if self._reader is None:
            raise RuntimeError('Call .start() first')
        while True:
            msg = yield from self._reader.read()

            if msg.tp == MSG_CLOSE:
                if self._closing:
                    exc = WebSocketDisconnectedError(msg.data, msg.extra)
                    self._closing_fut.set_exception(exc)
                    raise exc
                else:
                    self._closing = True
                    self._writer.close(msg.data, msg.extra)
                    yield from self.drain()
                    exc = WebSocketDisconnectedError(msg.data, msg.extra)
                    self._closing_fut.set_exception(exc)
                    raise exc
            elif not self._closing:
                if msg.tp == MSG_PING:
                    self._writer.pong()
                elif msg.tp == MSG_TEXT:
                    return msg.data
                elif msg.tp == MSG_BINARY:
                    return msg.data

    def write(self, data):
        raise RuntimeError("Cannot call .write() for websocket")


############################################################
# HTTP Exceptions
############################################################

class HTTPException(Response, Exception):

    # You should set in subclasses:
    # status = 200

    status_code = None

    def __init__(self, *, headers=None, reason=None,
                 body=None, text=None, content_type=None):
        Response.__init__(self, status=self.status_code,
                          headers=headers, reason=reason,
                          body=body, text=text, content_type=content_type)
        Exception.__init__(self, self.reason)
        if self.body is None:
            self.text = "{}: {}".format(self.status, self.reason)


class HTTPError(HTTPException):
    """Base class for exceptions with status codes in the 400s and 500s."""


class HTTPRedirection(HTTPException):
    """Base class for exceptions with status codes in the 300s."""


class HTTPSuccessful(HTTPException):
    """Base class for exceptions with status codes in the 200s."""


class HTTPOk(HTTPSuccessful):
    status_code = 200


class HTTPCreated(HTTPSuccessful):
    status_code = 201


class HTTPAccepted(HTTPSuccessful):
    status_code = 202


class HTTPNonAuthoritativeInformation(HTTPSuccessful):
    status_code = 203


class HTTPNoContent(HTTPSuccessful):
    status_code = 204


class HTTPResetContent(HTTPSuccessful):
    status_code = 205


class HTTPPartialContent(HTTPSuccessful):
    status_code = 206


############################################################
# 3xx redirection
############################################################


class _HTTPMove(HTTPRedirection):

    def __init__(self, location, *, headers=None, reason=None,
                 body=None, text=None, content_type=None):
        if not location:
            raise ValueError("HTTP redirects need a location to redirect to.")
        super().__init__(headers=headers, reason=reason,
                         body=body, text=text, content_type=content_type)
        self.headers['Location'] = location
        self.location = location


class HTTPMultipleChoices(_HTTPMove):
    status_code = 300


class HTTPMovedPermanently(_HTTPMove):
    status_code = 301


class HTTPFound(_HTTPMove):
    status_code = 302


# This one is safe after a POST (the redirected location will be
# retrieved with GET):
class HTTPSeeOther(_HTTPMove):
    status_code = 303


class HTTPNotModified(HTTPRedirection):
    # FIXME: this should include a date or etag header
    status_code = 304


class HTTPUseProxy(_HTTPMove):
    # Not a move, but looks a little like one
    status_code = 305


class HTTPTemporaryRedirect(_HTTPMove):
    status_code = 307


############################################################
# 4xx client error
############################################################


class HTTPClientError(HTTPError):
    pass


class HTTPBadRequest(HTTPClientError):
    status_code = 400


class HTTPUnauthorized(HTTPClientError):
    status_code = 401


class HTTPPaymentRequired(HTTPClientError):
    status_code = 402


class HTTPForbidden(HTTPClientError):
    status_code = 403


class HTTPNotFound(HTTPClientError):
    status_code = 404


class HTTPMethodNotAllowed(HTTPClientError):
    status_code = 405

    def __init__(self, method, allowed_methods, *, headers=None, reason=None,
                 body=None, text=None, content_type=None):
        allow = ','.join(sorted(allowed_methods))
        super().__init__(headers=headers, reason=reason,
                         body=body, text=text, content_type=content_type)
        self.headers['Allow'] = allow
        self.allowed_methods = allowed_methods
        self.method = method.upper()


class HTTPNotAcceptable(HTTPClientError):
    status_code = 406


class HTTPProxyAuthenticationRequired(HTTPClientError):
    status_code = 407


class HTTPRequestTimeout(HTTPClientError):
    status_code = 408


class HTTPConflict(HTTPClientError):
    status_code = 409


class HTTPGone(HTTPClientError):
    status_code = 410


class HTTPLengthRequired(HTTPClientError):
    status_code = 411


class HTTPPreconditionFailed(HTTPClientError):
    status_code = 412


class HTTPRequestEntityTooLarge(HTTPClientError):
    status_code = 413


class HTTPRequestURITooLong(HTTPClientError):
    status_code = 414


class HTTPUnsupportedMediaType(HTTPClientError):
    status_code = 415


class HTTPRequestRangeNotSatisfiable(HTTPClientError):
    status_code = 416


class HTTPExpectationFailed(HTTPClientError):
    status_code = 417


############################################################
# 5xx Server Error
############################################################
#  Response status codes beginning with the digit "5" indicate cases in
#  which the server is aware that it has erred or is incapable of
#  performing the request. Except when responding to a HEAD request, the
#  server SHOULD include an entity containing an explanation of the error
#  situation, and whether it is a temporary or permanent condition. User
#  agents SHOULD display any included entity to the user. These response
#  codes are applicable to any request method.


class HTTPServerError(HTTPError):
    pass


class HTTPInternalServerError(HTTPServerError):
    status_code = 500


class HTTPNotImplemented(HTTPServerError):
    status_code = 501


class HTTPBadGateway(HTTPServerError):
    status_code = 502


class HTTPServiceUnavailable(HTTPServerError):
    status_code = 503


class HTTPGatewayTimeout(HTTPServerError):
    status_code = 504


class HTTPVersionNotSupported(HTTPServerError):
    status_code = 505


############################################################
# UrlDispatcher implementation
############################################################


class UrlMappingMatchInfo(dict, AbstractMatchInfo):

    def __init__(self, match_dict, route):
        super().__init__(match_dict)
        self._route = route

    @property
    def handler(self):
        return self._route.handler

    @property
    def route(self):
        return self._route


class Route(metaclass=abc.ABCMeta):

    def __init__(self, method, handler, name):
        self._method = method
        self._handler = handler
        self._name = name

    @property
    def method(self):
        return self._method

    @property
    def handler(self):
        return self._handler

    @property
    def name(self):
        return self._name

    @abc.abstractmethod
    def match(self, path):
        """Return dict with info for given path or
        None if route cannot process path."""

    @abc.abstractmethod
    def url(self, **kwargs):
        """Construct url for route with additional params."""

    @staticmethod
    def _append_query(url, query):
        if query is not None:
            return url + "?" + urlencode(query)
        else:
            return url


class PlainRoute(Route):

    def __init__(self, method, handler, name, path):
        super().__init__(method, handler, name)
        self._path = path

    def match(self, path):
        # string comparsion about 10 times faster than regexp matching
        if self._path == path:
            return {}
        else:
            return None

    def url(self, *, query=None):
        return self._append_query(self._path, query)

    def __repr__(self):
        name = "'" + self.name + "' " if self.name is not None else ""
        return "<PlainRoute {name}[{method}] {path} -> {handler!r}".format(
            name=name, method=self.method, path=self._path,
            handler=self.handler)


class DynamicRoute(Route):

    def __init__(self, method, handler, name, pattern, formatter):
        super().__init__(method, handler, name)
        self._pattern = pattern
        self._formatter = formatter

    def match(self, path):
        match = self._pattern.match(path)
        if match is None:
            return None
        else:
            return match.groupdict()

    def url(self, *, parts, query=None):
        url = self._formatter.format_map(parts)
        return self._append_query(url, query)

    def __repr__(self):
        name = "'" + self.name + "' " if self.name is not None else ""
        return ("<DynamicRoute {name}[{method}] {formatter} -> {handler!r}"
                .format(name=name, method=self.method,
                        formatter=self._formatter, handler=self.handler))


class StaticRoute(Route):

    def __init__(self, name, prefix, directory):
        assert prefix.startswith('/'), prefix
        assert prefix.endswith('/'), prefix
        super().__init__('GET', self.handle, name)
        self._prefix = prefix
        self._prefix_len = len(self._prefix)
        self._directory = directory

    def match(self, path):
        if not path.startswith(self._prefix):
            return None
        return {'filename': path[self._prefix_len:]}

    def url(self, *, filename, query=None):
        while filename.startswith('/'):
            filename = filename[1:]
        url = self._prefix + filename
        return self._append_query(url, query)

    @asyncio.coroutine
    def handle(self, request):
        resp = StreamResponse()
        filename = request.match_info['filename']
        filepath = os.path.join(self._directory, filename)
        if '..' in filename:
            raise HTTPNotFound()
        if not os.path.exists(filepath) or not os.path.isfile(filepath):
            raise HTTPNotFound()

        ct = mimetypes.guess_type(filename)[0]
        if not ct:
            ct = 'application/octet-stream'
        resp.content_type = ct

        resp.headers['transfer-encoding'] = 'chunked'
        resp.start(request)

        with open(filepath, 'rb') as f:
            chunk = f.read(8192)
            while chunk:
                resp.write(chunk)
                chunk = f.read(8192)

        yield from resp.write_eof()
        return resp

    def __repr__(self):
        name = "'" + self.name + "' " if self.name is not None else ""
        return "<StaticRoute {name}[{method}] {path} -> {directory!r}".format(
            name=name, method=self.method, path=self._prefix,
            directory=self._directory)


class UrlDispatcher(AbstractRouter, collections.abc.Mapping):

    DYN = re.compile(r'^\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*)\}$')
    DYN_WITH_RE = re.compile(
        r'^\{(?P<var>[a-zA-Z][_a-zA-Z0-9]*):(?P<re>.+)\}$')
    GOOD = r'[^{}/]+'
    PLAIN = re.compile('^' + GOOD + '$')

    METHODS = {'POST', 'GET', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'}

    def __init__(self):
        super().__init__()
        self._urls = []
        self._routes = {}

    @asyncio.coroutine
    def resolve(self, request):
        path = request.path
        method = request.method
        allowed_methods = set()
        for route in self._urls:
            match_dict = route.match(path)
            if match_dict is None:
                continue
            route_method = route.method
            if route_method != method:
                allowed_methods.add(route_method)
            else:
                return UrlMappingMatchInfo(match_dict, route)
        else:
            if allowed_methods:
                raise HTTPMethodNotAllowed(method, allowed_methods)
            else:
                raise HTTPNotFound()

    def __iter__(self):
        return iter(self._routes)

    def __len__(self):
        return len(self._routes)

    def __contains__(self, name):
        return name in self._routes

    def __getitem__(self, name):
        return self._routes[name]

    def _register_endpoint(self, route):
        name = route.name
        if name is not None:
            if name in self._routes:
                raise ValueError('Duplicate {!r}, '
                                 'already handled by {!r}'
                                 .format(name, self._routes[name]))
            else:
                self._routes[name] = route
        self._urls.append(route)

    def add_route(self, method, path, handler, *, name=None):
        assert path.startswith('/')
        assert callable(handler), handler
        if not asyncio.iscoroutinefunction(handler):
            handler = asyncio.coroutine(handler)
        method = method.upper()
        assert method in self.METHODS, method
        parts = []
        factory = PlainRoute
        for part in path.split('/'):
            if not part:
                continue
            match = self.DYN.match(part)
            if match:
                parts.append('(?P<' + match.group('var') + '>' +
                             self.GOOD + ')')
                factory = DynamicRoute
                continue

            match = self.DYN_WITH_RE.match(part)
            if match:
                parts.append('(?P<' + match.group('var') + '>' +
                             match.group('re') + ')')
                factory = DynamicRoute
                continue
            if self.PLAIN.match(part):
                parts.append(re.escape(part))
                continue
            raise ValueError("Invalid path '{}'['{}']".format(path, part))
        if factory is PlainRoute:
            route = PlainRoute(method, handler, name, path)
        else:
            pattern = '/' + '/'.join(parts)
            if path.endswith('/') and pattern != '/':
                pattern += '/'
            try:
                compiled = re.compile('^' + pattern + '$')
            except re.error as exc:
                raise ValueError(
                    "Bad pattern '{}': {}".format(pattern, exc)) from None
            route = DynamicRoute(method, handler, name, compiled, path)
        self._register_endpoint(route)
        return route

    def add_static(self, prefix, path, *, name=None):
        """
        Adds static files view
        :param prefix - url prefix
        :param path - folder with files
        """
        assert prefix.startswith('/')
        assert os.path.isdir(path), 'Path does not directory %s' % path
        path = os.path.abspath(path)
        if not prefix.endswith('/'):
            prefix += '/'
        route = StaticRoute(name, prefix, path)
        self._register_endpoint(route)
        return route


############################################################
# Application implementation
############################################################


class RequestHandler(ServerHttpProtocol):

    def __init__(self, manager, app, router, **kwargs):
        super().__init__(**kwargs)

        self._manager = manager
        self._app = app
        self._router = router
        self._middlewares = app.middlewares

    def connection_made(self, transport):
        super().connection_made(transport)

        self._manager.connection_made(self, transport)

    def connection_lost(self, exc):
        self._manager.connection_lost(self, exc)

        super().connection_lost(exc)

    @asyncio.coroutine
    def handle_request(self, message, payload):
        now = self._loop.time()

        app = self._app
        request = Request(app, message, payload,
                          self.transport, self.reader, self.writer,
                          self.keep_alive_timeout)
        try:
            match_info = yield from self._router.resolve(request)

            assert isinstance(match_info, AbstractMatchInfo), match_info

            request._match_info = match_info
            handler = match_info.handler

            for factory in reversed(self._middlewares):
                handler = yield from factory(app, handler)
            resp = yield from handler(request)

            if not isinstance(resp, StreamResponse):
                raise RuntimeError(
                    ("Handler {!r} should return response instance, "
                     "got {!r} [middlewares {!r}]").format(
                         match_info.handler,
                         type(resp),
                         self._middlewares))
        except HTTPException as exc:
            resp = exc

        resp_msg = resp.start(request)
        yield from resp.write_eof()

        # notify server about keep-alive
        self.keep_alive(resp_msg.keep_alive())

        # log access
        self.log_access(message, None, resp_msg, self._loop.time() - now)


class RequestHandlerFactory:

    def __init__(self, app, router, *,
                 handler=RequestHandler, loop=None, **kwargs):
        self._app = app
        self._router = router
        self._handler = handler
        self._loop = loop
        self._connections = {}
        self._kwargs = kwargs
        self._kwargs.setdefault('logger', app.logger)

    @property
    def connections(self):
        return list(self._connections.keys())

    def connection_made(self, handler, transport):
        self._connections[handler] = transport

    def connection_lost(self, handler, exc=None):
        if handler in self._connections:
            del self._connections[handler]

    @asyncio.coroutine
    def finish_connections(self, timeout=None):
        for handler in self._connections.keys():
            handler.closing()

        def cleanup():
            sleep = 0.05
            while self._connections:
                yield from asyncio.sleep(sleep, loop=self._loop)
                if sleep < 5:
                    sleep = sleep * 2

        if timeout:
            try:
                yield from asyncio.wait_for(
                    cleanup(), timeout, loop=self._loop)
            except asyncio.TimeoutError:
                self._app.logger.warning(
                    "Not all connections are closed (pending: %d)",
                    len(self._connections))

        for transport in self._connections.values():
            transport.close()

        self._connections.clear()

    def __call__(self):
        return self._handler(
            self, self._app, self._router, loop=self._loop, **self._kwargs)


class Application(dict):

    def __init__(self, *, logger=web_logger, loop=None,
                 router=None, handler_factory=RequestHandlerFactory,
                 middlewares=(), **kwargs):
        if loop is None:
            loop = asyncio.get_event_loop()
        if router is None:
            router = UrlDispatcher()
        assert isinstance(router, AbstractRouter), router

        self._router = router
        self._handler_factory = handler_factory
        self._finish_callbacks = []
        self._loop = loop
        self.logger = logger

        self.update(**kwargs)
        for factory in middlewares:
            assert asyncio.iscoroutinefunction(factory), factory
        self._middlewares = tuple(middlewares)

    @property
    def router(self):
        return self._router

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

    @property
    def middlewares(self):
        return self._middlewares

    def make_handler(self, **kwargs):
        return self._handler_factory(
            self, self.router, loop=self.loop, **kwargs)

    @asyncio.coroutine
    def finish(self):
        callbacks = self._finish_callbacks
        self._finish_callbacks = []

        for (cb, args, kwargs) in callbacks:
            try:
                res = cb(self, *args, **kwargs)
                if (asyncio.iscoroutine(res) or
                        isinstance(res, asyncio.Future)):
                    yield from res
            except Exception as exc:
                self._loop.call_exception_handler({
                    'message': "Error in finish callback",
                    'exception': exc,
                    'application': self,
                })

    def register_on_finish(self, func, *args, **kwargs):
        self._finish_callbacks.insert(0, (func, args, kwargs))

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