diff --git a/slack_sdk/web/async_base_client.py b/slack_sdk/web/async_base_client.py index e4275f685..f02a59e00 100644 --- a/slack_sdk/web/async_base_client.py +++ b/slack_sdk/web/async_base_client.py @@ -195,16 +195,12 @@ async def _send(self, http_verb: str, api_url: str, req_args: dict) -> AsyncSlac Returns: The response parsed into a AsyncSlackResponse object. """ - open_files = _files_to_data(req_args) - try: + with _files_to_data(req_args): if "params" in req_args: # True/False -> "1"/"0" req_args["params"] = convert_bool_to_0_or_1(req_args["params"]) res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args) - finally: - for f in open_files: - f.close() data = { "client": self, diff --git a/slack_sdk/web/async_internal_utils.py b/slack_sdk/web/async_internal_utils.py index ac3f6d1eb..8622f4b21 100644 --- a/slack_sdk/web/async_internal_utils.py +++ b/slack_sdk/web/async_internal_utils.py @@ -2,8 +2,9 @@ import json import logging from asyncio import AbstractEventLoop +from contextlib import ExitStack from logging import Logger -from typing import Optional, BinaryIO, Dict, Sequence, Union, List, Any +from typing import Optional, Dict, Union, List, Any import aiohttp from aiohttp import ClientSession @@ -27,18 +28,17 @@ def _get_event_loop() -> AbstractEventLoop: return loop -def _files_to_data(req_args: dict) -> Sequence[BinaryIO]: - open_files = [] - files = req_args.pop("files", None) - if files is not None: - for k, v in files.items(): - if isinstance(v, str): - f = open(v.encode("utf-8", "ignore"), "rb") - open_files.append(f) - req_args["data"].update({k: f}) - else: - req_args["data"].update({k: v}) - return open_files +def _files_to_data(req_args: dict) -> ExitStack: + with ExitStack() as stack: + files = req_args.pop("files", None) + if files is not None: + for k, v in files.items(): + if isinstance(v, str): + f = stack.enter_context(open(v.encode("utf-8", "ignore"), "rb")) + req_args["data"].update({k: f}) + else: + req_args["data"].update({k: v}) + return stack.pop_all() async def _request_with_session( diff --git a/slack_sdk/web/legacy_base_client.py b/slack_sdk/web/legacy_base_client.py index 2cf1f1089..26be03e6e 100644 --- a/slack_sdk/web/legacy_base_client.py +++ b/slack_sdk/web/legacy_base_client.py @@ -208,16 +208,12 @@ async def _send(self, http_verb: str, api_url: str, req_args: dict) -> SlackResp Returns: The response parsed into a SlackResponse object. """ - open_files = _files_to_data(req_args) - try: + with _files_to_data(req_args): if "params" in req_args: # True/False -> "1"/"0" req_args["params"] = convert_bool_to_0_or_1(req_args["params"]) res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args) - finally: - for f in open_files: - f.close() data = { "client": self, diff --git a/tests/slack_sdk_async/web/test_async_internal_utils.py b/tests/slack_sdk_async/web/test_async_internal_utils.py new file mode 100644 index 000000000..3b9a49556 --- /dev/null +++ b/tests/slack_sdk_async/web/test_async_internal_utils.py @@ -0,0 +1,33 @@ +import os +import tempfile +import unittest + +from slack_sdk.web.async_internal_utils import _files_to_data + + +class TestAsyncInternalUtils(unittest.TestCase): + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + self.existing_path = os.path.join(self.tmp_dir.name, "existing.txt") + with open(self.existing_path, "w") as f: + f.write("hello") + + def tearDown(self): + self.tmp_dir.cleanup() + + def test_files_to_data_closes_opened_files_when_a_later_file_fails_to_open(self): + missing_path = os.path.join(self.tmp_dir.name, "missing.txt") + req_args = {"files": {"first": self.existing_path, "second": missing_path}, "data": {}} + + with self.assertRaises(FileNotFoundError): + _files_to_data(req_args) + + self.assertTrue(req_args["data"]["first"].closed) + + def test_files_to_data_keeps_files_open_until_the_returned_stack_exits(self): + req_args = {"files": {"first": self.existing_path}, "data": {}} + + with _files_to_data(req_args): + self.assertFalse(req_args["data"]["first"].closed) + + self.assertTrue(req_args["data"]["first"].closed)