Skip to content
Myr

Drop ContentStream (#1295)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Drop ContentStream

authored by Tom Christie · committed by GitHub · parent e1f7791 · Browse files · 15 files+416 added−311 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+416 added−311 removed

  • tests:+244 added−143 removed
  • other:+172 added−168 removed

15 files+416 added−311 removed

modified:docs/exceptions.md-4 removed
modified:httpx/__init__.py-2 removed
19 unmodified lines
20 ProxyError,21 ReadError,22 ReadTimeout,23 RemoteProtocolError,24 RequestBodyUnavailable,24 RequestError,25 RequestNotRead,26 ResponseClosed,27 ResponseNotRead,
54 unmodified lines
82 "ReadTimeout",83 "RemoteProtocolError",84 "request",85 "Request",87 "RequestBodyUnavailable",86 "RequestError",87 "RequestNotRead",88 "Response",89 "ResponseClosed",
21 unmodified lines
modified:httpx/_auth.py+1 added-8 removed
4 unmodified lines
5import typing6from base64 import b64encode7from urllib.request import parse_http_list89from ._exceptions import ProtocolError, RequestBodyUnavailable9from ._exceptions import ProtocolError10from ._models import Request, Response11from ._utils import to_bytes, to_str, unquote1213
142 unmodified lines
156 self._username = to_bytes(username)157 self._password = to_bytes(password)158159 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:160 if not request.stream.can_replay():161 raise RequestBodyUnavailable(162 "Cannot use digest auth with streaming requests that are unable "163 "to replay the request body if a second request is required.",164 request=request,165 )166160 response = yield request161162 if response.status_code != 401 or "www-authenticate" not in response.headers:163 # If the response is not a 401 then we don't
149 unmodified lines
modified:httpx/_client.py+19 added-14 removed
1import datetime2import functools3import typing4import warnings5from types import TracebackType
12 unmodified lines
18 Timeout,19 UnsetType,20 create_ssl_context,21)21from ._content_streams import ContentStream22from ._decoders import SUPPORTED_DECODERS23from ._exceptions import (24 HTTPCORE_EXC_MAP,25 InvalidURL,26 RemoteProtocolError,27 RequestBodyUnavailable,27 TooManyRedirects,28 map_exceptions,29)30from ._models import URL, Cookies, Headers, QueryParams, Request, Response
1 unmodified line
32from ._transports.asgi import ASGITransport33from ._transports.wsgi import WSGITransport34from ._types import (35 AuthTypes,36 ByteStream,37 CertTypes,38 CookieTypes,39 HeaderTypes,40 ProxiesTypes,
438 unmodified lines
479 return headers480481 def _redirect_stream(482 self, request: Request, method: str483 ) -> typing.Optional[ContentStream]:483 ) -> typing.Optional[ByteStream]:484 """485 Return the body that should be used for the redirect request.486 """487 if method != request.method and method == "GET":488 return None489490 if not request.stream.can_replay():491 raise RequestBodyUnavailable(492 "Got a redirect response, but the request body was streaming "493 "and is no longer available.",494 request=request,495 )496490 return request.stream491492493class Client(BaseClient):
362 unmodified lines
856 ) = transport.request(857 request.method.encode(),858 request.url.raw,859 headers=request.headers.raw,867 stream=request.stream,860 stream=request.stream, # type: ignore861 timeout=timeout.as_dict(),862 )863864 def on_close(response: Response) -> None:865 response.elapsed = datetime.timedelta(timer.sync_elapsed())866 if hasattr(stream, "close"):867 stream.close()868869 response = Response(870 status_code,871 http_version=http_version.decode("ascii"),872 headers=headers,873 stream=stream, # type: ignore874 request=request,876 elapsed_func=timer.sync_elapsed,875 on_close=on_close,876 )877878 self.cookies.extract_cookies(response)879
627 unmodified lines
1507 ) = await transport.request(1508 request.method.encode(),1509 request.url.raw,1510 headers=request.headers.raw,1512 stream=request.stream,1511 stream=request.stream, # type: ignore1512 timeout=timeout.as_dict(),1513 )15141515 async def on_close(response: Response) -> None:1516 response.elapsed = datetime.timedelta(await timer.async_elapsed())1517 if hasattr(stream, "close"):1518 await stream.aclose()15191520 response = Response(1521 status_code,1522 http_version=http_version.decode("ascii"),1523 headers=headers,1524 stream=stream, # type: ignore1525 request=request,1521 elapsed_func=timer.async_elapsed,1526 on_close=on_close,1527 )15281529 self.cookies.extract_cookies(response)1530
320 unmodified lines
modified:httpx/_content_streams.py+73 added-103 removed
1import binascii2import inspect3import os4import typing5from json import dumps as json_dumps6from pathlib import Path7from urllib.parse import urlencode88import httpcore99from ._exceptions import StreamConsumed10from ._types import (11 ByteStream,12 FileContent,13 FileTypes,14 RequestContent,15 RequestData,
7 unmodified lines
23 to_bytes,24)252627class ContentStream(httpcore.AsyncByteStream, httpcore.SyncByteStream):28 def get_headers(self) -> typing.Dict[str, str]:29 """30 Return a dictionary of headers that are implied by the encoding.31 """32 return {}3334 def can_replay(self) -> bool:35 """36 Return `True` if `__aiter__` can be called multiple times.3738 We need this in cases such determining if we can re-issue a request39 body when we receive a redirect response.40 """41 return True4243 def __iter__(self) -> typing.Iterator[bytes]:44 yield b""4546 def close(self) -> None:47 pass4849 async def __aiter__(self) -> typing.AsyncIterator[bytes]:50 yield b""5152 async def aclose(self) -> None:53 pass545556class ByteStream(ContentStream):27class PlainByteStream:28 """29 Request content encoded as plain bytes.30 """31
12 unmodified lines
44 async def __aiter__(self) -> typing.AsyncIterator[bytes]:45 yield self.body464777class IteratorStream(ContentStream):48class GeneratorStream:49 """79 Request content encoded as plain bytes, using an byte iterator.50 Request content encoded as plain bytes, using an byte generator.51 """5282 def __init__(self, iterator: typing.Iterator[bytes]) -> None:83 self.iterator = iterator84 self.is_stream_consumed = False53 def __init__(self, generator: typing.Iterable[bytes]) -> None:54 self._generator = generator55 self._is_stream_consumed = False5686 def can_replay(self) -> bool:87 return False8889 def get_headers(self) -> typing.Dict[str, str]:90 return {"Transfer-Encoding": "chunked"}9157 def __iter__(self) -> typing.Iterator[bytes]:93 if self.is_stream_consumed:58 if self._is_stream_consumed:59 raise StreamConsumed()95 self.is_stream_consumed = True96 for part in self.iterator:60 self._is_stream_consumed = True61 for part in self._generator:62 yield part6399 def __aiter__(self) -> typing.AsyncIterator[bytes]:100 raise RuntimeError("Attempted to call a async iterator on an sync stream.")64102103class AsyncIteratorStream(ContentStream):65class AsyncGeneratorStream:66 """67 Request content encoded as plain bytes, using an async byte iterator.68 """69108 def __init__(self, aiterator: typing.AsyncIterator[bytes]) -> None:109 self.aiterator = aiterator110 self.is_stream_consumed = False70 def __init__(self, agenerator: typing.AsyncIterable[bytes]) -> None:71 self._agenerator = agenerator72 self._is_stream_consumed = False73112 def can_replay(self) -> bool:113 return False114115 def get_headers(self) -> typing.Dict[str, str]:116 return {"Transfer-Encoding": "chunked"}117118 def __iter__(self) -> typing.Iterator[bytes]:119 raise RuntimeError("Attempted to call a sync iterator on an async stream.")12074 async def __aiter__(self) -> typing.AsyncIterator[bytes]:122 if self.is_stream_consumed:75 if self._is_stream_consumed:76 raise StreamConsumed()124 self.is_stream_consumed = True125 async for part in self.aiterator:77 self._is_stream_consumed = True78 async for part in self._agenerator:79 yield part8081129class JSONStream(ContentStream):82class JSONStream:83 """84 Request content encoded as JSON.85 """86
11 unmodified lines
98 async def __aiter__(self) -> typing.AsyncIterator[bytes]:99 yield self.body100101149class URLEncodedStream(ContentStream):102class URLEncodedStream:103 """104 Request content as URL encoded form data.105 """106
11 unmodified lines
118 async def __aiter__(self) -> typing.AsyncIterator[bytes]:119 yield self.body120121169class MultipartStream(ContentStream):122class MultipartStream:123 """124 Request content as streaming multipart encoded form data.125 """126
33 unmodified lines
160 headers = self.render_headers()161 data = self.render_data()162 return len(headers) + len(data)163211 def can_replay(self) -> bool:212 return True213164 def render(self) -> typing.Iterator[bytes]:165 yield self.render_headers()166 yield self.render_data()167
20 unmodified lines
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()196
37 unmodified lines
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)244290 # Get ready for the next replay, if possible.291 if self.can_replay():292 assert self.file.seekable()293 self.file.seek(0)294295 def can_replay(self) -> bool:296 return True if isinstance(self.file, (str, bytes)) else self.file.seekable()297245 def render(self) -> typing.Iterator[bytes]:246 yield self.render_headers()247 yield from self.render_data()248
43 unmodified lines
292 return sum(self.iter_chunks_lengths())293294 # Content stream interface.295349 def can_replay(self) -> bool:350 return all(field.can_replay() for field in self.fields)351296 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}
12 unmodified lines
312 data: RequestData = None,313 files: RequestFiles = None,314 json: typing.Any = None,315 boundary: bytes = None,372) -> ContentStream:316) -> typing.Tuple[typing.Dict[str, str], ByteStream]:317 """318 Handles encoding the given `content`, `data`, `files`, and `json`,375 returning a `ContentStream` implementation.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 or
6 unmodified lines
330 data = None331332 if content is not None:333 if isinstance(content, (str, bytes)):390 return ByteStream(body=content)391 elif hasattr(content, "__aiter__"):392 content = typing.cast(typing.AsyncIterator[bytes], content)393 return AsyncIteratorStream(aiterator=content)394 elif hasattr(content, "__iter__"):395 content = typing.cast(typing.Iterator[bytes], content)396 return IteratorStream(iterator=content)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:402 return MultipartStream(data=data, files=files, boundary=boundary)350 multipart_stream = MultipartStream(351 data=data, files=files, boundary=boundary352 )353 headers = multipart_stream.get_headers()354 return headers, multipart_stream355 else:404 return URLEncodedStream(data=data)356 urlencoded_stream = URLEncodedStream(data=data)357 headers = urlencoded_stream.get_headers()358 return headers, urlencoded_stream359360 elif files:407 return MultipartStream(data={}, files=files, boundary=boundary)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:410 return JSONStream(json=json)366 json_stream = JSONStream(json=json)367 headers = json_stream.get_headers()368 return headers, json_stream369412 return ByteStream(body=b"")370 byte_stream = PlainByteStream(body=b"")371 headers = byte_stream.get_headers()372 return headers, byte_stream373374415def encode_response(content: ResponseContent = None) -> ContentStream:375def encode_response(376 content: ResponseContent = None,377) -> typing.Tuple[typing.Dict[str, str], ByteStream]:378 if content is None:417 return ByteStream(b"")379 byte_stream = PlainByteStream(b"")380 headers = byte_stream.get_headers()381 return headers, byte_stream382 elif isinstance(content, bytes):419 return ByteStream(body=content)420 elif isinstance(content, typing.AsyncIterator):421 return AsyncIteratorStream(aiterator=content)422 elif isinstance(content, typing.Iterator):423 return IteratorStream(iterator=content)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}")
modified:httpx/_exceptions.py+7 added-10 removed
205 unmodified lines
206 Too many redirects.207 """208209210class RequestBodyUnavailable(RequestError):211 """212 Had to send the request again, but the request body was streaming, and is213 no longer available.214 """215216210# Client errors211212213class HTTPStatusError(HTTPError):
61 unmodified lines
275276277class StreamConsumed(StreamError):278 """286 Attempted to read or stream response content, but the content has already279 Attempted to read or stream content, but the content has already280 been streamed.281 """282283 def __init__(self) -> None:284 message = (292 "Attempted to read or stream response content, but the content has "293 "already been streamed."285 "Attempted to read or stream some content, but the content has "286 "already been streamed. For requests, this could be due to passing "287 "a generator as request content, and then receiving a redirect "288 "response or a secondary request as part of an authentication flow."289 "For responses, this could be due to attempting to stream the response "290 "content more than once."291 )292 super().__init__(message)293294
81 unmodified lines
modified:httpx/_models.py+67 added-23 removed
11 unmodified lines
1213import rfc398614import rfc3986.exceptions1516from ._content_streams import ByteStream, ContentStream, encode_request, encode_response16from ._content_streams import PlainByteStream, encode_request, encode_response17from ._decoders import (18 SUPPORTED_DECODERS,19 ContentDecoder,20 IdentityDecoder,
15 unmodified lines
36 map_exceptions,37)38from ._status_codes import codes39from ._types import (40 ByteStream,41 CookieTypes,42 HeaderTypes,43 PrimitiveData,44 QueryParamTypes,
561 unmodified lines
606 content: RequestContent = None,607 data: RequestData = None,608 files: RequestFiles = None,609 json: typing.Any = None,609 stream: ContentStream = None,610 stream: ByteStream = None,611 ):612 if isinstance(method, bytes):613 self.method = method.decode("ascii").upper()614 else:
3 unmodified lines
618 if cookies:619 Cookies(cookies).set_cookie_header(self)620621 if stream is not None:622 # There's an important distinction between `Request(content=...)`,623 # and `Request(stream=...)`.624 #625 # Using `content=...` implies automatically populated content headers,626 # of either `Content-Length: ...` or `Transfer-Encoding: chunked`.627 #628 # Using `stream=...` will not automatically include any content headers.629 #630 # As an end-user you don't really need `stream=...`. It's only631 # useful when:632 #633 # * Preserving the request stream when copying requests, eg for redirects.634 # * Creating request instances on the *server-side* of the transport API.635 self.stream = stream636 self._prepare({})637 else:623 self.stream = encode_request(content, data, files, json)638 headers, stream = encode_request(content, data, files, json)639 self._prepare(headers)640 self.stream = stream641625 self._prepare()626627 def _prepare(self) -> None:628 for key, value in self.stream.get_headers().items():642 def _prepare(self, default_headers: typing.Dict[str, str]) -> None:643 for key, value in default_headers.items():644 # Ignore Transfer-Encoding if the Content-Length has been set explicitly.645 if key.lower() == "transfer-encoding" and "content-length" in self.headers:646 continue647 self.headers.setdefault(key, value)
23 unmodified lines
671 """672 Read and return the request content.673 """674 if not hasattr(self, "_content"):675 assert isinstance(self.stream, typing.Iterable)676 self._content = b"".join(self.stream)677 # If a streaming request has been read entirely into memory, then678 # we can replace the stream with a raw bytes implementation,679 # to ensure that any non-replayable streams can still be used.664 self.stream = ByteStream(self._content)680 self.stream = PlainByteStream(self._content)681 return self._content682683 async def aread(self) -> bytes:684 """685 Read and return the request content.686 """687 if not hasattr(self, "_content"):688 assert isinstance(self.stream, typing.AsyncIterable)689 self._content = b"".join([part async for part in self.stream])690 # If a streaming request has been read entirely into memory, then691 # we can replace the stream with a raw bytes implementation,692 # to ensure that any non-replayable streams can still be used.676 self.stream = ByteStream(self._content)693 self.stream = PlainByteStream(self._content)694 return self._content695696 def __repr__(self) -> str:697 class_name = self.__class__.__name__
8 unmodified lines
706 *,707 request: Request = None,708 http_version: str = None,709 headers: HeaderTypes = None,693 stream: ContentStream = None,710 content: ResponseContent = None,711 stream: ByteStream = None,712 history: typing.List["Response"] = None,696 elapsed_func: typing.Callable = None,713 on_close: typing.Callable = None,714 ):715 self.status_code = status_code716 self.http_version = http_version717 self.headers = Headers(headers)
2 unmodified lines
720721 self.call_next: typing.Optional[typing.Callable] = None722723 self.history = [] if history is None else list(history)707 self._elapsed_func = elapsed_func724 self._on_close = on_close725726 self.is_closed = False727 self.is_stream_consumed = False728729 if stream is not None:730 # There's an important distinction between `Response(content=...)`,731 # and `Response(stream=...)`.732 #733 # Using `content=...` implies automatically populated content headers,734 # of either `Content-Length: ...` or `Transfer-Encoding: chunked`.735 #736 # Using `stream=...` will not automatically include any content headers.737 #738 # As an end-user you don't really need `stream=...`. It's only739 # useful when creating response instances having received a stream740 # from the transport API.712 self._raw_stream = stream741 self.stream = stream742 else:714 self._raw_stream = encode_response(content)743 headers, stream = encode_response(content)744 self._prepare(headers)745 self.stream = stream746 if content is None or isinstance(content, bytes):747 # Load the response body, except for streaming content.748 self.read()749750 self._num_bytes_downloaded = 0751752 def _prepare(self, default_headers: typing.Dict[str, str]) -> None:753 for key, value in default_headers.items():754 # Ignore Transfer-Encoding if the Content-Length has been set explicitly.755 if key.lower() == "transfer-encoding" and "content-length" in self.headers:756 continue757 self.headers.setdefault(key, value)758759 @property760 def elapsed(self) -> datetime.timedelta:761 """762 Returns the time taken for the complete request/response
3 unmodified lines
766 raise RuntimeError(767 "'.elapsed' may only be accessed after the response "768 "has been read or closed."769 )732 return datetime.timedelta(seconds=self._elapsed)770 return self._elapsed771772 @elapsed.setter773 def elapsed(self, elapsed: datetime.timedelta) -> None:774 self._elapsed = elapsed775776 @property777 def request(self) -> Request:778 """779 Returns the request instance associated to the current response.
224 unmodified lines
1004 if self.is_stream_consumed:1005 raise StreamConsumed()1006 if self.is_closed:1007 raise ResponseClosed()1008 if not isinstance(self.stream, typing.Iterable):1009 raise RuntimeError("Attempted to call a sync iterator on an async stream.")10101011 self.is_stream_consumed = True1012 self._num_bytes_downloaded = 01013 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):970 for part in self._raw_stream:1014 for part in self.stream:1015 self._num_bytes_downloaded += len(part)1016 yield part1017 self.close()1018
16 unmodified lines
1035 Automatically called if the response body is read to completion.1036 """1037 if not self.is_closed:1038 self.is_closed = True995 if self._elapsed_func is not None:996 self._elapsed = self._elapsed_func()997 self._raw_stream.close()1039 if self._on_close is not None:1040 self._on_close(self)10411042 async def aread(self) -> bytes:1043 """1044 Read and return the response content.
44 unmodified lines
1089 if self.is_stream_consumed:1090 raise StreamConsumed()1091 if self.is_closed:1092 raise ResponseClosed()1093 if not isinstance(self.stream, typing.AsyncIterable):1094 raise RuntimeError("Attempted to call a async iterator on a sync stream.")10951096 self.is_stream_consumed = True1097 self._num_bytes_downloaded = 01098 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1054 async for part in self._raw_stream:1099 async for part in self.stream:1100 self._num_bytes_downloaded += len(part)1101 yield part1102 await self.aclose()1103
15 unmodified lines
1119 Automatically called if the response body is read to completion.1120 """1121 if not self.is_closed:1122 self.is_closed = True1078 if self._elapsed_func is not None:1079 self._elapsed = await self._elapsed_func()1080 await self._raw_stream.aclose()1123 if self._on_close is not None:1124 await self._on_close(self)112511261127class Cookies(MutableMapping):1128 """
177 unmodified lines
modified:httpx/_types.py+5 added-4 removed
5 unmodified lines
6from http.cookiejar import CookieJar7from typing import (8 IO,9 TYPE_CHECKING,10 AsyncIterator,10 AsyncIterable,11 Callable,12 Dict,13 Iterator,13 Iterable,14 List,15 Mapping,16 Optional,17 Sequence,
47 unmodified lines
65 "Auth",66 None,67]6869RequestContent = Union[str, bytes, Iterator[bytes], AsyncIterator[bytes]]70ResponseContent = Union[bytes, Iterator[bytes], AsyncIterator[bytes]]69RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]70ResponseContent = Union[bytes, Iterable[bytes], AsyncIterable[bytes]]71ByteStream = Union[Iterable[bytes], AsyncIterable[bytes]]7273RequestData = dict7475FileContent = Union[IO[str], IO[bytes], str, bytes]
9 unmodified lines
modified:tests/client/test_auth.py+3 added-12 removed
11 unmodified lines
1213import pytest1415import httpx16from httpx import (17 URL,18 Auth,19 BasicAuth,20 DigestAuth,21 ProtocolError,22 Request,23 RequestBodyUnavailable,24 Response,25)16from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response17from tests.utils import AsyncMockTransport, MockTransport1819from ..common import FIXTURES_DIR20
586 unmodified lines
607@pytest.mark.asyncio608async def test_digest_auth_unavailable_streaming_body():609 url = "https://example.org/"610 auth = DigestAuth(username="tomchristie", password="password123")620 app = App()611 app = DigestApp()612613 async def streaming_body():614 yield b"Example request body" # pragma: nocover615616 async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:626 with pytest.raises(RequestBodyUnavailable):617 with pytest.raises(httpx.StreamConsumed):618 await client.post(url, data=streaming_body(), auth=auth)619620621@pytest.mark.asyncio
63 unmodified lines
modified:tests/client/test_redirects.py+1 added-1 removed
332 unmodified lines
333334 def streaming_body():335 yield b"Example request body" # pragma: nocover336337 with pytest.raises(httpx.RequestBodyUnavailable):337 with pytest.raises(httpx.StreamConsumed):338 client.post(url, content=streaming_body())339340341def test_cross_subdomain_redirect():
73 unmodified lines
modified:tests/models/test_requests.py+41 added-1 removed
1import typing23import pytest45import httpx6
12 unmodified lines
19 request = httpx.Request("POST", "http://example.org", content=b"test 123")20 assert request.headers["Content-Length"] == "8"212223def test_iterable_content():24 class Content:25 def __iter__(self):26 yield b"test 123" # pragma: nocover2728 request = httpx.Request("POST", "http://example.org", content=Content())29 assert request.headers == httpx.Headers(30 {"Host": "example.org", "Transfer-Encoding": "chunked"}31 )323334def test_generator_with_transfer_encoding_header():35 def content():36 yield b"test 123" # pragma: nocover3738 request = httpx.Request("POST", "http://example.org", content=content())39 assert request.headers == httpx.Headers(40 {"Host": "example.org", "Transfer-Encoding": "chunked"}41 )424344def test_generator_with_content_length_header():45 def content():46 yield b"test 123" # pragma: nocover4748 headers = {"Content-Length": "8"}49 request = httpx.Request(50 "POST", "http://example.org", content=content(), headers=headers51 )52 assert request.headers == httpx.Headers(53 {"Host": "example.org", "Content-Length": "8"}54 )555657def test_url_encoded_data():58 request = httpx.Request("POST", "http://example.org", data={"test": "123"})59 request.read()60
25 unmodified lines
86 # Ensure a request may still be streamed if it has been read.87 # Needed for cases such as authentication classes that read the request body.88 request = httpx.Request("POST", "http://example.org", json={"test": 123})89 request.read()90 assert request.stream is not None91 assert isinstance(request.stream, typing.Iterable)92 content = b"".join([part for part in request.stream])93 assert content == request.content9495
2 unmodified lines
98 # Ensure a request may still be streamed if it has been read.99 # Needed for cases such as authentication classes that read the request body.100 request = httpx.Request("POST", "http://example.org", json={"test": 123})101 await request.aread()102 assert request.stream is not None103 assert isinstance(request.stream, typing.AsyncIterable)104 content = b"".join([part async for part in request.stream])105 assert content == request.content106107108@pytest.mark.asyncio109async def test_cannot_access_content_without_read():110 # Ensure a request may still be streamed if it has been read.71 #  Needed for cases such as authentication classes that read the request body.111 # Needed for cases such as authentication classes that read the request body.112 request = httpx.Request("POST", "http://example.org", json={"test": 123})113 with pytest.raises(httpx.RequestNotRead):114 request.content115
66 unmodified lines
modified:tests/models/test_responses.py+87 added
5 unmodified lines
67import httpx8910class StreamingBody:11 def __iter__(self):12 yield b"Hello, "13 yield b"world!"141516def streaming_body():17 yield b"Hello, "18 yield b"world!"19
215 unmodified lines
235 assert response.content == b"Hello, world!"236 assert response.is_closed237238239def test_empty_read():240 response = httpx.Response(200)241242 assert response.status_code == 200243 assert response.text == ""244 assert response.encoding is None245 assert response.is_closed246247 content = response.read()248249 assert content == b""250 assert response.content == b""251 assert response.is_closed252253254@pytest.mark.asyncio255async def test_aread():256 response = httpx.Response(257 200,
11 unmodified lines
269 assert response.content == b"Hello, world!"270 assert response.is_closed271272273@pytest.mark.asyncio274async def test_empty_aread():275 response = httpx.Response(200)276277 assert response.status_code == 200278 assert response.text == ""279 assert response.encoding is None280 assert response.is_closed281282 content = await response.aread()283284 assert content == b""285 assert response.content == b""286 assert response.is_closed287288289def test_iter_raw():290 response = httpx.Response(291 200,292 content=streaming_body(),
4 unmodified lines
297 raw += part298 assert raw == b"Hello, world!"299300301def test_iter_raw_on_iterable():302 response = httpx.Response(303 200,304 content=StreamingBody(),305 )306307 raw = b""308 for part in response.iter_raw():309 raw += part310 assert raw == b"Hello, world!"311312313def test_iter_raw_on_async():314 response = httpx.Response(315 200,316 content=async_streaming_body(),317 )318319 with pytest.raises(RuntimeError):320 [part for part in response.iter_raw()]321322323def test_iter_raw_increments_updates_counter():324 response = httpx.Response(200, content=streaming_body())325326 num_downloaded = response.num_bytes_downloaded
12 unmodified lines
339 assert raw == b"Hello, world!"340341342@pytest.mark.asyncio343async def test_aiter_raw_on_sync():344 response = httpx.Response(345 200,346 content=streaming_body(),347 )348349 with pytest.raises(RuntimeError):350 [part async for part in response.aiter_raw()]351352353@pytest.mark.asyncio354async def test_aiter_raw_increments_updates_counter():355 response = httpx.Response(200, content=async_streaming_body())356357 num_downloaded = response.num_bytes_downloaded
321 unmodified lines
679 response = httpx.Response(200, content=b"Hello, world!")680681 with pytest.raises(RuntimeError):682 response.request683684685def test_generator_with_transfer_encoding_header():686 def content():687 yield b"test 123" # pragma: nocover688689 response = httpx.Response(200, content=content())690 assert response.headers == httpx.Headers({"Transfer-Encoding": "chunked"})691692693def test_generator_with_content_length_header():694 def content():695 yield b"test 123" # pragma: nocover696697 headers = {"Content-Length": "8"}698 response = httpx.Response(200, content=content(), headers=headers)699 assert response.headers == httpx.Headers({"Content-Length": "8"})
modified:tests/test_content_streams.py+87 added-76 removed
1import io2import typing34import pytest56from httpx import StreamConsumed6from httpx._content_streams import ContentStream, encode_request, encode_response7from httpx._content_streams import encode_request, encode_response8910@pytest.mark.asyncio10async def test_base_content():11 stream = ContentStream()12 sync_content = b"".join([part for part in stream])13 async_content = b"".join([part async for part in stream])1415 assert stream.can_replay()16 assert stream.get_headers() == {}17 assert sync_content == b""18 assert async_content == b""192021@pytest.mark.asyncio11async def test_empty_content():23 stream = encode_request()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])1827 assert stream.can_replay()28 assert stream.get_headers() == {}19 assert headers == {}20 assert sync_content == b""21 assert async_content == b""222324@pytest.mark.asyncio25async def test_bytes_content():35 stream = encode_request(content=b"Hello, world!")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])3239 assert stream.can_replay()40 assert stream.get_headers() == {"Content-Length": "13"}33 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.45 stream = encode_request(data=b"Hello, world!") # type: ignore38 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])4449 assert stream.can_replay()50 assert stream.get_headers() == {"Content-Length": "13"}45 assert headers == {"Content-Length": "13"}46 assert sync_content == b"Hello, world!"47 assert async_content == b"Hello, world!"4849
2 unmodified lines
52 def hello_world():53 yield b"Hello, "54 yield b"world!"5561 stream = encode_request(content=hello_world())56 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])6164 assert not stream.can_replay()65 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}62 assert headers == {"Transfer-Encoding": "chunked"}63 assert content == b"Hello, world!"6468 with pytest.raises(RuntimeError):69 [part async for part in stream]7065 with pytest.raises(StreamConsumed):66 [part for part in stream]6768 # Support 'data' for compat with requests.75 stream = encode_request(data=hello_world()) # type: ignore69 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])7478 assert not stream.can_replay()79 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}75 assert headers == {"Transfer-Encoding": "chunked"}76 assert content == b"Hello, world!"777879@pytest.mark.asyncio
1 unmodified line
81 async def hello_world():82 yield b"Hello, "83 yield b"world!"8489 stream = encode_request(content=hello_world())85 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])9092 assert not stream.can_replay()93 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}91 assert headers == {"Transfer-Encoding": "chunked"}92 assert content == b"Hello, world!"9396 with pytest.raises(RuntimeError):97 [part for part in stream]9894 with pytest.raises(StreamConsumed):95 [part async for part in stream]9697 # Support 'data' for compat with requests.103 stream = encode_request(data=hello_world()) # type: ignore98 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])103106 assert not stream.can_replay()107 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}104 assert headers == {"Transfer-Encoding": "chunked"}105 assert content == b"Hello, world!"106107108@pytest.mark.asyncio109async def test_json_content():113 stream = encode_request(json={"Hello": "world!"})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 stream.can_replay()118 assert stream.get_headers() == {117 assert headers == {118 "Content-Length": "19",119 "Content-Type": "application/json",120 }121 assert sync_content == b'{"Hello": "world!"}'
1 unmodified line
123124125@pytest.mark.asyncio126async def test_urlencoded_content():128 stream = encode_request(data={"Hello": "world!"})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])133132 assert stream.can_replay()133 assert stream.get_headers() == {134 assert headers == {135 "Content-Length": "14",136 "Content-Type": "application/x-www-form-urlencoded",137 }138 assert sync_content == b"Hello=world%21"
2 unmodified lines
141142@pytest.mark.asyncio143async def test_multipart_files_content():144 files = {"file": io.BytesIO(b"<file content>")}144 stream = encode_request(files=files, boundary=b"+++")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])151148 assert stream.can_replay()149 assert stream.get_headers() == {152 assert headers == {153 "Content-Length": "138",154 "Content-Type": "multipart/form-data; boundary=+++",155 }156 assert sync_content == b"".join(
21 unmodified lines
178@pytest.mark.asyncio179async def test_multipart_data_and_files_content():180 data = {"message": "Hello, world!"}181 files = {"file": io.BytesIO(b"<file content>")}179 stream = encode_request(data=data, files=files, boundary=b"+++")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])188183 assert stream.can_replay()184 assert stream.get_headers() == {189 assert headers == {190 "Content-Length": "210",191 "Content-Type": "multipart/form-data; boundary=+++",192 }193 assert sync_content == b"".join(
27 unmodified lines
221222223@pytest.mark.asyncio224async def test_empty_request():220 stream = encode_request(data={}, files={})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])231224 assert stream.can_replay()225 assert stream.get_headers() == {}232 assert headers == {}233 assert sync_content == b""234 assert async_content == b""235236
7 unmodified lines
244 files = [245 ("file", io.BytesIO(b"<file content 1>")),246 ("file", io.BytesIO(b"<file content 2>")),247 ]241 stream = encode_request(files=files, boundary=b"+++")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])254245 assert stream.can_replay()246 assert stream.get_headers() == {255 assert headers == {256 "Content-Length": "271",257 "Content-Type": "multipart/form-data; boundary=+++",258 }259 assert sync_content == b"".join(
29 unmodified lines
289290291@pytest.mark.asyncio292async def test_response_empty_content():284 stream = encode_response()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])299288 assert stream.can_replay()289 assert stream.get_headers() == {}300 assert headers == {}301 assert sync_content == b""302 assert async_content == b""303304305@pytest.mark.asyncio306async def test_response_bytes_content():296 stream = encode_response(content=b"Hello, world!")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])313300 assert stream.can_replay()301 assert stream.get_headers() == {"Content-Length": "13"}314 assert headers == {"Content-Length": "13"}315 assert sync_content == b"Hello, world!"316 assert async_content == b"Hello, world!"317318
2 unmodified lines
321 def hello_world():322 yield b"Hello, "323 yield b"world!"324312 stream = encode_response(content=hello_world())325 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])330315 assert not stream.can_replay()316 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}331 assert headers == {"Transfer-Encoding": "chunked"}332 assert content == b"Hello, world!"333319 with pytest.raises(RuntimeError):320 [part async for part in stream]321334 with pytest.raises(StreamConsumed):335 [part for part in stream]336337
2 unmodified lines
340 async def hello_world():341 yield b"Hello, "342 yield b"world!"343332 stream = encode_response(content=hello_world())344 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])349335 assert not stream.can_replay()336 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}350 assert headers == {"Transfer-Encoding": "chunked"}351 assert content == b"Hello, world!"352339 with pytest.raises(RuntimeError):340 [part for part in stream]341353 with pytest.raises(StreamConsumed):354 [part async for part in stream]355356
3 unmodified lines
modified:tests/test_multipart.py+9 added-16 removed
108 unmodified lines
109110 with mock.patch("os.urandom", return_value=os.urandom(16)):111 boundary = os.urandom(16).hex()112113 stream = encode_request(data=data, files=files)113 headers, stream = encode_request(data=data, files=files)114 assert isinstance(stream, MultipartStream)115 assert stream.can_replay()115116 assert stream.content_type == f"multipart/form-data; boundary={boundary}"117 content = (118 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'
7 unmodified lines
126 "Content-Type: text/plain\r\n\r\n<file content>\r\n"127 "--{0}--\r\n"128 "".format(boundary).encode("ascii")129 )131 assert stream.get_headers()["Content-Length"] == str(len(content))130 assert headers["Content-Length"] == str(len(content))131 assert b"".join(stream) == content132133134def test_multipart_encode_files_allows_filenames_as_none() -> None:135 files = {"file": (None, io.BytesIO(b"<file content>"))}136 with mock.patch("os.urandom", return_value=os.urandom(16)):137 boundary = os.urandom(16).hex()138140 stream = encode_request(data={}, files=files)139 headers, stream = encode_request(data={}, files=files)140 assert isinstance(stream, MultipartStream)142 assert stream.can_replay()141142 assert stream.content_type == f"multipart/form-data; boundary={boundary}"143 assert b"".join(stream) == (144 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'
16 unmodified lines
161 files = {"file": (file_name, io.BytesIO(b"<file content>"))}162 with mock.patch("os.urandom", return_value=os.urandom(16)):163 boundary = os.urandom(16).hex()164167 stream = encode_request(data={}, files=files)165 headers, stream = encode_request(data={}, files=files)166 assert isinstance(stream, MultipartStream)169 assert stream.can_replay()167168 assert stream.content_type == f"multipart/form-data; boundary={boundary}"169 assert b"".join(stream) == (170 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '
13 unmodified lines
184 files = {"file": ("test.txt", value, "text/plain")}185 with mock.patch("os.urandom", return_value=os.urandom(16)):186 boundary = os.urandom(16).hex()187191 stream = encode_request(data={}, files=files)188 headers, stream = encode_request(data={}, files=files)189 assert isinstance(stream, MultipartStream)193 assert stream.can_replay()190191 assert stream.content_type == f"multipart/form-data; boundary={boundary}"192 content = (193 '--{0}\r\nContent-Disposition: form-data; name="file"; '
1 unmodified line
195 "Content-Type: text/plain\r\n\r\n{1}\r\n"196 "--{0}--\r\n"197 "".format(boundary, output).encode("ascii")198 )203 assert stream.get_headers()["Content-Length"] == str(len(content))199 assert headers["Content-Length"] == str(len(content))200 assert b"".join(stream) == content201202203def test_multipart_encode_non_seekable_filelike() -> None:
5 unmodified lines
209 class IteratorIO(io.IOBase):210 def __init__(self, iterator: typing.Iterator[bytes]) -> None:211 self._iterator = iterator212217 def seekable(self) -> bool:218 return False219213 def read(self, *args: typing.Any) -> bytes:214 return b"".join(self._iterator)215216 def data() -> typing.Iterator[bytes]:
1 unmodified line
218 yield b"World"219220 fileobj: typing.Any = IteratorIO(data())221 files = {"file": fileobj}229 stream = encode_request(files=files, boundary=b"+++")230 assert not stream.can_replay()222 headers, stream = encode_request(files=files, boundary=b"+++")223 assert isinstance(stream, typing.Iterable)224225 content = (226 b"--+++\r\n"227 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'
1 unmodified line
229 b"\r\n"230 b"HelloWorld\r\n"231 b"--+++--\r\n"232 )240 assert stream.get_headers() == {233 assert headers == {234 "Content-Type": "multipart/form-data; boundary=+++",235 "Content-Length": str(len(content)),236 }237 assert b"".join(stream) == content
18 unmodified lines
modified:tests/utils.py+16 added-37 removed
34 unmodified lines
35 headers: List[Tuple[bytes, bytes]] = None,36 stream: httpcore.SyncByteStream = None,37 timeout: Mapping[str, Optional[float]] = None,38 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:39 request_headers = httpx.Headers(headers)40 content = (41 (item for item in stream)42 if stream43 and (44 "Content-Length" in request_headers45 or "Transfer-Encoding" in request_headers46 )47 else None48 )4939 request = httpx.Request(40 method=method,41 url=url,53 headers=request_headers,54 content=content,42 headers=headers,43 stream=stream,44 )45 request.read()46 response = self.handler(request)47 return (48 (response.http_version or "HTTP/1.1").encode("ascii"),49 response.status_code,50 response.reason_phrase.encode("ascii"),51 response.headers.raw,63 response._raw_stream,52 response.stream,53 )545556class AsyncMockTransport(httpcore.AsyncHTTPTransport):57 def __init__(self, handler: Callable) -> None:69 self.impl = MockTransport(handler)58 self.handler = handler5960 async def request(61 self,62 method: bytes,
1 unmodified line
64 headers: List[Tuple[bytes, bytes]] = None,65 stream: httpcore.AsyncByteStream = None,66 timeout: Mapping[str, Optional[float]] = None,67 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:79 content = (80 httpcore.PlainByteStream(b"".join([part async for part in stream]))81 if stream82 else httpcore.PlainByteStream(b"")68 request = httpx.Request(69 method=method,70 url=url,71 headers=headers,72 stream=stream,73 )8485 (86 http_version,87 status_code,88 reason_phrase,89 headers,90 response_stream,91 ) = self.impl.request(92 method, url, headers=headers, stream=content, timeout=timeout93 )9495 content = httpcore.PlainByteStream(b"".join([part for part in response_stream]))9674 await request.aread()75 response = self.handler(request)76 return (98 http_version,99 status_code,100 reason_phrase,101 headers,102 content,77 (response.http_version or "HTTP/1.1").encode("ascii"),78 response.status_code,79 response.reason_phrase.encode("ascii"),80 response.headers.raw,81 response.stream,82 )