Skip to content

Commit

Permalink
Merge pull request slackapi#727 from NoAnyLove/unclosed-client-session
Browse files Browse the repository at this point in the history
Fix slackapi#645 Unclosed client session
  • Loading branch information
seratch authored Jul 1, 2020
2 parents 4870b9a + ca23138 commit b30e72d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 12 deletions.
29 changes: 17 additions & 12 deletions slack/web/base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,18 +294,23 @@ async def _request(self, *, http_verb, api_url, req_args):
)

response = None
async with session.request(http_verb, api_url, **req_args) as res:
data = {}
try:
data = await res.json()
except aiohttp.ContentTypeError:
self._logger.debug(
f"No response data returned from the following API call: {api_url}."
)
response = {"data": data, "headers": res.headers, "status_code": res.status}

if not use_running_session:
await session.close()
try:
async with session.request(http_verb, api_url, **req_args) as res:
data = {}
try:
data = await res.json()
except aiohttp.ContentTypeError:
self._logger.debug(
f"No response data returned from the following API call: {api_url}."
)
response = {
"data": data,
"headers": res.headers,
"status_code": res.status,
}
finally:
if not use_running_session:
await session.close()
return response

# =================================================================
Expand Down
21 changes: 21 additions & 0 deletions tests/web/test_web_client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import gc
import re
import socket
import unittest
Expand Down Expand Up @@ -223,3 +224,23 @@ async def test_timeout_issue_712_async(self):
client = WebClient(base_url="http://localhost:8888", timeout=1, run_async=True)
with self.assertRaises(asyncio.TimeoutError):
await client.users_list(token="xoxb-timeout")

def test_unclosed_client_session_issue_645_in_async_mode(self):
def exception_handler(_, context):
nonlocal session_unclosed
if context["message"] == "Unclosed client session":
session_unclosed = True

async def issue_645():
client = WebClient(base_url="http://localhost:8888", timeout=1, run_async=True)
try:
await client.users_list(token="xoxb-timeout")
except asyncio.TimeoutError:
pass

session_unclosed = False
loop = asyncio.get_event_loop()
loop.set_exception_handler(exception_handler)
loop.run_until_complete(issue_645())
gc.collect() # force Python to gc unclosed client session
self.assertFalse(session_unclosed, "Unclosed client session")

0 comments on commit b30e72d

Please sign in to comment.