Skip to content
Myr

Adds check to enforce single consumption of AsyncIteratorStream. (#697)

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

authored by Gabriel Strauss · committed by Tom Christie · parent 35b7516 · Browse files · 2 files+21 added−0 removed
This commit

State

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

Diff stats

2 files+21 added−0 removed

  • tests:+16 added−0 removed
  • other:+5 added−0 removed

2 files+21 added−0 removed

modified:httpx/content_streams.py+5 added
5 unmodified lines
6from json import dumps as json_dumps7from pathlib import Path8from urllib.parse import urlencode910from .exceptions import StreamConsumed11from .utils import format_form_param1213RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]14
66 unmodified lines
81 self, aiterator: typing.AsyncIterator[bytes], close_func: typing.Callable = None82 ) -> None:83 self.aiterator = aiterator84 self.close_func = close_func85 self.is_stream_consumed = False8687 def can_replay(self) -> bool:88 return False8990 def get_headers(self) -> typing.Dict[str, str]:91 return {"Transfer-Encoding": "chunked"}9293 async def __aiter__(self) -> typing.AsyncIterator[bytes]:94 if self.is_stream_consumed:95 raise StreamConsumed()96 self.is_stream_consumed = True97 async for part in self.aiterator:98 yield part99100 async def aclose(self) -> None:
184 unmodified lines
modified:tests/test_content_streams.py+16 added
1 unmodified line
23import pytest45from httpx.content_streams import encode6from httpx.exceptions import StreamConsumed789@pytest.mark.asyncio10async def test_empty_content():
29 unmodified lines
40 assert content == b"Hello, world!"414243@pytest.mark.asyncio44async def test_aiterator_is_stream_consumed():45 async def hello_world():46 yield b"Hello, "47 yield b"world!"4849 stream = encode(data=hello_world())50 b"".join([part async for part in stream])5152 assert stream.is_stream_consumed5354 with pytest.raises(StreamConsumed) as _:55 b"".join([part async for part in stream])565758@pytest.mark.asyncio59async def test_json_content():60 stream = encode(json={"Hello": "world!"})61 content = b"".join([part async for part in stream])62
70 unmodified lines