Skip to content

Commit

Permalink
Close session on error in aiohttp.request (#3628) (#3640)
Browse files Browse the repository at this point in the history
  • Loading branch information
fried-sausage authored and asvetlov committed Jul 19, 2019
1 parent 9afc44b commit 20bfadc
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 @@ -198,6 +198,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 @@ -992,8 +992,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 @@ -2346,6 +2346,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 20bfadc

Please sign in to comment.