Refactor content streams (#1296)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Refactor content_streams internally * Tidy up multipart * Use ByteStream annotation internally
authored by Tom Christie · committed by GitHub · parent fbb21fb · Browse files · 8 files·+756 added−773 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+756 added−773 removed
- tests:+387 added−375 removed
- other:+369 added−398 removed
Provenance
- Commit
354c4ca- Tree
e6f78fc- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
fbb21fb
8 files changed+756 added−773 removed
deleted:httpx/_content_streams.py-395 removed
1-import binascii2-import inspect3-import os4-import typing5-from json import dumps as json_dumps6-from pathlib import Path7-from urllib.parse import urlencode8-9-from ._exceptions import StreamConsumed10-from ._types import (11- ByteStream,12- FileContent,13- FileTypes,14- RequestContent,15- RequestData,16- RequestFiles,17- ResponseContent,18-)19-from ._utils import (20- format_form_param,21- guess_content_type,22- peek_filelike_length,23- to_bytes,24-)25-26-27-class PlainByteStream:28- """29- Request content encoded as plain bytes.30- """31-32- def __init__(self, body: typing.Union[str, bytes]) -> None:33- self.body = body.encode("utf-8") if isinstance(body, str) else body34-35- def get_headers(self) -> typing.Dict[str, str]:36- if not self.body:37- return {}38- content_length = str(len(self.body))39- return {"Content-Length": content_length}40-41- def __iter__(self) -> typing.Iterator[bytes]:42- yield self.body43-44- async def __aiter__(self) -> typing.AsyncIterator[bytes]:45- yield self.body46-47-48-class GeneratorStream:49- """50- Request content encoded as plain bytes, using an byte generator.51- """52-53- def __init__(self, generator: typing.Iterable[bytes]) -> None:54- self._generator = generator55- self._is_stream_consumed = False56-57- def __iter__(self) -> typing.Iterator[bytes]:58- if self._is_stream_consumed:59- raise StreamConsumed()60- self._is_stream_consumed = True61- for part in self._generator:62- yield part63-64-65-class AsyncGeneratorStream:66- """67- Request content encoded as plain bytes, using an async byte iterator.68- """69-70- def __init__(self, agenerator: typing.AsyncIterable[bytes]) -> None:71- self._agenerator = agenerator72- self._is_stream_consumed = False73-74- async def __aiter__(self) -> typing.AsyncIterator[bytes]:75- if self._is_stream_consumed:76- raise StreamConsumed()77- self._is_stream_consumed = True78- async for part in self._agenerator:79- yield part80-81-82-class JSONStream:83- """84- Request content encoded as JSON.85- """86-87- def __init__(self, json: typing.Any) -> None:88- self.body = json_dumps(json).encode("utf-8")89-90- def get_headers(self) -> typing.Dict[str, str]:91- content_length = str(len(self.body))92- content_type = "application/json"93- return {"Content-Length": content_length, "Content-Type": content_type}94-95- def __iter__(self) -> typing.Iterator[bytes]:96- yield self.body97-98- async def __aiter__(self) -> typing.AsyncIterator[bytes]:99- yield self.body100-101-102-class URLEncodedStream:103- """104- Request content as URL encoded form data.105- """106-107- def __init__(self, data: dict) -> None:108- self.body = urlencode(data, doseq=True).encode("utf-8")109-110- def get_headers(self) -> typing.Dict[str, str]:111- content_length = str(len(self.body))112- content_type = "application/x-www-form-urlencoded"113- return {"Content-Length": content_length, "Content-Type": content_type}114-115- def __iter__(self) -> typing.Iterator[bytes]:116- yield self.body117-118- async def __aiter__(self) -> typing.AsyncIterator[bytes]:119- yield self.body120-121-122-class MultipartStream:123- """124- Request content as streaming multipart encoded form data.125- """126-127- class DataField:128- """129- A single form field item, within a multipart form field.130- """131-132- def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:133- if not isinstance(name, str):134- raise TypeError("Invalid type for name. Expected str.")135- if not isinstance(value, (str, bytes)):136- raise TypeError("Invalid type for value. Expected str or bytes.")137- self.name = name138- self.value = value139-140- def render_headers(self) -> bytes:141- if not hasattr(self, "_headers"):142- name = format_form_param("name", self.name)143- self._headers = b"".join(144- [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"]145- )146-147- return self._headers148-149- def render_data(self) -> bytes:150- if not hasattr(self, "_data"):151- self._data = (152- self.value153- if isinstance(self.value, bytes)154- else self.value.encode("utf-8")155- )156-157- return self._data158-159- def get_length(self) -> int:160- headers = self.render_headers()161- data = self.render_data()162- return len(headers) + len(data)163-164- def render(self) -> typing.Iterator[bytes]:165- yield self.render_headers()166- yield self.render_data()167-168- class FileField:169- """170- A single file field item, within a multipart form field.171- """172-173- def __init__(self, name: str, value: FileTypes) -> None:174- self.name = name175-176- fileobj: FileContent177-178- if isinstance(value, tuple):179- try:180- filename, fileobj, content_type = value # type: ignore181- except ValueError:182- filename, fileobj = value # type: ignore183- content_type = guess_content_type(filename)184- else:185- filename = Path(str(getattr(value, "name", "upload"))).name186- fileobj = value187- content_type = guess_content_type(filename)188-189- self.filename = filename190- self.file = fileobj191- self.content_type = content_type192- self._consumed = False193-194- def get_length(self) -> int:195- headers = self.render_headers()196-197- if isinstance(self.file, (str, bytes)):198- return len(headers) + len(self.file)199-200- # Let's do our best not to read `file` into memory.201- try:202- file_length = peek_filelike_length(self.file)203- except OSError:204- # As a last resort, read file and cache contents for later.205- assert not hasattr(self, "_data")206- self._data = to_bytes(self.file.read())207- file_length = len(self._data)208-209- return len(headers) + file_length210-211- def render_headers(self) -> bytes:212- if not hasattr(self, "_headers"):213- parts = [214- b"Content-Disposition: form-data; ",215- format_form_param("name", self.name),216- ]217- if self.filename:218- filename = format_form_param("filename", self.filename)219- parts.extend([b"; ", filename])220- if self.content_type is not None:221- content_type = self.content_type.encode()222- parts.extend([b"\r\nContent-Type: ", content_type])223- parts.append(b"\r\n\r\n")224- self._headers = b"".join(parts)225-226- return self._headers227-228- def render_data(self) -> typing.Iterator[bytes]:229- if isinstance(self.file, (str, bytes)):230- yield to_bytes(self.file)231- return232-233- if hasattr(self, "_data"):234- # Already rendered.235- yield self._data236- return237-238- if self._consumed: # pragma: nocover239- self.file.seek(0)240- self._consumed = True241-242- for chunk in self.file:243- yield to_bytes(chunk)244-245- def render(self) -> typing.Iterator[bytes]:246- yield self.render_headers()247- yield from self.render_data()248-249- def __init__(250- self, data: typing.Mapping, files: RequestFiles, boundary: bytes = None251- ) -> None:252- if boundary is None:253- boundary = binascii.hexlify(os.urandom(16))254-255- self.boundary = boundary256- self.content_type = "multipart/form-data; boundary=%s" % boundary.decode(257- "ascii"258- )259- self.fields = list(self._iter_fields(data, files))260-261- def _iter_fields(262- self, data: typing.Mapping, files: RequestFiles263- ) -> typing.Iterator[typing.Union["FileField", "DataField"]]:264- for name, value in data.items():265- if isinstance(value, list):266- for item in value:267- yield self.DataField(name=name, value=item)268- else:269- yield self.DataField(name=name, value=value)270-271- file_items = files.items() if isinstance(files, typing.Mapping) else files272- for name, value in file_items:273- yield self.FileField(name=name, value=value)274-275- def iter_chunks(self) -> typing.Iterator[bytes]:276- for field in self.fields:277- yield b"--%s\r\n" % self.boundary278- yield from field.render()279- yield b"\r\n"280- yield b"--%s--\r\n" % self.boundary281-282- def iter_chunks_lengths(self) -> typing.Iterator[int]:283- boundary_length = len(self.boundary)284- # Follow closely what `.iter_chunks()` does.285- for field in self.fields:286- yield 2 + boundary_length + 2287- yield field.get_length()288- yield 2289- yield 2 + boundary_length + 4290-291- def get_content_length(self) -> int:292- return sum(self.iter_chunks_lengths())293-294- # Content stream interface.295-296- def get_headers(self) -> typing.Dict[str, str]:297- content_length = str(self.get_content_length())298- content_type = self.content_type299- return {"Content-Length": content_length, "Content-Type": content_type}300-301- def __iter__(self) -> typing.Iterator[bytes]:302- for chunk in self.iter_chunks():303- yield chunk304-305- async def __aiter__(self) -> typing.AsyncIterator[bytes]:306- for chunk in self.iter_chunks():307- yield chunk308-309-310-def encode_request(311- content: RequestContent = None,312- data: RequestData = None,313- files: RequestFiles = None,314- json: typing.Any = None,315- boundary: bytes = None,316-) -> typing.Tuple[typing.Dict[str, str], ByteStream]:317- """318- Handles encoding the given `content`, `data`, `files`, and `json`,319- returning a two-tuple of (<headers>, <stream>).320- """321- if data is not None and not isinstance(data, dict):322- # We prefer to seperate `content=<bytes|byte iterator|bytes aiterator>`323- # for raw request content, and `data=<form data>` for url encoded or324- # multipart form content.325- #326- # However for compat with requests, we *do* still support327- # `data=<bytes...>` usages. We deal with that case here, treating it328- # as if `content=<...>` had been supplied instead.329- content = data330- data = None331-332- if content is not None:333- if isinstance(content, (str, bytes)):334- byte_stream = PlainByteStream(body=content)335- headers = byte_stream.get_headers()336- return headers, byte_stream337- elif isinstance(content, (typing.Iterable, typing.AsyncIterable)):338- if inspect.isgenerator(content):339- generator_stream = GeneratorStream(content) # type: ignore340- return {"Transfer-Encoding": "chunked"}, generator_stream341- if inspect.isasyncgen(content):342- agenerator_stream = AsyncGeneratorStream(content) # type: ignore343- return {"Transfer-Encoding": "chunked"}, agenerator_stream344- return {"Transfer-Encoding": "chunked"}, content # type: ignore345- else:346- raise TypeError(f"Unexpected type for 'content', {type(content)!r}")347-348- elif data:349- if files:350- multipart_stream = MultipartStream(351- data=data, files=files, boundary=boundary352- )353- headers = multipart_stream.get_headers()354- return headers, multipart_stream355- else:356- urlencoded_stream = URLEncodedStream(data=data)357- headers = urlencoded_stream.get_headers()358- return headers, urlencoded_stream359-360- elif files:361- multipart_stream = MultipartStream(data={}, files=files, boundary=boundary)362- headers = multipart_stream.get_headers()363- return headers, multipart_stream364-365- elif json is not None:366- json_stream = JSONStream(json=json)367- headers = json_stream.get_headers()368- return headers, json_stream369-370- byte_stream = PlainByteStream(body=b"")371- headers = byte_stream.get_headers()372- return headers, byte_stream373-374-375-def encode_response(376- content: ResponseContent = None,377-) -> typing.Tuple[typing.Dict[str, str], ByteStream]:378- if content is None:379- byte_stream = PlainByteStream(b"")380- headers = byte_stream.get_headers()381- return headers, byte_stream382- elif isinstance(content, bytes):383- byte_stream = PlainByteStream(body=content)384- headers = byte_stream.get_headers()385- return headers, byte_stream386- elif isinstance(content, (typing.Iterable, typing.AsyncIterable)):387- if inspect.isgenerator(content):388- generator_stream = GeneratorStream(content) # type: ignore389- return {"Transfer-Encoding": "chunked"}, generator_stream390- elif inspect.isasyncgen(content):391- agenerator_stream = AsyncGeneratorStream(content) # type: ignore392- return {"Transfer-Encoding": "chunked"}, agenerator_stream393- return {"Transfer-Encoding": "chunked"}, content # type: ignore394-395- raise TypeError(f"Unexpected type for 'content', {type(content)!r}")added:httpx/_content.py+166 added
1+import inspect2+import typing3+from json import dumps as json_dumps4+from urllib.parse import urlencode5+6+from ._exceptions import StreamConsumed7+from ._multipart import MultipartStream8+from ._types import (9+ ByteStream,10+ RequestContent,11+ RequestData,12+ RequestFiles,13+ ResponseContent,14+)15+16+17+class PlainByteStream:18+ """19+ Request content encoded as plain bytes.20+ """21+22+ def __init__(self, body: bytes) -> None:23+ self._body = body24+25+ def __iter__(self) -> typing.Iterator[bytes]:26+ yield self._body27+28+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:29+ yield self._body30+31+32+class GeneratorStream:33+ """34+ Request content encoded as plain bytes, using an byte generator.35+ """36+37+ def __init__(self, generator: typing.Iterable[bytes]) -> None:38+ self._generator = generator39+ self._is_stream_consumed = False40+41+ def __iter__(self) -> typing.Iterator[bytes]:42+ if self._is_stream_consumed:43+ raise StreamConsumed()44+45+ self._is_stream_consumed = True46+ for part in self._generator:47+ yield part48+49+50+class AsyncGeneratorStream:51+ """52+ Request content encoded as plain bytes, using an async byte iterator.53+ """54+55+ def __init__(self, agenerator: typing.AsyncIterable[bytes]) -> None:56+ self._agenerator = agenerator57+ self._is_stream_consumed = False58+59+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:60+ if self._is_stream_consumed:61+ raise StreamConsumed()62+63+ self._is_stream_consumed = True64+ async for part in self._agenerator:65+ yield part66+67+68+def encode_content(69+ content: typing.Union[str, bytes, ByteStream]70+) -> typing.Tuple[typing.Dict[str, str], ByteStream]:71+ if isinstance(content, (str, bytes)):72+ body = content.encode("utf-8") if isinstance(content, str) else content73+ content_length = str(len(body))74+ headers = {"Content-Length": content_length} if body else {}75+ stream = PlainByteStream(body)76+ return headers, stream77+78+ elif isinstance(content, (typing.Iterable, typing.AsyncIterable)):79+ headers = {"Transfer-Encoding": "chunked"}80+81+ # Generators should be wrapped in GeneratorStream/AsyncGeneratorStream82+ # which will raise `StreamConsumed` if the stream is accessed more83+ # than once. (Eg. Following HTTP 307 or HTTP 308 redirects.)84+ if inspect.isgenerator(content):85+ generator_stream = GeneratorStream(content) # type: ignore86+ return headers, generator_stream87+ if inspect.isasyncgen(content):88+ agenerator_stream = AsyncGeneratorStream(content) # type: ignore89+ return headers, agenerator_stream90+91+ # Other iterables may be passed through as-is.92+ return headers, content # type: ignore93+94+ raise TypeError(f"Unexpected type for 'content', {type(content)!r}")95+96+97+def encode_urlencoded_data(98+ data: dict,99+) -> typing.Tuple[typing.Dict[str, str], ByteStream]:100+ body = urlencode(data, doseq=True).encode("utf-8")101+ content_length = str(len(body))102+ content_type = "application/x-www-form-urlencoded"103+ headers = {"Content-Length": content_length, "Content-Type": content_type}104+ return headers, PlainByteStream(body)105+106+107+def encode_multipart_data(108+ data: dict, files: RequestFiles, boundary: bytes = None109+) -> typing.Tuple[typing.Dict[str, str], ByteStream]:110+ stream = MultipartStream(data=data, files=files, boundary=boundary)111+ headers = stream.get_headers()112+ return headers, stream113+114+115+def encode_json(json: typing.Any) -> typing.Tuple[typing.Dict[str, str], ByteStream]:116+ body = json_dumps(json).encode("utf-8")117+ content_length = str(len(body))118+ content_type = "application/json"119+ headers = {"Content-Length": content_length, "Content-Type": content_type}120+ return headers, PlainByteStream(body)121+122+123+def encode_request(124+ content: RequestContent = None,125+ data: RequestData = None,126+ files: RequestFiles = None,127+ json: typing.Any = None,128+ boundary: bytes = None,129+) -> typing.Tuple[typing.Dict[str, str], ByteStream]:130+ """131+ Handles encoding the given `content`, `data`, `files`, and `json`,132+ returning a two-tuple of (<headers>, <stream>).133+ """134+ if data is not None and not isinstance(data, dict):135+ # We prefer to seperate `content=<bytes|str|byte iterator|bytes aiterator>`136+ # for raw request content, and `data=<form data>` for url encoded or137+ # multipart form content.138+ #139+ # However for compat with requests, we *do* still support140+ # `data=<bytes...>` usages. We deal with that case here, treating it141+ # as if `content=<...>` had been supplied instead.142+ return encode_content(data)143+144+ if content is not None:145+ return encode_content(content)146+ elif files:147+ return encode_multipart_data(data or {}, files, boundary)148+ elif data:149+ return encode_urlencoded_data(data)150+ elif json is not None:151+ return encode_json(json)152+153+ return {}, PlainByteStream(b"")154+155+156+def encode_response(157+ content: ResponseContent = None,158+) -> typing.Tuple[typing.Dict[str, str], ByteStream]:159+ """160+ Handles encoding the given `content`, returning a two-tuple of161+ (<headers>, <stream>).162+ """163+ if content is not None:164+ return encode_content(content)165+166+ return {}, PlainByteStream(b"")modified:httpx/_models.py+1 added-1 removed
11 unmodified lines12 13 import rfc398614 import rfc3986.exceptions15 16-from ._content_streams import PlainByteStream, encode_request, encode_response16+from ._content import PlainByteStream, encode_request, encode_response17 from ._decoders import (18 SUPPORTED_DECODERS,19 ContentDecoder,20 IdentityDecoder,1285 unmodified linesadded:httpx/_multipart.py+200 added
1+import binascii2+import os3+import typing4+from pathlib import Path5+6+from ._types import FileContent, FileTypes, RequestFiles7+from ._utils import (8+ format_form_param,9+ guess_content_type,10+ peek_filelike_length,11+ to_bytes,12+)13+14+15+class DataField:16+ """17+ A single form field item, within a multipart form field.18+ """19+20+ def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:21+ if not isinstance(name, str):22+ raise TypeError("Invalid type for name. Expected str.")23+ if not isinstance(value, (str, bytes)):24+ raise TypeError("Invalid type for value. Expected str or bytes.")25+ self.name = name26+ self.value = value27+28+ def render_headers(self) -> bytes:29+ if not hasattr(self, "_headers"):30+ name = format_form_param("name", self.name)31+ self._headers = b"".join(32+ [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"]33+ )34+35+ return self._headers36+37+ def render_data(self) -> bytes:38+ if not hasattr(self, "_data"):39+ self._data = (40+ self.value41+ if isinstance(self.value, bytes)42+ else self.value.encode("utf-8")43+ )44+45+ return self._data46+47+ def get_length(self) -> int:48+ headers = self.render_headers()49+ data = self.render_data()50+ return len(headers) + len(data)51+52+ def render(self) -> typing.Iterator[bytes]:53+ yield self.render_headers()54+ yield self.render_data()55+56+57+class FileField:58+ """59+ A single file field item, within a multipart form field.60+ """61+62+ def __init__(self, name: str, value: FileTypes) -> None:63+ self.name = name64+65+ fileobj: FileContent66+67+ if isinstance(value, tuple):68+ try:69+ filename, fileobj, content_type = value # type: ignore70+ except ValueError:71+ filename, fileobj = value # type: ignore72+ content_type = guess_content_type(filename)73+ else:74+ filename = Path(str(getattr(value, "name", "upload"))).name75+ fileobj = value76+ content_type = guess_content_type(filename)77+78+ self.filename = filename79+ self.file = fileobj80+ self.content_type = content_type81+ self._consumed = False82+83+ def get_length(self) -> int:84+ headers = self.render_headers()85+86+ if isinstance(self.file, (str, bytes)):87+ return len(headers) + len(self.file)88+89+ # Let's do our best not to read `file` into memory.90+ try:91+ file_length = peek_filelike_length(self.file)92+ except OSError:93+ # As a last resort, read file and cache contents for later.94+ assert not hasattr(self, "_data")95+ self._data = to_bytes(self.file.read())96+ file_length = len(self._data)97+98+ return len(headers) + file_length99+100+ def render_headers(self) -> bytes:101+ if not hasattr(self, "_headers"):102+ parts = [103+ b"Content-Disposition: form-data; ",104+ format_form_param("name", self.name),105+ ]106+ if self.filename:107+ filename = format_form_param("filename", self.filename)108+ parts.extend([b"; ", filename])109+ if self.content_type is not None:110+ content_type = self.content_type.encode()111+ parts.extend([b"\r\nContent-Type: ", content_type])112+ parts.append(b"\r\n\r\n")113+ self._headers = b"".join(parts)114+115+ return self._headers116+117+ def render_data(self) -> typing.Iterator[bytes]:118+ if isinstance(self.file, (str, bytes)):119+ yield to_bytes(self.file)120+ return121+122+ if hasattr(self, "_data"):123+ # Already rendered.124+ yield self._data125+ return126+127+ if self._consumed: # pragma: nocover128+ self.file.seek(0)129+ self._consumed = True130+131+ for chunk in self.file:132+ yield to_bytes(chunk)133+134+ def render(self) -> typing.Iterator[bytes]:135+ yield self.render_headers()136+ yield from self.render_data()137+138+139+class MultipartStream:140+ """141+ Request content as streaming multipart encoded form data.142+ """143+144+ def __init__(self, data: dict, files: RequestFiles, boundary: bytes = None) -> None:145+ if boundary is None:146+ boundary = binascii.hexlify(os.urandom(16))147+148+ self.boundary = boundary149+ self.content_type = "multipart/form-data; boundary=%s" % boundary.decode(150+ "ascii"151+ )152+ self.fields = list(self._iter_fields(data, files))153+154+ def _iter_fields(155+ self, data: dict, files: RequestFiles156+ ) -> typing.Iterator[typing.Union[FileField, DataField]]:157+ for name, value in data.items():158+ if isinstance(value, list):159+ for item in value:160+ yield DataField(name=name, value=item)161+ else:162+ yield DataField(name=name, value=value)163+164+ file_items = files.items() if isinstance(files, typing.Mapping) else files165+ for name, value in file_items:166+ yield FileField(name=name, value=value)167+168+ def iter_chunks(self) -> typing.Iterator[bytes]:169+ for field in self.fields:170+ yield b"--%s\r\n" % self.boundary171+ yield from field.render()172+ yield b"\r\n"173+ yield b"--%s--\r\n" % self.boundary174+175+ def iter_chunks_lengths(self) -> typing.Iterator[int]:176+ boundary_length = len(self.boundary)177+ # Follow closely what `.iter_chunks()` does.178+ for field in self.fields:179+ yield 2 + boundary_length + 2180+ yield field.get_length()181+ yield 2182+ yield 2 + boundary_length + 4183+184+ def get_content_length(self) -> int:185+ return sum(self.iter_chunks_lengths())186+187+ # Content stream interface.188+189+ def get_headers(self) -> typing.Dict[str, str]:190+ content_length = str(self.get_content_length())191+ content_type = self.content_type192+ return {"Content-Length": content_length, "Content-Type": content_type}193+194+ def __iter__(self) -> typing.Iterator[bytes]:195+ for chunk in self.iter_chunks():196+ yield chunk197+198+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:199+ for chunk in self.iter_chunks():200+ yield chunkmodified:httpx/_types.py+2 added-2 removed
64 unmodified lines65 "Auth",66 None,67 ]68 69-RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]70-ResponseContent = Union[bytes, Iterable[bytes], AsyncIterable[bytes]]69 ByteStream = Union[Iterable[bytes], AsyncIterable[bytes]]70+RequestContent = Union[str, bytes, ByteStream]71+ResponseContent = Union[str, bytes, ByteStream]72 73 RequestData = dict74 75 FileContent = Union[IO[str], IO[bytes], str, bytes]9 unmodified linesdeleted:tests/test_content_streams.py-359 removed
1-import io2-import typing3-4-import pytest5-6-from httpx import StreamConsumed7-from httpx._content_streams import encode_request, encode_response8-9-10-@pytest.mark.asyncio11-async def test_empty_content():12- headers, stream = encode_request()13- assert isinstance(stream, typing.Iterable)14- assert isinstance(stream, typing.AsyncIterable)15-16- sync_content = b"".join([part for part in stream])17- async_content = b"".join([part async for part in stream])18-19- assert headers == {}20- assert sync_content == b""21- assert async_content == b""22-23-24-@pytest.mark.asyncio25-async def test_bytes_content():26- headers, stream = encode_request(content=b"Hello, world!")27- assert isinstance(stream, typing.Iterable)28- assert isinstance(stream, typing.AsyncIterable)29-30- sync_content = b"".join([part for part in stream])31- async_content = b"".join([part async for part in stream])32-33- assert headers == {"Content-Length": "13"}34- assert sync_content == b"Hello, world!"35- assert async_content == b"Hello, world!"36-37- # Support 'data' for compat with requests.38- headers, stream = encode_request(data=b"Hello, world!") # type: ignore39- assert isinstance(stream, typing.Iterable)40- assert isinstance(stream, typing.AsyncIterable)41-42- sync_content = b"".join([part for part in stream])43- async_content = b"".join([part async for part in stream])44-45- assert headers == {"Content-Length": "13"}46- assert sync_content == b"Hello, world!"47- assert async_content == b"Hello, world!"48-49-50-@pytest.mark.asyncio51-async def test_iterator_content():52- def hello_world():53- yield b"Hello, "54- yield b"world!"55-56- headers, stream = encode_request(content=hello_world())57- assert isinstance(stream, typing.Iterable)58- assert not isinstance(stream, typing.AsyncIterable)59-60- content = b"".join([part for part in stream])61-62- assert headers == {"Transfer-Encoding": "chunked"}63- assert content == b"Hello, world!"64-65- with pytest.raises(StreamConsumed):66- [part for part in stream]67-68- # Support 'data' for compat with requests.69- headers, stream = encode_request(data=hello_world()) # type: ignore70- assert isinstance(stream, typing.Iterable)71- assert not isinstance(stream, typing.AsyncIterable)72-73- content = b"".join([part for part in stream])74-75- assert headers == {"Transfer-Encoding": "chunked"}76- assert content == b"Hello, world!"77-78-79-@pytest.mark.asyncio80-async def test_aiterator_content():81- async def hello_world():82- yield b"Hello, "83- yield b"world!"84-85- headers, stream = encode_request(content=hello_world())86- assert not isinstance(stream, typing.Iterable)87- assert isinstance(stream, typing.AsyncIterable)88-89- content = b"".join([part async for part in stream])90-91- assert headers == {"Transfer-Encoding": "chunked"}92- assert content == b"Hello, world!"93-94- with pytest.raises(StreamConsumed):95- [part async for part in stream]96-97- # Support 'data' for compat with requests.98- headers, stream = encode_request(data=hello_world()) # type: ignore99- assert not isinstance(stream, typing.Iterable)100- assert isinstance(stream, typing.AsyncIterable)101-102- content = b"".join([part async for part in stream])103-104- assert headers == {"Transfer-Encoding": "chunked"}105- assert content == b"Hello, world!"106-107-108-@pytest.mark.asyncio109-async def test_json_content():110- headers, stream = encode_request(json={"Hello": "world!"})111- assert isinstance(stream, typing.Iterable)112- assert isinstance(stream, typing.AsyncIterable)113-114- sync_content = b"".join([part for part in stream])115- async_content = b"".join([part async for part in stream])116-117- assert headers == {118- "Content-Length": "19",119- "Content-Type": "application/json",120- }121- assert sync_content == b'{"Hello": "world!"}'122- assert async_content == b'{"Hello": "world!"}'123-124-125-@pytest.mark.asyncio126-async def test_urlencoded_content():127- headers, stream = encode_request(data={"Hello": "world!"})128- assert isinstance(stream, typing.Iterable)129- assert isinstance(stream, typing.AsyncIterable)130-131- sync_content = b"".join([part for part in stream])132- async_content = b"".join([part async for part in stream])133-134- assert headers == {135- "Content-Length": "14",136- "Content-Type": "application/x-www-form-urlencoded",137- }138- assert sync_content == b"Hello=world%21"139- assert async_content == b"Hello=world%21"140-141-142-@pytest.mark.asyncio143-async def test_multipart_files_content():144- files = {"file": io.BytesIO(b"<file content>")}145- headers, stream = encode_request(files=files, boundary=b"+++")146- assert isinstance(stream, typing.Iterable)147- assert isinstance(stream, typing.AsyncIterable)148-149- sync_content = b"".join([part for part in stream])150- async_content = b"".join([part async for part in stream])151-152- assert headers == {153- "Content-Length": "138",154- "Content-Type": "multipart/form-data; boundary=+++",155- }156- assert sync_content == b"".join(157- [158- b"--+++\r\n",159- b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',160- b"Content-Type: application/octet-stream\r\n",161- b"\r\n",162- b"<file content>\r\n",163- b"--+++--\r\n",164- ]165- )166- assert async_content == b"".join(167- [168- b"--+++\r\n",169- b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',170- b"Content-Type: application/octet-stream\r\n",171- b"\r\n",172- b"<file content>\r\n",173- b"--+++--\r\n",174- ]175- )176-177-178-@pytest.mark.asyncio179-async def test_multipart_data_and_files_content():180- data = {"message": "Hello, world!"}181- files = {"file": io.BytesIO(b"<file content>")}182- headers, stream = encode_request(data=data, files=files, boundary=b"+++")183- assert isinstance(stream, typing.Iterable)184- assert isinstance(stream, typing.AsyncIterable)185-186- sync_content = b"".join([part for part in stream])187- async_content = b"".join([part async for part in stream])188-189- assert headers == {190- "Content-Length": "210",191- "Content-Type": "multipart/form-data; boundary=+++",192- }193- assert sync_content == b"".join(194- [195- b"--+++\r\n",196- b'Content-Disposition: form-data; name="message"\r\n',197- b"\r\n",198- b"Hello, world!\r\n",199- b"--+++\r\n",200- b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',201- b"Content-Type: application/octet-stream\r\n",202- b"\r\n",203- b"<file content>\r\n",204- b"--+++--\r\n",205- ]206- )207- assert async_content == b"".join(208- [209- b"--+++\r\n",210- b'Content-Disposition: form-data; name="message"\r\n',211- b"\r\n",212- b"Hello, world!\r\n",213- b"--+++\r\n",214- b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',215- b"Content-Type: application/octet-stream\r\n",216- b"\r\n",217- b"<file content>\r\n",218- b"--+++--\r\n",219- ]220- )221-222-223-@pytest.mark.asyncio224-async def test_empty_request():225- headers, stream = encode_request(data={}, files={})226- assert isinstance(stream, typing.Iterable)227- assert isinstance(stream, typing.AsyncIterable)228-229- sync_content = b"".join([part for part in stream])230- async_content = b"".join([part async for part in stream])231-232- assert headers == {}233- assert sync_content == b""234- assert async_content == b""235-236-237-def test_invalid_argument():238- with pytest.raises(TypeError):239- encode_request(123) # type: ignore240-241-242-@pytest.mark.asyncio243-async def test_multipart_multiple_files_single_input_content():244- files = [245- ("file", io.BytesIO(b"<file content 1>")),246- ("file", io.BytesIO(b"<file content 2>")),247- ]248- headers, stream = encode_request(files=files, boundary=b"+++")249- assert isinstance(stream, typing.Iterable)250- assert isinstance(stream, typing.AsyncIterable)251-252- sync_content = b"".join([part for part in stream])253- async_content = b"".join([part async for part in stream])254-255- assert headers == {256- "Content-Length": "271",257- "Content-Type": "multipart/form-data; boundary=+++",258- }259- assert sync_content == b"".join(260- [261- b"--+++\r\n",262- b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',263- b"Content-Type: application/octet-stream\r\n",264- b"\r\n",265- b"<file content 1>\r\n",266- b"--+++\r\n",267- b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',268- b"Content-Type: application/octet-stream\r\n",269- b"\r\n",270- b"<file content 2>\r\n",271- b"--+++--\r\n",272- ]273- )274- assert async_content == b"".join(275- [276- b"--+++\r\n",277- b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',278- b"Content-Type: application/octet-stream\r\n",279- b"\r\n",280- b"<file content 1>\r\n",281- b"--+++\r\n",282- b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',283- b"Content-Type: application/octet-stream\r\n",284- b"\r\n",285- b"<file content 2>\r\n",286- b"--+++--\r\n",287- ]288- )289-290-291-@pytest.mark.asyncio292-async def test_response_empty_content():293- headers, stream = encode_response()294- assert isinstance(stream, typing.Iterable)295- assert isinstance(stream, typing.AsyncIterable)296-297- sync_content = b"".join([part for part in stream])298- async_content = b"".join([part async for part in stream])299-300- assert headers == {}301- assert sync_content == b""302- assert async_content == b""303-304-305-@pytest.mark.asyncio306-async def test_response_bytes_content():307- headers, stream = encode_response(content=b"Hello, world!")308- assert isinstance(stream, typing.Iterable)309- assert isinstance(stream, typing.AsyncIterable)310-311- sync_content = b"".join([part for part in stream])312- async_content = b"".join([part async for part in stream])313-314- assert headers == {"Content-Length": "13"}315- assert sync_content == b"Hello, world!"316- assert async_content == b"Hello, world!"317-318-319-@pytest.mark.asyncio320-async def test_response_iterator_content():321- def hello_world():322- yield b"Hello, "323- yield b"world!"324-325- headers, stream = encode_response(content=hello_world())326- assert isinstance(stream, typing.Iterable)327- assert not isinstance(stream, typing.AsyncIterable)328-329- content = b"".join([part for part in stream])330-331- assert headers == {"Transfer-Encoding": "chunked"}332- assert content == b"Hello, world!"333-334- with pytest.raises(StreamConsumed):335- [part for part in stream]336-337-338-@pytest.mark.asyncio339-async def test_response_aiterator_content():340- async def hello_world():341- yield b"Hello, "342- yield b"world!"343-344- headers, stream = encode_response(content=hello_world())345- assert not isinstance(stream, typing.Iterable)346- assert isinstance(stream, typing.AsyncIterable)347-348- content = b"".join([part async for part in stream])349-350- assert headers == {"Transfer-Encoding": "chunked"}351- assert content == b"Hello, world!"352-353- with pytest.raises(StreamConsumed):354- [part async for part in stream]355-356-357-def test_response_invalid_argument():358- with pytest.raises(TypeError):359- encode_response(123) # type: ignoreadded:tests/test_content.py+359 added
1+import io2+import typing3+4+import pytest5+6+from httpx import StreamConsumed7+from httpx._content import encode_request, encode_response8+9+10+@pytest.mark.asyncio11+async def test_empty_content():12+ headers, stream = encode_request()13+ assert isinstance(stream, typing.Iterable)14+ assert isinstance(stream, typing.AsyncIterable)15+16+ sync_content = b"".join([part for part in stream])17+ async_content = b"".join([part async for part in stream])18+19+ assert headers == {}20+ assert sync_content == b""21+ assert async_content == b""22+23+24+@pytest.mark.asyncio25+async def test_bytes_content():26+ headers, stream = encode_request(content=b"Hello, world!")27+ assert isinstance(stream, typing.Iterable)28+ assert isinstance(stream, typing.AsyncIterable)29+30+ sync_content = b"".join([part for part in stream])31+ async_content = b"".join([part async for part in stream])32+33+ assert headers == {"Content-Length": "13"}34+ assert sync_content == b"Hello, world!"35+ assert async_content == b"Hello, world!"36+37+ # Support 'data' for compat with requests.38+ headers, stream = encode_request(data=b"Hello, world!") # type: ignore39+ assert isinstance(stream, typing.Iterable)40+ assert isinstance(stream, typing.AsyncIterable)41+42+ sync_content = b"".join([part for part in stream])43+ async_content = b"".join([part async for part in stream])44+45+ assert headers == {"Content-Length": "13"}46+ assert sync_content == b"Hello, world!"47+ assert async_content == b"Hello, world!"48+49+50+@pytest.mark.asyncio51+async def test_iterator_content():52+ def hello_world():53+ yield b"Hello, "54+ yield b"world!"55+56+ headers, stream = encode_request(content=hello_world())57+ assert isinstance(stream, typing.Iterable)58+ assert not isinstance(stream, typing.AsyncIterable)59+60+ content = b"".join([part for part in stream])61+62+ assert headers == {"Transfer-Encoding": "chunked"}63+ assert content == b"Hello, world!"64+65+ with pytest.raises(StreamConsumed):66+ [part for part in stream]67+68+ # Support 'data' for compat with requests.69+ headers, stream = encode_request(data=hello_world()) # type: ignore70+ assert isinstance(stream, typing.Iterable)71+ assert not isinstance(stream, typing.AsyncIterable)72+73+ content = b"".join([part for part in stream])74+75+ assert headers == {"Transfer-Encoding": "chunked"}76+ assert content == b"Hello, world!"77+78+79+@pytest.mark.asyncio80+async def test_aiterator_content():81+ async def hello_world():82+ yield b"Hello, "83+ yield b"world!"84+85+ headers, stream = encode_request(content=hello_world())86+ assert not isinstance(stream, typing.Iterable)87+ assert isinstance(stream, typing.AsyncIterable)88+89+ content = b"".join([part async for part in stream])90+91+ assert headers == {"Transfer-Encoding": "chunked"}92+ assert content == b"Hello, world!"93+94+ with pytest.raises(StreamConsumed):95+ [part async for part in stream]96+97+ # Support 'data' for compat with requests.98+ headers, stream = encode_request(data=hello_world()) # type: ignore99+ assert not isinstance(stream, typing.Iterable)100+ assert isinstance(stream, typing.AsyncIterable)101+102+ content = b"".join([part async for part in stream])103+104+ assert headers == {"Transfer-Encoding": "chunked"}105+ assert content == b"Hello, world!"106+107+108+@pytest.mark.asyncio109+async def test_json_content():110+ headers, stream = encode_request(json={"Hello": "world!"})111+ assert isinstance(stream, typing.Iterable)112+ assert isinstance(stream, typing.AsyncIterable)113+114+ sync_content = b"".join([part for part in stream])115+ async_content = b"".join([part async for part in stream])116+117+ assert headers == {118+ "Content-Length": "19",119+ "Content-Type": "application/json",120+ }121+ assert sync_content == b'{"Hello": "world!"}'122+ assert async_content == b'{"Hello": "world!"}'123+124+125+@pytest.mark.asyncio126+async def test_urlencoded_content():127+ headers, stream = encode_request(data={"Hello": "world!"})128+ assert isinstance(stream, typing.Iterable)129+ assert isinstance(stream, typing.AsyncIterable)130+131+ sync_content = b"".join([part for part in stream])132+ async_content = b"".join([part async for part in stream])133+134+ assert headers == {135+ "Content-Length": "14",136+ "Content-Type": "application/x-www-form-urlencoded",137+ }138+ assert sync_content == b"Hello=world%21"139+ assert async_content == b"Hello=world%21"140+141+142+@pytest.mark.asyncio143+async def test_multipart_files_content():144+ files = {"file": io.BytesIO(b"<file content>")}145+ headers, stream = encode_request(files=files, boundary=b"+++")146+ assert isinstance(stream, typing.Iterable)147+ assert isinstance(stream, typing.AsyncIterable)148+149+ sync_content = b"".join([part for part in stream])150+ async_content = b"".join([part async for part in stream])151+152+ assert headers == {153+ "Content-Length": "138",154+ "Content-Type": "multipart/form-data; boundary=+++",155+ }156+ assert sync_content == b"".join(157+ [158+ b"--+++\r\n",159+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',160+ b"Content-Type: application/octet-stream\r\n",161+ b"\r\n",162+ b"<file content>\r\n",163+ b"--+++--\r\n",164+ ]165+ )166+ assert async_content == b"".join(167+ [168+ b"--+++\r\n",169+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',170+ b"Content-Type: application/octet-stream\r\n",171+ b"\r\n",172+ b"<file content>\r\n",173+ b"--+++--\r\n",174+ ]175+ )176+177+178+@pytest.mark.asyncio179+async def test_multipart_data_and_files_content():180+ data = {"message": "Hello, world!"}181+ files = {"file": io.BytesIO(b"<file content>")}182+ headers, stream = encode_request(data=data, files=files, boundary=b"+++")183+ assert isinstance(stream, typing.Iterable)184+ assert isinstance(stream, typing.AsyncIterable)185+186+ sync_content = b"".join([part for part in stream])187+ async_content = b"".join([part async for part in stream])188+189+ assert headers == {190+ "Content-Length": "210",191+ "Content-Type": "multipart/form-data; boundary=+++",192+ }193+ assert sync_content == b"".join(194+ [195+ b"--+++\r\n",196+ b'Content-Disposition: form-data; name="message"\r\n',197+ b"\r\n",198+ b"Hello, world!\r\n",199+ b"--+++\r\n",200+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',201+ b"Content-Type: application/octet-stream\r\n",202+ b"\r\n",203+ b"<file content>\r\n",204+ b"--+++--\r\n",205+ ]206+ )207+ assert async_content == b"".join(208+ [209+ b"--+++\r\n",210+ b'Content-Disposition: form-data; name="message"\r\n',211+ b"\r\n",212+ b"Hello, world!\r\n",213+ b"--+++\r\n",214+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',215+ b"Content-Type: application/octet-stream\r\n",216+ b"\r\n",217+ b"<file content>\r\n",218+ b"--+++--\r\n",219+ ]220+ )221+222+223+@pytest.mark.asyncio224+async def test_empty_request():225+ headers, stream = encode_request(data={}, files={})226+ assert isinstance(stream, typing.Iterable)227+ assert isinstance(stream, typing.AsyncIterable)228+229+ sync_content = b"".join([part for part in stream])230+ async_content = b"".join([part async for part in stream])231+232+ assert headers == {}233+ assert sync_content == b""234+ assert async_content == b""235+236+237+def test_invalid_argument():238+ with pytest.raises(TypeError):239+ encode_request(123) # type: ignore240+241+242+@pytest.mark.asyncio243+async def test_multipart_multiple_files_single_input_content():244+ files = [245+ ("file", io.BytesIO(b"<file content 1>")),246+ ("file", io.BytesIO(b"<file content 2>")),247+ ]248+ headers, stream = encode_request(files=files, boundary=b"+++")249+ assert isinstance(stream, typing.Iterable)250+ assert isinstance(stream, typing.AsyncIterable)251+252+ sync_content = b"".join([part for part in stream])253+ async_content = b"".join([part async for part in stream])254+255+ assert headers == {256+ "Content-Length": "271",257+ "Content-Type": "multipart/form-data; boundary=+++",258+ }259+ assert sync_content == b"".join(260+ [261+ b"--+++\r\n",262+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',263+ b"Content-Type: application/octet-stream\r\n",264+ b"\r\n",265+ b"<file content 1>\r\n",266+ b"--+++\r\n",267+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',268+ b"Content-Type: application/octet-stream\r\n",269+ b"\r\n",270+ b"<file content 2>\r\n",271+ b"--+++--\r\n",272+ ]273+ )274+ assert async_content == b"".join(275+ [276+ b"--+++\r\n",277+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',278+ b"Content-Type: application/octet-stream\r\n",279+ b"\r\n",280+ b"<file content 1>\r\n",281+ b"--+++\r\n",282+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',283+ b"Content-Type: application/octet-stream\r\n",284+ b"\r\n",285+ b"<file content 2>\r\n",286+ b"--+++--\r\n",287+ ]288+ )289+290+291+@pytest.mark.asyncio292+async def test_response_empty_content():293+ headers, stream = encode_response()294+ assert isinstance(stream, typing.Iterable)295+ assert isinstance(stream, typing.AsyncIterable)296+297+ sync_content = b"".join([part for part in stream])298+ async_content = b"".join([part async for part in stream])299+300+ assert headers == {}301+ assert sync_content == b""302+ assert async_content == b""303+304+305+@pytest.mark.asyncio306+async def test_response_bytes_content():307+ headers, stream = encode_response(content=b"Hello, world!")308+ assert isinstance(stream, typing.Iterable)309+ assert isinstance(stream, typing.AsyncIterable)310+311+ sync_content = b"".join([part for part in stream])312+ async_content = b"".join([part async for part in stream])313+314+ assert headers == {"Content-Length": "13"}315+ assert sync_content == b"Hello, world!"316+ assert async_content == b"Hello, world!"317+318+319+@pytest.mark.asyncio320+async def test_response_iterator_content():321+ def hello_world():322+ yield b"Hello, "323+ yield b"world!"324+325+ headers, stream = encode_response(content=hello_world())326+ assert isinstance(stream, typing.Iterable)327+ assert not isinstance(stream, typing.AsyncIterable)328+329+ content = b"".join([part for part in stream])330+331+ assert headers == {"Transfer-Encoding": "chunked"}332+ assert content == b"Hello, world!"333+334+ with pytest.raises(StreamConsumed):335+ [part for part in stream]336+337+338+@pytest.mark.asyncio339+async def test_response_aiterator_content():340+ async def hello_world():341+ yield b"Hello, "342+ yield b"world!"343+344+ headers, stream = encode_response(content=hello_world())345+ assert not isinstance(stream, typing.Iterable)346+ assert isinstance(stream, typing.AsyncIterable)347+348+ content = b"".join([part async for part in stream])349+350+ assert headers == {"Transfer-Encoding": "chunked"}351+ assert content == b"Hello, world!"352+353+ with pytest.raises(StreamConsumed):354+ [part async for part in stream]355+356+357+def test_response_invalid_argument():358+ with pytest.raises(TypeError):359+ encode_response(123) # type: ignoremodified:tests/test_multipart.py+28 added-16 removed
5 unmodified lines6 7 import pytest8 9 import httpx10-from httpx._content_streams import MultipartStream, encode_request10+from httpx._content import encode_request11 from httpx._utils import format_form_param12 from tests.utils import MockTransport13 14 95 unmodified lines110 with mock.patch("os.urandom", return_value=os.urandom(16)):111 boundary = os.urandom(16).hex()112 113 headers, stream = encode_request(data=data, files=files)114- assert isinstance(stream, MultipartStream)114+ assert isinstance(stream, typing.Iterable)115 116- assert stream.content_type == f"multipart/form-data; boundary={boundary}"116 content = (117 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'118 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'119 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'5 unmodified lines125 "Content-Type: text/plain\r\n\r\n<file content>\r\n"126 "--{0}--\r\n"127 "".format(boundary).encode("ascii")128 )130- assert headers["Content-Length"] == str(len(content))131- assert b"".join(stream) == content129+ assert headers == {130+ "Content-Type": f"multipart/form-data; boundary={boundary}",131+ "Content-Length": str(len(content)),132+ }133+ assert content == b"".join(stream)134 135 136 def test_multipart_encode_files_allows_filenames_as_none() -> None:137 files = {"file": (None, io.BytesIO(b"<file content>"))}138 with mock.patch("os.urandom", return_value=os.urandom(16)):139 boundary = os.urandom(16).hex()140 141 headers, stream = encode_request(data={}, files=files)140- assert isinstance(stream, MultipartStream)142+ assert isinstance(stream, typing.Iterable)143 142- assert stream.content_type == f"multipart/form-data; boundary={boundary}"143- assert b"".join(stream) == (144+ content = (145 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'146 "<file content>\r\n--{0}--\r\n"147 "".format(boundary).encode("ascii")148 )149+ assert headers == {150+ "Content-Type": f"multipart/form-data; boundary={boundary}",151+ "Content-Length": str(len(content)),152+ }153+ assert content == b"".join(stream)154 155 156 @pytest.mark.parametrize(157 "file_name,expected_content_type",10 unmodified lines168 with mock.patch("os.urandom", return_value=os.urandom(16)):169 boundary = os.urandom(16).hex()170 171 headers, stream = encode_request(data={}, files=files)166- assert isinstance(stream, MultipartStream)172+ assert isinstance(stream, typing.Iterable)173 168- assert stream.content_type == f"multipart/form-data; boundary={boundary}"169- assert b"".join(stream) == (174+ content = (175 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '176 f'filename="{file_name}"\r\nContent-Type: '177 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"178 "".encode("ascii")179 )180+ assert headers == {181+ "Content-Type": f"multipart/form-data; boundary={boundary}",182+ "Content-Length": str(len(content)),183+ }184+ assert content == b"".join(stream)185 186 187 @pytest.mark.parametrize(188 "value, output",6 unmodified lines195 with mock.patch("os.urandom", return_value=os.urandom(16)):196 boundary = os.urandom(16).hex()197 198 headers, stream = encode_request(data={}, files=files)189- assert isinstance(stream, MultipartStream)199+ assert isinstance(stream, typing.Iterable)200 191- assert stream.content_type == f"multipart/form-data; boundary={boundary}"201 content = (202 '--{0}\r\nContent-Disposition: form-data; name="file"; '203 'filename="test.txt"\r\n'204 "Content-Type: text/plain\r\n\r\n{1}\r\n"205 "--{0}--\r\n"206 "".format(boundary, output).encode("ascii")207 )199- assert headers["Content-Length"] == str(len(content))200- assert b"".join(stream) == content208+ assert headers == {209+ "Content-Type": f"multipart/form-data; boundary={boundary}",210+ "Content-Length": str(len(content)),211+ }212+ assert content == b"".join(stream)213 214 215 def test_multipart_encode_non_seekable_filelike() -> None:216 """28 unmodified lines245 assert headers == {246 "Content-Type": "multipart/form-data; boundary=+++",247 "Content-Length": str(len(content)),248 }237- assert b"".join(stream) == content249+ assert content == b"".join(stream)250 251 252 class TestHeaderParamHTML5Formatting:253 def test_unicode(self):14 unmodified lines