Skip to content

Commit

Permalink
[3.5] Close session on error in aiohttp.request (#3628) (#3640) (#3917)
Browse files Browse the repository at this point in the history
(cherry picked from commit 20bfadc)

Co-authored-by: Robert Nikolich <[email protected]>
  • Loading branch information
asvetlov and fried-sausage authored Jul 20, 2019
1 parent 456c0ca commit 6da1d71
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES/3628.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Close session created inside ``aiohttp.request`` when unhandled exception occurs
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ Rafael Viotti
Raúl Cumplido
Required Field
Robert Lu
Robert Nikolich
Roman Podoliaka
Samuel Colvin
Sean Hunt
Expand Down
9 changes: 7 additions & 2 deletions aiohttp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1048,8 +1048,13 @@ def __init__(self,
self._session = session

async def __aenter__(self) -> ClientResponse:
self._resp = await self._coro
return self._resp
try:
self._resp = await self._coro
except BaseException:
await self._session.close()
raise
else:
return self._resp

async def __aexit__(self,
exc_type: Optional[Type[BaseException]],
Expand Down
18 changes: 18 additions & 0 deletions tests/test_client_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -2383,6 +2383,24 @@ async def handler(request):
assert resp.status == 200


async def test_aiohttp_request_ctx_manager_close_sess_on_error(
ssl_ctx, aiohttp_server) -> None:
async def handler(request):
return web.Response()

app = web.Application()
app.router.add_get('/', handler)
server = await aiohttp_server(app, ssl=ssl_ctx)

cm = aiohttp.request('GET', server.make_url('/'))

with pytest.raises(aiohttp.ClientConnectionError):
async with cm:
pass

assert cm._session.closed


async def test_aiohttp_request_ctx_manager_not_found() -> None:

with pytest.raises(aiohttp.ClientConnectionError):
Expand Down

0 comments on commit 6da1d71

Please sign in to comment.