{
    "file_diffs": [
        {
            "old_file_content": "CHANGES\n=======\n\n0.17.0a0 (XX-XX-XXXX)\n---------------------\n\n- Make StaticRoute support Last-Modified and If-Modified-Since headers #386\n\n- Add Request.if_modified_since and Stream.Response.last_modified properties\n\n- Fix deflate compression when writing a chunked response #395\n\n- Request's content-length header is cleared now after redirect from\n  POST method #391\n\n- Return a 400 if server received a non HTTP content #405\n\n- Fix keep-alive support for aiohttp clients #406\n\n- Allow gzip compression in high-level server response interface #403\n\n- Rename TCPConnector.resolve and family to dns_cache #415\n\n- Make UrlDispatcher ignore quoted characters during url matching #414\n  Backward-compatibility warning: this may change the url matched by\n  your queries if they send quoted characted (like %2F for /) #414\n\n- Use optional cchardet accelerator if present #418\n\n- Borrow loop from Connector in ClientSession if loop is not set\n\n- Add context manager support to ClientSession for session closing.\n\n- Add toplevel get(), post(), put(), head(), delete(), options(),\n  patch() coroutines.\n\n- Fix IPv6 support for client API #425\n\n- Pass ssl context through proxy connector #421\n\n- Make the rule: path for add_route should start with slash\n\n- Don't process request finishing by low-level server on closed event loop\n\n- Don't override data if multiple files are uploaded with same key #433\n\n\n0.16.5 (06-13-2015)\n-------------------\n\n- Get rid of all comprehensions and yielding in _multidict #410\n\n\n0.16.4 (06-13-2015)\n-------------------\n\n- Don't clear current exception in multidict's `__repr__` (cythonized\n  versions) #410\n\n\n0.16.3 (05-30-2015)\n-------------------\n\n- Fix StaticRoute vulnerability to directory traversal attacks #380\n\n\n0.16.2 (05-27-2015)\n-------------------\n\n- Update python version required for `__del__` usage: it's actially\n  3.4.1 instead of 3.4.0\n\n- Add check for presence of loop.is_closed() method before call the\n  former #378\n\n\n0.16.1 (05-27-2015)\n-------------------\n\n- Fix regression in static file handling #377\n\n0.16.0 (05-26-2015)\n-------------------\n\n- Unset waiter future after cancellation #363\n\n- Update request url with query parameters #372\n\n- Support new `fingerprint` param of TCPConnector to enable verifying\n  ssl certificates via md5, sha1, or sha256 digest #366\n\n- Setup uploaded filename if field value is binary and transfer\n  encoding is not specified #349\n\n- Implement `ClientSession.close()` method\n\n- Implement `connector.closed` readonly property\n\n- Implement `ClientSession.closed` readonly property\n\n- Implement `ClientSession.connector` readonly property\n\n- Implement `ClientSession.detach` method\n\n- Add `__del__` to client-side objects: sessions, connectors,\n  connections, requests, responses.\n\n- Refactor connections cleanup by connector #357\n\n- Add `limit` parameter to connector constructor #358\n\n- Add `request.has_body` property #364\n\n- Add `response_class` parameter to `ws_connect()` #367\n\n- `ProxyConnector` doesn't support keep-alive requests by default\n  starting from now #368\n\n- Add `connector.force_close` property\n\n- Add ws_connect to ClientSession #374\n\n- Support optional `chunk_size` parameter in `router.add_static()`\n",
            "new_file_content": "CHANGES\n=======\n\n0.17.0a0 (XX-XX-XXXX)\n---------------------\n\n- Make StaticRoute support Last-Modified and If-Modified-Since headers #386\n\n- Add Request.if_modified_since and Stream.Response.last_modified properties\n\n- Fix deflate compression when writing a chunked response #395\n\n- Request's content-length header is cleared now after redirect from\n  POST method #391\n\n- Return a 400 if server received a non HTTP content #405\n\n- Fix keep-alive support for aiohttp clients #406\n\n- Allow gzip compression in high-level server response interface #403\n\n- Rename TCPConnector.resolve and family to dns_cache #415\n\n- Make UrlDispatcher ignore quoted characters during url matching #414\n  Backward-compatibility warning: this may change the url matched by\n  your queries if they send quoted characted (like %2F for /) #414\n\n- Use optional cchardet accelerator if present #418\n\n- Borrow loop from Connector in ClientSession if loop is not set\n\n- Add context manager support to ClientSession for session closing.\n\n- Add toplevel get(), post(), put(), head(), delete(), options(),\n  patch() coroutines.\n\n- Fix IPv6 support for client API #425\n\n- Pass ssl context through proxy connector #421\n\n- Make the rule: path for add_route should start with slash\n\n- Don't process request finishing by low-level server on closed event loop\n\n- Don't override data if multiple files are uploaded with same key #433\n\n- Ensure multipart.BodyPartReader.read_chunk read all the necessary data\n  to avoid false assertions about malformed multipart payload\n\n\n0.16.5 (06-13-2015)\n-------------------\n\n- Get rid of all comprehensions and yielding in _multidict #410\n\n\n0.16.4 (06-13-2015)\n-------------------\n\n- Don't clear current exception in multidict's `__repr__` (cythonized\n  versions) #410\n\n\n0.16.3 (05-30-2015)\n-------------------\n\n- Fix StaticRoute vulnerability to directory traversal attacks #380\n\n\n0.16.2 (05-27-2015)\n-------------------\n\n- Update python version required for `__del__` usage: it's actially\n  3.4.1 instead of 3.4.0\n\n- Add check for presence of loop.is_closed() method before call the\n  former #378\n\n\n0.16.1 (05-27-2015)\n-------------------\n\n- Fix regression in static file handling #377\n\n0.16.0 (05-26-2015)\n-------------------\n\n- Unset waiter future after cancellation #363\n\n- Update request url with query parameters #372\n\n- Support new `fingerprint` param of TCPConnector to enable verifying\n  ssl certificates via md5, sha1, or sha256 digest #366\n\n- Setup uploaded filename if field value is binary and transfer\n  encoding is not specified #349\n\n- Implement `ClientSession.close()` method\n\n- Implement `connector.closed` readonly property\n\n- Implement `ClientSession.closed` readonly property\n\n- Implement `ClientSession.connector` readonly property\n\n- Implement `ClientSession.detach` method\n\n- Add `__del__` to client-side objects: sessions, connectors,\n  connections, requests, responses.\n\n- Refactor connections cleanup by connector #357\n\n- Add `limit` parameter to connector constructor #358\n\n- Add `request.has_body` property #364\n\n- Add `response_class` parameter to `ws_connect()` #367\n\n- `ProxyConnector` doesn't support keep-alive requests by default\n  starting from now #368\n\n- Add `connector.force_close` property\n\n- Add ws_connect to ClientSession #374\n\n- Support optional `chunk_size` parameter in `router.add_static()`\n",
            "header": {
                "file": {
                    "path": "CHANGES.txt"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "ee98dce7",
                "new_commit_hash": "95c189f0",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/CHANGES.txt"
            },
            "plus_file": {
                "path": "b/CHANGES.txt"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 44,
                            "length": 6
                        },
                        "new_range": {
                            "start": 44,
                            "length": 9
                        },
                        "section": "CHANGES"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "- Don't override data if multiple files are uploaded with same key #433",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "- Ensure multipart.BodyPartReader.read_chunk read all the necessary data",
                                "type": "added"
                            },
                            {
                                "content": "  to avoid false assertions about malformed multipart payload",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "0.16.5 (06-13-2015)",
                                "type": "context"
                            },
                            {
                                "content": "-------------------",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport binascii\nimport base64\nimport json\nimport io\nimport mimetypes\nimport os\nimport re\nimport uuid\nimport warnings\nimport zlib\nfrom urllib.parse import quote, unquote, urlencode, parse_qsl\nfrom collections import Mapping, Sequence\n\nfrom .helpers import parse_mimetype\nfrom .multidict import CIMultiDict\nfrom .protocol import HttpParser\nfrom .hdrs import (\n    CONTENT_DISPOSITION,\n    CONTENT_ENCODING,\n    CONTENT_LENGTH,\n    CONTENT_TRANSFER_ENCODING,\n    CONTENT_TYPE\n)\n\n\n__all__ = ('MultipartReader', 'MultipartWriter',\n           'BodyPartReader', 'BodyPartWriter',\n           'BadContentDispositionHeader', 'BadContentDispositionParam',\n           'parse_content_disposition', 'content_disposition_filename')\n\n\nCHAR = set(chr(i) for i in range(0, 128))\nCTL = set(chr(i) for i in range(0, 32)) | {chr(127), }\nSEPARATORS = {'(', ')', '<', '>', '@', ',', ';', ':', '\\\\', '\"', '/', '[', ']',\n              '?', '=', '{', '}', ' ', chr(9)}\nTOKEN = CHAR ^ CTL ^ SEPARATORS\n\n\nclass BadContentDispositionHeader(RuntimeWarning):\n    pass\n\n\nclass BadContentDispositionParam(RuntimeWarning):\n    pass\n\n\ndef parse_content_disposition(header):\n    def is_token(string):\n        return string and TOKEN >= set(string)\n\n    def is_quoted(string):\n        return string[0] == string[-1] == '\"'\n\n    def is_rfc5987(string):\n        return is_token(string) and string.count(\"'\") == 2\n\n    def is_extended_param(string):\n        return string.endswith('*')\n\n    def is_continuous_param(string):\n        pos = string.find('*') + 1\n        if not pos:\n            return False\n        substring = string[pos:-1] if string.endswith('*') else string[pos:]\n        return substring.isdigit()\n\n    def unescape(text, *, chars=''.join(map(re.escape, CHAR))):\n        return re.sub('\\\\\\\\([{}])'.format(chars), '\\\\1', text)\n\n    if not header:\n        return None, {}\n\n    disptype, *parts = header.split(';')\n    if not is_token(disptype):\n        warnings.warn(BadContentDispositionHeader(header))\n        return None, {}\n\n    params = {}\n    for item in parts:\n        if '=' not in item:\n            warnings.warn(BadContentDispositionHeader(header))\n            return None, {}\n\n        key, value = item.split('=', 1)\n        key = key.lower().strip()\n        value = value.lstrip()\n\n        if key in params:\n            warnings.warn(BadContentDispositionHeader(header))\n            return None, {}\n\n        if not is_token(key):\n            warnings.warn(BadContentDispositionParam(item))\n            continue\n\n        elif is_continuous_param(key):\n            if is_quoted(value):\n                value = unescape(value[1:-1])\n            elif not is_token(value):\n                warnings.warn(BadContentDispositionParam(item))\n                continue\n\n        elif is_extended_param(key):\n            if is_rfc5987(value):\n                encoding, _, value = value.split(\"'\", 2)\n                encoding = encoding or 'utf-8'\n            else:\n                warnings.warn(BadContentDispositionParam(item))\n                continue\n\n            try:\n                value = unquote(value, encoding, 'strict')\n            except UnicodeDecodeError:  # pragma: nocover\n                warnings.warn(BadContentDispositionParam(item))\n                continue\n\n        else:\n            if is_quoted(value):\n                value = unescape(value[1:-1].lstrip('\\\\/'))\n            elif not is_token(value):\n                warnings.warn(BadContentDispositionHeader(header))\n                return None, {}\n\n        params[key] = value\n\n    return disptype.lower(), params\n\n\ndef content_disposition_filename(params):\n    if not params:\n        return None\n    elif 'filename*' in params:\n        return params['filename*']\n    elif 'filename' in params:\n        return params['filename']\n    else:\n        parts = []\n        fnparams = sorted((key, value)\n                          for key, value in params.items()\n                          if key.startswith('filename*'))\n        for num, (key, value) in enumerate(fnparams):\n            _, tail = key.split('*', 1)\n            if tail.endswith('*'):\n                tail = tail[:-1]\n            if tail == str(num):\n                parts.append(value)\n            else:\n                break\n        if not parts:\n            return None\n        value = ''.join(parts)\n        if \"'\" in value:\n            encoding, _, value = value.split(\"'\", 2)\n            encoding = encoding or 'utf-8'\n            return unquote(value, encoding, 'strict')\n        return value\n\n\nclass MultipartResponseWrapper(object):\n    \"\"\"Wrapper around the :class:`MultipartBodyReader` to take care about\n    underlying connection and close it when it needs in.\"\"\"\n\n    def __init__(self, resp, stream):\n        self.resp = resp\n        self.stream = stream\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` when all response data had been read.\n\n        :rtype: bool\n        \"\"\"\n        return self.resp.content.at_eof()\n\n    @asyncio.coroutine\n    def next(self):\n        \"\"\"Emits next multipart reader object.\"\"\"\n        item = yield from self.stream.next()\n        if self.stream.at_eof():\n            yield from self.release()\n        return item\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Releases the connection gracefully, reading all the content\n        to the void.\"\"\"\n        yield from self.resp.release()\n\n\nclass BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n            assert b'\\r\\n' == (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)\n\n\nclass MultipartReader(object):\n    \"\"\"Multipart body reader.\"\"\"\n\n    #: Response wrapper, used when multipart readers constructs from response.\n    response_wrapper_cls = MultipartResponseWrapper\n    #: Multipart reader class, used to handle multipart/* body parts.\n    #: None points to type(self)\n    multipart_reader_cls = None\n    #: Body part reader class for non multipart/* content types.\n    part_reader_cls = BodyPartReader\n\n    def __init__(self, headers, content):\n        self.headers = headers\n        self._boundary = ('--' + self._get_boundary()).encode()\n        self._content = content\n        self._last_part = None\n        self._at_eof = False\n        self._unread = []\n\n    @classmethod\n    def from_response(cls, response):\n        \"\"\"Constructs reader instance from HTTP response.\n\n        :param response: :class:`~aiohttp.client.ClientResponse` instance\n        \"\"\"\n        obj = cls.response_wrapper_cls(response, cls(response.headers,\n                                                     response.content))\n        return obj\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the final boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    @asyncio.coroutine\n    def next(self):\n        \"\"\"Emits the next multipart body part.\"\"\"\n        if self._at_eof:\n            return\n        yield from self._maybe_release_last_part()\n        yield from self._read_boundary()\n        if self._at_eof:  # we just read the last boundary, nothing to do there\n            return\n        self._last_part = yield from self.fetch_next_part()\n        return self._last_part\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Reads all the body parts to the void till the final boundary.\"\"\"\n        while not self._at_eof:\n            item = yield from self.next()\n            if item is None:\n                break\n            yield from item.release()\n\n    @asyncio.coroutine\n    def fetch_next_part(self):\n        \"\"\"Returns the next body part reader.\"\"\"\n        headers = yield from self._read_headers()\n        return self._get_part_reader(headers)\n\n    def _get_part_reader(self, headers):\n        \"\"\"Dispatches the response by the `Content-Type` header, returning\n        suitable reader instance.\n\n        :param dict headers: Response headers\n        \"\"\"\n        ctype = headers.get(CONTENT_TYPE, '')\n        mtype, *_ = parse_mimetype(ctype)\n        if mtype == 'multipart':\n            if self.multipart_reader_cls is None:\n                return type(self)(headers, self._content)\n            return self.multipart_reader_cls(headers, self._content)\n        else:\n            return self.part_reader_cls(self._boundary, headers, self._content)\n\n    def _get_boundary(self):\n        mtype, *_, params = parse_mimetype(self.headers[CONTENT_TYPE])\n\n        assert mtype == 'multipart', 'multipart/* content type expected'\n\n        if 'boundary' not in params:\n            raise ValueError('boundary missed for Content-Type: %s'\n                             % self.headers[CONTENT_TYPE])\n\n        boundary = params['boundary']\n        if len(boundary) > 70:\n            raise ValueError('boundary %r is too long (70 chars max)'\n                             % boundary)\n\n        return boundary\n\n    @asyncio.coroutine\n    def _readline(self):\n        if self._unread:\n            return self._unread.pop()\n        return (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def _read_boundary(self):\n        chunk = (yield from self._readline()).rstrip()\n        if chunk == self._boundary:\n            pass\n        elif chunk == self._boundary + b'--':\n            self._at_eof = True\n        else:\n            raise ValueError('Invalid boundary %r, expected %r'\n                             % (chunk, self._boundary))\n\n    @asyncio.coroutine\n    def _read_headers(self):\n        lines = ['']\n        while True:\n            chunk = yield from self._content.readline()\n            chunk = chunk.decode().strip()\n            lines.append(chunk)\n            if not chunk:\n                break\n        parser = HttpParser()\n        headers, *_ = parser.parse_headers(lines)\n        return headers\n\n    @asyncio.coroutine\n    def _maybe_release_last_part(self):\n        \"\"\"Ensures that the last read body part is read completely.\"\"\"\n        if self._last_part is not None:\n            if not self._last_part.at_eof():\n                yield from self._last_part.release()\n            self._unread.extend(self._last_part._unread)\n            self._last_part = None\n\n\nclass BodyPartWriter(object):\n    \"\"\"Multipart writer for single body part.\"\"\"\n\n    def __init__(self, obj, headers=None, *, chunk_size=8192):\n        if headers is None:\n            headers = CIMultiDict()\n        elif not isinstance(headers, CIMultiDict):\n            headers = CIMultiDict(headers)\n\n        self.obj = obj\n        self.headers = headers\n        self._chunk_size = chunk_size\n        self._fill_headers_with_defaults()\n\n        self._serialize_map = {\n            bytes: self._serialize_bytes,\n            str: self._serialize_str,\n            io.IOBase: self._serialize_io,\n            MultipartWriter: self._serialize_multipart,\n            ('application', 'json'): self._serialize_json,\n            ('application', 'x-www-form-urlencoded'): self._serialize_form\n        }\n\n    def _fill_headers_with_defaults(self):\n        if CONTENT_TYPE not in self.headers:\n            content_type = self._guess_content_type(self.obj)\n            if content_type is not None:\n                self.headers[CONTENT_TYPE] = content_type\n\n        if CONTENT_LENGTH not in self.headers:\n            content_length = self._guess_content_length(self.obj)\n            if content_length is not None:\n                self.headers[CONTENT_LENGTH] = str(content_length)\n\n        if CONTENT_DISPOSITION not in self.headers:\n            filename = self._guess_filename(self.obj)\n            if filename is not None:\n                self.set_content_disposition('attachment', filename=filename)\n\n    def _guess_content_length(self, obj):\n        if isinstance(obj, bytes):\n            return len(obj)\n        elif isinstance(obj, str):\n            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n            charset = params.get('charset', 'us-ascii')\n            return len(obj.encode(charset))\n        elif isinstance(obj, io.StringIO):\n            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n            charset = params.get('charset', 'us-ascii')\n            return len(obj.getvalue().encode(charset)) - obj.tell()\n        elif isinstance(obj, io.BytesIO):\n            return len(obj.getvalue()) - obj.tell()\n        elif isinstance(obj, io.IOBase):\n            try:\n                return os.fstat(obj.fileno()).st_size - obj.tell()\n            except (AttributeError, OSError):\n                return None\n        else:\n            return None\n\n    def _guess_content_type(self, obj, default='application/octet-stream'):\n        if hasattr(obj, 'name'):\n            name = getattr(obj, 'name')\n            return mimetypes.guess_type(name)[0]\n        elif isinstance(obj, (str, io.StringIO)):\n            return 'text/plain; charset=utf-8'\n        else:\n            return default\n\n    def _guess_filename(self, obj):\n        if isinstance(obj, io.IOBase):\n            name = getattr(obj, 'name', None)\n            if name is not None:\n                return os.path.basename(name)\n\n    def serialize(self):\n        \"\"\"Yields byte chunks for body part.\"\"\"\n\n        has_encoding = (\n            CONTENT_ENCODING in self.headers\n            and self.headers[CONTENT_ENCODING] != 'identity'\n            or CONTENT_TRANSFER_ENCODING in self.headers\n        )\n        if has_encoding:\n            # since we're following streaming approach which doesn't assumes\n            # any intermediate buffers, we cannot calculate real content length\n            # with the specified content encoding scheme. So, instead of lying\n            # about content length and cause reading issues, we have to strip\n            # this information.\n            self.headers.pop(CONTENT_LENGTH, None)\n\n        if self.headers:\n            yield b'\\r\\n'.join(\n                b': '.join(map(lambda i: i.encode('latin1'), item))\n                for item in self.headers.items()\n            )\n        yield b'\\r\\n\\r\\n'\n        yield from self._maybe_encode_stream(self._serialize_obj())\n        yield b'\\r\\n'\n\n    def _serialize_obj(self):\n        obj = self.obj\n        mtype, stype, *_ = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        serializer = self._serialize_map.get((mtype, stype))\n        if serializer is not None:\n            return serializer(obj)\n\n        for key in self._serialize_map:\n            if not isinstance(key, tuple) and isinstance(obj, key):\n                return self._serialize_map[key](obj)\n        return self._serialize_default(obj)\n\n    def _serialize_bytes(self, obj):\n        yield obj\n\n    def _serialize_str(self, obj):\n        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        yield obj.encode(params.get('charset', 'us-ascii'))\n\n    def _serialize_io(self, obj):\n        while True:\n            chunk = obj.read(self._chunk_size)\n            if not chunk:\n                break\n            if isinstance(chunk, str):\n                yield from self._serialize_str(chunk)\n            else:\n                yield from self._serialize_bytes(chunk)\n\n    def _serialize_multipart(self, obj):\n        yield from obj.serialize()\n\n    def _serialize_json(self, obj):\n        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        yield json.dumps(obj).encode(params.get('charset', 'utf-8'))\n\n    def _serialize_form(self, obj):\n        if isinstance(obj, Mapping):\n            obj = list(obj.items())\n        return self._serialize_str(urlencode(obj, doseq=True))\n\n    def _serialize_default(self, obj):\n        raise TypeError('unknown body part type %r' % type(obj))\n\n    def _maybe_encode_stream(self, stream):\n        if CONTENT_ENCODING in self.headers:\n            stream = self._apply_content_encoding(stream)\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            stream = self._apply_content_transfer_encoding(stream)\n        yield from stream\n\n    def _apply_content_encoding(self, stream):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n        if encoding == 'identity':\n            yield from stream\n        elif encoding in ('deflate', 'gzip'):\n            zlib_mode = (16 + zlib.MAX_WBITS\n                         if encoding == 'gzip' else\n                         -zlib.MAX_WBITS)\n            zcomp = zlib.compressobj(wbits=zlib_mode)\n            for chunk in stream:\n                yield zcomp.compress(chunk)\n            else:\n                yield zcomp.flush()\n        else:\n            raise RuntimeError('unknown content encoding: {}'\n                               ''.format(encoding))\n\n    def _apply_content_transfer_encoding(self, stream):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n        if encoding == 'base64':\n            buffer = bytearray()\n            while True:\n                if buffer:\n                    div, mod = divmod(len(buffer), 3)\n                    chunk, buffer = buffer[:div * 3], buffer[div * 3:]\n                    if chunk:\n                        yield base64.b64encode(chunk)\n                chunk = next(stream, None)\n                if not chunk:\n                    if buffer:\n                        yield base64.b64encode(buffer[:])\n                    return\n                buffer.extend(chunk)\n        elif encoding == 'quoted-printable':\n            for chunk in stream:\n                yield binascii.b2a_qp(chunk)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def set_content_disposition(self, disptype, **params):\n        \"\"\"Sets ``Content-Disposition`` header.\n\n        :param str disptype: Disposition type: inline, attachment, form-data.\n                            Should be valid extension token (see RFC 2183)\n        :param dict params: Disposition params\n        \"\"\"\n        if not disptype or not (TOKEN > set(disptype)):\n            raise ValueError('bad content disposition type {!r}'\n                             ''.format(disptype))\n        value = disptype\n        if params:\n            lparams = []\n            for key, val in params.items():\n                if not key or not (TOKEN > set(key)):\n                    raise ValueError('bad content disposition parameter'\n                                     ' {!r}={!r}'.format(key, val))\n                qval = quote(val, '')\n                if key == 'filename':\n                    lparams.append((key, '\"%s\"' % qval))\n                    lparams.append(('filename*', \"utf-8''\" + qval))\n                else:\n                    lparams.append((key, \"%s\" % qval))\n            sparams = '; '.join('='.join(pair) for pair in lparams)\n            value = '; '.join((value, sparams))\n        self.headers[CONTENT_DISPOSITION] = value\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)\n\n\nclass MultipartWriter(object):\n    \"\"\"Multipart body writer.\"\"\"\n\n    #: Body part reader class for non multipart/* content types.\n    part_writer_cls = BodyPartWriter\n\n    def __init__(self, subtype='mixed', boundary=None):\n        boundary = boundary if boundary is not None else uuid.uuid4().hex\n        try:\n            boundary.encode('us-ascii')\n        except UnicodeEncodeError:\n            raise ValueError('boundary should contains ASCII only chars')\n        self.headers = CIMultiDict()\n        self.headers[CONTENT_TYPE] = 'multipart/{}; boundary=\"{}\"'.format(\n            subtype, boundary\n        )\n        self.parts = []\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        pass\n\n    def __iter__(self):\n        return iter(self.parts)\n\n    def __len__(self):\n        return len(self.parts)\n\n    @property\n    def boundary(self):\n        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        return params['boundary'].encode('us-ascii')\n\n    def append(self, obj, headers=None):\n        \"\"\"Adds a new body part to multipart writer.\"\"\"\n        if isinstance(obj, self.part_writer_cls):\n            if headers:\n                obj.headers.update(headers)\n            self.parts.append(obj)\n        else:\n            if not headers:\n                headers = CIMultiDict()\n            self.parts.append(self.part_writer_cls(obj, headers))\n        return self.parts[-1]\n\n    def append_json(self, obj, headers=None):\n        \"\"\"Helper to append JSON part.\"\"\"\n        if not headers:\n            headers = CIMultiDict()\n        headers[CONTENT_TYPE] = 'application/json'\n        return self.append(obj, headers)\n\n    def append_form(self, obj, headers=None):\n        \"\"\"Helper to append form urlencoded part.\"\"\"\n        if not headers:\n            headers = CIMultiDict()\n        headers[CONTENT_TYPE] = 'application/x-www-form-urlencoded'\n        assert isinstance(obj, (Sequence, Mapping))\n        return self.append(obj, headers)\n\n    def serialize(self):\n        \"\"\"Yields multipart byte chunks.\"\"\"\n        if not self.parts:\n            yield b''\n            return\n\n        for part in self.parts:\n            yield b'--' + self.boundary + b'\\r\\n'\n            yield from part.serialize()\n        else:\n            yield b'--' + self.boundary + b'--\\r\\n'\n\n        yield b''\n",
            "new_file_content": "import asyncio\nimport binascii\nimport base64\nimport json\nimport io\nimport mimetypes\nimport os\nimport re\nimport uuid\nimport warnings\nimport zlib\nfrom urllib.parse import quote, unquote, urlencode, parse_qsl\nfrom collections import Mapping, Sequence\n\nfrom .helpers import parse_mimetype\nfrom .multidict import CIMultiDict\nfrom .protocol import HttpParser\nfrom .hdrs import (\n    CONTENT_DISPOSITION,\n    CONTENT_ENCODING,\n    CONTENT_LENGTH,\n    CONTENT_TRANSFER_ENCODING,\n    CONTENT_TYPE\n)\n\n\n__all__ = ('MultipartReader', 'MultipartWriter',\n           'BodyPartReader', 'BodyPartWriter',\n           'BadContentDispositionHeader', 'BadContentDispositionParam',\n           'parse_content_disposition', 'content_disposition_filename')\n\n\nCHAR = set(chr(i) for i in range(0, 128))\nCTL = set(chr(i) for i in range(0, 32)) | {chr(127), }\nSEPARATORS = {'(', ')', '<', '>', '@', ',', ';', ':', '\\\\', '\"', '/', '[', ']',\n              '?', '=', '{', '}', ' ', chr(9)}\nTOKEN = CHAR ^ CTL ^ SEPARATORS\n\n\nclass BadContentDispositionHeader(RuntimeWarning):\n    pass\n\n\nclass BadContentDispositionParam(RuntimeWarning):\n    pass\n\n\ndef parse_content_disposition(header):\n    def is_token(string):\n        return string and TOKEN >= set(string)\n\n    def is_quoted(string):\n        return string[0] == string[-1] == '\"'\n\n    def is_rfc5987(string):\n        return is_token(string) and string.count(\"'\") == 2\n\n    def is_extended_param(string):\n        return string.endswith('*')\n\n    def is_continuous_param(string):\n        pos = string.find('*') + 1\n        if not pos:\n            return False\n        substring = string[pos:-1] if string.endswith('*') else string[pos:]\n        return substring.isdigit()\n\n    def unescape(text, *, chars=''.join(map(re.escape, CHAR))):\n        return re.sub('\\\\\\\\([{}])'.format(chars), '\\\\1', text)\n\n    if not header:\n        return None, {}\n\n    disptype, *parts = header.split(';')\n    if not is_token(disptype):\n        warnings.warn(BadContentDispositionHeader(header))\n        return None, {}\n\n    params = {}\n    for item in parts:\n        if '=' not in item:\n            warnings.warn(BadContentDispositionHeader(header))\n            return None, {}\n\n        key, value = item.split('=', 1)\n        key = key.lower().strip()\n        value = value.lstrip()\n\n        if key in params:\n            warnings.warn(BadContentDispositionHeader(header))\n            return None, {}\n\n        if not is_token(key):\n            warnings.warn(BadContentDispositionParam(item))\n            continue\n\n        elif is_continuous_param(key):\n            if is_quoted(value):\n                value = unescape(value[1:-1])\n            elif not is_token(value):\n                warnings.warn(BadContentDispositionParam(item))\n                continue\n\n        elif is_extended_param(key):\n            if is_rfc5987(value):\n                encoding, _, value = value.split(\"'\", 2)\n                encoding = encoding or 'utf-8'\n            else:\n                warnings.warn(BadContentDispositionParam(item))\n                continue\n\n            try:\n                value = unquote(value, encoding, 'strict')\n            except UnicodeDecodeError:  # pragma: nocover\n                warnings.warn(BadContentDispositionParam(item))\n                continue\n\n        else:\n            if is_quoted(value):\n                value = unescape(value[1:-1].lstrip('\\\\/'))\n            elif not is_token(value):\n                warnings.warn(BadContentDispositionHeader(header))\n                return None, {}\n\n        params[key] = value\n\n    return disptype.lower(), params\n\n\ndef content_disposition_filename(params):\n    if not params:\n        return None\n    elif 'filename*' in params:\n        return params['filename*']\n    elif 'filename' in params:\n        return params['filename']\n    else:\n        parts = []\n        fnparams = sorted((key, value)\n                          for key, value in params.items()\n                          if key.startswith('filename*'))\n        for num, (key, value) in enumerate(fnparams):\n            _, tail = key.split('*', 1)\n            if tail.endswith('*'):\n                tail = tail[:-1]\n            if tail == str(num):\n                parts.append(value)\n            else:\n                break\n        if not parts:\n            return None\n        value = ''.join(parts)\n        if \"'\" in value:\n            encoding, _, value = value.split(\"'\", 2)\n            encoding = encoding or 'utf-8'\n            return unquote(value, encoding, 'strict')\n        return value\n\n\nclass MultipartResponseWrapper(object):\n    \"\"\"Wrapper around the :class:`MultipartBodyReader` to take care about\n    underlying connection and close it when it needs in.\"\"\"\n\n    def __init__(self, resp, stream):\n        self.resp = resp\n        self.stream = stream\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` when all response data had been read.\n\n        :rtype: bool\n        \"\"\"\n        return self.resp.content.at_eof()\n\n    @asyncio.coroutine\n    def next(self):\n        \"\"\"Emits next multipart reader object.\"\"\"\n        item = yield from self.stream.next()\n        if self.stream.at_eof():\n            yield from self.release()\n        return item\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Releases the connection gracefully, reading all the content\n        to the void.\"\"\"\n        yield from self.resp.release()\n\n\nclass BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)\n\n\nclass MultipartReader(object):\n    \"\"\"Multipart body reader.\"\"\"\n\n    #: Response wrapper, used when multipart readers constructs from response.\n    response_wrapper_cls = MultipartResponseWrapper\n    #: Multipart reader class, used to handle multipart/* body parts.\n    #: None points to type(self)\n    multipart_reader_cls = None\n    #: Body part reader class for non multipart/* content types.\n    part_reader_cls = BodyPartReader\n\n    def __init__(self, headers, content):\n        self.headers = headers\n        self._boundary = ('--' + self._get_boundary()).encode()\n        self._content = content\n        self._last_part = None\n        self._at_eof = False\n        self._unread = []\n\n    @classmethod\n    def from_response(cls, response):\n        \"\"\"Constructs reader instance from HTTP response.\n\n        :param response: :class:`~aiohttp.client.ClientResponse` instance\n        \"\"\"\n        obj = cls.response_wrapper_cls(response, cls(response.headers,\n                                                     response.content))\n        return obj\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the final boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    @asyncio.coroutine\n    def next(self):\n        \"\"\"Emits the next multipart body part.\"\"\"\n        if self._at_eof:\n            return\n        yield from self._maybe_release_last_part()\n        yield from self._read_boundary()\n        if self._at_eof:  # we just read the last boundary, nothing to do there\n            return\n        self._last_part = yield from self.fetch_next_part()\n        return self._last_part\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Reads all the body parts to the void till the final boundary.\"\"\"\n        while not self._at_eof:\n            item = yield from self.next()\n            if item is None:\n                break\n            yield from item.release()\n\n    @asyncio.coroutine\n    def fetch_next_part(self):\n        \"\"\"Returns the next body part reader.\"\"\"\n        headers = yield from self._read_headers()\n        return self._get_part_reader(headers)\n\n    def _get_part_reader(self, headers):\n        \"\"\"Dispatches the response by the `Content-Type` header, returning\n        suitable reader instance.\n\n        :param dict headers: Response headers\n        \"\"\"\n        ctype = headers.get(CONTENT_TYPE, '')\n        mtype, *_ = parse_mimetype(ctype)\n        if mtype == 'multipart':\n            if self.multipart_reader_cls is None:\n                return type(self)(headers, self._content)\n            return self.multipart_reader_cls(headers, self._content)\n        else:\n            return self.part_reader_cls(self._boundary, headers, self._content)\n\n    def _get_boundary(self):\n        mtype, *_, params = parse_mimetype(self.headers[CONTENT_TYPE])\n\n        assert mtype == 'multipart', 'multipart/* content type expected'\n\n        if 'boundary' not in params:\n            raise ValueError('boundary missed for Content-Type: %s'\n                             % self.headers[CONTENT_TYPE])\n\n        boundary = params['boundary']\n        if len(boundary) > 70:\n            raise ValueError('boundary %r is too long (70 chars max)'\n                             % boundary)\n\n        return boundary\n\n    @asyncio.coroutine\n    def _readline(self):\n        if self._unread:\n            return self._unread.pop()\n        return (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def _read_boundary(self):\n        chunk = (yield from self._readline()).rstrip()\n        if chunk == self._boundary:\n            pass\n        elif chunk == self._boundary + b'--':\n            self._at_eof = True\n        else:\n            raise ValueError('Invalid boundary %r, expected %r'\n                             % (chunk, self._boundary))\n\n    @asyncio.coroutine\n    def _read_headers(self):\n        lines = ['']\n        while True:\n            chunk = yield from self._content.readline()\n            chunk = chunk.decode().strip()\n            lines.append(chunk)\n            if not chunk:\n                break\n        parser = HttpParser()\n        headers, *_ = parser.parse_headers(lines)\n        return headers\n\n    @asyncio.coroutine\n    def _maybe_release_last_part(self):\n        \"\"\"Ensures that the last read body part is read completely.\"\"\"\n        if self._last_part is not None:\n            if not self._last_part.at_eof():\n                yield from self._last_part.release()\n            self._unread.extend(self._last_part._unread)\n            self._last_part = None\n\n\nclass BodyPartWriter(object):\n    \"\"\"Multipart writer for single body part.\"\"\"\n\n    def __init__(self, obj, headers=None, *, chunk_size=8192):\n        if headers is None:\n            headers = CIMultiDict()\n        elif not isinstance(headers, CIMultiDict):\n            headers = CIMultiDict(headers)\n\n        self.obj = obj\n        self.headers = headers\n        self._chunk_size = chunk_size\n        self._fill_headers_with_defaults()\n\n        self._serialize_map = {\n            bytes: self._serialize_bytes,\n            str: self._serialize_str,\n            io.IOBase: self._serialize_io,\n            MultipartWriter: self._serialize_multipart,\n            ('application', 'json'): self._serialize_json,\n            ('application', 'x-www-form-urlencoded'): self._serialize_form\n        }\n\n    def _fill_headers_with_defaults(self):\n        if CONTENT_TYPE not in self.headers:\n            content_type = self._guess_content_type(self.obj)\n            if content_type is not None:\n                self.headers[CONTENT_TYPE] = content_type\n\n        if CONTENT_LENGTH not in self.headers:\n            content_length = self._guess_content_length(self.obj)\n            if content_length is not None:\n                self.headers[CONTENT_LENGTH] = str(content_length)\n\n        if CONTENT_DISPOSITION not in self.headers:\n            filename = self._guess_filename(self.obj)\n            if filename is not None:\n                self.set_content_disposition('attachment', filename=filename)\n\n    def _guess_content_length(self, obj):\n        if isinstance(obj, bytes):\n            return len(obj)\n        elif isinstance(obj, str):\n            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n            charset = params.get('charset', 'us-ascii')\n            return len(obj.encode(charset))\n        elif isinstance(obj, io.StringIO):\n            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n            charset = params.get('charset', 'us-ascii')\n            return len(obj.getvalue().encode(charset)) - obj.tell()\n        elif isinstance(obj, io.BytesIO):\n            return len(obj.getvalue()) - obj.tell()\n        elif isinstance(obj, io.IOBase):\n            try:\n                return os.fstat(obj.fileno()).st_size - obj.tell()\n            except (AttributeError, OSError):\n                return None\n        else:\n            return None\n\n    def _guess_content_type(self, obj, default='application/octet-stream'):\n        if hasattr(obj, 'name'):\n            name = getattr(obj, 'name')\n            return mimetypes.guess_type(name)[0]\n        elif isinstance(obj, (str, io.StringIO)):\n            return 'text/plain; charset=utf-8'\n        else:\n            return default\n\n    def _guess_filename(self, obj):\n        if isinstance(obj, io.IOBase):\n            name = getattr(obj, 'name', None)\n            if name is not None:\n                return os.path.basename(name)\n\n    def serialize(self):\n        \"\"\"Yields byte chunks for body part.\"\"\"\n\n        has_encoding = (\n            CONTENT_ENCODING in self.headers\n            and self.headers[CONTENT_ENCODING] != 'identity'\n            or CONTENT_TRANSFER_ENCODING in self.headers\n        )\n        if has_encoding:\n            # since we're following streaming approach which doesn't assumes\n            # any intermediate buffers, we cannot calculate real content length\n            # with the specified content encoding scheme. So, instead of lying\n            # about content length and cause reading issues, we have to strip\n            # this information.\n            self.headers.pop(CONTENT_LENGTH, None)\n\n        if self.headers:\n            yield b'\\r\\n'.join(\n                b': '.join(map(lambda i: i.encode('latin1'), item))\n                for item in self.headers.items()\n            )\n        yield b'\\r\\n\\r\\n'\n        yield from self._maybe_encode_stream(self._serialize_obj())\n        yield b'\\r\\n'\n\n    def _serialize_obj(self):\n        obj = self.obj\n        mtype, stype, *_ = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        serializer = self._serialize_map.get((mtype, stype))\n        if serializer is not None:\n            return serializer(obj)\n\n        for key in self._serialize_map:\n            if not isinstance(key, tuple) and isinstance(obj, key):\n                return self._serialize_map[key](obj)\n        return self._serialize_default(obj)\n\n    def _serialize_bytes(self, obj):\n        yield obj\n\n    def _serialize_str(self, obj):\n        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        yield obj.encode(params.get('charset', 'us-ascii'))\n\n    def _serialize_io(self, obj):\n        while True:\n            chunk = obj.read(self._chunk_size)\n            if not chunk:\n                break\n            if isinstance(chunk, str):\n                yield from self._serialize_str(chunk)\n            else:\n                yield from self._serialize_bytes(chunk)\n\n    def _serialize_multipart(self, obj):\n        yield from obj.serialize()\n\n    def _serialize_json(self, obj):\n        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        yield json.dumps(obj).encode(params.get('charset', 'utf-8'))\n\n    def _serialize_form(self, obj):\n        if isinstance(obj, Mapping):\n            obj = list(obj.items())\n        return self._serialize_str(urlencode(obj, doseq=True))\n\n    def _serialize_default(self, obj):\n        raise TypeError('unknown body part type %r' % type(obj))\n\n    def _maybe_encode_stream(self, stream):\n        if CONTENT_ENCODING in self.headers:\n            stream = self._apply_content_encoding(stream)\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            stream = self._apply_content_transfer_encoding(stream)\n        yield from stream\n\n    def _apply_content_encoding(self, stream):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n        if encoding == 'identity':\n            yield from stream\n        elif encoding in ('deflate', 'gzip'):\n            zlib_mode = (16 + zlib.MAX_WBITS\n                         if encoding == 'gzip' else\n                         -zlib.MAX_WBITS)\n            zcomp = zlib.compressobj(wbits=zlib_mode)\n            for chunk in stream:\n                yield zcomp.compress(chunk)\n            else:\n                yield zcomp.flush()\n        else:\n            raise RuntimeError('unknown content encoding: {}'\n                               ''.format(encoding))\n\n    def _apply_content_transfer_encoding(self, stream):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n        if encoding == 'base64':\n            buffer = bytearray()\n            while True:\n                if buffer:\n                    div, mod = divmod(len(buffer), 3)\n                    chunk, buffer = buffer[:div * 3], buffer[div * 3:]\n                    if chunk:\n                        yield base64.b64encode(chunk)\n                chunk = next(stream, None)\n                if not chunk:\n                    if buffer:\n                        yield base64.b64encode(buffer[:])\n                    return\n                buffer.extend(chunk)\n        elif encoding == 'quoted-printable':\n            for chunk in stream:\n                yield binascii.b2a_qp(chunk)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def set_content_disposition(self, disptype, **params):\n        \"\"\"Sets ``Content-Disposition`` header.\n\n        :param str disptype: Disposition type: inline, attachment, form-data.\n                            Should be valid extension token (see RFC 2183)\n        :param dict params: Disposition params\n        \"\"\"\n        if not disptype or not (TOKEN > set(disptype)):\n            raise ValueError('bad content disposition type {!r}'\n                             ''.format(disptype))\n        value = disptype\n        if params:\n            lparams = []\n            for key, val in params.items():\n                if not key or not (TOKEN > set(key)):\n                    raise ValueError('bad content disposition parameter'\n                                     ' {!r}={!r}'.format(key, val))\n                qval = quote(val, '')\n                if key == 'filename':\n                    lparams.append((key, '\"%s\"' % qval))\n                    lparams.append(('filename*', \"utf-8''\" + qval))\n                else:\n                    lparams.append((key, \"%s\" % qval))\n            sparams = '; '.join('='.join(pair) for pair in lparams)\n            value = '; '.join((value, sparams))\n        self.headers[CONTENT_DISPOSITION] = value\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)\n\n\nclass MultipartWriter(object):\n    \"\"\"Multipart body writer.\"\"\"\n\n    #: Body part reader class for non multipart/* content types.\n    part_writer_cls = BodyPartWriter\n\n    def __init__(self, subtype='mixed', boundary=None):\n        boundary = boundary if boundary is not None else uuid.uuid4().hex\n        try:\n            boundary.encode('us-ascii')\n        except UnicodeEncodeError:\n            raise ValueError('boundary should contains ASCII only chars')\n        self.headers = CIMultiDict()\n        self.headers[CONTENT_TYPE] = 'multipart/{}; boundary=\"{}\"'.format(\n            subtype, boundary\n        )\n        self.parts = []\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        pass\n\n    def __iter__(self):\n        return iter(self.parts)\n\n    def __len__(self):\n        return len(self.parts)\n\n    @property\n    def boundary(self):\n        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        return params['boundary'].encode('us-ascii')\n\n    def append(self, obj, headers=None):\n        \"\"\"Adds a new body part to multipart writer.\"\"\"\n        if isinstance(obj, self.part_writer_cls):\n            if headers:\n                obj.headers.update(headers)\n            self.parts.append(obj)\n        else:\n            if not headers:\n                headers = CIMultiDict()\n            self.parts.append(self.part_writer_cls(obj, headers))\n        return self.parts[-1]\n\n    def append_json(self, obj, headers=None):\n        \"\"\"Helper to append JSON part.\"\"\"\n        if not headers:\n            headers = CIMultiDict()\n        headers[CONTENT_TYPE] = 'application/json'\n        return self.append(obj, headers)\n\n    def append_form(self, obj, headers=None):\n        \"\"\"Helper to append form urlencoded part.\"\"\"\n        if not headers:\n            headers = CIMultiDict()\n        headers[CONTENT_TYPE] = 'application/x-www-form-urlencoded'\n        assert isinstance(obj, (Sequence, Mapping))\n        return self.append(obj, headers)\n\n    def serialize(self):\n        \"\"\"Yields multipart byte chunks.\"\"\"\n        if not self.parts:\n            yield b''\n            return\n\n        for part in self.parts:\n            yield b'--' + self.boundary + b'\\r\\n'\n            yield from part.serialize()\n        else:\n            yield b'--' + self.boundary + b'--\\r\\n'\n\n        yield b''\n",
            "header": {
                "file": {
                    "path": "aiohttp/multipart.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "7cc7e113",
                "new_commit_hash": "296c6790",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/aiohttp/multipart.py"
            },
            "plus_file": {
                "path": "b/aiohttp/multipart.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 228,
                            "length": 8
                        },
                        "new_range": {
                            "start": 228,
                            "length": 6
                        },
                        "section": "class BodyPartReader(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            while not self._at_eof:",
                                "type": "context"
                            },
                            {
                                "content": "                data.extend((yield from self.read_chunk(self.chunk_size)))",
                                "type": "context"
                            },
                            {
                                "content": "            assert b'\\r\\n' == (yield from self._content.readline()), \\",
                                "type": "deleted"
                            },
                            {
                                "content": "                'reader did not read all the data or it is malformed'",
                                "type": "deleted"
                            },
                            {
                                "content": "        if decode:",
                                "type": "context"
                            },
                            {
                                "content": "            return self.decode(data)",
                                "type": "context"
                            },
                            {
                                "content": "        return data",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/multipart.py",
                            "type": "class",
                            "name": "BodyPartReader",
                            "content": "class BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n            assert b'\\r\\n' == (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 190,
                            "end_lineno": 401,
                            "parent": null
                        },
                        {
                            "file_name": "aiohttp/multipart.py",
                            "type": "method",
                            "name": "BodyPartReader.read",
                            "content": "class BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n            assert b'\\r\\n' == (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 213,
                            "end_lineno": 235,
                            "parent": {
                                "file_name": "aiohttp/multipart.py",
                                "type": "class",
                                "name": "BodyPartReader",
                                "content": "class BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n            assert b'\\r\\n' == (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 190,
                                "end_lineno": 401,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 252,
                            "length": 6
                        },
                        "new_range": {
                            "start": 250,
                            "length": 8
                        },
                        "section": "class BodyPartReader(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self._read_bytes += chunk_size",
                                "type": "context"
                            },
                            {
                                "content": "        if self._read_bytes == self._length:",
                                "type": "context"
                            },
                            {
                                "content": "            self._at_eof = True",
                                "type": "context"
                            },
                            {
                                "content": "            assert b'\\r\\n' == (yield from self._content.readline()), \\",
                                "type": "added"
                            },
                            {
                                "content": "                'reader did not read all the data or it is malformed'",
                                "type": "added"
                            },
                            {
                                "content": "        return chunk",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @asyncio.coroutine",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/multipart.py",
                            "type": "class",
                            "name": "BodyPartReader",
                            "content": "class BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 190,
                            "end_lineno": 400,
                            "parent": null
                        },
                        {
                            "file_name": "aiohttp/multipart.py",
                            "type": "method",
                            "name": "BodyPartReader.read_chunk",
                            "content": "class BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 236,
                            "end_lineno": 255,
                            "parent": {
                                "file_name": "aiohttp/multipart.py",
                                "type": "class",
                                "name": "BodyPartReader",
                                "content": "class BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 190,
                                "end_lineno": 400,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 290,
                            "length": 7
                        },
                        "new_range": {
                            "start": 290,
                            "length": 6
                        },
                        "section": "class BodyPartReader(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            while not self._at_eof:",
                                "type": "context"
                            },
                            {
                                "content": "                yield from self.read_chunk(self.chunk_size)",
                                "type": "context"
                            },
                            {
                                "content": "            assert b'\\r\\n' == (yield from self._content.readline())",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @asyncio.coroutine",
                                "type": "context"
                            },
                            {
                                "content": "    def text(self, *, encoding=None):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "aiohttp/multipart.py",
                            "type": "method",
                            "name": "BodyPartReader.release",
                            "content": "class BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n            assert b'\\r\\n' == (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 280,
                            "end_lineno": 293,
                            "parent": {
                                "file_name": "aiohttp/multipart.py",
                                "type": "class",
                                "name": "BodyPartReader",
                                "content": "class BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n            assert b'\\r\\n' == (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 190,
                                "end_lineno": 401,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "aiohttp/multipart.py",
                            "type": "class",
                            "name": "BodyPartReader",
                            "content": "class BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n            assert b'\\r\\n' == (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 190,
                            "end_lineno": 401,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import asyncio\nimport functools\nimport io\nimport os\nimport unittest\nimport unittest.mock as mock\nimport zlib\n\nimport aiohttp.multipart\nfrom aiohttp.helpers import parse_mimetype\nfrom aiohttp.hdrs import (\n    CONTENT_DISPOSITION,\n    CONTENT_ENCODING,\n    CONTENT_TRANSFER_ENCODING,\n    CONTENT_TYPE\n)\nfrom aiohttp.multipart import (\n    parse_content_disposition,\n    content_disposition_filename\n)\n\n\ndef run_in_loop(f):\n    @functools.wraps(f)\n    def wrapper(testcase, *args, **kwargs):\n        coro = asyncio.coroutine(f)\n        future = asyncio.wait_for(coro(testcase, *args, **kwargs), timeout=5)\n        return testcase.loop.run_until_complete(future)\n    return wrapper\n\n\nclass MetaAioTestCase(type):\n\n    def __new__(cls, name, bases, attrs):\n        for key, obj in attrs.items():\n            if key.startswith('test_'):\n                attrs[key] = run_in_loop(obj)\n        return super().__new__(cls, name, bases, attrs)\n\n\nclass TestCase(unittest.TestCase, metaclass=MetaAioTestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n\n    def tearDown(self):\n        self.loop.close()\n\n    def future(self, obj):\n        fut = asyncio.Future(loop=self.loop)\n        fut.set_result(obj)\n        return fut\n\n\nclass Response(object):\n\n    def __init__(self, headers, content):\n        self.headers = headers\n        self.content = content\n\n\nclass Stream(object):\n\n    def __init__(self, content):\n        self.content = io.BytesIO(content)\n\n    @asyncio.coroutine\n    def read(self, size=None):\n        return self.content.read(size)\n\n    @asyncio.coroutine\n    def readline(self):\n        return self.content.readline()\n\n\nclass MultipartResponseWrapperTestCase(TestCase):\n\n    def setUp(self):\n        super().setUp()\n        wrapper = aiohttp.multipart.MultipartResponseWrapper(mock.Mock(),\n                                                             mock.Mock())\n        self.wrapper = wrapper\n\n    def test_at_eof(self):\n        self.wrapper.at_eof()\n        self.assertTrue(self.wrapper.resp.content.at_eof.called)\n\n    def test_next(self):\n        self.wrapper.stream.next.return_value = self.future(b'')\n        self.wrapper.stream.at_eof.return_value = False\n        yield from self.wrapper.next()\n        self.assertTrue(self.wrapper.stream.next.called)\n\n    def test_release(self):\n        self.wrapper.resp.release.return_value = self.future(None)\n        yield from self.wrapper.release()\n        self.assertTrue(self.wrapper.resp.release.called)\n\n    def test_release_when_stream_at_eof(self):\n        self.wrapper.resp.release.return_value = self.future(None)\n        self.wrapper.stream.next.return_value = self.future(b'')\n        self.wrapper.stream.at_eof.return_value = True\n        yield from self.wrapper.next()\n        self.assertTrue(self.wrapper.stream.next.called)\n        self.assertTrue(self.wrapper.resp.release.called)\n\n\nclass PartReaderTestCase(TestCase):\n\n    def setUp(self):\n        super().setUp()\n        self.boundary = b'--:'\n\n    def test_next(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        result = yield from obj.next()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_next_next(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        result = yield from obj.next()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertTrue(obj.at_eof())\n        result = yield from obj.next()\n        self.assertIsNone(result)\n\n    def test_read(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        result = yield from obj.read()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_chunk_at_eof(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'--:'))\n        obj._at_eof = True\n        result = yield from obj.read_chunk()\n        self.assertEqual(b'', result)\n\n    def test_read_chunk_requires_content_length(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        with self.assertRaises(AssertionError):\n            yield from obj.read_chunk()\n\n    def test_read_does_reads_boundary(self):\n        stream = Stream(b'Hello, world!\\r\\n--:')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, stream)\n        result = yield from obj.read()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertEqual(b'', (yield from stream.read()))\n        self.assertEqual([b'--:'], obj._unread)\n\n    def test_multiread(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello,\\r\\n--:\\r\\n\\r\\nworld!\\r\\n--:--'))\n        result = yield from obj.read()\n        self.assertEqual(b'Hello,\\r\\n', result)\n        result = yield from obj.read()\n        self.assertEqual(b'', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_multiline(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello\\n,\\r\\nworld!\\r\\n--:--'))\n        result = yield from obj.read()\n        self.assertEqual(b'Hello\\n,\\r\\nworld!\\r\\n', result)\n        result = yield from obj.read()\n        self.assertEqual(b'', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_respects_content_length(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {'CONTENT-LENGTH': 100500},\n            Stream(b'.' * 100500 + b'\\r\\n--:--'))\n        result = yield from obj.read()\n        self.assertEqual(b'.' * 100500, result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_with_content_encoding_gzip(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'gzip'},\n            Stream(b'\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x0b\\xc9\\xccMU'\n                   b'(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00$\\xfb\\x9eV\\x0e\\x00\\x00\\x00'\n                   b'\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'Time to Relax!', result)\n\n    def test_read_with_content_encoding_deflate(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'deflate'},\n            Stream(b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'Time to Relax!', result)\n\n    def test_read_with_content_encoding_identity(self):\n        thing = (b'\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x0b\\xc9\\xccMU'\n                 b'(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00$\\xfb\\x9eV\\x0e\\x00\\x00\\x00'\n                 b'\\r\\n')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'identity'},\n            Stream(thing + b'--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(thing, result)\n\n    def test_read_with_content_encoding_unknown(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'snappy'},\n            Stream(b'\\x0e4Time to Relax!\\r\\n--:--'))\n        with self.assertRaises(RuntimeError):\n            yield from obj.read(decode=True)\n\n    def test_read_with_content_transfer_encoding_base64(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TRANSFER_ENCODING: 'base64'},\n            Stream(b'VGltZSB0byBSZWxheCE=\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'Time to Relax!', result)\n\n    def test_read_with_content_transfer_encoding_quoted_printable(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TRANSFER_ENCODING: 'quoted-printable'},\n            Stream(b'=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,'\n                   b' =D0=BC=D0=B8=D1=80!\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'\\xd0\\x9f\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82,'\n                         b' \\xd0\\xbc\\xd0\\xb8\\xd1\\x80!\\r\\n', result)\n\n    def test_read_with_content_transfer_encoding_unknown(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TRANSFER_ENCODING: 'unknown'},\n            Stream(b'\\x0e4Time to Relax!\\r\\n--:--'))\n        with self.assertRaises(RuntimeError):\n            yield from obj.read(decode=True)\n\n    def test_read_text(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:--'))\n        result = yield from obj.text()\n        self.assertEqual('Hello, world!\\r\\n', result)\n\n    def test_read_text_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {},\n            Stream('Привет, Мир!\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.text(encoding='cp1251')\n        self.assertEqual('Привет, Мир!\\r\\n', result)\n\n    def test_read_text_guess_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'text/plain;charset=cp1251'},\n            Stream('Привет, Мир!\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.text()\n        self.assertEqual('Привет, Мир!\\r\\n', result)\n\n    def test_read_text_compressed(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'deflate',\n                            CONTENT_TYPE: 'text/plain'},\n            Stream(b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00\\r\\n--:--'))\n        result = yield from obj.text()\n        self.assertEqual('Time to Relax!', result)\n\n    def test_read_text_while_closed(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'text/plain'}, Stream(b''))\n        obj._at_eof = True\n        result = yield from obj.text()\n        self.assertEqual('', result)\n\n    def test_read_json(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json'},\n            Stream(b'{\"test\": \"passed\"}\\r\\n--:--'))\n        result = yield from obj.json()\n        self.assertEqual({'test': 'passed'}, result)\n\n    def test_read_json_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json'},\n            Stream('{\"тест\": \"пассед\"}\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.json(encoding='cp1251')\n        self.assertEqual({'тест': 'пассед'}, result)\n\n    def test_read_json_guess_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json; charset=cp1251'},\n            Stream('{\"тест\": \"пассед\"}\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.json()\n        self.assertEqual({'тест': 'пассед'}, result)\n\n    def test_read_json_compressed(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'deflate',\n                            CONTENT_TYPE: 'application/json'},\n            Stream(b'\\xabV*I-.Q\\xb2RP*H,.NMQ\\xaa\\x05\\x00\\r\\n--:--'))\n        result = yield from obj.json()\n        self.assertEqual({'test': 'passed'}, result)\n\n    def test_read_json_while_closed(self):\n        stream = Stream(b'')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json'}, stream)\n        obj._at_eof = True\n        result = yield from obj.json()\n        self.assertEqual(None, result)\n\n    def test_read_form(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/x-www-form-urlencoded'},\n            Stream(b'foo=bar&foo=baz&boo=zoo\\r\\n--:--'))\n        result = yield from obj.form()\n        self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],\n                         result)\n\n    def test_read_form_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/x-www-form-urlencoded'},\n            Stream('foo=bar&foo=baz&boo=zoo\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.form(encoding='cp1251')\n        self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],\n                         result)\n\n    def test_read_form_guess_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary,\n            {CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=utf-8'},\n            Stream('foo=bar&foo=baz&boo=zoo\\r\\n--:--'.encode('utf-8')))\n        result = yield from obj.form()\n        self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],\n                         result)\n\n    def test_read_form_while_closed(self):\n        stream = Stream(b'')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary,\n            {CONTENT_TYPE: 'application/x-www-form-urlencoded'}, stream)\n        obj._at_eof = True\n        result = yield from obj.form()\n        self.assertEqual(None, result)\n\n    def test_release(self):\n        stream = Stream(b'Hello,\\r\\n--:\\r\\n\\r\\nworld!\\r\\n--:--')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, stream)\n        yield from obj.release()\n        self.assertTrue(obj.at_eof())\n        self.assertEqual(b'\\r\\nworld!\\r\\n--:--', stream.content.read())\n        self.assertEqual([b'--:\\r\\n'], obj._unread)\n\n    def test_release_respects_content_length(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {'CONTENT-LENGTH': 100500},\n            Stream(b'.' * 100500 + b'\\r\\n--:--'))\n        result = yield from obj.release()\n        self.assertIsNone(result)\n        self.assertTrue(obj.at_eof())\n\n    def test_release_release(self):\n        stream = Stream(b'Hello,\\r\\n--:\\r\\n\\r\\nworld!\\r\\n--:--')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, stream)\n        yield from obj.release()\n        yield from obj.release()\n        self.assertEqual(b'\\r\\nworld!\\r\\n--:--', stream.content.read())\n        self.assertEqual([b'--:\\r\\n'], obj._unread)\n\n    def test_filename(self):\n        part = aiohttp.multipart.BodyPartReader(\n            self.boundary,\n            {CONTENT_DISPOSITION: 'attachment; filename=foo.html'},\n            None)\n        self.assertEqual('foo.html', part.filename)\n\n\nclass MultipartReaderTestCase(TestCase):\n\n    def test_from_response(self):\n        resp = Response({CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n                        Stream(b'--:\\r\\n\\r\\nhello\\r\\n--:--'))\n        res = aiohttp.multipart.MultipartReader.from_response(resp)\n        self.assertIsInstance(res,\n                              aiohttp.multipart.MultipartResponseWrapper)\n        self.assertIsInstance(res.stream,\n                              aiohttp.multipart.MultipartReader)\n\n    def test_bad_boundary(self):\n        resp = Response(\n            {CONTENT_TYPE: 'multipart/related;boundary=' + 'a' * 80},\n            Stream(b''))\n        with self.assertRaises(ValueError):\n            aiohttp.multipart.MultipartReader.from_response(resp)\n\n    def test_dispatch(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_bodypart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_multipart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, reader.__class__)\n\n    def test_dispatch_custom_multipart_reader(self):\n        class CustomReader(aiohttp.multipart.MultipartReader):\n            pass\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        reader.multipart_reader_cls = CustomReader\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, CustomReader)\n\n    def test_emit_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = yield from reader.next()\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_invalid_boundary(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'---:\\r\\n\\r\\necho\\r\\n---:--'))\n        with self.assertRaises(ValueError):\n            yield from reader.next()\n\n    def test_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/mixed;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Type: multipart/related;boundary=--:--\\r\\n'\n                   b'\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        res = yield from reader.next()\n        self.assertIsNone(res)\n\n    def test_second_next_releases_previous_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        self.assertIsInstance(first, aiohttp.multipart.BodyPartReader)\n        second = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertFalse(second.at_eof())\n\n    def test_release_without_read_the_last_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        second = yield from reader.next()\n        third = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertIsNone(third)\n\n\nclass BodyPartWriterTestCase(unittest.TestCase):\n\n    def setUp(self):\n        self.part = aiohttp.multipart.BodyPartWriter(b'')\n\n    def test_guess_content_length(self):\n        self.part.headers[CONTENT_TYPE] = 'text/plain; charset=utf-8'\n        self.assertIsNone(self.part._guess_content_length({}))\n        self.assertIsNone(self.part._guess_content_length(object()))\n        self.assertEqual(3,\n                         self.part._guess_content_length(io.BytesIO(b'foo')))\n        self.assertEqual(3,\n                         self.part._guess_content_length(io.StringIO('foo')))\n        self.assertEqual(6,\n                         self.part._guess_content_length(io.StringIO('мяу')))\n        self.assertEqual(3, self.part._guess_content_length(b'bar'))\n        self.assertEqual(12, self.part._guess_content_length('пассед'))\n        with open(__file__, 'rb') as f:\n            self.assertEqual(os.fstat(f.fileno()).st_size,\n                             self.part._guess_content_length(f))\n\n    def test_guess_content_type(self):\n        default = 'application/octet-stream'\n        self.assertEqual(default, self.part._guess_content_type(b'foo'))\n        self.assertEqual('text/plain; charset=utf-8',\n                         self.part._guess_content_type('foo'))\n\n        here = os.path.dirname(__file__)\n        filename = os.path.join(here, 'software_development_in_picture.jpg')\n\n        with open(filename, 'rb') as f:\n            self.assertEqual('image/jpeg',\n                             self.part._guess_content_type(f))\n\n    def test_guess_filename(self):\n        class Named:\n            name = 'foo'\n        self.assertIsNone(self.part._guess_filename({}))\n        self.assertIsNone(self.part._guess_filename(object()))\n        self.assertIsNone(self.part._guess_filename(io.BytesIO(b'foo')))\n        self.assertIsNone(self.part._guess_filename(Named()))\n        with open(__file__, 'rb') as f:\n            self.assertEqual(os.path.basename(f.name),\n                             self.part._guess_filename(f))\n\n    def test_autoset_content_disposition(self):\n        self.part.obj = open(__file__, 'rb')\n        self.addCleanup(self.part.obj.close)\n        self.part._fill_headers_with_defaults()\n        self.assertIn(CONTENT_DISPOSITION, self.part.headers)\n        fname = os.path.basename(self.part.obj.name)\n        self.assertEqual(\n            'attachment; filename=\"{0}\"; filename*=utf-8\\'\\'{0}'.format(fname),\n            self.part.headers[CONTENT_DISPOSITION])\n\n    def test_set_content_disposition(self):\n        self.part.set_content_disposition('attachment', foo='bar')\n        self.assertEqual(\n            'attachment; foo=bar',\n            self.part.headers[CONTENT_DISPOSITION])\n\n    def test_set_content_disposition_bad_type(self):\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('foo bar')\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('тест')\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('foo\\x00bar')\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('')\n\n    def test_set_content_disposition_bad_param(self):\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline', **{'foo bar': 'baz'})\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline', **{'тест': 'baz'})\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline', **{'': 'baz'})\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline',\n                                              **{'foo\\x00bar': 'baz'})\n\n    def test_serialize_bytes(self):\n        self.assertEqual(b'foo', next(self.part._serialize_bytes(b'foo')))\n\n    def test_serialize_str(self):\n        self.assertEqual(b'foo', next(self.part._serialize_str('foo')))\n\n    def test_serialize_str_custom_encoding(self):\n        self.part.headers[CONTENT_TYPE] = \\\n            'text/plain;charset=cp1251'\n        self.assertEqual('привет'.encode('cp1251'),\n                         next(self.part._serialize_str('привет')))\n\n    def test_serialize_io(self):\n        self.assertEqual(b'foo',\n                         next(self.part._serialize_io(io.BytesIO(b'foo'))))\n        self.assertEqual(b'foo',\n                         next(self.part._serialize_io(io.StringIO('foo'))))\n\n    def test_serialize_io_chunk(self):\n        flo = io.BytesIO(b'foobarbaz')\n        self.part._chunk_size = 3\n        self.assertEqual([b'foo', b'bar', b'baz'],\n                         list(self.part._serialize_io(flo)))\n\n    def test_serialize_json(self):\n        self.assertEqual(b'{\"\\\\u043f\\\\u0440\\\\u0438\\\\u0432\\\\u0435\\\\u0442\":'\n                         b' \"\\\\u043c\\\\u0438\\\\u0440\"}',\n                         next(self.part._serialize_json({'привет': 'мир'})))\n\n    def test_serialize_form(self):\n        data = [('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')]\n        self.assertEqual(b'foo=bar&foo=baz&boo=zoo',\n                         next(self.part._serialize_form(data)))\n\n    def test_serialize_form_dict(self):\n        data = {'hello': 'мир'}\n        self.assertEqual(b'hello=%D0%BC%D0%B8%D1%80',\n                         next(self.part._serialize_form(data)))\n\n    def test_serialize_multipart(self):\n        multipart = aiohttp.multipart.MultipartWriter(boundary=':')\n        multipart.append('foo-bar-baz')\n        multipart.append_json({'test': 'passed'})\n        self.assertEqual(\n            [b'--:\\r\\n',\n             b'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n             b'CONTENT-LENGTH: 11',\n             b'\\r\\n\\r\\n',\n             b'foo-bar-baz',\n             b'\\r\\n',\n             b'--:\\r\\n',\n             b'CONTENT-TYPE: application/json',\n             b'\\r\\n\\r\\n',\n             b'{\"test\": \"passed\"}',\n             b'\\r\\n',\n             b'--:--\\r\\n',\n             b''],\n            list(self.part._serialize_multipart(multipart))\n        )\n\n    def test_serialize_default(self):\n        with self.assertRaises(TypeError):\n            self.part.obj = object()\n            list(self.part.serialize())\n        with self.assertRaises(TypeError):\n            next(self.part._serialize_default(object()))\n\n    def test_serialize_with_content_encoding_gzip(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_ENCODING: 'gzip'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-ENCODING: gzip\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        result = b''.join(stream)\n\n        decompressor = zlib.decompressobj(wbits=16+zlib.MAX_WBITS)\n        data = decompressor.decompress(result)\n        self.assertEqual(b'Time to Relax!', data)\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_encoding_deflate(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_ENCODING: 'deflate'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-ENCODING: deflate\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        thing = b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00\\r\\n'\n        self.assertEqual(thing, b''.join(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_encoding_identity(self):\n        thing = b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00'\n        part = aiohttp.multipart.BodyPartWriter(\n            thing, {CONTENT_ENCODING: 'identity'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-ENCODING: identity\\r\\n'\n                         b'CONTENT-TYPE: application/octet-stream\\r\\n'\n                         b'CONTENT-LENGTH: 16',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(thing, next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_encoding_unknown(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_ENCODING: 'snappy'})\n        with self.assertRaises(RuntimeError):\n            list(part.serialize())\n\n    def test_serialize_with_content_transfer_encoding_base64(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_TRANSFER_ENCODING: 'base64'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-TRANSFER-ENCODING: base64\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(b'VGltZSB0byBSZWxh', next(stream))\n        self.assertEqual(b'eCE=', next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_io_with_content_transfer_encoding_base64(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            io.BytesIO(b'Time to Relax!'),\n            {CONTENT_TRANSFER_ENCODING: 'base64'})\n        part._chunk_size = 6\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-TRANSFER-ENCODING: base64\\r\\n'\n                         b'CONTENT-TYPE: application/octet-stream',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(b'VGltZSB0', next(stream))\n        self.assertEqual(b'byBSZWxh', next(stream))\n        self.assertEqual(b'eCE=', next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_transfer_encoding_quote_printable(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Привет, мир!', {CONTENT_TRANSFER_ENCODING: 'quoted-printable'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-TRANSFER-ENCODING: quoted-printable\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(b'=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,'\n                         b' =D0=BC=D0=B8=D1=80!', next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_transfer_encoding_unknown(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_TRANSFER_ENCODING: 'unknown'})\n        with self.assertRaises(RuntimeError):\n            list(part.serialize())\n\n    def test_filename(self):\n        self.part.set_content_disposition('related', filename='foo.html')\n        self.assertEqual('foo.html', self.part.filename)\n\n\nclass MultipartWriterTestCase(unittest.TestCase):\n\n    def setUp(self):\n        self.writer = aiohttp.multipart.MultipartWriter(boundary=':')\n\n    def test_default_subtype(self):\n        mtype, stype, *_ = parse_mimetype(\n            self.writer.headers.get(CONTENT_TYPE))\n        self.assertEqual('multipart', mtype)\n        self.assertEqual('mixed', stype)\n\n    def test_bad_boundary(self):\n        with self.assertRaises(ValueError):\n            aiohttp.multipart.MultipartWriter(boundary='тест')\n\n    def test_default_headers(self):\n        self.assertEqual({CONTENT_TYPE: 'multipart/mixed; boundary=\":\"'},\n                         self.writer.headers)\n\n    def test_iter_parts(self):\n        self.writer.append('foo')\n        self.writer.append('bar')\n        self.writer.append('baz')\n        self.assertEqual(3, len(list(self.writer)))\n\n    def test_append(self):\n        self.assertEqual(0, len(self.writer))\n        self.writer.append('hello, world!')\n        self.assertEqual(1, len(self.writer))\n        self.assertIsInstance(self.writer.parts[0],\n                              self.writer.part_writer_cls)\n\n    def test_append_with_headers(self):\n        self.writer.append('hello, world!', {'x-foo': 'bar'})\n        self.assertEqual(1, len(self.writer))\n        self.assertIn('x-foo', self.writer.parts[0].headers)\n        self.assertEqual(self.writer.parts[0].headers['x-foo'], 'bar')\n\n    def test_append_json(self):\n        self.writer.append_json({'foo': 'bar'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE], 'application/json')\n\n    def test_append_part(self):\n        part = aiohttp.multipart.BodyPartWriter('test',\n                                                {CONTENT_TYPE: 'text/plain'})\n        self.writer.append(part, {CONTENT_TYPE: 'test/passed'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE], 'test/passed')\n\n    def test_append_json_overrides_content_type(self):\n        self.writer.append_json({'foo': 'bar'}, {CONTENT_TYPE: 'test/passed'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE], 'application/json')\n\n    def test_append_form(self):\n        self.writer.append_form({'foo': 'bar'}, {CONTENT_TYPE: 'test/passed'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE],\n                         'application/x-www-form-urlencoded')\n\n    def test_serialize(self):\n        self.assertEqual([b''], list(self.writer.serialize()))\n\n    def test_with(self):\n        with aiohttp.multipart.MultipartWriter(boundary=':') as writer:\n            writer.append('foo')\n            writer.append(b'bar')\n            writer.append_json({'baz': True})\n        self.assertEqual(3, len(writer))\n\n\nclass ParseContentDispositionTestCase(unittest.TestCase):\n    # http://greenbytes.de/tech/tc2231/\n\n    def test_parse_empty(self):\n        disptype, params = parse_content_disposition(None)\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_inlonly(self):\n        disptype, params = parse_content_disposition('inline')\n        self.assertEqual('inline', disptype)\n        self.assertEqual({}, params)\n\n    def test_inlonlyquoted(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition('\"inline\"')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_inlwithasciifilename(self):\n        disptype, params = parse_content_disposition(\n            'inline; filename=\"foo.html\"')\n        self.assertEqual('inline', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_inlwithfnattach(self):\n        disptype, params = parse_content_disposition(\n            'inline; filename=\"Not an attachment!\"')\n        self.assertEqual('inline', disptype)\n        self.assertEqual({'filename': 'Not an attachment!'}, params)\n\n    def test_attonly(self):\n        disptype, params = parse_content_disposition('attachment')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attonlyquoted(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition('\"attachment\"')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attonlyucase(self):\n        disptype, params = parse_content_disposition('ATTACHMENT')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithasciifilename(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_inlwithasciifilenamepdf(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo.pdf\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.pdf'}, params)\n\n    def test_attwithasciifilename25(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"0000000000111111111122222\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '0000000000111111111122222'}, params)\n\n    def test_attwithasciifilename35(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"00000000001111111111222222222233333\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '00000000001111111111222222222233333'},\n                         params)\n\n    def test_attwithasciifnescapedchar(self):\n        disptype, params = parse_content_disposition(\n            r'attachment; filename=\"f\\oo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwithasciifnescapedquote(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"\\\"quoting\\\" tested.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '\"quoting\" tested.html'}, params)\n\n    @unittest.skip('need more smart parser which respects quoted text')\n    def test_attwithquotedsemicolon(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"Here\\'s a semicolon;.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'Here\\'s a semicolon;.html'}, params)\n\n    def test_attwithfilenameandextparam(self):\n        disptype, params = parse_content_disposition(\n            'attachment; foo=\"bar\"; filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html', 'foo': 'bar'}, params)\n\n    def test_attwithfilenameandextparamescaped(self):\n        disptype, params = parse_content_disposition(\n            'attachment; foo=\"\\\"\\\\\";filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html', 'foo': '\"\\\\'}, params)\n\n    def test_attwithasciifilenameucase(self):\n        disptype, params = parse_content_disposition(\n            'attachment; FILENAME=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwithasciifilenamenq(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=foo.html')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwithtokfncommanq(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo,bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithasciifilenamenqs(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo.html ;')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attemptyparam(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; ;filename=foo')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithasciifilenamenqws(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfntokensq(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename='foo.html'\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': \"'foo.html'\"}, params)\n\n    def test_attwithisofnplain(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-ä.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-ä.html'}, params)\n\n    def test_attwithutf8fnplain(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-Ã¤.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-Ã¤.html'}, params)\n\n    def test_attwithfnrawpctenca(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-%41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-%41.html'}, params)\n\n    def test_attwithfnusingpct(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"50%.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '50%.html'}, params)\n\n    def test_attwithfnrawpctencaq(self):\n        disptype, params = parse_content_disposition(\n            r'attachment; filename=\"foo-%\\41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': r'foo-%41.html'}, params)\n\n    def test_attwithnamepct(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-%41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-%41.html'}, params)\n\n    def test_attwithfilenamepctandiso(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"ä-%41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'ä-%41.html'}, params)\n\n    def test_attwithfnrawpctenclong(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-%c3%a4-%e2%82%ac.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-%c3%a4-%e2%82%ac.html'}, params)\n\n    def test_attwithasciifilenamews1(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename =\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwith2filenames(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=\"foo.html\"; filename=\"bar.html\"')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attfnbrokentoken(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo[1](2).html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attfnbrokentokeniso(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo-ä.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attfnbrokentokenutf(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo-Ã¤.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'x=y; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition3(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                '\"foo; filename=bar;baz\"; filename=qux')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition4(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'filename=foo.html, filename=bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_emptydisposition(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                '; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_doublecolon(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                ': inline; attachment; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attandinline(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'inline; attachment; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attandinline2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; inline; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attbrokenquotedfn(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=\"foo.html\".txt')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attbrokenquotedfn2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=\"bar')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attbrokenquotedfn3(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo\"bar;baz\"qux')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmultinstances(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo.html, attachment; filename=bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdelim(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; foo=foo filename=bar')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdelim2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=bar foo=foo')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdelim3(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment filename=bar')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attreversed(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'filename=foo.html; attachment')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attconfusedparam(self):\n        disptype, params = parse_content_disposition(\n            'attachment; xfilename=foo.html')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'xfilename': 'foo.html'}, params)\n\n    def test_attabspath(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"/foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attabspathwin(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"\\\\foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attcdate(self):\n        disptype, params = parse_content_disposition(\n            'attachment; creation-date=\"Wed, 12 Feb 1997 16:29:51 -0500\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'creation-date': 'Wed, 12 Feb 1997 16:29:51 -0500'},\n                         params)\n\n    def test_attmdate(self):\n        disptype, params = parse_content_disposition(\n            'attachment; modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual(\n            {'modification-date': 'Wed, 12 Feb 1997 16:29:51 -0500'},\n            params)\n\n    def test_dispext(self):\n        disptype, params = parse_content_disposition('foobar')\n        self.assertEqual('foobar', disptype)\n        self.assertEqual({}, params)\n\n    def test_dispextbadfn(self):\n        disptype, params = parse_content_disposition(\n            'attachment; example=\"filename=example.txt\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'example': 'filename=example.txt'}, params)\n\n    def test_attwithisofn2231iso(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=iso-8859-1''foo-%E4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    def test_attwithfn2231utf8(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''foo-%c3%a4-%e2%82%ac.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä-€.html'}, params)\n\n    def test_attwithfn2231noc(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=''foo-%c3%a4-%e2%82%ac.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä-€.html'}, params)\n\n    def test_attwithfn2231utf8comp(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''foo-a%cc%88.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    @unittest.skip('should raise decoding error: %82 is invalid for latin1')\n    def test_attwithfn2231utf8_bad(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=iso-8859-1''foo-%c3%a4-%e2%82%ac.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    @unittest.skip('should raise decoding error: %E4 is invalid for utf-8')\n    def test_attwithfn2231iso_bad(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=utf-8''foo-%E4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231ws1(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename *=UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231ws2(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*= UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    def test_attwithfn2231ws3(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename* =UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    def test_attwithfn2231quot(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=\\\"UTF-8''foo-%c3%a4.html\\\"\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231quot2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=\\\"foo%20bar.html\\\"\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231singleqmissing(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=UTF-8'foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    @unittest.skip('urllib.parse.unquote is tolerate to standalone % chars')\n    def test_attwithfn2231nbadpct1(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=UTF-8''foo%\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    @unittest.skip('urllib.parse.unquote is tolerate to standalone % chars')\n    def test_attwithfn2231nbadpct2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=UTF-8''f%oo.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231dpct(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''A-%2541.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'A-%41.html'}, params)\n\n    def test_attwithfn2231abspathdisguised(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''%5cfoo.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': '\\\\foo.html'}, params)\n\n    def test_attfncont(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo.\"; filename*1=\"html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo.',\n                          'filename*1': 'html'}, params)\n\n    def test_attfncontqs(self):\n        disptype, params = parse_content_disposition(\n            r'attachment; filename*0=\"foo\"; filename*1=\"\\b\\a\\r.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*1': 'bar.html'}, params)\n\n    def test_attfncontenc(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0*=UTF-8''foo-%c3%a4; filename*1=\".html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0*': 'UTF-8''foo-%c3%a4',\n                          'filename*1': '.html'}, params)\n\n    def test_attfncontlz(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo\"; filename*01=\"bar\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*01': 'bar'}, params)\n\n    def test_attfncontnc(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo\"; filename*2=\"bar\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*2': 'bar'}, params)\n\n    def test_attfnconts1(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo.\"; filename*2=\"html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo.',\n                          'filename*2': 'html'}, params)\n\n    def test_attfncontord(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*1=\"bar\"; filename*0=\"foo\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*1': 'bar'}, params)\n\n    def test_attfnboth(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-ae.html\";'\n            \" filename*=UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-ae.html',\n                          'filename*': 'foo-ä.html'}, params)\n\n    def test_attfnboth2(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''foo-%c3%a4.html;\"\n            ' filename=\"foo-ae.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-ae.html',\n                          'filename*': 'foo-ä.html'}, params)\n\n    def test_attfnboth3(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4;\"\n            \" filename*=ISO-8859-1''currency-sign%3d%a4\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'currency-sign=¤',\n                          'filename*0*': \"ISO-8859-15''euro-sign%3d%a4\"},\n                         params)\n\n    def test_attnewandfn(self):\n        disptype, params = parse_content_disposition(\n            'attachment; foobar=x; filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'foobar': 'x',\n                          'filename': 'foo.html'}, params)\n\n    def test_attrfc2047token(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename==?ISO-8859-1?Q?foo-=E4.html?=')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attrfc2047quoted(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"=?ISO-8859-1?Q?foo-=E4.html?=\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '=?ISO-8859-1?Q?foo-=E4.html?='}, params)\n\n    def test_bad_continuous_param(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                'attachment; filename*0=foo bar')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n\nclass ContentDispositionFilenameTestCase(unittest.TestCase):\n    # http://greenbytes.de/tech/tc2231/\n\n    def test_no_filename(self):\n        self.assertIsNone(content_disposition_filename({}))\n        self.assertIsNone(content_disposition_filename({'foo': 'bar'}))\n\n    def test_filename(self):\n        params = {'filename': 'foo.html'}\n        self.assertEqual('foo.html', content_disposition_filename(params))\n\n    def test_filename_ext(self):\n        params = {'filename*': 'файл.html'}\n        self.assertEqual('файл.html', content_disposition_filename(params))\n\n    def test_attfncont(self):\n        params = {'filename*0': 'foo.', 'filename*1': 'html'}\n        self.assertEqual('foo.html', content_disposition_filename(params))\n\n    def test_attfncontqs(self):\n        params = {'filename*0': 'foo', 'filename*1': 'bar.html'}\n        self.assertEqual('foobar.html', content_disposition_filename(params))\n\n    def test_attfncontenc(self):\n        params = {'filename*0*': \"UTF-8''foo-%c3%a4\",\n                  'filename*1': '.html'}\n        self.assertEqual('foo-ä.html', content_disposition_filename(params))\n\n    def test_attfncontlz(self):\n        params = {'filename*0': 'foo',\n                  'filename*01': 'bar'}\n        self.assertEqual('foo', content_disposition_filename(params))\n\n    def test_attfncontnc(self):\n        params = {'filename*0': 'foo',\n                  'filename*2': 'bar'}\n        self.assertEqual('foo', content_disposition_filename(params))\n\n    def test_attfnconts1(self):\n        params = {'filename*1': 'foo',\n                  'filename*2': 'bar'}\n        self.assertEqual(None, content_disposition_filename(params))\n\n    def test_attfnboth(self):\n        params = {'filename': 'foo-ae.html',\n                  'filename*': 'foo-ä.html'}\n        self.assertEqual('foo-ä.html', content_disposition_filename(params))\n\n    def test_attfnboth3(self):\n        params = {'filename*0*': \"ISO-8859-15''euro-sign%3d%a4\",\n                  'filename*': 'currency-sign=¤'}\n        self.assertEqual('currency-sign=¤',\n                         content_disposition_filename(params))\n\n    def test_attrfc2047quoted(self):\n        params = {'filename': '=?ISO-8859-1?Q?foo-=E4.html?='}\n        self.assertEqual('=?ISO-8859-1?Q?foo-=E4.html?=',\n                         content_disposition_filename(params))\n",
            "new_file_content": "import asyncio\nimport functools\nimport io\nimport os\nimport unittest\nimport unittest.mock as mock\nimport zlib\n\nimport aiohttp.multipart\nfrom aiohttp.helpers import parse_mimetype\nfrom aiohttp.hdrs import (\n    CONTENT_DISPOSITION,\n    CONTENT_ENCODING,\n    CONTENT_TRANSFER_ENCODING,\n    CONTENT_TYPE\n)\nfrom aiohttp.multipart import (\n    parse_content_disposition,\n    content_disposition_filename\n)\n\n\ndef run_in_loop(f):\n    @functools.wraps(f)\n    def wrapper(testcase, *args, **kwargs):\n        coro = asyncio.coroutine(f)\n        future = asyncio.wait_for(coro(testcase, *args, **kwargs), timeout=5)\n        return testcase.loop.run_until_complete(future)\n    return wrapper\n\n\nclass MetaAioTestCase(type):\n\n    def __new__(cls, name, bases, attrs):\n        for key, obj in attrs.items():\n            if key.startswith('test_'):\n                attrs[key] = run_in_loop(obj)\n        return super().__new__(cls, name, bases, attrs)\n\n\nclass TestCase(unittest.TestCase, metaclass=MetaAioTestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n\n    def tearDown(self):\n        self.loop.close()\n\n    def future(self, obj):\n        fut = asyncio.Future(loop=self.loop)\n        fut.set_result(obj)\n        return fut\n\n\nclass Response(object):\n\n    def __init__(self, headers, content):\n        self.headers = headers\n        self.content = content\n\n\nclass Stream(object):\n\n    def __init__(self, content):\n        self.content = io.BytesIO(content)\n\n    @asyncio.coroutine\n    def read(self, size=None):\n        return self.content.read(size)\n\n    @asyncio.coroutine\n    def readline(self):\n        return self.content.readline()\n\n\nclass MultipartResponseWrapperTestCase(TestCase):\n\n    def setUp(self):\n        super().setUp()\n        wrapper = aiohttp.multipart.MultipartResponseWrapper(mock.Mock(),\n                                                             mock.Mock())\n        self.wrapper = wrapper\n\n    def test_at_eof(self):\n        self.wrapper.at_eof()\n        self.assertTrue(self.wrapper.resp.content.at_eof.called)\n\n    def test_next(self):\n        self.wrapper.stream.next.return_value = self.future(b'')\n        self.wrapper.stream.at_eof.return_value = False\n        yield from self.wrapper.next()\n        self.assertTrue(self.wrapper.stream.next.called)\n\n    def test_release(self):\n        self.wrapper.resp.release.return_value = self.future(None)\n        yield from self.wrapper.release()\n        self.assertTrue(self.wrapper.resp.release.called)\n\n    def test_release_when_stream_at_eof(self):\n        self.wrapper.resp.release.return_value = self.future(None)\n        self.wrapper.stream.next.return_value = self.future(b'')\n        self.wrapper.stream.at_eof.return_value = True\n        yield from self.wrapper.next()\n        self.assertTrue(self.wrapper.stream.next.called)\n        self.assertTrue(self.wrapper.resp.release.called)\n\n\nclass PartReaderTestCase(TestCase):\n\n    def setUp(self):\n        super().setUp()\n        self.boundary = b'--:'\n\n    def test_next(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        result = yield from obj.next()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_next_next(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        result = yield from obj.next()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertTrue(obj.at_eof())\n        result = yield from obj.next()\n        self.assertIsNone(result)\n\n    def test_read(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        result = yield from obj.read()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_chunk_at_eof(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'--:'))\n        obj._at_eof = True\n        result = yield from obj.read_chunk()\n        self.assertEqual(b'', result)\n\n    def test_read_chunk_requires_content_length(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        with self.assertRaises(AssertionError):\n            yield from obj.read_chunk()\n\n    def test_read_does_reads_boundary(self):\n        stream = Stream(b'Hello, world!\\r\\n--:')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, stream)\n        result = yield from obj.read()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertEqual(b'', (yield from stream.read()))\n        self.assertEqual([b'--:'], obj._unread)\n\n    def test_multiread(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello,\\r\\n--:\\r\\n\\r\\nworld!\\r\\n--:--'))\n        result = yield from obj.read()\n        self.assertEqual(b'Hello,\\r\\n', result)\n        result = yield from obj.read()\n        self.assertEqual(b'', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_multiline(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello\\n,\\r\\nworld!\\r\\n--:--'))\n        result = yield from obj.read()\n        self.assertEqual(b'Hello\\n,\\r\\nworld!\\r\\n', result)\n        result = yield from obj.read()\n        self.assertEqual(b'', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_respects_content_length(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {'CONTENT-LENGTH': 100500},\n            Stream(b'.' * 100500 + b'\\r\\n--:--'))\n        result = yield from obj.read()\n        self.assertEqual(b'.' * 100500, result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_with_content_encoding_gzip(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'gzip'},\n            Stream(b'\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x0b\\xc9\\xccMU'\n                   b'(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00$\\xfb\\x9eV\\x0e\\x00\\x00\\x00'\n                   b'\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'Time to Relax!', result)\n\n    def test_read_with_content_encoding_deflate(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'deflate'},\n            Stream(b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'Time to Relax!', result)\n\n    def test_read_with_content_encoding_identity(self):\n        thing = (b'\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x0b\\xc9\\xccMU'\n                 b'(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00$\\xfb\\x9eV\\x0e\\x00\\x00\\x00'\n                 b'\\r\\n')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'identity'},\n            Stream(thing + b'--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(thing, result)\n\n    def test_read_with_content_encoding_unknown(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'snappy'},\n            Stream(b'\\x0e4Time to Relax!\\r\\n--:--'))\n        with self.assertRaises(RuntimeError):\n            yield from obj.read(decode=True)\n\n    def test_read_with_content_transfer_encoding_base64(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TRANSFER_ENCODING: 'base64'},\n            Stream(b'VGltZSB0byBSZWxheCE=\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'Time to Relax!', result)\n\n    def test_read_with_content_transfer_encoding_quoted_printable(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TRANSFER_ENCODING: 'quoted-printable'},\n            Stream(b'=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,'\n                   b' =D0=BC=D0=B8=D1=80!\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'\\xd0\\x9f\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82,'\n                         b' \\xd0\\xbc\\xd0\\xb8\\xd1\\x80!\\r\\n', result)\n\n    def test_read_with_content_transfer_encoding_unknown(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TRANSFER_ENCODING: 'unknown'},\n            Stream(b'\\x0e4Time to Relax!\\r\\n--:--'))\n        with self.assertRaises(RuntimeError):\n            yield from obj.read(decode=True)\n\n    def test_read_text(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:--'))\n        result = yield from obj.text()\n        self.assertEqual('Hello, world!\\r\\n', result)\n\n    def test_read_text_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {},\n            Stream('Привет, Мир!\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.text(encoding='cp1251')\n        self.assertEqual('Привет, Мир!\\r\\n', result)\n\n    def test_read_text_guess_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'text/plain;charset=cp1251'},\n            Stream('Привет, Мир!\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.text()\n        self.assertEqual('Привет, Мир!\\r\\n', result)\n\n    def test_read_text_compressed(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'deflate',\n                            CONTENT_TYPE: 'text/plain'},\n            Stream(b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00\\r\\n--:--'))\n        result = yield from obj.text()\n        self.assertEqual('Time to Relax!', result)\n\n    def test_read_text_while_closed(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'text/plain'}, Stream(b''))\n        obj._at_eof = True\n        result = yield from obj.text()\n        self.assertEqual('', result)\n\n    def test_read_json(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json'},\n            Stream(b'{\"test\": \"passed\"}\\r\\n--:--'))\n        result = yield from obj.json()\n        self.assertEqual({'test': 'passed'}, result)\n\n    def test_read_json_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json'},\n            Stream('{\"тест\": \"пассед\"}\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.json(encoding='cp1251')\n        self.assertEqual({'тест': 'пассед'}, result)\n\n    def test_read_json_guess_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json; charset=cp1251'},\n            Stream('{\"тест\": \"пассед\"}\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.json()\n        self.assertEqual({'тест': 'пассед'}, result)\n\n    def test_read_json_compressed(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'deflate',\n                            CONTENT_TYPE: 'application/json'},\n            Stream(b'\\xabV*I-.Q\\xb2RP*H,.NMQ\\xaa\\x05\\x00\\r\\n--:--'))\n        result = yield from obj.json()\n        self.assertEqual({'test': 'passed'}, result)\n\n    def test_read_json_while_closed(self):\n        stream = Stream(b'')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json'}, stream)\n        obj._at_eof = True\n        result = yield from obj.json()\n        self.assertEqual(None, result)\n\n    def test_read_form(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/x-www-form-urlencoded'},\n            Stream(b'foo=bar&foo=baz&boo=zoo\\r\\n--:--'))\n        result = yield from obj.form()\n        self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],\n                         result)\n\n    def test_read_form_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/x-www-form-urlencoded'},\n            Stream('foo=bar&foo=baz&boo=zoo\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.form(encoding='cp1251')\n        self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],\n                         result)\n\n    def test_read_form_guess_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary,\n            {CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=utf-8'},\n            Stream('foo=bar&foo=baz&boo=zoo\\r\\n--:--'.encode('utf-8')))\n        result = yield from obj.form()\n        self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],\n                         result)\n\n    def test_read_form_while_closed(self):\n        stream = Stream(b'')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary,\n            {CONTENT_TYPE: 'application/x-www-form-urlencoded'}, stream)\n        obj._at_eof = True\n        result = yield from obj.form()\n        self.assertEqual(None, result)\n\n    def test_release(self):\n        stream = Stream(b'Hello,\\r\\n--:\\r\\n\\r\\nworld!\\r\\n--:--')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, stream)\n        yield from obj.release()\n        self.assertTrue(obj.at_eof())\n        self.assertEqual(b'\\r\\nworld!\\r\\n--:--', stream.content.read())\n        self.assertEqual([b'--:\\r\\n'], obj._unread)\n\n    def test_release_respects_content_length(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {'CONTENT-LENGTH': 100500},\n            Stream(b'.' * 100500 + b'\\r\\n--:--'))\n        result = yield from obj.release()\n        self.assertIsNone(result)\n        self.assertTrue(obj.at_eof())\n\n    def test_release_release(self):\n        stream = Stream(b'Hello,\\r\\n--:\\r\\n\\r\\nworld!\\r\\n--:--')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, stream)\n        yield from obj.release()\n        yield from obj.release()\n        self.assertEqual(b'\\r\\nworld!\\r\\n--:--', stream.content.read())\n        self.assertEqual([b'--:\\r\\n'], obj._unread)\n\n    def test_filename(self):\n        part = aiohttp.multipart.BodyPartReader(\n            self.boundary,\n            {CONTENT_DISPOSITION: 'attachment; filename=foo.html'},\n            None)\n        self.assertEqual('foo.html', part.filename)\n\n\nclass MultipartReaderTestCase(TestCase):\n\n    def test_from_response(self):\n        resp = Response({CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n                        Stream(b'--:\\r\\n\\r\\nhello\\r\\n--:--'))\n        res = aiohttp.multipart.MultipartReader.from_response(resp)\n        self.assertIsInstance(res,\n                              aiohttp.multipart.MultipartResponseWrapper)\n        self.assertIsInstance(res.stream,\n                              aiohttp.multipart.MultipartReader)\n\n    def test_bad_boundary(self):\n        resp = Response(\n            {CONTENT_TYPE: 'multipart/related;boundary=' + 'a' * 80},\n            Stream(b''))\n        with self.assertRaises(ValueError):\n            aiohttp.multipart.MultipartReader.from_response(resp)\n\n    def test_dispatch(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_bodypart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_multipart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, reader.__class__)\n\n    def test_dispatch_custom_multipart_reader(self):\n        class CustomReader(aiohttp.multipart.MultipartReader):\n            pass\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        reader.multipart_reader_cls = CustomReader\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, CustomReader)\n\n    def test_emit_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = yield from reader.next()\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_invalid_boundary(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'---:\\r\\n\\r\\necho\\r\\n---:--'))\n        with self.assertRaises(ValueError):\n            yield from reader.next()\n\n    def test_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/mixed;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Type: multipart/related;boundary=--:--\\r\\n'\n                   b'\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        res = yield from reader.next()\n        self.assertIsNone(res)\n\n    def test_second_next_releases_previous_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        self.assertIsInstance(first, aiohttp.multipart.BodyPartReader)\n        second = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertFalse(second.at_eof())\n\n    def test_release_without_read_the_last_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        second = yield from reader.next()\n        third = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertIsNone(third)\n\n    def test_read_chunk_doesnt_breaks_reader(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Length: 4\\r\\n\\r\\n'\n                   b'test'\n                   b'\\r\\n--:\\r\\n'\n                   b'Content-Length: 6\\r\\n\\r\\n'\n                   b'passed'\n                   b'\\r\\n--:--'))\n        while True:\n            part = yield from reader.next()\n            if part is None:\n                break\n            while not part.at_eof():\n                yield from part.read_chunk(3)\n\n\nclass BodyPartWriterTestCase(unittest.TestCase):\n\n    def setUp(self):\n        self.part = aiohttp.multipart.BodyPartWriter(b'')\n\n    def test_guess_content_length(self):\n        self.part.headers[CONTENT_TYPE] = 'text/plain; charset=utf-8'\n        self.assertIsNone(self.part._guess_content_length({}))\n        self.assertIsNone(self.part._guess_content_length(object()))\n        self.assertEqual(3,\n                         self.part._guess_content_length(io.BytesIO(b'foo')))\n        self.assertEqual(3,\n                         self.part._guess_content_length(io.StringIO('foo')))\n        self.assertEqual(6,\n                         self.part._guess_content_length(io.StringIO('мяу')))\n        self.assertEqual(3, self.part._guess_content_length(b'bar'))\n        self.assertEqual(12, self.part._guess_content_length('пассед'))\n        with open(__file__, 'rb') as f:\n            self.assertEqual(os.fstat(f.fileno()).st_size,\n                             self.part._guess_content_length(f))\n\n    def test_guess_content_type(self):\n        default = 'application/octet-stream'\n        self.assertEqual(default, self.part._guess_content_type(b'foo'))\n        self.assertEqual('text/plain; charset=utf-8',\n                         self.part._guess_content_type('foo'))\n\n        here = os.path.dirname(__file__)\n        filename = os.path.join(here, 'software_development_in_picture.jpg')\n\n        with open(filename, 'rb') as f:\n            self.assertEqual('image/jpeg',\n                             self.part._guess_content_type(f))\n\n    def test_guess_filename(self):\n        class Named:\n            name = 'foo'\n        self.assertIsNone(self.part._guess_filename({}))\n        self.assertIsNone(self.part._guess_filename(object()))\n        self.assertIsNone(self.part._guess_filename(io.BytesIO(b'foo')))\n        self.assertIsNone(self.part._guess_filename(Named()))\n        with open(__file__, 'rb') as f:\n            self.assertEqual(os.path.basename(f.name),\n                             self.part._guess_filename(f))\n\n    def test_autoset_content_disposition(self):\n        self.part.obj = open(__file__, 'rb')\n        self.addCleanup(self.part.obj.close)\n        self.part._fill_headers_with_defaults()\n        self.assertIn(CONTENT_DISPOSITION, self.part.headers)\n        fname = os.path.basename(self.part.obj.name)\n        self.assertEqual(\n            'attachment; filename=\"{0}\"; filename*=utf-8\\'\\'{0}'.format(fname),\n            self.part.headers[CONTENT_DISPOSITION])\n\n    def test_set_content_disposition(self):\n        self.part.set_content_disposition('attachment', foo='bar')\n        self.assertEqual(\n            'attachment; foo=bar',\n            self.part.headers[CONTENT_DISPOSITION])\n\n    def test_set_content_disposition_bad_type(self):\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('foo bar')\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('тест')\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('foo\\x00bar')\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('')\n\n    def test_set_content_disposition_bad_param(self):\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline', **{'foo bar': 'baz'})\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline', **{'тест': 'baz'})\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline', **{'': 'baz'})\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline',\n                                              **{'foo\\x00bar': 'baz'})\n\n    def test_serialize_bytes(self):\n        self.assertEqual(b'foo', next(self.part._serialize_bytes(b'foo')))\n\n    def test_serialize_str(self):\n        self.assertEqual(b'foo', next(self.part._serialize_str('foo')))\n\n    def test_serialize_str_custom_encoding(self):\n        self.part.headers[CONTENT_TYPE] = \\\n            'text/plain;charset=cp1251'\n        self.assertEqual('привет'.encode('cp1251'),\n                         next(self.part._serialize_str('привет')))\n\n    def test_serialize_io(self):\n        self.assertEqual(b'foo',\n                         next(self.part._serialize_io(io.BytesIO(b'foo'))))\n        self.assertEqual(b'foo',\n                         next(self.part._serialize_io(io.StringIO('foo'))))\n\n    def test_serialize_io_chunk(self):\n        flo = io.BytesIO(b'foobarbaz')\n        self.part._chunk_size = 3\n        self.assertEqual([b'foo', b'bar', b'baz'],\n                         list(self.part._serialize_io(flo)))\n\n    def test_serialize_json(self):\n        self.assertEqual(b'{\"\\\\u043f\\\\u0440\\\\u0438\\\\u0432\\\\u0435\\\\u0442\":'\n                         b' \"\\\\u043c\\\\u0438\\\\u0440\"}',\n                         next(self.part._serialize_json({'привет': 'мир'})))\n\n    def test_serialize_form(self):\n        data = [('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')]\n        self.assertEqual(b'foo=bar&foo=baz&boo=zoo',\n                         next(self.part._serialize_form(data)))\n\n    def test_serialize_form_dict(self):\n        data = {'hello': 'мир'}\n        self.assertEqual(b'hello=%D0%BC%D0%B8%D1%80',\n                         next(self.part._serialize_form(data)))\n\n    def test_serialize_multipart(self):\n        multipart = aiohttp.multipart.MultipartWriter(boundary=':')\n        multipart.append('foo-bar-baz')\n        multipart.append_json({'test': 'passed'})\n        self.assertEqual(\n            [b'--:\\r\\n',\n             b'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n             b'CONTENT-LENGTH: 11',\n             b'\\r\\n\\r\\n',\n             b'foo-bar-baz',\n             b'\\r\\n',\n             b'--:\\r\\n',\n             b'CONTENT-TYPE: application/json',\n             b'\\r\\n\\r\\n',\n             b'{\"test\": \"passed\"}',\n             b'\\r\\n',\n             b'--:--\\r\\n',\n             b''],\n            list(self.part._serialize_multipart(multipart))\n        )\n\n    def test_serialize_default(self):\n        with self.assertRaises(TypeError):\n            self.part.obj = object()\n            list(self.part.serialize())\n        with self.assertRaises(TypeError):\n            next(self.part._serialize_default(object()))\n\n    def test_serialize_with_content_encoding_gzip(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_ENCODING: 'gzip'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-ENCODING: gzip\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        result = b''.join(stream)\n\n        decompressor = zlib.decompressobj(wbits=16+zlib.MAX_WBITS)\n        data = decompressor.decompress(result)\n        self.assertEqual(b'Time to Relax!', data)\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_encoding_deflate(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_ENCODING: 'deflate'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-ENCODING: deflate\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        thing = b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00\\r\\n'\n        self.assertEqual(thing, b''.join(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_encoding_identity(self):\n        thing = b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00'\n        part = aiohttp.multipart.BodyPartWriter(\n            thing, {CONTENT_ENCODING: 'identity'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-ENCODING: identity\\r\\n'\n                         b'CONTENT-TYPE: application/octet-stream\\r\\n'\n                         b'CONTENT-LENGTH: 16',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(thing, next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_encoding_unknown(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_ENCODING: 'snappy'})\n        with self.assertRaises(RuntimeError):\n            list(part.serialize())\n\n    def test_serialize_with_content_transfer_encoding_base64(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_TRANSFER_ENCODING: 'base64'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-TRANSFER-ENCODING: base64\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(b'VGltZSB0byBSZWxh', next(stream))\n        self.assertEqual(b'eCE=', next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_io_with_content_transfer_encoding_base64(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            io.BytesIO(b'Time to Relax!'),\n            {CONTENT_TRANSFER_ENCODING: 'base64'})\n        part._chunk_size = 6\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-TRANSFER-ENCODING: base64\\r\\n'\n                         b'CONTENT-TYPE: application/octet-stream',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(b'VGltZSB0', next(stream))\n        self.assertEqual(b'byBSZWxh', next(stream))\n        self.assertEqual(b'eCE=', next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_transfer_encoding_quote_printable(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Привет, мир!', {CONTENT_TRANSFER_ENCODING: 'quoted-printable'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-TRANSFER-ENCODING: quoted-printable\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(b'=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,'\n                         b' =D0=BC=D0=B8=D1=80!', next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_transfer_encoding_unknown(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_TRANSFER_ENCODING: 'unknown'})\n        with self.assertRaises(RuntimeError):\n            list(part.serialize())\n\n    def test_filename(self):\n        self.part.set_content_disposition('related', filename='foo.html')\n        self.assertEqual('foo.html', self.part.filename)\n\n\nclass MultipartWriterTestCase(unittest.TestCase):\n\n    def setUp(self):\n        self.writer = aiohttp.multipart.MultipartWriter(boundary=':')\n\n    def test_default_subtype(self):\n        mtype, stype, *_ = parse_mimetype(\n            self.writer.headers.get(CONTENT_TYPE))\n        self.assertEqual('multipart', mtype)\n        self.assertEqual('mixed', stype)\n\n    def test_bad_boundary(self):\n        with self.assertRaises(ValueError):\n            aiohttp.multipart.MultipartWriter(boundary='тест')\n\n    def test_default_headers(self):\n        self.assertEqual({CONTENT_TYPE: 'multipart/mixed; boundary=\":\"'},\n                         self.writer.headers)\n\n    def test_iter_parts(self):\n        self.writer.append('foo')\n        self.writer.append('bar')\n        self.writer.append('baz')\n        self.assertEqual(3, len(list(self.writer)))\n\n    def test_append(self):\n        self.assertEqual(0, len(self.writer))\n        self.writer.append('hello, world!')\n        self.assertEqual(1, len(self.writer))\n        self.assertIsInstance(self.writer.parts[0],\n                              self.writer.part_writer_cls)\n\n    def test_append_with_headers(self):\n        self.writer.append('hello, world!', {'x-foo': 'bar'})\n        self.assertEqual(1, len(self.writer))\n        self.assertIn('x-foo', self.writer.parts[0].headers)\n        self.assertEqual(self.writer.parts[0].headers['x-foo'], 'bar')\n\n    def test_append_json(self):\n        self.writer.append_json({'foo': 'bar'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE], 'application/json')\n\n    def test_append_part(self):\n        part = aiohttp.multipart.BodyPartWriter('test',\n                                                {CONTENT_TYPE: 'text/plain'})\n        self.writer.append(part, {CONTENT_TYPE: 'test/passed'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE], 'test/passed')\n\n    def test_append_json_overrides_content_type(self):\n        self.writer.append_json({'foo': 'bar'}, {CONTENT_TYPE: 'test/passed'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE], 'application/json')\n\n    def test_append_form(self):\n        self.writer.append_form({'foo': 'bar'}, {CONTENT_TYPE: 'test/passed'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE],\n                         'application/x-www-form-urlencoded')\n\n    def test_serialize(self):\n        self.assertEqual([b''], list(self.writer.serialize()))\n\n    def test_with(self):\n        with aiohttp.multipart.MultipartWriter(boundary=':') as writer:\n            writer.append('foo')\n            writer.append(b'bar')\n            writer.append_json({'baz': True})\n        self.assertEqual(3, len(writer))\n\n\nclass ParseContentDispositionTestCase(unittest.TestCase):\n    # http://greenbytes.de/tech/tc2231/\n\n    def test_parse_empty(self):\n        disptype, params = parse_content_disposition(None)\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_inlonly(self):\n        disptype, params = parse_content_disposition('inline')\n        self.assertEqual('inline', disptype)\n        self.assertEqual({}, params)\n\n    def test_inlonlyquoted(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition('\"inline\"')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_inlwithasciifilename(self):\n        disptype, params = parse_content_disposition(\n            'inline; filename=\"foo.html\"')\n        self.assertEqual('inline', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_inlwithfnattach(self):\n        disptype, params = parse_content_disposition(\n            'inline; filename=\"Not an attachment!\"')\n        self.assertEqual('inline', disptype)\n        self.assertEqual({'filename': 'Not an attachment!'}, params)\n\n    def test_attonly(self):\n        disptype, params = parse_content_disposition('attachment')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attonlyquoted(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition('\"attachment\"')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attonlyucase(self):\n        disptype, params = parse_content_disposition('ATTACHMENT')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithasciifilename(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_inlwithasciifilenamepdf(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo.pdf\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.pdf'}, params)\n\n    def test_attwithasciifilename25(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"0000000000111111111122222\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '0000000000111111111122222'}, params)\n\n    def test_attwithasciifilename35(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"00000000001111111111222222222233333\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '00000000001111111111222222222233333'},\n                         params)\n\n    def test_attwithasciifnescapedchar(self):\n        disptype, params = parse_content_disposition(\n            r'attachment; filename=\"f\\oo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwithasciifnescapedquote(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"\\\"quoting\\\" tested.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '\"quoting\" tested.html'}, params)\n\n    @unittest.skip('need more smart parser which respects quoted text')\n    def test_attwithquotedsemicolon(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"Here\\'s a semicolon;.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'Here\\'s a semicolon;.html'}, params)\n\n    def test_attwithfilenameandextparam(self):\n        disptype, params = parse_content_disposition(\n            'attachment; foo=\"bar\"; filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html', 'foo': 'bar'}, params)\n\n    def test_attwithfilenameandextparamescaped(self):\n        disptype, params = parse_content_disposition(\n            'attachment; foo=\"\\\"\\\\\";filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html', 'foo': '\"\\\\'}, params)\n\n    def test_attwithasciifilenameucase(self):\n        disptype, params = parse_content_disposition(\n            'attachment; FILENAME=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwithasciifilenamenq(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=foo.html')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwithtokfncommanq(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo,bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithasciifilenamenqs(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo.html ;')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attemptyparam(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; ;filename=foo')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithasciifilenamenqws(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfntokensq(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename='foo.html'\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': \"'foo.html'\"}, params)\n\n    def test_attwithisofnplain(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-ä.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-ä.html'}, params)\n\n    def test_attwithutf8fnplain(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-Ã¤.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-Ã¤.html'}, params)\n\n    def test_attwithfnrawpctenca(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-%41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-%41.html'}, params)\n\n    def test_attwithfnusingpct(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"50%.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '50%.html'}, params)\n\n    def test_attwithfnrawpctencaq(self):\n        disptype, params = parse_content_disposition(\n            r'attachment; filename=\"foo-%\\41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': r'foo-%41.html'}, params)\n\n    def test_attwithnamepct(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-%41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-%41.html'}, params)\n\n    def test_attwithfilenamepctandiso(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"ä-%41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'ä-%41.html'}, params)\n\n    def test_attwithfnrawpctenclong(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-%c3%a4-%e2%82%ac.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-%c3%a4-%e2%82%ac.html'}, params)\n\n    def test_attwithasciifilenamews1(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename =\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwith2filenames(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=\"foo.html\"; filename=\"bar.html\"')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attfnbrokentoken(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo[1](2).html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attfnbrokentokeniso(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo-ä.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attfnbrokentokenutf(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo-Ã¤.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'x=y; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition3(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                '\"foo; filename=bar;baz\"; filename=qux')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition4(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'filename=foo.html, filename=bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_emptydisposition(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                '; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_doublecolon(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                ': inline; attachment; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attandinline(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'inline; attachment; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attandinline2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; inline; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attbrokenquotedfn(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=\"foo.html\".txt')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attbrokenquotedfn2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=\"bar')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attbrokenquotedfn3(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo\"bar;baz\"qux')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmultinstances(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo.html, attachment; filename=bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdelim(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; foo=foo filename=bar')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdelim2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=bar foo=foo')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdelim3(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment filename=bar')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attreversed(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'filename=foo.html; attachment')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attconfusedparam(self):\n        disptype, params = parse_content_disposition(\n            'attachment; xfilename=foo.html')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'xfilename': 'foo.html'}, params)\n\n    def test_attabspath(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"/foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attabspathwin(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"\\\\foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attcdate(self):\n        disptype, params = parse_content_disposition(\n            'attachment; creation-date=\"Wed, 12 Feb 1997 16:29:51 -0500\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'creation-date': 'Wed, 12 Feb 1997 16:29:51 -0500'},\n                         params)\n\n    def test_attmdate(self):\n        disptype, params = parse_content_disposition(\n            'attachment; modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual(\n            {'modification-date': 'Wed, 12 Feb 1997 16:29:51 -0500'},\n            params)\n\n    def test_dispext(self):\n        disptype, params = parse_content_disposition('foobar')\n        self.assertEqual('foobar', disptype)\n        self.assertEqual({}, params)\n\n    def test_dispextbadfn(self):\n        disptype, params = parse_content_disposition(\n            'attachment; example=\"filename=example.txt\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'example': 'filename=example.txt'}, params)\n\n    def test_attwithisofn2231iso(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=iso-8859-1''foo-%E4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    def test_attwithfn2231utf8(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''foo-%c3%a4-%e2%82%ac.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä-€.html'}, params)\n\n    def test_attwithfn2231noc(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=''foo-%c3%a4-%e2%82%ac.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä-€.html'}, params)\n\n    def test_attwithfn2231utf8comp(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''foo-a%cc%88.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    @unittest.skip('should raise decoding error: %82 is invalid for latin1')\n    def test_attwithfn2231utf8_bad(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=iso-8859-1''foo-%c3%a4-%e2%82%ac.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    @unittest.skip('should raise decoding error: %E4 is invalid for utf-8')\n    def test_attwithfn2231iso_bad(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=utf-8''foo-%E4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231ws1(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename *=UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231ws2(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*= UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    def test_attwithfn2231ws3(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename* =UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    def test_attwithfn2231quot(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=\\\"UTF-8''foo-%c3%a4.html\\\"\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231quot2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=\\\"foo%20bar.html\\\"\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231singleqmissing(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=UTF-8'foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    @unittest.skip('urllib.parse.unquote is tolerate to standalone % chars')\n    def test_attwithfn2231nbadpct1(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=UTF-8''foo%\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    @unittest.skip('urllib.parse.unquote is tolerate to standalone % chars')\n    def test_attwithfn2231nbadpct2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=UTF-8''f%oo.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231dpct(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''A-%2541.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'A-%41.html'}, params)\n\n    def test_attwithfn2231abspathdisguised(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''%5cfoo.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': '\\\\foo.html'}, params)\n\n    def test_attfncont(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo.\"; filename*1=\"html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo.',\n                          'filename*1': 'html'}, params)\n\n    def test_attfncontqs(self):\n        disptype, params = parse_content_disposition(\n            r'attachment; filename*0=\"foo\"; filename*1=\"\\b\\a\\r.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*1': 'bar.html'}, params)\n\n    def test_attfncontenc(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0*=UTF-8''foo-%c3%a4; filename*1=\".html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0*': 'UTF-8''foo-%c3%a4',\n                          'filename*1': '.html'}, params)\n\n    def test_attfncontlz(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo\"; filename*01=\"bar\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*01': 'bar'}, params)\n\n    def test_attfncontnc(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo\"; filename*2=\"bar\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*2': 'bar'}, params)\n\n    def test_attfnconts1(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo.\"; filename*2=\"html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo.',\n                          'filename*2': 'html'}, params)\n\n    def test_attfncontord(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*1=\"bar\"; filename*0=\"foo\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*1': 'bar'}, params)\n\n    def test_attfnboth(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-ae.html\";'\n            \" filename*=UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-ae.html',\n                          'filename*': 'foo-ä.html'}, params)\n\n    def test_attfnboth2(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''foo-%c3%a4.html;\"\n            ' filename=\"foo-ae.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-ae.html',\n                          'filename*': 'foo-ä.html'}, params)\n\n    def test_attfnboth3(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4;\"\n            \" filename*=ISO-8859-1''currency-sign%3d%a4\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'currency-sign=¤',\n                          'filename*0*': \"ISO-8859-15''euro-sign%3d%a4\"},\n                         params)\n\n    def test_attnewandfn(self):\n        disptype, params = parse_content_disposition(\n            'attachment; foobar=x; filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'foobar': 'x',\n                          'filename': 'foo.html'}, params)\n\n    def test_attrfc2047token(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename==?ISO-8859-1?Q?foo-=E4.html?=')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attrfc2047quoted(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"=?ISO-8859-1?Q?foo-=E4.html?=\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '=?ISO-8859-1?Q?foo-=E4.html?='}, params)\n\n    def test_bad_continuous_param(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                'attachment; filename*0=foo bar')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n\nclass ContentDispositionFilenameTestCase(unittest.TestCase):\n    # http://greenbytes.de/tech/tc2231/\n\n    def test_no_filename(self):\n        self.assertIsNone(content_disposition_filename({}))\n        self.assertIsNone(content_disposition_filename({'foo': 'bar'}))\n\n    def test_filename(self):\n        params = {'filename': 'foo.html'}\n        self.assertEqual('foo.html', content_disposition_filename(params))\n\n    def test_filename_ext(self):\n        params = {'filename*': 'файл.html'}\n        self.assertEqual('файл.html', content_disposition_filename(params))\n\n    def test_attfncont(self):\n        params = {'filename*0': 'foo.', 'filename*1': 'html'}\n        self.assertEqual('foo.html', content_disposition_filename(params))\n\n    def test_attfncontqs(self):\n        params = {'filename*0': 'foo', 'filename*1': 'bar.html'}\n        self.assertEqual('foobar.html', content_disposition_filename(params))\n\n    def test_attfncontenc(self):\n        params = {'filename*0*': \"UTF-8''foo-%c3%a4\",\n                  'filename*1': '.html'}\n        self.assertEqual('foo-ä.html', content_disposition_filename(params))\n\n    def test_attfncontlz(self):\n        params = {'filename*0': 'foo',\n                  'filename*01': 'bar'}\n        self.assertEqual('foo', content_disposition_filename(params))\n\n    def test_attfncontnc(self):\n        params = {'filename*0': 'foo',\n                  'filename*2': 'bar'}\n        self.assertEqual('foo', content_disposition_filename(params))\n\n    def test_attfnconts1(self):\n        params = {'filename*1': 'foo',\n                  'filename*2': 'bar'}\n        self.assertEqual(None, content_disposition_filename(params))\n\n    def test_attfnboth(self):\n        params = {'filename': 'foo-ae.html',\n                  'filename*': 'foo-ä.html'}\n        self.assertEqual('foo-ä.html', content_disposition_filename(params))\n\n    def test_attfnboth3(self):\n        params = {'filename*0*': \"ISO-8859-15''euro-sign%3d%a4\",\n                  'filename*': 'currency-sign=¤'}\n        self.assertEqual('currency-sign=¤',\n                         content_disposition_filename(params))\n\n    def test_attrfc2047quoted(self):\n        params = {'filename': '=?ISO-8859-1?Q?foo-=E4.html?='}\n        self.assertEqual('=?ISO-8859-1?Q?foo-=E4.html?=',\n                         content_disposition_filename(params))\n",
            "header": {
                "file": {
                    "path": "tests/test_multipart.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "ebad57b1",
                "new_commit_hash": "2c40a6e0",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tests/test_multipart.py"
            },
            "plus_file": {
                "path": "b/tests/test_multipart.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 527,
                            "length": 6
                        },
                        "new_range": {
                            "start": 527,
                            "length": 23
                        },
                        "section": "class MultipartReaderTestCase(TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.assertTrue(second.at_eof())",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertIsNone(third)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_read_chunk_doesnt_breaks_reader(self):",
                                "type": "added"
                            },
                            {
                                "content": "        reader = aiohttp.multipart.MultipartReader(",
                                "type": "added"
                            },
                            {
                                "content": "            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},",
                                "type": "added"
                            },
                            {
                                "content": "            Stream(b'--:\\r\\n'",
                                "type": "added"
                            },
                            {
                                "content": "                   b'Content-Length: 4\\r\\n\\r\\n'",
                                "type": "added"
                            },
                            {
                                "content": "                   b'test'",
                                "type": "added"
                            },
                            {
                                "content": "                   b'\\r\\n--:\\r\\n'",
                                "type": "added"
                            },
                            {
                                "content": "                   b'Content-Length: 6\\r\\n\\r\\n'",
                                "type": "added"
                            },
                            {
                                "content": "                   b'passed'",
                                "type": "added"
                            },
                            {
                                "content": "                   b'\\r\\n--:--'))",
                                "type": "added"
                            },
                            {
                                "content": "        while True:",
                                "type": "added"
                            },
                            {
                                "content": "            part = yield from reader.next()",
                                "type": "added"
                            },
                            {
                                "content": "            if part is None:",
                                "type": "added"
                            },
                            {
                                "content": "                break",
                                "type": "added"
                            },
                            {
                                "content": "            while not part.at_eof():",
                                "type": "added"
                            },
                            {
                                "content": "                yield from part.read_chunk(3)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class BodyPartWriterTestCase(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tests/test_multipart.py",
                            "type": "class",
                            "name": "MultipartReaderTestCase",
                            "content": "class MultipartReaderTestCase(TestCase):\n\n    def test_from_response(self):\n        resp = Response({CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n                        Stream(b'--:\\r\\n\\r\\nhello\\r\\n--:--'))\n        res = aiohttp.multipart.MultipartReader.from_response(resp)\n        self.assertIsInstance(res,\n                              aiohttp.multipart.MultipartResponseWrapper)\n        self.assertIsInstance(res.stream,\n                              aiohttp.multipart.MultipartReader)\n\n    def test_bad_boundary(self):\n        resp = Response(\n            {CONTENT_TYPE: 'multipart/related;boundary=' + 'a' * 80},\n            Stream(b''))\n        with self.assertRaises(ValueError):\n            aiohttp.multipart.MultipartReader.from_response(resp)\n\n    def test_dispatch(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_bodypart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_multipart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, reader.__class__)\n\n    def test_dispatch_custom_multipart_reader(self):\n        class CustomReader(aiohttp.multipart.MultipartReader):\n            pass\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        reader.multipart_reader_cls = CustomReader\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, CustomReader)\n\n    def test_emit_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = yield from reader.next()\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_invalid_boundary(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'---:\\r\\n\\r\\necho\\r\\n---:--'))\n        with self.assertRaises(ValueError):\n            yield from reader.next()\n\n    def test_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/mixed;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Type: multipart/related;boundary=--:--\\r\\n'\n                   b'\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        res = yield from reader.next()\n        self.assertIsNone(res)\n\n    def test_second_next_releases_previous_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        self.assertIsInstance(first, aiohttp.multipart.BodyPartReader)\n        second = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertFalse(second.at_eof())\n\n    def test_release_without_read_the_last_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        second = yield from reader.next()\n        third = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertIsNone(third)\n\n    def test_read_chunk_doesnt_breaks_reader(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Length: 4\\r\\n\\r\\n'\n                   b'test'\n                   b'\\r\\n--:\\r\\n'\n                   b'Content-Length: 6\\r\\n\\r\\n'\n                   b'passed'\n                   b'\\r\\n--:--'))\n        while True:\n            part = yield from reader.next()\n            if part is None:\n                break\n            while not part.at_eof():\n                yield from part.read_chunk(3)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 382,
                            "end_lineno": 545,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tests/test_multipart.py",
                            "type": "method",
                            "name": "MultipartReaderTestCase.test_read_chunk_doesnt_breaks_reader",
                            "content": "class MultipartReaderTestCase(TestCase):\n\n    def test_from_response(self):\n        resp = Response({CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n                        Stream(b'--:\\r\\n\\r\\nhello\\r\\n--:--'))\n        res = aiohttp.multipart.MultipartReader.from_response(resp)\n        self.assertIsInstance(res,\n                              aiohttp.multipart.MultipartResponseWrapper)\n        self.assertIsInstance(res.stream,\n                              aiohttp.multipart.MultipartReader)\n\n    def test_bad_boundary(self):\n        resp = Response(\n            {CONTENT_TYPE: 'multipart/related;boundary=' + 'a' * 80},\n            Stream(b''))\n        with self.assertRaises(ValueError):\n            aiohttp.multipart.MultipartReader.from_response(resp)\n\n    def test_dispatch(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_bodypart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_multipart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, reader.__class__)\n\n    def test_dispatch_custom_multipart_reader(self):\n        class CustomReader(aiohttp.multipart.MultipartReader):\n            pass\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        reader.multipart_reader_cls = CustomReader\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, CustomReader)\n\n    def test_emit_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = yield from reader.next()\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_invalid_boundary(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'---:\\r\\n\\r\\necho\\r\\n---:--'))\n        with self.assertRaises(ValueError):\n            yield from reader.next()\n\n    def test_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/mixed;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Type: multipart/related;boundary=--:--\\r\\n'\n                   b'\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        res = yield from reader.next()\n        self.assertIsNone(res)\n\n    def test_second_next_releases_previous_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        self.assertIsInstance(first, aiohttp.multipart.BodyPartReader)\n        second = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertFalse(second.at_eof())\n\n    def test_release_without_read_the_last_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        second = yield from reader.next()\n        third = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertIsNone(third)\n\n    def test_read_chunk_doesnt_breaks_reader(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Length: 4\\r\\n\\r\\n'\n                   b'test'\n                   b'\\r\\n--:\\r\\n'\n                   b'Content-Length: 6\\r\\n\\r\\n'\n                   b'passed'\n                   b'\\r\\n--:--'))\n        while True:\n            part = yield from reader.next()\n            if part is None:\n                break\n            while not part.at_eof():\n                yield from part.read_chunk(3)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 530,
                            "end_lineno": 545,
                            "parent": {
                                "file_name": "tests/test_multipart.py",
                                "type": "class",
                                "name": "MultipartReaderTestCase",
                                "content": "class MultipartReaderTestCase(TestCase):\n\n    def test_from_response(self):\n        resp = Response({CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n                        Stream(b'--:\\r\\n\\r\\nhello\\r\\n--:--'))\n        res = aiohttp.multipart.MultipartReader.from_response(resp)\n        self.assertIsInstance(res,\n                              aiohttp.multipart.MultipartResponseWrapper)\n        self.assertIsInstance(res.stream,\n                              aiohttp.multipart.MultipartReader)\n\n    def test_bad_boundary(self):\n        resp = Response(\n            {CONTENT_TYPE: 'multipart/related;boundary=' + 'a' * 80},\n            Stream(b''))\n        with self.assertRaises(ValueError):\n            aiohttp.multipart.MultipartReader.from_response(resp)\n\n    def test_dispatch(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_bodypart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_multipart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, reader.__class__)\n\n    def test_dispatch_custom_multipart_reader(self):\n        class CustomReader(aiohttp.multipart.MultipartReader):\n            pass\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        reader.multipart_reader_cls = CustomReader\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, CustomReader)\n\n    def test_emit_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = yield from reader.next()\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_invalid_boundary(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'---:\\r\\n\\r\\necho\\r\\n---:--'))\n        with self.assertRaises(ValueError):\n            yield from reader.next()\n\n    def test_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/mixed;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Type: multipart/related;boundary=--:--\\r\\n'\n                   b'\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        res = yield from reader.next()\n        self.assertIsNone(res)\n\n    def test_second_next_releases_previous_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        self.assertIsInstance(first, aiohttp.multipart.BodyPartReader)\n        second = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertFalse(second.at_eof())\n\n    def test_release_without_read_the_last_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        second = yield from reader.next()\n        third = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertIsNone(third)\n\n    def test_read_chunk_doesnt_breaks_reader(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Length: 4\\r\\n\\r\\n'\n                   b'test'\n                   b'\\r\\n--:\\r\\n'\n                   b'Content-Length: 6\\r\\n\\r\\n'\n                   b'passed'\n                   b'\\r\\n--:--'))\n        while True:\n            part = yield from reader.next()\n            if part is None:\n                break\n            while not part.at_eof():\n                yield from part.read_chunk(3)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 382,
                                "end_lineno": 545,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "d3fa32eb39057636c7e6246619a3680244061049^",
    "new_commit_hash": "d3fa32eb39057636c7e6246619a3680244061049",
    "commit_message": "Ensure BodyPartReader.read_chunk reads all the data\n\nIt didn't fetch trailing \\r\\n chars causing MultipartReader failure on\nread the boundary with the next readline() call with wrong assertion\nabout malformed multipart payload.",
    "commit_date": "2015-07-09T05:27:40+03:00",
    "metadata": {}
}
{
    "repo_name": "aiohttp",
    "new_commit_hash": "d3fa32eb39057636c7e6246619a3680244061049",
    "test_file_codes": [
        "import asyncio\nimport functools\nimport io\nimport os\nimport unittest\nimport unittest.mock as mock\nimport zlib\n\nimport aiohttp.multipart\nfrom aiohttp.helpers import parse_mimetype\nfrom aiohttp.hdrs import (\n    CONTENT_DISPOSITION,\n    CONTENT_ENCODING,\n    CONTENT_TRANSFER_ENCODING,\n    CONTENT_TYPE\n)\nfrom aiohttp.multipart import (\n    parse_content_disposition,\n    content_disposition_filename\n)\n\n\ndef run_in_loop(f):\n    @functools.wraps(f)\n    def wrapper(testcase, *args, **kwargs):\n        coro = asyncio.coroutine(f)\n        future = asyncio.wait_for(coro(testcase, *args, **kwargs), timeout=5)\n        return testcase.loop.run_until_complete(future)\n    return wrapper\n\n\nclass MetaAioTestCase(type):\n\n    def __new__(cls, name, bases, attrs):\n        for key, obj in attrs.items():\n            if key.startswith('test_'):\n                attrs[key] = run_in_loop(obj)\n        return super().__new__(cls, name, bases, attrs)\n\n\nclass TestCase(unittest.TestCase, metaclass=MetaAioTestCase):\n\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n\n    def tearDown(self):\n        self.loop.close()\n\n    def future(self, obj):\n        fut = asyncio.Future(loop=self.loop)\n        fut.set_result(obj)\n        return fut\n\n\nclass Response(object):\n\n    def __init__(self, headers, content):\n        self.headers = headers\n        self.content = content\n\n\nclass Stream(object):\n\n    def __init__(self, content):\n        self.content = io.BytesIO(content)\n\n    @asyncio.coroutine\n    def read(self, size=None):\n        return self.content.read(size)\n\n    @asyncio.coroutine\n    def readline(self):\n        return self.content.readline()\n\n\nclass MultipartResponseWrapperTestCase(TestCase):\n\n    def setUp(self):\n        super().setUp()\n        wrapper = aiohttp.multipart.MultipartResponseWrapper(mock.Mock(),\n                                                             mock.Mock())\n        self.wrapper = wrapper\n\n    def test_at_eof(self):\n        self.wrapper.at_eof()\n        self.assertTrue(self.wrapper.resp.content.at_eof.called)\n\n    def test_next(self):\n        self.wrapper.stream.next.return_value = self.future(b'')\n        self.wrapper.stream.at_eof.return_value = False\n        yield from self.wrapper.next()\n        self.assertTrue(self.wrapper.stream.next.called)\n\n    def test_release(self):\n        self.wrapper.resp.release.return_value = self.future(None)\n        yield from self.wrapper.release()\n        self.assertTrue(self.wrapper.resp.release.called)\n\n    def test_release_when_stream_at_eof(self):\n        self.wrapper.resp.release.return_value = self.future(None)\n        self.wrapper.stream.next.return_value = self.future(b'')\n        self.wrapper.stream.at_eof.return_value = True\n        yield from self.wrapper.next()\n        self.assertTrue(self.wrapper.stream.next.called)\n        self.assertTrue(self.wrapper.resp.release.called)\n\n\nclass PartReaderTestCase(TestCase):\n\n    def setUp(self):\n        super().setUp()\n        self.boundary = b'--:'\n\n    def test_next(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        result = yield from obj.next()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_next_next(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        result = yield from obj.next()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertTrue(obj.at_eof())\n        result = yield from obj.next()\n        self.assertIsNone(result)\n\n    def test_read(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        result = yield from obj.read()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_chunk_at_eof(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'--:'))\n        obj._at_eof = True\n        result = yield from obj.read_chunk()\n        self.assertEqual(b'', result)\n\n    def test_read_chunk_requires_content_length(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:'))\n        with self.assertRaises(AssertionError):\n            yield from obj.read_chunk()\n\n    def test_read_does_reads_boundary(self):\n        stream = Stream(b'Hello, world!\\r\\n--:')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, stream)\n        result = yield from obj.read()\n        self.assertEqual(b'Hello, world!\\r\\n', result)\n        self.assertEqual(b'', (yield from stream.read()))\n        self.assertEqual([b'--:'], obj._unread)\n\n    def test_multiread(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello,\\r\\n--:\\r\\n\\r\\nworld!\\r\\n--:--'))\n        result = yield from obj.read()\n        self.assertEqual(b'Hello,\\r\\n', result)\n        result = yield from obj.read()\n        self.assertEqual(b'', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_multiline(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello\\n,\\r\\nworld!\\r\\n--:--'))\n        result = yield from obj.read()\n        self.assertEqual(b'Hello\\n,\\r\\nworld!\\r\\n', result)\n        result = yield from obj.read()\n        self.assertEqual(b'', result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_respects_content_length(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {'CONTENT-LENGTH': 100500},\n            Stream(b'.' * 100500 + b'\\r\\n--:--'))\n        result = yield from obj.read()\n        self.assertEqual(b'.' * 100500, result)\n        self.assertTrue(obj.at_eof())\n\n    def test_read_with_content_encoding_gzip(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'gzip'},\n            Stream(b'\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x0b\\xc9\\xccMU'\n                   b'(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00$\\xfb\\x9eV\\x0e\\x00\\x00\\x00'\n                   b'\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'Time to Relax!', result)\n\n    def test_read_with_content_encoding_deflate(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'deflate'},\n            Stream(b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'Time to Relax!', result)\n\n    def test_read_with_content_encoding_identity(self):\n        thing = (b'\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x03\\x0b\\xc9\\xccMU'\n                 b'(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00$\\xfb\\x9eV\\x0e\\x00\\x00\\x00'\n                 b'\\r\\n')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'identity'},\n            Stream(thing + b'--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(thing, result)\n\n    def test_read_with_content_encoding_unknown(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'snappy'},\n            Stream(b'\\x0e4Time to Relax!\\r\\n--:--'))\n        with self.assertRaises(RuntimeError):\n            yield from obj.read(decode=True)\n\n    def test_read_with_content_transfer_encoding_base64(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TRANSFER_ENCODING: 'base64'},\n            Stream(b'VGltZSB0byBSZWxheCE=\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'Time to Relax!', result)\n\n    def test_read_with_content_transfer_encoding_quoted_printable(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TRANSFER_ENCODING: 'quoted-printable'},\n            Stream(b'=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,'\n                   b' =D0=BC=D0=B8=D1=80!\\r\\n--:--'))\n        result = yield from obj.read(decode=True)\n        self.assertEqual(b'\\xd0\\x9f\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82,'\n                         b' \\xd0\\xbc\\xd0\\xb8\\xd1\\x80!\\r\\n', result)\n\n    def test_read_with_content_transfer_encoding_unknown(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TRANSFER_ENCODING: 'unknown'},\n            Stream(b'\\x0e4Time to Relax!\\r\\n--:--'))\n        with self.assertRaises(RuntimeError):\n            yield from obj.read(decode=True)\n\n    def test_read_text(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, Stream(b'Hello, world!\\r\\n--:--'))\n        result = yield from obj.text()\n        self.assertEqual('Hello, world!\\r\\n', result)\n\n    def test_read_text_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {},\n            Stream('Привет, Мир!\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.text(encoding='cp1251')\n        self.assertEqual('Привет, Мир!\\r\\n', result)\n\n    def test_read_text_guess_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'text/plain;charset=cp1251'},\n            Stream('Привет, Мир!\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.text()\n        self.assertEqual('Привет, Мир!\\r\\n', result)\n\n    def test_read_text_compressed(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'deflate',\n                            CONTENT_TYPE: 'text/plain'},\n            Stream(b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00\\r\\n--:--'))\n        result = yield from obj.text()\n        self.assertEqual('Time to Relax!', result)\n\n    def test_read_text_while_closed(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'text/plain'}, Stream(b''))\n        obj._at_eof = True\n        result = yield from obj.text()\n        self.assertEqual('', result)\n\n    def test_read_json(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json'},\n            Stream(b'{\"test\": \"passed\"}\\r\\n--:--'))\n        result = yield from obj.json()\n        self.assertEqual({'test': 'passed'}, result)\n\n    def test_read_json_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json'},\n            Stream('{\"тест\": \"пассед\"}\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.json(encoding='cp1251')\n        self.assertEqual({'тест': 'пассед'}, result)\n\n    def test_read_json_guess_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json; charset=cp1251'},\n            Stream('{\"тест\": \"пассед\"}\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.json()\n        self.assertEqual({'тест': 'пассед'}, result)\n\n    def test_read_json_compressed(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_ENCODING: 'deflate',\n                            CONTENT_TYPE: 'application/json'},\n            Stream(b'\\xabV*I-.Q\\xb2RP*H,.NMQ\\xaa\\x05\\x00\\r\\n--:--'))\n        result = yield from obj.json()\n        self.assertEqual({'test': 'passed'}, result)\n\n    def test_read_json_while_closed(self):\n        stream = Stream(b'')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/json'}, stream)\n        obj._at_eof = True\n        result = yield from obj.json()\n        self.assertEqual(None, result)\n\n    def test_read_form(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/x-www-form-urlencoded'},\n            Stream(b'foo=bar&foo=baz&boo=zoo\\r\\n--:--'))\n        result = yield from obj.form()\n        self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],\n                         result)\n\n    def test_read_form_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {CONTENT_TYPE: 'application/x-www-form-urlencoded'},\n            Stream('foo=bar&foo=baz&boo=zoo\\r\\n--:--'.encode('cp1251')))\n        result = yield from obj.form(encoding='cp1251')\n        self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],\n                         result)\n\n    def test_read_form_guess_encoding(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary,\n            {CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=utf-8'},\n            Stream('foo=bar&foo=baz&boo=zoo\\r\\n--:--'.encode('utf-8')))\n        result = yield from obj.form()\n        self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],\n                         result)\n\n    def test_read_form_while_closed(self):\n        stream = Stream(b'')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary,\n            {CONTENT_TYPE: 'application/x-www-form-urlencoded'}, stream)\n        obj._at_eof = True\n        result = yield from obj.form()\n        self.assertEqual(None, result)\n\n    def test_release(self):\n        stream = Stream(b'Hello,\\r\\n--:\\r\\n\\r\\nworld!\\r\\n--:--')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, stream)\n        yield from obj.release()\n        self.assertTrue(obj.at_eof())\n        self.assertEqual(b'\\r\\nworld!\\r\\n--:--', stream.content.read())\n        self.assertEqual([b'--:\\r\\n'], obj._unread)\n\n    def test_release_respects_content_length(self):\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {'CONTENT-LENGTH': 100500},\n            Stream(b'.' * 100500 + b'\\r\\n--:--'))\n        result = yield from obj.release()\n        self.assertIsNone(result)\n        self.assertTrue(obj.at_eof())\n\n    def test_release_release(self):\n        stream = Stream(b'Hello,\\r\\n--:\\r\\n\\r\\nworld!\\r\\n--:--')\n        obj = aiohttp.multipart.BodyPartReader(\n            self.boundary, {}, stream)\n        yield from obj.release()\n        yield from obj.release()\n        self.assertEqual(b'\\r\\nworld!\\r\\n--:--', stream.content.read())\n        self.assertEqual([b'--:\\r\\n'], obj._unread)\n\n    def test_filename(self):\n        part = aiohttp.multipart.BodyPartReader(\n            self.boundary,\n            {CONTENT_DISPOSITION: 'attachment; filename=foo.html'},\n            None)\n        self.assertEqual('foo.html', part.filename)\n\n\nclass MultipartReaderTestCase(TestCase):\n\n    def test_from_response(self):\n        resp = Response({CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n                        Stream(b'--:\\r\\n\\r\\nhello\\r\\n--:--'))\n        res = aiohttp.multipart.MultipartReader.from_response(resp)\n        self.assertIsInstance(res,\n                              aiohttp.multipart.MultipartResponseWrapper)\n        self.assertIsInstance(res.stream,\n                              aiohttp.multipart.MultipartReader)\n\n    def test_bad_boundary(self):\n        resp = Response(\n            {CONTENT_TYPE: 'multipart/related;boundary=' + 'a' * 80},\n            Stream(b''))\n        with self.assertRaises(ValueError):\n            aiohttp.multipart.MultipartReader.from_response(resp)\n\n    def test_dispatch(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_bodypart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_dispatch_multipart(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, reader.__class__)\n\n    def test_dispatch_custom_multipart_reader(self):\n        class CustomReader(aiohttp.multipart.MultipartReader):\n            pass\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        reader.multipart_reader_cls = CustomReader\n        res = reader._get_part_reader(\n            {CONTENT_TYPE: 'multipart/related;boundary=--:--'})\n        self.assertIsInstance(res, CustomReader)\n\n    def test_emit_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        res = yield from reader.next()\n        self.assertIsInstance(res, reader.part_reader_cls)\n\n    def test_invalid_boundary(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'---:\\r\\n\\r\\necho\\r\\n---:--'))\n        with self.assertRaises(ValueError):\n            yield from reader.next()\n\n    def test_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/mixed;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Type: multipart/related;boundary=--:--\\r\\n'\n                   b'\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'----:--\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'----:----\\r\\n'\n                   b'--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_release(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n\n    def test_release_next(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n\\r\\necho\\r\\n--:--'))\n        yield from reader.release()\n        self.assertTrue(reader.at_eof())\n        res = yield from reader.next()\n        self.assertIsNone(res)\n\n    def test_second_next_releases_previous_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        self.assertIsInstance(first, aiohttp.multipart.BodyPartReader)\n        second = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertFalse(second.at_eof())\n\n    def test_release_without_read_the_last_object(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'test\\r\\n'\n                   b'--:\\r\\n'\n                   b'\\r\\n'\n                   b'passed\\r\\n'\n                   b'--:--'))\n        first = yield from reader.next()\n        second = yield from reader.next()\n        third = yield from reader.next()\n        self.assertTrue(first.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertTrue(second.at_eof())\n        self.assertIsNone(third)\n\n    def test_read_chunk_doesnt_breaks_reader(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Length: 4\\r\\n\\r\\n'\n                   b'test'\n                   b'\\r\\n--:\\r\\n'\n                   b'Content-Length: 6\\r\\n\\r\\n'\n                   b'passed'\n                   b'\\r\\n--:--'))\n        while True:\n            part = yield from reader.next()\n            if part is None:\n                break\n            while not part.at_eof():\n                yield from part.read_chunk(3)\n\n\nclass BodyPartWriterTestCase(unittest.TestCase):\n\n    def setUp(self):\n        self.part = aiohttp.multipart.BodyPartWriter(b'')\n\n    def test_guess_content_length(self):\n        self.part.headers[CONTENT_TYPE] = 'text/plain; charset=utf-8'\n        self.assertIsNone(self.part._guess_content_length({}))\n        self.assertIsNone(self.part._guess_content_length(object()))\n        self.assertEqual(3,\n                         self.part._guess_content_length(io.BytesIO(b'foo')))\n        self.assertEqual(3,\n                         self.part._guess_content_length(io.StringIO('foo')))\n        self.assertEqual(6,\n                         self.part._guess_content_length(io.StringIO('мяу')))\n        self.assertEqual(3, self.part._guess_content_length(b'bar'))\n        self.assertEqual(12, self.part._guess_content_length('пассед'))\n        with open(__file__, 'rb') as f:\n            self.assertEqual(os.fstat(f.fileno()).st_size,\n                             self.part._guess_content_length(f))\n\n    def test_guess_content_type(self):\n        default = 'application/octet-stream'\n        self.assertEqual(default, self.part._guess_content_type(b'foo'))\n        self.assertEqual('text/plain; charset=utf-8',\n                         self.part._guess_content_type('foo'))\n\n        here = os.path.dirname(__file__)\n        filename = os.path.join(here, 'software_development_in_picture.jpg')\n\n        with open(filename, 'rb') as f:\n            self.assertEqual('image/jpeg',\n                             self.part._guess_content_type(f))\n\n    def test_guess_filename(self):\n        class Named:\n            name = 'foo'\n        self.assertIsNone(self.part._guess_filename({}))\n        self.assertIsNone(self.part._guess_filename(object()))\n        self.assertIsNone(self.part._guess_filename(io.BytesIO(b'foo')))\n        self.assertIsNone(self.part._guess_filename(Named()))\n        with open(__file__, 'rb') as f:\n            self.assertEqual(os.path.basename(f.name),\n                             self.part._guess_filename(f))\n\n    def test_autoset_content_disposition(self):\n        self.part.obj = open(__file__, 'rb')\n        self.addCleanup(self.part.obj.close)\n        self.part._fill_headers_with_defaults()\n        self.assertIn(CONTENT_DISPOSITION, self.part.headers)\n        fname = os.path.basename(self.part.obj.name)\n        self.assertEqual(\n            'attachment; filename=\"{0}\"; filename*=utf-8\\'\\'{0}'.format(fname),\n            self.part.headers[CONTENT_DISPOSITION])\n\n    def test_set_content_disposition(self):\n        self.part.set_content_disposition('attachment', foo='bar')\n        self.assertEqual(\n            'attachment; foo=bar',\n            self.part.headers[CONTENT_DISPOSITION])\n\n    def test_set_content_disposition_bad_type(self):\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('foo bar')\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('тест')\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('foo\\x00bar')\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('')\n\n    def test_set_content_disposition_bad_param(self):\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline', **{'foo bar': 'baz'})\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline', **{'тест': 'baz'})\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline', **{'': 'baz'})\n        with self.assertRaises(ValueError):\n            self.part.set_content_disposition('inline',\n                                              **{'foo\\x00bar': 'baz'})\n\n    def test_serialize_bytes(self):\n        self.assertEqual(b'foo', next(self.part._serialize_bytes(b'foo')))\n\n    def test_serialize_str(self):\n        self.assertEqual(b'foo', next(self.part._serialize_str('foo')))\n\n    def test_serialize_str_custom_encoding(self):\n        self.part.headers[CONTENT_TYPE] = \\\n            'text/plain;charset=cp1251'\n        self.assertEqual('привет'.encode('cp1251'),\n                         next(self.part._serialize_str('привет')))\n\n    def test_serialize_io(self):\n        self.assertEqual(b'foo',\n                         next(self.part._serialize_io(io.BytesIO(b'foo'))))\n        self.assertEqual(b'foo',\n                         next(self.part._serialize_io(io.StringIO('foo'))))\n\n    def test_serialize_io_chunk(self):\n        flo = io.BytesIO(b'foobarbaz')\n        self.part._chunk_size = 3\n        self.assertEqual([b'foo', b'bar', b'baz'],\n                         list(self.part._serialize_io(flo)))\n\n    def test_serialize_json(self):\n        self.assertEqual(b'{\"\\\\u043f\\\\u0440\\\\u0438\\\\u0432\\\\u0435\\\\u0442\":'\n                         b' \"\\\\u043c\\\\u0438\\\\u0440\"}',\n                         next(self.part._serialize_json({'привет': 'мир'})))\n\n    def test_serialize_form(self):\n        data = [('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')]\n        self.assertEqual(b'foo=bar&foo=baz&boo=zoo',\n                         next(self.part._serialize_form(data)))\n\n    def test_serialize_form_dict(self):\n        data = {'hello': 'мир'}\n        self.assertEqual(b'hello=%D0%BC%D0%B8%D1%80',\n                         next(self.part._serialize_form(data)))\n\n    def test_serialize_multipart(self):\n        multipart = aiohttp.multipart.MultipartWriter(boundary=':')\n        multipart.append('foo-bar-baz')\n        multipart.append_json({'test': 'passed'})\n        self.assertEqual(\n            [b'--:\\r\\n',\n             b'CONTENT-TYPE: text/plain; charset=utf-8\\r\\n'\n             b'CONTENT-LENGTH: 11',\n             b'\\r\\n\\r\\n',\n             b'foo-bar-baz',\n             b'\\r\\n',\n             b'--:\\r\\n',\n             b'CONTENT-TYPE: application/json',\n             b'\\r\\n\\r\\n',\n             b'{\"test\": \"passed\"}',\n             b'\\r\\n',\n             b'--:--\\r\\n',\n             b''],\n            list(self.part._serialize_multipart(multipart))\n        )\n\n    def test_serialize_default(self):\n        with self.assertRaises(TypeError):\n            self.part.obj = object()\n            list(self.part.serialize())\n        with self.assertRaises(TypeError):\n            next(self.part._serialize_default(object()))\n\n    def test_serialize_with_content_encoding_gzip(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_ENCODING: 'gzip'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-ENCODING: gzip\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        result = b''.join(stream)\n\n        decompressor = zlib.decompressobj(wbits=16+zlib.MAX_WBITS)\n        data = decompressor.decompress(result)\n        self.assertEqual(b'Time to Relax!', data)\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_encoding_deflate(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_ENCODING: 'deflate'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-ENCODING: deflate\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        thing = b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00\\r\\n'\n        self.assertEqual(thing, b''.join(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_encoding_identity(self):\n        thing = b'\\x0b\\xc9\\xccMU(\\xc9W\\x08J\\xcdI\\xacP\\x04\\x00'\n        part = aiohttp.multipart.BodyPartWriter(\n            thing, {CONTENT_ENCODING: 'identity'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-ENCODING: identity\\r\\n'\n                         b'CONTENT-TYPE: application/octet-stream\\r\\n'\n                         b'CONTENT-LENGTH: 16',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(thing, next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_encoding_unknown(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_ENCODING: 'snappy'})\n        with self.assertRaises(RuntimeError):\n            list(part.serialize())\n\n    def test_serialize_with_content_transfer_encoding_base64(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_TRANSFER_ENCODING: 'base64'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-TRANSFER-ENCODING: base64\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(b'VGltZSB0byBSZWxh', next(stream))\n        self.assertEqual(b'eCE=', next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_io_with_content_transfer_encoding_base64(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            io.BytesIO(b'Time to Relax!'),\n            {CONTENT_TRANSFER_ENCODING: 'base64'})\n        part._chunk_size = 6\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-TRANSFER-ENCODING: base64\\r\\n'\n                         b'CONTENT-TYPE: application/octet-stream',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(b'VGltZSB0', next(stream))\n        self.assertEqual(b'byBSZWxh', next(stream))\n        self.assertEqual(b'eCE=', next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_transfer_encoding_quote_printable(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Привет, мир!', {CONTENT_TRANSFER_ENCODING: 'quoted-printable'})\n        stream = part.serialize()\n        self.assertEqual(b'CONTENT-TRANSFER-ENCODING: quoted-printable\\r\\n'\n                         b'CONTENT-TYPE: text/plain; charset=utf-8',\n                         next(stream))\n        self.assertEqual(b'\\r\\n\\r\\n', next(stream))\n\n        self.assertEqual(b'=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,'\n                         b' =D0=BC=D0=B8=D1=80!', next(stream))\n        self.assertEqual(b'\\r\\n', next(stream))\n        self.assertIsNone(next(stream, None))\n\n    def test_serialize_with_content_transfer_encoding_unknown(self):\n        part = aiohttp.multipart.BodyPartWriter(\n            'Time to Relax!', {CONTENT_TRANSFER_ENCODING: 'unknown'})\n        with self.assertRaises(RuntimeError):\n            list(part.serialize())\n\n    def test_filename(self):\n        self.part.set_content_disposition('related', filename='foo.html')\n        self.assertEqual('foo.html', self.part.filename)\n\n\nclass MultipartWriterTestCase(unittest.TestCase):\n\n    def setUp(self):\n        self.writer = aiohttp.multipart.MultipartWriter(boundary=':')\n\n    def test_default_subtype(self):\n        mtype, stype, *_ = parse_mimetype(\n            self.writer.headers.get(CONTENT_TYPE))\n        self.assertEqual('multipart', mtype)\n        self.assertEqual('mixed', stype)\n\n    def test_bad_boundary(self):\n        with self.assertRaises(ValueError):\n            aiohttp.multipart.MultipartWriter(boundary='тест')\n\n    def test_default_headers(self):\n        self.assertEqual({CONTENT_TYPE: 'multipart/mixed; boundary=\":\"'},\n                         self.writer.headers)\n\n    def test_iter_parts(self):\n        self.writer.append('foo')\n        self.writer.append('bar')\n        self.writer.append('baz')\n        self.assertEqual(3, len(list(self.writer)))\n\n    def test_append(self):\n        self.assertEqual(0, len(self.writer))\n        self.writer.append('hello, world!')\n        self.assertEqual(1, len(self.writer))\n        self.assertIsInstance(self.writer.parts[0],\n                              self.writer.part_writer_cls)\n\n    def test_append_with_headers(self):\n        self.writer.append('hello, world!', {'x-foo': 'bar'})\n        self.assertEqual(1, len(self.writer))\n        self.assertIn('x-foo', self.writer.parts[0].headers)\n        self.assertEqual(self.writer.parts[0].headers['x-foo'], 'bar')\n\n    def test_append_json(self):\n        self.writer.append_json({'foo': 'bar'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE], 'application/json')\n\n    def test_append_part(self):\n        part = aiohttp.multipart.BodyPartWriter('test',\n                                                {CONTENT_TYPE: 'text/plain'})\n        self.writer.append(part, {CONTENT_TYPE: 'test/passed'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE], 'test/passed')\n\n    def test_append_json_overrides_content_type(self):\n        self.writer.append_json({'foo': 'bar'}, {CONTENT_TYPE: 'test/passed'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE], 'application/json')\n\n    def test_append_form(self):\n        self.writer.append_form({'foo': 'bar'}, {CONTENT_TYPE: 'test/passed'})\n        self.assertEqual(1, len(self.writer))\n        part = self.writer.parts[0]\n        self.assertEqual(part.headers[CONTENT_TYPE],\n                         'application/x-www-form-urlencoded')\n\n    def test_serialize(self):\n        self.assertEqual([b''], list(self.writer.serialize()))\n\n    def test_with(self):\n        with aiohttp.multipart.MultipartWriter(boundary=':') as writer:\n            writer.append('foo')\n            writer.append(b'bar')\n            writer.append_json({'baz': True})\n        self.assertEqual(3, len(writer))\n\n\nclass ParseContentDispositionTestCase(unittest.TestCase):\n    # http://greenbytes.de/tech/tc2231/\n\n    def test_parse_empty(self):\n        disptype, params = parse_content_disposition(None)\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_inlonly(self):\n        disptype, params = parse_content_disposition('inline')\n        self.assertEqual('inline', disptype)\n        self.assertEqual({}, params)\n\n    def test_inlonlyquoted(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition('\"inline\"')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_inlwithasciifilename(self):\n        disptype, params = parse_content_disposition(\n            'inline; filename=\"foo.html\"')\n        self.assertEqual('inline', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_inlwithfnattach(self):\n        disptype, params = parse_content_disposition(\n            'inline; filename=\"Not an attachment!\"')\n        self.assertEqual('inline', disptype)\n        self.assertEqual({'filename': 'Not an attachment!'}, params)\n\n    def test_attonly(self):\n        disptype, params = parse_content_disposition('attachment')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attonlyquoted(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition('\"attachment\"')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attonlyucase(self):\n        disptype, params = parse_content_disposition('ATTACHMENT')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithasciifilename(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_inlwithasciifilenamepdf(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo.pdf\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.pdf'}, params)\n\n    def test_attwithasciifilename25(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"0000000000111111111122222\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '0000000000111111111122222'}, params)\n\n    def test_attwithasciifilename35(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"00000000001111111111222222222233333\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '00000000001111111111222222222233333'},\n                         params)\n\n    def test_attwithasciifnescapedchar(self):\n        disptype, params = parse_content_disposition(\n            r'attachment; filename=\"f\\oo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwithasciifnescapedquote(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"\\\"quoting\\\" tested.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '\"quoting\" tested.html'}, params)\n\n    @unittest.skip('need more smart parser which respects quoted text')\n    def test_attwithquotedsemicolon(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"Here\\'s a semicolon;.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'Here\\'s a semicolon;.html'}, params)\n\n    def test_attwithfilenameandextparam(self):\n        disptype, params = parse_content_disposition(\n            'attachment; foo=\"bar\"; filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html', 'foo': 'bar'}, params)\n\n    def test_attwithfilenameandextparamescaped(self):\n        disptype, params = parse_content_disposition(\n            'attachment; foo=\"\\\"\\\\\";filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html', 'foo': '\"\\\\'}, params)\n\n    def test_attwithasciifilenameucase(self):\n        disptype, params = parse_content_disposition(\n            'attachment; FILENAME=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwithasciifilenamenq(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=foo.html')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwithtokfncommanq(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo,bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithasciifilenamenqs(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo.html ;')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attemptyparam(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; ;filename=foo')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithasciifilenamenqws(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfntokensq(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename='foo.html'\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': \"'foo.html'\"}, params)\n\n    def test_attwithisofnplain(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-ä.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-ä.html'}, params)\n\n    def test_attwithutf8fnplain(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-Ã¤.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-Ã¤.html'}, params)\n\n    def test_attwithfnrawpctenca(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-%41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-%41.html'}, params)\n\n    def test_attwithfnusingpct(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"50%.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '50%.html'}, params)\n\n    def test_attwithfnrawpctencaq(self):\n        disptype, params = parse_content_disposition(\n            r'attachment; filename=\"foo-%\\41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': r'foo-%41.html'}, params)\n\n    def test_attwithnamepct(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-%41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-%41.html'}, params)\n\n    def test_attwithfilenamepctandiso(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"ä-%41.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'ä-%41.html'}, params)\n\n    def test_attwithfnrawpctenclong(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-%c3%a4-%e2%82%ac.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-%c3%a4-%e2%82%ac.html'}, params)\n\n    def test_attwithasciifilenamews1(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename =\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attwith2filenames(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=\"foo.html\"; filename=\"bar.html\"')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attfnbrokentoken(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo[1](2).html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attfnbrokentokeniso(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo-ä.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attfnbrokentokenutf(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo-Ã¤.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'x=y; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition3(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                '\"foo; filename=bar;baz\"; filename=qux')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdisposition4(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'filename=foo.html, filename=bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_emptydisposition(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                '; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_doublecolon(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                ': inline; attachment; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attandinline(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'inline; attachment; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attandinline2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; inline; filename=foo.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attbrokenquotedfn(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=\"foo.html\".txt')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attbrokenquotedfn2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=\"bar')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attbrokenquotedfn3(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo\"bar;baz\"qux')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmultinstances(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=foo.html, attachment; filename=bar.html')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdelim(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; foo=foo filename=bar')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdelim2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename=bar foo=foo')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attmissingdelim3(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment filename=bar')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attreversed(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'filename=foo.html; attachment')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attconfusedparam(self):\n        disptype, params = parse_content_disposition(\n            'attachment; xfilename=foo.html')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'xfilename': 'foo.html'}, params)\n\n    def test_attabspath(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"/foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attabspathwin(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"\\\\foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo.html'}, params)\n\n    def test_attcdate(self):\n        disptype, params = parse_content_disposition(\n            'attachment; creation-date=\"Wed, 12 Feb 1997 16:29:51 -0500\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'creation-date': 'Wed, 12 Feb 1997 16:29:51 -0500'},\n                         params)\n\n    def test_attmdate(self):\n        disptype, params = parse_content_disposition(\n            'attachment; modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual(\n            {'modification-date': 'Wed, 12 Feb 1997 16:29:51 -0500'},\n            params)\n\n    def test_dispext(self):\n        disptype, params = parse_content_disposition('foobar')\n        self.assertEqual('foobar', disptype)\n        self.assertEqual({}, params)\n\n    def test_dispextbadfn(self):\n        disptype, params = parse_content_disposition(\n            'attachment; example=\"filename=example.txt\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'example': 'filename=example.txt'}, params)\n\n    def test_attwithisofn2231iso(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=iso-8859-1''foo-%E4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    def test_attwithfn2231utf8(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''foo-%c3%a4-%e2%82%ac.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä-€.html'}, params)\n\n    def test_attwithfn2231noc(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=''foo-%c3%a4-%e2%82%ac.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä-€.html'}, params)\n\n    def test_attwithfn2231utf8comp(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''foo-a%cc%88.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    @unittest.skip('should raise decoding error: %82 is invalid for latin1')\n    def test_attwithfn2231utf8_bad(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=iso-8859-1''foo-%c3%a4-%e2%82%ac.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    @unittest.skip('should raise decoding error: %E4 is invalid for utf-8')\n    def test_attwithfn2231iso_bad(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=utf-8''foo-%E4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231ws1(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename *=UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231ws2(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*= UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    def test_attwithfn2231ws3(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename* =UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'foo-ä.html'}, params)\n\n    def test_attwithfn2231quot(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=\\\"UTF-8''foo-%c3%a4.html\\\"\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231quot2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=\\\"foo%20bar.html\\\"\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231singleqmissing(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=UTF-8'foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    @unittest.skip('urllib.parse.unquote is tolerate to standalone % chars')\n    def test_attwithfn2231nbadpct1(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=UTF-8''foo%\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    @unittest.skip('urllib.parse.unquote is tolerate to standalone % chars')\n    def test_attwithfn2231nbadpct2(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                \"attachment; filename*=UTF-8''f%oo.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n    def test_attwithfn2231dpct(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''A-%2541.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'A-%41.html'}, params)\n\n    def test_attwithfn2231abspathdisguised(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''%5cfoo.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': '\\\\foo.html'}, params)\n\n    def test_attfncont(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo.\"; filename*1=\"html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo.',\n                          'filename*1': 'html'}, params)\n\n    def test_attfncontqs(self):\n        disptype, params = parse_content_disposition(\n            r'attachment; filename*0=\"foo\"; filename*1=\"\\b\\a\\r.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*1': 'bar.html'}, params)\n\n    def test_attfncontenc(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0*=UTF-8''foo-%c3%a4; filename*1=\".html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0*': 'UTF-8''foo-%c3%a4',\n                          'filename*1': '.html'}, params)\n\n    def test_attfncontlz(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo\"; filename*01=\"bar\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*01': 'bar'}, params)\n\n    def test_attfncontnc(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo\"; filename*2=\"bar\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*2': 'bar'}, params)\n\n    def test_attfnconts1(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*0=\"foo.\"; filename*2=\"html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo.',\n                          'filename*2': 'html'}, params)\n\n    def test_attfncontord(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename*1=\"bar\"; filename*0=\"foo\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*0': 'foo',\n                          'filename*1': 'bar'}, params)\n\n    def test_attfnboth(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"foo-ae.html\";'\n            \" filename*=UTF-8''foo-%c3%a4.html\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-ae.html',\n                          'filename*': 'foo-ä.html'}, params)\n\n    def test_attfnboth2(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*=UTF-8''foo-%c3%a4.html;\"\n            ' filename=\"foo-ae.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': 'foo-ae.html',\n                          'filename*': 'foo-ä.html'}, params)\n\n    def test_attfnboth3(self):\n        disptype, params = parse_content_disposition(\n            \"attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4;\"\n            \" filename*=ISO-8859-1''currency-sign%3d%a4\")\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename*': 'currency-sign=¤',\n                          'filename*0*': \"ISO-8859-15''euro-sign%3d%a4\"},\n                         params)\n\n    def test_attnewandfn(self):\n        disptype, params = parse_content_disposition(\n            'attachment; foobar=x; filename=\"foo.html\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'foobar': 'x',\n                          'filename': 'foo.html'}, params)\n\n    def test_attrfc2047token(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionHeader):\n            disptype, params = parse_content_disposition(\n                'attachment; filename==?ISO-8859-1?Q?foo-=E4.html?=')\n        self.assertEqual(None, disptype)\n        self.assertEqual({}, params)\n\n    def test_attrfc2047quoted(self):\n        disptype, params = parse_content_disposition(\n            'attachment; filename=\"=?ISO-8859-1?Q?foo-=E4.html?=\"')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({'filename': '=?ISO-8859-1?Q?foo-=E4.html?='}, params)\n\n    def test_bad_continuous_param(self):\n        with self.assertWarns(aiohttp.multipart.BadContentDispositionParam):\n            disptype, params = parse_content_disposition(\n                'attachment; filename*0=foo bar')\n        self.assertEqual('attachment', disptype)\n        self.assertEqual({}, params)\n\n\nclass ContentDispositionFilenameTestCase(unittest.TestCase):\n    # http://greenbytes.de/tech/tc2231/\n\n    def test_no_filename(self):\n        self.assertIsNone(content_disposition_filename({}))\n        self.assertIsNone(content_disposition_filename({'foo': 'bar'}))\n\n    def test_filename(self):\n        params = {'filename': 'foo.html'}\n        self.assertEqual('foo.html', content_disposition_filename(params))\n\n    def test_filename_ext(self):\n        params = {'filename*': 'файл.html'}\n        self.assertEqual('файл.html', content_disposition_filename(params))\n\n    def test_attfncont(self):\n        params = {'filename*0': 'foo.', 'filename*1': 'html'}\n        self.assertEqual('foo.html', content_disposition_filename(params))\n\n    def test_attfncontqs(self):\n        params = {'filename*0': 'foo', 'filename*1': 'bar.html'}\n        self.assertEqual('foobar.html', content_disposition_filename(params))\n\n    def test_attfncontenc(self):\n        params = {'filename*0*': \"UTF-8''foo-%c3%a4\",\n                  'filename*1': '.html'}\n        self.assertEqual('foo-ä.html', content_disposition_filename(params))\n\n    def test_attfncontlz(self):\n        params = {'filename*0': 'foo',\n                  'filename*01': 'bar'}\n        self.assertEqual('foo', content_disposition_filename(params))\n\n    def test_attfncontnc(self):\n        params = {'filename*0': 'foo',\n                  'filename*2': 'bar'}\n        self.assertEqual('foo', content_disposition_filename(params))\n\n    def test_attfnconts1(self):\n        params = {'filename*1': 'foo',\n                  'filename*2': 'bar'}\n        self.assertEqual(None, content_disposition_filename(params))\n\n    def test_attfnboth(self):\n        params = {'filename': 'foo-ae.html',\n                  'filename*': 'foo-ä.html'}\n        self.assertEqual('foo-ä.html', content_disposition_filename(params))\n\n    def test_attfnboth3(self):\n        params = {'filename*0*': \"ISO-8859-15''euro-sign%3d%a4\",\n                  'filename*': 'currency-sign=¤'}\n        self.assertEqual('currency-sign=¤',\n                         content_disposition_filename(params))\n\n    def test_attrfc2047quoted(self):\n        params = {'filename': '=?ISO-8859-1?Q?foo-=E4.html?='}\n        self.assertEqual('=?ISO-8859-1?Q?foo-=E4.html?=',\n                         content_disposition_filename(params))\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Transforming aiohttp/worker.py\nTransforming aiohttp/client_reqrep.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 23ms\nInstalled 26 packages in 51ms\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_d3fa32eb39057636c7e6246619a3680244061049\nplugins: mock-3.14.0, asyncio-0.25.1, cov-6.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollected 192 items\n\nr2e_tests/test_1.py .................................................... [ 27%]\n...F.................................................................... [ 64%]\n.....................sss.....s............s.........................     [100%]\n\n=================================== FAILURES ===================================\n________________ BodyPartWriterTestCase.test_guess_content_type ________________\n\nself = <r2e_tests.test_1.BodyPartWriterTestCase testMethod=test_guess_content_type>\n\n    def test_guess_content_type(self):\n        default = 'application/octet-stream'\n        self.assertEqual(default, self.part._guess_content_type(b'foo'))\n        self.assertEqual('text/plain; charset=utf-8',\n                         self.part._guess_content_type('foo'))\n    \n        here = os.path.dirname(__file__)\n        filename = os.path.join(here, 'software_development_in_picture.jpg')\n    \n>       with open(filename, 'rb') as f:\nE       FileNotFoundError: [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d3fa32eb39057636c7e6246619a3680244061049/r2e_tests/software_development_in_picture.jpg'\n\nr2e_tests/test_1.py:578: FileNotFoundError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::MultipartResponseWrapperTestCase::test_at_eof\nPASSED r2e_tests/test_1.py::MultipartResponseWrapperTestCase::test_next\nPASSED r2e_tests/test_1.py::MultipartResponseWrapperTestCase::test_release\nPASSED r2e_tests/test_1.py::MultipartResponseWrapperTestCase::test_release_when_stream_at_eof\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_filename\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_multiread\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_next\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_next_next\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_chunk_at_eof\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_chunk_requires_content_length\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_does_reads_boundary\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_form\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_form_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_form_guess_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_form_while_closed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json_compressed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json_guess_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json_while_closed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_multiline\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_respects_content_length\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text_compressed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text_guess_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text_while_closed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_encoding_deflate\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_encoding_gzip\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_encoding_identity\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_encoding_unknown\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_transfer_encoding_base64\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_transfer_encoding_quoted_printable\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_transfer_encoding_unknown\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_release\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_release_release\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_release_respects_content_length\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_bad_boundary\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_dispatch\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_dispatch_bodypart\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_dispatch_custom_multipart_reader\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_dispatch_multipart\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_emit_next\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_from_response\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_invalid_boundary\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_read_chunk_doesnt_breaks_reader\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_release\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_release_next\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_release_release\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_release_without_read_the_last_object\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_second_next_releases_previous_object\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_autoset_content_disposition\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_filename\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_guess_content_length\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_guess_filename\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_bytes\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_default\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_form\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_form_dict\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_io\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_io_chunk\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_io_with_content_transfer_encoding_base64\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_json\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_multipart\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_str\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_str_custom_encoding\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_encoding_deflate\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_encoding_gzip\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_encoding_identity\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_encoding_unknown\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_transfer_encoding_base64\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_transfer_encoding_quote_printable\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_transfer_encoding_unknown\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_set_content_disposition\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_set_content_disposition_bad_param\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_set_content_disposition_bad_type\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_form\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_json\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_json_overrides_content_type\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_part\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_with_headers\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_bad_boundary\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_default_headers\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_default_subtype\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_iter_parts\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_serialize\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_with\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attabspath\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attabspathwin\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attandinline\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attandinline2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attbrokenquotedfn\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attbrokenquotedfn2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attbrokenquotedfn3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attcdate\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attconfusedparam\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attemptyparam\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnboth\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnboth2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnboth3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnbrokentoken\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnbrokentokeniso\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnbrokentokenutf\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncont\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontenc\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontlz\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontnc\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontord\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontqs\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnconts1\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmdate\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdelim\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdelim2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdelim3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdisposition\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdisposition2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdisposition3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdisposition4\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmultinstances\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attnewandfn\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attonly\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attonlyquoted\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attonlyucase\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attreversed\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attrfc2047quoted\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attrfc2047token\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwith2filenames\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilename\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilename25\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilename35\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenamenq\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenamenqs\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenamenqws\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenameucase\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenamews1\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifnescapedchar\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifnescapedquote\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfilenameandextparam\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfilenameandextparamescaped\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfilenamepctandiso\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231abspathdisguised\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231dpct\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231noc\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231quot\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231quot2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231singleqmissing\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231utf8\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231utf8comp\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231ws1\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231ws2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231ws3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfnrawpctenca\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfnrawpctencaq\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfnrawpctenclong\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfntokensq\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfnusingpct\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithisofn2231iso\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithisofnplain\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithnamepct\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithtokfncommanq\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithutf8fnplain\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_bad_continuous_param\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_dispext\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_dispextbadfn\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_doublecolon\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_emptydisposition\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlonly\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlonlyquoted\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlwithasciifilename\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlwithasciifilenamepdf\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlwithfnattach\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_parse_empty\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfnboth\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfnboth3\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncont\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncontenc\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncontlz\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncontnc\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncontqs\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfnconts1\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attrfc2047quoted\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_filename\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_filename_ext\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_no_filename\nSKIPPED [1] r2e_tests/test_1.py:1298: should raise decoding error: %E4 is invalid for utf-8\nSKIPPED [1] r2e_tests/test_1.py:1346: urllib.parse.unquote is tolerate to standalone % chars\nSKIPPED [1] r2e_tests/test_1.py:1354: urllib.parse.unquote is tolerate to standalone % chars\nSKIPPED [1] r2e_tests/test_1.py:1290: should raise decoding error: %82 is invalid for latin1\nSKIPPED [1] r2e_tests/test_1.py:963: need more smart parser which respects quoted text\nFAILED r2e_tests/test_1.py::BodyPartWriterTestCase::test_guess_content_type\n=================== 1 failed, 186 passed, 5 skipped in 0.84s ===================\n",
    "new_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d3fa32eb39057636c7e6246619a3680244061049/.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_d3fa32eb39057636c7e6246619a3680244061049\nplugins: mock-3.14.0, asyncio-0.25.1, cov-6.0.0\nasyncio: mode=strict, asyncio_default_fixture_loop_scope=None\ncollected 192 items\n\nr2e_tests/test_1.py ..............................................F..... [ 27%]\n...F.................................................................... [ 64%]\n.....................sss.....s............s.........................     [100%]\n\n=================================== FAILURES ===================================\n_________ MultipartReaderTestCase.test_read_chunk_doesnt_breaks_reader _________\n\nself = <r2e_tests.test_1.MultipartReaderTestCase testMethod=test_read_chunk_doesnt_breaks_reader>\n\n    def test_read_chunk_doesnt_breaks_reader(self):\n        reader = aiohttp.multipart.MultipartReader(\n            {CONTENT_TYPE: 'multipart/related;boundary=\":\"'},\n            Stream(b'--:\\r\\n'\n                   b'Content-Length: 4\\r\\n\\r\\n'\n                   b'test'\n                   b'\\r\\n--:\\r\\n'\n                   b'Content-Length: 6\\r\\n\\r\\n'\n                   b'passed'\n                   b'\\r\\n--:--'))\n        while True:\n>           part = yield from reader.next()\n\nr2e_tests/test_1.py:541: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \naiohttp/multipart.py:447: in next\n    yield from self._read_boundary()\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <aiohttp.multipart.MultipartReader object at 0x7427763f1880>\n\n    @asyncio.coroutine\n    def _read_boundary(self):\n        chunk = (yield from self._readline()).rstrip()\n        if chunk == self._boundary:\n            pass\n        elif chunk == self._boundary + b'--':\n            self._at_eof = True\n        else:\n>           raise ValueError('Invalid boundary %r, expected %r'\n                             % (chunk, self._boundary))\nE           ValueError: Invalid boundary b'', expected b'--:'\n\naiohttp/multipart.py:513: ValueError\n________________ BodyPartWriterTestCase.test_guess_content_type ________________\n\nself = <r2e_tests.test_1.BodyPartWriterTestCase testMethod=test_guess_content_type>\n\n    def test_guess_content_type(self):\n        default = 'application/octet-stream'\n        self.assertEqual(default, self.part._guess_content_type(b'foo'))\n        self.assertEqual('text/plain; charset=utf-8',\n                         self.part._guess_content_type('foo'))\n    \n        here = os.path.dirname(__file__)\n        filename = os.path.join(here, 'software_development_in_picture.jpg')\n    \n>       with open(filename, 'rb') as f:\nE       FileNotFoundError: [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d3fa32eb39057636c7e6246619a3680244061049/r2e_tests/software_development_in_picture.jpg'\n\nr2e_tests/test_1.py:578: FileNotFoundError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::MultipartResponseWrapperTestCase::test_at_eof\nPASSED r2e_tests/test_1.py::MultipartResponseWrapperTestCase::test_next\nPASSED r2e_tests/test_1.py::MultipartResponseWrapperTestCase::test_release\nPASSED r2e_tests/test_1.py::MultipartResponseWrapperTestCase::test_release_when_stream_at_eof\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_filename\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_multiread\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_next\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_next_next\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_chunk_at_eof\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_chunk_requires_content_length\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_does_reads_boundary\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_form\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_form_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_form_guess_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_form_while_closed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json_compressed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json_guess_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_json_while_closed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_multiline\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_respects_content_length\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text_compressed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text_guess_encoding\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_text_while_closed\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_encoding_deflate\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_encoding_gzip\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_encoding_identity\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_encoding_unknown\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_transfer_encoding_base64\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_transfer_encoding_quoted_printable\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_read_with_content_transfer_encoding_unknown\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_release\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_release_release\nPASSED r2e_tests/test_1.py::PartReaderTestCase::test_release_respects_content_length\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_bad_boundary\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_dispatch\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_dispatch_bodypart\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_dispatch_custom_multipart_reader\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_dispatch_multipart\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_emit_next\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_from_response\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_invalid_boundary\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_release\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_release_next\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_release_release\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_release_without_read_the_last_object\nPASSED r2e_tests/test_1.py::MultipartReaderTestCase::test_second_next_releases_previous_object\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_autoset_content_disposition\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_filename\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_guess_content_length\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_guess_filename\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_bytes\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_default\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_form\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_form_dict\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_io\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_io_chunk\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_io_with_content_transfer_encoding_base64\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_json\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_multipart\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_str\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_str_custom_encoding\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_encoding_deflate\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_encoding_gzip\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_encoding_identity\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_encoding_unknown\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_transfer_encoding_base64\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_transfer_encoding_quote_printable\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_serialize_with_content_transfer_encoding_unknown\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_set_content_disposition\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_set_content_disposition_bad_param\nPASSED r2e_tests/test_1.py::BodyPartWriterTestCase::test_set_content_disposition_bad_type\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_form\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_json\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_json_overrides_content_type\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_part\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_append_with_headers\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_bad_boundary\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_default_headers\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_default_subtype\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_iter_parts\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_serialize\nPASSED r2e_tests/test_1.py::MultipartWriterTestCase::test_with\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attabspath\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attabspathwin\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attandinline\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attandinline2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attbrokenquotedfn\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attbrokenquotedfn2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attbrokenquotedfn3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attcdate\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attconfusedparam\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attemptyparam\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnboth\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnboth2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnboth3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnbrokentoken\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnbrokentokeniso\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnbrokentokenutf\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncont\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontenc\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontlz\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontnc\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontord\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfncontqs\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attfnconts1\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmdate\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdelim\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdelim2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdelim3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdisposition\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdisposition2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdisposition3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmissingdisposition4\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attmultinstances\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attnewandfn\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attonly\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attonlyquoted\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attonlyucase\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attreversed\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attrfc2047quoted\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attrfc2047token\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwith2filenames\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilename\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilename25\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilename35\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenamenq\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenamenqs\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenamenqws\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenameucase\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifilenamews1\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifnescapedchar\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithasciifnescapedquote\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfilenameandextparam\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfilenameandextparamescaped\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfilenamepctandiso\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231abspathdisguised\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231dpct\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231noc\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231quot\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231quot2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231singleqmissing\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231utf8\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231utf8comp\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231ws1\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231ws2\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfn2231ws3\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfnrawpctenca\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfnrawpctencaq\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfnrawpctenclong\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfntokensq\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithfnusingpct\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithisofn2231iso\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithisofnplain\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithnamepct\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithtokfncommanq\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_attwithutf8fnplain\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_bad_continuous_param\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_dispext\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_dispextbadfn\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_doublecolon\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_emptydisposition\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlonly\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlonlyquoted\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlwithasciifilename\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlwithasciifilenamepdf\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_inlwithfnattach\nPASSED r2e_tests/test_1.py::ParseContentDispositionTestCase::test_parse_empty\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfnboth\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfnboth3\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncont\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncontenc\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncontlz\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncontnc\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfncontqs\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attfnconts1\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_attrfc2047quoted\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_filename\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_filename_ext\nPASSED r2e_tests/test_1.py::ContentDispositionFilenameTestCase::test_no_filename\nSKIPPED [1] r2e_tests/test_1.py:1298: should raise decoding error: %E4 is invalid for utf-8\nSKIPPED [1] r2e_tests/test_1.py:1346: urllib.parse.unquote is tolerate to standalone % chars\nSKIPPED [1] r2e_tests/test_1.py:1354: urllib.parse.unquote is tolerate to standalone % chars\nSKIPPED [1] r2e_tests/test_1.py:1290: should raise decoding error: %82 is invalid for latin1\nSKIPPED [1] r2e_tests/test_1.py:963: need more smart parser which respects quoted text\nFAILED r2e_tests/test_1.py::MultipartReaderTestCase::test_read_chunk_doesnt_breaks_reader\nFAILED r2e_tests/test_1.py::BodyPartWriterTestCase::test_guess_content_type\n=================== 2 failed, 185 passed, 5 skipped in 0.53s ===================\n",
    "old_commit_res_stderr": "/home/gcpuser/buckets/local_repoeval_bucket/repos/aiohttp_d3fa32eb39057636c7e6246619a3680244061049/.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"
}
CHANGES.txt aiohttp/multipart.py tests/test_multipart.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** MultipartReader Fails to Read Trailing Characters, Causing Boundary Parsing Error

**Description:**
When processing multipart payloads, the `MultipartReader` fails to correctly handle boundaries if the `read_chunk` method does not read all data, specifically missing the trailing `\r\n` characters. This results in an assertion error indicating a malformed multipart payload.

**Example Code:**
```python
reader = aiohttp.multipart.MultipartReader(
    {'Content-Type': 'multipart/related;boundary=":"'},
    Stream(b'--:\r\nContent-Length: 4\r\n\r\ntest\r\n--:\r\nContent-Length: 6\r\n\r\npassed\r\n--:--')
)

while True:
    part = yield from reader.next()
    if part is None:
        break
    while not part.at_eof():
        yield from part.read_chunk(3)
```

**Expected Behavior:**
The `MultipartReader` should successfully parse all boundaries and read the complete data without raising any errors.

**Actual Behavior:**
A `ValueError` is raised with the message: 
```
ValueError: Invalid boundary b'', expected b'--:'
```
This indicates that the reader did not correctly read all the necessary trailing characters, leading to a failure in boundary detection.

[/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/multipart.py
import asyncio
import binascii
import base64
import json
import io
import mimetypes
import os
import re
import uuid
import warnings
import zlib
from urllib.parse import quote, unquote, urlencode, parse_qsl
from collections import Mapping, Sequence

from .helpers import parse_mimetype
from .multidict import CIMultiDict
from .protocol import HttpParser
from .hdrs import (
    CONTENT_DISPOSITION,
    CONTENT_ENCODING,
    CONTENT_LENGTH,
    CONTENT_TRANSFER_ENCODING,
    CONTENT_TYPE
)


__all__ = ('MultipartReader', 'MultipartWriter',
           'BodyPartReader', 'BodyPartWriter',
           'BadContentDispositionHeader', 'BadContentDispositionParam',
           'parse_content_disposition', 'content_disposition_filename')


CHAR = set(chr(i) for i in range(0, 128))
CTL = set(chr(i) for i in range(0, 32)) | {chr(127), }
SEPARATORS = {'(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']',
              '?', '=', '{', '}', ' ', chr(9)}
TOKEN = CHAR ^ CTL ^ SEPARATORS


class BadContentDispositionHeader(RuntimeWarning):
    pass


class BadContentDispositionParam(RuntimeWarning):
    pass


def parse_content_disposition(header):
    def is_token(string):
        return string and TOKEN >= set(string)

    def is_quoted(string):
        return string[0] == string[-1] == '"'

    def is_rfc5987(string):
        return is_token(string) and string.count("'") == 2

    def is_extended_param(string):
        return string.endswith('*')

    def is_continuous_param(string):
        pos = string.find('*') + 1
        if not pos:
            return False
        substring = string[pos:-1] if string.endswith('*') else string[pos:]
        return substring.isdigit()

    def unescape(text, *, chars=''.join(map(re.escape, CHAR))):
        return re.sub('\\\\([{}])'.format(chars), '\\1', text)

    if not header:
        return None, {}

    disptype, *parts = header.split(';')
    if not is_token(disptype):
        warnings.warn(BadContentDispositionHeader(header))
        return None, {}

    params = {}
    for item in parts:
        if '=' not in item:
            warnings.warn(BadContentDispositionHeader(header))
            return None, {}

        key, value = item.split('=', 1)
        key = key.lower().strip()
        value = value.lstrip()

        if key in params:
            warnings.warn(BadContentDispositionHeader(header))
            return None, {}

        if not is_token(key):
            warnings.warn(BadContentDispositionParam(item))
            continue

        elif is_continuous_param(key):
            if is_quoted(value):
                value = unescape(value[1:-1])
            elif not is_token(value):
                warnings.warn(BadContentDispositionParam(item))
                continue

        elif is_extended_param(key):
            if is_rfc5987(value):
                encoding, _, value = value.split("'", 2)
                encoding = encoding or 'utf-8'
            else:
                warnings.warn(BadContentDispositionParam(item))
                continue

            try:
                value = unquote(value, encoding, 'strict')
            except UnicodeDecodeError:  # pragma: nocover
                warnings.warn(BadContentDispositionParam(item))
                continue

        else:
            if is_quoted(value):
                value = unescape(value[1:-1].lstrip('\\/'))
            elif not is_token(value):
                warnings.warn(BadContentDispositionHeader(header))
                return None, {}

        params[key] = value

    return disptype.lower(), params


def content_disposition_filename(params):
    if not params:
        return None
    elif 'filename*' in params:
        return params['filename*']
    elif 'filename' in params:
        return params['filename']
    else:
        parts = []
        fnparams = sorted((key, value)
                          for key, value in params.items()
                          if key.startswith('filename*'))
        for num, (key, value) in enumerate(fnparams):
            _, tail = key.split('*', 1)
            if tail.endswith('*'):
                tail = tail[:-1]
            if tail == str(num):
                parts.append(value)
            else:
                break
        if not parts:
            return None
        value = ''.join(parts)
        if "'" in value:
            encoding, _, value = value.split("'", 2)
            encoding = encoding or 'utf-8'
            return unquote(value, encoding, 'strict')
        return value


class MultipartResponseWrapper(object):
    """Wrapper around the :class:`MultipartBodyReader` to take care about
    underlying connection and close it when it needs in."""

    def __init__(self, resp, stream):
        self.resp = resp
        self.stream = stream

    def at_eof(self):
        """Returns ``True`` when all response data had been read.

        :rtype: bool
        """
        return self.resp.content.at_eof()

    @asyncio.coroutine
    def next(self):
        """Emits next multipart reader object."""
        item = yield from self.stream.next()
        if self.stream.at_eof():
            yield from self.release()
        return item

    @asyncio.coroutine
    def release(self):
        """Releases the connection gracefully, reading all the content
        to the void."""
        yield from self.resp.release()


class BodyPartReader(object):
    """Multipart reader for single body part."""

    chunk_size = 8192

    def __init__(self, boundary, headers, content):
        self.headers = headers
        self._boundary = boundary
        self._content = content
        self._at_eof = False
        length = self.headers.get(CONTENT_LENGTH, None)
        self._length = int(length) if length is not None else None
        self._read_bytes = 0
        self._unread = []

    @asyncio.coroutine
    def next(self):
        item = yield from self.read()
        if not item:
            return None
        return item

    @asyncio.coroutine
    def read(self, *, decode=False):
        """Reads body part data.

        :param bool decode: Decodes data following by encoding
                            method from `Content-Encoding` header. If it missed
                            data remains untouched

        :rtype: bytearray
        """
        if self._at_eof:
            return b''
        data = bytearray()
        if self._length is None:
            while not self._at_eof:
                data.extend((yield from self.readline()))
        else:
            while not self._at_eof:
                data.extend((yield from self.read_chunk(self.chunk_size)))
            assert b'\r\n' == (yield from self._content.readline()), \
                'reader did not read all the data or it is malformed'
        if decode:
            return self.decode(data)
        return data

    @asyncio.coroutine
    def read_chunk(self, size=chunk_size):
        """Reads body part content chunk of the specified size.
        The body part must has `Content-Length` header with proper value.

        :param int size: chunk size

        :rtype: bytearray
        """
        if self._at_eof:
            return b''
        assert self._length is not None, \
            'Content-Length required for chunked read'
        chunk_size = min(size, self._length - self._read_bytes)
        chunk = yield from self._content.read(chunk_size)
        self._read_bytes += chunk_size
        if self._read_bytes == self._length:
            self._at_eof = True
        return chunk

    @asyncio.coroutine
    def readline(self):
        """Reads body part by line by line.

        :rtype: bytearray
        """
        if self._at_eof:
            return b''
        line = yield from self._content.readline()
        if line.startswith(self._boundary):
            # the very last boundary may not come with \r\n,
            # so set single rules for everyone
            sline = line.rstrip(b'\r\n')
            boundary = self._boundary
            last_boundary = self._boundary + b'--'
            # ensure that we read exactly the boundary, not something alike
            if sline == boundary or sline == last_boundary:
                self._at_eof = True
                self._unread.append(line)
                return b''
        return line

    @asyncio.coroutine
    def release(self):
        """Lke :meth:`read`, but reads all the data to the void.

        :rtype: None
        """
        if self._at_eof:
            return
        if self._length is None:
            while not self._at_eof:
                yield from self.readline()
        else:
            while not self._at_eof:
                yield from self.read_chunk(self.chunk_size)
            assert b'\r\n' == (yield from self._content.readline())

    @asyncio.coroutine
    def text(self, *, encoding=None):
        """Lke :meth:`read`, but assumes that body part contains text data.

        :param str encoding: Custom text encoding. Overrides specified
                             in charset param of `Content-Type` header

        :rtype: str
        """
        data = yield from self.read(decode=True)
        encoding = encoding or self.get_charset(default='latin1')
        return data.decode(encoding)

    @asyncio.coroutine
    def json(self, *, encoding=None):
        """Lke :meth:`read`, but assumes that body parts contains JSON data.

        :param str encoding: Custom JSON encoding. Overrides specified
                             in charset param of `Content-Type` header
        """
        data = yield from self.read(decode=True)
        if not data:
            return None
        encoding = encoding or self.get_charset(default='utf-8')
        return json.loads(data.decode(encoding))

    @asyncio.coroutine
    def form(self, *, encoding=None):
        """Lke :meth:`read`, but assumes that body parts contains form
        urlencoded data.

        :param str encoding: Custom form encoding. Overrides specified
                             in charset param of `Content-Type` header
        """
        data = yield from self.read(decode=True)
        if not data:
            return None
        encoding = encoding or self.get_charset(default='utf-8')
        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)

    def at_eof(self):
        """Returns ``True`` if the boundary was reached or
        ``False`` otherwise.

        :rtype: bool
        """
        return self._at_eof

    def decode(self, data):
        """Decodes data according the specified `Content-Encoding`
        or `Content-Transfer-Encoding` headers value.

        Supports ``gzip``, ``deflate`` and ``identity`` encodings for
        `Content-Encoding` header.

        Supports ``base64``, ``quoted-printable`` encodings for
        `Content-Transfer-Encoding` header.

        :param bytearray data: Data to decode.

        :raises: :exc:`RuntimeError` - if encoding is unknown.

        :rtype: bytes
        """
        if CONTENT_TRANSFER_ENCODING in self.headers:
            data = self._decode_content_transfer(data)
        if CONTENT_ENCODING in self.headers:
            return self._decode_content(data)
        return data

    def _decode_content(self, data):
        encoding = self.headers[CONTENT_ENCODING].lower()

        if encoding == 'deflate':
            return zlib.decompress(data, -zlib.MAX_WBITS)
        elif encoding == 'gzip':
            return zlib.decompress(data, 16 + zlib.MAX_WBITS)
        elif encoding == 'identity':
            return data
        else:
            raise RuntimeError('unknown content encoding: {}'.format(encoding))

    def _decode_content_transfer(self, data):
        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()

        if encoding == 'base64':
            return base64.b64decode(data)
        elif encoding == 'quoted-printable':
            return binascii.a2b_qp(data)
        else:
            raise RuntimeError('unknown content transfer encoding: {}'
                               ''.format(encoding))

    def get_charset(self, default=None):
        """Returns charset parameter from ``Content-Type`` header or default.
        """
        ctype = self.headers.get(CONTENT_TYPE, '')
        *_, params = parse_mimetype(ctype)
        return params.get('charset', default)

    @property
    def filename(self):
        """Returns filename specified in Content-Disposition header or ``None``
        if missed or header is malformed."""
        _, params = parse_content_disposition(
            self.headers.get(CONTENT_DISPOSITION))
        return content_disposition_filename(params)


class MultipartReader(object):
    """Multipart body reader."""

    #: Response wrapper, used when multipart readers constructs from response.
    response_wrapper_cls = MultipartResponseWrapper
    #: Multipart reader class, used to handle multipart/* body parts.
    #: None points to type(self)
    multipart_reader_cls = None
    #: Body part reader class for non multipart/* content types.
    part_reader_cls = BodyPartReader

    def __init__(self, headers, content):
        self.headers = headers
        self._boundary = ('--' + self._get_boundary()).encode()
        self._content = content
        self._last_part = None
        self._at_eof = False
        self._unread = []

    @classmethod
    def from_response(cls, response):
        """Constructs reader instance from HTTP response.

        :param response: :class:`~aiohttp.client.ClientResponse` instance
        """
        obj = cls.response_wrapper_cls(response, cls(response.headers,
                                                     response.content))
        return obj

    def at_eof(self):
        """Returns ``True`` if the final boundary was reached or
        ``False`` otherwise.

        :rtype: bool
        """
        return self._at_eof

    @asyncio.coroutine
    def next(self):
        """Emits the next multipart body part."""
        if self._at_eof:
            return
        yield from self._maybe_release_last_part()
        yield from self._read_boundary()
        if self._at_eof:  # we just read the last boundary, nothing to do there
            return
        self._last_part = yield from self.fetch_next_part()
        return self._last_part

    @asyncio.coroutine
    def release(self):
        """Reads all the body parts to the void till the final boundary."""
        while not self._at_eof:
            item = yield from self.next()
            if item is None:
                break
            yield from item.release()

    @asyncio.coroutine
    def fetch_next_part(self):
        """Returns the next body part reader."""
        headers = yield from self._read_headers()
        return self._get_part_reader(headers)

    def _get_part_reader(self, headers):
        """Dispatches the response by the `Content-Type` header, returning
        suitable reader instance.

        :param dict headers: Response headers
        """
        ctype = headers.get(CONTENT_TYPE, '')
        mtype, *_ = parse_mimetype(ctype)
        if mtype == 'multipart':
            if self.multipart_reader_cls is None:
                return type(self)(headers, self._content)
            return self.multipart_reader_cls(headers, self._content)
        else:
            return self.part_reader_cls(self._boundary, headers, self._content)

    def _get_boundary(self):
        mtype, *_, params = parse_mimetype(self.headers[CONTENT_TYPE])

        assert mtype == 'multipart', 'multipart/* content type expected'

        if 'boundary' not in params:
            raise ValueError('boundary missed for Content-Type: %s'
                             % self.headers[CONTENT_TYPE])

        boundary = params['boundary']
        if len(boundary) > 70:
            raise ValueError('boundary %r is too long (70 chars max)'
                             % boundary)

        return boundary

    @asyncio.coroutine
    def _readline(self):
        if self._unread:
            return self._unread.pop()
        return (yield from self._content.readline())

    @asyncio.coroutine
    def _read_boundary(self):
        chunk = (yield from self._readline()).rstrip()
        if chunk == self._boundary:
            pass
        elif chunk == self._boundary + b'--':
            self._at_eof = True
        else:
            raise ValueError('Invalid boundary %r, expected %r'
                             % (chunk, self._boundary))

    @asyncio.coroutine
    def _read_headers(self):
        lines = ['']
        while True:
            chunk = yield from self._content.readline()
            chunk = chunk.decode().strip()
            lines.append(chunk)
            if not chunk:
                break
        parser = HttpParser()
        headers, *_ = parser.parse_headers(lines)
        return headers

    @asyncio.coroutine
    def _maybe_release_last_part(self):
        """Ensures that the last read body part is read completely."""
        if self._last_part is not None:
            if not self._last_part.at_eof():
                yield from self._last_part.release()
            self._unread.extend(self._last_part._unread)
            self._last_part = None


class BodyPartWriter(object):
    """Multipart writer for single body part."""

    def __init__(self, obj, headers=None, *, chunk_size=8192):
        if headers is None:
            headers = CIMultiDict()
        elif not isinstance(headers, CIMultiDict):
            headers = CIMultiDict(headers)

        self.obj = obj
        self.headers = headers
        self._chunk_size = chunk_size
        self._fill_headers_with_defaults()

        self._serialize_map = {
            bytes: self._serialize_bytes,
            str: self._serialize_str,
            io.IOBase: self._serialize_io,
            MultipartWriter: self._serialize_multipart,
            ('application', 'json'): self._serialize_json,
            ('application', 'x-www-form-urlencoded'): self._serialize_form
        }

    def _fill_headers_with_defaults(self):
        if CONTENT_TYPE not in self.headers:
            content_type = self._guess_content_type(self.obj)
            if content_type is not None:
                self.headers[CONTENT_TYPE] = content_type

        if CONTENT_LENGTH not in self.headers:
            content_length = self._guess_content_length(self.obj)
            if content_length is not None:
                self.headers[CONTENT_LENGTH] = str(content_length)

        if CONTENT_DISPOSITION not in self.headers:
            filename = self._guess_filename(self.obj)
            if filename is not None:
                self.set_content_disposition('attachment', filename=filename)

    def _guess_content_length(self, obj):
        if isinstance(obj, bytes):
            return len(obj)
        elif isinstance(obj, str):
            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
            charset = params.get('charset', 'us-ascii')
            return len(obj.encode(charset))
        elif isinstance(obj, io.StringIO):
            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
            charset = params.get('charset', 'us-ascii')
            return len(obj.getvalue().encode(charset)) - obj.tell()
        elif isinstance(obj, io.BytesIO):
            return len(obj.getvalue()) - obj.tell()
        elif isinstance(obj, io.IOBase):
            try:
                return os.fstat(obj.fileno()).st_size - obj.tell()
            except (AttributeError, OSError):
                return None
        else:
            return None

    def _guess_content_type(self, obj, default='application/octet-stream'):
        if hasattr(obj, 'name'):
            name = getattr(obj, 'name')
            return mimetypes.guess_type(name)[0]
        elif isinstance(obj, (str, io.StringIO)):
            return 'text/plain; charset=utf-8'
        else:
            return default

    def _guess_filename(self, obj):
        if isinstance(obj, io.IOBase):
            name = getattr(obj, 'name', None)
            if name is not None:
                return os.path.basename(name)

    def serialize(self):
        """Yields byte chunks for body part."""

        has_encoding = (
            CONTENT_ENCODING in self.headers
            and self.headers[CONTENT_ENCODING] != 'identity'
            or CONTENT_TRANSFER_ENCODING in self.headers
        )
        if has_encoding:
            # since we're following streaming approach which doesn't assumes
            # any intermediate buffers, we cannot calculate real content length
            # with the specified content encoding scheme. So, instead of lying
            # about content length and cause reading issues, we have to strip
            # this information.
            self.headers.pop(CONTENT_LENGTH, None)

        if self.headers:
            yield b'\r\n'.join(
                b': '.join(map(lambda i: i.encode('latin1'), item))
                for item in self.headers.items()
            )
        yield b'\r\n\r\n'
        yield from self._maybe_encode_stream(self._serialize_obj())
        yield b'\r\n'

    def _serialize_obj(self):
        obj = self.obj
        mtype, stype, *_ = parse_mimetype(self.headers.get(CONTENT_TYPE))
        serializer = self._serialize_map.get((mtype, stype))
        if serializer is not None:
            return serializer(obj)

        for key in self._serialize_map:
            if not isinstance(key, tuple) and isinstance(obj, key):
                return self._serialize_map[key](obj)
        return self._serialize_default(obj)

    def _serialize_bytes(self, obj):
        yield obj

    def _serialize_str(self, obj):
        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
        yield obj.encode(params.get('charset', 'us-ascii'))

    def _serialize_io(self, obj):
        while True:
            chunk = obj.read(self._chunk_size)
            if not chunk:
                break
            if isinstance(chunk, str):
                yield from self._serialize_str(chunk)
            else:
                yield from self._serialize_bytes(chunk)

    def _serialize_multipart(self, obj):
        yield from obj.serialize()

    def _serialize_json(self, obj):
        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
        yield json.dumps(obj).encode(params.get('charset', 'utf-8'))

    def _serialize_form(self, obj):
        if isinstance(obj, Mapping):
            obj = list(obj.items())
        return self._serialize_str(urlencode(obj, doseq=True))

    def _serialize_default(self, obj):
        raise TypeError('unknown body part type %r' % type(obj))

    def _maybe_encode_stream(self, stream):
        if CONTENT_ENCODING in self.headers:
            stream = self._apply_content_encoding(stream)
        if CONTENT_TRANSFER_ENCODING in self.headers:
            stream = self._apply_content_transfer_encoding(stream)
        yield from stream

    def _apply_content_encoding(self, stream):
        encoding = self.headers[CONTENT_ENCODING].lower()
        if encoding == 'identity':
            yield from stream
        elif encoding in ('deflate', 'gzip'):
            zlib_mode = (16 + zlib.MAX_WBITS
                         if encoding == 'gzip' else
                         -zlib.MAX_WBITS)
            zcomp = zlib.compressobj(wbits=zlib_mode)
            for chunk in stream:
                yield zcomp.compress(chunk)
            else:
                yield zcomp.flush()
        else:
            raise RuntimeError('unknown content encoding: {}'
                               ''.format(encoding))

    def _apply_content_transfer_encoding(self, stream):
        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()
        if encoding == 'base64':
            buffer = bytearray()
            while True:
                if buffer:
                    div, mod = divmod(len(buffer), 3)
                    chunk, buffer = buffer[:div * 3], buffer[div * 3:]
                    if chunk:
                        yield base64.b64encode(chunk)
                chunk = next(stream, None)
                if not chunk:
                    if buffer:
                        yield base64.b64encode(buffer[:])
                    return
                buffer.extend(chunk)
        elif encoding == 'quoted-printable':
            for chunk in stream:
                yield binascii.b2a_qp(chunk)
        else:
            raise RuntimeError('unknown content transfer encoding: {}'
                               ''.format(encoding))

    def set_content_disposition(self, disptype, **params):
        """Sets ``Content-Disposition`` header.

        :param str disptype: Disposition type: inline, attachment, form-data.
                            Should be valid extension token (see RFC 2183)
        :param dict params: Disposition params
        """
        if not disptype or not (TOKEN > set(disptype)):
            raise ValueError('bad content disposition type {!r}'
                             ''.format(disptype))
        value = disptype
        if params:
            lparams = []
            for key, val in params.items():
                if not key or not (TOKEN > set(key)):
                    raise ValueError('bad content disposition parameter'
                                     ' {!r}={!r}'.format(key, val))
                qval = quote(val, '')
                if key == 'filename':
                    lparams.append((key, '"%s"' % qval))
                    lparams.append(('filename*', "utf-8''" + qval))
                else:
                    lparams.append((key, "%s" % qval))
            sparams = '; '.join('='.join(pair) for pair in lparams)
            value = '; '.join((value, sparams))
        self.headers[CONTENT_DISPOSITION] = value

    @property
    def filename(self):
        """Returns filename specified in Content-Disposition header or ``None``
        if missed."""
        _, params = parse_content_disposition(
            self.headers.get(CONTENT_DISPOSITION))
        return content_disposition_filename(params)


class MultipartWriter(object):
    """Multipart body writer."""

    #: Body part reader class for non multipart/* content types.
    part_writer_cls = BodyPartWriter

    def __init__(self, subtype='mixed', boundary=None):
        boundary = boundary if boundary is not None else uuid.uuid4().hex
        try:
            boundary.encode('us-ascii')
        except UnicodeEncodeError:
            raise ValueError('boundary should contains ASCII only chars')
        self.headers = CIMultiDict()
        self.headers[CONTENT_TYPE] = 'multipart/{}; boundary="{}"'.format(
            subtype, boundary
        )
        self.parts = []

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

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

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

    @property
    def boundary(self):
        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
        return params['boundary'].encode('us-ascii')

    def append(self, obj, headers=None):
        """Adds a new body part to multipart writer."""
        if isinstance(obj, self.part_writer_cls):
            if headers:
                obj.headers.update(headers)
            self.parts.append(obj)
        else:
            if not headers:
                headers = CIMultiDict()
            self.parts.append(self.part_writer_cls(obj, headers))
        return self.parts[-1]

    def append_json(self, obj, headers=None):
        """Helper to append JSON part."""
        if not headers:
            headers = CIMultiDict()
        headers[CONTENT_TYPE] = 'application/json'
        return self.append(obj, headers)

    def append_form(self, obj, headers=None):
        """Helper to append form urlencoded part."""
        if not headers:
            headers = CIMultiDict()
        headers[CONTENT_TYPE] = 'application/x-www-form-urlencoded'
        assert isinstance(obj, (Sequence, Mapping))
        return self.append(obj, headers)

    def serialize(self):
        """Yields multipart byte chunks."""
        if not self.parts:
            yield b''
            return

        for part in self.parts:
            yield b'--' + self.boundary + b'\r\n'
            yield from part.serialize()
        else:
            yield b'--' + self.boundary + b'--\r\n'

        yield b''

```
--- 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:** MultipartReader Fails to Read Trailing Characters, Causing Boundary Parsing Error

**Description:**
When processing multipart payloads, the `MultipartReader` fails to correctly handle boundaries if the `read_chunk` method does not read all data, specifically missing the trailing `\r\n` characters. This results in an assertion error indicating a malformed multipart payload.

**Example Code:**
```python
reader = aiohttp.multipart.MultipartReader(
    {'Content-Type': 'multipart/related;boundary=":"'},
    Stream(b'--:\r\nContent-Length: 4\r\n\r\ntest\r\n--:\r\nContent-Length: 6\r\n\r\npassed\r\n--:--')
)

while True:
    part = yield from reader.next()
    if part is None:
        break
    while not part.at_eof():
        yield from part.read_chunk(3)
```

**Expected Behavior:**
The `MultipartReader` should successfully parse all boundaries and read the complete data without raising any errors.

**Actual Behavior:**
A `ValueError` is raised with the message: 
```
ValueError: Invalid boundary b'', expected b'--:'
```
This indicates that the reader did not correctly read all the necessary trailing characters, leading to a failure in boundary detection.

[/ISSUE]
{
    "MultipartResponseWrapperTestCase.test_at_eof": "PASSED",
    "MultipartResponseWrapperTestCase.test_next": "PASSED",
    "MultipartResponseWrapperTestCase.test_release": "PASSED",
    "MultipartResponseWrapperTestCase.test_release_when_stream_at_eof": "PASSED",
    "PartReaderTestCase.test_filename": "PASSED",
    "PartReaderTestCase.test_multiread": "PASSED",
    "PartReaderTestCase.test_next": "PASSED",
    "PartReaderTestCase.test_next_next": "PASSED",
    "PartReaderTestCase.test_read": "PASSED",
    "PartReaderTestCase.test_read_chunk_at_eof": "PASSED",
    "PartReaderTestCase.test_read_chunk_requires_content_length": "PASSED",
    "PartReaderTestCase.test_read_does_reads_boundary": "PASSED",
    "PartReaderTestCase.test_read_form": "PASSED",
    "PartReaderTestCase.test_read_form_encoding": "PASSED",
    "PartReaderTestCase.test_read_form_guess_encoding": "PASSED",
    "PartReaderTestCase.test_read_form_while_closed": "PASSED",
    "PartReaderTestCase.test_read_json": "PASSED",
    "PartReaderTestCase.test_read_json_compressed": "PASSED",
    "PartReaderTestCase.test_read_json_encoding": "PASSED",
    "PartReaderTestCase.test_read_json_guess_encoding": "PASSED",
    "PartReaderTestCase.test_read_json_while_closed": "PASSED",
    "PartReaderTestCase.test_read_multiline": "PASSED",
    "PartReaderTestCase.test_read_respects_content_length": "PASSED",
    "PartReaderTestCase.test_read_text": "PASSED",
    "PartReaderTestCase.test_read_text_compressed": "PASSED",
    "PartReaderTestCase.test_read_text_encoding": "PASSED",
    "PartReaderTestCase.test_read_text_guess_encoding": "PASSED",
    "PartReaderTestCase.test_read_text_while_closed": "PASSED",
    "PartReaderTestCase.test_read_with_content_encoding_deflate": "PASSED",
    "PartReaderTestCase.test_read_with_content_encoding_gzip": "PASSED",
    "PartReaderTestCase.test_read_with_content_encoding_identity": "PASSED",
    "PartReaderTestCase.test_read_with_content_encoding_unknown": "PASSED",
    "PartReaderTestCase.test_read_with_content_transfer_encoding_base64": "PASSED",
    "PartReaderTestCase.test_read_with_content_transfer_encoding_quoted_printable": "PASSED",
    "PartReaderTestCase.test_read_with_content_transfer_encoding_unknown": "PASSED",
    "PartReaderTestCase.test_release": "PASSED",
    "PartReaderTestCase.test_release_release": "PASSED",
    "PartReaderTestCase.test_release_respects_content_length": "PASSED",
    "MultipartReaderTestCase.test_bad_boundary": "PASSED",
    "MultipartReaderTestCase.test_dispatch": "PASSED",
    "MultipartReaderTestCase.test_dispatch_bodypart": "PASSED",
    "MultipartReaderTestCase.test_dispatch_custom_multipart_reader": "PASSED",
    "MultipartReaderTestCase.test_dispatch_multipart": "PASSED",
    "MultipartReaderTestCase.test_emit_next": "PASSED",
    "MultipartReaderTestCase.test_from_response": "PASSED",
    "MultipartReaderTestCase.test_invalid_boundary": "PASSED",
    "MultipartReaderTestCase.test_read_chunk_doesnt_breaks_reader": "PASSED",
    "MultipartReaderTestCase.test_release": "PASSED",
    "MultipartReaderTestCase.test_release_next": "PASSED",
    "MultipartReaderTestCase.test_release_release": "PASSED",
    "MultipartReaderTestCase.test_release_without_read_the_last_object": "PASSED",
    "MultipartReaderTestCase.test_second_next_releases_previous_object": "PASSED",
    "BodyPartWriterTestCase.test_autoset_content_disposition": "PASSED",
    "BodyPartWriterTestCase.test_filename": "PASSED",
    "BodyPartWriterTestCase.test_guess_content_length": "PASSED",
    "BodyPartWriterTestCase.test_guess_filename": "PASSED",
    "BodyPartWriterTestCase.test_serialize_bytes": "PASSED",
    "BodyPartWriterTestCase.test_serialize_default": "PASSED",
    "BodyPartWriterTestCase.test_serialize_form": "PASSED",
    "BodyPartWriterTestCase.test_serialize_form_dict": "PASSED",
    "BodyPartWriterTestCase.test_serialize_io": "PASSED",
    "BodyPartWriterTestCase.test_serialize_io_chunk": "PASSED",
    "BodyPartWriterTestCase.test_serialize_io_with_content_transfer_encoding_base64": "PASSED",
    "BodyPartWriterTestCase.test_serialize_json": "PASSED",
    "BodyPartWriterTestCase.test_serialize_multipart": "PASSED",
    "BodyPartWriterTestCase.test_serialize_str": "PASSED",
    "BodyPartWriterTestCase.test_serialize_str_custom_encoding": "PASSED",
    "BodyPartWriterTestCase.test_serialize_with_content_encoding_deflate": "PASSED",
    "BodyPartWriterTestCase.test_serialize_with_content_encoding_gzip": "PASSED",
    "BodyPartWriterTestCase.test_serialize_with_content_encoding_identity": "PASSED",
    "BodyPartWriterTestCase.test_serialize_with_content_encoding_unknown": "PASSED",
    "BodyPartWriterTestCase.test_serialize_with_content_transfer_encoding_base64": "PASSED",
    "BodyPartWriterTestCase.test_serialize_with_content_transfer_encoding_quote_printable": "PASSED",
    "BodyPartWriterTestCase.test_serialize_with_content_transfer_encoding_unknown": "PASSED",
    "BodyPartWriterTestCase.test_set_content_disposition": "PASSED",
    "BodyPartWriterTestCase.test_set_content_disposition_bad_param": "PASSED",
    "BodyPartWriterTestCase.test_set_content_disposition_bad_type": "PASSED",
    "MultipartWriterTestCase.test_append": "PASSED",
    "MultipartWriterTestCase.test_append_form": "PASSED",
    "MultipartWriterTestCase.test_append_json": "PASSED",
    "MultipartWriterTestCase.test_append_json_overrides_content_type": "PASSED",
    "MultipartWriterTestCase.test_append_part": "PASSED",
    "MultipartWriterTestCase.test_append_with_headers": "PASSED",
    "MultipartWriterTestCase.test_bad_boundary": "PASSED",
    "MultipartWriterTestCase.test_default_headers": "PASSED",
    "MultipartWriterTestCase.test_default_subtype": "PASSED",
    "MultipartWriterTestCase.test_iter_parts": "PASSED",
    "MultipartWriterTestCase.test_serialize": "PASSED",
    "MultipartWriterTestCase.test_with": "PASSED",
    "ParseContentDispositionTestCase.test_attabspath": "PASSED",
    "ParseContentDispositionTestCase.test_attabspathwin": "PASSED",
    "ParseContentDispositionTestCase.test_attandinline": "PASSED",
    "ParseContentDispositionTestCase.test_attandinline2": "PASSED",
    "ParseContentDispositionTestCase.test_attbrokenquotedfn": "PASSED",
    "ParseContentDispositionTestCase.test_attbrokenquotedfn2": "PASSED",
    "ParseContentDispositionTestCase.test_attbrokenquotedfn3": "PASSED",
    "ParseContentDispositionTestCase.test_attcdate": "PASSED",
    "ParseContentDispositionTestCase.test_attconfusedparam": "PASSED",
    "ParseContentDispositionTestCase.test_attemptyparam": "PASSED",
    "ParseContentDispositionTestCase.test_attfnboth": "PASSED",
    "ParseContentDispositionTestCase.test_attfnboth2": "PASSED",
    "ParseContentDispositionTestCase.test_attfnboth3": "PASSED",
    "ParseContentDispositionTestCase.test_attfnbrokentoken": "PASSED",
    "ParseContentDispositionTestCase.test_attfnbrokentokeniso": "PASSED",
    "ParseContentDispositionTestCase.test_attfnbrokentokenutf": "PASSED",
    "ParseContentDispositionTestCase.test_attfncont": "PASSED",
    "ParseContentDispositionTestCase.test_attfncontenc": "PASSED",
    "ParseContentDispositionTestCase.test_attfncontlz": "PASSED",
    "ParseContentDispositionTestCase.test_attfncontnc": "PASSED",
    "ParseContentDispositionTestCase.test_attfncontord": "PASSED",
    "ParseContentDispositionTestCase.test_attfncontqs": "PASSED",
    "ParseContentDispositionTestCase.test_attfnconts1": "PASSED",
    "ParseContentDispositionTestCase.test_attmdate": "PASSED",
    "ParseContentDispositionTestCase.test_attmissingdelim": "PASSED",
    "ParseContentDispositionTestCase.test_attmissingdelim2": "PASSED",
    "ParseContentDispositionTestCase.test_attmissingdelim3": "PASSED",
    "ParseContentDispositionTestCase.test_attmissingdisposition": "PASSED",
    "ParseContentDispositionTestCase.test_attmissingdisposition2": "PASSED",
    "ParseContentDispositionTestCase.test_attmissingdisposition3": "PASSED",
    "ParseContentDispositionTestCase.test_attmissingdisposition4": "PASSED",
    "ParseContentDispositionTestCase.test_attmultinstances": "PASSED",
    "ParseContentDispositionTestCase.test_attnewandfn": "PASSED",
    "ParseContentDispositionTestCase.test_attonly": "PASSED",
    "ParseContentDispositionTestCase.test_attonlyquoted": "PASSED",
    "ParseContentDispositionTestCase.test_attonlyucase": "PASSED",
    "ParseContentDispositionTestCase.test_attreversed": "PASSED",
    "ParseContentDispositionTestCase.test_attrfc2047quoted": "PASSED",
    "ParseContentDispositionTestCase.test_attrfc2047token": "PASSED",
    "ParseContentDispositionTestCase.test_attwith2filenames": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifilename": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifilename25": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifilename35": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifilenamenq": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifilenamenqs": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifilenamenqws": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifilenameucase": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifilenamews1": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifnescapedchar": "PASSED",
    "ParseContentDispositionTestCase.test_attwithasciifnescapedquote": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfilenameandextparam": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfilenameandextparamescaped": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfilenamepctandiso": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231abspathdisguised": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231dpct": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231noc": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231quot": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231quot2": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231singleqmissing": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231utf8": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231utf8comp": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231ws1": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231ws2": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfn2231ws3": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfnrawpctenca": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfnrawpctencaq": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfnrawpctenclong": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfntokensq": "PASSED",
    "ParseContentDispositionTestCase.test_attwithfnusingpct": "PASSED",
    "ParseContentDispositionTestCase.test_attwithisofn2231iso": "PASSED",
    "ParseContentDispositionTestCase.test_attwithisofnplain": "PASSED",
    "ParseContentDispositionTestCase.test_attwithnamepct": "PASSED",
    "ParseContentDispositionTestCase.test_attwithtokfncommanq": "PASSED",
    "ParseContentDispositionTestCase.test_attwithutf8fnplain": "PASSED",
    "ParseContentDispositionTestCase.test_bad_continuous_param": "PASSED",
    "ParseContentDispositionTestCase.test_dispext": "PASSED",
    "ParseContentDispositionTestCase.test_dispextbadfn": "PASSED",
    "ParseContentDispositionTestCase.test_doublecolon": "PASSED",
    "ParseContentDispositionTestCase.test_emptydisposition": "PASSED",
    "ParseContentDispositionTestCase.test_inlonly": "PASSED",
    "ParseContentDispositionTestCase.test_inlonlyquoted": "PASSED",
    "ParseContentDispositionTestCase.test_inlwithasciifilename": "PASSED",
    "ParseContentDispositionTestCase.test_inlwithasciifilenamepdf": "PASSED",
    "ParseContentDispositionTestCase.test_inlwithfnattach": "PASSED",
    "ParseContentDispositionTestCase.test_parse_empty": "PASSED",
    "ContentDispositionFilenameTestCase.test_attfnboth": "PASSED",
    "ContentDispositionFilenameTestCase.test_attfnboth3": "PASSED",
    "ContentDispositionFilenameTestCase.test_attfncont": "PASSED",
    "ContentDispositionFilenameTestCase.test_attfncontenc": "PASSED",
    "ContentDispositionFilenameTestCase.test_attfncontlz": "PASSED",
    "ContentDispositionFilenameTestCase.test_attfncontnc": "PASSED",
    "ContentDispositionFilenameTestCase.test_attfncontqs": "PASSED",
    "ContentDispositionFilenameTestCase.test_attfnconts1": "PASSED",
    "ContentDispositionFilenameTestCase.test_attrfc2047quoted": "PASSED",
    "ContentDispositionFilenameTestCase.test_filename": "PASSED",
    "ContentDispositionFilenameTestCase.test_filename_ext": "PASSED",
    "ContentDispositionFilenameTestCase.test_no_filename": "PASSED",
    "BodyPartWriterTestCase.test_guess_content_type": "FAILED"
}
diff --git a/aiohttp/multipart.py b/aiohttp/multipart.py
index 7cc7e113..296c6790 100644
--- a/aiohttp/multipart.py
+++ b/aiohttp/multipart.py
@@ -228,8 +228,6 @@ class BodyPartReader(object):
         else:
             while not self._at_eof:
                 data.extend((yield from self.read_chunk(self.chunk_size)))
-            assert b'\r\n' == (yield from self._content.readline()), \
-                'reader did not read all the data or it is malformed'
         if decode:
             return self.decode(data)
         return data
@@ -252,6 +250,8 @@ class BodyPartReader(object):
         self._read_bytes += chunk_size
         if self._read_bytes == self._length:
             self._at_eof = True
+            assert b'\r\n' == (yield from self._content.readline()), \
+                'reader did not read all the data or it is malformed'
         return chunk
 
     @asyncio.coroutine
@@ -290,7 +290,6 @@ class BodyPartReader(object):
         else:
             while not self._at_eof:
                 yield from self.read_chunk(self.chunk_size)
-            assert b'\r\n' == (yield from self._content.readline())
 
     @asyncio.coroutine
     def text(self, *, encoding=None):

{"aiohttp/multipart.py": "import asyncio\nimport binascii\nimport base64\nimport json\nimport io\nimport mimetypes\nimport os\nimport re\nimport uuid\nimport warnings\nimport zlib\nfrom urllib.parse import quote, unquote, urlencode, parse_qsl\nfrom collections import Mapping, Sequence\n\nfrom .helpers import parse_mimetype\nfrom .multidict import CIMultiDict\nfrom .protocol import HttpParser\nfrom .hdrs import (\n    CONTENT_DISPOSITION,\n    CONTENT_ENCODING,\n    CONTENT_LENGTH,\n    CONTENT_TRANSFER_ENCODING,\n    CONTENT_TYPE\n)\n\n\n__all__ = ('MultipartReader', 'MultipartWriter',\n           'BodyPartReader', 'BodyPartWriter',\n           'BadContentDispositionHeader', 'BadContentDispositionParam',\n           'parse_content_disposition', 'content_disposition_filename')\n\n\nCHAR = set(chr(i) for i in range(0, 128))\nCTL = set(chr(i) for i in range(0, 32)) | {chr(127), }\nSEPARATORS = {'(', ')', '<', '>', '@', ',', ';', ':', '\\\\', '\"', '/', '[', ']',\n              '?', '=', '{', '}', ' ', chr(9)}\nTOKEN = CHAR ^ CTL ^ SEPARATORS\n\n\nclass BadContentDispositionHeader(RuntimeWarning):\n    pass\n\n\nclass BadContentDispositionParam(RuntimeWarning):\n    pass\n\n\ndef parse_content_disposition(header):\n    def is_token(string):\n        return string and TOKEN >= set(string)\n\n    def is_quoted(string):\n        return string[0] == string[-1] == '\"'\n\n    def is_rfc5987(string):\n        return is_token(string) and string.count(\"'\") == 2\n\n    def is_extended_param(string):\n        return string.endswith('*')\n\n    def is_continuous_param(string):\n        pos = string.find('*') + 1\n        if not pos:\n            return False\n        substring = string[pos:-1] if string.endswith('*') else string[pos:]\n        return substring.isdigit()\n\n    def unescape(text, *, chars=''.join(map(re.escape, CHAR))):\n        return re.sub('\\\\\\\\([{}])'.format(chars), '\\\\1', text)\n\n    if not header:\n        return None, {}\n\n    disptype, *parts = header.split(';')\n    if not is_token(disptype):\n        warnings.warn(BadContentDispositionHeader(header))\n        return None, {}\n\n    params = {}\n    for item in parts:\n        if '=' not in item:\n            warnings.warn(BadContentDispositionHeader(header))\n            return None, {}\n\n        key, value = item.split('=', 1)\n        key = key.lower().strip()\n        value = value.lstrip()\n\n        if key in params:\n            warnings.warn(BadContentDispositionHeader(header))\n            return None, {}\n\n        if not is_token(key):\n            warnings.warn(BadContentDispositionParam(item))\n            continue\n\n        elif is_continuous_param(key):\n            if is_quoted(value):\n                value = unescape(value[1:-1])\n            elif not is_token(value):\n                warnings.warn(BadContentDispositionParam(item))\n                continue\n\n        elif is_extended_param(key):\n            if is_rfc5987(value):\n                encoding, _, value = value.split(\"'\", 2)\n                encoding = encoding or 'utf-8'\n            else:\n                warnings.warn(BadContentDispositionParam(item))\n                continue\n\n            try:\n                value = unquote(value, encoding, 'strict')\n            except UnicodeDecodeError:  # pragma: nocover\n                warnings.warn(BadContentDispositionParam(item))\n                continue\n\n        else:\n            if is_quoted(value):\n                value = unescape(value[1:-1].lstrip('\\\\/'))\n            elif not is_token(value):\n                warnings.warn(BadContentDispositionHeader(header))\n                return None, {}\n\n        params[key] = value\n\n    return disptype.lower(), params\n\n\ndef content_disposition_filename(params):\n    if not params:\n        return None\n    elif 'filename*' in params:\n        return params['filename*']\n    elif 'filename' in params:\n        return params['filename']\n    else:\n        parts = []\n        fnparams = sorted((key, value)\n                          for key, value in params.items()\n                          if key.startswith('filename*'))\n        for num, (key, value) in enumerate(fnparams):\n            _, tail = key.split('*', 1)\n            if tail.endswith('*'):\n                tail = tail[:-1]\n            if tail == str(num):\n                parts.append(value)\n            else:\n                break\n        if not parts:\n            return None\n        value = ''.join(parts)\n        if \"'\" in value:\n            encoding, _, value = value.split(\"'\", 2)\n            encoding = encoding or 'utf-8'\n            return unquote(value, encoding, 'strict')\n        return value\n\n\nclass MultipartResponseWrapper(object):\n    \"\"\"Wrapper around the :class:`MultipartBodyReader` to take care about\n    underlying connection and close it when it needs in.\"\"\"\n\n    def __init__(self, resp, stream):\n        self.resp = resp\n        self.stream = stream\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` when all response data had been read.\n\n        :rtype: bool\n        \"\"\"\n        return self.resp.content.at_eof()\n\n    @asyncio.coroutine\n    def next(self):\n        \"\"\"Emits next multipart reader object.\"\"\"\n        item = yield from self.stream.next()\n        if self.stream.at_eof():\n            yield from self.release()\n        return item\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Releases the connection gracefully, reading all the content\n        to the void.\"\"\"\n        yield from self.resp.release()\n\n\nclass BodyPartReader(object):\n    \"\"\"Multipart reader for single body part.\"\"\"\n\n    chunk_size = 8192\n\n    def __init__(self, boundary, headers, content):\n        self.headers = headers\n        self._boundary = boundary\n        self._content = content\n        self._at_eof = False\n        length = self.headers.get(CONTENT_LENGTH, None)\n        self._length = int(length) if length is not None else None\n        self._read_bytes = 0\n        self._unread = []\n\n    @asyncio.coroutine\n    def next(self):\n        item = yield from self.read()\n        if not item:\n            return None\n        return item\n\n    @asyncio.coroutine\n    def read(self, *, decode=False):\n        \"\"\"Reads body part data.\n\n        :param bool decode: Decodes data following by encoding\n                            method from `Content-Encoding` header. If it missed\n                            data remains untouched\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        data = bytearray()\n        if self._length is None:\n            while not self._at_eof:\n                data.extend((yield from self.readline()))\n        else:\n            while not self._at_eof:\n                data.extend((yield from self.read_chunk(self.chunk_size)))\n            assert b'\\r\\n' == (yield from self._content.readline()), \\\n                'reader did not read all the data or it is malformed'\n        if decode:\n            return self.decode(data)\n        return data\n\n    @asyncio.coroutine\n    def read_chunk(self, size=chunk_size):\n        \"\"\"Reads body part content chunk of the specified size.\n        The body part must has `Content-Length` header with proper value.\n\n        :param int size: chunk size\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        assert self._length is not None, \\\n            'Content-Length required for chunked read'\n        chunk_size = min(size, self._length - self._read_bytes)\n        chunk = yield from self._content.read(chunk_size)\n        self._read_bytes += chunk_size\n        if self._read_bytes == self._length:\n            self._at_eof = True\n        return chunk\n\n    @asyncio.coroutine\n    def readline(self):\n        \"\"\"Reads body part by line by line.\n\n        :rtype: bytearray\n        \"\"\"\n        if self._at_eof:\n            return b''\n        line = yield from self._content.readline()\n        if line.startswith(self._boundary):\n            # the very last boundary may not come with \\r\\n,\n            # so set single rules for everyone\n            sline = line.rstrip(b'\\r\\n')\n            boundary = self._boundary\n            last_boundary = self._boundary + b'--'\n            # ensure that we read exactly the boundary, not something alike\n            if sline == boundary or sline == last_boundary:\n                self._at_eof = True\n                self._unread.append(line)\n                return b''\n        return line\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Lke :meth:`read`, but reads all the data to the void.\n\n        :rtype: None\n        \"\"\"\n        if self._at_eof:\n            return\n        if self._length is None:\n            while not self._at_eof:\n                yield from self.readline()\n        else:\n            while not self._at_eof:\n                yield from self.read_chunk(self.chunk_size)\n            assert b'\\r\\n' == (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def text(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body part contains text data.\n\n        :param str encoding: Custom text encoding. Overrides specified\n                             in charset param of `Content-Type` header\n\n        :rtype: str\n        \"\"\"\n        data = yield from self.read(decode=True)\n        encoding = encoding or self.get_charset(default='latin1')\n        return data.decode(encoding)\n\n    @asyncio.coroutine\n    def json(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains JSON data.\n\n        :param str encoding: Custom JSON encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return json.loads(data.decode(encoding))\n\n    @asyncio.coroutine\n    def form(self, *, encoding=None):\n        \"\"\"Lke :meth:`read`, but assumes that body parts contains form\n        urlencoded data.\n\n        :param str encoding: Custom form encoding. Overrides specified\n                             in charset param of `Content-Type` header\n        \"\"\"\n        data = yield from self.read(decode=True)\n        if not data:\n            return None\n        encoding = encoding or self.get_charset(default='utf-8')\n        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    def decode(self, data):\n        \"\"\"Decodes data according the specified `Content-Encoding`\n        or `Content-Transfer-Encoding` headers value.\n\n        Supports ``gzip``, ``deflate`` and ``identity`` encodings for\n        `Content-Encoding` header.\n\n        Supports ``base64``, ``quoted-printable`` encodings for\n        `Content-Transfer-Encoding` header.\n\n        :param bytearray data: Data to decode.\n\n        :raises: :exc:`RuntimeError` - if encoding is unknown.\n\n        :rtype: bytes\n        \"\"\"\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            data = self._decode_content_transfer(data)\n        if CONTENT_ENCODING in self.headers:\n            return self._decode_content(data)\n        return data\n\n    def _decode_content(self, data):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n\n        if encoding == 'deflate':\n            return zlib.decompress(data, -zlib.MAX_WBITS)\n        elif encoding == 'gzip':\n            return zlib.decompress(data, 16 + zlib.MAX_WBITS)\n        elif encoding == 'identity':\n            return data\n        else:\n            raise RuntimeError('unknown content encoding: {}'.format(encoding))\n\n    def _decode_content_transfer(self, data):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n\n        if encoding == 'base64':\n            return base64.b64decode(data)\n        elif encoding == 'quoted-printable':\n            return binascii.a2b_qp(data)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def get_charset(self, default=None):\n        \"\"\"Returns charset parameter from ``Content-Type`` header or default.\n        \"\"\"\n        ctype = self.headers.get(CONTENT_TYPE, '')\n        *_, params = parse_mimetype(ctype)\n        return params.get('charset', default)\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed or header is malformed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)\n\n\nclass MultipartReader(object):\n    \"\"\"Multipart body reader.\"\"\"\n\n    #: Response wrapper, used when multipart readers constructs from response.\n    response_wrapper_cls = MultipartResponseWrapper\n    #: Multipart reader class, used to handle multipart/* body parts.\n    #: None points to type(self)\n    multipart_reader_cls = None\n    #: Body part reader class for non multipart/* content types.\n    part_reader_cls = BodyPartReader\n\n    def __init__(self, headers, content):\n        self.headers = headers\n        self._boundary = ('--' + self._get_boundary()).encode()\n        self._content = content\n        self._last_part = None\n        self._at_eof = False\n        self._unread = []\n\n    @classmethod\n    def from_response(cls, response):\n        \"\"\"Constructs reader instance from HTTP response.\n\n        :param response: :class:`~aiohttp.client.ClientResponse` instance\n        \"\"\"\n        obj = cls.response_wrapper_cls(response, cls(response.headers,\n                                                     response.content))\n        return obj\n\n    def at_eof(self):\n        \"\"\"Returns ``True`` if the final boundary was reached or\n        ``False`` otherwise.\n\n        :rtype: bool\n        \"\"\"\n        return self._at_eof\n\n    @asyncio.coroutine\n    def next(self):\n        \"\"\"Emits the next multipart body part.\"\"\"\n        if self._at_eof:\n            return\n        yield from self._maybe_release_last_part()\n        yield from self._read_boundary()\n        if self._at_eof:  # we just read the last boundary, nothing to do there\n            return\n        self._last_part = yield from self.fetch_next_part()\n        return self._last_part\n\n    @asyncio.coroutine\n    def release(self):\n        \"\"\"Reads all the body parts to the void till the final boundary.\"\"\"\n        while not self._at_eof:\n            item = yield from self.next()\n            if item is None:\n                break\n            yield from item.release()\n\n    @asyncio.coroutine\n    def fetch_next_part(self):\n        \"\"\"Returns the next body part reader.\"\"\"\n        headers = yield from self._read_headers()\n        return self._get_part_reader(headers)\n\n    def _get_part_reader(self, headers):\n        \"\"\"Dispatches the response by the `Content-Type` header, returning\n        suitable reader instance.\n\n        :param dict headers: Response headers\n        \"\"\"\n        ctype = headers.get(CONTENT_TYPE, '')\n        mtype, *_ = parse_mimetype(ctype)\n        if mtype == 'multipart':\n            if self.multipart_reader_cls is None:\n                return type(self)(headers, self._content)\n            return self.multipart_reader_cls(headers, self._content)\n        else:\n            return self.part_reader_cls(self._boundary, headers, self._content)\n\n    def _get_boundary(self):\n        mtype, *_, params = parse_mimetype(self.headers[CONTENT_TYPE])\n\n        assert mtype == 'multipart', 'multipart/* content type expected'\n\n        if 'boundary' not in params:\n            raise ValueError('boundary missed for Content-Type: %s'\n                             % self.headers[CONTENT_TYPE])\n\n        boundary = params['boundary']\n        if len(boundary) > 70:\n            raise ValueError('boundary %r is too long (70 chars max)'\n                             % boundary)\n\n        return boundary\n\n    @asyncio.coroutine\n    def _readline(self):\n        if self._unread:\n            return self._unread.pop()\n        return (yield from self._content.readline())\n\n    @asyncio.coroutine\n    def _read_boundary(self):\n        chunk = (yield from self._readline()).rstrip()\n        if chunk == self._boundary:\n            pass\n        elif chunk == self._boundary + b'--':\n            self._at_eof = True\n        else:\n            raise ValueError('Invalid boundary %r, expected %r'\n                             % (chunk, self._boundary))\n\n    @asyncio.coroutine\n    def _read_headers(self):\n        lines = ['']\n        while True:\n            chunk = yield from self._content.readline()\n            chunk = chunk.decode().strip()\n            lines.append(chunk)\n            if not chunk:\n                break\n        parser = HttpParser()\n        headers, *_ = parser.parse_headers(lines)\n        return headers\n\n    @asyncio.coroutine\n    def _maybe_release_last_part(self):\n        \"\"\"Ensures that the last read body part is read completely.\"\"\"\n        if self._last_part is not None:\n            if not self._last_part.at_eof():\n                yield from self._last_part.release()\n            self._unread.extend(self._last_part._unread)\n            self._last_part = None\n\n\nclass BodyPartWriter(object):\n    \"\"\"Multipart writer for single body part.\"\"\"\n\n    def __init__(self, obj, headers=None, *, chunk_size=8192):\n        if headers is None:\n            headers = CIMultiDict()\n        elif not isinstance(headers, CIMultiDict):\n            headers = CIMultiDict(headers)\n\n        self.obj = obj\n        self.headers = headers\n        self._chunk_size = chunk_size\n        self._fill_headers_with_defaults()\n\n        self._serialize_map = {\n            bytes: self._serialize_bytes,\n            str: self._serialize_str,\n            io.IOBase: self._serialize_io,\n            MultipartWriter: self._serialize_multipart,\n            ('application', 'json'): self._serialize_json,\n            ('application', 'x-www-form-urlencoded'): self._serialize_form\n        }\n\n    def _fill_headers_with_defaults(self):\n        if CONTENT_TYPE not in self.headers:\n            content_type = self._guess_content_type(self.obj)\n            if content_type is not None:\n                self.headers[CONTENT_TYPE] = content_type\n\n        if CONTENT_LENGTH not in self.headers:\n            content_length = self._guess_content_length(self.obj)\n            if content_length is not None:\n                self.headers[CONTENT_LENGTH] = str(content_length)\n\n        if CONTENT_DISPOSITION not in self.headers:\n            filename = self._guess_filename(self.obj)\n            if filename is not None:\n                self.set_content_disposition('attachment', filename=filename)\n\n    def _guess_content_length(self, obj):\n        if isinstance(obj, bytes):\n            return len(obj)\n        elif isinstance(obj, str):\n            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n            charset = params.get('charset', 'us-ascii')\n            return len(obj.encode(charset))\n        elif isinstance(obj, io.StringIO):\n            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n            charset = params.get('charset', 'us-ascii')\n            return len(obj.getvalue().encode(charset)) - obj.tell()\n        elif isinstance(obj, io.BytesIO):\n            return len(obj.getvalue()) - obj.tell()\n        elif isinstance(obj, io.IOBase):\n            try:\n                return os.fstat(obj.fileno()).st_size - obj.tell()\n            except (AttributeError, OSError):\n                return None\n        else:\n            return None\n\n    def _guess_content_type(self, obj, default='application/octet-stream'):\n        if hasattr(obj, 'name'):\n            name = getattr(obj, 'name')\n            return mimetypes.guess_type(name)[0]\n        elif isinstance(obj, (str, io.StringIO)):\n            return 'text/plain; charset=utf-8'\n        else:\n            return default\n\n    def _guess_filename(self, obj):\n        if isinstance(obj, io.IOBase):\n            name = getattr(obj, 'name', None)\n            if name is not None:\n                return os.path.basename(name)\n\n    def serialize(self):\n        \"\"\"Yields byte chunks for body part.\"\"\"\n\n        has_encoding = (\n            CONTENT_ENCODING in self.headers\n            and self.headers[CONTENT_ENCODING] != 'identity'\n            or CONTENT_TRANSFER_ENCODING in self.headers\n        )\n        if has_encoding:\n            # since we're following streaming approach which doesn't assumes\n            # any intermediate buffers, we cannot calculate real content length\n            # with the specified content encoding scheme. So, instead of lying\n            # about content length and cause reading issues, we have to strip\n            # this information.\n            self.headers.pop(CONTENT_LENGTH, None)\n\n        if self.headers:\n            yield b'\\r\\n'.join(\n                b': '.join(map(lambda i: i.encode('latin1'), item))\n                for item in self.headers.items()\n            )\n        yield b'\\r\\n\\r\\n'\n        yield from self._maybe_encode_stream(self._serialize_obj())\n        yield b'\\r\\n'\n\n    def _serialize_obj(self):\n        obj = self.obj\n        mtype, stype, *_ = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        serializer = self._serialize_map.get((mtype, stype))\n        if serializer is not None:\n            return serializer(obj)\n\n        for key in self._serialize_map:\n            if not isinstance(key, tuple) and isinstance(obj, key):\n                return self._serialize_map[key](obj)\n        return self._serialize_default(obj)\n\n    def _serialize_bytes(self, obj):\n        yield obj\n\n    def _serialize_str(self, obj):\n        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        yield obj.encode(params.get('charset', 'us-ascii'))\n\n    def _serialize_io(self, obj):\n        while True:\n            chunk = obj.read(self._chunk_size)\n            if not chunk:\n                break\n            if isinstance(chunk, str):\n                yield from self._serialize_str(chunk)\n            else:\n                yield from self._serialize_bytes(chunk)\n\n    def _serialize_multipart(self, obj):\n        yield from obj.serialize()\n\n    def _serialize_json(self, obj):\n        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        yield json.dumps(obj).encode(params.get('charset', 'utf-8'))\n\n    def _serialize_form(self, obj):\n        if isinstance(obj, Mapping):\n            obj = list(obj.items())\n        return self._serialize_str(urlencode(obj, doseq=True))\n\n    def _serialize_default(self, obj):\n        raise TypeError('unknown body part type %r' % type(obj))\n\n    def _maybe_encode_stream(self, stream):\n        if CONTENT_ENCODING in self.headers:\n            stream = self._apply_content_encoding(stream)\n        if CONTENT_TRANSFER_ENCODING in self.headers:\n            stream = self._apply_content_transfer_encoding(stream)\n        yield from stream\n\n    def _apply_content_encoding(self, stream):\n        encoding = self.headers[CONTENT_ENCODING].lower()\n        if encoding == 'identity':\n            yield from stream\n        elif encoding in ('deflate', 'gzip'):\n            zlib_mode = (16 + zlib.MAX_WBITS\n                         if encoding == 'gzip' else\n                         -zlib.MAX_WBITS)\n            zcomp = zlib.compressobj(wbits=zlib_mode)\n            for chunk in stream:\n                yield zcomp.compress(chunk)\n            else:\n                yield zcomp.flush()\n        else:\n            raise RuntimeError('unknown content encoding: {}'\n                               ''.format(encoding))\n\n    def _apply_content_transfer_encoding(self, stream):\n        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()\n        if encoding == 'base64':\n            buffer = bytearray()\n            while True:\n                if buffer:\n                    div, mod = divmod(len(buffer), 3)\n                    chunk, buffer = buffer[:div * 3], buffer[div * 3:]\n                    if chunk:\n                        yield base64.b64encode(chunk)\n                chunk = next(stream, None)\n                if not chunk:\n                    if buffer:\n                        yield base64.b64encode(buffer[:])\n                    return\n                buffer.extend(chunk)\n        elif encoding == 'quoted-printable':\n            for chunk in stream:\n                yield binascii.b2a_qp(chunk)\n        else:\n            raise RuntimeError('unknown content transfer encoding: {}'\n                               ''.format(encoding))\n\n    def set_content_disposition(self, disptype, **params):\n        \"\"\"Sets ``Content-Disposition`` header.\n\n        :param str disptype: Disposition type: inline, attachment, form-data.\n                            Should be valid extension token (see RFC 2183)\n        :param dict params: Disposition params\n        \"\"\"\n        if not disptype or not (TOKEN > set(disptype)):\n            raise ValueError('bad content disposition type {!r}'\n                             ''.format(disptype))\n        value = disptype\n        if params:\n            lparams = []\n            for key, val in params.items():\n                if not key or not (TOKEN > set(key)):\n                    raise ValueError('bad content disposition parameter'\n                                     ' {!r}={!r}'.format(key, val))\n                qval = quote(val, '')\n                if key == 'filename':\n                    lparams.append((key, '\"%s\"' % qval))\n                    lparams.append(('filename*', \"utf-8''\" + qval))\n                else:\n                    lparams.append((key, \"%s\" % qval))\n            sparams = '; '.join('='.join(pair) for pair in lparams)\n            value = '; '.join((value, sparams))\n        self.headers[CONTENT_DISPOSITION] = value\n\n    @property\n    def filename(self):\n        \"\"\"Returns filename specified in Content-Disposition header or ``None``\n        if missed.\"\"\"\n        _, params = parse_content_disposition(\n            self.headers.get(CONTENT_DISPOSITION))\n        return content_disposition_filename(params)\n\n\nclass MultipartWriter(object):\n    \"\"\"Multipart body writer.\"\"\"\n\n    #: Body part reader class for non multipart/* content types.\n    part_writer_cls = BodyPartWriter\n\n    def __init__(self, subtype='mixed', boundary=None):\n        boundary = boundary if boundary is not None else uuid.uuid4().hex\n        try:\n            boundary.encode('us-ascii')\n        except UnicodeEncodeError:\n            raise ValueError('boundary should contains ASCII only chars')\n        self.headers = CIMultiDict()\n        self.headers[CONTENT_TYPE] = 'multipart/{}; boundary=\"{}\"'.format(\n            subtype, boundary\n        )\n        self.parts = []\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        pass\n\n    def __iter__(self):\n        return iter(self.parts)\n\n    def __len__(self):\n        return len(self.parts)\n\n    @property\n    def boundary(self):\n        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))\n        return params['boundary'].encode('us-ascii')\n\n    def append(self, obj, headers=None):\n        \"\"\"Adds a new body part to multipart writer.\"\"\"\n        if isinstance(obj, self.part_writer_cls):\n            if headers:\n                obj.headers.update(headers)\n            self.parts.append(obj)\n        else:\n            if not headers:\n                headers = CIMultiDict()\n            self.parts.append(self.part_writer_cls(obj, headers))\n        return self.parts[-1]\n\n    def append_json(self, obj, headers=None):\n        \"\"\"Helper to append JSON part.\"\"\"\n        if not headers:\n            headers = CIMultiDict()\n        headers[CONTENT_TYPE] = 'application/json'\n        return self.append(obj, headers)\n\n    def append_form(self, obj, headers=None):\n        \"\"\"Helper to append form urlencoded part.\"\"\"\n        if not headers:\n            headers = CIMultiDict()\n        headers[CONTENT_TYPE] = 'application/x-www-form-urlencoded'\n        assert isinstance(obj, (Sequence, Mapping))\n        return self.append(obj, headers)\n\n    def serialize(self):\n        \"\"\"Yields multipart byte chunks.\"\"\"\n        if not self.parts:\n            yield b''\n            return\n\n        for part in self.parts:\n            yield b'--' + self.boundary + b'\\r\\n'\n            yield from part.serialize()\n        else:\n            yield b'--' + self.boundary + b'--\\r\\n'\n\n        yield b''\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:** MultipartReader Fails to Read Trailing Characters, Causing Boundary Parsing Error

**Description:**
When processing multipart payloads, the `MultipartReader` fails to correctly handle boundaries if the `read_chunk` method does not read all data, specifically missing the trailing `\r\n` characters. This results in an assertion error indicating a malformed multipart payload.

**Example Code:**
```python
reader = aiohttp.multipart.MultipartReader(
    {'Content-Type': 'multipart/related;boundary=":"'},
    Stream(b'--:\r\nContent-Length: 4\r\n\r\ntest\r\n--:\r\nContent-Length: 6\r\n\r\npassed\r\n--:--')
)

while True:
    part = yield from reader.next()
    if part is None:
        break
    while not part.at_eof():
        yield from part.read_chunk(3)
```

**Expected Behavior:**
The `MultipartReader` should successfully parse all boundaries and read the complete data without raising any errors.

**Actual Behavior:**
A `ValueError` is raised with the message: 
```
ValueError: Invalid boundary b'', expected b'--:'
```
This indicates that the reader did not correctly read all the necessary trailing characters, leading to a failure in boundary detection.

[/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/multipart.py
import asyncio
import binascii
import base64
import json
import io
import mimetypes
import os
import re
import uuid
import warnings
import zlib
from urllib.parse import quote, unquote, urlencode, parse_qsl
from collections import Mapping, Sequence

from .helpers import parse_mimetype
from .multidict import CIMultiDict
from .protocol import HttpParser
from .hdrs import (
    CONTENT_DISPOSITION,
    CONTENT_ENCODING,
    CONTENT_LENGTH,
    CONTENT_TRANSFER_ENCODING,
    CONTENT_TYPE
)


__all__ = ('MultipartReader', 'MultipartWriter',
           'BodyPartReader', 'BodyPartWriter',
           'BadContentDispositionHeader', 'BadContentDispositionParam',
           'parse_content_disposition', 'content_disposition_filename')


CHAR = set(chr(i) for i in range(0, 128))
CTL = set(chr(i) for i in range(0, 32)) | {chr(127), }
SEPARATORS = {'(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']',
              '?', '=', '{', '}', ' ', chr(9)}
TOKEN = CHAR ^ CTL ^ SEPARATORS


class BadContentDispositionHeader(RuntimeWarning):
    pass


class BadContentDispositionParam(RuntimeWarning):
    pass


def parse_content_disposition(header):
    def is_token(string):
        return string and TOKEN >= set(string)

    def is_quoted(string):
        return string[0] == string[-1] == '"'

    def is_rfc5987(string):
        return is_token(string) and string.count("'") == 2

    def is_extended_param(string):
        return string.endswith('*')

    def is_continuous_param(string):
        pos = string.find('*') + 1
        if not pos:
            return False
        substring = string[pos:-1] if string.endswith('*') else string[pos:]
        return substring.isdigit()

    def unescape(text, *, chars=''.join(map(re.escape, CHAR))):
        return re.sub('\\\\([{}])'.format(chars), '\\1', text)

    if not header:
        return None, {}

    disptype, *parts = header.split(';')
    if not is_token(disptype):
        warnings.warn(BadContentDispositionHeader(header))
        return None, {}

    params = {}
    for item in parts:
        if '=' not in item:
            warnings.warn(BadContentDispositionHeader(header))
            return None, {}

        key, value = item.split('=', 1)
        key = key.lower().strip()
        value = value.lstrip()

        if key in params:
            warnings.warn(BadContentDispositionHeader(header))
            return None, {}

        if not is_token(key):
            warnings.warn(BadContentDispositionParam(item))
            continue

        elif is_continuous_param(key):
            if is_quoted(value):
                value = unescape(value[1:-1])
            elif not is_token(value):
                warnings.warn(BadContentDispositionParam(item))
                continue

        elif is_extended_param(key):
            if is_rfc5987(value):
                encoding, _, value = value.split("'", 2)
                encoding = encoding or 'utf-8'
            else:
                warnings.warn(BadContentDispositionParam(item))
                continue

            try:
                value = unquote(value, encoding, 'strict')
            except UnicodeDecodeError:  # pragma: nocover
                warnings.warn(BadContentDispositionParam(item))
                continue

        else:
            if is_quoted(value):
                value = unescape(value[1:-1].lstrip('\\/'))
            elif not is_token(value):
                warnings.warn(BadContentDispositionHeader(header))
                return None, {}

        params[key] = value

    return disptype.lower(), params


def content_disposition_filename(params):
    if not params:
        return None
    elif 'filename*' in params:
        return params['filename*']
    elif 'filename' in params:
        return params['filename']
    else:
        parts = []
        fnparams = sorted((key, value)
                          for key, value in params.items()
                          if key.startswith('filename*'))
        for num, (key, value) in enumerate(fnparams):
            _, tail = key.split('*', 1)
            if tail.endswith('*'):
                tail = tail[:-1]
            if tail == str(num):
                parts.append(value)
            else:
                break
        if not parts:
            return None
        value = ''.join(parts)
        if "'" in value:
            encoding, _, value = value.split("'", 2)
            encoding = encoding or 'utf-8'
            return unquote(value, encoding, 'strict')
        return value


class MultipartResponseWrapper(object):
    """Wrapper around the :class:`MultipartBodyReader` to take care about
    underlying connection and close it when it needs in."""

    def __init__(self, resp, stream):
        self.resp = resp
        self.stream = stream

    def at_eof(self):
        """Returns ``True`` when all response data had been read.

        :rtype: bool
        """
        return self.resp.content.at_eof()

    @asyncio.coroutine
    def next(self):
        """Emits next multipart reader object."""
        item = yield from self.stream.next()
        if self.stream.at_eof():
            yield from self.release()
        return item

    @asyncio.coroutine
    def release(self):
        """Releases the connection gracefully, reading all the content
        to the void."""
        yield from self.resp.release()


class BodyPartReader(object):
    """Multipart reader for single body part."""

    chunk_size = 8192

    def __init__(self, boundary, headers, content):
        self.headers = headers
        self._boundary = boundary
        self._content = content
        self._at_eof = False
        length = self.headers.get(CONTENT_LENGTH, None)
        self._length = int(length) if length is not None else None
        self._read_bytes = 0
        self._unread = []

    @asyncio.coroutine
    def next(self):
        item = yield from self.read()
        if not item:
            return None
        return item

    @asyncio.coroutine
    def read(self, *, decode=False):
        """Reads body part data.

        :param bool decode: Decodes data following by encoding
                            method from `Content-Encoding` header. If it missed
                            data remains untouched

        :rtype: bytearray
        """
        if self._at_eof:
            return b''
        data = bytearray()
        if self._length is None:
            while not self._at_eof:
                data.extend((yield from self.readline()))
        else:
            while not self._at_eof:
                data.extend((yield from self.read_chunk(self.chunk_size)))
            assert b'\r\n' == (yield from self._content.readline()), \
                'reader did not read all the data or it is malformed'
        if decode:
            return self.decode(data)
        return data

    @asyncio.coroutine
    def read_chunk(self, size=chunk_size):
        """Reads body part content chunk of the specified size.
        The body part must has `Content-Length` header with proper value.

        :param int size: chunk size

        :rtype: bytearray
        """
        if self._at_eof:
            return b''
        assert self._length is not None, \
            'Content-Length required for chunked read'
        chunk_size = min(size, self._length - self._read_bytes)
        chunk = yield from self._content.read(chunk_size)
        self._read_bytes += chunk_size
        if self._read_bytes == self._length:
            self._at_eof = True
        return chunk

    @asyncio.coroutine
    def readline(self):
        """Reads body part by line by line.

        :rtype: bytearray
        """
        if self._at_eof:
            return b''
        line = yield from self._content.readline()
        if line.startswith(self._boundary):
            # the very last boundary may not come with \r\n,
            # so set single rules for everyone
            sline = line.rstrip(b'\r\n')
            boundary = self._boundary
            last_boundary = self._boundary + b'--'
            # ensure that we read exactly the boundary, not something alike
            if sline == boundary or sline == last_boundary:
                self._at_eof = True
                self._unread.append(line)
                return b''
        return line

    @asyncio.coroutine
    def release(self):
        """Lke :meth:`read`, but reads all the data to the void.

        :rtype: None
        """
        if self._at_eof:
            return
        if self._length is None:
            while not self._at_eof:
                yield from self.readline()
        else:
            while not self._at_eof:
                yield from self.read_chunk(self.chunk_size)
            assert b'\r\n' == (yield from self._content.readline())

    @asyncio.coroutine
    def text(self, *, encoding=None):
        """Lke :meth:`read`, but assumes that body part contains text data.

        :param str encoding: Custom text encoding. Overrides specified
                             in charset param of `Content-Type` header

        :rtype: str
        """
        data = yield from self.read(decode=True)
        encoding = encoding or self.get_charset(default='latin1')
        return data.decode(encoding)

    @asyncio.coroutine
    def json(self, *, encoding=None):
        """Lke :meth:`read`, but assumes that body parts contains JSON data.

        :param str encoding: Custom JSON encoding. Overrides specified
                             in charset param of `Content-Type` header
        """
        data = yield from self.read(decode=True)
        if not data:
            return None
        encoding = encoding or self.get_charset(default='utf-8')
        return json.loads(data.decode(encoding))

    @asyncio.coroutine
    def form(self, *, encoding=None):
        """Lke :meth:`read`, but assumes that body parts contains form
        urlencoded data.

        :param str encoding: Custom form encoding. Overrides specified
                             in charset param of `Content-Type` header
        """
        data = yield from self.read(decode=True)
        if not data:
            return None
        encoding = encoding or self.get_charset(default='utf-8')
        return parse_qsl(data.rstrip().decode(encoding), encoding=encoding)

    def at_eof(self):
        """Returns ``True`` if the boundary was reached or
        ``False`` otherwise.

        :rtype: bool
        """
        return self._at_eof

    def decode(self, data):
        """Decodes data according the specified `Content-Encoding`
        or `Content-Transfer-Encoding` headers value.

        Supports ``gzip``, ``deflate`` and ``identity`` encodings for
        `Content-Encoding` header.

        Supports ``base64``, ``quoted-printable`` encodings for
        `Content-Transfer-Encoding` header.

        :param bytearray data: Data to decode.

        :raises: :exc:`RuntimeError` - if encoding is unknown.

        :rtype: bytes
        """
        if CONTENT_TRANSFER_ENCODING in self.headers:
            data = self._decode_content_transfer(data)
        if CONTENT_ENCODING in self.headers:
            return self._decode_content(data)
        return data

    def _decode_content(self, data):
        encoding = self.headers[CONTENT_ENCODING].lower()

        if encoding == 'deflate':
            return zlib.decompress(data, -zlib.MAX_WBITS)
        elif encoding == 'gzip':
            return zlib.decompress(data, 16 + zlib.MAX_WBITS)
        elif encoding == 'identity':
            return data
        else:
            raise RuntimeError('unknown content encoding: {}'.format(encoding))

    def _decode_content_transfer(self, data):
        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()

        if encoding == 'base64':
            return base64.b64decode(data)
        elif encoding == 'quoted-printable':
            return binascii.a2b_qp(data)
        else:
            raise RuntimeError('unknown content transfer encoding: {}'
                               ''.format(encoding))

    def get_charset(self, default=None):
        """Returns charset parameter from ``Content-Type`` header or default.
        """
        ctype = self.headers.get(CONTENT_TYPE, '')
        *_, params = parse_mimetype(ctype)
        return params.get('charset', default)

    @property
    def filename(self):
        """Returns filename specified in Content-Disposition header or ``None``
        if missed or header is malformed."""
        _, params = parse_content_disposition(
            self.headers.get(CONTENT_DISPOSITION))
        return content_disposition_filename(params)


class MultipartReader(object):
    """Multipart body reader."""

    #: Response wrapper, used when multipart readers constructs from response.
    response_wrapper_cls = MultipartResponseWrapper
    #: Multipart reader class, used to handle multipart/* body parts.
    #: None points to type(self)
    multipart_reader_cls = None
    #: Body part reader class for non multipart/* content types.
    part_reader_cls = BodyPartReader

    def __init__(self, headers, content):
        self.headers = headers
        self._boundary = ('--' + self._get_boundary()).encode()
        self._content = content
        self._last_part = None
        self._at_eof = False
        self._unread = []

    @classmethod
    def from_response(cls, response):
        """Constructs reader instance from HTTP response.

        :param response: :class:`~aiohttp.client.ClientResponse` instance
        """
        obj = cls.response_wrapper_cls(response, cls(response.headers,
                                                     response.content))
        return obj

    def at_eof(self):
        """Returns ``True`` if the final boundary was reached or
        ``False`` otherwise.

        :rtype: bool
        """
        return self._at_eof

    @asyncio.coroutine
    def next(self):
        """Emits the next multipart body part."""
        if self._at_eof:
            return
        yield from self._maybe_release_last_part()
        yield from self._read_boundary()
        if self._at_eof:  # we just read the last boundary, nothing to do there
            return
        self._last_part = yield from self.fetch_next_part()
        return self._last_part

    @asyncio.coroutine
    def release(self):
        """Reads all the body parts to the void till the final boundary."""
        while not self._at_eof:
            item = yield from self.next()
            if item is None:
                break
            yield from item.release()

    @asyncio.coroutine
    def fetch_next_part(self):
        """Returns the next body part reader."""
        headers = yield from self._read_headers()
        return self._get_part_reader(headers)

    def _get_part_reader(self, headers):
        """Dispatches the response by the `Content-Type` header, returning
        suitable reader instance.

        :param dict headers: Response headers
        """
        ctype = headers.get(CONTENT_TYPE, '')
        mtype, *_ = parse_mimetype(ctype)
        if mtype == 'multipart':
            if self.multipart_reader_cls is None:
                return type(self)(headers, self._content)
            return self.multipart_reader_cls(headers, self._content)
        else:
            return self.part_reader_cls(self._boundary, headers, self._content)

    def _get_boundary(self):
        mtype, *_, params = parse_mimetype(self.headers[CONTENT_TYPE])

        assert mtype == 'multipart', 'multipart/* content type expected'

        if 'boundary' not in params:
            raise ValueError('boundary missed for Content-Type: %s'
                             % self.headers[CONTENT_TYPE])

        boundary = params['boundary']
        if len(boundary) > 70:
            raise ValueError('boundary %r is too long (70 chars max)'
                             % boundary)

        return boundary

    @asyncio.coroutine
    def _readline(self):
        if self._unread:
            return self._unread.pop()
        return (yield from self._content.readline())

    @asyncio.coroutine
    def _read_boundary(self):
        chunk = (yield from self._readline()).rstrip()
        if chunk == self._boundary:
            pass
        elif chunk == self._boundary + b'--':
            self._at_eof = True
        else:
            raise ValueError('Invalid boundary %r, expected %r'
                             % (chunk, self._boundary))

    @asyncio.coroutine
    def _read_headers(self):
        lines = ['']
        while True:
            chunk = yield from self._content.readline()
            chunk = chunk.decode().strip()
            lines.append(chunk)
            if not chunk:
                break
        parser = HttpParser()
        headers, *_ = parser.parse_headers(lines)
        return headers

    @asyncio.coroutine
    def _maybe_release_last_part(self):
        """Ensures that the last read body part is read completely."""
        if self._last_part is not None:
            if not self._last_part.at_eof():
                yield from self._last_part.release()
            self._unread.extend(self._last_part._unread)
            self._last_part = None


class BodyPartWriter(object):
    """Multipart writer for single body part."""

    def __init__(self, obj, headers=None, *, chunk_size=8192):
        if headers is None:
            headers = CIMultiDict()
        elif not isinstance(headers, CIMultiDict):
            headers = CIMultiDict(headers)

        self.obj = obj
        self.headers = headers
        self._chunk_size = chunk_size
        self._fill_headers_with_defaults()

        self._serialize_map = {
            bytes: self._serialize_bytes,
            str: self._serialize_str,
            io.IOBase: self._serialize_io,
            MultipartWriter: self._serialize_multipart,
            ('application', 'json'): self._serialize_json,
            ('application', 'x-www-form-urlencoded'): self._serialize_form
        }

    def _fill_headers_with_defaults(self):
        if CONTENT_TYPE not in self.headers:
            content_type = self._guess_content_type(self.obj)
            if content_type is not None:
                self.headers[CONTENT_TYPE] = content_type

        if CONTENT_LENGTH not in self.headers:
            content_length = self._guess_content_length(self.obj)
            if content_length is not None:
                self.headers[CONTENT_LENGTH] = str(content_length)

        if CONTENT_DISPOSITION not in self.headers:
            filename = self._guess_filename(self.obj)
            if filename is not None:
                self.set_content_disposition('attachment', filename=filename)

    def _guess_content_length(self, obj):
        if isinstance(obj, bytes):
            return len(obj)
        elif isinstance(obj, str):
            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
            charset = params.get('charset', 'us-ascii')
            return len(obj.encode(charset))
        elif isinstance(obj, io.StringIO):
            *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
            charset = params.get('charset', 'us-ascii')
            return len(obj.getvalue().encode(charset)) - obj.tell()
        elif isinstance(obj, io.BytesIO):
            return len(obj.getvalue()) - obj.tell()
        elif isinstance(obj, io.IOBase):
            try:
                return os.fstat(obj.fileno()).st_size - obj.tell()
            except (AttributeError, OSError):
                return None
        else:
            return None

    def _guess_content_type(self, obj, default='application/octet-stream'):
        if hasattr(obj, 'name'):
            name = getattr(obj, 'name')
            return mimetypes.guess_type(name)[0]
        elif isinstance(obj, (str, io.StringIO)):
            return 'text/plain; charset=utf-8'
        else:
            return default

    def _guess_filename(self, obj):
        if isinstance(obj, io.IOBase):
            name = getattr(obj, 'name', None)
            if name is not None:
                return os.path.basename(name)

    def serialize(self):
        """Yields byte chunks for body part."""

        has_encoding = (
            CONTENT_ENCODING in self.headers
            and self.headers[CONTENT_ENCODING] != 'identity'
            or CONTENT_TRANSFER_ENCODING in self.headers
        )
        if has_encoding:
            # since we're following streaming approach which doesn't assumes
            # any intermediate buffers, we cannot calculate real content length
            # with the specified content encoding scheme. So, instead of lying
            # about content length and cause reading issues, we have to strip
            # this information.
            self.headers.pop(CONTENT_LENGTH, None)

        if self.headers:
            yield b'\r\n'.join(
                b': '.join(map(lambda i: i.encode('latin1'), item))
                for item in self.headers.items()
            )
        yield b'\r\n\r\n'
        yield from self._maybe_encode_stream(self._serialize_obj())
        yield b'\r\n'

    def _serialize_obj(self):
        obj = self.obj
        mtype, stype, *_ = parse_mimetype(self.headers.get(CONTENT_TYPE))
        serializer = self._serialize_map.get((mtype, stype))
        if serializer is not None:
            return serializer(obj)

        for key in self._serialize_map:
            if not isinstance(key, tuple) and isinstance(obj, key):
                return self._serialize_map[key](obj)
        return self._serialize_default(obj)

    def _serialize_bytes(self, obj):
        yield obj

    def _serialize_str(self, obj):
        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
        yield obj.encode(params.get('charset', 'us-ascii'))

    def _serialize_io(self, obj):
        while True:
            chunk = obj.read(self._chunk_size)
            if not chunk:
                break
            if isinstance(chunk, str):
                yield from self._serialize_str(chunk)
            else:
                yield from self._serialize_bytes(chunk)

    def _serialize_multipart(self, obj):
        yield from obj.serialize()

    def _serialize_json(self, obj):
        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
        yield json.dumps(obj).encode(params.get('charset', 'utf-8'))

    def _serialize_form(self, obj):
        if isinstance(obj, Mapping):
            obj = list(obj.items())
        return self._serialize_str(urlencode(obj, doseq=True))

    def _serialize_default(self, obj):
        raise TypeError('unknown body part type %r' % type(obj))

    def _maybe_encode_stream(self, stream):
        if CONTENT_ENCODING in self.headers:
            stream = self._apply_content_encoding(stream)
        if CONTENT_TRANSFER_ENCODING in self.headers:
            stream = self._apply_content_transfer_encoding(stream)
        yield from stream

    def _apply_content_encoding(self, stream):
        encoding = self.headers[CONTENT_ENCODING].lower()
        if encoding == 'identity':
            yield from stream
        elif encoding in ('deflate', 'gzip'):
            zlib_mode = (16 + zlib.MAX_WBITS
                         if encoding == 'gzip' else
                         -zlib.MAX_WBITS)
            zcomp = zlib.compressobj(wbits=zlib_mode)
            for chunk in stream:
                yield zcomp.compress(chunk)
            else:
                yield zcomp.flush()
        else:
            raise RuntimeError('unknown content encoding: {}'
                               ''.format(encoding))

    def _apply_content_transfer_encoding(self, stream):
        encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower()
        if encoding == 'base64':
            buffer = bytearray()
            while True:
                if buffer:
                    div, mod = divmod(len(buffer), 3)
                    chunk, buffer = buffer[:div * 3], buffer[div * 3:]
                    if chunk:
                        yield base64.b64encode(chunk)
                chunk = next(stream, None)
                if not chunk:
                    if buffer:
                        yield base64.b64encode(buffer[:])
                    return
                buffer.extend(chunk)
        elif encoding == 'quoted-printable':
            for chunk in stream:
                yield binascii.b2a_qp(chunk)
        else:
            raise RuntimeError('unknown content transfer encoding: {}'
                               ''.format(encoding))

    def set_content_disposition(self, disptype, **params):
        """Sets ``Content-Disposition`` header.

        :param str disptype: Disposition type: inline, attachment, form-data.
                            Should be valid extension token (see RFC 2183)
        :param dict params: Disposition params
        """
        if not disptype or not (TOKEN > set(disptype)):
            raise ValueError('bad content disposition type {!r}'
                             ''.format(disptype))
        value = disptype
        if params:
            lparams = []
            for key, val in params.items():
                if not key or not (TOKEN > set(key)):
                    raise ValueError('bad content disposition parameter'
                                     ' {!r}={!r}'.format(key, val))
                qval = quote(val, '')
                if key == 'filename':
                    lparams.append((key, '"%s"' % qval))
                    lparams.append(('filename*', "utf-8''" + qval))
                else:
                    lparams.append((key, "%s" % qval))
            sparams = '; '.join('='.join(pair) for pair in lparams)
            value = '; '.join((value, sparams))
        self.headers[CONTENT_DISPOSITION] = value

    @property
    def filename(self):
        """Returns filename specified in Content-Disposition header or ``None``
        if missed."""
        _, params = parse_content_disposition(
            self.headers.get(CONTENT_DISPOSITION))
        return content_disposition_filename(params)


class MultipartWriter(object):
    """Multipart body writer."""

    #: Body part reader class for non multipart/* content types.
    part_writer_cls = BodyPartWriter

    def __init__(self, subtype='mixed', boundary=None):
        boundary = boundary if boundary is not None else uuid.uuid4().hex
        try:
            boundary.encode('us-ascii')
        except UnicodeEncodeError:
            raise ValueError('boundary should contains ASCII only chars')
        self.headers = CIMultiDict()
        self.headers[CONTENT_TYPE] = 'multipart/{}; boundary="{}"'.format(
            subtype, boundary
        )
        self.parts = []

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

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

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

    @property
    def boundary(self):
        *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE))
        return params['boundary'].encode('us-ascii')

    def append(self, obj, headers=None):
        """Adds a new body part to multipart writer."""
        if isinstance(obj, self.part_writer_cls):
            if headers:
                obj.headers.update(headers)
            self.parts.append(obj)
        else:
            if not headers:
                headers = CIMultiDict()
            self.parts.append(self.part_writer_cls(obj, headers))
        return self.parts[-1]

    def append_json(self, obj, headers=None):
        """Helper to append JSON part."""
        if not headers:
            headers = CIMultiDict()
        headers[CONTENT_TYPE] = 'application/json'
        return self.append(obj, headers)

    def append_form(self, obj, headers=None):
        """Helper to append form urlencoded part."""
        if not headers:
            headers = CIMultiDict()
        headers[CONTENT_TYPE] = 'application/x-www-form-urlencoded'
        assert isinstance(obj, (Sequence, Mapping))
        return self.append(obj, headers)

    def serialize(self):
        """Yields multipart byte chunks."""
        if not self.parts:
            yield b''
            return

        for part in self.parts:
            yield b'--' + self.boundary + b'\r\n'
            yield from part.serialize()
        else:
            yield b'--' + self.boundary + b'--\r\n'

        yield b''

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