Skip to content

Commit 420911b

Browse files
Ensure that iter_bytes does not ever yield any zero-length chunks (#2068)
1 parent 0088253 commit 420911b

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

httpx/_decoders.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def __init__(self, chunk_size: int = None) -> None:
172172

173173
def decode(self, content: bytes) -> typing.List[bytes]:
174174
if self._chunk_size is None:
175-
return [content]
175+
return [content] if content else []
176176

177177
self._buffer.write(content)
178178
if self._buffer.tell() >= self._chunk_size:

httpx/_models.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1585,7 +1585,7 @@ def iter_bytes(self, chunk_size: int = None) -> typing.Iterator[bytes]:
15851585
yield chunk
15861586
decoded = decoder.flush()
15871587
for chunk in chunker.decode(decoded):
1588-
yield chunk
1588+
yield chunk # pragma: nocover
15891589
for chunk in chunker.flush():
15901590
yield chunk
15911591

@@ -1683,7 +1683,7 @@ async def aiter_bytes(self, chunk_size: int = None) -> typing.AsyncIterator[byte
16831683
yield chunk
16841684
decoded = decoder.flush()
16851685
for chunk in chunker.decode(decoded):
1686-
yield chunk
1686+
yield chunk # pragma: nocover
16871687
for chunk in chunker.flush():
16881688
yield chunk
16891689

tests/models/test_responses.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,19 @@ def test_iter_raw_with_chunksize():
396396
assert parts == [b"Hello, world!"]
397397

398398

399+
def test_iter_raw_doesnt_return_empty_chunks():
400+
def streaming_body_with_empty_chunks():
401+
yield b"Hello, "
402+
yield b""
403+
yield b"world!"
404+
yield b""
405+
406+
response = httpx.Response(200, content=streaming_body_with_empty_chunks())
407+
408+
parts = [part for part in response.iter_raw()]
409+
assert parts == [b"Hello, ", b"world!"]
410+
411+
399412
def test_iter_raw_on_iterable():
400413
response = httpx.Response(
401414
200,
@@ -526,6 +539,19 @@ def test_iter_bytes_with_empty_response():
526539
assert parts == []
527540

528541

542+
def test_iter_bytes_doesnt_return_empty_chunks():
543+
def streaming_body_with_empty_chunks():
544+
yield b"Hello, "
545+
yield b""
546+
yield b"world!"
547+
yield b""
548+
549+
response = httpx.Response(200, content=streaming_body_with_empty_chunks())
550+
551+
parts = [part for part in response.iter_bytes()]
552+
assert parts == [b"Hello, ", b"world!"]
553+
554+
529555
@pytest.mark.asyncio
530556
async def test_aiter_bytes():
531557
response = httpx.Response(

0 commit comments

Comments
 (0)