Skip to content
Myr

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

8 files+756 added−773 removed

deleted:httpx/_content_streams.py-395 removed
1import binascii2import inspect3import os4import typing5from json import dumps as json_dumps6from pathlib import Path7from urllib.parse import urlencode89from ._exceptions import StreamConsumed10from ._types import (11 ByteStream,12 FileContent,13 FileTypes,14 RequestContent,15 RequestData,16 RequestFiles,17 ResponseContent,18)19from ._utils import (20 format_form_param,21 guess_content_type,22 peek_filelike_length,23 to_bytes,24)252627class PlainByteStream:28 """29 Request content encoded as plain bytes.30 """3132 def __init__(self, body: typing.Union[str, bytes]) -> None:33 self.body = body.encode("utf-8") if isinstance(body, str) else body3435 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}4041 def __iter__(self) -> typing.Iterator[bytes]:42 yield self.body4344 async def __aiter__(self) -> typing.AsyncIterator[bytes]:45 yield self.body464748class GeneratorStream:49 """50 Request content encoded as plain bytes, using an byte generator.51 """5253 def __init__(self, generator: typing.Iterable[bytes]) -> None:54 self._generator = generator55 self._is_stream_consumed = False5657 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 part636465class AsyncGeneratorStream:66 """67 Request content encoded as plain bytes, using an async byte iterator.68 """6970 def __init__(self, agenerator: typing.AsyncIterable[bytes]) -> None:71 self._agenerator = agenerator72 self._is_stream_consumed = False7374 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 part808182class JSONStream:83 """84 Request content encoded as JSON.85 """8687 def __init__(self, json: typing.Any) -> None:88 self.body = json_dumps(json).encode("utf-8")8990 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}9495 def __iter__(self) -> typing.Iterator[bytes]:96 yield self.body9798 async def __aiter__(self) -> typing.AsyncIterator[bytes]:99 yield self.body100101102class URLEncodedStream:103 """104 Request content as URL encoded form data.105 """106107 def __init__(self, data: dict) -> None:108 self.body = urlencode(data, doseq=True).encode("utf-8")109110 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}114115 def __iter__(self) -> typing.Iterator[bytes]:116 yield self.body117118 async def __aiter__(self) -> typing.AsyncIterator[bytes]:119 yield self.body120121122class MultipartStream:123 """124 Request content as streaming multipart encoded form data.125 """126127 class DataField:128 """129 A single form field item, within a multipart form field.130 """131132 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 = value139140 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 )146147 return self._headers148149 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 )156157 return self._data158159 def get_length(self) -> int:160 headers = self.render_headers()161 data = self.render_data()162 return len(headers) + len(data)163164 def render(self) -> typing.Iterator[bytes]:165 yield self.render_headers()166 yield self.render_data()167168 class FileField:169 """170 A single file field item, within a multipart form field.171 """172173 def __init__(self, name: str, value: FileTypes) -> None:174 self.name = name175176 fileobj: FileContent177178 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)188189 self.filename = filename190 self.file = fileobj191 self.content_type = content_type192 self._consumed = False193194 def get_length(self) -> int:195 headers = self.render_headers()196197 if isinstance(self.file, (str, bytes)):198 return len(headers) + len(self.file)199200 # 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)208209 return len(headers) + file_length210211 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)225226 return self._headers227228 def render_data(self) -> typing.Iterator[bytes]:229 if isinstance(self.file, (str, bytes)):230 yield to_bytes(self.file)231 return232233 if hasattr(self, "_data"):234 # Already rendered.235 yield self._data236 return237238 if self._consumed: # pragma: nocover239 self.file.seek(0)240 self._consumed = True241242 for chunk in self.file:243 yield to_bytes(chunk)244245 def render(self) -> typing.Iterator[bytes]:246 yield self.render_headers()247 yield from self.render_data()248249 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))254255 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))260261 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)270271 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)274275 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.boundary281282 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 + 4290291 def get_content_length(self) -> int:292 return sum(self.iter_chunks_lengths())293294 # Content stream interface.295296 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}300301 def __iter__(self) -> typing.Iterator[bytes]:302 for chunk in self.iter_chunks():303 yield chunk304305 async def __aiter__(self) -> typing.AsyncIterator[bytes]:306 for chunk in self.iter_chunks():307 yield chunk308309310def 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 = None331332 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}")347348 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_stream359360 elif files:361 multipart_stream = MultipartStream(data={}, files=files, boundary=boundary)362 headers = multipart_stream.get_headers()363 return headers, multipart_stream364365 elif json is not None:366 json_stream = JSONStream(json=json)367 headers = json_stream.get_headers()368 return headers, json_stream369370 byte_stream = PlainByteStream(body=b"")371 headers = byte_stream.get_headers()372 return headers, byte_stream373374375def 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: ignore394395 raise TypeError(f"Unexpected type for 'content', {type(content)!r}")
added:httpx/_content.py+166 added
1import inspect2import typing3from json import dumps as json_dumps4from urllib.parse import urlencode56from ._exceptions import StreamConsumed7from ._multipart import MultipartStream8from ._types import (9 ByteStream,10 RequestContent,11 RequestData,12 RequestFiles,13 ResponseContent,14)151617class PlainByteStream:18 """19 Request content encoded as plain bytes.20 """2122 def __init__(self, body: bytes) -> None:23 self._body = body2425 def __iter__(self) -> typing.Iterator[bytes]:26 yield self._body2728 async def __aiter__(self) -> typing.AsyncIterator[bytes]:29 yield self._body303132class GeneratorStream:33 """34 Request content encoded as plain bytes, using an byte generator.35 """3637 def __init__(self, generator: typing.Iterable[bytes]) -> None:38 self._generator = generator39 self._is_stream_consumed = False4041 def __iter__(self) -> typing.Iterator[bytes]:42 if self._is_stream_consumed:43 raise StreamConsumed()4445 self._is_stream_consumed = True46 for part in self._generator:47 yield part484950class AsyncGeneratorStream:51 """52 Request content encoded as plain bytes, using an async byte iterator.53 """5455 def __init__(self, agenerator: typing.AsyncIterable[bytes]) -> None:56 self._agenerator = agenerator57 self._is_stream_consumed = False5859 async def __aiter__(self) -> typing.AsyncIterator[bytes]:60 if self._is_stream_consumed:61 raise StreamConsumed()6263 self._is_stream_consumed = True64 async for part in self._agenerator:65 yield part666768def 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, stream7778 elif isinstance(content, (typing.Iterable, typing.AsyncIterable)):79 headers = {"Transfer-Encoding": "chunked"}8081 # 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_stream9091 # Other iterables may be passed through as-is.92 return headers, content # type: ignore9394 raise TypeError(f"Unexpected type for 'content', {type(content)!r}")959697def 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)105106107def 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, stream113114115def 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)121122123def 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)143144 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)152153 return {}, PlainByteStream(b"")154155156def 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)165166 return {}, PlainByteStream(b"")
modified:httpx/_models.py+1 added-1 removed
11 unmodified lines
1213import rfc398614import rfc3986.exceptions1516from ._content_streams import PlainByteStream, encode_request, encode_response16from ._content import PlainByteStream, encode_request, encode_response17from ._decoders import (18 SUPPORTED_DECODERS,19 ContentDecoder,20 IdentityDecoder,
1285 unmodified lines
added:httpx/_multipart.py+200 added
1import binascii2import os3import typing4from pathlib import Path56from ._types import FileContent, FileTypes, RequestFiles7from ._utils import (8 format_form_param,9 guess_content_type,10 peek_filelike_length,11 to_bytes,12)131415class DataField:16 """17 A single form field item, within a multipart form field.18 """1920 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 = value2728 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 )3435 return self._headers3637 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 )4445 return self._data4647 def get_length(self) -> int:48 headers = self.render_headers()49 data = self.render_data()50 return len(headers) + len(data)5152 def render(self) -> typing.Iterator[bytes]:53 yield self.render_headers()54 yield self.render_data()555657class FileField:58 """59 A single file field item, within a multipart form field.60 """6162 def __init__(self, name: str, value: FileTypes) -> None:63 self.name = name6465 fileobj: FileContent6667 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)7778 self.filename = filename79 self.file = fileobj80 self.content_type = content_type81 self._consumed = False8283 def get_length(self) -> int:84 headers = self.render_headers()8586 if isinstance(self.file, (str, bytes)):87 return len(headers) + len(self.file)8889 # 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)9798 return len(headers) + file_length99100 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)114115 return self._headers116117 def render_data(self) -> typing.Iterator[bytes]:118 if isinstance(self.file, (str, bytes)):119 yield to_bytes(self.file)120 return121122 if hasattr(self, "_data"):123 # Already rendered.124 yield self._data125 return126127 if self._consumed: # pragma: nocover128 self.file.seek(0)129 self._consumed = True130131 for chunk in self.file:132 yield to_bytes(chunk)133134 def render(self) -> typing.Iterator[bytes]:135 yield self.render_headers()136 yield from self.render_data()137138139class MultipartStream:140 """141 Request content as streaming multipart encoded form data.142 """143144 def __init__(self, data: dict, files: RequestFiles, boundary: bytes = None) -> None:145 if boundary is None:146 boundary = binascii.hexlify(os.urandom(16))147148 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))153154 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)163164 file_items = files.items() if isinstance(files, typing.Mapping) else files165 for name, value in file_items:166 yield FileField(name=name, value=value)167168 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.boundary174175 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 + 4183184 def get_content_length(self) -> int:185 return sum(self.iter_chunks_lengths())186187 # Content stream interface.188189 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}193194 def __iter__(self) -> typing.Iterator[bytes]:195 for chunk in self.iter_chunks():196 yield chunk197198 async def __aiter__(self) -> typing.AsyncIterator[bytes]:199 for chunk in self.iter_chunks():200 yield chunk
modified:httpx/_types.py+2 added-2 removed
64 unmodified lines
65 "Auth",66 None,67]6869RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]70ResponseContent = Union[bytes, Iterable[bytes], AsyncIterable[bytes]]69ByteStream = Union[Iterable[bytes], AsyncIterable[bytes]]70RequestContent = Union[str, bytes, ByteStream]71ResponseContent = Union[str, bytes, ByteStream]7273RequestData = dict7475FileContent = Union[IO[str], IO[bytes], str, bytes]
9 unmodified lines
deleted:tests/test_content_streams.py-359 removed
1import io2import typing34import pytest56from httpx import StreamConsumed7from httpx._content_streams import encode_request, encode_response8910@pytest.mark.asyncio11async def test_empty_content():12 headers, stream = encode_request()13 assert isinstance(stream, typing.Iterable)14 assert isinstance(stream, typing.AsyncIterable)1516 sync_content = b"".join([part for part in stream])17 async_content = b"".join([part async for part in stream])1819 assert headers == {}20 assert sync_content == b""21 assert async_content == b""222324@pytest.mark.asyncio25async 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)2930 sync_content = b"".join([part for part in stream])31 async_content = b"".join([part async for part in stream])3233 assert headers == {"Content-Length": "13"}34 assert sync_content == b"Hello, world!"35 assert async_content == b"Hello, world!"3637 # 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)4142 sync_content = b"".join([part for part in stream])43 async_content = b"".join([part async for part in stream])4445 assert headers == {"Content-Length": "13"}46 assert sync_content == b"Hello, world!"47 assert async_content == b"Hello, world!"484950@pytest.mark.asyncio51async def test_iterator_content():52 def hello_world():53 yield b"Hello, "54 yield b"world!"5556 headers, stream = encode_request(content=hello_world())57 assert isinstance(stream, typing.Iterable)58 assert not isinstance(stream, typing.AsyncIterable)5960 content = b"".join([part for part in stream])6162 assert headers == {"Transfer-Encoding": "chunked"}63 assert content == b"Hello, world!"6465 with pytest.raises(StreamConsumed):66 [part for part in stream]6768 # 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)7273 content = b"".join([part for part in stream])7475 assert headers == {"Transfer-Encoding": "chunked"}76 assert content == b"Hello, world!"777879@pytest.mark.asyncio80async def test_aiterator_content():81 async def hello_world():82 yield b"Hello, "83 yield b"world!"8485 headers, stream = encode_request(content=hello_world())86 assert not isinstance(stream, typing.Iterable)87 assert isinstance(stream, typing.AsyncIterable)8889 content = b"".join([part async for part in stream])9091 assert headers == {"Transfer-Encoding": "chunked"}92 assert content == b"Hello, world!"9394 with pytest.raises(StreamConsumed):95 [part async for part in stream]9697 # 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)101102 content = b"".join([part async for part in stream])103104 assert headers == {"Transfer-Encoding": "chunked"}105 assert content == b"Hello, world!"106107108@pytest.mark.asyncio109async def test_json_content():110 headers, stream = encode_request(json={"Hello": "world!"})111 assert isinstance(stream, typing.Iterable)112 assert isinstance(stream, typing.AsyncIterable)113114 sync_content = b"".join([part for part in stream])115 async_content = b"".join([part async for part in stream])116117 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!"}'123124125@pytest.mark.asyncio126async def test_urlencoded_content():127 headers, stream = encode_request(data={"Hello": "world!"})128 assert isinstance(stream, typing.Iterable)129 assert isinstance(stream, typing.AsyncIterable)130131 sync_content = b"".join([part for part in stream])132 async_content = b"".join([part async for part in stream])133134 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"140141142@pytest.mark.asyncio143async 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)148149 sync_content = b"".join([part for part in stream])150 async_content = b"".join([part async for part in stream])151152 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 )176177178@pytest.mark.asyncio179async 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)185186 sync_content = b"".join([part for part in stream])187 async_content = b"".join([part async for part in stream])188189 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 )221222223@pytest.mark.asyncio224async def test_empty_request():225 headers, stream = encode_request(data={}, files={})226 assert isinstance(stream, typing.Iterable)227 assert isinstance(stream, typing.AsyncIterable)228229 sync_content = b"".join([part for part in stream])230 async_content = b"".join([part async for part in stream])231232 assert headers == {}233 assert sync_content == b""234 assert async_content == b""235236237def test_invalid_argument():238 with pytest.raises(TypeError):239 encode_request(123) # type: ignore240241242@pytest.mark.asyncio243async 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)251252 sync_content = b"".join([part for part in stream])253 async_content = b"".join([part async for part in stream])254255 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 )289290291@pytest.mark.asyncio292async def test_response_empty_content():293 headers, stream = encode_response()294 assert isinstance(stream, typing.Iterable)295 assert isinstance(stream, typing.AsyncIterable)296297 sync_content = b"".join([part for part in stream])298 async_content = b"".join([part async for part in stream])299300 assert headers == {}301 assert sync_content == b""302 assert async_content == b""303304305@pytest.mark.asyncio306async 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)310311 sync_content = b"".join([part for part in stream])312 async_content = b"".join([part async for part in stream])313314 assert headers == {"Content-Length": "13"}315 assert sync_content == b"Hello, world!"316 assert async_content == b"Hello, world!"317318319@pytest.mark.asyncio320async def test_response_iterator_content():321 def hello_world():322 yield b"Hello, "323 yield b"world!"324325 headers, stream = encode_response(content=hello_world())326 assert isinstance(stream, typing.Iterable)327 assert not isinstance(stream, typing.AsyncIterable)328329 content = b"".join([part for part in stream])330331 assert headers == {"Transfer-Encoding": "chunked"}332 assert content == b"Hello, world!"333334 with pytest.raises(StreamConsumed):335 [part for part in stream]336337338@pytest.mark.asyncio339async def test_response_aiterator_content():340 async def hello_world():341 yield b"Hello, "342 yield b"world!"343344 headers, stream = encode_response(content=hello_world())345 assert not isinstance(stream, typing.Iterable)346 assert isinstance(stream, typing.AsyncIterable)347348 content = b"".join([part async for part in stream])349350 assert headers == {"Transfer-Encoding": "chunked"}351 assert content == b"Hello, world!"352353 with pytest.raises(StreamConsumed):354 [part async for part in stream]355356357def test_response_invalid_argument():358 with pytest.raises(TypeError):359 encode_response(123) # type: ignore
added:tests/test_content.py+359 added
1import io2import typing34import pytest56from httpx import StreamConsumed7from httpx._content import encode_request, encode_response8910@pytest.mark.asyncio11async def test_empty_content():12 headers, stream = encode_request()13 assert isinstance(stream, typing.Iterable)14 assert isinstance(stream, typing.AsyncIterable)1516 sync_content = b"".join([part for part in stream])17 async_content = b"".join([part async for part in stream])1819 assert headers == {}20 assert sync_content == b""21 assert async_content == b""222324@pytest.mark.asyncio25async 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)2930 sync_content = b"".join([part for part in stream])31 async_content = b"".join([part async for part in stream])3233 assert headers == {"Content-Length": "13"}34 assert sync_content == b"Hello, world!"35 assert async_content == b"Hello, world!"3637 # 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)4142 sync_content = b"".join([part for part in stream])43 async_content = b"".join([part async for part in stream])4445 assert headers == {"Content-Length": "13"}46 assert sync_content == b"Hello, world!"47 assert async_content == b"Hello, world!"484950@pytest.mark.asyncio51async def test_iterator_content():52 def hello_world():53 yield b"Hello, "54 yield b"world!"5556 headers, stream = encode_request(content=hello_world())57 assert isinstance(stream, typing.Iterable)58 assert not isinstance(stream, typing.AsyncIterable)5960 content = b"".join([part for part in stream])6162 assert headers == {"Transfer-Encoding": "chunked"}63 assert content == b"Hello, world!"6465 with pytest.raises(StreamConsumed):66 [part for part in stream]6768 # 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)7273 content = b"".join([part for part in stream])7475 assert headers == {"Transfer-Encoding": "chunked"}76 assert content == b"Hello, world!"777879@pytest.mark.asyncio80async def test_aiterator_content():81 async def hello_world():82 yield b"Hello, "83 yield b"world!"8485 headers, stream = encode_request(content=hello_world())86 assert not isinstance(stream, typing.Iterable)87 assert isinstance(stream, typing.AsyncIterable)8889 content = b"".join([part async for part in stream])9091 assert headers == {"Transfer-Encoding": "chunked"}92 assert content == b"Hello, world!"9394 with pytest.raises(StreamConsumed):95 [part async for part in stream]9697 # 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)101102 content = b"".join([part async for part in stream])103104 assert headers == {"Transfer-Encoding": "chunked"}105 assert content == b"Hello, world!"106107108@pytest.mark.asyncio109async def test_json_content():110 headers, stream = encode_request(json={"Hello": "world!"})111 assert isinstance(stream, typing.Iterable)112 assert isinstance(stream, typing.AsyncIterable)113114 sync_content = b"".join([part for part in stream])115 async_content = b"".join([part async for part in stream])116117 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!"}'123124125@pytest.mark.asyncio126async def test_urlencoded_content():127 headers, stream = encode_request(data={"Hello": "world!"})128 assert isinstance(stream, typing.Iterable)129 assert isinstance(stream, typing.AsyncIterable)130131 sync_content = b"".join([part for part in stream])132 async_content = b"".join([part async for part in stream])133134 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"140141142@pytest.mark.asyncio143async 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)148149 sync_content = b"".join([part for part in stream])150 async_content = b"".join([part async for part in stream])151152 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 )176177178@pytest.mark.asyncio179async 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)185186 sync_content = b"".join([part for part in stream])187 async_content = b"".join([part async for part in stream])188189 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 )221222223@pytest.mark.asyncio224async def test_empty_request():225 headers, stream = encode_request(data={}, files={})226 assert isinstance(stream, typing.Iterable)227 assert isinstance(stream, typing.AsyncIterable)228229 sync_content = b"".join([part for part in stream])230 async_content = b"".join([part async for part in stream])231232 assert headers == {}233 assert sync_content == b""234 assert async_content == b""235236237def test_invalid_argument():238 with pytest.raises(TypeError):239 encode_request(123) # type: ignore240241242@pytest.mark.asyncio243async 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)251252 sync_content = b"".join([part for part in stream])253 async_content = b"".join([part async for part in stream])254255 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 )289290291@pytest.mark.asyncio292async def test_response_empty_content():293 headers, stream = encode_response()294 assert isinstance(stream, typing.Iterable)295 assert isinstance(stream, typing.AsyncIterable)296297 sync_content = b"".join([part for part in stream])298 async_content = b"".join([part async for part in stream])299300 assert headers == {}301 assert sync_content == b""302 assert async_content == b""303304305@pytest.mark.asyncio306async 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)310311 sync_content = b"".join([part for part in stream])312 async_content = b"".join([part async for part in stream])313314 assert headers == {"Content-Length": "13"}315 assert sync_content == b"Hello, world!"316 assert async_content == b"Hello, world!"317318319@pytest.mark.asyncio320async def test_response_iterator_content():321 def hello_world():322 yield b"Hello, "323 yield b"world!"324325 headers, stream = encode_response(content=hello_world())326 assert isinstance(stream, typing.Iterable)327 assert not isinstance(stream, typing.AsyncIterable)328329 content = b"".join([part for part in stream])330331 assert headers == {"Transfer-Encoding": "chunked"}332 assert content == b"Hello, world!"333334 with pytest.raises(StreamConsumed):335 [part for part in stream]336337338@pytest.mark.asyncio339async def test_response_aiterator_content():340 async def hello_world():341 yield b"Hello, "342 yield b"world!"343344 headers, stream = encode_response(content=hello_world())345 assert not isinstance(stream, typing.Iterable)346 assert isinstance(stream, typing.AsyncIterable)347348 content = b"".join([part async for part in stream])349350 assert headers == {"Transfer-Encoding": "chunked"}351 assert content == b"Hello, world!"352353 with pytest.raises(StreamConsumed):354 [part async for part in stream]355356357def test_response_invalid_argument():358 with pytest.raises(TypeError):359 encode_response(123) # type: ignore
modified:tests/test_multipart.py+28 added-16 removed
5 unmodified lines
67import pytest89import httpx10from httpx._content_streams import MultipartStream, encode_request10from httpx._content import encode_request11from httpx._utils import format_form_param12from tests.utils import MockTransport1314
95 unmodified lines
110 with mock.patch("os.urandom", return_value=os.urandom(16)):111 boundary = os.urandom(16).hex()112113 headers, stream = encode_request(data=data, files=files)114 assert isinstance(stream, MultipartStream)114 assert isinstance(stream, typing.Iterable)115116 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 lines
125 "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)134135136def 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()140141 headers, stream = encode_request(data={}, files=files)140 assert isinstance(stream, MultipartStream)142 assert isinstance(stream, typing.Iterable)143142 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)154155156@pytest.mark.parametrize(157 "file_name,expected_content_type",
10 unmodified lines
168 with mock.patch("os.urandom", return_value=os.urandom(16)):169 boundary = os.urandom(16).hex()170171 headers, stream = encode_request(data={}, files=files)166 assert isinstance(stream, MultipartStream)172 assert isinstance(stream, typing.Iterable)173168 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)185186187@pytest.mark.parametrize(188 "value, output",
6 unmodified lines
195 with mock.patch("os.urandom", return_value=os.urandom(16)):196 boundary = os.urandom(16).hex()197198 headers, stream = encode_request(data={}, files=files)189 assert isinstance(stream, MultipartStream)199 assert isinstance(stream, typing.Iterable)200191 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)213214215def test_multipart_encode_non_seekable_filelike() -> None:216 """
28 unmodified lines
245 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)250251252class TestHeaderParamHTML5Formatting:253 def test_unicode(self):
14 unmodified lines