Skip to content

Commit

Permalink
Fix HTTPResponse.read(0) when underlying buffer is empty (#2998)
Browse files Browse the repository at this point in the history
  • Loading branch information
pquentin committed Apr 29, 2023
1 parent 4fb8da2 commit 02ae65a
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/2998.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed ``HTTPResponse.read(0)`` call when underlying buffer is empty.
4 changes: 3 additions & 1 deletion src/urllib3/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,9 @@ def put(self, data: bytes) -> None:
self._size += len(data)

def get(self, n: int) -> bytes:
if not self.buffer:
if n == 0:
return b""
elif not self.buffer:
raise RuntimeError("buffer is empty")
elif n < 0:
raise ValueError("n should be > 0")
Expand Down
3 changes: 3 additions & 0 deletions test/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ def test_single_chunk(self) -> None:
with pytest.raises(RuntimeError, match="buffer is empty"):
assert buffer.get(10)

assert buffer.get(0) == b""

buffer.put(b"foo")
with pytest.raises(ValueError, match="n should be > 0"):
buffer.get(-1)
Expand Down Expand Up @@ -181,6 +183,7 @@ def test_reference_read(self) -> None:
fp = BytesIO(b"foo")
r = HTTPResponse(fp, preload_content=False)

assert r.read(0) == b""
assert r.read(1) == b"f"
assert r.read(2) == b"oo"
assert r.read() == b""
Expand Down

0 comments on commit 02ae65a

Please sign in to comment.