Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix HTTPResponse.read(0) as first read call #2998

Merged
merged 3 commits into from
Apr 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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