Skip to content

Commit

Permalink
Eliminate side-effects from the ClientResponse.ok property
Browse files Browse the repository at this point in the history
This change makes it so accessing `ClientResponse.ok` only does the status
code check.

Prior to this commit, it'd call `ClientResponse.raise_for_status()` which
in turn, closed the underlying TCP session whenever the status was 400 or
higher making it effectively impossible to keep working with the response,
including reading the HTTP response payload.

PR aio-libs#5404 by @adamko147

Fixes aio-libs#5403

Co-authored-by: Sviatoslav Sydorenko <[email protected]>
  • Loading branch information
2 people authored and commonism committed Apr 27, 2021
1 parent b82a954 commit 933220d
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGES/5403.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Stop automatically releasing the ``ClientResponse`` object on calls to the ``ok`` property for the failed requests.
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
A. Jesse Jiryu Davis
Adam Bannister
Adam Cooper
Adam Horacek
Adam Mills
Adrian Krupa
Adrián Chaves
Expand Down
8 changes: 2 additions & 6 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -923,14 +923,10 @@ def ok(self) -> bool:
This is **not** a check for ``200 OK`` but a check that the response
status is under 400.
"""
try:
self.raise_for_status()
except ClientResponseError:
return False
return True
return 400 > self.status

def raise_for_status(self) -> None:
if 400 <= self.status:
if not self.ok:
# reason should always be not None for a started response
assert self.reason is not None
self.release()
Expand Down
21 changes: 21 additions & 0 deletions tests/test_client_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -1243,3 +1243,24 @@ def test_response_links_empty(loop: Any, session: Any) -> None:
)
response._headers = CIMultiDict()
assert response.links == {}


def test_response_not_closed_after_get_ok(mocker) -> None:
response = ClientResponse(
"get",
URL("http://del-cl-resp.org"),
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
traces=[],
loop=mock.Mock(),
session=mock.Mock(),
)
response.status = 400
response.reason = "Bad Request"
response._closed = False
spy = mocker.spy(response, "raise_for_status")
assert not response.ok
assert not response.closed
assert spy.call_count == 0

0 comments on commit 933220d

Please sign in to comment.