diff --git a/integration_tests/audit_logs/test_async_client.py b/integration_tests/audit_logs/test_async_client.py index 962a24134..aae4888e3 100644 --- a/integration_tests/audit_logs/test_async_client.py +++ b/integration_tests/audit_logs/test_async_client.py @@ -10,9 +10,7 @@ class TestAuditLogsClient(unittest.TestCase): def setUp(self): - self.client = AsyncAuditLogsClient( - token=os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] - ) + self.client = AsyncAuditLogsClient(token=os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN]) def tearDown(self): pass diff --git a/integration_tests/audit_logs/test_client.py b/integration_tests/audit_logs/test_client.py index 6ea021ca7..fa9966039 100644 --- a/integration_tests/audit_logs/test_client.py +++ b/integration_tests/audit_logs/test_client.py @@ -9,9 +9,7 @@ class TestAuditLogsClient(unittest.TestCase): def setUp(self): - self.client = AuditLogsClient( - token=os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] - ) + self.client = AuditLogsClient(token=os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN]) def tearDown(self): pass diff --git a/integration_tests/audit_logs/test_pagination.py b/integration_tests/audit_logs/test_pagination.py index 507df1a4c..cdee8b178 100644 --- a/integration_tests/audit_logs/test_pagination.py +++ b/integration_tests/audit_logs/test_pagination.py @@ -10,9 +10,7 @@ class TestAuditLogsClient(unittest.TestCase): def setUp(self): - self.client = AuditLogsClient( - token=os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] - ) + self.client = AuditLogsClient(token=os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN]) def tearDown(self): pass @@ -22,11 +20,7 @@ def test_pagination(self): response = None ids = [] while call_count < 10 and (response is None or response.status_code != 429): - cursor = ( - response.body["response_metadata"]["next_cursor"] - if response is not None - else None - ) + cursor = response.body["response_metadata"]["next_cursor"] if response is not None else None response = self.client.logs(action="user_login", limit=1, cursor=cursor) ids += map(lambda v: v["id"], response.body.get("entries", [])) call_count += 1 diff --git a/integration_tests/env_variable_names.py b/integration_tests/env_variable_names.py index 213297ebe..993cdaf4c 100644 --- a/integration_tests/env_variable_names.py +++ b/integration_tests/env_variable_names.py @@ -18,9 +18,7 @@ # Testing with Grid workspaces SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN = "SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN" -SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN = ( - "SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN" -) +SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN = "SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN" SLACK_SDK_TEST_GRID_WORKSPACE_USER_TOKEN = "SLACK_SDK_TEST_GRID_WORKSPACE_USER_TOKEN" SLACK_SDK_TEST_GRID_WORKSPACE_BOT_TOKEN = "SLACK_SDK_TEST_GRID_WORKSPACE_BOT_TOKEN" SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID = "SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID" @@ -32,17 +30,9 @@ # Webhook SLACK_SDK_TEST_INCOMING_WEBHOOK_URL = "SLACK_SDK_TEST_INCOMING_WEBHOOK_URL" -SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME = ( - "SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME" -) +SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME = "SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME" # For Slack Connect shared tests -SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN = ( - "SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN" -) -SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN = ( - "SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN" -) -SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID = ( - "SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID" -) +SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN = "SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN" +SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN = "SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN" +SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID = "SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID" diff --git a/integration_tests/rtm/test_issue_530.py b/integration_tests/rtm/test_issue_530.py index a372291b1..cd992b7c3 100644 --- a/integration_tests/rtm/test_issue_530.py +++ b/integration_tests/rtm/test_issue_530.py @@ -22,15 +22,12 @@ def tearDown(self): def test_issue_530(self): try: - rtm_client = RTMClient( - token="I am not a token", run_async=False, loop=asyncio.new_event_loop() - ) + rtm_client = RTMClient(token="I am not a token", run_async=False, loop=asyncio.new_event_loop()) rtm_client.start() self.fail("Raising an error here was expected") except Exception as e: self.assertEqual( - "The request to the Slack API failed.\n" - "The server responded with: {'ok': False, 'error': 'invalid_auth'}", + "The request to the Slack API failed.\n" "The server responded with: {'ok': False, 'error': 'invalid_auth'}", str(e), ) finally: @@ -45,8 +42,7 @@ async def test_issue_530_async(self): self.fail("Raising an error here was expected") except Exception as e: self.assertEqual( - "The request to the Slack API failed.\n" - "The server responded with: {'ok': False, 'error': 'invalid_auth'}", + "The request to the Slack API failed.\n" "The server responded with: {'ok': False, 'error': 'invalid_auth'}", str(e), ) finally: diff --git a/integration_tests/rtm/test_issue_558.py b/integration_tests/rtm/test_issue_558.py index c9c51cae2..0e18bb48d 100644 --- a/integration_tests/rtm/test_issue_558.py +++ b/integration_tests/rtm/test_issue_558.py @@ -61,9 +61,7 @@ async def process_reactions(**payload): await asyncio.sleep(3) try: - first_reaction = await web_client.reactions_add( - channel=channel_id, timestamp=ts, name="eyes" - ) + first_reaction = await web_client.reactions_add(channel=channel_id, timestamp=ts, name="eyes") self.assertFalse("error" in first_reaction) await asyncio.sleep(2) @@ -72,9 +70,7 @@ async def process_reactions(**payload): # used to start blocking here # This reaction_add event won't be handled due to a bug - second_reaction = await web_client.reactions_add( - channel=channel_id, timestamp=ts, name="tada" - ) + second_reaction = await web_client.reactions_add(channel=channel_id, timestamp=ts, name="tada") self.assertFalse("error" in second_reaction) await asyncio.sleep(2) diff --git a/integration_tests/rtm/test_issue_569.py b/integration_tests/rtm/test_issue_569.py index 6f3b35cd9..f2c1a6bd6 100644 --- a/integration_tests/rtm/test_issue_569.py +++ b/integration_tests/rtm/test_issue_569.py @@ -43,9 +43,7 @@ def run_cpu_monitor(self): if current_cpu_usage > TestRTMClient.cpu_usage: TestRTMClient.cpu_usage = current_cpu_usage - TestRTMClient.cpu_monitor = threading.Thread( - target=run_cpu_monitor, args=[self] - ) + TestRTMClient.cpu_monitor = threading.Thread(target=run_cpu_monitor, args=[self]) TestRTMClient.cpu_monitor.daemon = True TestRTMClient.cpu_monitor.start() @@ -59,13 +57,9 @@ def tearDown(self): if hasattr(self, "rtm_client") and not self.rtm_client._stopped: self.rtm_client.stop() - @pytest.mark.skipif( - condition=is_not_specified(), reason="To avoid rate_limited errors" - ) + @pytest.mark.skipif(condition=is_not_specified(), reason="To avoid rate_limited errors") def test_cpu_usage(self): - self.rtm_client = RTMClient( - token=self.bot_token, run_async=False, loop=asyncio.new_event_loop() - ) + self.rtm_client = RTMClient(token=self.bot_token, run_async=False, loop=asyncio.new_event_loop()) self.web_client = WebClient(token=self.bot_token) self.call_count = 0 @@ -97,9 +91,7 @@ def connect(): time.sleep(5) text = "This message was sent by ! (test_cpu_usage)" - new_message = self.web_client.chat_postMessage( - channel=self.channel_id, text=text - ) + new_message = self.web_client.chat_postMessage(channel=self.channel_id, text=text) self.assertFalse("error" in new_message) time.sleep(5) @@ -140,9 +132,7 @@ async def send_reply_async(**payload): await asyncio.sleep(5) text = "This message was sent by ! (test_cpu_usage_async)" - new_message = await self.web_client.chat_postMessage( - channel=self.channel_id, text=text - ) + new_message = await self.web_client.chat_postMessage(channel=self.channel_id, text=text) self.assertFalse("error" in new_message) await asyncio.sleep(5) diff --git a/integration_tests/rtm/test_issue_605.py b/integration_tests/rtm/test_issue_605.py index 2ca239ec3..68e3ce867 100644 --- a/integration_tests/rtm/test_issue_605.py +++ b/integration_tests/rtm/test_issue_605.py @@ -32,9 +32,7 @@ def tearDown(self): # Reset the decorators by @RTMClient.run_on RTMClient._callbacks = collections.defaultdict(list) - @pytest.mark.skipif( - condition=is_not_specified(), reason="To avoid rate_limited errors" - ) + @pytest.mark.skipif(condition=is_not_specified(), reason="To avoid rate_limited errors") def test_issue_605(self): self.text = "This message was sent to verify issue #605" self.called = False @@ -60,9 +58,7 @@ def connect(): token=self.bot_token, run_async=False, ) - new_message = self.web_client.chat_postMessage( - channel=self.channel_id, text=self.text - ) + new_message = self.web_client.chat_postMessage(channel=self.channel_id, text=self.text) self.assertFalse("error" in new_message) time.sleep(5) diff --git a/integration_tests/rtm/test_issue_611.py b/integration_tests/rtm/test_issue_611.py index 6ba27dde8..4df8de337 100644 --- a/integration_tests/rtm/test_issue_611.py +++ b/integration_tests/rtm/test_issue_611.py @@ -29,9 +29,7 @@ def tearDown(self): # Reset the decorators by @RTMClient.run_on RTMClient._callbacks = collections.defaultdict(list) - @pytest.mark.skipif( - condition=is_not_specified(), reason="To avoid rate limited errors" - ) + @pytest.mark.skipif(condition=is_not_specified(), reason="To avoid rate limited errors") @async_test async def test_issue_611(self): channel_id = os.environ[SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID] @@ -41,16 +39,11 @@ async def test_issue_611(self): async def process_messages(**payload): self.logger.info(payload) - if ( - "subtype" in payload["data"] - and payload["data"]["subtype"] == "message_replied" - ): + if "subtype" in payload["data"] and payload["data"]["subtype"] == "message_replied": return # skip self.message_count += 1 - raise Exception( - "something is wrong!" - ) # This causes the termination of the process + raise Exception("something is wrong!") # This causes the termination of the process async def process_reactions(**payload): self.logger.info(payload) @@ -72,21 +65,15 @@ async def process_reactions(**payload): try: await asyncio.sleep(3) - first_reaction = await web_client.reactions_add( - channel=channel_id, timestamp=ts, name="eyes" - ) + first_reaction = await web_client.reactions_add(channel=channel_id, timestamp=ts, name="eyes") self.assertFalse("error" in first_reaction) await asyncio.sleep(2) - should_be_ignored = await web_client.chat_postMessage( - channel=channel_id, text="Hello?", thread_ts=ts - ) + should_be_ignored = await web_client.chat_postMessage(channel=channel_id, text="Hello?", thread_ts=ts) self.assertFalse("error" in should_be_ignored) await asyncio.sleep(2) - second_reaction = await web_client.reactions_add( - channel=channel_id, timestamp=ts, name="tada" - ) + second_reaction = await web_client.reactions_add(channel=channel_id, timestamp=ts, name="tada") self.assertFalse("error" in second_reaction) await asyncio.sleep(2) diff --git a/integration_tests/rtm/test_issue_631.py b/integration_tests/rtm/test_issue_631.py index b2a64ef70..0fe55a65c 100644 --- a/integration_tests/rtm/test_issue_631.py +++ b/integration_tests/rtm/test_issue_631.py @@ -37,9 +37,7 @@ def tearDown(self): if hasattr(self, "rtm_client") and not self.rtm_client._stopped: self.rtm_client.stop() - @pytest.mark.skipif( - condition=is_not_specified(), reason="to avoid rate_limited errors" - ) + @pytest.mark.skipif(condition=is_not_specified(), reason="to avoid rate_limited errors") def test_issue_631_sharing_event_loop(self): self.success = None self.text = "This message was sent to verify issue #631" @@ -85,9 +83,7 @@ def send_reply(**payload): if "text" in data and self.text in data["text"]: channel_id = data["channel"] thread_ts = data["ts"] - self.success = web_client.chat_postMessage( - channel=channel_id, text="Thanks!", thread_ts=thread_ts - ) + self.success = web_client.chat_postMessage(channel=channel_id, text="Thanks!", thread_ts=thread_ts) except Exception as e: self.logger.error(traceback.format_exc()) raise e @@ -108,9 +104,7 @@ def connect(): token=self.bot_token, run_async=False, ) - new_message = self.web_client.chat_postMessage( - channel=self.channel_id, text=self.text - ) + new_message = self.web_client.chat_postMessage(channel=self.channel_id, text=self.text) self.assertFalse("error" in new_message) time.sleep(5) @@ -119,9 +113,7 @@ def connect(): t.join(0.3) # Solution (2) for #631 - @pytest.mark.skipif( - condition=is_not_specified(), reason="this is just for reference" - ) + @pytest.mark.skipif(condition=is_not_specified(), reason="this is just for reference") @async_test async def test_issue_631_sharing_event_loop_async(self): self.success = None @@ -141,9 +133,7 @@ async def send_reply(**payload): if "text" in data and self.text in data["text"]: channel_id = data["channel"] thread_ts = data["ts"] - self.success = await web_client.chat_postMessage( - channel=channel_id, text="Thanks!", thread_ts=thread_ts - ) + self.success = await web_client.chat_postMessage(channel=channel_id, text="Thanks!", thread_ts=thread_ts) except Exception as e: self.logger.error(traceback.format_exc()) raise e @@ -158,9 +148,7 @@ async def send_reply(**payload): token=self.bot_token, run_async=True, # all need to be async here ) - new_message = await self.web_client.chat_postMessage( - channel=self.channel_id, text=self.text - ) + new_message = await self.web_client.chat_postMessage(channel=self.channel_id, text=self.text) self.assertFalse("error" in new_message) await asyncio.sleep(5) diff --git a/integration_tests/rtm/test_issue_701.py b/integration_tests/rtm/test_issue_701.py index 8711aa3c9..793bab772 100644 --- a/integration_tests/rtm/test_issue_701.py +++ b/integration_tests/rtm/test_issue_701.py @@ -40,9 +40,7 @@ def test_receiving_all_messages(self): def send_reply(**payload): self.logger.debug(payload) web_client, data = payload["web_client"], payload["data"] - web_client.reactions_add( - channel=data["channel"], timestamp=data["ts"], name="eyes" - ) + web_client.reactions_add(channel=data["channel"], timestamp=data["ts"], name="eyes") self.call_count += 1 def connect(): @@ -84,13 +82,9 @@ def sent_bulk_message(): time.sleep(1) wait_seconds += 1 - self.assertEqual( - total_num * num_of_senders, self.call_count, "The RTM handler failed" - ) + self.assertEqual(total_num * num_of_senders, self.call_count, "The RTM handler failed") - @pytest.mark.skipif( - condition=is_not_specified(), reason="to avoid rate_limited errors" - ) + @pytest.mark.skipif(condition=is_not_specified(), reason="to avoid rate_limited errors") @async_test async def test_receiving_all_messages_async(self): self.rtm_client = RTMClient(token=self.bot_token, run_async=True) @@ -102,9 +96,7 @@ async def test_receiving_all_messages_async(self): async def send_reply(**payload): self.logger.debug(payload) web_client, data = payload["web_client"], payload["data"] - await web_client.reactions_add( - channel=data["channel"], timestamp=data["ts"], name="eyes" - ) + await web_client.reactions_add(channel=data["channel"], timestamp=data["ts"], name="eyes") self.call_count += 1 # intentionally not waiting here @@ -141,6 +133,4 @@ def sent_bulk_message(): await asyncio.sleep(1) wait_seconds += 1 - self.assertEqual( - total_num * num_of_senders, self.call_count, "The RTM handler failed" - ) + self.assertEqual(total_num * num_of_senders, self.call_count, "The RTM handler failed") diff --git a/integration_tests/rtm/test_rtm_client.py b/integration_tests/rtm/test_rtm_client.py index b4a7393a6..b56b12ded 100644 --- a/integration_tests/rtm/test_rtm_client.py +++ b/integration_tests/rtm/test_rtm_client.py @@ -58,9 +58,7 @@ def connect(): time.sleep(5) text = "This message was sent by ! (test_basic_operations)" - new_message = self.web_client.chat_postMessage( - channel=self.channel_id, text=text - ) + new_message = self.web_client.chat_postMessage(channel=self.channel_id, text=text) self.assertFalse("error" in new_message) time.sleep(5) @@ -86,9 +84,7 @@ async def send_reply(**payload): await asyncio.sleep(5) text = "This message was sent by ! (test_basic_operations_async)" - new_message = await self.async_web_client.chat_postMessage( - channel=self.channel_id, text=text - ) + new_message = await self.async_web_client.chat_postMessage(channel=self.channel_id, text=text) self.assertFalse("error" in new_message) await asyncio.sleep(5) self.assertEqual(self.sent_text, text) diff --git a/integration_tests/samples/basic_usage/calling_any_api_methods.py b/integration_tests/samples/basic_usage/calling_any_api_methods.py index 976b71412..bc545af39 100644 --- a/integration_tests/samples/basic_usage/calling_any_api_methods.py +++ b/integration_tests/samples/basic_usage/calling_any_api_methods.py @@ -9,7 +9,5 @@ from slack_sdk.web import WebClient client = WebClient(token=os.environ["SLACK_API_TOKEN"]) -response = client.api_call( - api_method="chat.postMessage", json={"channel": "#random", "text": "Hello world!"} -) +response = client.api_call(api_method="chat.postMessage", json={"channel": "#random", "text": "Hello world!"}) assert response["message"]["text"] == "Hello world!" diff --git a/integration_tests/samples/basic_usage/sending_a_message.py b/integration_tests/samples/basic_usage/sending_a_message.py index 80b13d054..ed55ad00b 100644 --- a/integration_tests/samples/basic_usage/sending_a_message.py +++ b/integration_tests/samples/basic_usage/sending_a_message.py @@ -18,17 +18,13 @@ channel_id = "C0XXXXXX" user_id = "U0XXXXXXX" -response = client.chat_postMessage( - channel=channel_id, text="Hello from your app! :tada:" -) +response = client.chat_postMessage(channel=channel_id, text="Hello from your app! :tada:") # Ensure the channel_id is not a name channel_id = response["channel"] thread_ts = response["message"]["ts"] -response = client.chat_postEphemeral( - channel=channel_id, user=user_id, text="Hello silently from your app! :tada:" -) +response = client.chat_postEphemeral(channel=channel_id, user=user_id, text="Hello silently from your app! :tada:") response = client.chat_postMessage( channel=channel_id, @@ -61,9 +57,7 @@ ) # Threading Messages -response = client.chat_postMessage( - channel=channel_id, text="Hello from your app! :tada:", thread_ts=thread_ts -) +response = client.chat_postMessage(channel=channel_id, text="Hello from your app! :tada:", thread_ts=thread_ts) response = client.chat_postMessage( channel=channel_id, @@ -76,9 +70,7 @@ response = client.chat_postMessage(channel=channel_id, text="To be modified :eyes:") ts = response["message"]["ts"] -response = client.chat_update( - channel=channel_id, ts=ts, text="updates from your app! :tada:" -) +response = client.chat_update(channel=channel_id, ts=ts, text="updates from your app! :tada:") # Deleting a message response = client.chat_postMessage(channel=channel_id, text="To be deleted :eyes:") diff --git a/integration_tests/samples/basic_usage/views.py b/integration_tests/samples/basic_usage/views.py index 3fcf1a921..ef791116e 100644 --- a/integration_tests/samples/basic_usage/views.py +++ b/integration_tests/samples/basic_usage/views.py @@ -66,15 +66,10 @@ def slack_app(): code = e.response["error"] return make_response(f"Failed to open a modal due to {code}", 200) - if ( - payload["type"] == "view_submission" - and payload["view"]["callback_id"] == "modal-id" - ): + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": # Handle a data submission request from the modal submitted_data = payload["view"]["state"]["values"] - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response( jsonify( { diff --git a/integration_tests/samples/basic_usage/views_2.py b/integration_tests/samples/basic_usage/views_2.py index daf870d6a..7ed4feea9 100644 --- a/integration_tests/samples/basic_usage/views_2.py +++ b/integration_tests/samples/basic_usage/views_2.py @@ -63,15 +63,10 @@ def slack_app(): code = e.response["error"] return make_response(f"Failed to open a modal due to {code}", 200) - if ( - payload["type"] == "view_submission" - and payload["view"]["callback_id"] == "modal-id" - ): + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": # Handle a data submission request from the modal submitted_data = payload["view"]["state"]["values"] - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response( jsonify( { @@ -84,9 +79,7 @@ def slack_app(): blocks=[ SectionBlock( block_id="b-id", - text=PlainTextObject( - text="Thanks for submitting the data!" - ), + text=PlainTextObject(text="Thanks for submitting the data!"), ) ], ).to_dict(), diff --git a/integration_tests/samples/basic_usage/views_default_to_current_conversation.py b/integration_tests/samples/basic_usage/views_default_to_current_conversation.py index 425bf5bb3..13cbd710a 100644 --- a/integration_tests/samples/basic_usage/views_default_to_current_conversation.py +++ b/integration_tests/samples/basic_usage/views_default_to_current_conversation.py @@ -84,15 +84,10 @@ def slack_app(): # Open a new modal by a global shortcut return open_modal(payload["trigger_id"]) - if ( - payload["type"] == "view_submission" - and payload["view"]["callback_id"] == "modal-id" - ): + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": # Handle a data submission request from the modal submitted_data = payload["view"]["state"]["values"] - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response("", 200) return make_response("", 404) diff --git a/integration_tests/samples/conversations/create_private_channel.py b/integration_tests/samples/conversations/create_private_channel.py index a081e75af..4ab780b2b 100644 --- a/integration_tests/samples/conversations/create_private_channel.py +++ b/integration_tests/samples/conversations/create_private_channel.py @@ -15,9 +15,7 @@ response = client.conversations_create(name=channel_name, is_private=True) channel_id = response["channel"]["id"] -response = client.conversations_info( - channel=channel_id, include_num_members=1 # TODO: True -) +response = client.conversations_info(channel=channel_id, include_num_members=1) # TODO: True response = client.conversations_members(channel=channel_id) user_ids = response["members"] diff --git a/integration_tests/samples/conversations/list_conversations.py b/integration_tests/samples/conversations/list_conversations.py index f099b1cbb..19749f04d 100644 --- a/integration_tests/samples/conversations/list_conversations.py +++ b/integration_tests/samples/conversations/list_conversations.py @@ -16,6 +16,4 @@ channel_id = response["channels"][0]["id"] -response = client.conversations_info( - channel=channel_id, include_num_members=1 # TODO: True -) +response = client.conversations_info(channel=channel_id, include_num_members=1) # TODO: True diff --git a/integration_tests/samples/issues/issue_497.py b/integration_tests/samples/issues/issue_497.py index 8cc53c050..7741c7ecb 100644 --- a/integration_tests/samples/issues/issue_497.py +++ b/integration_tests/samples/issues/issue_497.py @@ -22,9 +22,7 @@ singleton_client = WebClient(token=os.environ["SLACK_BOT_TOKEN"], run_async=False) singleton_loop = asyncio.new_event_loop() -singleton_async_client = WebClient( - token=os.environ["SLACK_BOT_TOKEN"], run_async=True, loop=singleton_loop -) +singleton_async_client = WebClient(token=os.environ["SLACK_BOT_TOKEN"], run_async=True, loop=singleton_loop) # Fixed in 2.6.0: This doesn't work @@ -47,9 +45,7 @@ def singleton(): def per_request(): try: client = WebClient(token=os.environ["SLACK_BOT_TOKEN"], run_async=False) - response = client.chat_postMessage( - channel="#random", text="You used a new WebClient for posting this message!" - ) + response = client.chat_postMessage(channel="#random", text="You used a new WebClient for posting this message!") return str(response) except SlackApiError as e: return make_response(str(e), 400) diff --git a/integration_tests/samples/issues/issue_690.py b/integration_tests/samples/issues/issue_690.py index 2c283fa94..eadbce5f7 100644 --- a/integration_tests/samples/issues/issue_690.py +++ b/integration_tests/samples/issues/issue_690.py @@ -25,9 +25,7 @@ def endpoint(): client = WebClient(token="") client_id = os.environ["SLACK_CLIENT_ID"] client_secret = os.environ["SLACK_CLIENT_SECRET"] - response = client.oauth_v2_access( - client_id=client_id, client_secret=client_secret, code=code - ) + response = client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) result = response.get("error", "success!") return str(result) except SlackApiError as e: diff --git a/integration_tests/samples/issues/issue_838.py b/integration_tests/samples/issues/issue_838.py index b54617379..0c84b59ff 100644 --- a/integration_tests/samples/issues/issue_838.py +++ b/integration_tests/samples/issues/issue_838.py @@ -33,9 +33,7 @@ def slack_app(): if request.headers["content-type"] == "application/json": body = json.loads(request_body) - response = app_token_client.apps_event_authorizations_list( - event_context=body["event_context"] - ) + response = app_token_client.apps_event_authorizations_list(event_context=body["event_context"]) print(response) return make_response("", 200) diff --git a/integration_tests/samples/oauth/oauth_v2.py b/integration_tests/samples/oauth/oauth_v2.py index 197b29bf5..764c5af85 100644 --- a/integration_tests/samples/oauth/oauth_v2.py +++ b/integration_tests/samples/oauth/oauth_v2.py @@ -54,9 +54,7 @@ def oauth_callback(): if state_store.consume(state): code = request.args["code"] client = WebClient() # no prepared token needed for this app - oauth_response = client.oauth_v2_access( - client_id=client_id, client_secret=client_secret, code=code - ) + oauth_response = client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) logger.info(f"oauth.v2.access response: {oauth_response}") installed_enterprise = oauth_response.get("enterprise", {}) @@ -92,9 +90,7 @@ def oauth_callback(): incoming_webhook_url=incoming_webhook.get("url"), incoming_webhook_channel=incoming_webhook.get("channel"), incoming_webhook_channel_id=incoming_webhook.get("channel_id"), - incoming_webhook_configuration_url=incoming_webhook.get( - "configuration_url" - ), + incoming_webhook_configuration_url=incoming_webhook.get("configuration_url"), is_enterprise_install=is_enterprise_install, token_type=oauth_response.get("token_type"), ) @@ -106,14 +102,10 @@ def oauth_callback(): enterprise_url=installation.enterprise_url, ) else: - return redirect_page_renderer.render_failure_page( - "the state value is already expired" - ) + return redirect_page_renderer.render_failure_page("the state value is already expired") error = request.args["error"] if "error" in request.args else "" - return make_response( - f"Something is wrong with the installation (error: {error})", 400 - ) + return make_response(f"Something is wrong with the installation (error: {error})", 400) # --------------------- @@ -182,14 +174,9 @@ def slack_app(): elif "payload" in request.form: payload = json.loads(request.form["payload"]) - if ( - payload["type"] == "view_submission" - and payload["view"]["callback_id"] == "modal-id" - ): + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": submitted_data = payload["view"]["state"]["values"] - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response("", 200) return make_response("", 404) diff --git a/integration_tests/samples/oauth/oauth_v2_async.py b/integration_tests/samples/oauth/oauth_v2_async.py index 21a2a1d38..3c7e2442a 100644 --- a/integration_tests/samples/oauth/oauth_v2_async.py +++ b/integration_tests/samples/oauth/oauth_v2_async.py @@ -57,9 +57,7 @@ async def oauth_callback(req: Request): if state_store.consume(state): code = req.args.get("code") client = AsyncWebClient() # no prepared token needed for this app - oauth_response = await client.oauth_v2_access( - client_id=client_id, client_secret=client_secret, code=code - ) + oauth_response = await client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) logger.info(f"oauth.v2.access response: {oauth_response}") installed_enterprise = oauth_response.get("enterprise") or {} @@ -86,9 +84,7 @@ async def oauth_callback(req: Request): user_scopes=installer.get("scope"), # comma-separated string incoming_webhook_url=incoming_webhook.get("url"), incoming_webhook_channel_id=incoming_webhook.get("channel_id"), - incoming_webhook_configuration_url=incoming_webhook.get( - "configuration_url" - ), + incoming_webhook_configuration_url=incoming_webhook.get("configuration_url"), ) installation_store.save(installation) html = redirect_page_renderer.render_success_page( @@ -105,9 +101,7 @@ async def oauth_callback(req: Request): body=html, ) else: - html = redirect_page_renderer.render_failure_page( - "the state value is already expired" - ) + html = redirect_page_renderer.render_failure_page("the state value is already expired") return HTTPResponse( status=400, headers={ @@ -117,9 +111,7 @@ async def oauth_callback(req: Request): ) error = req.args.get("error") if "error" in req.args else "" - return HTTPResponse( - status=400, body=f"Something is wrong with the installation (error: {error})" - ) + return HTTPResponse(status=400, body=f"Something is wrong with the installation (error: {error})") # --------------------- @@ -183,20 +175,13 @@ async def slack_app(req: Request): return HTTPResponse(status=200, body="") except SlackApiError as e: code = e.response["error"] - return HTTPResponse( - status=200, body=f"Failed to open a modal due to {code}" - ) + return HTTPResponse(status=200, body=f"Failed to open a modal due to {code}") elif "payload" in req.form: payload = json.loads(req.form.get("payload")) - if ( - payload.get("type") == "view_submission" - and payload.get("view").get("callback_id") == "modal-id" - ): + if payload.get("type") == "view_submission" and payload.get("view").get("callback_id") == "modal-id": submitted_data = payload.get("view").get("state").get("values") - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return HTTPResponse(status=200, body="") return HTTPResponse(status=404, body="Not found") diff --git a/integration_tests/samples/oauth/oauth_v2_legacy.py b/integration_tests/samples/oauth/oauth_v2_legacy.py index bc82da70d..d9a8b1b40 100644 --- a/integration_tests/samples/oauth/oauth_v2_legacy.py +++ b/integration_tests/samples/oauth/oauth_v2_legacy.py @@ -50,9 +50,7 @@ def save(self, oauth_v2_response): "bot_token": oauth_v2_response["access_token"], "bot_user_id": oauth_v2_response["bot_user_id"], "user_id": installer["id"], - "user_token": installer["access_token"] - if "access_token" in installer - else None, + "user_token": installer["access_token"] if "access_token" in installer else None, } logger.debug(f"all rows: {list(self.tokens.keys())}") @@ -102,14 +100,10 @@ def oauth_callback(): database.save(response) return "Thanks for installing this app!" else: - return make_response( - f"Try the installation again (the state value is already expired)", 400 - ) + return make_response(f"Try the installation again (the state value is already expired)", 400) error = request.args["error"] if "error" in request.args else "" - return make_response( - f"Something is wrong with the installation (error: {error})", 400 - ) + return make_response(f"Something is wrong with the installation (error: {error})", 400) # --------------------- @@ -122,9 +116,7 @@ def oauth_callback(): import json -def verify_slack_request( - signing_secret: str, request_body: str, timestamp: str, signature: str -) -> bool: +def verify_slack_request(signing_secret: str, request_body: str, timestamp: str, signature: str) -> bool: """Slack Request Verification For more information: https://github.com/slackapi/python-slack-events-api @@ -135,18 +127,12 @@ def verify_slack_request( if hasattr(hmac, "compare_digest"): req = str.encode("v0:" + str(timestamp) + ":") + request_body - request_hash = ( - "v0=" - + hmac.new(str.encode(signing_secret), req, hashlib.sha256).hexdigest() - ) + request_hash = "v0=" + hmac.new(str.encode(signing_secret), req, hashlib.sha256).hexdigest() return hmac.compare_digest(request_hash, signature) else: # So, we'll compare the signatures explicitly req = str.encode("v0:" + str(timestamp) + ":") + request_body - request_hash = ( - "v0=" - + hmac.new(str.encode(signing_secret), req, hashlib.sha256).hexdigest() - ) + request_hash = "v0=" + hmac.new(str.encode(signing_secret), req, hashlib.sha256).hexdigest() if len(request_hash) != len(signature): return False @@ -216,14 +202,9 @@ def slack_app(): elif "payload" in request.form: payload = json.loads(request.form["payload"]) - if ( - payload["type"] == "view_submission" - and payload["view"]["callback_id"] == "modal-id" - ): + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": submitted_data = payload["view"]["state"]["values"] - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response("", 200) return make_response("", 404) diff --git a/integration_tests/samples/openid_connect/flask_example.py b/integration_tests/samples/openid_connect/flask_example.py index 1490277fb..770b4a2ef 100644 --- a/integration_tests/samples/openid_connect/flask_example.py +++ b/integration_tests/samples/openid_connect/flask_example.py @@ -58,15 +58,11 @@ def oauth_callback(): ) logger.info(f"openid.connect.token response: {token_response}") id_token = token_response.get("id_token") - claims = jwt.decode( - id_token, options={"verify_signature": False}, algorithms=["RS256"] - ) + claims = jwt.decode(id_token, options={"verify_signature": False}, algorithms=["RS256"]) logger.info(f"claims (decoded id_token): {claims}") user_token = token_response.get("access_token") - user_info_response = WebClient( - token=user_token - ).openid_connect_userInfo() + user_info_response = WebClient(token=user_token).openid_connect_userInfo() logger.info(f"openid.connect.userInfo response: {user_info_response}") return f""" @@ -90,18 +86,12 @@ def oauth_callback(): except Exception: logger.exception("Failed to perform openid.connect.token API call") - return redirect_page_renderer.render_failure_page( - "Failed to perform openid.connect.token API call" - ) + return redirect_page_renderer.render_failure_page("Failed to perform openid.connect.token API call") else: - return redirect_page_renderer.render_failure_page( - "The state value is already expired" - ) + return redirect_page_renderer.render_failure_page("The state value is already expired") error = request.args["error"] if "error" in request.args else "" - return make_response( - f"Something is wrong with the installation (error: {error})", 400 - ) + return make_response(f"Something is wrong with the installation (error: {error})", 400) if __name__ == "__main__": diff --git a/integration_tests/samples/openid_connect/sanic_example.py b/integration_tests/samples/openid_connect/sanic_example.py index f65288355..bb62f6a9f 100644 --- a/integration_tests/samples/openid_connect/sanic_example.py +++ b/integration_tests/samples/openid_connect/sanic_example.py @@ -63,15 +63,11 @@ async def oauth_callback(req: Request): ) logger.info(f"openid.connect.token response: {token_response}") id_token = token_response.get("id_token") - claims = jwt.decode( - id_token, options={"verify_signature": False}, algorithms=["RS256"] - ) + claims = jwt.decode(id_token, options={"verify_signature": False}, algorithms=["RS256"]) logger.info(f"claims (decoded id_token): {claims}") user_token = token_response.get("access_token") - user_info_response = await AsyncWebClient( - token=user_token - ).openid_connect_userInfo() + user_info_response = await AsyncWebClient(token=user_token).openid_connect_userInfo() logger.info(f"openid.connect.userInfo response: {user_info_response}") html = f""" @@ -102,14 +98,10 @@ async def oauth_callback(req: Request): except Exception: logger.exception("Failed to perform openid.connect.token API call") - return redirect_page_renderer.render_failure_page( - "Failed to perform openid.connect.token API call" - ) + return redirect_page_renderer.render_failure_page("Failed to perform openid.connect.token API call") else: - html = redirect_page_renderer.render_failure_page( - "The state value is already expired" - ) + html = redirect_page_renderer.render_failure_page("The state value is already expired") return HTTPResponse( status=400, headers={ @@ -119,9 +111,7 @@ async def oauth_callback(req: Request): ) error = req.args.get("error") if "error" in req.args else "" - return HTTPResponse( - status=400, body=f"Something is wrong with the installation (error: {error})" - ) + return HTTPResponse(status=400, body=f"Something is wrong with the installation (error: {error})") if __name__ == "__main__": diff --git a/integration_tests/samples/readme/rtm_client_basics.py b/integration_tests/samples/readme/rtm_client_basics.py index 44d0bd491..c97df1115 100644 --- a/integration_tests/samples/readme/rtm_client_basics.py +++ b/integration_tests/samples/readme/rtm_client_basics.py @@ -21,9 +21,7 @@ def say_hello(**payload): user = data["user"] try: - response = web_client.chat_postMessage( - channel=channel_id, text=f"Hi <@{user}>!", thread_ts=thread_ts - ) + response = web_client.chat_postMessage(channel=channel_id, text=f"Hi <@{user}>!", thread_ts=thread_ts) except SlackApiError as e: # You will get a SlackApiError if "ok" is False assert e.response["ok"] is False diff --git a/integration_tests/samples/socket_mode/aiohttp_example.py b/integration_tests/samples/socket_mode/aiohttp_example.py index 3c16bad2a..208ff32d4 100644 --- a/integration_tests/samples/socket_mode/aiohttp_example.py +++ b/integration_tests/samples/socket_mode/aiohttp_example.py @@ -14,9 +14,7 @@ async def main(): client = SocketModeClient( app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), - web_client=AsyncWebClient( - token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") - ), + web_client=AsyncWebClient(token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN")), trace_enabled=True, ) diff --git a/integration_tests/samples/socket_mode/bolt_adapter/async_base_handler.py b/integration_tests/samples/socket_mode/bolt_adapter/async_base_handler.py index 2837a3d09..36311318d 100644 --- a/integration_tests/samples/socket_mode/bolt_adapter/async_base_handler.py +++ b/integration_tests/samples/socket_mode/bolt_adapter/async_base_handler.py @@ -13,9 +13,7 @@ class AsyncBaseSocketModeHandler: app: Union[App, AsyncApp] # type: ignore client: AsyncBaseSocketModeClient - async def handle( - self, client: AsyncBaseSocketModeClient, req: SocketModeRequest - ) -> None: + async def handle(self, client: AsyncBaseSocketModeClient, req: SocketModeRequest) -> None: raise NotImplementedError() async def connect_async(self): diff --git a/integration_tests/samples/socket_mode/bolt_adapter/async_internals.py b/integration_tests/samples/socket_mode/bolt_adapter/async_internals.py index 5b5750bd1..d80968050 100644 --- a/integration_tests/samples/socket_mode/bolt_adapter/async_internals.py +++ b/integration_tests/samples/socket_mode/bolt_adapter/async_internals.py @@ -26,14 +26,10 @@ async def send_async_response( if bolt_resp.status == 200: content_type = bolt_resp.headers.get("content-type", [""])[0] if bolt_resp.body is None or len(bolt_resp.body) == 0: - await client.send_socket_mode_response( - SocketModeResponse(envelope_id=req.envelope_id) - ) + await client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id)) elif content_type.startswith("application/json"): dict_body = json.loads(bolt_resp.body) - await client.send_socket_mode_response( - SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body) - ) + await client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body)) else: await client.send_socket_mode_response( SocketModeResponse( @@ -45,6 +41,4 @@ async def send_async_response( spent_time = int((time() - start_time) * 1000) client.logger.debug(f"Response time: {spent_time} milliseconds") else: - client.logger.info( - f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})" - ) + client.logger.info(f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})") diff --git a/integration_tests/samples/socket_mode/bolt_adapter/internals.py b/integration_tests/samples/socket_mode/bolt_adapter/internals.py index 4f7f4d68c..065bb0204 100644 --- a/integration_tests/samples/socket_mode/bolt_adapter/internals.py +++ b/integration_tests/samples/socket_mode/bolt_adapter/internals.py @@ -26,25 +26,17 @@ def send_response( if bolt_resp.status == 200: content_type = bolt_resp.headers.get("content-type", [""])[0] if bolt_resp.body is None or len(bolt_resp.body) == 0: - client.send_socket_mode_response( - SocketModeResponse(envelope_id=req.envelope_id) - ) + client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id)) elif content_type.startswith("application/json"): dict_body = json.loads(bolt_resp.body) - client.send_socket_mode_response( - SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body) - ) + client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body)) else: client.send_socket_mode_response( - SocketModeResponse( - envelope_id=req.envelope_id, payload={"text": bolt_resp.body} - ) + SocketModeResponse(envelope_id=req.envelope_id, payload={"text": bolt_resp.body}) ) if client.logger.level <= logging.DEBUG: spent_time = int((time() - start_time) * 1000) client.logger.debug(f"Response time: {spent_time} milliseconds") else: - client.logger.info( - f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})" - ) + client.logger.info(f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})") diff --git a/integration_tests/samples/socket_mode/websockets_example.py b/integration_tests/samples/socket_mode/websockets_example.py index d72bdfd32..f29c66940 100644 --- a/integration_tests/samples/socket_mode/websockets_example.py +++ b/integration_tests/samples/socket_mode/websockets_example.py @@ -14,9 +14,7 @@ async def main(): client = SocketModeClient( app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), - web_client=AsyncWebClient( - token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") - ), + web_client=AsyncWebClient(token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN")), ) async def process(client: SocketModeClient, req: SocketModeRequest): diff --git a/integration_tests/samples/token_rotation/oauth.py b/integration_tests/samples/token_rotation/oauth.py index df216bc50..2f59cc923 100644 --- a/integration_tests/samples/token_rotation/oauth.py +++ b/integration_tests/samples/token_rotation/oauth.py @@ -139,14 +139,9 @@ def slack_app(): elif "payload" in request.form: payload = json.loads(request.form["payload"]) - if ( - payload["type"] == "view_submission" - and payload["view"]["callback_id"] == "modal-id" - ): + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": submitted_data = payload["view"]["state"]["values"] - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response("", 200) else: @@ -195,9 +190,7 @@ def oauth_callback(): if state_store.consume(state): code = request.args["code"] client = WebClient() # no prepared token needed for this app - oauth_response = client.oauth_v2_access( - client_id=client_id, client_secret=client_secret, code=code - ) + oauth_response = client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) logger.info(f"oauth.v2.access response: {oauth_response}") installed_enterprise = oauth_response.get("enterprise", {}) @@ -237,9 +230,7 @@ def oauth_callback(): incoming_webhook_url=incoming_webhook.get("url"), incoming_webhook_channel=incoming_webhook.get("channel"), incoming_webhook_channel_id=incoming_webhook.get("channel_id"), - incoming_webhook_configuration_url=incoming_webhook.get( - "configuration_url" - ), + incoming_webhook_configuration_url=incoming_webhook.get("configuration_url"), is_enterprise_install=is_enterprise_install, token_type=oauth_response.get("token_type"), ) @@ -251,14 +242,10 @@ def oauth_callback(): enterprise_url=installation.enterprise_url, ) else: - return redirect_page_renderer.render_failure_page( - "the state value is already expired" - ) + return redirect_page_renderer.render_failure_page("the state value is already expired") error = request.args["error"] if "error" in request.args else "" - return make_response( - f"Something is wrong with the installation (error: {error})", 400 - ) + return make_response(f"Something is wrong with the installation (error: {error})", 400) if __name__ == "__main__": diff --git a/integration_tests/samples/token_rotation/oauth_async.py b/integration_tests/samples/token_rotation/oauth_async.py index 27661f906..5540c4aa3 100644 --- a/integration_tests/samples/token_rotation/oauth_async.py +++ b/integration_tests/samples/token_rotation/oauth_async.py @@ -135,20 +135,13 @@ async def slack_app(req: Request): return HTTPResponse(status=200, body="") except SlackApiError as e: code = e.response["error"] - return HTTPResponse( - status=200, body=f"Failed to open a modal due to {code}" - ) + return HTTPResponse(status=200, body=f"Failed to open a modal due to {code}") elif "payload" in req.form: payload = json.loads(req.form.get("payload")) - if ( - payload.get("type") == "view_submission" - and payload.get("view").get("callback_id") == "modal-id" - ): + if payload.get("type") == "view_submission" and payload.get("view").get("callback_id") == "modal-id": submitted_data = payload.get("view").get("state").get("values") - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return HTTPResponse(status=200, body="") else: @@ -200,9 +193,7 @@ async def oauth_callback(req: Request): if state_store.consume(state): code = req.args.get("code") client = AsyncWebClient() # no prepared token needed for this app - oauth_response = await client.oauth_v2_access( - client_id=client_id, client_secret=client_secret, code=code - ) + oauth_response = await client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) logger.info(f"oauth.v2.access response: {oauth_response}") installed_enterprise = oauth_response.get("enterprise") or {} @@ -233,9 +224,7 @@ async def oauth_callback(req: Request): user_token_expires_in=installer.get("expires_in"), incoming_webhook_url=incoming_webhook.get("url"), incoming_webhook_channel_id=incoming_webhook.get("channel_id"), - incoming_webhook_configuration_url=incoming_webhook.get( - "configuration_url" - ), + incoming_webhook_configuration_url=incoming_webhook.get("configuration_url"), ) await installation_store.async_save(installation) html = redirect_page_renderer.render_success_page( @@ -252,9 +241,7 @@ async def oauth_callback(req: Request): body=html, ) else: - html = redirect_page_renderer.render_failure_page( - "the state value is already expired" - ) + html = redirect_page_renderer.render_failure_page("the state value is already expired") return HTTPResponse( status=400, headers={ @@ -264,9 +251,7 @@ async def oauth_callback(req: Request): ) error = req.args.get("error") if "error" in req.args else "" - return HTTPResponse( - status=400, body=f"Something is wrong with the installation (error: {error})" - ) + return HTTPResponse(status=400, body=f"Something is wrong with the installation (error: {error})") if __name__ == "__main__": diff --git a/integration_tests/samples/token_rotation/oauth_sqlalchemy.py b/integration_tests/samples/token_rotation/oauth_sqlalchemy.py index be95e475a..cb9fe0e6f 100644 --- a/integration_tests/samples/token_rotation/oauth_sqlalchemy.py +++ b/integration_tests/samples/token_rotation/oauth_sqlalchemy.py @@ -168,14 +168,9 @@ def slack_app(): elif "payload" in request.form: payload = json.loads(request.form["payload"]) - if ( - payload["type"] == "view_submission" - and payload["view"]["callback_id"] == "modal-id" - ): + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": submitted_data = payload["view"]["state"]["values"] - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response("", 200) else: @@ -224,9 +219,7 @@ def oauth_callback(): if state_store.consume(state): code = request.args["code"] client = WebClient() # no prepared token needed for this app - oauth_response = client.oauth_v2_access( - client_id=client_id, client_secret=client_secret, code=code - ) + oauth_response = client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) logger.info(f"oauth.v2.access response: {oauth_response}") installed_enterprise = oauth_response.get("enterprise", {}) @@ -266,9 +259,7 @@ def oauth_callback(): incoming_webhook_url=incoming_webhook.get("url"), incoming_webhook_channel=incoming_webhook.get("channel"), incoming_webhook_channel_id=incoming_webhook.get("channel_id"), - incoming_webhook_configuration_url=incoming_webhook.get( - "configuration_url" - ), + incoming_webhook_configuration_url=incoming_webhook.get("configuration_url"), is_enterprise_install=is_enterprise_install, token_type=oauth_response.get("token_type"), ) @@ -280,14 +271,10 @@ def oauth_callback(): enterprise_url=installation.enterprise_url, ) else: - return redirect_page_renderer.render_failure_page( - "the state value is already expired" - ) + return redirect_page_renderer.render_failure_page("the state value is already expired") error = request.args["error"] if "error" in request.args else "" - return make_response( - f"Something is wrong with the installation (error: {error})", 400 - ) + return make_response(f"Something is wrong with the installation (error: {error})", 400) if __name__ == "__main__": diff --git a/integration_tests/samples/token_rotation/oauth_sqlite3.py b/integration_tests/samples/token_rotation/oauth_sqlite3.py index 4c2adde7f..005b64b81 100644 --- a/integration_tests/samples/token_rotation/oauth_sqlite3.py +++ b/integration_tests/samples/token_rotation/oauth_sqlite3.py @@ -161,14 +161,9 @@ def slack_app(): elif "payload" in request.form: payload = json.loads(request.form["payload"]) - if ( - payload["type"] == "view_submission" - and payload["view"]["callback_id"] == "modal-id" - ): + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": submitted_data = payload["view"]["state"]["values"] - print( - submitted_data - ) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response("", 200) else: @@ -217,9 +212,7 @@ def oauth_callback(): if state_store.consume(state): code = request.args["code"] client = WebClient() # no prepared token needed for this app - oauth_response = client.oauth_v2_access( - client_id=client_id, client_secret=client_secret, code=code - ) + oauth_response = client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) logger.info(f"oauth.v2.access response: {oauth_response}") installed_enterprise = oauth_response.get("enterprise", {}) @@ -259,9 +252,7 @@ def oauth_callback(): incoming_webhook_url=incoming_webhook.get("url"), incoming_webhook_channel=incoming_webhook.get("channel"), incoming_webhook_channel_id=incoming_webhook.get("channel_id"), - incoming_webhook_configuration_url=incoming_webhook.get( - "configuration_url" - ), + incoming_webhook_configuration_url=incoming_webhook.get("configuration_url"), is_enterprise_install=is_enterprise_install, token_type=oauth_response.get("token_type"), ) @@ -273,14 +264,10 @@ def oauth_callback(): enterprise_url=installation.enterprise_url, ) else: - return redirect_page_renderer.render_failure_page( - "the state value is already expired" - ) + return redirect_page_renderer.render_failure_page("the state value is already expired") error = request.args["error"] if "error" in request.args else "" - return make_response( - f"Something is wrong with the installation (error: {error})", 400 - ) + return make_response(f"Something is wrong with the installation (error: {error})", 400) if __name__ == "__main__": diff --git a/integration_tests/samples/token_rotation/util.py b/integration_tests/samples/token_rotation/util.py index 9948db5ba..f0d201199 100644 --- a/integration_tests/samples/token_rotation/util.py +++ b/integration_tests/samples/token_rotation/util.py @@ -6,9 +6,7 @@ def parse_body(body: str, content_type: Optional[str]) -> Dict[str, Any]: if not body: return {} - if ( - content_type is not None and content_type == "application/json" - ) or body.startswith("{"): + if (content_type is not None and content_type == "application/json") or body.startswith("{"): return json.loads(body) else: if "payload" in body: # This is not JSON format yet @@ -24,9 +22,7 @@ def parse_body(body: str, content_type: Optional[str]) -> Dict[str, Any]: def extract_is_enterprise_install(payload: Dict[str, Any]) -> Optional[bool]: if "is_enterprise_install" in payload: is_enterprise_install = payload.get("is_enterprise_install") - return is_enterprise_install is not None and ( - is_enterprise_install is True or is_enterprise_install == "true" - ) + return is_enterprise_install is not None and (is_enterprise_install is True or is_enterprise_install == "true") return False diff --git a/integration_tests/samples/workflows/steps_from_apps.py b/integration_tests/samples/workflows/steps_from_apps.py index b52c01c5a..f77d6187a 100644 --- a/integration_tests/samples/workflows/steps_from_apps.py +++ b/integration_tests/samples/workflows/steps_from_apps.py @@ -48,12 +48,8 @@ def handle_step(): workflow_step_execute_id=step["workflow_step_execute_id"], outputs={ "taskName": step["inputs"]["taskName"]["value"], - "taskDescription": step["inputs"]["taskDescription"][ - "value" - ], - "taskAuthorEmail": step["inputs"]["taskAuthorEmail"][ - "value" - ], + "taskDescription": step["inputs"]["taskDescription"]["value"], + "taskAuthorEmail": step["inputs"]["taskAuthorEmail"]["value"], }, ) except Exception as err: @@ -130,10 +126,7 @@ def handle_step(): ) return make_response("", 200) - if ( - body["type"] == "view_submission" - and body["view"]["callback_id"] == "copy_review_view" - ): + if body["type"] == "view_submission" and body["view"]["callback_id"] == "copy_review_view": state_values = body["view"]["state"]["values"] client.workflows_updateStep( @@ -143,14 +136,10 @@ def handle_step(): "value": state_values["task_name_input"]["task_name"]["value"], }, "taskDescription": { - "value": state_values["task_description_input"][ - "task_description" - ]["value"], + "value": state_values["task_description_input"]["task_description"]["value"], }, "taskAuthorEmail": { - "value": state_values["task_author_input"]["task_author"][ - "value" - ], + "value": state_values["task_author_input"]["task_author"]["value"], }, }, outputs=[ diff --git a/integration_tests/scim/test_scim_client_read.py b/integration_tests/scim/test_scim_client_read.py index f506b8b26..700dbceef 100644 --- a/integration_tests/scim/test_scim_client_read.py +++ b/integration_tests/scim/test_scim_client_read.py @@ -48,9 +48,7 @@ def test_lookup_users_error(self): # error error_result = self.client.search_users(start_index=1, count=1, filter="foo") self.assertEqual(error_result.errors.code, 400) - self.assertEqual( - error_result.errors.description, "no_filters (is_aggregate_call=1)" - ) + self.assertEqual(error_result.errors.description, "no_filters (is_aggregate_call=1)") def test_lookup_groups(self): search_result = self.client.search_groups(start_index=1, count=1) @@ -73,6 +71,4 @@ def test_lookup_groups_error(self): # error error_result = self.client.search_groups(start_index=1, count=-1, filter="foo") self.assertEqual(error_result.errors.code, 400) - self.assertEqual( - error_result.errors.description, "no_filters (is_aggregate_call=1)" - ) + self.assertEqual(error_result.errors.description, "no_filters (is_aggregate_call=1)") diff --git a/integration_tests/web/test_admin_analytics.py b/integration_tests/web/test_admin_analytics.py index 0c34a7bef..13fe7c8dc 100644 --- a/integration_tests/web/test_admin_analytics.py +++ b/integration_tests/web/test_admin_analytics.py @@ -18,9 +18,7 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] - self.legacy_client: LegacyWebClient = LegacyWebClient( - token=self.org_admin_token - ) + self.legacy_client: LegacyWebClient = LegacyWebClient(token=self.org_admin_token) self.sync_client: WebClient = WebClient(token=self.org_admin_token) self.async_client: WebClient = AsyncWebClient(token=self.org_admin_token) @@ -46,18 +44,14 @@ def test_sync_error(self): def test_sync_public_channel(self): client = self.sync_client - response = client.admin_analytics_getFile( - date="2020-10-20", type="public_channel" - ) + response = client.admin_analytics_getFile(date="2020-10-20", type="public_channel") self.assertTrue(isinstance(response.data, bytes)) self.assertIsNotNone(response.data) def test_sync_public_channel_medata_only(self): client = self.sync_client - response = client.admin_analytics_getFile( - type="public_channel", metadata_only=True - ) + response = client.admin_analytics_getFile(type="public_channel", metadata_only=True) self.assertTrue(isinstance(response.data, bytes)) self.assertIsNotNone(response.data) @@ -65,9 +59,7 @@ def test_sync_public_channel_medata_only(self): async def test_async(self): client = self.async_client - response = await client.admin_analytics_getFile( - date="2020-10-20", type="member" - ) + response = await client.admin_analytics_getFile(date="2020-10-20", type="member") self.assertTrue(isinstance(response.data, bytes)) self.assertIsNotNone(response.data) @@ -85,9 +77,7 @@ async def test_async_error(self): async def test_async_public_channel(self): client = self.async_client - response = await client.admin_analytics_getFile( - date="2020-10-20", type="public_channel" - ) + response = await client.admin_analytics_getFile(date="2020-10-20", type="public_channel") self.assertTrue(isinstance(response.data, bytes)) self.assertIsNotNone(response.data) @@ -112,17 +102,13 @@ def test_legacy(self): def test_legacy_public_channel(self): client = self.legacy_client - response = client.admin_analytics_getFile( - date="2020-10-20", type="public_channel" - ) + response = client.admin_analytics_getFile(date="2020-10-20", type="public_channel") self.assertTrue(isinstance(response.data, bytes)) self.assertIsNotNone(response.data) def test_legacy_public_channel_metadata_only(self): client = self.legacy_client - response = client.admin_analytics_getFile( - type="public_channel", metadata_only=True - ) + response = client.admin_analytics_getFile(type="public_channel", metadata_only=True) self.assertTrue(isinstance(response.data, bytes)) self.assertIsNotNone(response.data) diff --git a/integration_tests/web/test_admin_auth_policy.py b/integration_tests/web/test_admin_auth_policy.py index c09b284f8..d83ad8c82 100644 --- a/integration_tests/web/test_admin_auth_policy.py +++ b/integration_tests/web/test_admin_auth_policy.py @@ -27,9 +27,7 @@ def tearDown(self): def test_sync(self): client = self.sync_client - list = client.admin_auth_policy_getEntities( - policy_name="email_password", limit=3 - ) + list = client.admin_auth_policy_getEntities(policy_name="email_password", limit=3) self.assertIsNotNone(list) assignment = client.admin_auth_policy_assignEntities( @@ -38,9 +36,7 @@ def test_sync(self): entity_type="USER", ) self.assertIsNotNone(assignment) - self.assertEqual( - list["entity_total_count"] + 1, assignment["entity_total_count"] - ) + self.assertEqual(list["entity_total_count"] + 1, assignment["entity_total_count"]) removal = client.admin_auth_policy_removeEntities( entity_ids=self.user_ids, @@ -54,9 +50,7 @@ def test_sync(self): async def test_async(self): client = self.async_client - list = await client.admin_auth_policy_getEntities( - policy_name="email_password", limit=3 - ) + list = await client.admin_auth_policy_getEntities(policy_name="email_password", limit=3) self.assertIsNotNone(list) assignment = await client.admin_auth_policy_assignEntities( @@ -65,9 +59,7 @@ async def test_async(self): entity_type="USER", ) self.assertIsNotNone(assignment) - self.assertEqual( - list["entity_total_count"] + 1, assignment["entity_total_count"] - ) + self.assertEqual(list["entity_total_count"] + 1, assignment["entity_total_count"]) removal = await client.admin_auth_policy_removeEntities( entity_ids=self.user_ids, diff --git a/integration_tests/web/test_admin_conversations_restrictAccess.py b/integration_tests/web/test_admin_conversations_restrictAccess.py index 4569333ea..54ee4e6c9 100644 --- a/integration_tests/web/test_admin_conversations_restrictAccess.py +++ b/integration_tests/web/test_admin_conversations_restrictAccess.py @@ -28,30 +28,21 @@ def setUp(self): self.idp_group_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] if not hasattr(self, "channel_id"): - team_admin_token = os.environ[ - SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN - ] + team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] client = WebClient(token=team_admin_token) # Only fetching private channels since admin.conversations.restrictAccess methods # do not work for public channels - convs = client.conversations_list( - exclude_archived=True, limit=100, types="private_channel" - ) + convs = client.conversations_list(exclude_archived=True, limit=100, types="private_channel") self.channel_id = next( - ( - c["id"] - for c in convs["channels"] - if c["name"] != "general" and not c["is_ext_shared"] - ), + (c["id"] for c in convs["channels"] if c["name"] != "general" and not c["is_ext_shared"]), None, ) if self.channel_id is None: millis = int(round(time.time() * 1000)) channel_name = f"private-test-channel-{millis}" - self.channel_id = client.conversations_create( - name=channel_name, - is_private=True, - )["channel"]["id"] + self.channel_id = client.conversations_create(name=channel_name, is_private=True,)[ + "channel" + ]["id"] def tearDown(self): pass @@ -67,9 +58,7 @@ def test_sync(self): # To avoid rate limiting errors time.sleep(10) - list_groups = client.admin_conversations_restrictAccess_listGroups( - team_id=self.team_id, channel_id=self.channel_id - ) + list_groups = client.admin_conversations_restrictAccess_listGroups(team_id=self.team_id, channel_id=self.channel_id) self.assertIsNotNone(list_groups) # To avoid rate limiting errors time.sleep(10) diff --git a/integration_tests/web/test_admin_rate_limit_retries.py b/integration_tests/web/test_admin_rate_limit_retries.py index 8c88d6b31..86260720a 100644 --- a/integration_tests/web/test_admin_rate_limit_retries.py +++ b/integration_tests/web/test_admin_rate_limit_retries.py @@ -21,13 +21,9 @@ def setUp(self): self.logger = logging.getLogger(__name__) self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] self.sync_client: WebClient = WebClient(token=self.org_admin_token) - self.sync_client.retry_handlers.append( - RateLimitErrorRetryHandler(max_retry_count=2) - ) + self.sync_client.retry_handlers.append(RateLimitErrorRetryHandler(max_retry_count=2)) self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) - self.async_client.retry_handlers.append( - AsyncRateLimitErrorRetryHandler(max_retry_count=2) - ) + self.async_client.retry_handlers.append(AsyncRateLimitErrorRetryHandler(max_retry_count=2)) def tearDown(self): pass diff --git a/integration_tests/web/test_admin_usergroups.py b/integration_tests/web/test_admin_usergroups.py index 7e365b1d2..2a845dc4d 100644 --- a/integration_tests/web/test_admin_usergroups.py +++ b/integration_tests/web/test_admin_usergroups.py @@ -27,14 +27,10 @@ def setUp(self): self.idp_usergroup_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] if not hasattr(self, "channel_ids"): - team_admin_token = os.environ[ - SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN - ] + team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] client = WebClient(token=team_admin_token) convs = client.conversations_list(exclude_archived=True, limit=100) - self.channel_ids = [ - c["id"] for c in convs["channels"] if c["name"] == "general" - ] + self.channel_ids = [c["id"] for c in convs["channels"] if c["name"] == "general"] def tearDown(self): pass diff --git a/integration_tests/web/test_admin_users.py b/integration_tests/web/test_admin_users.py index 8ec1de084..317354a51 100644 --- a/integration_tests/web/test_admin_users.py +++ b/integration_tests/web/test_admin_users.py @@ -27,14 +27,10 @@ def setUp(self): self.idp_usergroup_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] if not hasattr(self, "channel_ids"): - team_admin_token = os.environ[ - SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN - ] + team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] client = WebClient(token=team_admin_token) convs = client.conversations_list(exclude_archived=True, limit=100) - self.channel_ids = [ - c["id"] for c in convs["channels"] if c["name"] == "general" - ] + self.channel_ids = [c["id"] for c in convs["channels"] if c["name"] == "general"] def tearDown(self): pass diff --git a/integration_tests/web/test_admin_users_session.py b/integration_tests/web/test_admin_users_session.py index e9660ed50..6dfa285c2 100644 --- a/integration_tests/web/test_admin_users_session.py +++ b/integration_tests/web/test_admin_users_session.py @@ -14,9 +14,7 @@ def setUp(self): self.client: WebClient = WebClient(token=self.org_admin_token) if not hasattr(self, "user_ids"): - team_admin_token = os.environ[ - SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN - ] + team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] client = WebClient(token=team_admin_token) users = client.users_list(exclude_archived=True, limit=50) self.user_ids = [ @@ -41,7 +39,5 @@ def test_resetBulk(self): self.assertIsNone(response.get("error")) def test_resetBulk_str(self): - response = self.client.admin_users_session_resetBulk( - user_ids=",".join(self.user_ids) - ) + response = self.client.admin_users_session_resetBulk(user_ids=",".join(self.user_ids)) self.assertIsNone(response.get("error")) diff --git a/integration_tests/web/test_admin_users_session_settings.py b/integration_tests/web/test_admin_users_session_settings.py index e8e335670..0054ef3be 100644 --- a/integration_tests/web/test_admin_users_session_settings.py +++ b/integration_tests/web/test_admin_users_session_settings.py @@ -26,9 +26,7 @@ def setUp(self): self.idp_usergroup_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] if not hasattr(self, "user_ids"): - team_admin_token = os.environ[ - SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN - ] + team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] client = WebClient(token=team_admin_token) users = client.users_list(exclude_archived=True, limit=50) self.user_ids = [ @@ -49,9 +47,7 @@ def test_sync(self): response = client.admin_users_session_getSettings(user_ids=self.user_ids) self.assertIsNotNone(response["session_settings"]) - client.admin_users_session_setSettings( - user_ids=self.user_ids, duration=60 * 60 * 24 * 30 - ) + client.admin_users_session_setSettings(user_ids=self.user_ids, duration=60 * 60 * 24 * 30) client.admin_users_session_clearSettings(user_ids=self.user_ids) @async_test @@ -60,7 +56,5 @@ async def test_async(self): response = await client.admin_users_session_getSettings(user_ids=self.user_ids) self.assertIsNotNone(response["session_settings"]) - await client.admin_users_session_setSettings( - user_ids=self.user_ids, duration=60 * 60 * 24 * 30 - ) + await client.admin_users_session_setSettings(user_ids=self.user_ids, duration=60 * 60 * 24 * 30) await client.admin_users_session_clearSettings(user_ids=self.user_ids) diff --git a/integration_tests/web/test_async_web_client.py b/integration_tests/web/test_async_web_client.py index ed6d9e5fa..6785c59c9 100644 --- a/integration_tests/web/test_async_web_client.py +++ b/integration_tests/web/test_async_web_client.py @@ -75,9 +75,7 @@ async def test_basic_chat_operations_async(self): "This message was posted by ! " + "(integration_tests/test_web_client.py #test_chat_operations)" ) - new_message: AsyncSlackResponse = await client.chat_postMessage( - channel=channel, text=message - ) + new_message: AsyncSlackResponse = await client.chat_postMessage(channel=channel, text=message) self.assertEqual(new_message["message"]["text"], message) ts = new_message["ts"] @@ -88,32 +86,22 @@ async def test_basic_chat_operations_async(self): f"{url}archives/{channel}/.+", ) - new_reaction = await client.reactions_add( - channel=channel, timestamp=ts, name="eyes" - ) + new_reaction = await client.reactions_add(channel=channel, timestamp=ts, name="eyes") self.assertIsNotNone(new_reaction) reactions = await client.reactions_get(channel=channel, timestamp=ts) self.assertIsNotNone(reactions) - reaction_removal = await client.reactions_remove( - channel=channel, timestamp=ts, name="eyes" - ) + reaction_removal = await client.reactions_remove(channel=channel, timestamp=ts, name="eyes") self.assertIsNotNone(reaction_removal) - thread_reply = await client.chat_postMessage( - channel=channel, thread_ts=ts, text="threading..." - ) + thread_reply = await client.chat_postMessage(channel=channel, thread_ts=ts, text="threading...") self.assertIsNotNone(thread_reply) - modification = await client.chat_update( - channel=channel, ts=ts, text="Is this intentional?" - ) + modification = await client.chat_update(channel=channel, ts=ts, text="Is this intentional?") self.assertIsNotNone(modification) - reply_deletion = await client.chat_delete( - channel=channel, ts=thread_reply["ts"] - ) + reply_deletion = await client.chat_delete(channel=channel, ts=thread_reply["ts"]) self.assertIsNotNone(reply_deletion) message_deletion = await client.chat_delete(channel=channel, ts=ts) self.assertIsNotNone(message_deletion) @@ -180,9 +168,7 @@ async def test_pagination_with_iterator_async(self): client = self.async_client fetched_count = 0 # AsyncSlackResponse is an iterator that fetches next if next_cursor is not "" - async for response in await client.conversations_list( - limit=1, exclude_archived=1, types="public_channel" - ): + async for response in await client.conversations_list(limit=1, exclude_archived=1, types="public_channel"): fetched_count += len(response["channels"]) if fetched_count > 1: break diff --git a/integration_tests/web/test_bookmarks.py b/integration_tests/web/test_bookmarks.py index f18bd6984..8216055ad 100644 --- a/integration_tests/web/test_bookmarks.py +++ b/integration_tests/web/test_bookmarks.py @@ -38,11 +38,7 @@ def test_adding_listing_editing_removing_bookmark(self): # make sure we find the bookmark we just added all_bookmarks = client.bookmarks_list(channel_id=self.channel_id) self.assertIsNotNone(all_bookmarks) - self.assertIsNotNone( - next( - (b for b in all_bookmarks["bookmarks"] if b["id"] == bookmark_id), None - ) - ) + self.assertIsNotNone(next((b for b in all_bookmarks["bookmarks"] if b["id"] == bookmark_id), None)) # edit the bookmark bookmark = client.bookmarks_edit( bookmark_id=bookmark_id, @@ -55,19 +51,13 @@ def test_adding_listing_editing_removing_bookmark(self): # make sure we find the edited bookmark we just added all_bookmarks = client.bookmarks_list(channel_id=self.channel_id) self.assertIsNotNone(all_bookmarks) - edited_bookmark = next( - (b for b in all_bookmarks["bookmarks"] if b["id"] == bookmark_id), None - ) + edited_bookmark = next((b for b in all_bookmarks["bookmarks"] if b["id"] == bookmark_id), None) self.assertIsNotNone(edited_bookmark) self.assertEqual(edited_bookmark["title"], "slack api!") # remove the bookmark - removed_bookmark = client.bookmarks_remove( - bookmark_id=bookmark_id, channel_id=self.channel_id - ) + removed_bookmark = client.bookmarks_remove(bookmark_id=bookmark_id, channel_id=self.channel_id) self.assertIsNotNone(removed_bookmark) # make sure we cannot find the bookmark we just removed all_bookmarks = client.bookmarks_list(channel_id=self.channel_id) self.assertIsNotNone(all_bookmarks) - self.assertIsNone( - next((b for b in all_bookmarks if b["id"] == bookmark_id), None) - ) + self.assertIsNone(next((b for b in all_bookmarks if b["id"] == bookmark_id), None)) diff --git a/integration_tests/web/test_calls.py b/integration_tests/web/test_calls.py index bd05df0b0..7f5979378 100644 --- a/integration_tests/web/test_calls.py +++ b/integration_tests/web/test_calls.py @@ -24,12 +24,9 @@ def tearDown(self): def test_sync(self): client = self.sync_client - user_id = list( - filter( - lambda u: not u["deleted"] and "bot_id" not in u, - client.users_list(limit=50)["members"], - ) - )[0]["id"] + user_id = list(filter(lambda u: not u["deleted"] and "bot_id" not in u, client.users_list(limit=50)["members"],))[ + 0 + ]["id"] new_call = client.calls_add( external_unique_id=str(uuid.uuid4()), @@ -57,9 +54,7 @@ def test_sync(self): ) self.assertIsNotNone(channel_message) - channel_message = client.chat_postMessage( - channel="#random", blocks=[CallBlock(call_id=call_id)] - ) + channel_message = client.chat_postMessage(channel="#random", blocks=[CallBlock(call_id=call_id)]) self.assertIsNotNone(channel_message) call_info = client.calls_info(id=call_id) @@ -89,9 +84,7 @@ def test_sync(self): ) self.assertIsNotNone(participants_removal) - modified_call = client.calls_update( - id=call_id, join_url="https://www.example.com/calls/99999" - ) + modified_call = client.calls_update(id=call_id, join_url="https://www.example.com/calls/99999") self.assertIsNotNone(modified_call) ended_call = client.calls_end(id=call_id) @@ -101,9 +94,7 @@ def test_sync(self): async def test_async(self): client = self.async_client users = await client.users_list(limit=50) - user_id = list( - filter(lambda u: not u["deleted"] and "bot_id" not in u, users["members"]) - )[0]["id"] + user_id = list(filter(lambda u: not u["deleted"] and "bot_id" not in u, users["members"]))[0]["id"] new_call = await client.calls_add( external_unique_id=str(uuid.uuid4()), @@ -146,9 +137,7 @@ async def test_async(self): ) self.assertIsNotNone(new_participants) - modified_call = await client.calls_update( - id=call_id, join_url="https://www.example.com/calls/99999" - ) + modified_call = await client.calls_update(id=call_id, join_url="https://www.example.com/calls/99999") self.assertIsNotNone(modified_call) ended_call = await client.calls_end(id=call_id) diff --git a/integration_tests/web/test_conversations_connect.py b/integration_tests/web/test_conversations_connect.py index 740b7201a..798f8ed11 100644 --- a/integration_tests/web/test_conversations_connect.py +++ b/integration_tests/web/test_conversations_connect.py @@ -29,20 +29,12 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) - self.sender_bot_token = os.environ[ - SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN - ] - self.receiver_bot_token = os.environ[ - SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN - ] + self.sender_bot_token = os.environ[SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN] + self.receiver_bot_token = os.environ[SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN] self.sender_sync_client: WebClient = WebClient(token=self.sender_bot_token) - self.sender_async_client: AsyncWebClient = AsyncWebClient( - token=self.sender_bot_token - ) + self.sender_async_client: AsyncWebClient = AsyncWebClient(token=self.sender_bot_token) self.receiver_sync_client: WebClient = WebClient(token=self.receiver_bot_token) - self.receiver_async_client: AsyncWebClient = AsyncWebClient( - token=self.receiver_bot_token - ) + self.receiver_async_client: AsyncWebClient = AsyncWebClient(token=self.receiver_bot_token) def tearDown(self): pass @@ -59,9 +51,7 @@ def test_sync(self): # creates channel in sender workspace to share unique_channel_name = str(int(time.time())) + "-shared" - new_channel: SlackResponse = sender.conversations_create( - name=unique_channel_name - ) + new_channel: SlackResponse = sender.conversations_create(name=unique_channel_name) self.assertIsNotNone(new_channel["channel"]) self.assertIsNotNone(new_channel["channel"]["id"]) channel_id = new_channel["channel"]["id"] @@ -89,9 +79,7 @@ def test_sync(self): finally: if channel_id is not None: # clean up created channel - delete_channel: SlackResponse = sender.conversations_archive( - channel=new_channel["channel"]["id"] - ) + delete_channel: SlackResponse = sender.conversations_archive(channel=new_channel["channel"]["id"]) self.assertIsNotNone(delete_channel) @async_test @@ -102,16 +90,12 @@ async def test_async(self): try: # list senders pending connect invites - connect_invites: SlackResponse = ( - await sender.conversations_listConnectInvites() - ) + connect_invites: SlackResponse = await sender.conversations_listConnectInvites() self.assertIsNotNone(connect_invites["invites"]) # creates channel in sender workspace to share unique_channel_name = str(int(time.time())) + "-shared" - new_channel: SlackResponse = await sender.conversations_create( - name=unique_channel_name - ) + new_channel: SlackResponse = await sender.conversations_create(name=unique_channel_name) self.assertIsNotNone(new_channel["channel"]) self.assertIsNotNone(new_channel["channel"]["id"]) channel_id = new_channel["channel"]["id"] @@ -132,13 +116,9 @@ async def test_async(self): # receiver attempt to approve invite already accepted by an admin level token should fail with self.assertRaises(SlackApiError): - await receiver.conversations_approveSharedInvite( - invite_id=invite["invite_id"] - ) + await receiver.conversations_approveSharedInvite(invite_id=invite["invite_id"]) finally: if channel_id is not None: # clean up created channel - delete_channel: SlackResponse = await sender.conversations_archive( - channel=new_channel["channel"]["id"] - ) + delete_channel: SlackResponse = await sender.conversations_archive(channel=new_channel["channel"]["id"]) self.assertIsNotNone(delete_channel) diff --git a/integration_tests/web/test_issue_1053.py b/integration_tests/web/test_issue_1053.py index eaa5f50b4..607920efb 100644 --- a/integration_tests/web/test_issue_1053.py +++ b/integration_tests/web/test_issue_1053.py @@ -39,9 +39,7 @@ def test_issue_1053(self): and u.get("is_ultra_restricted", False) is False and u.get("is_email_confirmed", False) is True ] - invitations = client.conversations_invite( - channel=channel_id, users=user_ids - ) + invitations = client.conversations_invite(channel=channel_id, users=user_ids) self.assertIsNone(invitations.get("error")) finally: if channel_id is not None: diff --git a/integration_tests/web/test_issue_594.py b/integration_tests/web/test_issue_594.py index 718ee35c4..32c1d6ff8 100644 --- a/integration_tests/web/test_issue_594.py +++ b/integration_tests/web/test_issue_594.py @@ -45,9 +45,7 @@ def test_issue_594(self): ) self.assertIsNotNone(creation) - sharing = client.files_remote_share( - channels=self.channel_id, external_id=external_id - ) + sharing = client.files_remote_share(channels=self.channel_id, external_id=external_id) self.assertIsNotNone(sharing) message = client.chat_postEphemeral( @@ -82,9 +80,7 @@ def test_no_preview_image(self): ) self.assertIsNotNone(creation) - sharing = client.files_remote_share( - channels=self.channel_id, external_id=external_id - ) + sharing = client.files_remote_share(channels=self.channel_id, external_id=external_id) self.assertIsNotNone(sharing) message = client.chat_postEphemeral( diff --git a/integration_tests/web/test_issue_728.py b/integration_tests/web/test_issue_728.py index bdd62702d..080e1b988 100644 --- a/integration_tests/web/test_issue_728.py +++ b/integration_tests/web/test_issue_728.py @@ -26,9 +26,7 @@ def tearDown(self): def test_bytes_for_file_param(self): client: WebClient = WebClient(token=self.bot_token) bytes = bytearray("This is a test", "utf-8") - upload = client.files_upload( - file=bytes, filename="test.txt", channels=self.channel_ids - ) + upload = client.files_upload(file=bytes, filename="test.txt", channels=self.channel_ids) self.assertIsNotNone(upload) deletion = client.files_delete(file=upload["file"]["id"]) self.assertIsNotNone(deletion) @@ -37,9 +35,7 @@ def test_bytes_for_file_param(self): async def test_bytes_for_file_param_async(self): client: AsyncWebClient = AsyncWebClient(token=self.bot_token) bytes = bytearray("This is a test", "utf-8") - upload = await client.files_upload( - file=bytes, filename="test.txt", channels=self.channel_ids - ) + upload = await client.files_upload(file=bytes, filename="test.txt", channels=self.channel_ids) self.assertIsNotNone(upload) deletion = await client.files_delete(file=upload["file"]["id"]) self.assertIsNotNone(deletion) diff --git a/integration_tests/web/test_issue_770.py b/integration_tests/web/test_issue_770.py index 2add51b75..d9cb78aac 100644 --- a/integration_tests/web/test_issue_770.py +++ b/integration_tests/web/test_issue_770.py @@ -31,9 +31,7 @@ def tearDown(self): def test_bytes_for_file_param_bytes(self): client: WebClient = WebClient(token=self.bot_token) bytes = BytesIO(bytearray("This is a test (bytes)", "utf-8")).getvalue() - upload = client.files_upload( - file=bytes, filename="test.txt", channels=self.channel_ids - ) + upload = client.files_upload(file=bytes, filename="test.txt", channels=self.channel_ids) self.assertIsNotNone(upload) deletion = client.files_delete(file=upload["file"]["id"]) self.assertIsNotNone(deletion) @@ -42,9 +40,7 @@ def test_bytes_for_file_param_bytes(self): async def test_bytes_for_file_param_bytes_async(self): client: AsyncWebClient = AsyncWebClient(token=self.bot_token) bytes = BytesIO(bytearray("This is a test (bytes)", "utf-8")).getvalue() - upload = await client.files_upload( - file=bytes, filename="test.txt", channels=self.channel_ids - ) + upload = await client.files_upload(file=bytes, filename="test.txt", channels=self.channel_ids) self.assertIsNotNone(upload) deletion = await client.files_delete(file=upload["file"]["id"]) self.assertIsNotNone(deletion) diff --git a/integration_tests/web/test_web_client.py b/integration_tests/web/test_web_client.py index 5570320cc..14087fa06 100644 --- a/integration_tests/web/test_web_client.py +++ b/integration_tests/web/test_web_client.py @@ -95,9 +95,7 @@ def test_basic_chat_operations(self): "This message was posted by ! " + "(integration_tests/test_web_client.py #test_chat_operations)" ) - new_message: SlackResponse = client.chat_postMessage( - channel=channel, text=message - ) + new_message: SlackResponse = client.chat_postMessage(channel=channel, text=message) self.assertEqual(new_message["message"]["text"], message) ts = new_message["ts"] @@ -114,19 +112,13 @@ def test_basic_chat_operations(self): reactions = client.reactions_get(channel=channel, timestamp=ts) self.assertIsNotNone(reactions) - reaction_removal = client.reactions_remove( - channel=channel, timestamp=ts, name="eyes" - ) + reaction_removal = client.reactions_remove(channel=channel, timestamp=ts, name="eyes") self.assertIsNotNone(reaction_removal) - thread_reply = client.chat_postMessage( - channel=channel, thread_ts=ts, text="threading..." - ) + thread_reply = client.chat_postMessage(channel=channel, thread_ts=ts, text="threading...") self.assertIsNotNone(thread_reply) - modification = client.chat_update( - channel=channel, ts=ts, text="Is this intentional?" - ) + modification = client.chat_update(channel=channel, ts=ts, text="Is this intentional?") self.assertIsNotNone(modification) reply_deletion = client.chat_delete(channel=channel, ts=thread_reply["ts"]) @@ -147,9 +139,7 @@ async def test_basic_chat_operations_async(self): "This message was posted by ! " + "(integration_tests/test_web_client.py #test_chat_operations)" ) - new_message: SlackResponse = await client.chat_postMessage( - channel=channel, text=message - ) + new_message: SlackResponse = await client.chat_postMessage(channel=channel, text=message) self.assertEqual(new_message["message"]["text"], message) ts = new_message["ts"] @@ -160,32 +150,22 @@ async def test_basic_chat_operations_async(self): f"{url}archives/{channel}/.+", ) - new_reaction = await client.reactions_add( - channel=channel, timestamp=ts, name="eyes" - ) + new_reaction = await client.reactions_add(channel=channel, timestamp=ts, name="eyes") self.assertIsNotNone(new_reaction) reactions = await client.reactions_get(channel=channel, timestamp=ts) self.assertIsNotNone(reactions) - reaction_removal = await client.reactions_remove( - channel=channel, timestamp=ts, name="eyes" - ) + reaction_removal = await client.reactions_remove(channel=channel, timestamp=ts, name="eyes") self.assertIsNotNone(reaction_removal) - thread_reply = await client.chat_postMessage( - channel=channel, thread_ts=ts, text="threading..." - ) + thread_reply = await client.chat_postMessage(channel=channel, thread_ts=ts, text="threading...") self.assertIsNotNone(thread_reply) - modification = await client.chat_update( - channel=channel, ts=ts, text="Is this intentional?" - ) + modification = await client.chat_update(channel=channel, ts=ts, text="Is this intentional?") self.assertIsNotNone(modification) - reply_deletion = await client.chat_delete( - channel=channel, ts=thread_reply["ts"] - ) + reply_deletion = await client.chat_delete(channel=channel, ts=thread_reply["ts"]) self.assertIsNotNone(reply_deletion) message_deletion = await client.chat_delete(channel=channel, ts=ts) self.assertIsNotNone(message_deletion) @@ -196,9 +176,7 @@ async def test_basic_chat_operations_async(self): def test_uploading_text_files(self): client = self.sync_client file, filename = __file__, os.path.basename(__file__) - upload = client.files_upload( - channels=self.channel_id, filename=filename, file=file - ) + upload = client.files_upload(channels=self.channel_id, filename=filename, file=file) self.assertIsNotNone(upload) deletion = client.files_delete(file=upload["file"]["id"]) @@ -313,9 +291,7 @@ def test_pagination_with_iterator(self): client = self.sync_client fetched_count = 0 # SlackResponse is an iterator that fetches next if next_cursor is not "" - for response in client.conversations_list( - limit=1, exclude_archived=1, types="public_channel" - ): + for response in client.conversations_list(limit=1, exclude_archived=1, types="public_channel"): fetched_count += len(response["channels"]) if fetched_count > 1: break @@ -331,9 +307,7 @@ def test_pagination_with_iterator_use_sync_aiohttp(self): ) fetched_count = 0 # SlackResponse is an iterator that fetches next if next_cursor is not "" - for response in client.conversations_list( - limit=1, exclude_archived=1, types="public_channel" - ): + for response in client.conversations_list(limit=1, exclude_archived=1, types="public_channel"): fetched_count += len(response["channels"]) if fetched_count > 1: break @@ -346,9 +320,7 @@ async def test_pagination_with_iterator_async(self): client = self.async_client fetched_count = 0 # SlackResponse is an iterator that fetches next if next_cursor is not "" - for response in await client.conversations_list( - limit=1, exclude_archived=1, types="public_channel" - ): + for response in await client.conversations_list(limit=1, exclude_archived=1, types="public_channel"): fetched_count += len(response["channels"]) if fetched_count > 1: break diff --git a/integration_tests/webhook/test_async_webhook.py b/integration_tests/webhook/test_async_webhook.py index c5dab75c4..911382873 100644 --- a/integration_tests/webhook/test_async_webhook.py +++ b/integration_tests/webhook/test_async_webhook.py @@ -21,9 +21,7 @@ class TestAsyncWebhook(unittest.TestCase): async def setUp(self): if not hasattr(self, "channel_id"): token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - channel_name = os.environ[ - SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME - ].replace("#", "") + channel_name = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME].replace("#", "") client = AsyncWebClient(token=token) self.channel_id = None async for resp in await client.conversations_list(limit=1000): @@ -105,9 +103,7 @@ async def test_with_blocks(self): blocks=[ SectionBlock( block_id="sb-id", - text=MarkdownTextObject( - text="This is a mrkdwn text section block." - ), + text=MarkdownTextObject(text="This is a mrkdwn text section block."), fields=[ PlainTextObject(text="*this is plain_text text*", emoji=True), MarkdownTextObject(text="*this is mrkdwn text*"), @@ -219,12 +215,7 @@ async def test_with_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField( - title=f"field_{i}_title", value=f"field_{i}_value" - ) - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", diff --git a/integration_tests/webhook/test_webhook.py b/integration_tests/webhook/test_webhook.py index 78fb39837..a9aa46897 100644 --- a/integration_tests/webhook/test_webhook.py +++ b/integration_tests/webhook/test_webhook.py @@ -21,9 +21,7 @@ class TestWebhook(unittest.TestCase): def setUp(self): if not hasattr(self, "channel_id"): token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - channel_name = os.environ[ - SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME - ].replace("#", "") + channel_name = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME].replace("#", "") client = WebClient(token=token) self.channel_id = None for resp in client.conversations_list(limit=1000): @@ -102,9 +100,7 @@ def test_with_blocks(self): blocks=[ SectionBlock( block_id="sb-id", - text=MarkdownTextObject( - text="This is a mrkdwn text section block." - ), + text=MarkdownTextObject(text="This is a mrkdwn text section block."), fields=[ PlainTextObject(text="*this is plain_text text*", emoji=True), MarkdownTextObject(text="*this is mrkdwn text*"), @@ -214,12 +210,7 @@ def test_with_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField( - title=f"field_{i}_title", value=f"field_{i}_value" - ) - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..0cda914cd --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,4 @@ +# black project prefers pyproject.toml +# that's why we have this file in addition to other setting files +[tool.black] +line-length = 125 \ No newline at end of file diff --git a/slack/deprecation.py b/slack/deprecation.py index 996a7e562..6352e66a7 100644 --- a/slack/deprecation.py +++ b/slack/deprecation.py @@ -3,9 +3,7 @@ def show_message(old: str, new: str) -> None: - skip_deprecation = os.environ.get( - "SLACKCLIENT_SKIP_DEPRECATION" - ) # for unit tests etc. + skip_deprecation = os.environ.get("SLACKCLIENT_SKIP_DEPRECATION") # for unit tests etc. if skip_deprecation: return diff --git a/slack/signature/verifier.py b/slack/signature/verifier.py index 9217502b0..f5923ced8 100644 --- a/slack/signature/verifier.py +++ b/slack/signature/verifier.py @@ -55,9 +55,7 @@ def is_valid( return False return hmac.compare_digest(calculated_signature, signature) - def generate_signature( - self, *, timestamp: str, body: Union[str, bytes] - ) -> Optional[str]: + def generate_signature(self, *, timestamp: str, body: Union[str, bytes]) -> Optional[str]: """Generates a signature""" if timestamp is None: return None diff --git a/slack/web/async_base_client.py b/slack/web/async_base_client.py index be925dba8..9347bac71 100644 --- a/slack/web/async_base_client.py +++ b/slack/web/async_base_client.py @@ -41,9 +41,7 @@ def __init__( # https://github.com/slackapi/python-slack-sdk/issues/738 self.trust_env_in_session = trust_env_in_session self.headers = headers or {} - self.headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self._logger = logging.getLogger(__name__) async def api_call( # skipcq: PYL-R1710 @@ -116,9 +114,7 @@ async def api_call( # skipcq: PYL-R1710 req_args=req_args, ) - async def _send( - self, http_verb: str, api_url: str, req_args: dict - ) -> AsyncSlackResponse: + async def _send(self, http_verb: str, api_url: str, req_args: dict) -> AsyncSlackResponse: """Sends the request out for transmission. Args: @@ -141,9 +137,7 @@ async def _send( # 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 - ) + res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args) finally: for f in open_files: f.close() diff --git a/slack/web/async_internal_utils.py b/slack/web/async_internal_utils.py index ccad1abf7..79291571e 100644 --- a/slack/web/async_internal_utils.py +++ b/slack/web/async_internal_utils.py @@ -183,9 +183,7 @@ async def _request_with_session( try: data = await res.json() except aiohttp.ContentTypeError: - logger.debug( - f"No response data returned from the following API call: {api_url}." - ) + logger.debug(f"No response data returned from the following API call: {api_url}.") except json.decoder.JSONDecodeError as e: message = f"Failed to parse the response body: {str(e)}" raise SlackApiError(message, res) diff --git a/slack/web/async_slack_response.py b/slack/web/async_slack_response.py index 9f65c733d..150bc519e 100644 --- a/slack/web/async_slack_response.py +++ b/slack/web/async_slack_response.py @@ -75,9 +75,7 @@ def __init__( def __str__(self): """Return the Response data if object is converted to a string.""" if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") return f"{self.data}" def __contains__(self, key: str) -> bool: @@ -95,13 +93,9 @@ def __getitem__(self, key): The value from data or None. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") if self.data is None: - raise ValueError( - "As the response.data is empty, this operation is unsupported" - ) + raise ValueError("As the response.data is empty, this operation is unsupported") return self.data.get(key, None) def __aiter__(self): @@ -172,9 +166,7 @@ def get(self, key, default=None): The value from data or the specified default. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") if self.data is None: return None return self.data.get(key, default) diff --git a/slack/web/base_client.py b/slack/web/base_client.py index ffd1917e6..a5b435669 100644 --- a/slack/web/base_client.py +++ b/slack/web/base_client.py @@ -63,9 +63,7 @@ def __init__( self.use_sync_aiohttp = use_sync_aiohttp self.session = session self.headers = headers or {} - self.headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self._logger = logging.getLogger(__name__) self._event_loop = loop @@ -153,9 +151,7 @@ def api_call( # skipcq: PYL-R1710 # aiohttp based async WebClient # ================================================================= - async def _send( - self, http_verb: str, api_url: str, req_args: dict - ) -> SlackResponse: + async def _send(self, http_verb: str, api_url: str, req_args: dict) -> SlackResponse: """Sends the request out for transmission. Args: @@ -178,9 +174,7 @@ async def _send( # 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 - ) + res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args) finally: for f in open_files: f.close() @@ -219,18 +213,14 @@ def _sync_send(self, api_url, req_args) -> SlackResponse: _json = req_args["json"] if "json" in req_args else None headers = req_args["headers"] if "headers" in req_args else None token = params.get("token") if params and "token" in params else None - auth = ( - req_args["auth"] if "auth" in req_args else None - ) # Basic Auth for oauth.v2.access / oauth.access + auth = req_args["auth"] if "auth" in req_args else None # Basic Auth for oauth.v2.access / oauth.access if auth is not None: if isinstance(auth, BasicAuth): headers["Authorization"] = auth.encode() elif isinstance(auth, str): headers["Authorization"] = auth else: - self._logger.warning( - f"As the auth: {auth}: {type(auth)} is unsupported, skipped" - ) + self._logger.warning(f"As the auth: {auth}: {type(auth)} is unsupported, skipped") body_params = {} if params: @@ -285,15 +275,9 @@ def _urllib_api_call( def convert_params(values: dict) -> dict: if not values or not isinstance(values, dict): return {} - return { - k: ("(bytes)" if isinstance(v, bytes) else v) - for k, v in values.items() - } - - headers = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in additional_headers.items() - } + return {k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items()} + + headers = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in additional_headers.items()} self._logger.debug( f"Sending a request - url: {url}, " f"query_params: {convert_params(query_params)}, " @@ -368,9 +352,7 @@ def convert_params(values: dict) -> dict: if not f.closed: f.close() - def _perform_urllib_http_request( - self, *, url: str, args: Dict[str, Dict[str, any]] - ) -> Dict[str, any]: + def _perform_urllib_http_request(self, *, url: str, args: Dict[str, Dict[str, any]]) -> Dict[str, any]: headers = args["headers"] if args["json"]: body = json.dumps(args["json"]) @@ -387,16 +369,10 @@ def _perform_urllib_http_request( filename = "Uploaded file" name_attr = getattr(value, "name", None) if name_attr: - filename = ( - name_attr.decode("utf-8") - if isinstance(name_attr, bytes) - else name_attr - ) + filename = name_attr.decode("utf-8") if isinstance(name_attr, bytes) else name_attr if "filename" in data: filename = data["filename"] - mimetype = ( - mimetypes.guess_type(filename)[0] or "application/octet-stream" - ) + mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" title = ( f'\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\n' + f"Content-Type: {mimetype}\r\n" @@ -440,18 +416,14 @@ def _perform_urllib_http_request( HTTPSHandler(context=self.ssl), ) else: - raise SlackRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") # NOTE: BAN-B310 is already checked above resp: Optional[HTTPResponse] = None if opener: resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: - resp = urlopen( # skipcq: BAN-B310 - req, context=self.ssl, timeout=self.timeout - ) + resp = urlopen(req, context=self.ssl, timeout=self.timeout) # skipcq: BAN-B310 charset = resp.headers.get_content_charset() or "utf-8" body: str = resp.read().decode(charset) # read the response body here return {"status": resp.code, "headers": resp.headers, "body": body} @@ -490,9 +462,7 @@ def _build_urllib_request_headers( # ================================================================= @staticmethod - def validate_slack_signature( - *, signing_secret: str, data: str, timestamp: str, signature: str - ) -> bool: + def validate_slack_signature(*, signing_secret: str, data: str, timestamp: str, signature: str) -> bool: """ Slack creates a unique string for your app and shares it with you. Verify requests from Slack with confidence by verifying signatures using your diff --git a/slack/web/classes/interactions.py b/slack/web/classes/interactions.py index fe5b0481c..f4d871efa 100644 --- a/slack/web/classes/interactions.py +++ b/slack/web/classes/interactions.py @@ -42,9 +42,7 @@ def __init__(self, event: dict): super().__init__(event) self.user = IDNamePair(event["user"]["id"], event["user"]["username"]) self.team: IDNamePair = IDNamePair(event["team"]["id"], event["team"]["domain"]) - self.channel: IDNamePair = IDNamePair( - event["channel"]["id"], event["channel"]["name"] - ) + self.channel: IDNamePair = IDNamePair(event["channel"]["id"], event["channel"]["name"]) self.event_type = event["type"] self.message_ts = event["message"]["ts"] self.trigger_id = event["trigger_id"] @@ -92,9 +90,7 @@ def require_any(self, requirements: List[str]) -> dict: Args: requirements: List of required dialog components, by name """ - if any( # skipcq: PYL-R1705 - self.submission.get(requirement, "") for requirement in requirements - ): + if any(self.submission.get(requirement, "") for requirement in requirements): # skipcq: PYL-R1705 return {} else: errors = [] diff --git a/slack/web/deprecation.py b/slack/web/deprecation.py index 7781e0bfc..5ce5f067e 100644 --- a/slack/web/deprecation.py +++ b/slack/web/deprecation.py @@ -14,19 +14,13 @@ def show_2020_01_deprecation(method_name: str): """Prints a warning if the given method is deprecated""" - skip_deprecation = os.environ.get( - "SLACKCLIENT_SKIP_DEPRECATION" - ) # for unit tests etc. + skip_deprecation = os.environ.get("SLACKCLIENT_SKIP_DEPRECATION") # for unit tests etc. if skip_deprecation: return if not method_name: return - matched_prefixes = [ - prefix - for prefix in deprecated_method_prefixes_2020_01 - if method_name.startswith(prefix) - ] + matched_prefixes = [prefix for prefix in deprecated_method_prefixes_2020_01 if method_name.startswith(prefix)] if len(matched_prefixes) > 0: message = ( f"{method_name} is deprecated. Please use the Conversations API instead. " diff --git a/slack/webhook/async_client.py b/slack/webhook/async_client.py index 849f6c880..31310c96f 100644 --- a/slack/webhook/async_client.py +++ b/slack/webhook/async_client.py @@ -66,24 +66,18 @@ async def send( headers=headers, ) - async def send_dict( - self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None - ) -> WebhookResponse: + async def send_dict(self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse: return await self._perform_http_request( body=_build_body(body), headers=_build_request_headers(self.default_headers, headers), ) - async def _perform_http_request( - self, *, body: Dict[str, any], headers: Dict[str, str] - ) -> WebhookResponse: + async def _perform_http_request(self, *, body: Dict[str, any], headers: Dict[str, str]) -> WebhookResponse: body = json.dumps(body) headers["Content-Type"] = "application/json;charset=utf-8" if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Sending a request - url: {self.url}, body: {body}, headers: {headers}" - ) + self.logger.debug(f"Sending a request - url: {self.url}, body: {body}, headers: {headers}") session: Optional[ClientSession] = None use_running_session = self.session and not self.session.closed if use_running_session: @@ -107,9 +101,7 @@ async def _perform_http_request( try: response_body = await res.text() except aiohttp.ContentTypeError: - self._logger.debug( - f"No response data returned from the following API call: {self.url}." - ) + self._logger.debug(f"No response data returned from the following API call: {self.url}.") except json.decoder.JSONDecodeError as e: message = f"Failed to parse the response body: {str(e)}" raise SlackApiError(message, res) diff --git a/slack/webhook/client.py b/slack/webhook/client.py index bd1b62071..7d39c03df 100644 --- a/slack/webhook/client.py +++ b/slack/webhook/client.py @@ -50,32 +50,24 @@ def send( headers=headers, ) - def send_dict( - self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None - ) -> WebhookResponse: + def send_dict(self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse: return self._perform_http_request( body=_build_body(body), headers=_build_request_headers(self.default_headers, headers), ) - def _perform_http_request( - self, *, body: Dict[str, any], headers: Dict[str, str] - ) -> WebhookResponse: + def _perform_http_request(self, *, body: Dict[str, any], headers: Dict[str, str]) -> WebhookResponse: body = json.dumps(body) headers["Content-Type"] = "application/json;charset=utf-8" if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Sending a request - url: {self.url}, body: {body}, headers: {headers}" - ) + self.logger.debug(f"Sending a request - url: {self.url}, body: {body}, headers: {headers}") try: url = self.url opener: Optional[OpenerDirector] = None # for security (BAN-B310) if url.lower().startswith("http"): - req = Request( - method="POST", url=url, data=body.encode("utf-8"), headers=headers - ) + req = Request(method="POST", url=url, data=body.encode("utf-8"), headers=headers) if self.proxy is not None: if isinstance(self.proxy, str): opener = urllib.request.build_opener( @@ -83,9 +75,7 @@ def _perform_http_request( HTTPSHandler(context=self.ssl), ) else: - raise SlackRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") else: raise SlackRequestError(f"Invalid URL detected: {url}") @@ -94,9 +84,7 @@ def _perform_http_request( if opener: resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: - resp = urlopen( # skipcq: BAN-B310 - req, context=self.ssl, timeout=self.timeout - ) + resp = urlopen(req, context=self.ssl, timeout=self.timeout) # skipcq: BAN-B310 charset: str = resp.headers.get_content_charset() or "utf-8" response_body: str = resp.read().decode(charset) resp = WebhookResponse( diff --git a/slack_sdk/aiohttp_version_checker.py b/slack_sdk/aiohttp_version_checker.py index 74ca408eb..9f4d70fc3 100644 --- a/slack_sdk/aiohttp_version_checker.py +++ b/slack_sdk/aiohttp_version_checker.py @@ -16,9 +16,7 @@ def validate_aiohttp_version( if len(elements) >= 3: # patch version can be a non-numeric value major, minor, patch = int(elements[0]), int(elements[1]), elements[2] - if major <= 2 or ( - major == 3 and (minor == 6 or (minor == 7 and patch == "0")) - ): + if major <= 2 or (major == 3 and (minor == 6 or (minor == 7 and patch == "0"))): print_warning( "We highly recommend upgrading aiohttp to 3.7.3 or higher versions." "An older version of the library may not work with the Slack server-side in the future." diff --git a/slack_sdk/audit_logs/v1/async_client.py b/slack_sdk/audit_logs/v1/async_client.py index 5f01f7c76..8d8290906 100644 --- a/slack_sdk/audit_logs/v1/async_client.py +++ b/slack_sdk/audit_logs/v1/async_client.py @@ -84,13 +84,9 @@ def __init__( self.trust_env_in_session = trust_env_in_session self.auth = auth self.default_headers = default_headers if default_headers else {} - self.default_headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.logger = logger if logger is not None else logging.getLogger(__name__) - self.retry_handlers = ( - retry_handlers if retry_handlers is not None else async_default_handlers() - ) + self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers() if self.proxy is None or len(self.proxy.strip()) == 0: env_variable = load_http_proxy_from_env(self.logger) @@ -271,8 +267,7 @@ async def _perform_http_request( if self.logger.level <= logging.DEBUG: headers_for_logging = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in headers.items() + k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items() } self.logger.debug( f"Sending a request - " @@ -289,14 +284,10 @@ async def _perform_http_request( retry_response = RetryHttpResponse( status_code=res.status, headers=res.headers, - data=response_body.encode("utf-8") - if response_body is not None - else None, + data=response_body.encode("utf-8") if response_body is not None else None, ) except aiohttp.ContentTypeError: - self.logger.debug( - f"No response data returned from the following API call: {url}." - ) + self.logger.debug(f"No response data returned from the following API call: {url}.") except json.decoder.JSONDecodeError as e: message = f"Failed to parse the response body: {str(e)}" raise SlackApiError(message, res) @@ -341,8 +332,7 @@ async def _perform_http_request( ): if self.logger.level <= logging.DEBUG: self.logger.info( - f"A retry handler found: {type(handler).__name__} " - f"for {http_verb} {url} - {e}" + f"A retry handler found: {type(handler).__name__} " f"for {http_verb} {url} - {e}" ) await handler.prepare_for_next_attempt_async( state=retry_state, diff --git a/slack_sdk/audit_logs/v1/client.py b/slack_sdk/audit_logs/v1/client.py index ba0b3bbea..27e7cce95 100644 --- a/slack_sdk/audit_logs/v1/client.py +++ b/slack_sdk/audit_logs/v1/client.py @@ -73,13 +73,9 @@ def __init__( self.proxy = proxy self.base_url = base_url self.default_headers = default_headers if default_headers else {} - self.default_headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.logger = logger if logger is not None else logging.getLogger(__name__) - self.retry_handlers = ( - retry_handlers if retry_handlers is not None else default_retry_handlers() - ) + self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers() if self.proxy is None or len(self.proxy.strip()) == 0: env_variable = load_http_proxy_from_env(self.logger) @@ -225,13 +221,8 @@ def _perform_http_request( headers["Content-Type"] = "application/json;charset=utf-8" if self.logger.level <= logging.DEBUG: - headers_for_logging = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in headers.items() - } - self.logger.debug( - f"Sending a request - url: {url}, body: {body}, headers: {headers_for_logging}" - ) + headers_for_logging = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()} + self.logger.debug(f"Sending a request - url: {url}, body: {body}, headers: {headers_for_logging}") # NOTE: Intentionally ignore the `http_verb` here # Slack APIs accepts any API method requests with POST methods @@ -270,15 +261,9 @@ def _perform_http_request( ) if e.code == 429: # for backward-compatibility with WebClient (v.2.5.0 or older) - if ( - "retry-after" not in resp.headers - and "Retry-After" in resp.headers - ): + if "retry-after" not in resp.headers and "Retry-After" in resp.headers: resp.headers["retry-after"] = resp.headers["Retry-After"] - if ( - "Retry-After" not in resp.headers - and "retry-after" in resp.headers - ): + if "Retry-After" not in resp.headers and "retry-after" in resp.headers: resp.headers["Retry-After"] = resp.headers["retry-after"] _debug_log_response(self.logger, resp) @@ -287,9 +272,7 @@ def _perform_http_request( retry_response = RetryHttpResponse( status_code=e.code, headers={k: [v] for k, v in e.headers.items()}, - data=response_body.encode("utf-8") - if response_body is not None - else None, + data=response_body.encode("utf-8") if response_body is not None else None, ) for handler in self.retry_handlers: if handler.can_retry( @@ -315,9 +298,7 @@ def _perform_http_request( except Exception as err: last_error = err - self.logger.error( - f"Failed to send a request to Slack API server: {err}" - ) + self.logger.error(f"Failed to send a request to Slack API server: {err}") # Try to find a retry handler for this error retry_request = RetryHttpRequest.from_urllib_http_request(req) @@ -338,9 +319,7 @@ def _perform_http_request( response=None, error=err, ) - self.logger.info( - f"Going to retry the same request: {req.method} {req.full_url}" - ) + self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}") break if retry_state.next_attempt_requested is False: @@ -350,9 +329,7 @@ def _perform_http_request( return resp raise last_error - def _perform_http_request_internal( - self, url: str, req: Request - ) -> AuditLogsResponse: + def _perform_http_request_internal(self, url: str, req: Request) -> AuditLogsResponse: opener: Optional[OpenerDirector] = None # for security (BAN-B310) if url.lower().startswith("http"): @@ -363,9 +340,7 @@ def _perform_http_request_internal( HTTPSHandler(context=self.ssl), ) else: - raise SlackRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") else: raise SlackRequestError(f"Invalid URL detected: {url}") @@ -374,9 +349,7 @@ def _perform_http_request_internal( if opener: http_resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: - http_resp = urlopen( # skipcq: BAN-B310 - req, context=self.ssl, timeout=self.timeout - ) + http_resp = urlopen(req, context=self.ssl, timeout=self.timeout) # skipcq: BAN-B310 charset: str = http_resp.headers.get_content_charset() or "utf-8" response_body: str = http_resp.read().decode(charset) resp = AuditLogsResponse( diff --git a/slack_sdk/audit_logs/v1/internal_utils.py b/slack_sdk/audit_logs/v1/internal_utils.py index e1e88fee8..c4521c7eb 100644 --- a/slack_sdk/audit_logs/v1/internal_utils.py +++ b/slack_sdk/audit_logs/v1/internal_utils.py @@ -8,13 +8,7 @@ def _build_query(params: Optional[Dict[str, Any]]) -> str: if params is not None and len(params) > 0: - return "&".join( - { - f"{quote(str(k))}={quote(str(v))}" - for k, v in params.items() - if v is not None - } - ) + return "&".join({f"{quote(str(k))}={quote(str(v))}" for k, v in params.items() if v is not None}) return "" diff --git a/slack_sdk/audit_logs/v1/logs.py b/slack_sdk/audit_logs/v1/logs.py index 197c2f7dd..ee743657d 100644 --- a/slack_sdk/audit_logs/v1/logs.py +++ b/slack_sdk/audit_logs/v1/logs.py @@ -318,12 +318,8 @@ def __init__( self.non_sso_only = non_sso_only self.type = type self.is_workflow = is_workflow - self.inviter = ( - inviter if inviter is None or isinstance(inviter, User) else User(**inviter) - ) - self.kicker = ( - kicker if kicker is None or isinstance(kicker, User) else User(**kicker) - ) + self.inviter = inviter if inviter is None or isinstance(inviter, User) else User(**inviter) + self.kicker = kicker if kicker is None or isinstance(kicker, User) else User(**kicker) self.shared_to = shared_to self.reason = reason self.origin_team = origin_team @@ -370,14 +366,12 @@ def __init__( self.is_token_rotation_enabled_app = is_token_rotation_enabled_app self.old_retention_policy = ( old_retention_policy - if old_retention_policy is None - or isinstance(old_retention_policy, RetentionPolicy) + if old_retention_policy is None or isinstance(old_retention_policy, RetentionPolicy) else RetentionPolicy(**old_retention_policy) ) self.new_retention_policy = ( new_retention_policy - if new_retention_policy is None - or isinstance(new_retention_policy, RetentionPolicy) + if new_retention_policy is None or isinstance(new_retention_policy, RetentionPolicy) else RetentionPolicy(**new_retention_policy) ) self.who_can_post = ( @@ -386,9 +380,7 @@ def __init__( else ConversationPref(**who_can_post) ) self.can_thread = ( - can_thread - if can_thread is None or isinstance(can_thread, ConversationPref) - else ConversationPref(**can_thread) + can_thread if can_thread is None or isinstance(can_thread, ConversationPref) else ConversationPref(**can_thread) ) self.is_external_limited = is_external_limited self.exporting_team_id = exporting_team_id @@ -405,8 +397,7 @@ def __init__( ) self.enable_at_channel = ( enable_at_channel - if enable_at_channel is None - or isinstance(enable_at_channel, FeatureEnablement) + if enable_at_channel is None or isinstance(enable_at_channel, FeatureEnablement) else FeatureEnablement(**enable_at_channel) ) self.can_huddle = ( @@ -561,22 +552,14 @@ def __init__( ) -> None: self.type = type self.user = User(**user) if isinstance(user, dict) else user - self.workspace = ( - Location(**workspace) if isinstance(workspace, dict) else workspace - ) - self.enterprise = ( - Location(**enterprise) if isinstance(enterprise, dict) else enterprise - ) + self.workspace = Location(**workspace) if isinstance(workspace, dict) else workspace + self.enterprise = Location(**enterprise) if isinstance(enterprise, dict) else enterprise self.channel = Channel(**channel) if isinstance(channel, dict) else channel self.file = File(**file) if isinstance(file, dict) else file self.app = App(**app) if isinstance(app, dict) else app - self.usergroup = ( - Usergroup(**usergroup) if isinstance(usergroup, dict) else usergroup - ) + self.usergroup = Usergroup(**usergroup) if isinstance(usergroup, dict) else usergroup self.workflow = Workflow(**workflow) if isinstance(workflow, dict) else workflow - self.barrier = ( - InformationBarrier(**barrier) if isinstance(barrier, dict) else barrier - ) + self.barrier = InformationBarrier(**barrier) if isinstance(barrier, dict) else barrier self.unknown_fields = kwargs @@ -648,9 +631,7 @@ def __init__( ) -> None: self.entries = [Entry(**e) if isinstance(e, dict) else e for e in entries] self.response_metadata = ( - ResponseMetadata(**response_metadata) - if isinstance(response_metadata, dict) - else response_metadata + ResponseMetadata(**response_metadata) if isinstance(response_metadata, dict) else response_metadata ) self.ok = ok self.error = error diff --git a/slack_sdk/audit_logs/v1/response.py b/slack_sdk/audit_logs/v1/response.py index 013f47cdc..9fe66d04d 100644 --- a/slack_sdk/audit_logs/v1/response.py +++ b/slack_sdk/audit_logs/v1/response.py @@ -31,8 +31,4 @@ def __init__( self.status_code = status_code self.headers = headers self.raw_body = raw_body - self.body = ( - json.loads(raw_body) - if raw_body is not None and raw_body.startswith("{") - else None - ) + self.body = json.loads(raw_body) if raw_body is not None and raw_body.startswith("{") else None diff --git a/slack_sdk/http_retry/async_handler.py b/slack_sdk/http_retry/async_handler.py index 6060b32e9..ed9f6115a 100644 --- a/slack_sdk/http_retry/async_handler.py +++ b/slack_sdk/http_retry/async_handler.py @@ -74,9 +74,7 @@ async def prepare_for_next_attempt_async( error: Optional[Exception] = None, ) -> None: state.next_attempt_requested = True - duration = self.interval_calculator.calculate_sleep_duration( - state.current_attempt - ) + duration = self.interval_calculator.calculate_sleep_duration(state.current_attempt) await asyncio.sleep(duration) state.increment_current_attempt() diff --git a/slack_sdk/http_retry/builtin_async_handlers.py b/slack_sdk/http_retry/builtin_async_handlers.py index ac05d76dc..9993f5e60 100644 --- a/slack_sdk/http_retry/builtin_async_handlers.py +++ b/slack_sdk/http_retry/builtin_async_handlers.py @@ -81,9 +81,7 @@ async def prepare_for_next_attempt_async( # This situation usually does not arise. Just in case. duration += random.random() else: - duration = ( - int(response.headers.get(retry_after_header_name)[0]) + random.random() - ) + duration = int(response.headers.get(retry_after_header_name)[0]) + random.random() await asyncio.sleep(duration) state.increment_current_attempt() diff --git a/slack_sdk/http_retry/builtin_handlers.py b/slack_sdk/http_retry/builtin_handlers.py index 6fbb5cee6..d8ac13dce 100644 --- a/slack_sdk/http_retry/builtin_handlers.py +++ b/slack_sdk/http_retry/builtin_handlers.py @@ -84,8 +84,6 @@ def prepare_for_next_attempt( # This situation usually does not arise. Just in case. duration += random.random() else: - duration = ( - int(response.headers.get(retry_after_header_name)[0]) + random.random() - ) + duration = int(response.headers.get(retry_after_header_name)[0]) + random.random() time.sleep(duration) state.increment_current_attempt() diff --git a/slack_sdk/http_retry/handler.py b/slack_sdk/http_retry/handler.py index 671aace1b..7c8aa46bd 100644 --- a/slack_sdk/http_retry/handler.py +++ b/slack_sdk/http_retry/handler.py @@ -75,8 +75,6 @@ def prepare_for_next_attempt( error: Optional[Exception] = None, ) -> None: state.next_attempt_requested = True - duration = self.interval_calculator.calculate_sleep_duration( - state.current_attempt - ) + duration = self.interval_calculator.calculate_sleep_duration(state.current_attempt) time.sleep(duration) state.increment_current_attempt() diff --git a/slack_sdk/http_retry/request.py b/slack_sdk/http_retry/request.py index eadd9b598..76db4a419 100644 --- a/slack_sdk/http_retry/request.py +++ b/slack_sdk/http_retry/request.py @@ -22,9 +22,7 @@ def __init__( ): self.method = method self.url = url - self.headers = { - k: v if isinstance(v, list) else [v] for k, v in headers.items() - } + self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()} self.body_params = body_params self.data = data @@ -33,8 +31,6 @@ def from_urllib_http_request(cls, req: Request) -> "HttpRequest": return HttpRequest( method=req.method, url=req.full_url, - headers={ - k: v if isinstance(v, list) else [v] for k, v in req.headers.items() - }, + headers={k: v if isinstance(v, list) else [v] for k, v in req.headers.items()}, data=req.data, ) diff --git a/slack_sdk/http_retry/response.py b/slack_sdk/http_retry/response.py index 028f8230a..282681059 100644 --- a/slack_sdk/http_retry/response.py +++ b/slack_sdk/http_retry/response.py @@ -18,8 +18,6 @@ def __init__( data: Optional[bytes] = None, ): self.status_code = int(status_code) - self.headers = { - k: v if isinstance(v, list) else [v] for k, v in headers.items() - } + self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()} self.body = body self.data = data diff --git a/slack_sdk/models/__init__.py b/slack_sdk/models/__init__.py index 4ac135aa3..f3e9e3489 100644 --- a/slack_sdk/models/__init__.py +++ b/slack_sdk/models/__init__.py @@ -25,14 +25,11 @@ def extract_json( """ try: return [ # type: ignore - elem.to_dict(*format_args) if isinstance(elem, JsonObject) else elem - for elem in item_or_items + elem.to_dict(*format_args) if isinstance(elem, JsonObject) else elem for elem in item_or_items ] except TypeError: # not iterable, so try returning it as a single item return ( # type: ignore - item_or_items.to_dict(*format_args) - if isinstance(item_or_items, JsonObject) - else item_or_items + item_or_items.to_dict(*format_args) if isinstance(item_or_items, JsonObject) else item_or_items ) diff --git a/slack_sdk/models/attachments/__init__.py b/slack_sdk/models/attachments/__init__.py index c8cbcbeb3..6a40df9ba 100644 --- a/slack_sdk/models/attachments/__init__.py +++ b/slack_sdk/models/attachments/__init__.py @@ -127,9 +127,7 @@ class AbstractActionSelector(Action, metaclass=ABCMeta): def data_source(self) -> str: pass - def __init__( - self, *, name: str, text: str, selected_option: Optional[Option] = None - ): + def __init__(self, *, name: str, text: str, selected_option: Optional[Option] = None): super().__init__(text=text, name=name, subtype="select") self.selected_option = selected_option @@ -191,9 +189,7 @@ def __init__(self, name: str, text: str, selected_channel: Optional[Option] = No class ActionConversationSelector(AbstractActionSelector): data_source = "conversations" - def __init__( - self, name: str, text: str, selected_conversation: Optional[Option] = None - ): + def __init__(self, name: str, text: str, selected_conversation: Optional[Option] = None): """ Automatically populate the selector with a list of conversations they have in the workspace. @@ -396,13 +392,9 @@ def ts_without_footer(self) -> bool: @EnumValidator("markdown_in", MarkdownFields) def markdown_in_valid(self): - return not self.markdown_in or all( - e in self.MarkdownFields for e in self.markdown_in - ) + return not self.markdown_in or all(e in self.MarkdownFields for e in self.markdown_in) - @JsonValidator( - "color attribute must be 'good', 'warning', 'danger', or a hex color code" - ) + @JsonValidator("color attribute must be 'good', 'warning', 'danger', or a hex color code") def color_valid(self) -> bool: return ( self.color is None diff --git a/slack_sdk/models/basic_objects.py b/slack_sdk/models/basic_objects.py index 9943aa67f..232ec21ea 100644 --- a/slack_sdk/models/basic_objects.py +++ b/slack_sdk/models/basic_objects.py @@ -37,17 +37,13 @@ def get_non_null_attributes(self) -> dict: present on this object """ - def to_dict_compatible( - value: Union[dict, list, object, Tuple] - ) -> Union[dict, list, Any]: + def to_dict_compatible(value: Union[dict, list, object, Tuple]) -> Union[dict, list, Any]: if isinstance(value, (list, Tuple)): # skipcq: PYL-R1705 return [to_dict_compatible(v) for v in value] else: to_dict = getattr(value, "to_dict", None) if to_dict and callable(to_dict): # skipcq: PYL-R1705 - return { - k: to_dict_compatible(v) for k, v in value.to_dict().items() # type: ignore - } + return {k: to_dict_compatible(v) for k, v in value.to_dict().items()} # type: ignore else: return value @@ -62,9 +58,7 @@ def is_not_empty(self, key: str) -> bool: return value is not None return { - key: to_dict_compatible(getattr(self, key, None)) - for key in sorted(self.attributes) - if is_not_empty(self, key) + key: to_dict_compatible(getattr(self, key, None)) for key in sorted(self.attributes) if is_not_empty(self, key) } def to_dict(self, *args) -> dict: @@ -116,7 +110,4 @@ def wrapped_f(*args, **kwargs): class EnumValidator(JsonValidator): def __init__(self, attribute: str, enum: Iterable[str]): - super().__init__( - f"{attribute} attribute must be one of the following values: " - f"{', '.join(enum)}" - ) + super().__init__(f"{attribute} attribute must be one of the following values: " f"{', '.join(enum)}") diff --git a/slack_sdk/models/blocks/basic_components.py b/slack_sdk/models/blocks/basic_components.py index 363960cd9..1e708ffa6 100644 --- a/slack_sdk/models/blocks/basic_components.py +++ b/slack_sdk/models/blocks/basic_components.py @@ -53,9 +53,7 @@ def parse( elif isinstance(text, TextObject): return text else: - cls.logger.warning( - f"Unknown type ({type(text)}) detected when parsing a TextObject" - ) + cls.logger.warning(f"Unknown type ({type(text)}) detected when parsing a TextObject") return None def __init__( @@ -254,20 +252,14 @@ def _validate_label_length(self) -> bool: @JsonValidator(f"text attribute cannot exceed {label_max_length} characters") def _validate_text_length(self) -> bool: - return ( - self._text is None - or self._text.text is None - or len(self._text.text) <= self.label_max_length - ) + return self._text is None or self._text.text is None or len(self._text.text) <= self.label_max_length @JsonValidator(f"value attribute cannot exceed {value_max_length} characters") def _validate_value_length(self) -> bool: return len(self.value) <= self.value_max_length @classmethod - def parse_all( - cls, options: Optional[Sequence[Union[Dict[str, Any], "Option"]]] - ) -> Optional[List["Option"]]: + def parse_all(cls, options: Optional[Sequence[Union[Dict[str, Any], "Option"]]]) -> Optional[List["Option"]]: if options is None: return None option_objects: List[Option] = [] @@ -281,9 +273,7 @@ def parse_all( cls.logger.warning(f"Unknown option object detected and skipped ({o})") return option_objects - def to_dict( - self, option_type: str = "block" - ) -> Dict[str, Any]: # skipcq: PYL-W0221 + def to_dict(self, option_type: str = "block") -> Dict[str, Any]: # skipcq: PYL-W0221 """ Different parent classes must call this with a valid value from OptionTypes - either "dialog", "action", or "block", so that JSON is returned in the @@ -353,9 +343,7 @@ def __init__( options: A list of no more than 100 Option objects. """ # noqa prevent flake8 blowing up on the long URL # default_type=PlainTextObject.type is for backward-compatibility - self._label: Optional[TextObject] = TextObject.parse( - label, default_type=PlainTextObject.type - ) + self._label: Optional[TextObject] = TextObject.parse(label, default_type=PlainTextObject.type) self.label: Optional[str] = self._label.text if self._label else None self.options = Option.parse_all(options) # compatible with version 2.5 show_unknown_key_warning(self, others) @@ -382,14 +370,10 @@ def parse_all( elif isinstance(o, OptionGroup): option_group_objects.append(o) else: - cls.logger.warning( - f"Unknown option group object detected and skipped ({o})" - ) + cls.logger.warning(f"Unknown option group object detected and skipped ({o})") return option_group_objects - def to_dict( - self, option_type: str = "block" - ) -> Dict[str, Any]: # skipcq: PYL-W0221 + def to_dict(self, option_type: str = "block") -> Dict[str, Any]: # skipcq: PYL-W0221 self.validate_json() dict_options = [o.to_dict(option_type) for o in self.options] if option_type == "dialog": # skipcq: PYL-R1705 @@ -468,9 +452,7 @@ def text_length(self) -> bool: @JsonValidator(f"confirm attribute cannot exceed {confirm_max_length} characters") def confirm_length(self) -> bool: - return ( - self._confirm is None or len(self._confirm.text) <= self.confirm_max_length - ) + return self._confirm is None or len(self._confirm.text) <= self.confirm_max_length @JsonValidator(f"deny attribute cannot exceed {deny_max_length} characters") def deny_length(self) -> bool: @@ -480,19 +462,13 @@ def deny_length(self) -> bool: def _validate_confirm_style(self) -> bool: return self._style is None or self._style in ["primary", "danger"] - def to_dict( - self, option_type: str = "block" - ) -> Dict[str, Any]: # skipcq: PYL-W0221 + def to_dict(self, option_type: str = "block") -> Dict[str, Any]: # skipcq: PYL-W0221 if option_type == "action": # skipcq: PYL-R1705 # deliberately skipping JSON validators here - can't find documentation # on actual limits here json = { - "ok_text": self._confirm.text - if self._confirm and self._confirm.text != "Yes" - else "Okay", - "dismiss_text": self._deny.text - if self._deny and self._deny.text != "No" - else "Cancel", + "ok_text": self._confirm.text if self._confirm and self._confirm.text != "Yes" else "Okay", + "dismiss_text": self._deny.text if self._deny and self._deny.text != "No" else "Cancel", } if self._title: json["title"] = self._title.text diff --git a/slack_sdk/models/blocks/block_elements.py b/slack_sdk/models/blocks/block_elements.py index 2e72ec49b..890d835ca 100644 --- a/slack_sdk/models/blocks/block_elements.py +++ b/slack_sdk/models/blocks/block_elements.py @@ -57,9 +57,7 @@ def __init__( show_unknown_key_warning(self, others) @classmethod - def parse( - cls, block_element: Union[dict, "BlockElement"] - ) -> Optional[Union["BlockElement", TextObject]]: + def parse(cls, block_element: Union[dict, "BlockElement"]) -> Optional[Union["BlockElement", TextObject]]: if block_element is None: # skipcq: PYL-R1705 return None elif isinstance(block_element, dict): @@ -107,27 +105,19 @@ def parse( elif t == TimePickerElement.type: return TimePickerElement(**d) else: - cls.logger.warning( - f"Unknown element detected and skipped ({block_element})" - ) + cls.logger.warning(f"Unknown element detected and skipped ({block_element})") return None else: - cls.logger.warning( - f"Unknown element detected and skipped ({block_element})" - ) + cls.logger.warning(f"Unknown element detected and skipped ({block_element})") return None elif isinstance(block_element, (TextObject, BlockElement)): return block_element else: - cls.logger.warning( - f"Unknown element detected and skipped ({block_element})" - ) + cls.logger.warning(f"Unknown element detected and skipped ({block_element})") return None @classmethod - def parse_all( - cls, block_elements: Sequence[Union[dict, "BlockElement"]] - ) -> List["BlockElement"]: + def parse_all(cls, block_elements: Sequence[Union[dict, "BlockElement"]]) -> List["BlockElement"]: return [cls.parse(e) for e in block_elements or []] @@ -165,13 +155,9 @@ def __init__( self.action_id = action_id - @JsonValidator( - f"action_id attribute cannot exceed {action_id_max_length} characters" - ) + @JsonValidator(f"action_id attribute cannot exceed {action_id_max_length} characters") def _validate_action_id_length(self) -> bool: - return ( - self.action_id is None or len(self.action_id) <= self.action_id_max_length - ) + return self.action_id is None or len(self.action_id) <= self.action_id_max_length # This is a base class @@ -211,9 +197,7 @@ def __init__( self.confirm = ConfirmObject.parse(confirm) self.focus_on_load = focus_on_load - @JsonValidator( - f"placeholder attribute cannot exceed {placeholder_max_length} characters" - ) + @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters") def _validate_placeholder_length(self) -> bool: return ( self.placeholder is None @@ -235,9 +219,7 @@ class ButtonElement(InteractiveElement): @property def attributes(self) -> Set[str]: - return super().attributes.union( - {"text", "url", "value", "style", "confirm", "accessibility_label"} - ) + return super().attributes.union({"text", "url", "value", "style", "confirm", "accessibility_label"}) def __init__( self, @@ -293,11 +275,7 @@ def __init__( @JsonValidator(f"text attribute cannot exceed {text_max_length} characters") def _validate_text_length(self) -> bool: - return ( - self.text is None - or self.text.text is None - or len(self.text.text) <= self.text_max_length - ) + return self.text is None or self.text.text is None or len(self.text.text) <= self.text_max_length @JsonValidator(f"url attribute cannot exceed {url_max_length} characters") def _validate_url_length(self) -> bool: @@ -311,14 +289,9 @@ def _validate_value_length(self) -> bool: def _validate_style_valid(self): return self.style is None or self.style in ButtonStyles - @JsonValidator( - f"accessibility_label attribute cannot exceed {text_max_length} characters" - ) + @JsonValidator(f"accessibility_label attribute cannot exceed {text_max_length} characters") def _validate_accessibility_label_length(self) -> bool: - return ( - self.accessibility_label is None - or len(self.accessibility_label) <= self.text_max_length - ) + return self.accessibility_label is None or len(self.accessibility_label) <= self.text_max_length class LinkButtonElement(ButtonElement): @@ -472,10 +445,7 @@ def __init__( def _validate_initial_date_valid(self) -> bool: return ( self.initial_date is None - or re.match( - r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])", self.initial_date - ) - is not None + or re.match(r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])", self.initial_date) is not None ) @@ -536,11 +506,7 @@ def __init__( @JsonValidator("initial_time attribute must be in format 'HH:mm'") def _validate_initial_time_valid(self) -> bool: - return ( - self.initial_time is None - or re.match(r"([0-1][0-9]|2[0-3]):([0-5][0-9])", self.initial_time) - is not None - ) + return self.initial_time is None or re.match(r"([0-1][0-9]|2[0-3]):([0-5][0-9])", self.initial_time) is not None # ------------------------------------------------- @@ -579,9 +545,7 @@ def __init__( self.image_url = image_url self.alt_text = alt_text - @JsonValidator( - f"image_url attribute cannot exceed {image_url_max_length} characters" - ) + @JsonValidator(f"image_url attribute cannot exceed {image_url_max_length} characters") def _validate_image_url_length(self) -> bool: return len(self.image_url) <= self.image_url_max_length @@ -656,14 +620,9 @@ def __init__( def _validate_options_length(self) -> bool: return self.options is None or len(self.options) <= self.options_max_length - @JsonValidator( - f"option_groups attribute cannot exceed {option_groups_max_length} elements" - ) + @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements") def _validate_option_groups_length(self) -> bool: - return ( - self.option_groups is None - or len(self.option_groups) <= self.option_groups_max_length - ) + return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length @JsonValidator("options and option_groups cannot both be specified") def _validate_options_and_option_groups_both_specified(self) -> bool: @@ -681,9 +640,7 @@ class StaticMultiSelectElement(InputInteractiveElement): @property def attributes(self) -> Set[str]: - return super().attributes.union( - {"options", "option_groups", "initial_options", "max_selected_items"} - ) + return super().attributes.union({"options", "option_groups", "initial_options", "max_selected_items"}) def __init__( self, @@ -742,14 +699,9 @@ def __init__( def _validate_options_length(self) -> bool: return self.options is None or len(self.options) <= self.options_max_length - @JsonValidator( - f"option_groups attribute cannot exceed {option_groups_max_length} elements" - ) + @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements") def _validate_option_groups_length(self) -> bool: - return ( - self.option_groups is None - or len(self.option_groups) <= self.option_groups_max_length - ) + return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length @JsonValidator("options and option_groups cannot both be specified") def _validate_options_and_option_groups_both_specified(self) -> bool: @@ -822,14 +774,9 @@ def __init__( def _validate_options_length(self) -> bool: return self.options is None or len(self.options) <= self.options_max_length - @JsonValidator( - f"option_groups attribute cannot exceed {option_groups_max_length} elements" - ) + @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements") def _validate_option_groups_length(self) -> bool: - return ( - self.option_groups is None - or len(self.option_groups) <= self.option_groups_max_length - ) + return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length @JsonValidator("options and option_groups cannot both be specified") def _validate_options_and_option_groups_both_specified(self) -> bool: @@ -906,9 +853,7 @@ class ExternalDataMultiSelectElement(InputInteractiveElement): @property def attributes(self) -> Set[str]: - return super().attributes.union( - {"min_query_length", "initial_options", "max_selected_items"} - ) + return super().attributes.union({"min_query_length", "initial_options", "max_selected_items"}) def __init__( self, @@ -1108,9 +1053,7 @@ def parse(cls, filter: Union[dict, "ConversationFilter"]): # skipcq: PYL-W0622 d = copy.copy(filter) return ConversationFilter(**d) else: - cls.logger.warning( - f"Unknown conversation filter object detected and skipped ({filter})" - ) + cls.logger.warning(f"Unknown conversation filter object detected and skipped ({filter})") return None @@ -1534,9 +1477,6 @@ def __init__( self.options = options self.confirm = ConfirmObject.parse(confirm) - @JsonValidator( - f"options attribute must have between {options_min_length} " - f"and {options_max_length} items" - ) + @JsonValidator(f"options attribute must have between {options_min_length} " f"and {options_max_length} items") def _validate_options_length(self) -> bool: return self.options_min_length <= len(self.options) <= self.options_max_length diff --git a/slack_sdk/models/blocks/blocks.py b/slack_sdk/models/blocks/blocks.py index 2a15ee42a..fcbc502c2 100644 --- a/slack_sdk/models/blocks/blocks.py +++ b/slack_sdk/models/blocks/blocks.py @@ -94,9 +94,7 @@ def parse(cls, block: Union[dict, "Block"]) -> Optional["Block"]: return None @classmethod - def parse_all( - cls, blocks: Optional[Sequence[Union[dict, "Block"]]] - ) -> List["Block"]: + def parse_all(cls, blocks: Optional[Sequence[Union[dict, "Block"]]]) -> List["Block"]: return [cls.parse(b) for b in blocks or []] @@ -242,9 +240,7 @@ def __init__( self.alt_text = alt_text self.title = TextObject.parse(title) - @JsonValidator( - f"image_url attribute cannot exceed {image_url_max_length} characters" - ) + @JsonValidator(f"image_url attribute cannot exceed {image_url_max_length} characters") def _validate_image_url_length(self): return len(self.image_url) <= self.image_url_max_length @@ -254,11 +250,7 @@ def _validate_alt_text_length(self): @JsonValidator(f"title attribute cannot exceed {title_max_length} characters") def _validate_title_length(self): - return ( - self.title is None - or self.title.text is None - or len(self.title.text) <= self.title_max_length - ) + return self.title is None or self.title.text is None or len(self.title.text) <= self.title_max_length class ActionsBlock(Block): @@ -341,9 +333,7 @@ class InputBlock(Block): @property def attributes(self) -> Set[str]: - return super().attributes.union( - {"label", "hint", "element", "optional", "dispatch_action"} - ) + return super().attributes.union({"label", "hint", "element", "optional", "dispatch_action"}) def __init__( self, @@ -388,19 +378,11 @@ def __init__( @JsonValidator(f"label attribute cannot exceed {label_max_length} characters") def _validate_label_length(self): - return ( - self.label is None - or self.label.text is None - or len(self.label.text) <= self.label_max_length - ) + return self.label is None or self.label.text is None or len(self.label.text) <= self.label_max_length @JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters") def _validate_hint_length(self): - return ( - self.hint is None - or self.hint.text is None - or len(self.hint.text) <= self.label_max_length - ) + return self.hint is None or self.hint.text is None or len(self.hint.text) <= self.label_max_length @JsonValidator( ( @@ -409,9 +391,7 @@ def _validate_hint_length(self): ) ) def _validate_element_type(self): - return self.element is None or isinstance( - self.element, (str, InputInteractiveElement) - ) + return self.element is None or isinstance(self.element, (str, InputInteractiveElement)) class FileBlock(Block): diff --git a/slack_sdk/models/dialogs/__init__.py b/slack_sdk/models/dialogs/__init__.py index d2127e8aa..43bba25cf 100644 --- a/slack_sdk/models/dialogs/__init__.py +++ b/slack_sdk/models/dialogs/__init__.py @@ -70,14 +70,9 @@ def name_length(self) -> bool: def label_length(self) -> bool: return len(self.label) < self.label_max_length - @JsonValidator( - f"placeholder attribute cannot exceed {placeholder_max_length} characters" - ) + @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters") def placeholder_length(self) -> bool: - return ( - self.placeholder is None - or len(self.placeholder) < self.placeholder_max_length - ) + return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length @JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters") def hint_length(self) -> bool: @@ -175,14 +170,9 @@ def name_length(self) -> bool: def label_length(self) -> bool: return len(self.label) < self.label_max_length - @JsonValidator( - f"placeholder attribute cannot exceed {placeholder_max_length} characters" - ) + @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters") def placeholder_length(self) -> bool: - return ( - self.placeholder is None - or len(self.placeholder) < self.placeholder_max_length - ) + return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length @EnumValidator("data_source", DataSourceTypes) def data_source_valid(self) -> bool: @@ -837,10 +827,7 @@ def elements_length(self) -> bool: @JsonValidator(f"submit_label cannot exceed {submit_label_max_length} characters") def submit_label_length(self) -> bool: - return ( - self._submit_label is None - or len(self._submit_label) <= self.submit_label_max_length - ) + return self._submit_label is None or len(self._submit_label) <= self.submit_label_max_length @JsonValidator("submit_label can only be one word") def submit_label_valid(self) -> bool: diff --git a/slack_sdk/models/messages/message.py b/slack_sdk/models/messages/message.py index ae4bcca14..6d92ebe3d 100644 --- a/slack_sdk/models/messages/message.py +++ b/slack_sdk/models/messages/message.py @@ -15,10 +15,7 @@ skip_warn = os.environ.get("SLACKCLIENT_SKIP_DEPRECATION") # for unit tests etc. if not skip_warn: - message = ( - "This class is no longer actively maintained. " - "Please use a dict object for building message data instead." - ) + message = "This class is no longer actively maintained. " "Please use a dict object for building message data instead." warnings.warn(message) @@ -56,21 +53,14 @@ def __init__( self.blocks = blocks or [] self.markdown = markdown - @JsonValidator( - f"attachments attribute cannot exceed {attachments_max_length} items" - ) + @JsonValidator(f"attachments attribute cannot exceed {attachments_max_length} items") def attachments_length(self): - return ( - self.attachments is None - or len(self.attachments) <= self.attachments_max_length - ) + return self.attachments is None or len(self.attachments) <= self.attachments_max_length def to_dict(self) -> dict: # skipcq: PYL-W0221 json = super().to_dict() if len(self.text) > 40000: - LOGGER.error( - "Messages over 40,000 characters are automatically truncated by Slack" - ) + LOGGER.error("Messages over 40,000 characters are automatically truncated by Slack") # The following limitation used to be true in the past. # As of Feb 2021, having both is recommended # ----------------- diff --git a/slack_sdk/models/views/__init__.py b/slack_sdk/models/views/__init__.py index 39ef3006c..4b429076b 100644 --- a/slack_sdk/models/views/__init__.py +++ b/slack_sdk/models/views/__init__.py @@ -101,9 +101,7 @@ def _validate_blocks_length(self): @JsonValidator("home view cannot have submit and close") def _validate_home_tab_structure(self): - return self.type != "home" or ( - self.type == "home" and self.close is None and self.submit is None - ) + return self.type != "home" or (self.type == "home" and self.close is None and self.submit is None) @JsonValidator(f"close cannot exceed {close_max_length} characters") def _validate_close_length(self): @@ -111,25 +109,15 @@ def _validate_close_length(self): @JsonValidator(f"submit cannot exceed {submit_max_length} characters") def _validate_submit_length(self): - return self.submit is None or len(self.submit.text) <= int( - self.submit_max_length - ) + return self.submit is None or len(self.submit.text) <= int(self.submit_max_length) - @JsonValidator( - f"private_metadata cannot exceed {private_metadata_max_length} characters" - ) + @JsonValidator(f"private_metadata cannot exceed {private_metadata_max_length} characters") def _validate_private_metadata_max_length(self): - return ( - self.private_metadata is None - or len(self.private_metadata) <= self.private_metadata_max_length - ) + return self.private_metadata is None or len(self.private_metadata) <= self.private_metadata_max_length @JsonValidator(f"callback_id cannot exceed {callback_id_max_length} characters") def _validate_callback_id_max_length(self): - return ( - self.callback_id is None - or len(self.callback_id) <= self.callback_id_max_length - ) + return self.callback_id is None or len(self.callback_id) <= self.callback_id_max_length def __str__(self): return str(self.get_non_null_attributes()) @@ -146,9 +134,7 @@ class ViewState(JsonObject): def _show_warning_about_unknown(cls, value): c = value.__class__ name = ".".join([c.__module__, c.__name__]) - cls.logger.warning( - f"Unknown type for view.state.values detected ({name}) and ViewState skipped to add it" - ) + cls.logger.warning(f"Unknown type for view.state.values detected ({name}) and ViewState skipped to add it") def __init__( self, @@ -162,9 +148,7 @@ def __init__( if actions is None: # skipcq: PYL-R1724 continue elif isinstance(actions, dict): - new_actions: Dict[str, Union[ViewStateValue, dict]] = copy.copy( - actions - ) + new_actions: Dict[str, Union[ViewStateValue, dict]] = copy.copy(actions) for action_id, v in actions.items(): if isinstance(v, dict): d = copy.copy(v) diff --git a/slack_sdk/oauth/installation_store/amazon_s3/__init__.py b/slack_sdk/oauth/installation_store/amazon_s3/__init__.py index dfbde7ea0..beb14c07e 100644 --- a/slack_sdk/oauth/installation_store/amazon_s3/__init__.py +++ b/slack_sdk/oauth/installation_store/amazon_s3/__init__.py @@ -205,11 +205,7 @@ def find_installation( t_id = none workspace_path = f"{self.client_id}/{e_id}-{t_id}" try: - key = ( - f"{workspace_path}/installer-{user_id}-latest" - if user_id - else f"{workspace_path}/installer-latest" - ) + key = f"{workspace_path}/installer-{user_id}-latest" if user_id else f"{workspace_path}/installer-latest" fetch_response = self.s3_client.get_object( Bucket=self.bucket_name, Key=key, @@ -223,17 +219,13 @@ def find_installation( self.logger.warning(message) return None - async def async_delete_bot( - self, *, enterprise_id: Optional[str], team_id: Optional[str] - ) -> None: + async def async_delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: return self.delete_bot( enterprise_id=enterprise_id, team_id=team_id, ) - def delete_bot( - self, *, enterprise_id: Optional[str], team_id: Optional[str] - ) -> None: + def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: none = "none" e_id = enterprise_id or none t_id = team_id or none @@ -316,11 +308,7 @@ def delete_installation( Prefix=f"{workspace_path}/installer-", MaxKeys=10, # the small number would be enough for this purpose ) - keys = [ - c.get("Key") - for c in objects.get("Contents", []) - if c.get("Key") not in deleted_keys - ] + keys = [c.get("Key") for c in objects.get("Contents", []) if c.get("Key") not in deleted_keys] # If only installer-latest remains, we should delete the one as well if len(keys) == 1 and keys[0].endswith("installer-latest"): content = objects.get("Contents", [])[0] diff --git a/slack_sdk/oauth/installation_store/async_installation_store.py b/slack_sdk/oauth/installation_store/async_installation_store.py index 3f7bd48b2..f8b76b860 100644 --- a/slack_sdk/oauth/installation_store/async_installation_store.py +++ b/slack_sdk/oauth/installation_store/async_installation_store.py @@ -89,6 +89,4 @@ async def async_delete_all( ): """Deletes all installation data for the given workspace / org""" await self.async_delete_bot(enterprise_id=enterprise_id, team_id=team_id) - await self.async_delete_installation( - enterprise_id=enterprise_id, team_id=team_id - ) + await self.async_delete_installation(enterprise_id=enterprise_id, team_id=team_id) diff --git a/slack_sdk/oauth/installation_store/file/__init__.py b/slack_sdk/oauth/installation_store/file/__init__.py index 7b76fb7f7..6d93bef4f 100644 --- a/slack_sdk/oauth/installation_store/file/__init__.py +++ b/slack_sdk/oauth/installation_store/file/__init__.py @@ -66,9 +66,7 @@ def save(self, installation: Installation): entity: str = json.dumps(installation.__dict__) with open(f"{team_installation_dir}/installer-{u_id}-latest", "w") as f: f.write(entity) - with open( - f"{team_installation_dir}/installer-{u_id}-{history_version}", "w" - ) as f: + with open(f"{team_installation_dir}/installer-{u_id}-{history_version}", "w") as f: f.write(entity) else: @@ -129,9 +127,7 @@ def find_bot( data = json.loads(f.read()) return Bot(**data) except FileNotFoundError as e: - message = ( - f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}" - ) + message = f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}" self.logger.debug(message) return None @@ -165,29 +161,21 @@ def find_installation( t_id = none installation_filepath = f"{self.base_dir}/{e_id}-{t_id}/installer-latest" if user_id is not None: - installation_filepath = ( - f"{self.base_dir}/{e_id}-{t_id}/installer-{user_id}-latest" - ) + installation_filepath = f"{self.base_dir}/{e_id}-{t_id}/installer-{user_id}-latest" try: with open(installation_filepath) as f: data = json.loads(f.read()) return Installation(**data) except FileNotFoundError as e: - message = ( - f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}" - ) + message = f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}" self.logger.debug(message) return None - async def async_delete_bot( - self, *, enterprise_id: Optional[str], team_id: Optional[str] - ) -> None: + async def async_delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: return self.delete_bot(enterprise_id=enterprise_id, team_id=team_id) - def delete_bot( - self, *, enterprise_id: Optional[str], team_id: Optional[str] - ) -> None: + def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: none = "none" e_id = enterprise_id or none t_id = team_id or none @@ -201,9 +189,7 @@ async def async_delete_installation( team_id: Optional[str], user_id: Optional[str] = None, ) -> None: - return self.delete_installation( - enterprise_id=enterprise_id, team_id=team_id, user_id=user_id - ) + return self.delete_installation(enterprise_id=enterprise_id, team_id=team_id, user_id=user_id) def delete_installation( self, diff --git a/slack_sdk/oauth/installation_store/models/bot.py b/slack_sdk/oauth/installation_store/models/bot.py index 35c0da12c..36be38644 100644 --- a/slack_sdk/oauth/installation_store/models/bot.py +++ b/slack_sdk/oauth/installation_store/models/bot.py @@ -73,12 +73,8 @@ def __init__( if bot_token_expires_at is not None: if type(bot_token_expires_at) == datetime: self.bot_token_expires_at = int(bot_token_expires_at.timestamp()) # type: ignore - elif type(bot_token_expires_at) == str and not re.match( - "^\\d+$", bot_token_expires_at - ): - self.bot_token_expires_at = int( - _from_iso_format_to_unix_timestamp(bot_token_expires_at) - ) + elif type(bot_token_expires_at) == str and not re.match("^\\d+$", bot_token_expires_at): + self.bot_token_expires_at = int(_from_iso_format_to_unix_timestamp(bot_token_expires_at)) else: self.bot_token_expires_at = int(bot_token_expires_at) elif bot_token_expires_in is not None: diff --git a/slack_sdk/oauth/installation_store/models/installation.py b/slack_sdk/oauth/installation_store/models/installation.py index 0404dfbc7..e55cf2b98 100644 --- a/slack_sdk/oauth/installation_store/models/installation.py +++ b/slack_sdk/oauth/installation_store/models/installation.py @@ -104,12 +104,8 @@ def __init__( if type(bot_token_expires_at) == datetime: ts: float = bot_token_expires_at.timestamp() # type: ignore self.bot_token_expires_at = int(ts) - elif type(bot_token_expires_at) == str and not re.match( - "^\\d+$", bot_token_expires_at - ): - self.bot_token_expires_at = int( - _from_iso_format_to_unix_timestamp(bot_token_expires_at) - ) + elif type(bot_token_expires_at) == str and not re.match("^\\d+$", bot_token_expires_at): + self.bot_token_expires_at = int(_from_iso_format_to_unix_timestamp(bot_token_expires_at)) else: self.bot_token_expires_at = bot_token_expires_at # type: ignore elif bot_token_expires_in is not None: @@ -128,12 +124,8 @@ def __init__( if type(user_token_expires_at) == datetime: ts: float = user_token_expires_at.timestamp() # type: ignore self.user_token_expires_at = int(ts) - elif type(user_token_expires_at) == str and not re.match( - "^\\d+$", user_token_expires_at - ): - self.user_token_expires_at = int( - _from_iso_format_to_unix_timestamp(user_token_expires_at) - ) + elif type(user_token_expires_at) == str and not re.match("^\\d+$", user_token_expires_at): + self.user_token_expires_at = int(_from_iso_format_to_unix_timestamp(user_token_expires_at)) else: self.user_token_expires_at = user_token_expires_at # type: ignore elif user_token_expires_in is not None: @@ -209,9 +201,7 @@ def to_dict(self) -> Dict[str, Any]: "user_token": self.user_token, "user_scopes": ",".join(self.user_scopes) if self.user_scopes else None, "user_refresh_token": self.user_refresh_token, - "user_token_expires_at": datetime.utcfromtimestamp( - self.user_token_expires_at - ) + "user_token_expires_at": datetime.utcfromtimestamp(self.user_token_expires_at) if self.user_token_expires_at is not None else None, "incoming_webhook_url": self.incoming_webhook_url, diff --git a/slack_sdk/oauth/installation_store/sqlalchemy/__init__.py b/slack_sdk/oauth/installation_store/sqlalchemy/__init__.py index e38d5a1cd..4c6261b0e 100644 --- a/slack_sdk/oauth/installation_store/sqlalchemy/__init__.py +++ b/slack_sdk/oauth/installation_store/sqlalchemy/__init__.py @@ -120,12 +120,8 @@ def __init__( logger: Logger = logging.getLogger(__name__), ): self.metadata = sqlalchemy.MetaData() - self.bots = self.build_bots_table( - metadata=self.metadata, table_name=bots_table_name - ) - self.installations = self.build_installations_table( - metadata=self.metadata, table_name=installations_table_name - ) + self.bots = self.build_bots_table(metadata=self.metadata, table_name=bots_table_name) + self.installations = self.build_installations_table(metadata=self.metadata, table_name=installations_table_name) self.client_id = client_id self._logger = logger self.engine = engine @@ -161,11 +157,7 @@ def save(self, installation: Installation): if installations_row_id is None: conn.execute(self.installations.insert(), i) else: - update_statement = ( - self.installations.update() - .where(i_column.id == installations_row_id) - .values(**i) - ) + update_statement = self.installations.update().where(i_column.id == installations_row_id).values(**i) conn.execute(update_statement, i) # bots @@ -196,9 +188,7 @@ def save_bot(self, bot: Bot): if bots_row_id is None: conn.execute(self.bots.insert(), b) else: - update_statement = ( - self.bots.update().where(b_column.id == bots_row_id).values(**b) - ) + update_statement = self.bots.update().where(b_column.id == bots_row_id).values(**b) conn.execute(update_statement, b) def find_bot( @@ -266,12 +256,7 @@ def find_installation( c.user_id == user_id, ) - query = ( - self.installations.select() - .where(where_clause) - .order_by(desc(c.installed_at)) - .limit(1) - ) + query = self.installations.select().where(where_clause).order_by(desc(c.installed_at)).limit(1) with self.engine.connect() as conn: result: object = conn.execute(query) @@ -298,18 +283,14 @@ def find_installation( incoming_webhook_url=row["incoming_webhook_url"], incoming_webhook_channel=row["incoming_webhook_channel"], incoming_webhook_channel_id=row["incoming_webhook_channel_id"], - incoming_webhook_configuration_url=row[ - "incoming_webhook_configuration_url" - ], + incoming_webhook_configuration_url=row["incoming_webhook_configuration_url"], is_enterprise_install=row["is_enterprise_install"], token_type=row["token_type"], installed_at=row["installed_at"], ) return None - def delete_bot( - self, *, enterprise_id: Optional[str], team_id: Optional[str] - ) -> None: + def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: table = self.bots c = table.c with self.engine.begin() as conn: diff --git a/slack_sdk/oauth/installation_store/sqlite3/__init__.py b/slack_sdk/oauth/installation_store/sqlite3/__init__.py index 2386e1b4d..0bf4da471 100644 --- a/slack_sdk/oauth/installation_store/sqlite3/__init__.py +++ b/slack_sdk/oauth/installation_store/sqlite3/__init__.py @@ -36,9 +36,7 @@ def init(self): with sqlite3.connect(database=self.database) as conn: cur = conn.execute("select count(1) from slack_installations;") row_num = cur.fetchone()[0] - self.logger.debug( - f"{row_num} installations are stored in {self.database}" - ) + self.logger.debug(f"{row_num} installations are stored in {self.database}") except Exception: # skipcq: PYL-W0703 self.create_tables() self.init_called = True @@ -207,9 +205,7 @@ def save(self, installation: Installation): installation.bot_token_expires_at, installation.user_id, installation.user_token, - ",".join(installation.user_scopes) - if installation.user_scopes - else None, + ",".join(installation.user_scopes) if installation.user_scopes else None, installation.user_refresh_token, installation.user_token_expires_at, installation.incoming_webhook_url, @@ -337,9 +333,7 @@ def find_bot( ) row = cur.fetchone() result = "found" if row and len(row) > 0 else "not found" - self.logger.debug( - f"find_bot's query result: {result} (database: {self.database})" - ) + self.logger.debug(f"find_bot's query result: {result} (database: {self.database})") if row and len(row) > 0: bot = Bot( app_id=row[0], @@ -467,9 +461,7 @@ def find_installation( return None result = "found" if row and len(row) > 0 else "not found" - self.logger.debug( - f"find_installation's query result: {result} (database: {self.database})" - ) + self.logger.debug(f"find_installation's query result: {result} (database: {self.database})") if row and len(row) > 0: installation = Installation( app_id=row[0], @@ -508,9 +500,7 @@ def find_installation( self.logger.warning(message) return None - def delete_bot( - self, *, enterprise_id: Optional[str], team_id: Optional[str] - ) -> None: + def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: try: with self.connect() as conn: conn.execute( diff --git a/slack_sdk/oauth/redirect_uri_page_renderer/__init__.py b/slack_sdk/oauth/redirect_uri_page_renderer/__init__.py index 4ec0f5ba5..87b943a33 100644 --- a/slack_sdk/oauth/redirect_uri_page_renderer/__init__.py +++ b/slack_sdk/oauth/redirect_uri_page_renderer/__init__.py @@ -24,11 +24,7 @@ def render_success_page( ) -> str: url = self.success_url if url is None: - if ( - is_enterprise_install is True - and enterprise_url is not None - and app_id is not None - ): + if is_enterprise_install is True and enterprise_url is not None and app_id is not None: url = f"{enterprise_url}manage/organization/apps/profile/{app_id}/workspaces/add" elif team_id is None or app_id is None: url = "slack://open" diff --git a/slack_sdk/oauth/state_store/sqlalchemy/__init__.py b/slack_sdk/oauth/state_store/sqlalchemy/__init__.py index 562f12706..6f4a61f4b 100644 --- a/slack_sdk/oauth/state_store/sqlalchemy/__init__.py +++ b/slack_sdk/oauth/state_store/sqlalchemy/__init__.py @@ -62,9 +62,7 @@ def consume(self, state: str) -> bool: try: with self.engine.begin() as conn: c = self.oauth_states.c - query = self.oauth_states.select().where( - and_(c.state == state, c.expire_at > datetime.utcnow()) - ) + query = self.oauth_states.select().where(and_(c.state == state, c.expire_at > datetime.utcnow())) result = conn.execute(query) for row in result: self.logger.debug(f"consume's query result: {row}") diff --git a/slack_sdk/oauth/state_store/sqlite3/__init__.py b/slack_sdk/oauth/state_store/sqlite3/__init__.py index 89418ce68..8775c6e5f 100644 --- a/slack_sdk/oauth/state_store/sqlite3/__init__.py +++ b/slack_sdk/oauth/state_store/sqlite3/__init__.py @@ -33,9 +33,7 @@ def init(self): with sqlite3.connect(database=self.database) as conn: cur = conn.execute("select count(1) from oauth_states;") row_num = cur.fetchone()[0] - self.logger.debug( - f"{row_num} oauth states are stored in {self.database}" - ) + self.logger.debug(f"{row_num} oauth states are stored in {self.database}") except Exception: # skipcq: PYL-W0703 self.create_tables() self.init_called = True @@ -72,12 +70,8 @@ def issue(self, *args, **kwargs) -> str: state, time.time() + self.expiration_seconds, ] - conn.execute( - "insert into oauth_states (state, expire_at) values (?, ?);", parameters - ) - self.logger.debug( - f"issue's insertion result: {parameters} (database: {self.database})" - ) + conn.execute("insert into oauth_states (state, expire_at) values (?, ?);", parameters) + self.logger.debug(f"issue's insertion result: {parameters} (database: {self.database})") conn.commit() return state @@ -89,9 +83,7 @@ def consume(self, state: str) -> bool: [state, time.time()], ) row = cur.fetchone() - self.logger.debug( - f"consume's query result: {row} (database: {self.database})" - ) + self.logger.debug(f"consume's query result: {row} (database: {self.database})") if row and len(row) > 0: id = row[0] # skipcq: PYL-W0622 conn.execute("delete from oauth_states where id = ?;", [id]) diff --git a/slack_sdk/oauth/state_utils/__init__.py b/slack_sdk/oauth/state_utils/__init__.py index 3a5693f31..c4f821f4f 100644 --- a/slack_sdk/oauth/state_utils/__init__.py +++ b/slack_sdk/oauth/state_utils/__init__.py @@ -18,33 +18,17 @@ def __init__( self.expiration_seconds = expiration_seconds def build_set_cookie_for_new_state(self, state: str) -> str: - return ( - f"{self.cookie_name}={state}; " - "Secure; " - "HttpOnly; " - "Path=/; " - f"Max-Age={self.expiration_seconds}" - ) + return f"{self.cookie_name}={state}; " "Secure; " "HttpOnly; " "Path=/; " f"Max-Age={self.expiration_seconds}" def build_set_cookie_for_deletion(self) -> str: - return ( - f"{self.cookie_name}=deleted; " - "Secure; " - "HttpOnly; " - "Path=/; " - "Expires=Thu, 01 Jan 1970 00:00:00 GMT" - ) + return f"{self.cookie_name}=deleted; " "Secure; " "HttpOnly; " "Path=/; " "Expires=Thu, 01 Jan 1970 00:00:00 GMT" def is_valid_browser( self, state: Optional[str], request_headers: Dict[str, Union[str, Sequence[str]]], ) -> bool: - if ( - state is None - or request_headers is None - or request_headers.get("cookie", None) is None - ): + if state is None or request_headers is None or request_headers.get("cookie", None) is None: return False cookies = request_headers["cookie"] if isinstance(cookies, str): diff --git a/slack_sdk/oauth/token_rotation/async_rotator.py b/slack_sdk/oauth/token_rotation/async_rotator.py index b001c3298..c26e31bcc 100644 --- a/slack_sdk/oauth/token_rotation/async_rotator.py +++ b/slack_sdk/oauth/token_rotation/async_rotator.py @@ -96,9 +96,7 @@ async def perform_bot_token_rotation( # type: ignore refreshed_bot = Bot(**bot.to_dict()) # type: ignore refreshed_bot.bot_token = refresh_response.get("access_token") refreshed_bot.bot_refresh_token = refresh_response.get("refresh_token") - refreshed_bot.bot_token_expires_at = int(time()) + int( - refresh_response.get("expires_in") - ) + refreshed_bot.bot_token_expires_at = int(time()) + int(refresh_response.get("expires_in")) return refreshed_bot except SlackApiError as e: @@ -136,12 +134,8 @@ async def perform_user_token_rotation( # type: ignore refreshed_installation = Installation(**installation.to_dict()) # type: ignore refreshed_installation.user_token = refresh_response.get("access_token") - refreshed_installation.user_refresh_token = refresh_response.get( - "refresh_token" - ) - refreshed_installation.user_token_expires_at = int(time()) + int( - refresh_response.get("expires_in") - ) + refreshed_installation.user_refresh_token = refresh_response.get("refresh_token") + refreshed_installation.user_token_expires_at = int(time()) + int(refresh_response.get("expires_in")) return refreshed_installation # type: ignore except SlackApiError as e: diff --git a/slack_sdk/oauth/token_rotation/rotator.py b/slack_sdk/oauth/token_rotation/rotator.py index c37cb27f9..d3327ce87 100644 --- a/slack_sdk/oauth/token_rotation/rotator.py +++ b/slack_sdk/oauth/token_rotation/rotator.py @@ -11,9 +11,7 @@ class TokenRotator: client_id: str client_secret: str - def __init__( - self, *, client_id: str, client_secret: str, client: Optional[WebClient] = None - ): + def __init__(self, *, client_id: str, client_secret: str, client: Optional[WebClient] = None): self.client = client if client is not None else WebClient(token=None) self.client_id = client_id self.client_secret = client_secret @@ -90,9 +88,7 @@ def perform_bot_token_rotation( # type: ignore refreshed_bot = Bot(**bot.to_dict()) # type: ignore refreshed_bot.bot_token = refresh_response.get("access_token") refreshed_bot.bot_refresh_token = refresh_response.get("refresh_token") - refreshed_bot.bot_token_expires_at = int(time()) + int( - refresh_response.get("expires_in") - ) + refreshed_bot.bot_token_expires_at = int(time()) + int(refresh_response.get("expires_in")) return refreshed_bot except SlackApiError as e: @@ -131,12 +127,8 @@ def perform_user_token_rotation( # type: ignore refreshed_installation = Installation(**installation.to_dict()) # type: ignore refreshed_installation.user_token = refresh_response.get("access_token") - refreshed_installation.user_refresh_token = refresh_response.get( - "refresh_token" - ) - refreshed_installation.user_token_expires_at = int(time()) + int( - refresh_response.get("expires_in") - ) + refreshed_installation.user_refresh_token = refresh_response.get("refresh_token") + refreshed_installation.user_token_expires_at = int(time()) + int(refresh_response.get("expires_in")) return refreshed_installation except SlackApiError as e: diff --git a/slack_sdk/proxy_env_variable_loader.py b/slack_sdk/proxy_env_variable_loader.py index af2344937..848436905 100644 --- a/slack_sdk/proxy_env_variable_loader.py +++ b/slack_sdk/proxy_env_variable_loader.py @@ -17,9 +17,7 @@ def load_http_proxy_from_env(logger: logging.Logger = _default_logger) -> Option return None if len(proxy_url.strip()) == 0: # If the value is an empty string, the intention should be unsetting it - logger.debug( - "The Slack SDK ignored the proxy env variable as an empty value is set." - ) + logger.debug("The Slack SDK ignored the proxy env variable as an empty value is set.") return None logger.debug(f"HTTP proxy URL has been loaded from an env variable: {proxy_url}") diff --git a/slack_sdk/rtm/__init__.py b/slack_sdk/rtm/__init__.py index 225a480cf..dcfb1100d 100644 --- a/slack_sdk/rtm/__init__.py +++ b/slack_sdk/rtm/__init__.py @@ -204,9 +204,7 @@ def start(self) -> Union[asyncio.Future, Any]: for s in signals: self._event_loop.add_signal_handler(s, self.stop) - future: Future[Any] = asyncio.ensure_future( - self._connect_and_read(), loop=self._event_loop - ) + future: Future[Any] = asyncio.ensure_future(self._connect_and_read(), loop=self._event_loop) if self.run_async: return future @@ -261,9 +259,7 @@ def send_over_websocket(self, *, payload: dict): async def _send_json(self, payload): if self._websocket is None or self._event_loop is None: - raise client_err.SlackClientNotConnectedError( - "Websocket connection is closed." - ) + raise client_err.SlackClientNotConnectedError("Websocket connection is closed.") if "id" not in payload: payload["id"] = self._next_msg_id() @@ -314,12 +310,8 @@ def _validate_callback(callback): msg = "The specified callback '{}' is not callable.".format(cb_name) raise client_err.SlackClientError(msg) callback_params = inspect.signature(callback).parameters.values() - if not any( - param for param in callback_params if param.kind == param.VAR_KEYWORD - ): - msg = "The callback '{}' must accept keyword arguments (**kwargs).".format( - cb_name - ) + if not any(param for param in callback_params if param.kind == param.VAR_KEYWORD): + msg = "The callback '{}' must accept keyword arguments (**kwargs).".format(cb_name) raise client_err.SlackClientError(msg) def _next_msg_id(self): @@ -352,9 +344,7 @@ async def _connect_and_read(self): while not self._stopped: try: self._connection_attempts += 1 - async with aiohttp.ClientSession( - timeout=aiohttp.ClientTimeout(total=self.timeout) - ) as session: + async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout)) as session: self._session = session url, data = await self._retrieve_websocket_info() async with session.ws_connect( @@ -369,9 +359,7 @@ async def _connect_and_read(self): await self._read_messages() # The websocket has been disconnected, or self._stopped is True if not self._stopped and not self.auto_reconnect: - self._logger.warning( - "Not reconnecting the Websocket because auto_reconnect is False" - ) + self._logger.warning("Not reconnecting the Websocket because auto_reconnect is False") return # No need to wait exponentially here, since the connection was # established OK, but timed out, or was closed remotely @@ -381,11 +369,7 @@ async def _connect_and_read(self): # Not yet implemented: Catch websocket exceptions thrown by aiohttp. ) as exception: await self._dispatch_event(event="error", data=exception) - error_code = ( - exception.response.get("error", None) - if hasattr(exception, "response") - else None - ) + error_code = exception.response.get("error", None) if hasattr(exception, "response") else None if ( self.auto_reconnect and not self._stopped @@ -393,9 +377,7 @@ async def _connect_and_read(self): ): await self._wait_exponentially(exception) continue - self._logger.exception( - "The Websocket encountered an error. Closing the connection..." - ) + self._logger.exception("The Websocket encountered an error. Closing the connection...") self._close_websocket() raise @@ -432,9 +414,7 @@ async def _read_messages(self): await self._dispatch_event(event, data=payload) except Exception as err: # skipcq: PYL-W0703 data = message.data if message else message - self._logger.info( - f"Caught a raised exception ({err}) while dispatching a TEXT message ({data})" - ) + self._logger.info(f"Caught a raised exception ({err}) while dispatching a TEXT message ({data})") # Raised exceptions here happen in users' code and were just unhandled. # As they're not intended for closing current WebSocket connection, # this exception should not be propagated to higher level (#_connect_and_read()). @@ -486,9 +466,7 @@ async def _dispatch_event(self, event, data=None): break if inspect.iscoroutinefunction(callback): - await callback( - rtm_client=self, web_client=self._web_client, data=data - ) + await callback(rtm_client=self, web_client=self._web_client, data=data) else: if self.run_async is True: raise client_err.SlackRequestError( @@ -589,8 +567,6 @@ def _close_websocket(self) -> Sequence[Future]: ) # skipcq: PYL-E1102 futures.append(future) self._websocket = None - event_f = asyncio.ensure_future( - self._dispatch_event(event="close"), loop=self._event_loop - ) + event_f = asyncio.ensure_future(self._dispatch_event(event="close"), loop=self._event_loop) futures.append(event_f) return futures diff --git a/slack_sdk/rtm_v2/__init__.py b/slack_sdk/rtm_v2/__init__.py index f8e98d55d..21f96e347 100644 --- a/slack_sdk/rtm_v2/__init__.py +++ b/slack_sdk/rtm_v2/__init__.py @@ -116,9 +116,7 @@ def goodbye_listener(_self, event: dict): self.current_session = None self.current_session_state = ConnectionState() - self.current_session_runner = IntervalRunner( - self._run_current_session, 0.1 - ).start() + self.current_session_runner = IntervalRunner(self._run_current_session, 0.1).start() self.wss_uri = None self.current_app_monitor_started = False @@ -165,10 +163,7 @@ def new_message_listener(_self, event: dict): # SKip the events generated by this bot user return # https://github.com/slackapi/python-slack-sdk/issues/533 - if event_type == "*" or ( - actual_event_type is not None - and actual_event_type == event_type - ): + if event_type == "*" or (actual_event_type is not None and actual_event_type == event_type): func(_self, event) self.message_listeners.append(new_message_listener) @@ -254,9 +249,7 @@ def connect(self): self.current_app_monitor_started = True self.current_app_monitor.start() - self.logger.info( - f"A new session has been established (session id: {self.session_id()})" - ) + self.logger.info(f"A new session has been established (session id: {self.session_id()})") def disconnect(self): """Disconnects the current session.""" @@ -280,9 +273,7 @@ def send(self, payload: Union[dict, str]) -> None: if payload is None: return if self.current_session is None or not self.current_session.is_active(): - raise SlackClientError( - "The RTM client is not connected to the Slack servers" - ) + raise SlackClientError("The RTM client is not connected to the Slack servers") if isinstance(payload, str): self.current_session.send(payload) else: @@ -295,17 +286,13 @@ def send(self, payload: Union[dict, str]) -> None: def enqueue_message(self, message: str): self.message_queue.put(message) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new message enqueued (current queue size: {self.message_queue.qsize()})" - ) + self.logger.debug(f"A new message enqueued (current queue size: {self.message_queue.qsize()})") def process_message(self): try: raw_message = self.message_queue.get(timeout=1) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A message dequeued (current queue size: {self.message_queue.qsize()})" - ) + self.logger.debug(f"A message dequeued (current queue size: {self.message_queue.qsize()})") if raw_message is not None: message: dict = {} @@ -360,8 +347,7 @@ def run_all_message_listeners(self, message: str): def run_all_error_listeners(self, error: Exception): self.logger.exception( - f"on_error invoked (session id: {self.session_id()}, " - f"error: {type(error).__name__}, message: {error})" + f"on_error invoked (session id: {self.session_id()}, " f"error: {type(error).__name__}, message: {error})" ) for listener in self.on_error_listeners: listener(error) @@ -370,10 +356,7 @@ def run_all_close_listeners(self, code: int, reason: Optional[str] = None): if self.logger.level <= logging.DEBUG: self.logger.debug(f"on_close invoked (session id: {self.session_id()})") if self.auto_reconnect_enabled: - self.logger.info( - "Received CLOSE event. Going to reconnect... " - f"(session id: {self.session_id()})" - ) + self.logger.info("Received CLOSE event. Going to reconnect... " f"(session id: {self.session_id()})") self.connect_to_new_endpoint() for listener in self.on_close_listeners: listener(code, reason) @@ -382,20 +365,13 @@ def _run_current_session(self): if self.current_session is not None and self.current_session.is_active(): session_id = self.session_id() try: - self.logger.info( - "Starting to receive messages from a new connection" - f" (session id: {session_id})" - ) + self.logger.info("Starting to receive messages from a new connection" f" (session id: {session_id})") self.current_session_state.terminated = False self.current_session.run_until_completion(self.current_session_state) - self.logger.info( - "Stopped receiving messages from a connection" - f" (session id: {session_id})" - ) + self.logger.info("Stopped receiving messages from a connection" f" (session id: {session_id})") except Exception as e: self.logger.exception( - "Failed to start or stop the current session" - f" (session id: {session_id}, error: {e})" + "Failed to start or stop the current session" f" (session id: {session_id}, error: {e})" ) def _monitor_current_session(self): @@ -403,12 +379,9 @@ def _monitor_current_session(self): try: self.current_session.check_state() - if self.auto_reconnect_enabled and ( - self.current_session is None or not self.current_session.is_active() - ): + if self.auto_reconnect_enabled and (self.current_session is None or not self.current_session.is_active()): self.logger.info( - "The session seems to be already closed. Going to reconnect... " - f"(session id: {self.session_id()})" + "The session seems to be already closed. Going to reconnect... " f"(session id: {self.session_id()})" ) self.connect_to_new_endpoint() except Exception as e: diff --git a/slack_sdk/scim/v1/async_client.py b/slack_sdk/scim/v1/async_client.py index 0c5a061bb..0ab220b95 100644 --- a/slack_sdk/scim/v1/async_client.py +++ b/slack_sdk/scim/v1/async_client.py @@ -99,13 +99,9 @@ def __init__( self.trust_env_in_session = trust_env_in_session self.auth = auth self.default_headers = default_headers if default_headers else {} - self.default_headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.logger = logger if logger is not None else logging.getLogger(__name__) - self.retry_handlers = ( - retry_handlers if retry_handlers is not None else async_default_handlers() - ) + self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers() if self.proxy is None or len(self.proxy.strip()) == 0: env_variable = load_http_proxy_from_env(self.logger) @@ -137,26 +133,18 @@ async def search_users( ) async def read_user(self, id: str) -> ReadUserResponse: - return ReadUserResponse( - await self.api_call(http_verb="GET", path=f"Users/{quote(id)}") - ) + return ReadUserResponse(await self.api_call(http_verb="GET", path=f"Users/{quote(id)}")) - async def create_user( - self, user: Union[Dict[str, Any], User] - ) -> UserCreateResponse: + async def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse: return UserCreateResponse( await self.api_call( http_verb="POST", path="Users", - body_params=user.to_dict() - if isinstance(user, User) - else _to_dict_without_not_given(user), + body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user), ) ) - async def patch_user( - self, id: str, partial_user: Union[Dict[str, Any], User] - ) -> UserPatchResponse: + async def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse: return UserPatchResponse( await self.api_call( http_verb="PATCH", @@ -167,17 +155,13 @@ async def patch_user( ) ) - async def update_user( - self, user: Union[Dict[str, Any], User] - ) -> UserUpdateResponse: + async def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse: user_id = user.id if isinstance(user, User) else user["id"] return UserUpdateResponse( await self.api_call( http_verb="PUT", path=f"Users/{quote(user_id)}", - body_params=user.to_dict() - if isinstance(user, User) - else _to_dict_without_not_given(user), + body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user), ) ) @@ -214,26 +198,18 @@ async def search_groups( ) async def read_group(self, id: str) -> ReadGroupResponse: - return ReadGroupResponse( - await self.api_call(http_verb="GET", path=f"Groups/{quote(id)}") - ) + return ReadGroupResponse(await self.api_call(http_verb="GET", path=f"Groups/{quote(id)}")) - async def create_group( - self, group: Union[Dict[str, Any], Group] - ) -> GroupCreateResponse: + async def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse: return GroupCreateResponse( await self.api_call( http_verb="POST", path="Groups", - body_params=group.to_dict() - if isinstance(group, Group) - else _to_dict_without_not_given(group), + body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group), ) ) - async def patch_group( - self, id: str, partial_group: Union[Dict[str, Any], Group] - ) -> GroupPatchResponse: + async def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse: return GroupPatchResponse( await self.api_call( http_verb="PATCH", @@ -244,17 +220,13 @@ async def patch_group( ) ) - async def update_group( - self, group: Union[Dict[str, Any], Group] - ) -> GroupUpdateResponse: + async def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateResponse: group_id = group.id if isinstance(group, Group) else group["id"] return GroupUpdateResponse( await self.api_call( http_verb="PUT", path=f"Groups/{quote(group_id)}", - body_params=group.to_dict() - if isinstance(group, Group) - else _to_dict_without_not_given(group), + body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group), ) ) @@ -344,8 +316,7 @@ async def _perform_http_request( if self.logger.level <= logging.DEBUG: headers_for_logging = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in headers.items() + k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items() } self.logger.debug( f"Sending a request - url: {url}, params: {body_params}, headers: {headers_for_logging}" @@ -358,14 +329,10 @@ async def _perform_http_request( retry_response = RetryHttpResponse( status_code=res.status, headers=res.headers, - data=response_body.encode("utf-8") - if response_body is not None - else None, + data=response_body.encode("utf-8") if response_body is not None else None, ) except aiohttp.ContentTypeError: - self.logger.debug( - f"No response data returned from the following API call: {url}." - ) + self.logger.debug(f"No response data returned from the following API call: {url}.") if res.status == 429: for handler in self.retry_handlers: @@ -407,8 +374,7 @@ async def _perform_http_request( ): if self.logger.level <= logging.DEBUG: self.logger.info( - f"A retry handler found: {type(handler).__name__} " - f"for {http_verb} {url} - {e}" + f"A retry handler found: {type(handler).__name__} " f"for {http_verb} {url} - {e}" ) await handler.prepare_for_next_attempt_async( state=retry_state, diff --git a/slack_sdk/scim/v1/client.py b/slack_sdk/scim/v1/client.py index 48e5b52e1..450c02d81 100644 --- a/slack_sdk/scim/v1/client.py +++ b/slack_sdk/scim/v1/client.py @@ -95,13 +95,9 @@ def __init__( self.proxy = proxy self.base_url = base_url self.default_headers = default_headers if default_headers else {} - self.default_headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.logger = logger if logger is not None else logging.getLogger(__name__) - self.retry_handlers = ( - retry_handlers if retry_handlers is not None else default_retry_handlers() - ) + self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers() if self.proxy is None or len(self.proxy.strip()) == 0: env_variable = load_http_proxy_from_env(self.logger) @@ -133,24 +129,18 @@ def search_users( ) def read_user(self, id: str) -> ReadUserResponse: - return ReadUserResponse( - self.api_call(http_verb="GET", path=f"Users/{quote(id)}") - ) + return ReadUserResponse(self.api_call(http_verb="GET", path=f"Users/{quote(id)}")) def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse: return UserCreateResponse( self.api_call( http_verb="POST", path="Users", - body_params=user.to_dict() - if isinstance(user, User) - else _to_dict_without_not_given(user), + body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user), ) ) - def patch_user( - self, id: str, partial_user: Union[Dict[str, Any], User] - ) -> UserPatchResponse: + def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse: return UserPatchResponse( self.api_call( http_verb="PATCH", @@ -167,9 +157,7 @@ def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse: self.api_call( http_verb="PUT", path=f"Users/{quote(user_id)}", - body_params=user.to_dict() - if isinstance(user, User) - else _to_dict_without_not_given(user), + body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user), ) ) @@ -206,24 +194,18 @@ def search_groups( ) def read_group(self, id: str) -> ReadGroupResponse: - return ReadGroupResponse( - self.api_call(http_verb="GET", path=f"Groups/{quote(id)}") - ) + return ReadGroupResponse(self.api_call(http_verb="GET", path=f"Groups/{quote(id)}")) def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse: return GroupCreateResponse( self.api_call( http_verb="POST", path="Groups", - body_params=group.to_dict() - if isinstance(group, Group) - else _to_dict_without_not_given(group), + body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group), ) ) - def patch_group( - self, id: str, partial_group: Union[Dict[str, Any], Group] - ) -> GroupPatchResponse: + def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse: return GroupPatchResponse( self.api_call( http_verb="PATCH", @@ -240,9 +222,7 @@ def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateRespon self.api_call( http_verb="PUT", path=f"Groups/{quote(group_id)}", - body_params=group.to_dict() - if isinstance(group, Group) - else _to_dict_without_not_given(group), + body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group), ) ) @@ -297,13 +277,8 @@ def _perform_http_request( headers["Content-Type"] = "application/json;charset=utf-8" if self.logger.level <= logging.DEBUG: - headers_for_logging = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in headers.items() - } - self.logger.debug( - f"Sending a request - {http_verb} url: {url}, body: {body}, headers: {headers_for_logging}" - ) + headers_for_logging = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()} + self.logger.debug(f"Sending a request - {http_verb} url: {url}, body: {body}, headers: {headers_for_logging}") # NOTE: Intentionally ignore the `http_verb` here # Slack APIs accepts any API method requests with POST methods @@ -342,15 +317,9 @@ def _perform_http_request( ) if e.code == 429: # for backward-compatibility with WebClient (v.2.5.0 or older) - if ( - "retry-after" not in resp.headers - and "Retry-After" in resp.headers - ): + if "retry-after" not in resp.headers and "Retry-After" in resp.headers: resp.headers["retry-after"] = resp.headers["Retry-After"] - if ( - "Retry-After" not in resp.headers - and "retry-after" in resp.headers - ): + if "Retry-After" not in resp.headers and "retry-after" in resp.headers: resp.headers["Retry-After"] = resp.headers["retry-after"] _debug_log_response(self.logger, resp) @@ -359,9 +328,7 @@ def _perform_http_request( retry_response = RetryHttpResponse( status_code=e.code, headers={k: [v] for k, v in e.headers.items()}, - data=response_body.encode("utf-8") - if response_body is not None - else None, + data=response_body.encode("utf-8") if response_body is not None else None, ) for handler in self.retry_handlers: if handler.can_retry( @@ -387,9 +354,7 @@ def _perform_http_request( except Exception as err: last_error = err - self.logger.error( - f"Failed to send a request to Slack API server: {err}" - ) + self.logger.error(f"Failed to send a request to Slack API server: {err}") # Try to find a retry handler for this error retry_request = RetryHttpRequest.from_urllib_http_request(req) @@ -410,9 +375,7 @@ def _perform_http_request( response=None, error=err, ) - self.logger.info( - f"Going to retry the same request: {req.method} {req.full_url}" - ) + self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}") break if retry_state.next_attempt_requested is False: @@ -433,9 +396,7 @@ def _perform_http_request_internal(self, url: str, req: Request) -> SCIMResponse HTTPSHandler(context=self.ssl), ) else: - raise SlackRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") else: raise SlackRequestError(f"Invalid URL detected: {url}") @@ -444,9 +405,7 @@ def _perform_http_request_internal(self, url: str, req: Request) -> SCIMResponse if opener: http_resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: - http_resp = urlopen( # skipcq: BAN-B310 - req, context=self.ssl, timeout=self.timeout - ) + http_resp = urlopen(req, context=self.ssl, timeout=self.timeout) # skipcq: BAN-B310 charset: str = http_resp.headers.get_content_charset() or "utf-8" response_body: str = http_resp.read().decode(charset) resp = SCIMResponse( diff --git a/slack_sdk/scim/v1/group.py b/slack_sdk/scim/v1/group.py index d26fd5b74..5bee76460 100644 --- a/slack_sdk/scim/v1/group.py +++ b/slack_sdk/scim/v1/group.py @@ -65,13 +65,9 @@ def __init__( self.display_name = display_name self.id = id self.members = ( - [a if isinstance(a, GroupMember) else GroupMember(**a) for a in members] - if _is_iterable(members) - else members - ) - self.meta = ( - GroupMeta(**meta) if meta is not None and isinstance(meta, dict) else meta + [a if isinstance(a, GroupMember) else GroupMember(**a) for a in members] if _is_iterable(members) else members ) + self.meta = GroupMeta(**meta) if meta is not None and isinstance(meta, dict) else meta self.schemas = schemas self.unknown_fields = kwargs diff --git a/slack_sdk/scim/v1/internal_utils.py b/slack_sdk/scim/v1/internal_utils.py index 0e130a018..1ad1b80ec 100644 --- a/slack_sdk/scim/v1/internal_utils.py +++ b/slack_sdk/scim/v1/internal_utils.py @@ -12,13 +12,7 @@ def _build_query(params: Optional[Dict[str, Any]]) -> str: if params is not None and len(params) > 0: - return "&".join( - { - f"{quote(str(k))}={quote(str(v))}" - for k, v in params.items() - if v is not None - } - ) + return "&".join({f"{quote(str(k))}={quote(str(v))}" for k, v in params.items() if v is not None}) return "" @@ -40,15 +34,11 @@ def _to_dict_without_not_given(obj: Any) -> dict: if value is NotGiven: continue if isinstance(value, list): - dict_value[dict_key] = [ - elem.to_dict() if hasattr(elem, "to_dict") else elem for elem in value - ] + dict_value[dict_key] = [elem.to_dict() if hasattr(elem, "to_dict") else elem for elem in value] elif isinstance(value, dict): dict_value[dict_key] = _to_dict_without_not_given(value) else: - dict_value[dict_key] = ( - value.to_dict() if hasattr(value, "to_dict") else value - ) + dict_value[dict_key] = value.to_dict() if hasattr(value, "to_dict") else value return dict_value @@ -105,9 +95,7 @@ def _convert_dict_keys( new_key = convert(original_key) if isinstance(original_value, dict): result_dict[new_key] = {} - new_value = _convert_dict_keys( - original_value, result_dict[new_key], convert - ) + new_value = _convert_dict_keys(original_value, result_dict[new_key], convert) result_dict[new_key] = new_value elif isinstance(original_value, list): result_dict[new_key] = [] diff --git a/slack_sdk/scim/v1/response.py b/slack_sdk/scim/v1/response.py index cd1851280..3631de3e9 100644 --- a/slack_sdk/scim/v1/response.py +++ b/slack_sdk/scim/v1/response.py @@ -53,14 +53,8 @@ def __init__( self.status_code = status_code self.headers = headers self.raw_body = raw_body - self.body = ( - json.loads(raw_body) - if raw_body is not None and raw_body.startswith("{") - else None - ) - self._snake_cased_body = ( - None # build this when it's accessed for the first time - ) + self.body = json.loads(raw_body) if raw_body is not None and raw_body.startswith("{") else None + self._snake_cased_body = None # build this when it's accessed for the first time def __repr__(self): dict_value = {} diff --git a/slack_sdk/scim/v1/user.py b/slack_sdk/scim/v1/user.py index 2037cfe78..9b2d4ff97 100644 --- a/slack_sdk/scim/v1/user.py +++ b/slack_sdk/scim/v1/user.py @@ -151,31 +151,19 @@ def __init__( self, *, active: Union[Optional[bool], DefaultArg] = NotGiven, - addresses: Union[ - Optional[List[Union[UserAddress, Dict[str, Any]]]], DefaultArg - ] = NotGiven, + addresses: Union[Optional[List[Union[UserAddress, Dict[str, Any]]]], DefaultArg] = NotGiven, display_name: Union[Optional[str], DefaultArg] = NotGiven, - emails: Union[ - Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg - ] = NotGiven, + emails: Union[Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg] = NotGiven, external_id: Union[Optional[str], DefaultArg] = NotGiven, - groups: Union[ - Optional[List[Union[UserGroup, Dict[str, Any]]]], DefaultArg - ] = NotGiven, + groups: Union[Optional[List[Union[UserGroup, Dict[str, Any]]]], DefaultArg] = NotGiven, id: Union[Optional[str], DefaultArg] = NotGiven, meta: Union[Optional[Union[UserMeta, Dict[str, Any]]], DefaultArg] = NotGiven, name: Union[Optional[Union[UserName, Dict[str, Any]]], DefaultArg] = NotGiven, nick_name: Union[Optional[str], DefaultArg] = NotGiven, - phone_numbers: Union[ - Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg - ] = NotGiven, - photos: Union[ - Optional[List[Union[UserPhoto, Dict[str, Any]]]], DefaultArg - ] = NotGiven, + phone_numbers: Union[Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg] = NotGiven, + photos: Union[Optional[List[Union[UserPhoto, Dict[str, Any]]]], DefaultArg] = NotGiven, profile_url: Union[Optional[str], DefaultArg] = NotGiven, - roles: Union[ - Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg - ] = NotGiven, + roles: Union[Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg] = NotGiven, schemas: Union[Optional[List[str]], DefaultArg] = NotGiven, timezone: Union[Optional[str], DefaultArg] = NotGiven, title: Union[Optional[str], DefaultArg] = NotGiven, @@ -190,42 +178,27 @@ def __init__( ) self.display_name = display_name self.emails = ( # type: ignore - [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in emails] - if _is_iterable(emails) - else emails + [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in emails] if _is_iterable(emails) else emails ) self.external_id = external_id self.groups = ( # type: ignore - [a if isinstance(a, UserGroup) else UserGroup(**a) for a in groups] - if _is_iterable(groups) - else groups + [a if isinstance(a, UserGroup) else UserGroup(**a) for a in groups] if _is_iterable(groups) else groups ) self.id = id - self.meta = ( # type: ignore - UserMeta(**meta) if meta is not None and isinstance(meta, dict) else meta - ) - self.name = ( # type: ignore - UserName(**name) if name is not None and isinstance(name, dict) else name - ) + self.meta = UserMeta(**meta) if meta is not None and isinstance(meta, dict) else meta # type: ignore + self.name = UserName(**name) if name is not None and isinstance(name, dict) else name # type: ignore self.nick_name = nick_name self.phone_numbers = ( # type: ignore - [ - a if isinstance(a, TypeAndValue) else TypeAndValue(**a) - for a in phone_numbers - ] + [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in phone_numbers] if _is_iterable(phone_numbers) else phone_numbers ) self.photos = ( # type: ignore - [a if isinstance(a, UserPhoto) else UserPhoto(**a) for a in photos] - if _is_iterable(photos) - else photos + [a if isinstance(a, UserPhoto) else UserPhoto(**a) for a in photos] if _is_iterable(photos) else photos ) self.profile_url = profile_url self.roles = ( # type: ignore - [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in roles] - if _is_iterable(roles) - else roles + [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in roles] if _is_iterable(roles) else roles ) self.schemas = schemas self.timezone = timezone diff --git a/slack_sdk/signature/__init__.py b/slack_sdk/signature/__init__.py index 5c7adc2ba..77b8b8539 100644 --- a/slack_sdk/signature/__init__.py +++ b/slack_sdk/signature/__init__.py @@ -55,9 +55,7 @@ def is_valid( return False return hmac.compare_digest(calculated_signature, signature) - def generate_signature( - self, *, timestamp: str, body: Union[str, bytes] - ) -> Optional[str]: + def generate_signature(self, *, timestamp: str, body: Union[str, bytes]) -> Optional[str]: """Generates a signature""" if timestamp is None: return None diff --git a/slack_sdk/socket_mode/aiohttp/__init__.py b/slack_sdk/socket_mode/aiohttp/__init__.py index 1304ffe54..caaaa97b3 100644 --- a/slack_sdk/socket_mode/aiohttp/__init__.py +++ b/slack_sdk/socket_mode/aiohttp/__init__.py @@ -36,9 +36,7 @@ class SocketModeClient(AsyncBaseSocketModeClient): message_listeners: List[ Union[ AsyncWebSocketMessageListener, - Callable[ - ["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None] - ], + Callable[["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None]], ] ] socket_mode_request_listeners: List[ @@ -78,15 +76,9 @@ def __init__( auto_reconnect_enabled: bool = True, ping_interval: float = 5, trace_enabled: bool = False, - on_message_listeners: Optional[ - List[Callable[[WSMessage], Awaitable[None]]] - ] = None, - on_error_listeners: Optional[ - List[Callable[[WSMessage], Awaitable[None]]] - ] = None, - on_close_listeners: Optional[ - List[Callable[[WSMessage], Awaitable[None]]] - ] = None, + on_message_listeners: Optional[List[Callable[[WSMessage], Awaitable[None]]]] = None, + on_error_listeners: Optional[List[Callable[[WSMessage], Awaitable[None]]]] = None, + on_close_listeners: Optional[List[Callable[[WSMessage], Awaitable[None]]]] = None, ): """Socket Mode client @@ -149,9 +141,7 @@ async def monitor_current_session(self) -> None: session_id: str = self.build_session_id(session) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new monitor_current_session() execution loop for {session_id} started" - ) + self.logger.debug(f"A new monitor_current_session() execution loop for {session_id} started") try: logging_interval = 100 counter_for_logging = 0 @@ -159,9 +149,7 @@ async def monitor_current_session(self) -> None: while not self.closed: if session != self.current_session: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"The monitor_current_session task for {session_id} is now cancelled" - ) + self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled") break try: if self.trace_enabled and self.logger.level <= logging.DEBUG: @@ -189,22 +177,16 @@ async def monitor_current_session(self) -> None: # The ping() method can fail for some reason. # To establish a new connection even in this scenario, # we ignore the exception here. - self.logger.warning( - f"Failed to send a ping message ({session_id}): {e}" - ) + self.logger.warning(f"Failed to send a ping message ({session_id}): {e}") if self.auto_reconnect_enabled: should_reconnect = False if session is None or session.closed: - self.logger.info( - f"The session ({session_id}) seems to be already closed. Reconnecting..." - ) + self.logger.info(f"The session ({session_id}) seems to be already closed. Reconnecting...") should_reconnect = True if await self.is_ping_pong_failing(): - disconnected_seconds = int( - time.time() - self.last_ping_pong_time - ) + disconnected_seconds = int(time.time() - self.last_ping_pong_time) self.logger.info( f"The session ({session_id}) seems to be stale. Reconnecting..." f" reason: disconnected for {disconnected_seconds}+ seconds)" @@ -223,9 +205,7 @@ async def monitor_current_session(self) -> None: ) except asyncio.CancelledError: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"The monitor_current_session task for {session_id} is now cancelled" - ) + self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled") raise async def receive_messages(self) -> None: @@ -235,9 +215,7 @@ async def receive_messages(self) -> None: session = self.current_session session_id = self.build_session_id(session) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new receive_messages() execution loop with {session_id} started" - ) + self.logger.debug(f"A new receive_messages() execution loop with {session_id} started") try: consecutive_error_count = 0 logging_interval = 100 @@ -246,9 +224,7 @@ async def receive_messages(self) -> None: while not self.closed: if session != self.current_session: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"The running receive_messages task for {session_id} is now cancelled" - ) + self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled") break try: message: WSMessage = await session.receive() @@ -258,9 +234,7 @@ async def receive_messages(self) -> None: # The following logging prints every single received message # except empty message data ones. type = WSMsgType(message.type) - message_type = ( - type.name if type is not None else message.type - ) + message_type = type.name if type is not None else message.type message_data = message.data if isinstance(message_data, bytes): message_data = message_data.decode("utf-8") @@ -294,9 +268,7 @@ async def receive_messages(self) -> None: await listener(message) elif message.type == WSMsgType.CLOSE: if self.auto_reconnect_enabled: - self.logger.info( - f"Received CLOSE event from {session_id}. Reconnecting..." - ) + self.logger.info(f"Received CLOSE event from {session_id}. Reconnecting...") await self.connect_to_new_endpoint() for listener in self.on_close_listeners: await listener(message) @@ -313,10 +285,7 @@ async def receive_messages(self) -> None: if message.data is not None: str_message_data = message.data.decode("utf-8") elements = str_message_data.split(":") - if ( - len(elements) == 2 - and elements[0] == "sdk-ping-pong" - ): + if len(elements) == 2 and elements[0] == "sdk-ping-pong": try: self.last_ping_pong_time = float(elements[1]) except Exception as e: @@ -330,18 +299,14 @@ async def receive_messages(self) -> None: except Exception as e: consecutive_error_count += 1 - self.logger.error( - f"Failed to receive or enqueue a message: {type(e).__name__}, {e} ({session_id})" - ) + self.logger.error(f"Failed to receive or enqueue a message: {type(e).__name__}, {e} ({session_id})") if isinstance(e, ClientConnectionError): await asyncio.sleep(self.ping_interval) else: await asyncio.sleep(consecutive_error_count) except asyncio.CancelledError: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"The running receive_messages task for {session_id} is now cancelled" - ) + self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled") raise async def is_ping_pong_failing(self) -> bool: @@ -377,9 +342,7 @@ async def session_id(self) -> str: return self.build_session_id(self.current_session) async def connect(self): - old_session: Optional[ClientWebSocketResponse] = ( - None if self.current_session is None else self.current_session - ) + old_session: Optional[ClientWebSocketResponse] = None if self.current_session is None else self.current_session if self.wss_uri is None: # If the underlying WSS URL does not exist, # acquiring a new active WSS URL from the server-side first @@ -398,31 +361,23 @@ async def connect(self): # The first ping from the new connection if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Sending a ping message with the newly established connection ({session_id})..." - ) + self.logger.debug(f"Sending a ping message with the newly established connection ({session_id})...") t = time.time() await self.current_session.ping(f"sdk-ping-pong:{t}") if self.current_session_monitor is not None: self.current_session_monitor.cancel() - self.current_session_monitor = asyncio.ensure_future( - self.monitor_current_session() - ) + self.current_session_monitor = asyncio.ensure_future(self.monitor_current_session()) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new monitor_current_session() executor has been recreated for {session_id}" - ) + self.logger.debug(f"A new monitor_current_session() executor has been recreated for {session_id}") if self.message_receiver is not None: self.message_receiver.cancel() self.message_receiver = asyncio.ensure_future(self.receive_messages()) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new receive_messages() executor has been recreated for {session_id}" - ) + self.logger.debug(f"A new receive_messages() executor has been recreated for {session_id}") if old_session is not None: await old_session.close() @@ -433,16 +388,12 @@ async def disconnect(self): if self.current_session is not None: await self.current_session.close() session_id = await self.session_id() - self.logger.info( - f"The current session ({session_id}) has been abandoned by disconnect() method call" - ) + self.logger.info(f"The current session ({session_id}) has been abandoned by disconnect() method call") async def send_message(self, message: str): session_id = await self.session_id() if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Sending a message: {message} from session: {session_id}" - ) + self.logger.debug(f"Sending a message: {message} from session: {session_id}") try: await self.current_session.send_str(message) except ConnectionError as e: @@ -461,8 +412,7 @@ async def send_message(self, message: str): await self.current_session.send_str(message) else: self.logger.warning( - f"The current session ({session_id}) is no longer active. " - "Failed to send a message" + f"The current session ({session_id}) is no longer active. " "Failed to send a message" ) raise e finally: diff --git a/slack_sdk/socket_mode/async_client.py b/slack_sdk/socket_mode/async_client.py index 478ee51d3..7fc0d6756 100644 --- a/slack_sdk/socket_mode/async_client.py +++ b/slack_sdk/socket_mode/async_client.py @@ -30,9 +30,7 @@ class AsyncBaseSocketModeClient: message_listeners: List[ Union[ AsyncWebSocketMessageListener, - Callable[ - ["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None] - ], + Callable[["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None]], ] ] socket_mode_request_listeners: List[ @@ -44,9 +42,7 @@ class AsyncBaseSocketModeClient: async def issue_new_wss_url(self) -> str: try: - response = await self.web_client.apps_connections_open( - app_token=self.app_token - ) + response = await self.web_client.apps_connections_open(app_token=self.app_token) return response["url"] except SlackApiError as e: if e.response["error"] == "ratelimited": @@ -78,9 +74,7 @@ async def connect_to_new_endpoint(self, force: bool = False): try: await self.connect_operation_lock.acquire() if self.trace_enabled: - self.logger.debug( - f"For reconnection, the connect_operation_lock was acquired (session: {session_id})" - ) + self.logger.debug(f"For reconnection, the connect_operation_lock was acquired (session: {session_id})") if force or not await self.is_connected(): self.wss_uri = await self.issue_new_wss_url() await self.connect() @@ -88,9 +82,7 @@ async def connect_to_new_endpoint(self, force: bool = False): if self.connect_operation_lock.locked() is True: self.connect_operation_lock.release() if self.trace_enabled: - self.logger.debug( - f"The connect_operation_lock for reconnection was released (session: {session_id})" - ) + self.logger.debug(f"The connect_operation_lock for reconnection was released (session: {session_id})") async def close(self): self.closed = True @@ -99,9 +91,7 @@ async def close(self): async def send_message(self, message: str): raise NotImplementedError() - async def send_socket_mode_response( - self, response: Union[Dict[str, Any], SocketModeResponse] - ): + async def send_socket_mode_response(self, response: Union[Dict[str, Any], SocketModeResponse]): if isinstance(response, SocketModeResponse): await self.send_message(json.dumps(response.to_dict())) else: @@ -112,9 +102,7 @@ async def enqueue_message(self, message: str): if self.logger.level <= logging.DEBUG: queue_size = self.message_queue.qsize() session_id = await self.session_id() - self.logger.debug( - f"A new message enqueued (current queue size: {queue_size}, session: {session_id})" - ) + self.logger.debug(f"A new message enqueued (current queue size: {queue_size}, session: {session_id})") async def process_messages(self): session_id = await self.session_id() @@ -128,14 +116,10 @@ async def process_messages(self): if not self.closed: raise except Exception as e: - self.logger.exception( - f"Failed to process a message: {e}, session: {session_id}" - ) + self.logger.exception(f"Failed to process a message: {e}, session: {session_id}") except asyncio.CancelledError: if self.trace_enabled: - self.logger.debug( - f"The running process_messages task for {session_id} is now cancelled" - ) + self.logger.debug(f"The running process_messages task for {session_id} is now cancelled") raise async def process_message(self): @@ -144,9 +128,7 @@ async def process_message(self): message: dict = {} if raw_message.startswith("{"): message = json.loads(raw_message) - _: Future[None] = asyncio.ensure_future( - self.run_message_listeners(message, raw_message) - ) + _: Future[None] = asyncio.ensure_future(self.run_message_listeners(message, raw_message)) async def run_message_listeners(self, message: dict, raw_message: str) -> None: session_id = await self.session_id() @@ -164,9 +146,7 @@ async def run_message_listeners(self, message: dict, raw_message: str) -> None: try: await listener(self, message, raw_message) # type: ignore except Exception as e: - self.logger.exception( - f"Failed to run a message listener: {e}, session: {session_id}" - ) + self.logger.exception(f"Failed to run a message listener: {e}, session: {session_id}") if len(self.socket_mode_request_listeners) > 0: request = SocketModeRequest.from_dict(message) @@ -175,13 +155,9 @@ async def run_message_listeners(self, message: dict, raw_message: str) -> None: try: await listener(self, request) # type: ignore except Exception as e: - self.logger.exception( - f"Failed to run a request listener: {e}, session: {session_id}" - ) + self.logger.exception(f"Failed to run a request listener: {e}, session: {session_id}") except Exception as e: - self.logger.exception( - f"Failed to run message listeners: {e}, session: {session_id}" - ) + self.logger.exception(f"Failed to run message listeners: {e}, session: {session_id}") finally: if self.logger.level <= logging.DEBUG: self.logger.debug( diff --git a/slack_sdk/socket_mode/builtin/client.py b/slack_sdk/socket_mode/builtin/client.py index 89463a767..79f875d52 100644 --- a/slack_sdk/socket_mode/builtin/client.py +++ b/slack_sdk/socket_mode/builtin/client.py @@ -112,9 +112,7 @@ def __init__( self.ping_interval = ping_interval self.receive_buffer_size = receive_buffer_size if self.receive_buffer_size < 16: - raise SlackClientConfigurationError( - "Too small receive_buffer_size detected." - ) + raise SlackClientConfigurationError("Too small receive_buffer_size detected.") self.wss_uri = None self.message_queue = Queue() @@ -123,14 +121,10 @@ def __init__( self.current_session = None self.current_session_state = ConnectionState() - self.current_session_runner = IntervalRunner( - self._run_current_session, 0.1 - ).start() + self.current_session_runner = IntervalRunner(self._run_current_session, 0.1).start() self.current_app_monitor_started = False - self.current_app_monitor = IntervalRunner( - self._monitor_current_session, self.ping_interval - ) + self.current_app_monitor = IntervalRunner(self._monitor_current_session, self.ping_interval) self.closed = False self.connect_operation_lock = Lock() @@ -194,9 +188,7 @@ def connect(self) -> None: self.current_app_monitor_started = True self.current_app_monitor.start() - self.logger.info( - f"A new session has been established (session id: {self.session_id()})" - ) + self.logger.info(f"A new session has been established (session id: {self.session_id()})") def disconnect(self) -> None: if self.current_session is not None: @@ -204,9 +196,7 @@ def disconnect(self) -> None: def send_message(self, message: str) -> None: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Sending a message (session id: {self.session_id()}, message: {message})" - ) + self.logger.debug(f"Sending a message (session id: {self.session_id()}, message: {message})") try: self.current_session.send(message) except SlackClientNotConnectedError as e: @@ -248,8 +238,7 @@ def _on_message(self, message: str): def _on_error(self, error: Exception): error_message = ( - f"on_error invoked (session id: {self.session_id()}, " - f"error: {type(error).__name__}, message: {error})" + f"on_error invoked (session id: {self.session_id()}, " f"error: {type(error).__name__}, message: {error})" ) if self.trace_enabled: self.logger.exception(error_message) @@ -263,10 +252,7 @@ def _on_close(self, code: int, reason: Optional[str] = None): if self.logger.level <= logging.DEBUG: self.logger.debug(f"on_close invoked (session id: {self.session_id()})") if self.auto_reconnect_enabled: - self.logger.info( - "Received CLOSE event. Reconnecting... " - f"(session id: {self.session_id()})" - ) + self.logger.info("Received CLOSE event. Reconnecting... " f"(session id: {self.session_id()})") self.connect_to_new_endpoint() for listener in self.on_close_listeners: listener(code, reason) @@ -275,21 +261,12 @@ def _run_current_session(self): if self.current_session is not None and self.current_session.is_active(): session_id = self.session_id() try: - self.logger.info( - "Starting to receive messages from a new connection" - f" (session id: {session_id})" - ) + self.logger.info("Starting to receive messages from a new connection" f" (session id: {session_id})") self.current_session_state.terminated = False self.current_session.run_until_completion(self.current_session_state) - self.logger.info( - "Stopped receiving messages from a connection" - f" (session id: {session_id})" - ) + self.logger.info("Stopped receiving messages from a connection" f" (session id: {session_id})") except Exception as e: - error_message = ( - "Failed to start or stop the current session" - f" (session id: {session_id}, error: {e})" - ) + error_message = "Failed to start or stop the current session" f" (session id: {session_id}, error: {e})" if self.trace_enabled: self.logger.exception(error_message) else: @@ -300,12 +277,9 @@ def _monitor_current_session(self): try: self.current_session.check_state() - if self.auto_reconnect_enabled and ( - self.current_session is None or not self.current_session.is_active() - ): + if self.auto_reconnect_enabled and (self.current_session is None or not self.current_session.is_active()): self.logger.info( - "The session seems to be already closed. Reconnecting... " - f"(session id: {self.session_id()})" + "The session seems to be already closed. Reconnecting... " f"(session id: {self.session_id()})" ) self.connect_to_new_endpoint() except Exception as e: diff --git a/slack_sdk/socket_mode/builtin/connection.py b/slack_sdk/socket_mode/builtin/connection.py index d0c5ea303..dd9eed045 100644 --- a/slack_sdk/socket_mode/builtin/connection.py +++ b/slack_sdk/socket_mode/builtin/connection.py @@ -75,9 +75,7 @@ def __init__( self.receive_timeout = receive_timeout self.receive_buffer_size = receive_buffer_size if self.receive_buffer_size < 16: - raise SlackClientConfigurationError( - "Too small receive_buffer_size detected." - ) + raise SlackClientConfigurationError("Too small receive_buffer_size detected.") self.session_id = str(uuid4()) self.trace_enabled = trace_enabled @@ -104,8 +102,7 @@ def connect(self) -> None: port: int = parsed_url.port or (443 if parsed_url.scheme == "wss" else 80) if self.trace_enabled: self.logger.debug( - f"Connecting to the address for handshake: {hostname}:{port} " - f"(session id: {self.session_id})" + f"Connecting to the address for handshake: {hostname}:{port} " f"(session id: {self.session_id})" ) sock: Union[ssl.SSLSocket, socket] = _establish_new_socket_connection( # type: ignore session_id=self.session_id, @@ -195,9 +192,7 @@ def disconnect(self) -> None: self.sock = None # After this, all operations using self.sock will be skipped - self.logger.info( - f"The connection has been closed (session id: {self.session_id})" - ) + self.logger.info(f"The connection has been closed (session id: {self.session_id})") def is_active(self) -> bool: return self.sock is not None @@ -209,46 +204,33 @@ def ping(self, payload: Union[str, bytes] = "") -> None: if self.trace_enabled and self.ping_pong_trace_enabled: if isinstance(payload, bytes): payload = payload.decode("utf-8") - self.logger.debug( - "Sending a ping data frame " - f"(session id: {self.session_id}, payload: {payload})" - ) + self.logger.debug("Sending a ping data frame " f"(session id: {self.session_id}, payload: {payload})") data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PING) with self.sock_send_lock: if self.sock is not None: self.sock.send(data) else: if self.ping_pong_trace_enabled: - self.logger.debug( - "Skipped sending a ping message as the underlying socket is no longer available." - ) + self.logger.debug("Skipped sending a ping message as the underlying socket is no longer available.") def pong(self, payload: Union[str, bytes] = "") -> None: if self.trace_enabled and self.ping_pong_trace_enabled: if isinstance(payload, bytes): payload = payload.decode("utf-8") - self.logger.debug( - "Sending a pong data frame " - f"(session id: {self.session_id}, payload: {payload})" - ) + self.logger.debug("Sending a pong data frame " f"(session id: {self.session_id}, payload: {payload})") data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PONG) with self.sock_send_lock: if self.sock is not None: self.sock.send(data) else: if self.ping_pong_trace_enabled: - self.logger.debug( - "Skipped sending a pong message as the underlying socket is no longer available." - ) + self.logger.debug("Skipped sending a pong message as the underlying socket is no longer available.") def send(self, payload: str) -> None: if self.trace_enabled: if isinstance(payload, bytes): payload = payload.decode("utf-8") - self.logger.debug( - "Sending a text data frame " - f"(session id: {self.session_id}, payload: {payload})" - ) + self.logger.debug("Sending a text data frame " f"(session id: {self.session_id}, payload: {payload})") data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_TEXT) with self.sock_send_lock: try: @@ -296,10 +278,7 @@ def check_state(self) -> None: self.disconnect() return else: - self.logger.debug( - "This connection is already closed." - f" (session id: {self.session_id})" - ) + self.logger.debug("This connection is already closed." f" (session id: {self.session_id})") self.consecutive_check_state_error_count = 0 except Exception as e: error_message = ( @@ -323,9 +302,7 @@ def run_until_completion(self, state: ConnectionState) -> None: while not state.terminated: try: if self.is_active(): - received_messages: List[ - Tuple[Optional[FrameHeader], bytes] - ] = _receive_messages( + received_messages: List[Tuple[Optional[FrameHeader], bytes]] = _receive_messages( sock=self.sock, sock_receive_lock=self.sock_receive_lock, logger=self.logger, @@ -339,9 +316,7 @@ def run_until_completion(self, state: ConnectionState) -> None: # trace logging if self.trace_enabled is True: - opcode: str = ( - _to_readable_opcode(header.opcode) if header else "-" - ) + opcode: str = _to_readable_opcode(header.opcode) if header else "-" payload: str = _parse_text_payload(data, self.logger) count: Optional[int] = repeated_messages.get(payload) if count is None: @@ -349,11 +324,7 @@ def run_until_completion(self, state: ConnectionState) -> None: else: count += 1 repeated_messages = {payload: count} - if ( - not self.ping_pong_trace_enabled - and header is not None - and header.opcode is not None - ): + if not self.ping_pong_trace_enabled and header is not None and header.opcode is not None: if header.opcode == FrameHeader.OPCODE_PING: ping_count += 1 if ping_count % ping_pong_log_summary_size == 0: @@ -374,10 +345,7 @@ def run_until_completion(self, state: ConnectionState) -> None: ping_pong_to_skip = ( header is not None and header.opcode is not None - and ( - header.opcode == FrameHeader.OPCODE_PING - or header.opcode == FrameHeader.OPCODE_PONG - ) + and (header.opcode == FrameHeader.OPCODE_PING or header.opcode == FrameHeader.OPCODE_PONG) and not self.ping_pong_trace_enabled ) if not ping_pong_to_skip and count < 5: @@ -407,8 +375,7 @@ def run_until_completion(self, state: ConnectionState) -> None: self.last_ping_pong_time = float(ping_time) except Exception as e: self.logger.debug( - "Failed to parse a pong message " - f" (message: {str_message}, error: {e}" + "Failed to parse a pong message " f" (message: {str_message}, error: {e}" ) elif header.opcode == FrameHeader.OPCODE_TEXT: if self.on_message_listener is not None: @@ -426,19 +393,13 @@ def run_until_completion(self, state: ConnectionState) -> None: state.terminated = True else: # Just warn logging - opcode = ( - _to_readable_opcode(header.opcode) if header else "-" - ) + opcode = _to_readable_opcode(header.opcode) if header else "-" payload: Union[bytes, str] = data if header.opcode != FrameHeader.OPCODE_BINARY: try: - payload = ( - data.decode("utf-8") if data is not None else "" - ) + payload = data.decode("utf-8") if data is not None else "" except Exception as e: - self.logger.info( - f"Failed to convert the data to text {e}" - ) + self.logger.info(f"Failed to convert the data to text {e}") message = ( "Received an unsupported data frame " f"(session id: {self.session_id}, opcode: {opcode}, payload: {payload})" @@ -452,17 +413,13 @@ def run_until_completion(self, state: ConnectionState) -> None: # getting errno.EBADF and the socket is no longer available if e.errno == 9 and state.terminated: self.logger.debug( - "The reason why you got [Errno 9] Bad file descriptor here is " - "the socket is no longer available." + "The reason why you got [Errno 9] Bad file descriptor here is " "the socket is no longer available." ) else: if self.on_error_listener is not None: self.on_error_listener(e) else: - error_message = ( - "Got an OSError while receiving data" - f" (session id: {self.session_id}, error: {e})" - ) + error_message = "Got an OSError while receiving data" f" (session id: {self.session_id}, error: {e})" if self.trace_enabled: self.logger.exception(error_message) else: @@ -474,8 +431,7 @@ def run_until_completion(self, state: ConnectionState) -> None: self.disconnect() except Exception as disconnection_error: error_message = ( - "Failed to disconnect" - f" (session id: {self.session_id}, error: {disconnection_error})" + "Failed to disconnect" f" (session id: {self.session_id}, error: {disconnection_error})" ) if self.trace_enabled: self.logger.exception(error_message) @@ -487,10 +443,7 @@ def run_until_completion(self, state: ConnectionState) -> None: if self.on_error_listener is not None: self.on_error_listener(e) else: - error_message = ( - "Got an exception while receiving data" - f" (session id: {self.session_id}, error: {e})" - ) + error_message = "Got an exception while receiving data" f" (session id: {self.session_id}, error: {e})" if self.trace_enabled: self.logger.exception(error_message) else: diff --git a/slack_sdk/socket_mode/builtin/internals.py b/slack_sdk/socket_mode/builtin/internals.py index c0574c1ae..1bc9d1651 100644 --- a/slack_sdk/socket_mode/builtin/internals.py +++ b/slack_sdk/socket_mode/builtin/internals.py @@ -67,9 +67,7 @@ def _establish_new_socket_connection( message = [f"CONNECT {server_hostname}:{server_port} HTTP/1.0"] if parsed_proxy.username is not None and parsed_proxy.password is not None: # In the case where the proxy is "http://{username}:{password}@{hostname}:{port}" - raw_value = ( - f"{unquote(parsed_proxy.username)}:{unquote(parsed_proxy.password)}" - ) + raw_value = f"{unquote(parsed_proxy.username)}:{unquote(parsed_proxy.password)}" auth = b64encode(raw_value.encode("utf-8")).decode("ascii") message.append(f"Proxy-Authorization: Basic {auth}") if proxy_headers is not None: @@ -87,9 +85,7 @@ def _establish_new_socket_connection( log_message = f"Proxy connect response (session id: {session_id}):\n{text}" logger.debug(log_message) if status != 200: - raise Exception( - f"Failed to connect to the proxy (proxy: {proxy}, connect status code: {status})" - ) + raise Exception(f"Failed to connect to the proxy (proxy: {proxy}, connect status code: {status})") sock = ssl_context.wrap_socket( sock, @@ -101,9 +97,7 @@ def _establish_new_socket_connection( if server_port != 443: # only for library testing - logger.info( - f"Using non-ssl socket to connect ({server_hostname}:{server_port})" - ) + logger.info(f"Using non-ssl socket to connect ({server_hostname}:{server_port})") sock = socket.create_connection((server_hostname, server_port), timeout=3) return sock @@ -203,11 +197,7 @@ def _receive_messages( all_message_trace_enabled: bool = False, ) -> List[Tuple[Optional[FrameHeader], bytes]]: def receive(specific_buffer_size: Optional[int] = None): - size = ( - specific_buffer_size - if specific_buffer_size is not None - else receive_buffer_size - ) + size = specific_buffer_size if specific_buffer_size is not None else receive_buffer_size with sock_receive_lock: try: received_bytes = sock.recv(size) @@ -397,9 +387,7 @@ def _build_data_frame_for_sending( b1 = fin << 7 | rsv1 << 6 | rsv2 << 5 | rsv3 << 4 | opcode header: bytes = bytes([b1]) - original_payload_data: bytes = ( - payload.encode("utf-8") if isinstance(payload, str) else payload - ) + original_payload_data: bytes = payload.encode("utf-8") if isinstance(payload, str) else payload payload_length = len(original_payload_data) if payload_length <= 125: b2 = masked << 7 | payload_length @@ -411,8 +399,5 @@ def _build_data_frame_for_sending( mask_key: List[int] = random.choices(range(256), k=4) header += bytes(mask_key) - payload_data: bytes = bytes( - byte ^ mask - for byte, mask in zip(original_payload_data, itertools.cycle(mask_key)) - ) + payload_data: bytes = bytes(byte ^ mask for byte, mask in zip(original_payload_data, itertools.cycle(mask_key))) return header + payload_data diff --git a/slack_sdk/socket_mode/client.py b/slack_sdk/socket_mode/client.py index a3a37c0df..6340445d2 100644 --- a/slack_sdk/socket_mode/client.py +++ b/slack_sdk/socket_mode/client.py @@ -87,9 +87,7 @@ def close(self) -> None: def send_message(self, message: str) -> None: raise NotImplementedError() - def send_socket_mode_response( - self, response: Union[Dict[str, Any], SocketModeResponse] - ) -> None: + def send_socket_mode_response(self, response: Union[Dict[str, Any], SocketModeResponse]) -> None: if isinstance(response, SocketModeResponse): self.send_message(json.dumps(response.to_dict())) else: @@ -98,17 +96,13 @@ def send_socket_mode_response( def enqueue_message(self, message: str): self.message_queue.put(message) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new message enqueued (current queue size: {self.message_queue.qsize()})" - ) + self.logger.debug(f"A new message enqueued (current queue size: {self.message_queue.qsize()})") def process_message(self): try: raw_message = self.message_queue.get(timeout=1) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A message dequeued (current queue size: {self.message_queue.qsize()})" - ) + self.logger.debug(f"A message dequeued (current queue size: {self.message_queue.qsize()})") if raw_message is not None: message: dict = {} @@ -128,9 +122,7 @@ def _run_message_listeners(): def run_message_listeners(self, message: dict, raw_message: str) -> None: type, envelope_id = message.get("type"), message.get("envelope_id") if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Message processing started (type: {type}, envelope_id: {envelope_id})" - ) + self.logger.debug(f"Message processing started (type: {type}, envelope_id: {envelope_id})") try: # just in case, adding the same logic to reconnect here if message.get("type") == "disconnect": @@ -150,16 +142,12 @@ def run_message_listeners(self, message: dict, raw_message: str) -> None: try: listener(self, request) # type: ignore except Exception as e: - self.logger.exception( - f"Failed to run a request listener: {e}" - ) + self.logger.exception(f"Failed to run a request listener: {e}") except Exception as e: self.logger.exception(f"Failed to run message listeners: {e}") finally: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Message processing completed (type: {type}, envelope_id: {envelope_id})" - ) + self.logger.debug(f"Message processing completed (type: {type}, envelope_id: {envelope_id})") def process_messages(self) -> None: while not self.closed: diff --git a/slack_sdk/socket_mode/listeners.py b/slack_sdk/socket_mode/listeners.py index dac5e68d5..3a10834e2 100644 --- a/slack_sdk/socket_mode/listeners.py +++ b/slack_sdk/socket_mode/listeners.py @@ -13,7 +13,5 @@ def __call__( # type: ignore class SocketModeRequestListener: - def __call__( # type: ignore - client: "BaseSocketModeClient", request: SocketModeRequest # noqa: F821 - ): # noqa: F821 + def __call__(client: "BaseSocketModeClient", request: SocketModeRequest): # type: ignore # noqa: F821 # noqa: F821 raise NotImplementedError() diff --git a/slack_sdk/socket_mode/request.py b/slack_sdk/socket_mode/request.py index 6f77ad3e9..6a1d38e98 100644 --- a/slack_sdk/socket_mode/request.py +++ b/slack_sdk/socket_mode/request.py @@ -31,9 +31,7 @@ def __init__( self.payload = {"text": payload} else: unexpected_payload_type = type(payload) # type: ignore - raise ValueError( - f"Unsupported payload data type ({unexpected_payload_type})" - ) + raise ValueError(f"Unsupported payload data type ({unexpected_payload_type})") self.accepts_response_payload = accepts_response_payload or False self.retry_attempt = retry_attempt @@ -46,8 +44,7 @@ def from_dict(cls, message: dict) -> Optional["SocketModeRequest"]: type=message.get("type"), envelope_id=message.get("envelope_id"), payload=message.get("payload"), - accepts_response_payload=message.get("accepts_response_payload") - or False, + accepts_response_payload=message.get("accepts_response_payload") or False, retry_attempt=message.get("retry_attempt"), retry_reason=message.get("retry_reason"), ) diff --git a/slack_sdk/socket_mode/response.py b/slack_sdk/socket_mode/response.py index f748a6c8e..4984af03b 100644 --- a/slack_sdk/socket_mode/response.py +++ b/slack_sdk/socket_mode/response.py @@ -7,9 +7,7 @@ class SocketModeResponse: envelope_id: str payload: dict - def __init__( - self, envelope_id: str, payload: Optional[Union[dict, JsonObject, str]] = None - ): + def __init__(self, envelope_id: str, payload: Optional[Union[dict, JsonObject, str]] = None): self.envelope_id = envelope_id if payload is None: diff --git a/slack_sdk/socket_mode/websocket_client/__init__.py b/slack_sdk/socket_mode/websocket_client/__init__.py index 24037d287..851622a3a 100644 --- a/slack_sdk/socket_mode/websocket_client/__init__.py +++ b/slack_sdk/socket_mode/websocket_client/__init__.py @@ -77,12 +77,8 @@ def __init__( http_proxy_auth: Optional[Tuple[str, str]] = None, proxy_type: Optional[str] = None, on_open_listeners: Optional[List[Callable[[WebSocketApp], None]]] = None, - on_message_listeners: Optional[ - List[Callable[[WebSocketApp, str], None]] - ] = None, - on_error_listeners: Optional[ - List[Callable[[WebSocketApp, Exception], None]] - ] = None, + on_message_listeners: Optional[List[Callable[[WebSocketApp, str], None]]] = None, + on_error_listeners: Optional[List[Callable[[WebSocketApp, Exception], None]]] = None, on_close_listeners: Optional[List[Callable[[WebSocketApp], None]]] = None, ): """ @@ -115,14 +111,10 @@ def __init__( self.socket_mode_request_listeners = [] self.current_session = None - self.current_session_runner = IntervalRunner( - self._run_current_session, 0.5 - ).start() + self.current_session_runner = IntervalRunner(self._run_current_session, 0.5).start() self.current_app_monitor_started = False - self.current_app_monitor = IntervalRunner( - self._monitor_current_session, self.ping_interval - ) + self.current_app_monitor = IntervalRunner(self._monitor_current_session, self.ping_interval) self.closed = False self.connect_operation_lock = Lock() @@ -161,9 +153,7 @@ def on_message(ws: WebSocketApp, message: str): listener(ws, message) def on_error(ws: WebSocketApp, error: Exception): - self.logger.error( - f"on_error invoked (error: {type(error).__name__}, message: {error})" - ) + self.logger.error(f"on_error invoked (error: {type(error).__name__}, message: {error})") for listener in self.on_error_listeners: listener(ws, error) @@ -173,9 +163,7 @@ def on_close( close_msg: Optional[str] = None, ): if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"on_close invoked: (code: {close_status_code}, message: {close_msg})" - ) + self.logger.debug(f"on_close invoked: (code: {close_status_code}, message: {close_msg})") if self.auto_reconnect_enabled: self.logger.info("Received CLOSE event. Reconnecting...") self.connect_to_new_endpoint() @@ -255,19 +243,13 @@ def _run_current_session(self): ) self.logger.info("Stopped receiving messages from a connection") except Exception as e: - self.logger.exception( - f"Failed to start or stop the current session: {e}" - ) + self.logger.exception(f"Failed to start or stop the current session: {e}") def _monitor_current_session(self): if self.current_app_monitor_started: try: - if self.auto_reconnect_enabled and ( - self.current_session is None or self.current_session.sock is None - ): - self.logger.info( - "The session seems to be already closed. Reconnecting..." - ) + if self.auto_reconnect_enabled and (self.current_session is None or self.current_session.sock is None): + self.logger.info("The session seems to be already closed. Reconnecting...") self.connect_to_new_endpoint() except Exception as e: self.logger.error( diff --git a/slack_sdk/socket_mode/websockets/__init__.py b/slack_sdk/socket_mode/websockets/__init__.py index 275cd8a1f..39ed6b33f 100644 --- a/slack_sdk/socket_mode/websockets/__init__.py +++ b/slack_sdk/socket_mode/websockets/__init__.py @@ -37,9 +37,7 @@ class SocketModeClient(AsyncBaseSocketModeClient): message_listeners: List[ Union[ AsyncWebSocketMessageListener, - Callable[ - ["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None] - ], + Callable[["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None]], ] ] socket_mode_request_listeners: List[ @@ -108,25 +106,17 @@ async def monitor_current_session(self) -> None: session: WebSocketClientProtocol = self.current_session session_id: str = await self.session_id() if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new monitor_current_session() execution loop for {session_id} started" - ) + self.logger.debug(f"A new monitor_current_session() execution loop for {session_id} started") try: while not self.closed: if session != self.current_session: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"The monitor_current_session task for {session_id} is now cancelled" - ) + self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled") break await asyncio.sleep(self.ping_interval) try: - if self.auto_reconnect_enabled and ( - session is None or session.closed - ): - self.logger.info( - f"The session ({session_id}) seems to be already closed. Reconnecting..." - ) + if self.auto_reconnect_enabled and (session is None or session.closed): + self.logger.info(f"The session ({session_id}) seems to be already closed. Reconnecting...") await self.connect_to_new_endpoint() except Exception as e: self.logger.error( @@ -135,9 +125,7 @@ async def monitor_current_session(self) -> None: ) except asyncio.CancelledError: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"The monitor_current_session task for {session_id} is now cancelled" - ) + self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled") raise async def receive_messages(self) -> None: @@ -148,16 +136,12 @@ async def receive_messages(self) -> None: session_id: str = await self.session_id() consecutive_error_count = 0 if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new receive_messages() execution loop with {session_id} started" - ) + self.logger.debug(f"A new receive_messages() execution loop with {session_id} started") try: while not self.closed: if session != self.current_session: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"The running receive_messages task for {session_id} is now cancelled" - ) + self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled") break try: message = await session.recv() @@ -165,9 +149,7 @@ async def receive_messages(self) -> None: if isinstance(message, bytes): message = message.decode("utf-8") if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Received message: {message}, session: {session_id}" - ) + self.logger.debug(f"Received message: {message}, session: {session_id}") await self.enqueue_message(message) consecutive_error_count = 0 except Exception as e: @@ -181,17 +163,11 @@ async def receive_messages(self) -> None: await asyncio.sleep(consecutive_error_count) except asyncio.CancelledError: if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"The running receive_messages task for {session_id} is now cancelled" - ) + self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled") raise async def is_connected(self) -> bool: - return ( - not self.closed - and self.current_session is not None - and not self.current_session.closed - ) + return not self.closed and self.current_session is not None and not self.current_session.closed async def session_id(self) -> str: return self.build_session_id(self.current_session) @@ -199,9 +175,7 @@ async def session_id(self) -> str: async def connect(self): if self.wss_uri is None: self.wss_uri = await self.issue_new_wss_url() - old_session: Optional[WebSocketClientProtocol] = ( - None if self.current_session is None else self.current_session - ) + old_session: Optional[WebSocketClientProtocol] = None if self.current_session is None else self.current_session # NOTE: websockets does not support proxy settings self.current_session = await websockets.connect( uri=self.wss_uri, @@ -213,23 +187,17 @@ async def connect(self): if self.current_session_monitor is not None: self.current_session_monitor.cancel() - self.current_session_monitor = asyncio.ensure_future( - self.monitor_current_session() - ) + self.current_session_monitor = asyncio.ensure_future(self.monitor_current_session()) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new monitor_current_session() executor has been recreated for {session_id}" - ) + self.logger.debug(f"A new monitor_current_session() executor has been recreated for {session_id}") if self.message_receiver is not None: self.message_receiver.cancel() self.message_receiver = asyncio.ensure_future(self.receive_messages()) if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"A new receive_messages() executor has been recreated for {session_id}" - ) + self.logger.debug(f"A new receive_messages() executor has been recreated for {session_id}") if old_session is not None: await old_session.close() @@ -261,9 +229,7 @@ async def send_message(self, message: str): if await self.is_connected(): await self.current_session.send(message) else: - self.logger.warning( - f"The current session ({session_id}) is no longer active. Failed to send a message" - ) + self.logger.warning(f"The current session ({session_id}) is no longer active. Failed to send a message") raise e finally: if self.connect_operation_lock.locked() is True: diff --git a/slack_sdk/web/async_base_client.py b/slack_sdk/web/async_base_client.py index 39fae5f00..935487c5a 100644 --- a/slack_sdk/web/async_base_client.py +++ b/slack_sdk/web/async_base_client.py @@ -73,16 +73,12 @@ def __init__( `http_proxy` environment variables.""" self.headers = headers or {} """`dict` representing additional request headers to attach to all requests.""" - self.headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.default_params = {} if team_id is not None: self.default_params["team_id"] = team_id self._logger = logger if logger is not None else logging.getLogger(__name__) - self.retry_handlers = ( - retry_handlers if retry_handlers is not None else async_default_handlers() - ) + self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers() if self.proxy is None or len(self.proxy.strip()) == 0: env_variable = load_http_proxy_from_env(self._logger) @@ -168,9 +164,7 @@ async def api_call( # skipcq: PYL-R1710 req_args=req_args, ) - async def _send( - self, http_verb: str, api_url: str, req_args: dict - ) -> AsyncSlackResponse: + async def _send(self, http_verb: str, api_url: str, req_args: dict) -> AsyncSlackResponse: """Sends the request out for transmission. Args: @@ -193,9 +187,7 @@ async def _send( # 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 - ) + res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args) finally: for f in open_files: f.close() diff --git a/slack_sdk/web/async_client.py b/slack_sdk/web/async_client.py index 86bc51244..8eea40860 100644 --- a/slack_sdk/web/async_client.py +++ b/slack_sdk/web/async_client.py @@ -52,11 +52,6 @@ class AsyncWebClient(AsyncBaseClient): is not specified, if any of the following environment variables are present, they will be loaded into this parameter: `HTTPS_PROXY`, `https_proxy`, `HTTP_PROXY` or `http_proxy`. - session (ClientSession): [`aiohttp.ClientSession`][2] to attach to all outgoing requests. - trust_env_in_session (bool): Boolean setting whether aiohttp outgoing requests - are allowed to read environment variables. Commonly used in conjunction - with proxy support via the `HTTPS_PROXY`, `https_proxy`, `HTTP_PROXY` and - `http_proxy` environment variables. headers (dict): Additional request headers to attach to all requests. Methods: @@ -95,7 +90,6 @@ class AsyncWebClient(AsyncBaseClient): removed at anytime. [1]: https://docs.python.org/3/library/ssl.html#ssl.SSLContext - [2]: https://docs.aiohttp.org/en/stable/client_reference.html#client-session """ async def admin_analytics_getFile( @@ -136,9 +130,7 @@ async def admin_apps_approve( elif request_id: kwargs.update({"request_id": request_id}) else: - raise e.SlackRequestError( - "The app_id or request_id argument must be specified." - ) + raise e.SlackRequestError("The app_id or request_id argument must be specified.") kwargs.update( { @@ -168,9 +160,7 @@ async def admin_apps_approved_list( "team_id": team_id, } ) - return await self.api_call( - "admin.apps.approved.list", http_verb="GET", params=kwargs - ) + return await self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs) async def admin_apps_clearResolution( self, @@ -190,9 +180,7 @@ async def admin_apps_clearResolution( "team_id": team_id, } ) - return await self.api_call( - "admin.apps.clearResolution", http_verb="POST", params=kwargs - ) + return await self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs) async def admin_apps_requests_cancel( self, @@ -212,9 +200,7 @@ async def admin_apps_requests_cancel( "team_id": team_id, } ) - return await self.api_call( - "admin.apps.requests.cancel", http_verb="POST", params=kwargs - ) + return await self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs) async def admin_apps_requests_list( self, @@ -234,9 +220,7 @@ async def admin_apps_requests_list( "team_id": team_id, } ) - return await self.api_call( - "admin.apps.requests.list", http_verb="GET", params=kwargs - ) + return await self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs) async def admin_apps_restrict( self, @@ -258,9 +242,7 @@ async def admin_apps_restrict( elif request_id: kwargs.update({"request_id": request_id}) else: - raise e.SlackRequestError( - "The app_id or request_id argument must be specified." - ) + raise e.SlackRequestError("The app_id or request_id argument must be specified.") kwargs.update( { @@ -290,9 +272,7 @@ async def admin_apps_restricted_list( "team_id": team_id, } ) - return await self.api_call( - "admin.apps.restricted.list", http_verb="GET", params=kwargs - ) + return await self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs) async def admin_apps_uninstall( self, @@ -314,9 +294,7 @@ async def admin_apps_uninstall( kwargs.update({"team_ids": ",".join(team_ids)}) else: kwargs.update({"team_ids": team_ids}) - return await self.api_call( - "admin.apps.uninstall", http_verb="POST", params=kwargs - ) + return await self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs) async def admin_auth_policy_getEntities( self, @@ -337,9 +315,7 @@ async def admin_auth_policy_getEntities( kwargs.update({"entity_type": entity_type}) if limit is not None: kwargs.update({"limit": limit}) - return await self.api_call( - "admin.auth.policy.getEntities", http_verb="POST", params=kwargs - ) + return await self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs) async def admin_auth_policy_assignEntities( self, @@ -358,9 +334,7 @@ async def admin_auth_policy_assignEntities( kwargs.update({"entity_ids": entity_ids}) kwargs.update({"policy_name": policy_name}) kwargs.update({"entity_type": entity_type}) - return await self.api_call( - "admin.auth.policy.assignEntities", http_verb="POST", params=kwargs - ) + return await self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs) async def admin_auth_policy_removeEntities( self, @@ -379,9 +353,7 @@ async def admin_auth_policy_removeEntities( kwargs.update({"entity_ids": entity_ids}) kwargs.update({"policy_name": policy_name}) kwargs.update({"entity_type": entity_type}) - return await self.api_call( - "admin.auth.policy.removeEntities", http_verb="POST", params=kwargs - ) + return await self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs) async def admin_barriers_create( self, @@ -396,20 +368,14 @@ async def admin_barriers_create( """ kwargs.update({"primary_usergroup_id": primary_usergroup_id}) if isinstance(barriered_from_usergroup_ids, (list, Tuple)): - kwargs.update( - {"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)} - ) + kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)}) else: - kwargs.update( - {"barriered_from_usergroup_ids": barriered_from_usergroup_ids} - ) + kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids}) if isinstance(restricted_subjects, (list, Tuple)): kwargs.update({"restricted_subjects": ",".join(restricted_subjects)}) else: kwargs.update({"restricted_subjects": restricted_subjects}) - return await self.api_call( - "admin.barriers.create", http_verb="POST", params=kwargs - ) + return await self.api_call("admin.barriers.create", http_verb="POST", params=kwargs) async def admin_barriers_delete( self, @@ -421,9 +387,7 @@ async def admin_barriers_delete( https://api.slack.com/methods/admin.barriers.delete """ kwargs.update({"barrier_id": barrier_id}) - return await self.api_call( - "admin.barriers.delete", http_verb="POST", params=kwargs - ) + return await self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs) async def admin_barriers_update( self, @@ -437,24 +401,16 @@ async def admin_barriers_update( """Update an existing Information Barrier https://api.slack.com/methods/admin.barriers.update """ - kwargs.update( - {"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id} - ) + kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id}) if isinstance(barriered_from_usergroup_ids, (list, Tuple)): - kwargs.update( - {"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)} - ) + kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)}) else: - kwargs.update( - {"barriered_from_usergroup_ids": barriered_from_usergroup_ids} - ) + kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids}) if isinstance(restricted_subjects, (list, Tuple)): kwargs.update({"restricted_subjects": ",".join(restricted_subjects)}) else: kwargs.update({"restricted_subjects": restricted_subjects}) - return await self.api_call( - "admin.barriers.update", http_verb="POST", params=kwargs - ) + return await self.api_call("admin.barriers.update", http_verb="POST", params=kwargs) async def admin_barriers_list( self, @@ -471,9 +427,7 @@ async def admin_barriers_list( "limit": limit, } ) - return await self.api_call( - "admin.barriers.list", http_verb="GET", params=kwargs - ) + return await self.api_call("admin.barriers.list", http_verb="GET", params=kwargs) async def admin_conversations_create( self, @@ -613,9 +567,7 @@ async def admin_conversations_convertToPrivate( https://api.slack.com/methods/admin.conversations.convertToPrivate """ kwargs.update({"channel_id": channel_id}) - return await self.api_call( - "admin.conversations.convertToPrivate", params=kwargs - ) + return await self.api_call("admin.conversations.convertToPrivate", params=kwargs) async def admin_conversations_setConversationPrefs( self, @@ -632,9 +584,7 @@ async def admin_conversations_setConversationPrefs( kwargs.update({"prefs": json.dumps(prefs)}) else: kwargs.update({"prefs": prefs}) - return await self.api_call( - "admin.conversations.setConversationPrefs", params=kwargs - ) + return await self.api_call("admin.conversations.setConversationPrefs", params=kwargs) async def admin_conversations_getConversationPrefs( self, @@ -646,9 +596,7 @@ async def admin_conversations_getConversationPrefs( https://api.slack.com/methods/admin.conversations.getConversationPrefs """ kwargs.update({"channel_id": channel_id}) - return await self.api_call( - "admin.conversations.getConversationPrefs", params=kwargs - ) + return await self.api_call("admin.conversations.getConversationPrefs", params=kwargs) async def admin_conversations_disconnectShared( self, @@ -665,9 +613,7 @@ async def admin_conversations_disconnectShared( kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)}) else: kwargs.update({"leaving_team_ids": leaving_team_ids}) - return await self.api_call( - "admin.conversations.disconnectShared", params=kwargs - ) + return await self.api_call("admin.conversations.disconnectShared", params=kwargs) async def admin_conversations_ekm_listOriginalConnectedChannelInfo( self, @@ -697,9 +643,7 @@ async def admin_conversations_ekm_listOriginalConnectedChannelInfo( kwargs.update({"team_ids": ",".join(team_ids)}) else: kwargs.update({"team_ids": team_ids}) - return await self.api_call( - "admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs - ) + return await self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs) async def admin_conversations_restrictAccess_addGroup( self, @@ -826,9 +770,7 @@ async def admin_conversations_getCustomRetention( https://api.slack.com/methods/admin.conversations.getCustomRetention """ kwargs.update({"channel_id": channel_id}) - return await self.api_call( - "admin.conversations.getCustomRetention", params=kwargs - ) + return await self.api_call("admin.conversations.getCustomRetention", params=kwargs) async def admin_conversations_removeCustomRetention( self, @@ -840,9 +782,7 @@ async def admin_conversations_removeCustomRetention( https://api.slack.com/methods/admin.conversations.removeCustomRetention """ kwargs.update({"channel_id": channel_id}) - return await self.api_call( - "admin.conversations.removeCustomRetention", params=kwargs - ) + return await self.api_call("admin.conversations.removeCustomRetention", params=kwargs) async def admin_conversations_setCustomRetention( self, @@ -855,9 +795,7 @@ async def admin_conversations_setCustomRetention( https://api.slack.com/methods/admin.conversations.setCustomRetention """ kwargs.update({"channel_id": channel_id, "duration_days": duration_days}) - return await self.api_call( - "admin.conversations.setCustomRetention", params=kwargs - ) + return await self.api_call("admin.conversations.setCustomRetention", params=kwargs) async def admin_emoji_add( self, @@ -883,9 +821,7 @@ async def admin_emoji_addAlias( https://api.slack.com/methods/admin.emoji.addAlias """ kwargs.update({"alias_for": alias_for, "name": name}) - return await self.api_call( - "admin.emoji.addAlias", http_verb="GET", params=kwargs - ) + return await self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs) async def admin_emoji_list( self, @@ -1018,9 +954,7 @@ async def admin_teams_settings_setDefaultChannels( kwargs.update({"channel_ids": ",".join(channel_ids)}) else: kwargs.update({"channel_ids": channel_ids}) - return await self.api_call( - "admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs - ) + return await self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs) async def admin_users_session_getSettings( self, @@ -1095,9 +1029,7 @@ async def admin_users_unsupportedVersions_export( "date_sessions_started": date_sessions_started, } ) - return await self.api_call( - "admin.users.unsupportedVersions.export", params=kwargs - ) + return await self.api_call("admin.users.unsupportedVersions.export", params=kwargs) async def admin_inviteRequests_approve( self, @@ -1190,9 +1122,7 @@ async def admin_teams_admins_list( "team_id": team_id, } ) - return await self.api_call( - "admin.teams.admins.list", http_verb="GET", params=kwargs - ) + return await self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs) async def admin_teams_create( self, @@ -1241,9 +1171,7 @@ async def admin_teams_owners_list( https://api.slack.com/methods/admin.teams.owners.list """ kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit}) - return await self.api_call( - "admin.teams.owners.list", http_verb="GET", params=kwargs - ) + return await self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs) async def admin_teams_settings_info( self, @@ -1281,9 +1209,7 @@ async def admin_teams_settings_setDiscoverability( https://api.slack.com/methods/admin.teams.settings.setDiscoverability """ kwargs.update({"team_id": team_id, "discoverability": discoverability}) - return await self.api_call( - "admin.teams.settings.setDiscoverability", params=kwargs - ) + return await self.api_call("admin.teams.settings.setDiscoverability", params=kwargs) async def admin_teams_settings_setIcon( self, @@ -1296,9 +1222,7 @@ async def admin_teams_settings_setIcon( https://api.slack.com/methods/admin.teams.settings.setIcon """ kwargs.update({"team_id": team_id, "image_url": image_url}) - return await self.api_call( - "admin.teams.settings.setIcon", http_verb="GET", params=kwargs - ) + return await self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs) async def admin_teams_settings_setName( self, @@ -1437,9 +1361,7 @@ async def admin_users_invite( "email": email, "custom_message": custom_message, "email_password_policy_enabled": email_password_policy_enabled, - "guest_expiration_ts": str(guest_expiration_ts) - if guest_expiration_ts is not None - else None, + "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None, "is_restricted": is_restricted, "is_ultra_restricted": is_ultra_restricted, "real_name": real_name, @@ -1509,9 +1431,7 @@ async def admin_users_setExpiration( """Set an expiration for a guest user. https://api.slack.com/methods/admin.users.setExpiration """ - kwargs.update( - {"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id} - ) + kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id}) return await self.api_call("admin.users.setExpiration", params=kwargs) async def admin_users_setOwner( @@ -1563,9 +1483,7 @@ async def apps_connections_open( https://api.slack.com/methods/apps.connections.open """ kwargs.update({"token": app_token}) - return await self.api_call( - "apps.connections.open", http_verb="POST", params=kwargs - ) + return await self.api_call("apps.connections.open", http_verb="POST", params=kwargs) async def apps_event_authorizations_list( self, @@ -1579,9 +1497,7 @@ async def apps_event_authorizations_list( Each authorization represents an app installation that the event is visible to. https://api.slack.com/methods/apps.event.authorizations.list """ - kwargs.update( - {"event_context": event_context, "cursor": cursor, "limit": limit} - ) + kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit}) return await self.api_call("apps.event.authorizations.list", params=kwargs) async def apps_uninstall( @@ -1791,9 +1707,7 @@ async def calls_participants_add( """ kwargs.update({"id": id}) _update_call_participants(kwargs, users) - return await self.api_call( - "calls.participants.add", http_verb="POST", params=kwargs - ) + return await self.api_call("calls.participants.add", http_verb="POST", params=kwargs) async def calls_participants_remove( self, @@ -1807,9 +1721,7 @@ async def calls_participants_remove( """ kwargs.update({"id": id}) _update_call_participants(kwargs, users) - return await self.api_call( - "calls.participants.remove", http_verb="POST", params=kwargs - ) + return await self.api_call("calls.participants.remove", http_verb="POST", params=kwargs) async def calls_update( self, @@ -2320,9 +2232,7 @@ async def conversations_acceptSharedInvite( https://api.slack.com/methods/conversations.acceptSharedInvite """ if channel_id is None and invite_id is None: - raise e.SlackRequestError( - "Either channel_id or invite_id must be provided." - ) + raise e.SlackRequestError("Either channel_id or invite_id must be provided.") kwargs.update( { "channel_name": channel_name, @@ -2333,9 +2243,7 @@ async def conversations_acceptSharedInvite( "team_id": team_id, } ) - return await self.api_call( - "conversations.acceptSharedInvite", http_verb="POST", params=kwargs - ) + return await self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs) async def conversations_approveSharedInvite( self, @@ -2348,9 +2256,7 @@ async def conversations_approveSharedInvite( https://api.slack.com/methods/conversations.approveSharedInvite """ kwargs.update({"invite_id": invite_id, "target_team": target_team}) - return await self.api_call( - "conversations.approveSharedInvite", http_verb="POST", params=kwargs - ) + return await self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs) async def conversations_archive( self, @@ -2401,9 +2307,7 @@ async def conversations_declineSharedInvite( https://api.slack.com/methods/conversations.declineSharedInvite """ kwargs.update({"invite_id": invite_id, "target_team": target_team}) - return await self.api_call( - "conversations.declineSharedInvite", http_verb="GET", params=kwargs - ) + return await self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs) async def conversations_history( self, @@ -2431,9 +2335,7 @@ async def conversations_history( "oldest": oldest, } ) - return await self.api_call( - "conversations.history", http_verb="GET", params=kwargs - ) + return await self.api_call("conversations.history", http_verb="GET", params=kwargs) async def conversations_info( self, @@ -2494,9 +2396,7 @@ async def conversations_inviteShared( kwargs.update({"user_ids": ",".join(user_ids)}) else: kwargs.update({"user_ids": user_ids}) - return await self.api_call( - "conversations.inviteShared", http_verb="GET", params=kwargs - ) + return await self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs) async def conversations_join( self, @@ -2602,9 +2502,7 @@ async def conversations_members( https://api.slack.com/methods/conversations.members """ kwargs.update({"channel": channel, "cursor": cursor, "limit": limit}) - return await self.api_call( - "conversations.members", http_verb="GET", params=kwargs - ) + return await self.api_call("conversations.members", http_verb="GET", params=kwargs) async def conversations_open( self, @@ -2665,9 +2563,7 @@ async def conversations_replies( "oldest": oldest, } ) - return await self.api_call( - "conversations.replies", http_verb="GET", params=kwargs - ) + return await self.api_call("conversations.replies", http_verb="GET", params=kwargs) async def conversations_setPurpose( self, @@ -3000,9 +2896,7 @@ async def files_remote_remove( https://api.slack.com/methods/files.remote.remove """ kwargs.update({"external_id": external_id, "file": file}) - return await self.api_call( - "files.remote.remove", http_verb="POST", params=kwargs - ) + return await self.api_call("files.remote.remove", http_verb="POST", params=kwargs) async def files_remote_share( self, @@ -3067,9 +2961,7 @@ async def files_upload( if file is None and content is None: raise e.SlackRequestError("The file or content argument must be specified.") if file is not None and content is not None: - raise e.SlackRequestError( - "You cannot specify both the file and the content argument." - ) + raise e.SlackRequestError("You cannot specify both the file and the content argument.") if isinstance(channels, (list, Tuple)): kwargs.update({"channels": ",".join(channels)}) @@ -3089,9 +2981,7 @@ async def files_upload( # use the local filename if filename is missing if kwargs.get("filename") is None: kwargs["filename"] = file.split(os.path.sep)[-1] - return await self.api_call( - "files.upload", files={"file": file}, data=kwargs - ) + return await self.api_call("files.upload", files={"file": file}, data=kwargs) else: kwargs["content"] = content return await self.api_call("files.upload", data=kwargs) @@ -3503,9 +3393,7 @@ async def oauth_v2_exchange( """Exchanges a legacy access token for a new expiring access token and refresh token https://api.slack.com/methods/oauth.v2.exchange """ - kwargs.update( - {"client_id": client_id, "client_secret": client_secret, "token": token} - ) + kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token}) return await self.api_call("oauth.v2.exchange", params=kwargs) async def openid_connect_token( @@ -3757,9 +3645,7 @@ async def rtm_connect( """Starts a Real Time Messaging session. https://api.slack.com/methods/rtm.connect """ - kwargs.update( - {"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub} - ) + kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub}) return await self.api_call("rtm.connect", http_verb="GET", params=kwargs) async def rtm_start( @@ -4027,9 +3913,7 @@ async def team_integrationLogs( "user": user, } ) - return await self.api_call( - "team.integrationLogs", http_verb="GET", params=kwargs - ) + return await self.api_call("team.integrationLogs", http_verb="GET", params=kwargs) async def team_profile_get( self, @@ -4092,9 +3976,7 @@ async def usergroups_disable( """Disable an existing User Group https://api.slack.com/methods/usergroups.disable """ - kwargs.update( - {"usergroup": usergroup, "include_count": include_count, "team_id": team_id} - ) + kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id}) return await self.api_call("usergroups.disable", params=kwargs) async def usergroups_enable( @@ -4108,9 +3990,7 @@ async def usergroups_enable( """Enable a User Group https://api.slack.com/methods/usergroups.enable """ - kwargs.update( - {"usergroup": usergroup, "include_count": include_count, "team_id": team_id} - ) + kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id}) return await self.api_call("usergroups.enable", params=kwargs) async def usergroups_list( @@ -4184,9 +4064,7 @@ async def usergroups_users_list( "team_id": team_id, } ) - return await self.api_call( - "usergroups.users.list", http_verb="GET", params=kwargs - ) + return await self.api_call("usergroups.users.list", http_verb="GET", params=kwargs) async def usergroups_users_update( self, @@ -4240,9 +4118,7 @@ async def users_conversations( kwargs.update({"types": ",".join(types)}) else: kwargs.update({"types": types}) - return await self.api_call( - "users.conversations", http_verb="GET", params=kwargs - ) + return await self.api_call("users.conversations", http_verb="GET", params=kwargs) async def users_deletePhoto( self, @@ -4319,9 +4195,7 @@ async def users_lookupByEmail( https://api.slack.com/methods/users.lookupByEmail """ kwargs.update({"email": email}) - return await self.api_call( - "users.lookupByEmail", http_verb="GET", params=kwargs - ) + return await self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs) async def users_setPhoto( self, @@ -4336,9 +4210,7 @@ async def users_setPhoto( https://api.slack.com/methods/users.setPhoto """ kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y}) - return await self.api_call( - "users.setPhoto", files={"image": image}, data=kwargs - ) + return await self.api_call("users.setPhoto", files={"image": image}, data=kwargs) async def users_setPresence( self, diff --git a/slack_sdk/web/async_internal_utils.py b/slack_sdk/web/async_internal_utils.py index 72f30a4fd..19541e71d 100644 --- a/slack_sdk/web/async_internal_utils.py +++ b/slack_sdk/web/async_internal_utils.py @@ -91,14 +91,10 @@ async def _request_with_session( def convert_params(values: dict) -> dict: if not values or not isinstance(values, dict): return {} - return { - k: ("(bytes)" if isinstance(v, bytes) else v) - for k, v in values.items() - } + return {k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items()} headers = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in req_args.get("headers", {}).items() + k: "(redacted)" if k.lower() == "authorization" else v for k, v in req_args.get("headers", {}).items() } logger.debug( f"Sending a request - url: {http_verb} {api_url}, " @@ -130,9 +126,7 @@ def convert_params(values: dict) -> dict: body=data, ) except aiohttp.ContentTypeError: - logger.debug( - f"No response data returned from the following API call: {api_url}." - ) + logger.debug(f"No response data returned from the following API call: {api_url}.") except json.decoder.JSONDecodeError: try: body: str = await res.text() @@ -191,8 +185,7 @@ def convert_params(values: dict) -> dict: ): if logger.level <= logging.DEBUG: logger.info( - f"A retry handler found: {type(handler).__name__} " - f"for {http_verb} {api_url} - {e}" + f"A retry handler found: {type(handler).__name__} " f"for {http_verb} {api_url} - {e}" ) await handler.prepare_for_next_attempt_async( state=retry_state, diff --git a/slack_sdk/web/async_slack_response.py b/slack_sdk/web/async_slack_response.py index 511df99b7..868bf21c2 100644 --- a/slack_sdk/web/async_slack_response.py +++ b/slack_sdk/web/async_slack_response.py @@ -76,9 +76,7 @@ def __init__( def __str__(self): """Return the Response data if object is converted to a string.""" if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") return f"{self.data}" def __contains__(self, key: str) -> bool: @@ -96,13 +94,9 @@ def __getitem__(self, key): The value from data or None. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") if self.data is None: - raise ValueError( - "As the response.data is empty, this operation is unsupported" - ) + raise ValueError("As the response.data is empty, this operation is unsupported") return self.data.get(key, None) def __aiter__(self): @@ -116,9 +110,7 @@ def __aiter__(self): (AsyncSlackResponse) self """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") self._iteration = 0 self.data = self._initial_data return self @@ -143,9 +135,7 @@ async def __anext__(self): StopAsyncIteration: If 'next_cursor' is not present or empty. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") self._iteration += 1 if self._iteration == 1: return self @@ -181,9 +171,7 @@ def get(self, key, default=None): The value from data or the specified default. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") if self.data is None: return None return self.data.get(key, default) @@ -198,11 +186,7 @@ def validate(self): Raises: SlackApiError: The request to the Slack API failed. """ - if ( - self.status_code == 200 - and self.data - and (isinstance(self.data, bytes) or self.data.get("ok", False)) - ): + if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)): return self msg = f"The request to the Slack API failed. (url: {self.api_url})" raise e.SlackApiError(message=msg, response=self) diff --git a/slack_sdk/web/base_client.py b/slack_sdk/web/base_client.py index 564e1c057..0f53295ca 100644 --- a/slack_sdk/web/base_client.py +++ b/slack_sdk/web/base_client.py @@ -77,17 +77,13 @@ def __init__( `https_proxy`, `HTTP_PROXY` or `http_proxy`.""" self.headers = headers or {} """`dict` representing additional request headers to attach to all requests.""" - self.headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.default_params = {} if team_id is not None: self.default_params["team_id"] = team_id self._logger = logger if logger is not None else logging.getLogger(__name__) - self.retry_handlers = ( - retry_handlers if retry_handlers is not None else default_retry_handlers() - ) + self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers() if self.proxy is None or len(self.proxy.strip()) == 0: env_variable = load_http_proxy_from_env(self._logger) @@ -170,23 +166,17 @@ def _sync_send(self, api_url, req_args) -> SlackResponse: _json = req_args["json"] if "json" in req_args else None headers = req_args["headers"] if "headers" in req_args else None token = params.get("token") if params and "token" in params else None - auth = ( - req_args["auth"] if "auth" in req_args else None - ) # Basic Auth for oauth.v2.access / oauth.access + auth = req_args["auth"] if "auth" in req_args else None # Basic Auth for oauth.v2.access / oauth.access if auth is not None: headers = {} if isinstance(auth, str): headers["Authorization"] = auth elif isinstance(auth, dict): client_id, client_secret = auth["client_id"], auth["client_secret"] - value = b64encode( - f"{client_id}:{client_secret}".encode("utf-8") - ).decode("ascii") + value = b64encode(f"{client_id}:{client_secret}".encode("utf-8")).decode("ascii") headers["Authorization"] = f"Basic {value}" else: - self._logger.warning( - f"As the auth: {auth}: {type(auth)} is unsupported, skipped" - ) + self._logger.warning(f"As the auth: {auth}: {type(auth)} is unsupported, skipped") body_params = {} if params: @@ -204,9 +194,7 @@ def _sync_send(self, api_url, req_args) -> SlackResponse: additional_headers=headers, ) - def _request_for_pagination( - self, api_url: str, req_args: Dict[str, Dict[str, Any]] - ) -> Dict[str, Any]: + def _request_for_pagination(self, api_url: str, req_args: Dict[str, Dict[str, Any]]) -> Dict[str, Any]: """This method is supposed to be used only for SlackResponse pagination You can paginate using Python's for iterator as below: @@ -258,15 +246,9 @@ def _urllib_api_call( def convert_params(values: dict) -> dict: if not values or not isinstance(values, dict): return {} - return { - k: ("(bytes)" if isinstance(v, bytes) else v) - for k, v in values.items() - } - - headers = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in additional_headers.items() - } + return {k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items()} + + headers = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in additional_headers.items()} self._logger.debug( f"Sending a request - url: {url}, " f"query_params: {convert_params(query_params)}, " @@ -316,14 +298,10 @@ def convert_params(values: dict) -> dict: try: response_body_data = json.loads(response["body"]) except json.decoder.JSONDecodeError: - message = _build_unexpected_body_error_message( - response.get("body", "") - ) + message = _build_unexpected_body_error_message(response.get("body", "")) raise err.SlackApiError(message, response) - all_params: Dict[str, Any] = ( - copy.copy(body_params) if body_params is not None else {} - ) + all_params: Dict[str, Any] = copy.copy(body_params) if body_params is not None else {} if query_params: all_params.update(query_params) request_args["params"] = all_params # for backward-compatibility @@ -342,9 +320,7 @@ def convert_params(values: dict) -> dict: if not f.closed: f.close() - def _perform_urllib_http_request( - self, *, url: str, args: Dict[str, Dict[str, Any]] - ) -> Dict[str, Any]: + def _perform_urllib_http_request(self, *, url: str, args: Dict[str, Dict[str, Any]]) -> Dict[str, Any]: """Performs an HTTP request and parses the response. Args: @@ -374,16 +350,10 @@ def _perform_urllib_http_request( filename = "Uploaded file" name_attr = getattr(value, "name", None) if name_attr: - filename = ( - name_attr.decode("utf-8") - if isinstance(name_attr, bytes) - else name_attr - ) + filename = name_attr.decode("utf-8") if isinstance(name_attr, bytes) else name_attr if "filename" in data: filename = data["filename"] - mimetype = ( - mimetypes.guess_type(filename)[0] or "application/octet-stream" - ) + mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" title = ( f'\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\n' + f"Content-Type: {mimetype}\r\n" @@ -434,20 +404,10 @@ def _perform_urllib_http_request( resp = {"status": e.code, "headers": response_headers} if e.code == 429: # for compatibility with aiohttp - if ( - "retry-after" not in response_headers - and "Retry-After" in response_headers - ): - response_headers["retry-after"] = response_headers[ - "Retry-After" - ] - if ( - "Retry-After" not in response_headers - and "retry-after" in response_headers - ): - response_headers["Retry-After"] = response_headers[ - "retry-after" - ] + if "retry-after" not in response_headers and "Retry-After" in response_headers: + response_headers["retry-after"] = response_headers["Retry-After"] + if "Retry-After" not in response_headers and "retry-after" in response_headers: + response_headers["Retry-After"] = response_headers["retry-after"] # read the response body here charset = e.headers.get_content_charset() or "utf-8" @@ -459,9 +419,7 @@ def _perform_urllib_http_request( retry_response = RetryHttpResponse( status_code=e.code, headers={k: [v] for k, v in response_headers.items()}, - data=response_body.encode("utf-8") - if response_body is not None - else None, + data=response_body.encode("utf-8") if response_body is not None else None, ) for handler in self.retry_handlers: if handler.can_retry( @@ -487,9 +445,7 @@ def _perform_urllib_http_request( except Exception as err: last_error = err - self._logger.error( - f"Failed to send a request to Slack API server: {err}" - ) + self._logger.error(f"Failed to send a request to Slack API server: {err}") # Try to find a retry handler for this error retry_request = RetryHttpRequest.from_urllib_http_request(req) @@ -510,9 +466,7 @@ def _perform_urllib_http_request( response=None, error=err, ) - self._logger.info( - f"Going to retry the same request: {req.method} {req.full_url}" - ) + self._logger.info(f"Going to retry the same request: {req.method} {req.full_url}") break if retry_state.next_attempt_requested is False: @@ -540,18 +494,14 @@ def _perform_urllib_http_request_internal( HTTPSHandler(context=self.ssl), ) else: - raise SlackRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") # NOTE: BAN-B310 is already checked above resp: Optional[HTTPResponse] = None if opener: resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: - resp = urlopen( # skipcq: BAN-B310 - req, context=self.ssl, timeout=self.timeout - ) + resp = urlopen(req, context=self.ssl, timeout=self.timeout) # skipcq: BAN-B310 if resp.headers.get_content_type() == "application/gzip": # admin.analytics.getFile body: bytes = resp.read() @@ -595,9 +545,7 @@ def _build_urllib_request_headers( # ================================================================= @staticmethod - def validate_slack_signature( - *, signing_secret: str, data: str, timestamp: str, signature: str - ) -> bool: + def validate_slack_signature(*, signing_secret: str, data: str, timestamp: str, signature: str) -> bool: """ Slack creates a unique string for your app and shares it with you. Verify requests from Slack with confidence by verifying signatures using your diff --git a/slack_sdk/web/client.py b/slack_sdk/web/client.py index a4ec80ea0..5da8feda7 100644 --- a/slack_sdk/web/client.py +++ b/slack_sdk/web/client.py @@ -121,9 +121,7 @@ def admin_apps_approve( elif request_id: kwargs.update({"request_id": request_id}) else: - raise e.SlackRequestError( - "The app_id or request_id argument must be specified." - ) + raise e.SlackRequestError("The app_id or request_id argument must be specified.") kwargs.update( { @@ -173,9 +171,7 @@ def admin_apps_clearResolution( "team_id": team_id, } ) - return self.api_call( - "admin.apps.clearResolution", http_verb="POST", params=kwargs - ) + return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs) def admin_apps_requests_cancel( self, @@ -195,9 +191,7 @@ def admin_apps_requests_cancel( "team_id": team_id, } ) - return self.api_call( - "admin.apps.requests.cancel", http_verb="POST", params=kwargs - ) + return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs) def admin_apps_requests_list( self, @@ -239,9 +233,7 @@ def admin_apps_restrict( elif request_id: kwargs.update({"request_id": request_id}) else: - raise e.SlackRequestError( - "The app_id or request_id argument must be specified." - ) + raise e.SlackRequestError("The app_id or request_id argument must be specified.") kwargs.update( { @@ -271,9 +263,7 @@ def admin_apps_restricted_list( "team_id": team_id, } ) - return self.api_call( - "admin.apps.restricted.list", http_verb="GET", params=kwargs - ) + return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs) def admin_apps_uninstall( self, @@ -316,9 +306,7 @@ def admin_auth_policy_getEntities( kwargs.update({"entity_type": entity_type}) if limit is not None: kwargs.update({"limit": limit}) - return self.api_call( - "admin.auth.policy.getEntities", http_verb="POST", params=kwargs - ) + return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs) def admin_auth_policy_assignEntities( self, @@ -337,9 +325,7 @@ def admin_auth_policy_assignEntities( kwargs.update({"entity_ids": entity_ids}) kwargs.update({"policy_name": policy_name}) kwargs.update({"entity_type": entity_type}) - return self.api_call( - "admin.auth.policy.assignEntities", http_verb="POST", params=kwargs - ) + return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs) def admin_auth_policy_removeEntities( self, @@ -358,9 +344,7 @@ def admin_auth_policy_removeEntities( kwargs.update({"entity_ids": entity_ids}) kwargs.update({"policy_name": policy_name}) kwargs.update({"entity_type": entity_type}) - return self.api_call( - "admin.auth.policy.removeEntities", http_verb="POST", params=kwargs - ) + return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs) def admin_barriers_create( self, @@ -375,13 +359,9 @@ def admin_barriers_create( """ kwargs.update({"primary_usergroup_id": primary_usergroup_id}) if isinstance(barriered_from_usergroup_ids, (list, Tuple)): - kwargs.update( - {"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)} - ) + kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)}) else: - kwargs.update( - {"barriered_from_usergroup_ids": barriered_from_usergroup_ids} - ) + kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids}) if isinstance(restricted_subjects, (list, Tuple)): kwargs.update({"restricted_subjects": ",".join(restricted_subjects)}) else: @@ -412,17 +392,11 @@ def admin_barriers_update( """Update an existing Information Barrier https://api.slack.com/methods/admin.barriers.update """ - kwargs.update( - {"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id} - ) + kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id}) if isinstance(barriered_from_usergroup_ids, (list, Tuple)): - kwargs.update( - {"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)} - ) + kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)}) else: - kwargs.update( - {"barriered_from_usergroup_ids": barriered_from_usergroup_ids} - ) + kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids}) if isinstance(restricted_subjects, (list, Tuple)): kwargs.update({"restricted_subjects": ",".join(restricted_subjects)}) else: @@ -660,9 +634,7 @@ def admin_conversations_ekm_listOriginalConnectedChannelInfo( kwargs.update({"team_ids": ",".join(team_ids)}) else: kwargs.update({"team_ids": team_ids}) - return self.api_call( - "admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs - ) + return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs) def admin_conversations_restrictAccess_addGroup( self, @@ -973,9 +945,7 @@ def admin_teams_settings_setDefaultChannels( kwargs.update({"channel_ids": ",".join(channel_ids)}) else: kwargs.update({"channel_ids": channel_ids}) - return self.api_call( - "admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs - ) + return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs) def admin_users_session_getSettings( self, @@ -1243,9 +1213,7 @@ def admin_teams_settings_setIcon( https://api.slack.com/methods/admin.teams.settings.setIcon """ kwargs.update({"team_id": team_id, "image_url": image_url}) - return self.api_call( - "admin.teams.settings.setIcon", http_verb="GET", params=kwargs - ) + return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs) def admin_teams_settings_setName( self, @@ -1384,9 +1352,7 @@ def admin_users_invite( "email": email, "custom_message": custom_message, "email_password_policy_enabled": email_password_policy_enabled, - "guest_expiration_ts": str(guest_expiration_ts) - if guest_expiration_ts is not None - else None, + "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None, "is_restricted": is_restricted, "is_ultra_restricted": is_ultra_restricted, "real_name": real_name, @@ -1456,9 +1422,7 @@ def admin_users_setExpiration( """Set an expiration for a guest user. https://api.slack.com/methods/admin.users.setExpiration """ - kwargs.update( - {"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id} - ) + kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id}) return self.api_call("admin.users.setExpiration", params=kwargs) def admin_users_setOwner( @@ -1524,9 +1488,7 @@ def apps_event_authorizations_list( Each authorization represents an app installation that the event is visible to. https://api.slack.com/methods/apps.event.authorizations.list """ - kwargs.update( - {"event_context": event_context, "cursor": cursor, "limit": limit} - ) + kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit}) return self.api_call("apps.event.authorizations.list", params=kwargs) def apps_uninstall( @@ -1750,9 +1712,7 @@ def calls_participants_remove( """ kwargs.update({"id": id}) _update_call_participants(kwargs, users) - return self.api_call( - "calls.participants.remove", http_verb="POST", params=kwargs - ) + return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs) def calls_update( self, @@ -2263,9 +2223,7 @@ def conversations_acceptSharedInvite( https://api.slack.com/methods/conversations.acceptSharedInvite """ if channel_id is None and invite_id is None: - raise e.SlackRequestError( - "Either channel_id or invite_id must be provided." - ) + raise e.SlackRequestError("Either channel_id or invite_id must be provided.") kwargs.update( { "channel_name": channel_name, @@ -2276,9 +2234,7 @@ def conversations_acceptSharedInvite( "team_id": team_id, } ) - return self.api_call( - "conversations.acceptSharedInvite", http_verb="POST", params=kwargs - ) + return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs) def conversations_approveSharedInvite( self, @@ -2291,9 +2247,7 @@ def conversations_approveSharedInvite( https://api.slack.com/methods/conversations.approveSharedInvite """ kwargs.update({"invite_id": invite_id, "target_team": target_team}) - return self.api_call( - "conversations.approveSharedInvite", http_verb="POST", params=kwargs - ) + return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs) def conversations_archive( self, @@ -2344,9 +2298,7 @@ def conversations_declineSharedInvite( https://api.slack.com/methods/conversations.declineSharedInvite """ kwargs.update({"invite_id": invite_id, "target_team": target_team}) - return self.api_call( - "conversations.declineSharedInvite", http_verb="GET", params=kwargs - ) + return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs) def conversations_history( self, @@ -2435,9 +2387,7 @@ def conversations_inviteShared( kwargs.update({"user_ids": ",".join(user_ids)}) else: kwargs.update({"user_ids": user_ids}) - return self.api_call( - "conversations.inviteShared", http_verb="GET", params=kwargs - ) + return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs) def conversations_join( self, @@ -3002,9 +2952,7 @@ def files_upload( if file is None and content is None: raise e.SlackRequestError("The file or content argument must be specified.") if file is not None and content is not None: - raise e.SlackRequestError( - "You cannot specify both the file and the content argument." - ) + raise e.SlackRequestError("You cannot specify both the file and the content argument.") if isinstance(channels, (list, Tuple)): kwargs.update({"channels": ",".join(channels)}) @@ -3436,9 +3384,7 @@ def oauth_v2_exchange( """Exchanges a legacy access token for a new expiring access token and refresh token https://api.slack.com/methods/oauth.v2.exchange """ - kwargs.update( - {"client_id": client_id, "client_secret": client_secret, "token": token} - ) + kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token}) return self.api_call("oauth.v2.exchange", params=kwargs) def openid_connect_token( @@ -3690,9 +3636,7 @@ def rtm_connect( """Starts a Real Time Messaging session. https://api.slack.com/methods/rtm.connect """ - kwargs.update( - {"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub} - ) + kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub}) return self.api_call("rtm.connect", http_verb="GET", params=kwargs) def rtm_start( @@ -4023,9 +3967,7 @@ def usergroups_disable( """Disable an existing User Group https://api.slack.com/methods/usergroups.disable """ - kwargs.update( - {"usergroup": usergroup, "include_count": include_count, "team_id": team_id} - ) + kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id}) return self.api_call("usergroups.disable", params=kwargs) def usergroups_enable( @@ -4039,9 +3981,7 @@ def usergroups_enable( """Enable a User Group https://api.slack.com/methods/usergroups.enable """ - kwargs.update( - {"usergroup": usergroup, "include_count": include_count, "team_id": team_id} - ) + kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id}) return self.api_call("usergroups.enable", params=kwargs) def usergroups_list( diff --git a/slack_sdk/web/deprecation.py b/slack_sdk/web/deprecation.py index 7781e0bfc..5ce5f067e 100644 --- a/slack_sdk/web/deprecation.py +++ b/slack_sdk/web/deprecation.py @@ -14,19 +14,13 @@ def show_2020_01_deprecation(method_name: str): """Prints a warning if the given method is deprecated""" - skip_deprecation = os.environ.get( - "SLACKCLIENT_SKIP_DEPRECATION" - ) # for unit tests etc. + skip_deprecation = os.environ.get("SLACKCLIENT_SKIP_DEPRECATION") # for unit tests etc. if skip_deprecation: return if not method_name: return - matched_prefixes = [ - prefix - for prefix in deprecated_method_prefixes_2020_01 - if method_name.startswith(prefix) - ] + matched_prefixes = [prefix for prefix in deprecated_method_prefixes_2020_01 if method_name.startswith(prefix)] if len(matched_prefixes) > 0: message = ( f"{method_name} is deprecated. Please use the Conversations API instead. " diff --git a/slack_sdk/web/internal_utils.py b/slack_sdk/web/internal_utils.py index 7e45f685e..f1a7ad9e8 100644 --- a/slack_sdk/web/internal_utils.py +++ b/slack_sdk/web/internal_utils.py @@ -14,9 +14,7 @@ from slack_sdk.models.metadata import Metadata -def convert_bool_to_0_or_1( - params: Optional[Dict[str, Any]] -) -> Optional[Dict[str, Any]]: +def convert_bool_to_0_or_1(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: """Converts all bool values in dict to "0" or "1". Slack APIs safely accept "0"/"1" as boolean values. @@ -205,9 +203,7 @@ def to_dict(obj: Union[Dict, Block, Attachment, Metadata]): kwargs.update({"metadata": to_dict(metadata)}) -def _update_call_participants( - kwargs, users: Union[str, Sequence[Dict[str, str]]] -) -> None: +def _update_call_participants(kwargs, users: Union[str, Sequence[Dict[str, str]]]) -> None: if users is None: return @@ -241,9 +237,7 @@ def _to_0_or_1_if_bool(v: Any) -> Union[Any, str]: return v -def _warn_if_text_or_attachment_fallback_is_missing( - endpoint: str, kwargs: Dict[str, Any] -) -> None: +def _warn_if_text_or_attachment_fallback_is_missing(endpoint: str, kwargs: Dict[str, Any]) -> None: text = kwargs.get("text") if text and len(text.strip()) > 0: # If a top-level text arg is provided, we are good. This is the recommended accessibility field to always provide. @@ -273,11 +267,7 @@ def _warn_if_text_or_attachment_fallback_is_missing( attachments is not None and isinstance(attachments, list) and not all( - [ - isinstance(attachment, dict) - and len(attachment.get("fallback", "").strip()) > 0 - for attachment in attachments - ] + [isinstance(attachment, dict) and len(attachment.get("fallback", "").strip()) > 0 for attachment in attachments] ) ): # https://api.slack.com/reference/messaging/attachments @@ -293,9 +283,7 @@ def _warn_if_text_or_attachment_fallback_is_missing( def _build_unexpected_body_error_message(body: str) -> str: - body_for_logging = "".join( - [line.strip() for line in body.replace("\r", "\n").split("\n")] - ) + body_for_logging = "".join([line.strip() for line in body.replace("\r", "\n").split("\n")]) if len(body_for_logging) > 100: body_for_logging = body_for_logging[:100] + "..." message = f"Received a response in a non-JSON format: {body_for_logging}" diff --git a/slack_sdk/web/legacy_base_client.py b/slack_sdk/web/legacy_base_client.py index 7d37d7bd0..08b1ff5d9 100644 --- a/slack_sdk/web/legacy_base_client.py +++ b/slack_sdk/web/legacy_base_client.py @@ -82,9 +82,7 @@ def __init__( self.session = session self.headers = headers or {} """`dict` representing additional request headers to attach to all requests.""" - self.headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.default_params = {} if team_id is not None: self.default_params["team_id"] = team_id @@ -185,9 +183,7 @@ def api_call( # skipcq: PYL-R1710 # aiohttp based async WebClient # ================================================================= - async def _send( - self, http_verb: str, api_url: str, req_args: dict - ) -> SlackResponse: + async def _send(self, http_verb: str, api_url: str, req_args: dict) -> SlackResponse: """Sends the request out for transmission. Args: http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'. @@ -209,9 +205,7 @@ async def _send( # 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 - ) + res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args) finally: for f in open_files: f.close() @@ -250,9 +244,7 @@ def _sync_send(self, api_url, req_args) -> SlackResponse: _json = req_args["json"] if "json" in req_args else None headers = req_args["headers"] if "headers" in req_args else None token = params.get("token") if params and "token" in params else None - auth = ( - req_args["auth"] if "auth" in req_args else None - ) # Basic Auth for oauth.v2.access / oauth.access + auth = req_args["auth"] if "auth" in req_args else None # Basic Auth for oauth.v2.access / oauth.access if auth is not None: headers = {} if isinstance(auth, BasicAuth): @@ -260,9 +252,7 @@ def _sync_send(self, api_url, req_args) -> SlackResponse: elif isinstance(auth, str): headers["Authorization"] = auth else: - self._logger.warning( - f"As the auth: {auth}: {type(auth)} is unsupported, skipped" - ) + self._logger.warning(f"As the auth: {auth}: {type(auth)} is unsupported, skipped") body_params = {} if params: @@ -280,9 +270,7 @@ def _sync_send(self, api_url, req_args) -> SlackResponse: additional_headers=headers, ) - def _request_for_pagination( - self, api_url: str, req_args: Dict[str, Dict[str, Any]] - ) -> Dict[str, Any]: + def _request_for_pagination(self, api_url: str, req_args: Dict[str, Dict[str, Any]]) -> Dict[str, Any]: """This method is supposed to be used only for SlackResponse pagination You can paginate using Python's for iterator as below: for response in client.conversations_list(limit=100): @@ -331,15 +319,9 @@ def _urllib_api_call( def convert_params(values: dict) -> dict: if not values or not isinstance(values, dict): return {} - return { - k: ("(bytes)" if isinstance(v, bytes) else v) - for k, v in values.items() - } - - headers = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in additional_headers.items() - } + return {k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items()} + + headers = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in additional_headers.items()} self._logger.debug( f"Sending a request - url: {url}, " f"query_params: {convert_params(query_params)}, " @@ -389,14 +371,10 @@ def convert_params(values: dict) -> dict: try: response_body_data = json.loads(response["body"]) except json.decoder.JSONDecodeError: - message = _build_unexpected_body_error_message( - response.get("body", "") - ) + message = _build_unexpected_body_error_message(response.get("body", "")) raise err.SlackApiError(message, response) - all_params: Dict[str, Any] = ( - copy.copy(body_params) if body_params is not None else {} - ) + all_params: Dict[str, Any] = copy.copy(body_params) if body_params is not None else {} if query_params: all_params.update(query_params) request_args["params"] = all_params # for backward-compatibility @@ -416,9 +394,7 @@ def convert_params(values: dict) -> dict: if not f.closed: f.close() - def _perform_urllib_http_request( - self, *, url: str, args: Dict[str, Dict[str, Any]] - ) -> Dict[str, Any]: + def _perform_urllib_http_request(self, *, url: str, args: Dict[str, Dict[str, Any]]) -> Dict[str, Any]: """Performs an HTTP request and parses the response. Args: @@ -448,16 +424,10 @@ def _perform_urllib_http_request( filename = "Uploaded file" name_attr = getattr(value, "name", None) if name_attr: - filename = ( - name_attr.decode("utf-8") - if isinstance(name_attr, bytes) - else name_attr - ) + filename = name_attr.decode("utf-8") if isinstance(name_attr, bytes) else name_attr if "filename" in data: filename = data["filename"] - mimetype = ( - mimetypes.guess_type(filename)[0] or "application/octet-stream" - ) + mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" title = ( f'\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\n' + f"Content-Type: {mimetype}\r\n" @@ -501,18 +471,14 @@ def _perform_urllib_http_request( HTTPSHandler(context=self.ssl), ) else: - raise SlackRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") # NOTE: BAN-B310 is already checked above resp: Optional[HTTPResponse] = None if opener: resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: - resp = urlopen( # skipcq: BAN-B310 - req, context=self.ssl, timeout=self.timeout - ) + resp = urlopen(req, context=self.ssl, timeout=self.timeout) # skipcq: BAN-B310 if resp.headers.get_content_type() == "application/gzip": # admin.analytics.getFile body: bytes = resp.read() @@ -528,15 +494,9 @@ def _perform_urllib_http_request( resp = {"status": e.code, "headers": response_headers} if e.code == 429: # for compatibility with aiohttp - if ( - "retry-after" not in response_headers - and "Retry-After" in response_headers - ): + if "retry-after" not in response_headers and "Retry-After" in response_headers: response_headers["retry-after"] = response_headers["Retry-After"] - if ( - "Retry-After" not in response_headers - and "retry-after" in response_headers - ): + if "Retry-After" not in response_headers and "retry-after" in response_headers: response_headers["Retry-After"] = response_headers["retry-after"] # read the response body here @@ -568,9 +528,7 @@ def _build_urllib_request_headers( # ================================================================= @staticmethod - def validate_slack_signature( - *, signing_secret: str, data: str, timestamp: str, signature: str - ) -> bool: + def validate_slack_signature(*, signing_secret: str, data: str, timestamp: str, signature: str) -> bool: """ Slack creates a unique string for your app and shares it with you. Verify requests from Slack with confidence by verifying signatures using your diff --git a/slack_sdk/web/legacy_client.py b/slack_sdk/web/legacy_client.py index a96c17c8f..7a2430b6b 100644 --- a/slack_sdk/web/legacy_client.py +++ b/slack_sdk/web/legacy_client.py @@ -47,9 +47,8 @@ class LegacyWebClient(LegacyBaseClient): timeout (int): The maximum number of seconds the client will wait to connect and receive a response from Slack. Default is 30 seconds. - ssl (SSLContext): An [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext) - instance, helpful for specifying your own custom certificate - chain. + ssl (SSLContext): An [`ssl.SSLContext`][1] instance, helpful for specifying + your own custom certificate chain. proxy (str): String representing a fully-qualified URL to a proxy through which to route all requests to the Slack API. Even if this parameter is not specified, if any of the following environment variables are @@ -91,6 +90,8 @@ class LegacyWebClient(LegacyBaseClient): Any attributes or methods prefixed with _underscores are intended to be "private" internal use only. They may be changed or removed at anytime. + + [1]: https://docs.python.org/3/library/ssl.html#ssl.SSLContext """ def admin_analytics_getFile( @@ -131,9 +132,7 @@ def admin_apps_approve( elif request_id: kwargs.update({"request_id": request_id}) else: - raise e.SlackRequestError( - "The app_id or request_id argument must be specified." - ) + raise e.SlackRequestError("The app_id or request_id argument must be specified.") kwargs.update( { @@ -183,9 +182,7 @@ def admin_apps_clearResolution( "team_id": team_id, } ) - return self.api_call( - "admin.apps.clearResolution", http_verb="POST", params=kwargs - ) + return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs) def admin_apps_requests_cancel( self, @@ -205,9 +202,7 @@ def admin_apps_requests_cancel( "team_id": team_id, } ) - return self.api_call( - "admin.apps.requests.cancel", http_verb="POST", params=kwargs - ) + return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs) def admin_apps_requests_list( self, @@ -249,9 +244,7 @@ def admin_apps_restrict( elif request_id: kwargs.update({"request_id": request_id}) else: - raise e.SlackRequestError( - "The app_id or request_id argument must be specified." - ) + raise e.SlackRequestError("The app_id or request_id argument must be specified.") kwargs.update( { @@ -281,9 +274,7 @@ def admin_apps_restricted_list( "team_id": team_id, } ) - return self.api_call( - "admin.apps.restricted.list", http_verb="GET", params=kwargs - ) + return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs) def admin_apps_uninstall( self, @@ -326,9 +317,7 @@ def admin_auth_policy_getEntities( kwargs.update({"entity_type": entity_type}) if limit is not None: kwargs.update({"limit": limit}) - return self.api_call( - "admin.auth.policy.getEntities", http_verb="POST", params=kwargs - ) + return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs) def admin_auth_policy_assignEntities( self, @@ -347,9 +336,7 @@ def admin_auth_policy_assignEntities( kwargs.update({"entity_ids": entity_ids}) kwargs.update({"policy_name": policy_name}) kwargs.update({"entity_type": entity_type}) - return self.api_call( - "admin.auth.policy.assignEntities", http_verb="POST", params=kwargs - ) + return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs) def admin_auth_policy_removeEntities( self, @@ -368,9 +355,7 @@ def admin_auth_policy_removeEntities( kwargs.update({"entity_ids": entity_ids}) kwargs.update({"policy_name": policy_name}) kwargs.update({"entity_type": entity_type}) - return self.api_call( - "admin.auth.policy.removeEntities", http_verb="POST", params=kwargs - ) + return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs) def admin_barriers_create( self, @@ -385,13 +370,9 @@ def admin_barriers_create( """ kwargs.update({"primary_usergroup_id": primary_usergroup_id}) if isinstance(barriered_from_usergroup_ids, (list, Tuple)): - kwargs.update( - {"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)} - ) + kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)}) else: - kwargs.update( - {"barriered_from_usergroup_ids": barriered_from_usergroup_ids} - ) + kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids}) if isinstance(restricted_subjects, (list, Tuple)): kwargs.update({"restricted_subjects": ",".join(restricted_subjects)}) else: @@ -422,17 +403,11 @@ def admin_barriers_update( """Update an existing Information Barrier https://api.slack.com/methods/admin.barriers.update """ - kwargs.update( - {"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id} - ) + kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id}) if isinstance(barriered_from_usergroup_ids, (list, Tuple)): - kwargs.update( - {"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)} - ) + kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)}) else: - kwargs.update( - {"barriered_from_usergroup_ids": barriered_from_usergroup_ids} - ) + kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids}) if isinstance(restricted_subjects, (list, Tuple)): kwargs.update({"restricted_subjects": ",".join(restricted_subjects)}) else: @@ -670,9 +645,7 @@ def admin_conversations_ekm_listOriginalConnectedChannelInfo( kwargs.update({"team_ids": ",".join(team_ids)}) else: kwargs.update({"team_ids": team_ids}) - return self.api_call( - "admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs - ) + return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs) def admin_conversations_restrictAccess_addGroup( self, @@ -983,9 +956,7 @@ def admin_teams_settings_setDefaultChannels( kwargs.update({"channel_ids": ",".join(channel_ids)}) else: kwargs.update({"channel_ids": channel_ids}) - return self.api_call( - "admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs - ) + return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs) def admin_users_session_getSettings( self, @@ -1253,9 +1224,7 @@ def admin_teams_settings_setIcon( https://api.slack.com/methods/admin.teams.settings.setIcon """ kwargs.update({"team_id": team_id, "image_url": image_url}) - return self.api_call( - "admin.teams.settings.setIcon", http_verb="GET", params=kwargs - ) + return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs) def admin_teams_settings_setName( self, @@ -1394,9 +1363,7 @@ def admin_users_invite( "email": email, "custom_message": custom_message, "email_password_policy_enabled": email_password_policy_enabled, - "guest_expiration_ts": str(guest_expiration_ts) - if guest_expiration_ts is not None - else None, + "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None, "is_restricted": is_restricted, "is_ultra_restricted": is_ultra_restricted, "real_name": real_name, @@ -1466,9 +1433,7 @@ def admin_users_setExpiration( """Set an expiration for a guest user. https://api.slack.com/methods/admin.users.setExpiration """ - kwargs.update( - {"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id} - ) + kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id}) return self.api_call("admin.users.setExpiration", params=kwargs) def admin_users_setOwner( @@ -1534,9 +1499,7 @@ def apps_event_authorizations_list( Each authorization represents an app installation that the event is visible to. https://api.slack.com/methods/apps.event.authorizations.list """ - kwargs.update( - {"event_context": event_context, "cursor": cursor, "limit": limit} - ) + kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit}) return self.api_call("apps.event.authorizations.list", params=kwargs) def apps_uninstall( @@ -1760,9 +1723,7 @@ def calls_participants_remove( """ kwargs.update({"id": id}) _update_call_participants(kwargs, users) - return self.api_call( - "calls.participants.remove", http_verb="POST", params=kwargs - ) + return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs) def calls_update( self, @@ -2273,9 +2234,7 @@ def conversations_acceptSharedInvite( https://api.slack.com/methods/conversations.acceptSharedInvite """ if channel_id is None and invite_id is None: - raise e.SlackRequestError( - "Either channel_id or invite_id must be provided." - ) + raise e.SlackRequestError("Either channel_id or invite_id must be provided.") kwargs.update( { "channel_name": channel_name, @@ -2286,9 +2245,7 @@ def conversations_acceptSharedInvite( "team_id": team_id, } ) - return self.api_call( - "conversations.acceptSharedInvite", http_verb="POST", params=kwargs - ) + return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs) def conversations_approveSharedInvite( self, @@ -2301,9 +2258,7 @@ def conversations_approveSharedInvite( https://api.slack.com/methods/conversations.approveSharedInvite """ kwargs.update({"invite_id": invite_id, "target_team": target_team}) - return self.api_call( - "conversations.approveSharedInvite", http_verb="POST", params=kwargs - ) + return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs) def conversations_archive( self, @@ -2354,9 +2309,7 @@ def conversations_declineSharedInvite( https://api.slack.com/methods/conversations.declineSharedInvite """ kwargs.update({"invite_id": invite_id, "target_team": target_team}) - return self.api_call( - "conversations.declineSharedInvite", http_verb="GET", params=kwargs - ) + return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs) def conversations_history( self, @@ -2445,9 +2398,7 @@ def conversations_inviteShared( kwargs.update({"user_ids": ",".join(user_ids)}) else: kwargs.update({"user_ids": user_ids}) - return self.api_call( - "conversations.inviteShared", http_verb="GET", params=kwargs - ) + return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs) def conversations_join( self, @@ -3012,9 +2963,7 @@ def files_upload( if file is None and content is None: raise e.SlackRequestError("The file or content argument must be specified.") if file is not None and content is not None: - raise e.SlackRequestError( - "You cannot specify both the file and the content argument." - ) + raise e.SlackRequestError("You cannot specify both the file and the content argument.") if isinstance(channels, (list, Tuple)): kwargs.update({"channels": ",".join(channels)}) @@ -3446,9 +3395,7 @@ def oauth_v2_exchange( """Exchanges a legacy access token for a new expiring access token and refresh token https://api.slack.com/methods/oauth.v2.exchange """ - kwargs.update( - {"client_id": client_id, "client_secret": client_secret, "token": token} - ) + kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token}) return self.api_call("oauth.v2.exchange", params=kwargs) def openid_connect_token( @@ -3700,9 +3647,7 @@ def rtm_connect( """Starts a Real Time Messaging session. https://api.slack.com/methods/rtm.connect """ - kwargs.update( - {"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub} - ) + kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub}) return self.api_call("rtm.connect", http_verb="GET", params=kwargs) def rtm_start( @@ -4033,9 +3978,7 @@ def usergroups_disable( """Disable an existing User Group https://api.slack.com/methods/usergroups.disable """ - kwargs.update( - {"usergroup": usergroup, "include_count": include_count, "team_id": team_id} - ) + kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id}) return self.api_call("usergroups.disable", params=kwargs) def usergroups_enable( @@ -4049,9 +3992,7 @@ def usergroups_enable( """Enable a User Group https://api.slack.com/methods/usergroups.enable """ - kwargs.update( - {"usergroup": usergroup, "include_count": include_count, "team_id": team_id} - ) + kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id}) return self.api_call("usergroups.enable", params=kwargs) def usergroups_list( diff --git a/slack_sdk/web/legacy_slack_response.py b/slack_sdk/web/legacy_slack_response.py index ad72a0764..a9ca462e4 100644 --- a/slack_sdk/web/legacy_slack_response.py +++ b/slack_sdk/web/legacy_slack_response.py @@ -82,9 +82,7 @@ def __init__( def __str__(self): """Return the Response data if object is converted to a string.""" if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") return f"{self.data}" def __getitem__(self, key): @@ -99,9 +97,7 @@ def __getitem__(self, key): The value from data or None. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") return self.data.get(key, None) def __iter__(self): @@ -115,9 +111,7 @@ def __iter__(self): (SlackResponse) self """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") self._iteration = 0 # skipcq: PYL-W0201 self.data = self._initial_data return self @@ -142,9 +136,7 @@ def __next__(self): StopIteration: If 'next_cursor' is not present or empty. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") self._iteration += 1 if self._iteration == 1: return self @@ -189,9 +181,7 @@ def get(self, key, default=None): The value from data or the specified default. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") return self.data.get(key, default) def validate(self): @@ -212,11 +202,7 @@ def validate(self): f"headers: {dict(self.headers)}, " f"body: {body}" ) - if ( - self.status_code == 200 - and self.data - and (isinstance(self.data, bytes) or self.data.get("ok", False)) - ): + if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)): return self msg = "The request to the Slack API failed." raise e.SlackApiError(message=msg, response=self) diff --git a/slack_sdk/web/slack_response.py b/slack_sdk/web/slack_response.py index a18b672e6..936d4962e 100644 --- a/slack_sdk/web/slack_response.py +++ b/slack_sdk/web/slack_response.py @@ -76,9 +76,7 @@ def __init__( def __str__(self): """Return the Response data if object is converted to a string.""" if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") return f"{self.data}" def __contains__(self, key: str) -> bool: @@ -96,13 +94,9 @@ def __getitem__(self, key): The value from data or None. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") if self.data is None: - raise ValueError( - "As the response.data is empty, this operation is unsupported" - ) + raise ValueError("As the response.data is empty, this operation is unsupported") return self.data.get(key, None) def __iter__(self): @@ -139,9 +133,7 @@ def __next__(self): StopIteration: If 'next_cursor' is not present or empty. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") self._iteration += 1 if self._iteration == 1: return self @@ -149,9 +141,7 @@ def __next__(self): params = self.req_args.get("params", {}) if params is None: params = {} - next_cursor = self.data.get("response_metadata", {}).get( - "next_cursor" - ) or self.data.get("next_cursor") + next_cursor = self.data.get("response_metadata", {}).get("next_cursor") or self.data.get("next_cursor") params.update({"cursor": next_cursor}) self.req_args.update({"params": params}) @@ -178,9 +168,7 @@ def get(self, key, default=None): The value from data or the specified default. """ if isinstance(self.data, bytes): - raise ValueError( - "As the response.data is binary data, this operation is unsupported" - ) + raise ValueError("As the response.data is binary data, this operation is unsupported") if self.data is None: return None return self.data.get(key, default) @@ -195,11 +183,7 @@ def validate(self): Raises: SlackApiError: The request to the Slack API failed. """ - if ( - self.status_code == 200 - and self.data - and (isinstance(self.data, bytes) or self.data.get("ok", False)) - ): + if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)): return self msg = f"The request to the Slack API failed. (url: {self.api_url})" raise e.SlackApiError(message=msg, response=self) diff --git a/slack_sdk/webhook/async_client.py b/slack_sdk/webhook/async_client.py index 941b1431d..019854778 100644 --- a/slack_sdk/webhook/async_client.py +++ b/slack_sdk/webhook/async_client.py @@ -76,13 +76,9 @@ def __init__( self.session = session self.auth = auth self.default_headers = default_headers if default_headers else {} - self.default_headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.logger = logger if logger is not None else logging.getLogger(__name__) - self.retry_handlers = ( - retry_handlers if retry_handlers is not None else async_default_handlers() - ) + self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers() if self.proxy is None or len(self.proxy.strip()) == 0: env_variable = load_http_proxy_from_env(self.logger) @@ -134,9 +130,7 @@ async def send( headers=headers, ) - async def send_dict( - self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None - ) -> WebhookResponse: + async def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse: """Performs a Slack API request and returns the result. Args: @@ -151,9 +145,7 @@ async def send_dict( headers=_build_request_headers(self.default_headers, headers), ) - async def _perform_http_request( - self, *, body: Dict[str, Any], headers: Dict[str, str] - ) -> WebhookResponse: + async def _perform_http_request(self, *, body: Dict[str, Any], headers: Dict[str, str]) -> WebhookResponse: str_body: str = json.dumps(body) headers["Content-Type"] = "application/json;charset=utf-8" @@ -194,27 +186,19 @@ async def _perform_http_request( response_body = "" if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Sending a request - url: {self.url}, body: {str_body}, headers: {headers}" - ) + self.logger.debug(f"Sending a request - url: {self.url}, body: {str_body}, headers: {headers}") try: - async with session.request( - "POST", self.url, **request_kwargs - ) as res: + async with session.request("POST", self.url, **request_kwargs) as res: try: response_body = await res.text() retry_response = RetryHttpResponse( status_code=res.status, headers=res.headers, - data=response_body.encode("utf-8") - if response_body is not None - else None, + data=response_body.encode("utf-8") if response_body is not None else None, ) except aiohttp.ContentTypeError: - self.logger.debug( - f"No response data returned from the following API call: {self.url}" - ) + self.logger.debug(f"No response data returned from the following API call: {self.url}") if res.status == 429: for handler in self.retry_handlers: @@ -256,8 +240,7 @@ async def _perform_http_request( ): if self.logger.level <= logging.DEBUG: self.logger.info( - f"A retry handler found: {type(handler).__name__} " - f"for POST {self.url} - {e}" + f"A retry handler found: {type(handler).__name__} " f"for POST {self.url} - {e}" ) await handler.prepare_for_next_attempt_async( state=retry_state, diff --git a/slack_sdk/webhook/client.py b/slack_sdk/webhook/client.py index 30d294ce1..17df0b754 100644 --- a/slack_sdk/webhook/client.py +++ b/slack_sdk/webhook/client.py @@ -66,13 +66,9 @@ def __init__( self.ssl = ssl self.proxy = proxy self.default_headers = default_headers if default_headers else {} - self.default_headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.logger = logger if logger is not None else logging.getLogger(__name__) - self.retry_handlers = ( - retry_handlers if retry_handlers is not None else default_retry_handlers() - ) + self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers() if self.proxy is None or len(self.proxy.strip()) == 0: env_variable = load_http_proxy_from_env(self.logger) @@ -125,9 +121,7 @@ def send( headers=headers, ) - def send_dict( - self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None - ) -> WebhookResponse: + def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse: """Performs a Slack API request and returns the result. Args: @@ -142,23 +136,17 @@ def send_dict( headers=_build_request_headers(self.default_headers, headers), ) - def _perform_http_request( - self, *, body: Dict[str, Any], headers: Dict[str, str] - ) -> WebhookResponse: + def _perform_http_request(self, *, body: Dict[str, Any], headers: Dict[str, str]) -> WebhookResponse: body = json.dumps(body) headers["Content-Type"] = "application/json;charset=utf-8" if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Sending a request - url: {self.url}, body: {body}, headers: {headers}" - ) + self.logger.debug(f"Sending a request - url: {self.url}, body: {body}, headers: {headers}") url = self.url # NOTE: Intentionally ignore the `http_verb` here # Slack APIs accepts any API method requests with POST methods - req = Request( - method="POST", url=url, data=body.encode("utf-8"), headers=headers - ) + req = Request(method="POST", url=url, data=body.encode("utf-8"), headers=headers) resp = None last_error = None @@ -188,15 +176,9 @@ def _perform_http_request( ) if e.code == 429: # for backward-compatibility with WebClient (v.2.5.0 or older) - if ( - "retry-after" not in resp.headers - and "Retry-After" in resp.headers - ): + if "retry-after" not in resp.headers and "Retry-After" in resp.headers: resp.headers["retry-after"] = resp.headers["Retry-After"] - if ( - "Retry-After" not in resp.headers - and "retry-after" in resp.headers - ): + if "Retry-After" not in resp.headers and "retry-after" in resp.headers: resp.headers["Retry-After"] = resp.headers["retry-after"] _debug_log_response(self.logger, resp) @@ -205,9 +187,7 @@ def _perform_http_request( retry_response = RetryHttpResponse( status_code=e.code, headers={k: [v] for k, v in e.headers.items()}, - data=response_body.encode("utf-8") - if response_body is not None - else None, + data=response_body.encode("utf-8") if response_body is not None else None, ) for handler in self.retry_handlers: if handler.can_retry( @@ -233,9 +213,7 @@ def _perform_http_request( except Exception as err: last_error = err - self.logger.error( - f"Failed to send a request to Slack API server: {err}" - ) + self.logger.error(f"Failed to send a request to Slack API server: {err}") # Try to find a retry handler for this error retry_request = RetryHttpRequest.from_urllib_http_request(req) @@ -256,9 +234,7 @@ def _perform_http_request( response=None, error=err, ) - self.logger.info( - f"Going to retry the same request: {req.method} {req.full_url}" - ) + self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}") break if retry_state.next_attempt_requested is False: @@ -279,9 +255,7 @@ def _perform_http_request_internal(self, url: str, req: Request): HTTPSHandler(context=self.ssl), ) else: - raise SlackRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") else: raise SlackRequestError(f"Invalid URL detected: {url}") @@ -290,9 +264,7 @@ def _perform_http_request_internal(self, url: str, req: Request): if opener: http_resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: - http_resp = urlopen( # skipcq: BAN-B310 - req, context=self.ssl, timeout=self.timeout - ) + http_resp = urlopen(req, context=self.ssl, timeout=self.timeout) # skipcq: BAN-B310 charset: str = http_resp.headers.get_content_charset() or "utf-8" response_body: str = http_resp.read().decode(charset) resp = WebhookResponse( diff --git a/tests/rtm/mock_web_api_server.py b/tests/rtm/mock_web_api_server.py index 113349635..9d03ac837 100644 --- a/tests/rtm/mock_web_api_server.py +++ b/tests/rtm/mock_web_api_server.py @@ -13,9 +13,7 @@ class MockHandler(SimpleHTTPRequestHandler): logger = logging.getLogger(__name__) def is_valid_token(self): - return "authorization" in self.headers and str( - self.headers["authorization"] - ).startswith("Bearer xoxb-") + return "authorization" in self.headers and str(self.headers["authorization"]).startswith("Bearer xoxb-") def is_invalid_rtm_start(self): return ( @@ -53,9 +51,7 @@ def _handle(self): self.send_response(HTTPStatus.OK) self.set_common_headers() - body = ( - self.rtm_start_success if self.is_valid_token() else self.rtm_start_failure - ) + body = self.rtm_start_success if self.is_valid_token() else self.rtm_start_failure self.wfile.write(json.dumps(body).encode("utf-8")) self.wfile.close() @@ -67,9 +63,7 @@ def do_POST(self): class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self) self.handler = handler self.test = test diff --git a/tests/rtm/test_rtm_client.py b/tests/rtm/test_rtm_client.py index e1ac28ee0..ece3e57ac 100644 --- a/tests/rtm/test_rtm_client.py +++ b/tests/rtm/test_rtm_client.py @@ -13,9 +13,7 @@ class TestRTMClient(unittest.TestCase): def setUp(self): setup_mock_web_api_server(self) - self.client = slack.RTMClient( - token="xoxp-1234", base_url="http://localhost:8888", auto_reconnect=False - ) + self.client = slack.RTMClient(token="xoxp-1234", base_url="http://localhost:8888", auto_reconnect=False) def tearDown(self): cleanup_mock_web_api_server(self) @@ -70,9 +68,7 @@ def invalid_cb(): with self.assertRaises(e.SlackClientError) as context: self.client.on(event="message", callback=invalid_cb) - expected_error = ( - "The callback 'invalid_cb' must accept keyword arguments (**kwargs)." - ) + expected_error = "The callback 'invalid_cb' must accept keyword arguments (**kwargs)." error = str(context.exception) self.assertIn(expected_error, error) @@ -90,7 +86,6 @@ def test_start_raises_an_error_if_rtm_ws_url_is_not_returned(self): slack.RTMClient(token="xoxp-1234", auto_reconnect=False).start() expected_error = ( - "The request to the Slack API failed.\n" - "The server responded with: {'ok': False, 'error': 'invalid_auth'}" + "The request to the Slack API failed.\n" "The server responded with: {'ok': False, 'error': 'invalid_auth'}" ) self.assertIn(expected_error, str(context.exception)) diff --git a/tests/signature/test_signature_verifier.py b/tests/signature/test_signature_verifier.py index 765175334..f2dc79a01 100644 --- a/tests/signature/test_signature_verifier.py +++ b/tests/signature/test_signature_verifier.py @@ -21,9 +21,7 @@ def tearDown(self): body = "token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J&team_domain=testteamnow&channel_id=G8PSS9T3V&channel_name=foobar&user_id=U2CERLKJA&user_name=roadrunner&command=%2Fwebhook-collect&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT1DC2JH3J%2F397700885554%2F96rGlfmibIGlgcZRskXaIFfN&trigger_id=398738663015.47445629121.803a0bc887a14d10d2c447fce8b6703c" timestamp = "1531420618" - valid_signature = ( - "v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503" - ) + valid_signature = "v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503" headers = { "X-Slack-Request-Timestamp": timestamp, @@ -32,31 +30,21 @@ def tearDown(self): def test_generate_signature(self): verifier = SignatureVerifier(self.signing_secret) - signature = verifier.generate_signature( - timestamp=self.timestamp, body=self.body - ) + signature = verifier.generate_signature(timestamp=self.timestamp, body=self.body) self.assertEqual(self.valid_signature, signature) def test_generate_signature_body_as_bytes(self): verifier = SignatureVerifier(self.signing_secret) - signature = verifier.generate_signature( - timestamp=self.timestamp, body=self.body.encode("utf-8") - ) + signature = verifier.generate_signature(timestamp=self.timestamp, body=self.body.encode("utf-8")) self.assertEqual(self.valid_signature, signature) def test_is_valid_request(self): - verifier = SignatureVerifier( - signing_secret=self.signing_secret, clock=MockClock() - ) + verifier = SignatureVerifier(signing_secret=self.signing_secret, clock=MockClock()) self.assertTrue(verifier.is_valid_request(self.body, self.headers)) def test_is_valid_request_body_as_bytes(self): - verifier = SignatureVerifier( - signing_secret=self.signing_secret, clock=MockClock() - ) - self.assertTrue( - verifier.is_valid_request(self.body.encode("utf-8"), self.headers) - ) + verifier = SignatureVerifier(signing_secret=self.signing_secret, clock=MockClock()) + self.assertTrue(verifier.is_valid_request(self.body.encode("utf-8"), self.headers)) def test_is_valid_request_invalid_body(self): verifier = SignatureVerifier( @@ -72,9 +60,7 @@ def test_is_valid_request_invalid_body_as_bytes(self): clock=MockClock(), ) modified_body = self.body + "------" - self.assertFalse( - verifier.is_valid_request(modified_body.encode("utf-8"), self.headers) - ) + self.assertFalse(verifier.is_valid_request(modified_body.encode("utf-8"), self.headers)) def test_is_valid_request_expiration(self): verifier = SignatureVerifier( @@ -96,9 +82,7 @@ def test_is_valid(self): signing_secret=self.signing_secret, clock=MockClock(), ) - self.assertTrue( - verifier.is_valid(self.body, self.timestamp, self.valid_signature) - ) + self.assertTrue(verifier.is_valid(self.body, self.timestamp, self.valid_signature)) self.assertTrue(verifier.is_valid(self.body, 1531420618, self.valid_signature)) def test_is_valid_none(self): diff --git a/tests/slack_sdk/audit_logs/mock_web_api_server.py b/tests/slack_sdk/audit_logs/mock_web_api_server.py index 8204005c4..4857207f6 100644 --- a/tests/slack_sdk/audit_logs/mock_web_api_server.py +++ b/tests/slack_sdk/audit_logs/mock_web_api_server.py @@ -24,9 +24,7 @@ class MockHandler(SimpleHTTPRequestHandler): def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] - return self.pattern_for_language.search( - user_agent - ) and self.pattern_for_package_identifier.search(user_agent) + return self.pattern_for_language.search(user_agent) and self.pattern_for_package_identifier.search(user_agent) def set_common_headers(self): self.send_header("content-type", "application/json;charset=utf-8") @@ -51,9 +49,7 @@ def do_GET(self): self.send_response(429) self.send_header("retry-after", 1) self.set_common_headers() - self.wfile.write( - """{"ok": false, "error": "ratelimited"}""".encode("utf-8") - ) + self.wfile.write("""{"ok": false, "error": "ratelimited"}""".encode("utf-8")) return try: @@ -122,9 +118,7 @@ def stop(self): class MonitorThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self, daemon=True) self.handler = handler self.test = test @@ -136,9 +130,7 @@ def run(self) -> None: try: req = Request(f"{self.test.server_url}/received_requests.json") resp = urlopen(req, timeout=1) - self.test.mock_received_requests = json.loads( - resp.read().decode("utf-8") - ) + self.test.mock_received_requests = json.loads(resp.read().decode("utf-8")) except Exception as e: # skip logging for the initial request if self.test.mock_received_requests is not None: @@ -151,9 +143,7 @@ def stop(self): class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self) self.handler = handler self.test = test diff --git a/tests/slack_sdk/audit_logs/test_client.py b/tests/slack_sdk/audit_logs/test_client.py index 0d228f748..47766c4f8 100644 --- a/tests/slack_sdk/audit_logs/test_client.py +++ b/tests/slack_sdk/audit_logs/test_client.py @@ -24,9 +24,7 @@ def test_logs(self): self.assertEqual(resp.typed_body.entries[0].id, "xxx-yyy-zzz-111") def test_logs_pagination(self): - resp: AuditLogsResponse = self.client.logs( - limit=1, action="user_login", cursor="xxxxxxx" - ) + resp: AuditLogsResponse = self.client.logs(limit=1, action="user_login", cursor="xxxxxxx") self.assertEqual(200, resp.status_code) self.assertIsNotNone(resp.body.get("entries")) diff --git a/tests/slack_sdk/models/test_actions.py b/tests/slack_sdk/models/test_actions.py index f3707bc2e..df1de7fc0 100644 --- a/tests/slack_sdk/models/test_actions.py +++ b/tests/slack_sdk/models/test_actions.py @@ -47,9 +47,7 @@ def test_json(self): def test_value_length(self): with self.assertRaises(SlackObjectFormationError): - ActionButton( - name="button_1", text="Click me!", value=STRING_3001_CHARS - ).to_dict() + ActionButton(name="button_1", text="Click me!", value=STRING_3001_CHARS).to_dict() def test_style_validator(self): b = ActionButton(name="button_1", text="Click me!", value="btn_1") @@ -81,9 +79,7 @@ def setUp(self) -> None: def test_json(self): self.assertDictEqual( - ActionStaticSelector( - name="select_1", text="selector_1", options=self.options - ).to_dict(), + ActionStaticSelector(name="select_1", text="selector_1", options=self.options).to_dict(), { "name": "select_1", "text": "selector_1", @@ -94,9 +90,7 @@ def test_json(self): ) self.assertDictEqual( - ActionStaticSelector( - name="select_1", text="selector_1", options=self.option_group - ).to_dict(), + ActionStaticSelector(name="select_1", text="selector_1", options=self.option_group).to_dict(), { "name": "select_1", "text": "selector_1", @@ -108,9 +102,7 @@ def test_json(self): def test_options_length(self): with self.assertRaises(SlackObjectFormationError): - ActionStaticSelector( - name="select_1", text="selector_1", options=self.options * 34 - ).to_dict() + ActionStaticSelector(name="select_1", text="selector_1", options=self.options * 34).to_dict() class DynamicActionSelectorTests(unittest.TestCase): @@ -155,9 +147,7 @@ def test_json(self): option = Option.from_single_value("one") self.assertDictEqual( - ActionExternalSelector( - name="select_1", text="selector_1", min_query_length=3 - ).to_dict(), + ActionExternalSelector(name="select_1", text="selector_1", min_query_length=3).to_dict(), { "name": "select_1", "text": "selector_1", @@ -168,9 +158,7 @@ def test_json(self): ) self.assertDictEqual( - ActionExternalSelector( - name="select_1", text="selector_1", selected_option=option - ).to_dict(), + ActionExternalSelector(name="select_1", text="selector_1", selected_option=option).to_dict(), { "name": "select_1", "text": "selector_1", diff --git a/tests/slack_sdk/models/test_attachments.py b/tests/slack_sdk/models/test_attachments.py index b38d1210d..875302dce 100644 --- a/tests/slack_sdk/models/test_attachments.py +++ b/tests/slack_sdk/models/test_attachments.py @@ -26,9 +26,7 @@ def setUp(self) -> None: self.simple = Attachment(text="some_text") def test_basic_json(self): - self.assertDictEqual( - Attachment(text="some text").to_dict(), {"text": "some text", "fields": []} - ) + self.assertDictEqual(Attachment(text="some text").to_dict(), {"text": "some text", "fields": []}) self.assertDictEqual( Attachment( @@ -37,10 +35,7 @@ def test_basic_json(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -139,9 +134,7 @@ def test_basic_json(self): ActionLinkButton(text="navigate", url="http://google.com"), ] self.assertDictEqual( - InteractiveAttachment( - text="some text", callback_id="abc123", actions=actions - ).to_dict(), + InteractiveAttachment(text="some text", callback_id="abc123", actions=actions).to_dict(), { "text": "some text", "fields": [], @@ -159,10 +152,7 @@ def test_basic_json(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -201,14 +191,10 @@ def test_basic_json(self): ) def test_actions_length(self): - actions = [ - ActionButton(name="button_1", text="Click me", value="button_value_1") - ] * 6 + actions = [ActionButton(name="button_1", text="Click me", value="button_value_1")] * 6 with self.assertRaises(SlackObjectFormationError): - InteractiveAttachment( - text="some text", callback_id="abc123", actions=actions - ).to_dict(), + InteractiveAttachment(text="some text", callback_id="abc123", actions=actions).to_dict(), class BlockAttachmentTests(unittest.TestCase): diff --git a/tests/slack_sdk/models/test_blocks.py b/tests/slack_sdk/models/test_blocks.py index c79cfedba..86a717f85 100644 --- a/tests/slack_sdk/models/test_blocks.py +++ b/tests/slack_sdk/models/test_blocks.py @@ -141,9 +141,7 @@ def test_json(self): ], "type": "section", }, - SectionBlock( - text="some text", fields=[f"field{i}" for i in range(5)] - ).to_dict(), + SectionBlock(text="some text", fields=[f"field{i}" for i in range(5)]).to_dict(), ) button = LinkButtonElement(text="Click me!", url="http://google.com") @@ -181,9 +179,7 @@ def build_slack_block(cls, msg1, msg2, data): {"type": "section", "fields": []}, ] names = list(set(data.keys()) - set("user_comments")) - fields = [ - {"type": "mrkdwn", "text": f"*{name}*:\n{data[name]}"} for name in names - ] + fields = [{"type": "mrkdwn", "text": f"*{name}*:\n{data[name]}"} for name in names] blocks[1]["fields"] = fields return blocks @@ -194,9 +190,7 @@ def build_slack_block_native(cls, msg1, msg2, data): SectionBlock(fields=[]), ] names: List[str] = list(set(data.keys()) - set("user_comments")) - fields = [ - MarkdownTextObject.parse(f"*{name}*:\n{data[name]}") for name in names - ] + fields = [MarkdownTextObject.parse(f"*{name}*:\n{data[name]}") for name in names] blocks[1].fields = fields return list(b.to_dict() for b in blocks) @@ -224,9 +218,7 @@ def test_document(self): def test_json(self): self.assertDictEqual({"type": "divider"}, DividerBlock().to_dict()) - self.assertDictEqual( - {"type": "divider"}, DividerBlock(**{"type": "divider"}).to_dict() - ) + self.assertDictEqual({"type": "divider"}, DividerBlock(**{"type": "divider"}).to_dict()) def test_json_with_block_id(self): self.assertDictEqual( @@ -265,9 +257,7 @@ def test_json(self): "alt_text": "not really an image", "type": "image", }, - ImageBlock( - image_url="http://google.com", alt_text="not really an image" - ).to_dict(), + ImageBlock(image_url="http://google.com", alt_text="not really an image").to_dict(), ) def test_image_url_length(self): @@ -276,15 +266,11 @@ def test_image_url_length(self): def test_alt_text_length(self): with self.assertRaises(SlackObjectFormationError): - ImageBlock( - image_url="http://google.com", alt_text=STRING_3001_CHARS - ).to_dict() + ImageBlock(image_url="http://google.com", alt_text=STRING_3001_CHARS).to_dict() def test_title_length(self): with self.assertRaises(SlackObjectFormationError): - ImageBlock( - image_url="http://google.com", alt_text="text", title=STRING_3001_CHARS - ).to_dict() + ImageBlock(image_url="http://google.com", alt_text="text", title=STRING_3001_CHARS).to_dict() # ---------------------------------------------- @@ -417,9 +403,7 @@ def test_element_parsing(self): ButtonElement(text="Click me", action_id="reg_button", value="1"), StaticSelectElement(options=[Option(value="SelectOption")]), ImageElement(image_url="url", alt_text="alt-text"), - OverflowMenuElement( - options=[Option(value="MenuOption1"), Option(value="MenuOption2")] - ), + OverflowMenuElement(options=[Option(value="MenuOption1"), Option(value="MenuOption2")]), ] input = { "type": "actions", diff --git a/tests/slack_sdk/models/test_dialoags.py b/tests/slack_sdk/models/test_dialoags.py index 30f41e821..ca2544a8a 100644 --- a/tests/slack_sdk/models/test_dialoags.py +++ b/tests/slack_sdk/models/test_dialoags.py @@ -28,54 +28,34 @@ def test_json_validators(self): with self.assertRaises(SlackObjectFormationError, msg="label length"): component(name="dialog", label=STRING_51_CHARS).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="placeholder length" - ): - component( - name="dialog", label="Dialog", placeholder=STRING_301_CHARS - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="placeholder length"): + component(name="dialog", label="Dialog", placeholder=STRING_301_CHARS).to_dict() with self.assertRaises(SlackObjectFormationError, msg="hint length"): - component( - name="dialog", label="Dialog", hint=STRING_301_CHARS - ).to_dict() + component(name="dialog", label="Dialog", hint=STRING_301_CHARS).to_dict() with self.assertRaises(SlackObjectFormationError, msg="value length"): - component( - name="dialog", label="Dialog", value=STRING_3001_CHARS - ).to_dict() + component(name="dialog", label="Dialog", value=STRING_3001_CHARS).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="min_length out of bounds" - ): + with self.assertRaises(SlackObjectFormationError, msg="min_length out of bounds"): component( name="dialog", label="Dialog", min_length=component.max_value_length + 1, ).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="max_length out of bounds" - ): + with self.assertRaises(SlackObjectFormationError, msg="max_length out of bounds"): component( name="dialog", label="Dialog", max_length=component.max_value_length + 1, ).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="min_length > max length" - ): - component( - name="dialog", label="Dialog", min_length=100, max_length=50 - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="min_length > max length"): + component(name="dialog", label="Dialog", min_length=100, max_length=50).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="subtype invalid" - ): - component( - name="dialog", label="Dialog", subtype="abcdefg" - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="subtype invalid"): + component(name="dialog", label="Dialog", subtype="abcdefg").to_dict() class TextFieldComponentTests(unittest.TestCase): @@ -158,9 +138,7 @@ def test_basic_json_formation(self): Option.from_single_value("three"), ] self.assertDictEqual( - DialogStaticSelector( - name="dialog", label="Dialog", options=options - ).to_dict(), + DialogStaticSelector(name="dialog", label="Dialog", options=options).to_dict(), { "optional": False, "label": "Dialog", @@ -197,13 +175,9 @@ def test_json(self): }, ) - passing_obj = component( - name="select_1", label="selector_1", value=self.selected_opt - ).to_dict() + passing_obj = component(name="select_1", label="selector_1", value=self.selected_opt).to_dict() - passing_str = component( - name="select_1", label="selector_1", value="U12345" - ).to_dict() + passing_str = component(name="select_1", label="selector_1", value="U12345").to_dict() expected = { "name": "select_1", @@ -256,9 +230,7 @@ def setUp(self) -> None: optional=True, hint="Enter your signature", ) - .text_area( - name="message", label="Message", hint="Enter message to broadcast" - ) + .text_area(name="message", label="Message", hint="Enter message to broadcast") .conversation_selector(name="target", label="Choose Target") ) diff --git a/tests/slack_sdk/models/test_dialogs.py b/tests/slack_sdk/models/test_dialogs.py index 405146442..3dd12fe76 100644 --- a/tests/slack_sdk/models/test_dialogs.py +++ b/tests/slack_sdk/models/test_dialogs.py @@ -28,54 +28,34 @@ def test_json_validators(self): with self.assertRaises(SlackObjectFormationError, msg="label length"): component(name="dialog", label=STRING_51_CHARS).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="placeholder length" - ): - component( - name="dialog", label="Dialog", placeholder=STRING_301_CHARS - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="placeholder length"): + component(name="dialog", label="Dialog", placeholder=STRING_301_CHARS).to_dict() with self.assertRaises(SlackObjectFormationError, msg="hint length"): - component( - name="dialog", label="Dialog", hint=STRING_301_CHARS - ).to_dict() + component(name="dialog", label="Dialog", hint=STRING_301_CHARS).to_dict() with self.assertRaises(SlackObjectFormationError, msg="value length"): - component( - name="dialog", label="Dialog", value=STRING_3001_CHARS - ).to_dict() + component(name="dialog", label="Dialog", value=STRING_3001_CHARS).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="min_length out of bounds" - ): + with self.assertRaises(SlackObjectFormationError, msg="min_length out of bounds"): component( name="dialog", label="Dialog", min_length=component.max_value_length + 1, ).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="max_length out of bounds" - ): + with self.assertRaises(SlackObjectFormationError, msg="max_length out of bounds"): component( name="dialog", label="Dialog", max_length=component.max_value_length + 1, ).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="min_length > max length" - ): - component( - name="dialog", label="Dialog", min_length=100, max_length=50 - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="min_length > max length"): + component(name="dialog", label="Dialog", min_length=100, max_length=50).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="subtype invalid" - ): - component( - name="dialog", label="Dialog", subtype="abcdefg" - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="subtype invalid"): + component(name="dialog", label="Dialog", subtype="abcdefg").to_dict() class TextFieldComponentTests(unittest.TestCase): @@ -158,9 +138,7 @@ def test_basic_json_formation(self): Option.from_single_value("three"), ] self.assertDictEqual( - DialogStaticSelector( - name="dialog", label="Dialog", options=options - ).to_dict(), + DialogStaticSelector(name="dialog", label="Dialog", options=options).to_dict(), { "optional": False, "label": "Dialog", @@ -197,13 +175,9 @@ def test_json(self): }, ) - passing_obj = component( - name="select_1", label="selector_1", value=self.selected_opt - ).to_dict() + passing_obj = component(name="select_1", label="selector_1", value=self.selected_opt).to_dict() - passing_str = component( - name="select_1", label="selector_1", value="U12345" - ).to_dict() + passing_str = component(name="select_1", label="selector_1", value="U12345").to_dict() expected = { "name": "select_1", @@ -256,9 +230,7 @@ def setUp(self) -> None: optional=True, hint="Enter your signature", ) - .text_area( - name="message", label="Message", hint="Enter message to broadcast" - ) + .text_area(name="message", label="Message", hint="Enter message to broadcast") .conversation_selector(name="target", label="Choose Target") ) diff --git a/tests/slack_sdk/models/test_elements.py b/tests/slack_sdk/models/test_elements.py index a5f67a298..c4a25fb95 100644 --- a/tests/slack_sdk/models/test_elements.py +++ b/tests/slack_sdk/models/test_elements.py @@ -35,9 +35,7 @@ class BlockElementTests(unittest.TestCase): def test_eq(self): self.assertEqual(BlockElement(), BlockElement()) self.assertEqual(BlockElement(type="test"), BlockElement(type="test")) - self.assertNotEqual( - BlockElement(type="test"), BlockElement(type="another test") - ) + self.assertNotEqual(BlockElement(type="test"), BlockElement(type="another test")) def test_parse_timepicker(self): timepicker = BlockElement.parse( @@ -84,9 +82,7 @@ def test_with_input_interactive_element(self): class InteractiveElementTests(unittest.TestCase): def test_action_id(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="click me!", action_id=STRING_301_CHARS, value="clickable button" - ).to_dict() + ButtonElement(text="click me!", action_id=STRING_301_CHARS, value="clickable button").to_dict() class ButtonElementTests(unittest.TestCase): @@ -137,9 +133,7 @@ def test_json(self): "value": "button_123", "type": "button", }, - ButtonElement( - text="button text", action_id="some_button", value="button_123" - ).to_dict(), + ButtonElement(text="button text", action_id="some_button", value="button_123").to_dict(), ) confirm = ConfirmObject(title="really?", text="are you sure?") @@ -163,27 +157,19 @@ def test_json(self): def test_text_length(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text=STRING_301_CHARS, action_id="button", value="click_me" - ).to_dict() + ButtonElement(text=STRING_301_CHARS, action_id="button", value="click_me").to_dict() def test_action_id_length(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="test", action_id="1234567890" * 26, value="click_me" - ).to_dict() + ButtonElement(text="test", action_id="1234567890" * 26, value="click_me").to_dict() def test_value_length(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="Button", action_id="button", value=STRING_3001_CHARS - ).to_dict() + ButtonElement(text="Button", action_id="button", value=STRING_3001_CHARS).to_dict() def test_invalid_style(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="Button", action_id="button", value="button", style="invalid" - ).to_dict() + ButtonElement(text="Button", action_id="button", value="button", style="invalid").to_dict() def test_accessibility_label_length(self): with self.assertRaises(SlackObjectFormationError): @@ -197,9 +183,7 @@ def test_accessibility_label_length(self): class LinkButtonElementTests(unittest.TestCase): def test_json(self): - button = LinkButtonElement( - action_id="test", text="button text", url="http://google.com" - ) + button = LinkButtonElement(action_id="test", text="button text", url="http://google.com") self.assertDictEqual( { "text": {"emoji": True, "text": "button text", "type": "plain_text"}, @@ -251,9 +235,7 @@ def test_document(self): input = { "type": "checkboxes", "action_id": "this_is_an_action_id", - "initial_options": [ - {"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}} - ], + "initial_options": [{"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}}], "options": [ {"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}}, {"value": "A2", "text": {"type": "plain_text", "text": "Checkbox 2"}}, @@ -265,9 +247,7 @@ def test_focus_on_load(self): input = { "type": "checkboxes", "action_id": "this_is_an_action_id", - "initial_options": [ - {"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}} - ], + "initial_options": [{"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}}], "options": [ {"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}}, ], @@ -424,9 +404,7 @@ def test_json(self): "alt_text": "not really an image", "type": "image", }, - ImageElement( - image_url="http://google.com", alt_text="not really an image" - ).to_dict(), + ImageElement(image_url="http://google.com", alt_text="not really an image").to_dict(), ) def test_image_url_length(self): @@ -435,9 +413,7 @@ def test_image_url_length(self): def test_alt_text_length(self): with self.assertRaises(SlackObjectFormationError): - ImageElement( - image_url="http://google.com", alt_text=STRING_3001_CHARS - ).to_dict() + ImageElement(image_url="http://google.com", alt_text=STRING_3001_CHARS).to_dict() # ------------------------------------------------- @@ -753,9 +729,7 @@ def test_json(self): "min_query_length": 5, "type": "external_select", }, - ExternalDataSelectElement( - placeholder="selectedValue", action_id="dropdown", min_query_length=5 - ).to_dict(), + ExternalDataSelectElement(placeholder="selectedValue", action_id="dropdown", min_query_length=5).to_dict(), ) self.assertDictEqual( { diff --git a/tests/slack_sdk/models/test_objects.py b/tests/slack_sdk/models/test_objects.py index c7c626d9c..532cddd6b 100644 --- a/tests/slack_sdk/models/test_objects.py +++ b/tests/slack_sdk/models/test_objects.py @@ -61,12 +61,8 @@ def __init__( initial: Union[dict, KeyValueObject], options: List[Union[dict, KeyValueObject]], ): - self.initial = ( - KeyValueObject(**initial) if isinstance(initial, dict) else initial - ) - self.options = [ - KeyValueObject(**o) if isinstance(o, dict) else o for o in options - ] + self.initial = KeyValueObject(**initial) if isinstance(initial, dict) else initial + self.options = [KeyValueObject(**o) if isinstance(o, dict) else o for o in options] class JsonObjectTests(unittest.TestCase): @@ -199,12 +195,8 @@ def setUp(self) -> None: self.epoch = 1234567890 def test_simple_formation(self): - datelink = DateLink( - date=self.epoch, date_format="{date_long}", fallback=f"{self.epoch}" - ) - self.assertEqual( - f"{datelink}", f"" - ) + datelink = DateLink(date=self.epoch, date_format="{date_long}", fallback=f"{self.epoch}") + self.assertEqual(f"{datelink}", f"") def test_with_url(self): datelink = DateLink( @@ -266,9 +258,7 @@ def test_basic_json(self): def test_from_string(self): plaintext = PlainTextObject(text="some text", emoji=True) - self.assertDictEqual( - plaintext.to_dict(), PlainTextObject.direct_from_string("some text") - ) + self.assertDictEqual(plaintext.to_dict(), PlainTextObject.direct_from_string("some text")) class MarkdownTextObjectTests(unittest.TestCase): @@ -285,9 +275,7 @@ def test_basic_json(self): def test_from_string(self): markdown = MarkdownTextObject(text="some text") - self.assertDictEqual( - markdown.to_dict(), MarkdownTextObject.direct_from_string("some text") - ) + self.assertDictEqual(markdown.to_dict(), MarkdownTextObject.direct_from_string("some text")) class ConfirmObjectTests(unittest.TestCase): @@ -378,15 +366,11 @@ def test_text_length_with_object(self): def test_confirm_length(self): with self.assertRaises(SlackObjectFormationError): - ConfirmObject( - title="title", text="Are you sure?", confirm=STRING_51_CHARS - ).to_dict() + ConfirmObject(title="title", text="Are you sure?", confirm=STRING_51_CHARS).to_dict() def test_deny_length(self): with self.assertRaises(SlackObjectFormationError): - ConfirmObject( - title="title", text="Are you sure?", deny=STRING_51_CHARS - ).to_dict() + ConfirmObject(title="title", text="Are you sure?", deny=STRING_51_CHARS).to_dict() class OptionTests(unittest.TestCase): @@ -543,15 +527,11 @@ def test_action_style_json(self): def test_label_length(self): with self.assertRaises(SlackObjectFormationError): - OptionGroup(label=STRING_301_CHARS, options=self.common_options).to_dict( - "text" - ) + OptionGroup(label=STRING_301_CHARS, options=self.common_options).to_dict("text") def test_options_length(self): with self.assertRaises(SlackObjectFormationError): - OptionGroup(label="option_group", options=self.common_options * 34).to_dict( - "text" - ) + OptionGroup(label="option_group", options=self.common_options * 34).to_dict("text") def test_confirm_style(self): obj = ConfirmObject.parse( diff --git a/tests/slack_sdk/models/test_views.py b/tests/slack_sdk/models/test_views.py index 680392810..a8bdfb9ff 100644 --- a/tests/slack_sdk/models/test_views.py +++ b/tests/slack_sdk/models/test_views.py @@ -69,9 +69,7 @@ def test_valid_construction(self): ), SectionBlock( block_id="sb-id", - text=MarkdownTextObject( - text="This is a mrkdwn text section block." - ), + text=MarkdownTextObject(text="This is a mrkdwn text section block."), fields=[ PlainTextObject(text="*this is plain_text text*", emoji=True), MarkdownTextObject(text="*this is mrkdwn text*"), @@ -81,31 +79,23 @@ def test_valid_construction(self): DividerBlock(), SectionBlock( block_id="rb-id", - text=MarkdownTextObject( - text="This is a section block with radio button accessory" - ), + text=MarkdownTextObject(text="This is a section block with radio button accessory"), accessory=RadioButtonsElement( initial_option=Option( text=PlainTextObject(text="Option 1"), value="option 1", - description=PlainTextObject( - text="Description for option 1" - ), + description=PlainTextObject(text="Description for option 1"), ), options=[ Option( text=PlainTextObject(text="Option 1"), value="option 1", - description=PlainTextObject( - text="Description for option 1" - ), + description=PlainTextObject(text="Description for option 1"), ), Option( text=PlainTextObject(text="Option 2"), value="option 2", - description=PlainTextObject( - text="Description for option 2" - ), + description=PlainTextObject(text="Description for option 2"), ), ], ), @@ -113,14 +103,8 @@ def test_valid_construction(self): ], state=ViewState( values={ - "b1": { - "a1": ViewStateValue(type="plain_text_input", value="Title") - }, - "b2": { - "a2": ViewStateValue( - type="plain_text_input", value="Description" - ) - }, + "b1": {"a1": ViewStateValue(type="plain_text_input", value="Title")}, + "b2": {"a2": ViewStateValue(type="plain_text_input", value="Description")}, } ), ) @@ -268,14 +252,8 @@ def test_all_state_values(self): } state = ViewState( values={ - "b1": { - "a1": ViewStateValue(type="datepicker", selected_date="1990-04-12") - }, - "b2": { - "a2": ViewStateValue( - type="plain_text_input", value="This is a test" - ) - }, + "b1": {"a1": ViewStateValue(type="datepicker", selected_date="1990-04-12")}, + "b2": {"a2": ViewStateValue(type="plain_text_input", value="This is a test")}, "b3": { "a3": ViewStateValue( type="plain_text_input", @@ -283,46 +261,26 @@ def test_all_state_values(self): ) }, "b4": {"a4": ViewStateValue(type="users_select", selected_user="U123")}, - "b4-2": { - "a4-2": ViewStateValue( - type="multi_users_select", selected_users=["U123", "U234"] - ) - }, - "b5": { - "a5": ViewStateValue( - type="conversations_select", selected_conversation="C123" - ) - }, + "b4-2": {"a4-2": ViewStateValue(type="multi_users_select", selected_users=["U123", "U234"])}, + "b5": {"a5": ViewStateValue(type="conversations_select", selected_conversation="C123")}, "b5-2": { "a5-2": ViewStateValue( type="multi_conversations_select", selected_conversations=["C123", "C234"], ) }, - "b6": { - "a6": ViewStateValue( - type="channels_select", selected_channel="C123" - ) - }, - "b6-2": { - "a6-2": ViewStateValue( - type="multi_channels_select", selected_channels=["C123", "C234"] - ) - }, + "b6": {"a6": ViewStateValue(type="channels_select", selected_channel="C123")}, + "b6-2": {"a6-2": ViewStateValue(type="multi_channels_select", selected_channels=["C123", "C234"])}, "b7": { "a7": ViewStateValue( type="multi_static_select", selected_options=[ Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-0", ), Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-1", ), ], @@ -333,15 +291,11 @@ def test_all_state_values(self): type="checkboxes", selected_options=[ Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-0", ), Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-1", ), ], @@ -353,9 +307,7 @@ def test_all_state_values(self): selected_option=Option( text=PlainTextObject(text="Option 1", emoji=True), value="option 1", - description=PlainTextObject( - text="Description for option 1", emoji=True - ), + description=PlainTextObject(text="Description for option 1", emoji=True), ), ) }, @@ -442,9 +394,7 @@ def test_home_tab_construction(self): type="home", blocks=[ SectionBlock( - text=MarkdownTextObject( - text="*Here's what you can do with Project Tracker:*" - ), + text=MarkdownTextObject(text="*Here's what you can do with Project Tracker:*"), ), ActionsBlock( elements=[ diff --git a/tests/slack_sdk/oauth/installation_store/test_amazon_s3.py b/tests/slack_sdk/oauth/installation_store/test_amazon_s3.py index 97360a3f2..fa0d33cc4 100644 --- a/tests/slack_sdk/oauth/installation_store/test_amazon_s3.py +++ b/tests/slack_sdk/oauth/installation_store/test_amazon_s3.py @@ -65,24 +65,16 @@ def test_save_and_find(self): i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U222" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U222") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T222", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T222", user_id="U111") self.assertIsNone(i) # delete installations store.delete_installation(enterprise_id="E111", team_id="T111", user_id="U111") - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) @@ -93,9 +85,7 @@ def test_save_and_find(self): i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) bot = store.find_bot(enterprise_id="E111", team_id="T222") self.assertIsNone(bot) @@ -117,9 +107,7 @@ def test_org_installation(self): # find bots bot = store.find_bot(enterprise_id="EO111", team_id=None) self.assertIsNotNone(bot) - bot = store.find_bot( - enterprise_id="EO111", team_id="TO222", is_enterprise_install=True - ) + bot = store.find_bot(enterprise_id="EO111", team_id="TO222", is_enterprise_install=True) self.assertIsNotNone(bot) bot = store.find_bot(enterprise_id="EO111", team_id="TO222") self.assertIsNone(bot) @@ -138,18 +126,14 @@ def test_org_installation(self): # find installations i = store.find_installation(enterprise_id="EO111", team_id=None) self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="EO111", team_id="T111", is_enterprise_install=True - ) + i = store.find_installation(enterprise_id="EO111", team_id="T111", is_enterprise_install=True) self.assertIsNotNone(i) i = store.find_installation(enterprise_id="EO111", team_id="T222") self.assertIsNone(i) i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="EO111", team_id=None, user_id="UO111" - ) + i = store.find_installation(enterprise_id="EO111", team_id=None, user_id="UO111") self.assertIsNotNone(i) i = store.find_installation( enterprise_id="E111", @@ -234,24 +218,16 @@ def test_save_and_find_token_rotation(self): i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U222" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U222") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T222", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T222", user_id="U111") self.assertIsNone(i) # delete installations store.delete_installation(enterprise_id="E111", team_id="T111", user_id="U111") - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) @@ -262,9 +238,7 @@ def test_save_and_find_token_rotation(self): i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) bot = store.find_bot(enterprise_id="E111", team_id="T222") self.assertIsNone(bot) diff --git a/tests/slack_sdk/oauth/installation_store/test_file.py b/tests/slack_sdk/oauth/installation_store/test_file.py index da110fa0b..0cb44dc17 100644 --- a/tests/slack_sdk/oauth/installation_store/test_file.py +++ b/tests/slack_sdk/oauth/installation_store/test_file.py @@ -49,24 +49,16 @@ def test_save_and_find(self): i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U222" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U222") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T222", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T222", user_id="U111") self.assertIsNone(i) # delete installations store.delete_installation(enterprise_id="E111", team_id="T111", user_id="U111") - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNotNone(i) @@ -81,9 +73,7 @@ def test_save_and_find(self): i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) bot = store.find_bot(enterprise_id="E111", team_id="T222") self.assertIsNone(bot) @@ -105,9 +95,7 @@ def test_org_installation(self): # find bots bot = store.find_bot(enterprise_id="EO111", team_id=None) self.assertIsNotNone(bot) - bot = store.find_bot( - enterprise_id="EO111", team_id="TO222", is_enterprise_install=True - ) + bot = store.find_bot(enterprise_id="EO111", team_id="TO222", is_enterprise_install=True) self.assertIsNotNone(bot) bot = store.find_bot(enterprise_id="EO111", team_id="TO222") self.assertIsNone(bot) @@ -126,18 +114,14 @@ def test_org_installation(self): # find installations i = store.find_installation(enterprise_id="EO111", team_id=None) self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="EO111", team_id="T111", is_enterprise_install=True - ) + i = store.find_installation(enterprise_id="EO111", team_id="T111", is_enterprise_install=True) self.assertIsNotNone(i) i = store.find_installation(enterprise_id="EO111", team_id="T222") self.assertIsNone(i) i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="EO111", team_id=None, user_id="UO111" - ) + i = store.find_installation(enterprise_id="EO111", team_id=None, user_id="UO111") self.assertIsNotNone(i) i = store.find_installation( enterprise_id="E111", diff --git a/tests/slack_sdk/oauth/installation_store/test_simple_cache.py b/tests/slack_sdk/oauth/installation_store/test_simple_cache.py index 5cd2412d9..2af633430 100644 --- a/tests/slack_sdk/oauth/installation_store/test_simple_cache.py +++ b/tests/slack_sdk/oauth/installation_store/test_simple_cache.py @@ -10,9 +10,7 @@ class TestCacheable(unittest.TestCase): def test_save_and_find(self): - sqlite3_store = SQLite3InstallationStore( - database="logs/cacheable.db", client_id="111.222" - ) + sqlite3_store = SQLite3InstallationStore(database="logs/cacheable.db", client_id="111.222") sqlite3_store.init() store = CacheableInstallationStore(sqlite3_store) @@ -39,9 +37,7 @@ def test_save_and_find(self): self.assertIsNotNone(bot) # delete and find - sqlite3_store = SQLite3InstallationStore( - database="logs/cacheable.db", client_id="111.222" - ) + sqlite3_store = SQLite3InstallationStore(database="logs/cacheable.db", client_id="111.222") sqlite3_store.init() store = CacheableInstallationStore(sqlite3_store) @@ -56,9 +52,7 @@ def test_save_and_find(self): self.assertIsNotNone(bot) def test_save_and_find_token_rotation(self): - sqlite3_store = SQLite3InstallationStore( - database="logs/cacheable.db", client_id="111.222" - ) + sqlite3_store = SQLite3InstallationStore(database="logs/cacheable.db", client_id="111.222") sqlite3_store.init() store = CacheableInstallationStore(sqlite3_store) @@ -117,24 +111,16 @@ def test_save_and_find_token_rotation(self): i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U222" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U222") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T222", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T222", user_id="U111") self.assertIsNone(i) # delete installations store.delete_installation(enterprise_id="E111", team_id="T111", user_id="U111") - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) @@ -145,9 +131,7 @@ def test_save_and_find_token_rotation(self): i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) bot = store.find_bot(enterprise_id="E111", team_id="T222") self.assertIsNone(bot) diff --git a/tests/slack_sdk/oauth/installation_store/test_sqlalchemy.py b/tests/slack_sdk/oauth/installation_store/test_sqlalchemy.py index b42471ac9..5e8abea88 100644 --- a/tests/slack_sdk/oauth/installation_store/test_sqlalchemy.py +++ b/tests/slack_sdk/oauth/installation_store/test_sqlalchemy.py @@ -12,9 +12,7 @@ class TestSQLite3(unittest.TestCase): def setUp(self): self.engine = sqlalchemy.create_engine("sqlite:///:memory:") - self.store = SQLAlchemyInstallationStore( - client_id="111.222", engine=self.engine - ) + self.store = SQLAlchemyInstallationStore(client_id="111.222", engine=self.engine) self.store.metadata.create_all(self.engine) def tearDown(self): @@ -57,24 +55,16 @@ def test_save_and_find(self): i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U222" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U222") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T222", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T222", user_id="U111") self.assertIsNone(i) # delete installations store.delete_installation(enterprise_id="E111", team_id="T111", user_id="U111") - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) @@ -85,9 +75,7 @@ def test_save_and_find(self): i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) bot = store.find_bot(enterprise_id="E111", team_id="T222") self.assertIsNone(bot) @@ -110,9 +98,7 @@ def test_org_installation(self): # find bots bot = store.find_bot(enterprise_id="EO111", team_id=None) self.assertIsNotNone(bot) - bot = store.find_bot( - enterprise_id="EO111", team_id="TO222", is_enterprise_install=True - ) + bot = store.find_bot(enterprise_id="EO111", team_id="TO222", is_enterprise_install=True) self.assertIsNotNone(bot) bot = store.find_bot(enterprise_id="EO111", team_id="TO222") self.assertIsNone(bot) @@ -131,18 +117,14 @@ def test_org_installation(self): # find installations i = store.find_installation(enterprise_id="EO111", team_id=None) self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="EO111", team_id="T111", is_enterprise_install=True - ) + i = store.find_installation(enterprise_id="EO111", team_id="T111", is_enterprise_install=True) self.assertIsNotNone(i) i = store.find_installation(enterprise_id="EO111", team_id="T222") self.assertIsNone(i) i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="EO111", team_id=None, user_id="UO111" - ) + i = store.find_installation(enterprise_id="EO111", team_id=None, user_id="UO111") self.assertIsNotNone(i) i = store.find_installation( enterprise_id="E111", @@ -228,24 +210,16 @@ def test_save_and_find_token_rotation(self): i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U222" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U222") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T222", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T222", user_id="U111") self.assertIsNone(i) # delete installations store.delete_installation(enterprise_id="E111", team_id="T111", user_id="U111") - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) @@ -256,9 +230,7 @@ def test_save_and_find_token_rotation(self): i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) bot = store.find_bot(enterprise_id="E111", team_id="T222") self.assertIsNone(bot) diff --git a/tests/slack_sdk/oauth/installation_store/test_sqlite3.py b/tests/slack_sdk/oauth/installation_store/test_sqlite3.py index 623ee4419..24e106be9 100644 --- a/tests/slack_sdk/oauth/installation_store/test_sqlite3.py +++ b/tests/slack_sdk/oauth/installation_store/test_sqlite3.py @@ -57,24 +57,16 @@ def test_save_and_find(self): i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U222" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U222") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T222", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T222", user_id="U111") self.assertIsNone(i) # delete installations store.delete_installation(enterprise_id="E111", team_id="T111", user_id="U111") - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) @@ -85,9 +77,7 @@ def test_save_and_find(self): i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) bot = store.find_bot(enterprise_id="E111", team_id="T222") self.assertIsNone(bot) @@ -109,9 +99,7 @@ def test_org_installation(self): # find bots bot = store.find_bot(enterprise_id="EO111", team_id=None) self.assertIsNotNone(bot) - bot = store.find_bot( - enterprise_id="EO111", team_id="TO222", is_enterprise_install=True - ) + bot = store.find_bot(enterprise_id="EO111", team_id="TO222", is_enterprise_install=True) self.assertIsNotNone(bot) bot = store.find_bot(enterprise_id="EO111", team_id="TO222") self.assertIsNone(bot) @@ -130,18 +118,14 @@ def test_org_installation(self): # find installations i = store.find_installation(enterprise_id="EO111", team_id=None) self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="EO111", team_id="T111", is_enterprise_install=True - ) + i = store.find_installation(enterprise_id="EO111", team_id="T111", is_enterprise_install=True) self.assertIsNotNone(i) i = store.find_installation(enterprise_id="EO111", team_id="T222") self.assertIsNone(i) i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="EO111", team_id=None, user_id="UO111" - ) + i = store.find_installation(enterprise_id="EO111", team_id=None, user_id="UO111") self.assertIsNotNone(i) i = store.find_installation( enterprise_id="E111", @@ -227,24 +211,16 @@ def test_save_and_find_token_rotation(self): i = store.find_installation(enterprise_id=None, team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNotNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U222" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U222") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T222", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T222", user_id="U111") self.assertIsNone(i) # delete installations store.delete_installation(enterprise_id="E111", team_id="T111", user_id="U111") - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) @@ -255,9 +231,7 @@ def test_save_and_find_token_rotation(self): i = store.find_installation(enterprise_id="E111", team_id="T111") self.assertIsNone(i) - i = store.find_installation( - enterprise_id="E111", team_id="T111", user_id="U111" - ) + i = store.find_installation(enterprise_id="E111", team_id="T111", user_id="U111") self.assertIsNone(i) bot = store.find_bot(enterprise_id="E111", team_id="T222") self.assertIsNone(bot) diff --git a/tests/slack_sdk/oauth/state_utils/test_utils.py b/tests/slack_sdk/oauth/state_utils/test_utils.py index 8fc1f192f..add49e3bc 100644 --- a/tests/slack_sdk/oauth/state_utils/test_utils.py +++ b/tests/slack_sdk/oauth/state_utils/test_utils.py @@ -13,28 +13,20 @@ def tearDown(self): def test_is_valid_browser(self): utils = OAuthStateUtils() cookie_name = OAuthStateUtils.default_cookie_name - result = utils.is_valid_browser( - "state-value", {"cookie": f"{cookie_name}=state-value"} - ) + result = utils.is_valid_browser("state-value", {"cookie": f"{cookie_name}=state-value"}) self.assertTrue(result) result = utils.is_valid_browser("state-value", {"cookie": f"{cookie_name}=xxx"}) self.assertFalse(result) - result = utils.is_valid_browser( - "state-value", {"cookie": [f"{cookie_name}=state-value"]} - ) + result = utils.is_valid_browser("state-value", {"cookie": [f"{cookie_name}=state-value"]}) self.assertTrue(result) - result = utils.is_valid_browser( - "state-value", {"cookie": [f"{cookie_name}=xxx"]} - ) + result = utils.is_valid_browser("state-value", {"cookie": [f"{cookie_name}=xxx"]}) self.assertFalse(result) def test_build_set_cookie_for_new_state(self): utils = OAuthStateUtils() value = utils.build_set_cookie_for_new_state("state-value") - expected = ( - "slack-app-oauth-state=state-value; Secure; HttpOnly; Path=/; Max-Age=600" - ) + expected = "slack-app-oauth-state=state-value; Secure; HttpOnly; Path=/; Max-Age=600" self.assertEqual(expected, value) def test_build_set_cookie_for_deletion(self): diff --git a/tests/slack_sdk/oauth/token_rotation/test_token_rotator.py b/tests/slack_sdk/oauth/token_rotation/test_token_rotator.py index 969f43b4a..212cffc06 100644 --- a/tests/slack_sdk/oauth/token_rotation/test_token_rotator.py +++ b/tests/slack_sdk/oauth/token_rotation/test_token_rotator.py @@ -86,6 +86,4 @@ def test_refresh_error(self): bot_token_expires_in=43200, ) with self.assertRaises(SlackTokenRotationError): - token_rotator.perform_token_rotation( - installation=installation, minutes_before_expiration=60 * 24 * 365 - ) + token_rotator.perform_token_rotation(installation=installation, minutes_before_expiration=60 * 24 * 365) diff --git a/tests/slack_sdk/scim/mock_web_api_server.py b/tests/slack_sdk/scim/mock_web_api_server.py index 62e2b4c9a..aa50eb7d0 100644 --- a/tests/slack_sdk/scim/mock_web_api_server.py +++ b/tests/slack_sdk/scim/mock_web_api_server.py @@ -24,16 +24,12 @@ class MockHandler(SimpleHTTPRequestHandler): def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] - return self.pattern_for_language.search( - user_agent - ) and self.pattern_for_package_identifier.search(user_agent) + return self.pattern_for_language.search(user_agent) and self.pattern_for_package_identifier.search(user_agent) def is_valid_token(self): if self.path.startswith("oauth"): return True - return "Authorization" in self.headers and str( - self.headers["Authorization"] - ).startswith("Bearer xoxp-") + return "Authorization" in self.headers and str(self.headers["Authorization"]).startswith("Bearer xoxp-") def set_common_headers(self): self.send_header("content-type", "application/json;charset=utf-8") @@ -59,9 +55,7 @@ def _handle(self): self.send_response(429) self.send_header("retry-after", 1) self.set_common_headers() - self.wfile.write( - """{"ok": false, "error": "ratelimited"}""".encode("utf-8") - ) + self.wfile.write("""{"ok": false, "error": "ratelimited"}""".encode("utf-8")) return if self.is_valid_token() and self.is_valid_user_agent(): @@ -103,9 +97,7 @@ def stop(self): class MonitorThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self, daemon=True) self.handler = handler self.test = test @@ -117,9 +109,7 @@ def run(self) -> None: try: req = Request(f"{self.test.server_url}/received_requests.json") resp = urlopen(req, timeout=1) - self.test.mock_received_requests = json.loads( - resp.read().decode("utf-8") - ) + self.test.mock_received_requests = json.loads(resp.read().decode("utf-8")) except Exception as e: # skip logging for the initial request if self.test.mock_received_requests is not None: @@ -132,9 +122,7 @@ def stop(self): class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self) self.handler = handler self.test = test diff --git a/tests/slack_sdk/scim/test_client.py b/tests/slack_sdk/scim/test_client.py index bf99d4b2a..79a000666 100644 --- a/tests/slack_sdk/scim/test_client.py +++ b/tests/slack_sdk/scim/test_client.py @@ -59,9 +59,7 @@ def test_groups(self): client.create_group(group) # The mock server does not work for PATH requests try: - client.patch_group( - "S111", partial_group=Group(display_name=f"TestGroup_{now}_2") - ) + client.patch_group("S111", partial_group=Group(display_name=f"TestGroup_{now}_2")) except: pass group.id = "S111" diff --git a/tests/slack_sdk/signature/test_signature_verifier.py b/tests/slack_sdk/signature/test_signature_verifier.py index 3b5628a40..be3a0b72b 100644 --- a/tests/slack_sdk/signature/test_signature_verifier.py +++ b/tests/slack_sdk/signature/test_signature_verifier.py @@ -21,9 +21,7 @@ def tearDown(self): body = "token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J&team_domain=testteamnow&channel_id=G8PSS9T3V&channel_name=foobar&user_id=U2CERLKJA&user_name=roadrunner&command=%2Fwebhook-collect&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT1DC2JH3J%2F397700885554%2F96rGlfmibIGlgcZRskXaIFfN&trigger_id=398738663015.47445629121.803a0bc887a14d10d2c447fce8b6703c" timestamp = "1531420618" - valid_signature = ( - "v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503" - ) + valid_signature = "v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503" headers = { "X-Slack-Request-Timestamp": timestamp, @@ -32,31 +30,21 @@ def tearDown(self): def test_generate_signature(self): verifier = SignatureVerifier(self.signing_secret) - signature = verifier.generate_signature( - timestamp=self.timestamp, body=self.body - ) + signature = verifier.generate_signature(timestamp=self.timestamp, body=self.body) self.assertEqual(self.valid_signature, signature) def test_generate_signature_body_as_bytes(self): verifier = SignatureVerifier(self.signing_secret) - signature = verifier.generate_signature( - timestamp=self.timestamp, body=self.body.encode("utf-8") - ) + signature = verifier.generate_signature(timestamp=self.timestamp, body=self.body.encode("utf-8")) self.assertEqual(self.valid_signature, signature) def test_is_valid_request(self): - verifier = SignatureVerifier( - signing_secret=self.signing_secret, clock=MockClock() - ) + verifier = SignatureVerifier(signing_secret=self.signing_secret, clock=MockClock()) self.assertTrue(verifier.is_valid_request(self.body, self.headers)) def test_is_valid_request_body_as_bytes(self): - verifier = SignatureVerifier( - signing_secret=self.signing_secret, clock=MockClock() - ) - self.assertTrue( - verifier.is_valid_request(self.body.encode("utf-8"), self.headers) - ) + verifier = SignatureVerifier(signing_secret=self.signing_secret, clock=MockClock()) + self.assertTrue(verifier.is_valid_request(self.body.encode("utf-8"), self.headers)) def test_is_valid_request_invalid_body(self): verifier = SignatureVerifier( @@ -72,9 +60,7 @@ def test_is_valid_request_invalid_body_as_bytes(self): clock=MockClock(), ) modified_body = self.body + "------" - self.assertFalse( - verifier.is_valid_request(modified_body.encode("utf-8"), self.headers) - ) + self.assertFalse(verifier.is_valid_request(modified_body.encode("utf-8"), self.headers)) def test_is_valid_request_expiration(self): verifier = SignatureVerifier( @@ -96,9 +82,7 @@ def test_is_valid(self): signing_secret=self.signing_secret, clock=MockClock(), ) - self.assertTrue( - verifier.is_valid(self.body, self.timestamp, self.valid_signature) - ) + self.assertTrue(verifier.is_valid(self.body, self.timestamp, self.valid_signature)) self.assertTrue(verifier.is_valid(self.body, 1531420618, self.valid_signature)) def test_is_valid_none(self): diff --git a/tests/slack_sdk/socket_mode/mock_web_api_server.py b/tests/slack_sdk/socket_mode/mock_web_api_server.py index 9439eec33..b0fffef84 100644 --- a/tests/slack_sdk/socket_mode/mock_web_api_server.py +++ b/tests/slack_sdk/socket_mode/mock_web_api_server.py @@ -26,9 +26,7 @@ class MockHandler(SimpleHTTPRequestHandler): def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] - return self.pattern_for_language.search( - user_agent - ) and self.pattern_for_package_identifier.search(user_agent) + return self.pattern_for_language.search(user_agent) and self.pattern_for_package_identifier.search(user_agent) def is_valid_token(self): if self.path.startswith("oauth"): @@ -68,16 +66,12 @@ def _handle(self): if post_body.startswith("{"): request_body = json.loads(post_body) else: - request_body = { - k: v[0] for k, v in parse_qs(post_body).items() - } + request_body = {k: v[0] for k, v in parse_qs(post_body).items()} except UnicodeDecodeError: pass else: if parsed_path and parsed_path.query: - request_body = { - k: v[0] for k, v in parse_qs(parsed_path.query).items() - } + request_body = {k: v[0] for k, v in parse_qs(parsed_path.query).items()} body = {"ok": False, "error": "internal_error"} if self.path == "/auth.test": @@ -144,9 +138,7 @@ def stop(self): class MonitorThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self, daemon=True) self.handler = handler self.test = test @@ -158,9 +150,7 @@ def run(self) -> None: try: req = Request(f"{self.test.server_url}/received_requests.json") resp = urlopen(req, timeout=1) - self.test.mock_received_requests = json.loads( - resp.read().decode("utf-8") - ) + self.test.mock_received_requests = json.loads(resp.read().decode("utf-8")) except Exception as e: # skip logging for the initial request if self.test.mock_received_requests is not None: @@ -173,9 +163,7 @@ def stop(self): class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self) self.handler = handler self.test = test diff --git a/tests/slack_sdk/socket_mode/test_builtin.py b/tests/slack_sdk/socket_mode/test_builtin.py index 4a2fa24dc..66777208f 100644 --- a/tests/slack_sdk/socket_mode/test_builtin.py +++ b/tests/slack_sdk/socket_mode/test_builtin.py @@ -42,9 +42,7 @@ def tearDown(self): def test_init_close(self): on_message_listeners = [lambda message: None] - client = SocketModeClient( - app_token="xapp-A111-222-xyz", on_message_listeners=on_message_listeners - ) + client = SocketModeClient(app_token="xapp-A111-222-xyz", on_message_listeners=on_message_listeners) try: self.assertIsNotNone(client) self.assertFalse(client.is_connected()) @@ -60,9 +58,7 @@ def test_issue_new_wss_url(self): url = client.issue_new_wss_url() self.assertTrue(url.startswith("wss://")) - legacy_client = LegacyWebClient( - token="xoxb-api_test", base_url="http://localhost:8888" - ) + legacy_client = LegacyWebClient(token="xoxb-api_test", base_url="http://localhost:8888") response = legacy_client.apps_connections_open(app_token="xapp-A111-222-xyz") self.assertIsNotNone(response["url"]) diff --git a/tests/slack_sdk/socket_mode/test_builtin_message_parser.py b/tests/slack_sdk/socket_mode/test_builtin_message_parser.py index 96a4cfd70..096bd7d04 100644 --- a/tests/slack_sdk/socket_mode/test_builtin_message_parser.py +++ b/tests/slack_sdk/socket_mode/test_builtin_message_parser.py @@ -21,13 +21,9 @@ def receive(): self.assertEqual(len(messages), 3) self.assertEqual(messages[0], (None, b"\n")) self.assertEqual(messages[1][0].opcode, FrameHeader.OPCODE_PONG) - self.assertEqual( - messages[1][1], b"230b6da2-4280-46b3-9ab0-986d4093c5a1:1610196543.3950982" - ) + self.assertEqual(messages[1][1], b"230b6da2-4280-46b3-9ab0-986d4093c5a1:1610196543.3950982") self.assertEqual(messages[2][0].opcode, FrameHeader.OPCODE_PONG) - self.assertEqual( - messages[2][1], b"230b6da2-4280-46b3-9ab0-986d4093c5a1:1610196543.395274" - ) + self.assertEqual(messages[2][1], b"230b6da2-4280-46b3-9ab0-986d4093c5a1:1610196543.395274") def test_parse_test_server_response_2(self): socket_data = [ diff --git a/tests/slack_sdk/socket_mode/test_interactions_builtin.py b/tests/slack_sdk/socket_mode/test_interactions_builtin.py index a980c5141..529b66808 100644 --- a/tests/slack_sdk/socket_mode/test_interactions_builtin.py +++ b/tests/slack_sdk/socket_mode/test_interactions_builtin.py @@ -52,9 +52,7 @@ def test_interactions(self): time.sleep(2) # wait for the server try: - buffer_size_list = [1024, 9000, 35, 49] + list( - [randint(16, 128) for _ in range(10)] - ) + buffer_size_list = [1024, 9000, 35, 49] + list([randint(16, 128) for _ in range(10)]) for buffer_size in buffer_size_list: self.reset_sever_state() @@ -66,9 +64,7 @@ def message_handler(message): time.sleep(randint(50, 200) / 1000) received_messages.append(message) - def socket_mode_request_handler( - client: BaseSocketModeClient, request: SocketModeRequest - ): + def socket_mode_request_handler(client: BaseSocketModeClient, request: SocketModeRequest): self.logger.info(f"Socket Mode Request: {request}") time.sleep(randint(50, 200) / 1000) received_socket_mode_requests.append(request) @@ -83,9 +79,7 @@ def socket_mode_request_handler( trace_enabled=True, ) try: - client.socket_mode_request_listeners.append( - socket_mode_request_handler - ) + client.socket_mode_request_listeners.append(socket_mode_request_handler) client.wss_uri = "ws://0.0.0.0:3011/link" client.connect() self.assertTrue(client.is_connected()) @@ -98,28 +92,20 @@ def socket_mode_request_handler( client.send_message("baz") self.assertTrue(client.is_connected()) - expected = ( - socket_mode_envelopes - + [socket_mode_hello_message] - + ["foo", "bar", "baz"] * repeat - ) + expected = socket_mode_envelopes + [socket_mode_hello_message] + ["foo", "bar", "baz"] * repeat expected.sort() count = 0 while count < 5 and len(received_messages) < len(expected): time.sleep(0.1) - self.logger.debug( - f"Received messages: {len(received_messages)}" - ) + self.logger.debug(f"Received messages: {len(received_messages)}") count += 0.1 received_messages.sort() self.assertEqual(len(received_messages), len(expected)) self.assertEqual(received_messages, expected) - self.assertEqual( - len(socket_mode_envelopes), len(received_socket_mode_requests) - ) + self.assertEqual(len(socket_mode_envelopes), len(received_socket_mode_requests)) finally: pass # client.close() diff --git a/tests/slack_sdk/socket_mode/test_interactions_websocket_client.py b/tests/slack_sdk/socket_mode/test_interactions_websocket_client.py index 37b97c07a..43be7fc7d 100644 --- a/tests/slack_sdk/socket_mode/test_interactions_websocket_client.py +++ b/tests/slack_sdk/socket_mode/test_interactions_websocket_client.py @@ -52,9 +52,7 @@ def message_handler(ws_app, message): time.sleep(randint(50, 200) / 1000) received_messages.append(message) - def socket_mode_request_handler( - client: BaseSocketModeClient, request: SocketModeRequest - ): + def socket_mode_request_handler(client: BaseSocketModeClient, request: SocketModeRequest): self.logger.info(f"Socket Mode Request: {request}") time.sleep(randint(50, 200) / 1000) received_socket_mode_requests.append(request) @@ -81,11 +79,7 @@ def socket_mode_request_handler( client.send_message("baz") self.assertTrue(client.is_connected()) - expected = ( - socket_mode_envelopes - + [socket_mode_hello_message] - + ["foo", "bar", "baz"] * 10 - ) + expected = socket_mode_envelopes + [socket_mode_hello_message] + ["foo", "bar", "baz"] * 10 expected.sort() count = 0 @@ -96,9 +90,7 @@ def socket_mode_request_handler( received_messages.sort() self.assertEqual(received_messages, expected) - self.assertEqual( - len(socket_mode_envelopes), len(received_socket_mode_requests) - ) + self.assertEqual(len(socket_mode_envelopes), len(received_socket_mode_requests)) finally: client.close() self.server.stop() diff --git a/tests/slack_sdk/socket_mode/test_response.py b/tests/slack_sdk/socket_mode/test_response.py index ee09c38e2..fa5af71bc 100644 --- a/tests/slack_sdk/socket_mode/test_response.py +++ b/tests/slack_sdk/socket_mode/test_response.py @@ -21,6 +21,4 @@ def test_parser(self): def test_to_dict(self): response = SocketModeResponse(envelope_id="xxx", payload={"text": "hi"}) - self.assertDictEqual( - response.to_dict(), {"envelope_id": "xxx", "payload": {"text": "hi"}} - ) + self.assertDictEqual(response.to_dict(), {"envelope_id": "xxx", "payload": {"text": "hi"}}) diff --git a/tests/slack_sdk/web/mock_web_api_server.py b/tests/slack_sdk/web/mock_web_api_server.py index df36e993d..5cfd3f63c 100644 --- a/tests/slack_sdk/web/mock_web_api_server.py +++ b/tests/slack_sdk/web/mock_web_api_server.py @@ -32,16 +32,12 @@ class MockHandler(SimpleHTTPRequestHandler): def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] - return self.pattern_for_language.search( - user_agent - ) and self.pattern_for_package_identifier.search(user_agent) + return self.pattern_for_language.search(user_agent) and self.pattern_for_package_identifier.search(user_agent) def is_valid_token(self): if self.path.startswith("oauth"): return True - return "Authorization" in self.headers and str( - self.headers["Authorization"] - ).startswith("Bearer xoxb-") + return "Authorization" in self.headers and str(self.headers["Authorization"]).startswith("Bearer xoxb-") def set_common_headers(self): self.send_header("content-type", "application/json;charset=utf-8") @@ -94,16 +90,11 @@ def _handle(self): if self.headers["authorization"] == "Basic MTExLjIyMjpzZWNyZXQ=": self.wfile.write("""{"ok":true}""".encode("utf-8")) return - elif ( - self.headers["authorization"] - == "Basic MTExLjIyMjp0b2tlbl9yb3RhdGlvbl9zZWNyZXQ=" - ): + elif self.headers["authorization"] == "Basic MTExLjIyMjp0b2tlbl9yb3RhdGlvbl9zZWNyZXQ=": self.wfile.write(json.dumps(self.token_refresh).encode("utf-8")) return else: - self.wfile.write( - """{"ok":false, "error":"invalid"}""".encode("utf-8") - ) + self.wfile.write("""{"ok":false, "error":"invalid"}""".encode("utf-8")) return header = self.headers["Authorization"] @@ -117,9 +108,7 @@ def _handle(self): self.send_response(429) self.send_header("retry-after", 1) self.set_common_headers() - self.wfile.write( - """{"ok": false, "error": "ratelimited"}""".encode("utf-8") - ) + self.wfile.write("""{"ok": false, "error": "ratelimited"}""".encode("utf-8")) return if self.is_valid_token() and self.is_valid_user_agent(): @@ -135,16 +124,12 @@ def _handle(self): if post_body.startswith("{"): request_body = json.loads(post_body) else: - request_body = { - k: v[0] for k, v in parse_qs(post_body).items() - } + request_body = {k: v[0] for k, v in parse_qs(post_body).items()} except UnicodeDecodeError: pass else: if parsed_path and parsed_path.query: - request_body = { - k: v[0] for k, v in parse_qs(parsed_path.query).items() - } + request_body = {k: v[0] for k, v in parse_qs(parsed_path.query).items()} header = self.headers["authorization"] pattern = str(header).split("xoxb-", 1)[1] @@ -155,8 +140,7 @@ def _handle(self): return if pattern == "rate_limited" or ( - pattern == "rate_limited_only_once" - and self.state["rate_limited_count"] == 0 + pattern == "rate_limited_only_once" and self.state["rate_limited_count"] == 0 ): self.state["rate_limited_count"] += 1 self.send_response(429) @@ -164,9 +148,7 @@ def _handle(self): self.send_header("content-type", "application/json;charset=utf-8") self.send_header("connection", "close") self.end_headers() - self.wfile.write( - """{"ok":false,"error":"rate_limited"}""".encode("utf-8") - ) + self.wfile.write("""{"ok":false,"error":"rate_limited"}""".encode("utf-8")) self.wfile.close() return @@ -208,11 +190,7 @@ def _handle(self): else: self.send_response(400) self.set_common_headers() - self.wfile.write( - """{"ok":false, "error":"invalid_user_agent"}""".encode( - "utf-8" - ) - ) + self.wfile.write("""{"ok":false, "error":"invalid_user_agent"}""".encode("utf-8")) self.wfile.close() return @@ -232,17 +210,11 @@ def _handle(self): if request_body: for k, v in request_body.items(): if k in ids: - if not re.compile(r"^[^,\[\]]+?,[^,\[\]]+$").match( - v - ): - raise Exception( - f"The parameter {k} is not a comma-separated string value: {v}" - ) + if not re.compile(r"^[^,\[\]]+?,[^,\[\]]+$").match(v): + raise Exception(f"The parameter {k} is not a comma-separated string value: {v}") body = {"ok": True, "method": parsed_path.path.replace("/", "")} else: - with open( - f"tests/slack_sdk_fixture/web_response_{pattern}.json" - ) as file: + with open(f"tests/slack_sdk_fixture/web_response_{pattern}.json") as file: body = json.load(file) if self.path == "/api.test" and request_body: @@ -291,9 +263,7 @@ def stop(self): class MonitorThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self, daemon=True) self.handler = handler self.test = test @@ -305,9 +275,7 @@ def run(self) -> None: try: req = Request(f"{self.test.server_url}/received_requests.json") resp = urlopen(req, timeout=1) - self.test.mock_received_requests = json.loads( - resp.read().decode("utf-8") - ) + self.test.mock_received_requests = json.loads(resp.read().decode("utf-8")) except Exception as e: # skip logging for the initial request if self.test.mock_received_requests is not None: @@ -320,9 +288,7 @@ def stop(self): class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self) self.handler = handler self.test = test diff --git a/tests/slack_sdk/web/mock_web_api_server_http_retry.py b/tests/slack_sdk/web/mock_web_api_server_http_retry.py index 7005a411c..5dbc92bd4 100644 --- a/tests/slack_sdk/web/mock_web_api_server_http_retry.py +++ b/tests/slack_sdk/web/mock_web_api_server_http_retry.py @@ -45,9 +45,7 @@ def _handle(self): self.send_response(429) self.send_header("retry-after", 1) self.set_common_headers() - self.wfile.write( - """{"ok":false,"error":"rate_limited"}""".encode("utf-8") - ) + self.wfile.write("""{"ok":false,"error":"rate_limited"}""".encode("utf-8")) self.wfile.close() return @@ -93,9 +91,7 @@ def stop(self): class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self) self.handler = handler self.test = test diff --git a/tests/slack_sdk/web/test_web_client.py b/tests/slack_sdk/web/test_web_client.py index 6737b95b9..e7eee5a29 100644 --- a/tests/slack_sdk/web/test_web_client.py +++ b/tests/slack_sdk/web/test_web_client.py @@ -98,9 +98,7 @@ def test_slack_api_rate_limiting_exception_returns_retry_after(self): def test_the_api_call_files_argument_creates_the_expected_data(self): self.client.token = "xoxb-users_setPhoto" - resp = self.client.users_setPhoto( - image="tests/slack_sdk_fixture/slack_logo.png" - ) + resp = self.client.users_setPhoto(image="tests/slack_sdk_fixture/slack_logo.png") self.assertEqual(200, resp.status_code) def test_issue_560_bool_in_params_sync(self): @@ -111,25 +109,17 @@ def test_issue_560_bool_in_params_sync(self): def test_issue_690_oauth_v2_access(self): self.client.token = "" - resp = self.client.oauth_v2_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = self.client.oauth_v2_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - self.client.oauth_v2_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + self.client.oauth_v2_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") def test_issue_690_oauth_access(self): self.client.token = "" - resp = self.client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = self.client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - self.client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + self.client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") def test_issue_705_no_param_request_pagination(self): self.client.token = "xoxb-users_list_pagination" @@ -159,9 +149,7 @@ def test_html_response_body_issue_718(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertTrue( - str(e).startswith( - "Received a response in a non-JSON format: None: try: req = Request(f"{self.test.server_url}/received_requests.json") resp = urlopen(req, timeout=1) - self.test.mock_received_requests = json.loads( - resp.read().decode("utf-8") - ) + self.test.mock_received_requests = json.loads(resp.read().decode("utf-8")) except Exception as e: # skip logging for the initial request if self.test.mock_received_requests is not None: @@ -148,9 +142,7 @@ def stop(self): class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self) self.handler = handler self.test = test diff --git a/tests/slack_sdk/webhook/test_webhook.py b/tests/slack_sdk/webhook/test_webhook.py index 0d4cb694d..42a7ac585 100644 --- a/tests/slack_sdk/webhook/test_webhook.py +++ b/tests/slack_sdk/webhook/test_webhook.py @@ -129,12 +129,7 @@ def test_send_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField( - title=f"field_{i}_title", value=f"field_{i}_value" - ) - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -167,9 +162,7 @@ def test_error_response(self): self.assertTrue(resp.body.startswith("")) def test_proxy_issue_714(self): - client = WebhookClient( - url="http://localhost:8888", proxy="http://invalid-host:9999" - ) + client = WebhookClient(url="http://localhost:8888", proxy="http://invalid-host:9999") with self.assertRaises(urllib.error.URLError): client.send_dict({"text": "hello!"}) diff --git a/tests/slack_sdk_async/audit_logs/test_async_client.py b/tests/slack_sdk_async/audit_logs/test_async_client.py index e4a5269c7..ab9eea734 100644 --- a/tests/slack_sdk_async/audit_logs/test_async_client.py +++ b/tests/slack_sdk_async/audit_logs/test_async_client.py @@ -11,9 +11,7 @@ class TestAsyncAuditLogsClient(unittest.TestCase): def setUp(self): - self.client = AsyncAuditLogsClient( - token="xoxp-", base_url="http://localhost:8888/" - ) + self.client = AsyncAuditLogsClient(token="xoxp-", base_url="http://localhost:8888/") setup_mock_web_api_server(self) def tearDown(self): @@ -29,9 +27,7 @@ async def test_logs(self): @async_test async def test_logs_pagination(self): - resp: AuditLogsResponse = await self.client.logs( - limit=1, action="user_login", cursor="XXXXXXXXXXX" - ) + resp: AuditLogsResponse = await self.client.logs(limit=1, action="user_login", cursor="XXXXXXXXXXX") self.assertEqual(200, resp.status_code) self.assertIsNotNone(resp.body.get("entries")) diff --git a/tests/slack_sdk_async/oauth/installation_store/test_simple_cache.py b/tests/slack_sdk_async/oauth/installation_store/test_simple_cache.py index 1dab897c0..c1f43f4e4 100644 --- a/tests/slack_sdk_async/oauth/installation_store/test_simple_cache.py +++ b/tests/slack_sdk_async/oauth/installation_store/test_simple_cache.py @@ -12,9 +12,7 @@ class TestCacheable(unittest.TestCase): @async_test async def test_save_and_find(self): - sqlite3_store = SQLite3InstallationStore( - database="logs/cacheable.db", client_id="111.222" - ) + sqlite3_store = SQLite3InstallationStore(database="logs/cacheable.db", client_id="111.222") sqlite3_store.init() store = AsyncCacheableInstallationStore(sqlite3_store) @@ -42,9 +40,7 @@ async def test_save_and_find(self): @async_test async def test_save_and_find_token_rotation(self): - sqlite3_store = SQLite3InstallationStore( - database="logs/cacheable.db", client_id="111.222" - ) + sqlite3_store = SQLite3InstallationStore(database="logs/cacheable.db", client_id="111.222") sqlite3_store.init() store = AsyncCacheableInstallationStore(sqlite3_store) diff --git a/tests/slack_sdk_async/oauth/token_rotation/test_token_rotator.py b/tests/slack_sdk_async/oauth/token_rotation/test_token_rotator.py index c4d68f7d9..f379de925 100644 --- a/tests/slack_sdk_async/oauth/token_rotation/test_token_rotator.py +++ b/tests/slack_sdk_async/oauth/token_rotation/test_token_rotator.py @@ -90,6 +90,4 @@ async def test_refresh_error(self): bot_token_expires_in=43200, ) with self.assertRaises(SlackTokenRotationError): - await token_rotator.perform_token_rotation( - installation=installation, minutes_before_expiration=60 * 24 * 365 - ) + await token_rotator.perform_token_rotation(installation=installation, minutes_before_expiration=60 * 24 * 365) diff --git a/tests/slack_sdk_async/scim/test_async_client.py b/tests/slack_sdk_async/scim/test_async_client.py index 80b0e124e..1d38a673a 100644 --- a/tests/slack_sdk_async/scim/test_async_client.py +++ b/tests/slack_sdk_async/scim/test_async_client.py @@ -63,9 +63,7 @@ async def test_groups(self): await client.create_group(group) # The mock server does not work for PATH requests try: - await client.patch_group( - "S111", partial_group=Group(display_name=f"TestGroup_{now}_2") - ) + await client.patch_group("S111", partial_group=Group(display_name=f"TestGroup_{now}_2")) except: pass group.id = "S111" diff --git a/tests/slack_sdk_async/socket_mode/test_interactions_aiohttp.py b/tests/slack_sdk_async/socket_mode/test_interactions_aiohttp.py index dae257075..9903ce488 100644 --- a/tests/slack_sdk_async/socket_mode/test_interactions_aiohttp.py +++ b/tests/slack_sdk_async/socket_mode/test_interactions_aiohttp.py @@ -82,11 +82,7 @@ async def socket_mode_listener( await client.send_message("bar") await client.send_message("baz") - expected = ( - socket_mode_envelopes - + [socket_mode_hello_message] - + ["foo", "bar", "baz"] * 10 - ) + expected = socket_mode_envelopes + [socket_mode_hello_message] + ["foo", "bar", "baz"] * 10 expected.sort() expected.sort() @@ -98,9 +94,7 @@ async def socket_mode_listener( received_messages.sort() self.assertEqual(received_messages, expected) - self.assertEqual( - len(socket_mode_envelopes), len(received_socket_mode_requests) - ) + self.assertEqual(len(socket_mode_envelopes), len(received_socket_mode_requests)) finally: await client.close() self.server.stop() diff --git a/tests/slack_sdk_async/socket_mode/test_interactions_websockets.py b/tests/slack_sdk_async/socket_mode/test_interactions_websockets.py index a149a6937..a935c0f3c 100644 --- a/tests/slack_sdk_async/socket_mode/test_interactions_websockets.py +++ b/tests/slack_sdk_async/socket_mode/test_interactions_websockets.py @@ -86,11 +86,7 @@ async def socket_mode_listener( await client.send_message("bar") await client.send_message("baz") - expected = ( - socket_mode_envelopes - + [socket_mode_hello_message] - + ["foo", "bar", "baz"] * 10 - ) + expected = socket_mode_envelopes + [socket_mode_hello_message] + ["foo", "bar", "baz"] * 10 expected.sort() count = 0 @@ -101,9 +97,7 @@ async def socket_mode_listener( received_messages.sort() self.assertEqual(received_messages, expected) - self.assertEqual( - len(socket_mode_envelopes), len(received_socket_mode_requests) - ) + self.assertEqual(len(socket_mode_envelopes), len(received_socket_mode_requests)) finally: await client.close() self.server.stop() diff --git a/tests/slack_sdk_async/web/test_async_web_client.py b/tests/slack_sdk_async/web/test_async_web_client.py index 4ca9b3e43..236f3e9f6 100644 --- a/tests/slack_sdk_async/web/test_async_web_client.py +++ b/tests/slack_sdk_async/web/test_async_web_client.py @@ -77,9 +77,7 @@ async def test_slack_api_rate_limiting_exception_returns_retry_after(self): @async_test async def test_the_api_call_files_argument_creates_the_expected_data(self): self.client.token = "xoxb-users_setPhoto" - resp = await self.client.users_setPhoto( - image="tests/slack_sdk_fixture/slack_logo.png" - ) + resp = await self.client.users_setPhoto(image="tests/slack_sdk_fixture/slack_logo.png") self.assertEqual(200, resp.status_code) @async_test @@ -108,14 +106,10 @@ async def test_issue_690_oauth_v2_access_async(self): @async_test async def test_issue_690_oauth_access_async(self): self.client.token = "" - resp = await self.client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = await self.client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - await self.client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + await self.client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_token_param_async(self): diff --git a/tests/slack_sdk_async/web/test_web_client_coverage.py b/tests/slack_sdk_async/web/test_web_client_coverage.py index 7dd11f6c9..9456cdcc8 100644 --- a/tests/slack_sdk_async/web/test_web_client_coverage.py +++ b/tests/slack_sdk_async/web/test_web_client_coverage.py @@ -26,15 +26,9 @@ class TestWebClientCoverage(unittest.TestCase): def setUp(self): setup_mock_web_api_server(self) - self.client = slack_sdk.web.WebClient( - token="xoxb-coverage", base_url="http://localhost:8888" - ) - self.legacy_client = LegacyWebClient( - token="xoxb-coverage", base_url="http://localhost:8888" - ) - self.async_client = AsyncWebClient( - token="xoxb-coverage", base_url="http://localhost:8888" - ) + self.client = slack_sdk.web.WebClient(token="xoxb-coverage", base_url="http://localhost:8888") + self.legacy_client = LegacyWebClient(token="xoxb-coverage", base_url="http://localhost:8888") + self.async_client = AsyncWebClient(token="xoxb-coverage", base_url="http://localhost:8888") self.api_methods_to_call = [] for api_method in self.all_api_methods: @@ -65,45 +59,27 @@ async def run_method(self, method_name, method, async_method): # Run the api calls with required arguments if callable(method): if method_name == "admin_analytics_getFile": - self.api_methods_to_call.remove( - method(date="2020-09-01", type="member")["method"] - ) + self.api_methods_to_call.remove(method(date="2020-09-01", type="member")["method"]) await async_method(date="2020-09-01", type="member") elif method_name == "admin_apps_approve": - self.api_methods_to_call.remove( - method(app_id="AID123", request_id="RID123")["method"] - ) + self.api_methods_to_call.remove(method(app_id="AID123", request_id="RID123")["method"]) await async_method(app_id="AID123", request_id="RID123") elif method_name == "admin_apps_restrict": - self.api_methods_to_call.remove( - method(app_id="AID123", request_id="RID123")["method"] - ) + self.api_methods_to_call.remove(method(app_id="AID123", request_id="RID123")["method"]) await async_method(app_id="AID123", request_id="RID123") elif method_name == "admin_apps_uninstall": self.api_methods_to_call.remove( - method( - app_id="AID123", enterprise_id="E111", team_ids=["T1", "T2"] - )["method"] - ) - await async_method( - app_id="AID123", enterprise_id="E111", team_ids=["T1", "T2"] + method(app_id="AID123", enterprise_id="E111", team_ids=["T1", "T2"])["method"] ) + await async_method(app_id="AID123", enterprise_id="E111", team_ids=["T1", "T2"]) elif method_name == "admin_apps_requests_cancel": - self.api_methods_to_call.remove( - method(request_id="XXX", enterprise_id="E111", team_id="T123")[ - "method" - ] - ) - await async_method( - request_id="XXX", enterprise_id="E111", team_id="T123" - ) + self.api_methods_to_call.remove(method(request_id="XXX", enterprise_id="E111", team_id="T123")["method"]) + await async_method(request_id="XXX", enterprise_id="E111", team_id="T123") elif method_name == "admin_apps_clearResolution": self.api_methods_to_call.remove(method(app_id="AID123")["method"]) await async_method(app_id="AID123") elif method_name == "admin_auth_policy_getEntities": - self.api_methods_to_call.remove( - method(policy_name="policyname")["method"] - ) + self.api_methods_to_call.remove(method(policy_name="policyname")["method"]) await async_method(policy_name="policyname") elif method_name == "admin_auth_policy_assignEntities": self.api_methods_to_call.remove( @@ -113,9 +89,7 @@ async def run_method(self, method_name, method, async_method): policy_name="policyname", )["method"] ) - await async_method( - entity_ids=["1", "2"], entity_type="type", policy_name="policyname" - ) + await async_method(entity_ids=["1", "2"], entity_type="type", policy_name="policyname") elif method_name == "admin_auth_policy_removeEntities": self.api_methods_to_call.remove( method( @@ -124,9 +98,7 @@ async def run_method(self, method_name, method, async_method): policy_name="policyname", )["method"] ) - await async_method( - entity_ids=["1", "2"], entity_type="type", policy_name="policyname" - ) + await async_method(entity_ids=["1", "2"], entity_type="type", policy_name="policyname") elif method_name == "admin_barriers_create": self.api_methods_to_call.remove( method( @@ -159,42 +131,28 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(barrier_id="AAA")["method"]) await async_method(barrier_id="AAA") elif method_name == "admin_emoji_add": - self.api_methods_to_call.remove( - method(name="eyes", url="https://www.example.com/")["method"] - ) + self.api_methods_to_call.remove(method(name="eyes", url="https://www.example.com/")["method"]) await async_method(name="eyes", url="https://www.example.com/") elif method_name == "admin_emoji_addAlias": - self.api_methods_to_call.remove( - method(name="watching", alias_for="eyes")["method"] - ) + self.api_methods_to_call.remove(method(name="watching", alias_for="eyes")["method"]) await async_method(name="watching", alias_for="eyes") elif method_name == "admin_emoji_remove": self.api_methods_to_call.remove(method(name="eyes")["method"]) await async_method(name="eyes") elif method_name == "admin_emoji_rename": - self.api_methods_to_call.remove( - method(name="eyes", new_name="eyez")["method"] - ) + self.api_methods_to_call.remove(method(name="eyes", new_name="eyez")["method"]) await async_method(name="eyes", new_name="eyez") elif method_name == "admin_inviteRequests_approve": - self.api_methods_to_call.remove( - method(invite_request_id="ID123")["method"] - ) + self.api_methods_to_call.remove(method(invite_request_id="ID123")["method"]) await async_method(invite_request_id="ID123") elif method_name == "admin_inviteRequests_deny": - self.api_methods_to_call.remove( - method(invite_request_id="ID123")["method"] - ) + self.api_methods_to_call.remove(method(invite_request_id="ID123")["method"]) await async_method(invite_request_id="ID123") elif method_name == "admin_teams_admins_list": self.api_methods_to_call.remove(method(team_id="T123")["method"]) await async_method(team_id="T123") elif method_name == "admin_teams_create": - self.api_methods_to_call.remove( - method(team_domain="awesome-team", team_name="Awesome Team")[ - "method" - ] - ) + self.api_methods_to_call.remove(method(team_domain="awesome-team", team_name="Awesome Team")["method"]) await async_method(team_domain="awesome-team", team_name="Awesome Team") elif method_name == "admin_teams_owners_list": self.api_methods_to_call.remove(method(team_id="T123")["method"]) @@ -203,26 +161,18 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(team_id="T123")["method"]) await async_method(team_id="T123") elif method_name == "admin_teams_settings_setDefaultChannels": - self.api_methods_to_call.remove( - method(team_id="T123", channel_ids=["C123", "C234"])["method"] - ) + self.api_methods_to_call.remove(method(team_id="T123", channel_ids=["C123", "C234"])["method"]) # checking tuple compatibility as sample method(team_id="T123", channel_ids=("C123", "C234")) method(team_id="T123", channel_ids="C123,C234") await async_method(team_id="T123", channel_ids="C123,C234") elif method_name == "admin_teams_settings_setDescription": self.api_methods_to_call.remove( - method(team_id="T123", description="Workspace for an awesome team")[ - "method" - ] - ) - await async_method( - team_id="T123", description="Workspace for an awesome team" + method(team_id="T123", description="Workspace for an awesome team")["method"] ) + await async_method(team_id="T123", description="Workspace for an awesome team") elif method_name == "admin_teams_settings_setDiscoverability": - self.api_methods_to_call.remove( - method(team_id="T123", discoverability="invite_only")["method"] - ) + self.api_methods_to_call.remove(method(team_id="T123", discoverability="invite_only")["method"]) await async_method(team_id="T123", discoverability="invite_only") elif method_name == "admin_teams_settings_setIcon": self.api_methods_to_call.remove( @@ -236,9 +186,7 @@ async def run_method(self, method_name, method, async_method): image_url="https://www.example.com/images/dummy.png", ) elif method_name == "admin_teams_settings_setName": - self.api_methods_to_call.remove( - method(team_id="T123", name="Awesome Engineering Team")["method"] - ) + self.api_methods_to_call.remove(method(team_id="T123", name="Awesome Engineering Team")["method"]) await async_method(team_id="T123", name="Awesome Engineering Team") elif method_name == "admin_usergroups_addChannels": self.api_methods_to_call.remove( @@ -284,9 +232,7 @@ async def run_method(self, method_name, method, async_method): method(usergroup_id="S123", include_num_members=False, team_id="T123") method(usergroup_id="S123", include_num_members="0", team_id="T123") method(usergroup_id="S123", include_num_members=0, team_id="T123") - await async_method( - usergroup_id="S123", include_num_members=0, team_id="T123" - ) + await async_method(usergroup_id="S123", include_num_members=0, team_id="T123") elif method_name == "admin_usergroups_removeChannels": self.api_methods_to_call.remove( method( @@ -306,9 +252,7 @@ async def run_method(self, method_name, method, async_method): channel_ids="C1A2B3C4D,C26Z25Y24", ) elif method_name == "admin_users_assign": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) await async_method(team_id="T123", user_id="W123") elif method_name == "admin_users_invite": self.api_methods_to_call.remove( @@ -332,34 +276,22 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(team_id="T123")["method"]) await async_method(team_id="T123") elif method_name == "admin_users_remove": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) await async_method(team_id="T123", user_id="W123") elif method_name == "admin_users_setAdmin": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) await async_method(team_id="T123", user_id="W123") elif method_name == "admin_users_setExpiration": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123", expiration_ts=123)["method"] - ) + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123", expiration_ts=123)["method"]) await async_method(team_id="T123", user_id="W123", expiration_ts=123) elif method_name == "admin_users_setOwner": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) await async_method(team_id="T123", user_id="W123") elif method_name == "admin_users_setRegular": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) await async_method(team_id="T123", user_id="W123") elif method_name == "admin_users_session_invalidate": - self.api_methods_to_call.remove( - method(session_id="XXX", team_id="T111")["method"] - ) + self.api_methods_to_call.remove(method(session_id="XXX", team_id="T111")["method"]) await async_method(session_id="XXX", team_id="T111") elif method_name == "admin_users_session_reset": self.api_methods_to_call.remove(method(user_id="W123")["method"]) @@ -382,31 +314,19 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(event_context="xxx")["method"]) await async_method(event_context="xxx") elif method_name == "apps_uninstall": - self.api_methods_to_call.remove( - method(client_id="111.222", client_secret="xxx")["method"] - ) + self.api_methods_to_call.remove(method(client_id="111.222", client_secret="xxx")["method"]) await async_method(client_id="111.222", client_secret="xxx") elif method_name == "bookmarks_add": - self.api_methods_to_call.remove( - method(channel_id="C1234", title="bedtime story", type="article")[ - "method" - ] - ) - await async_method( - channel_id="C1234", title="bedtime story", type="article" - ) + self.api_methods_to_call.remove(method(channel_id="C1234", title="bedtime story", type="article")["method"]) + await async_method(channel_id="C1234", title="bedtime story", type="article") elif method_name == "bookmarks_edit": - self.api_methods_to_call.remove( - method(bookmark_id="B1234", channel_id="C1234")["method"] - ) + self.api_methods_to_call.remove(method(bookmark_id="B1234", channel_id="C1234")["method"]) await async_method(bookmark_id="B1234", channel_id="C1234") elif method_name == "bookmarks_list": self.api_methods_to_call.remove(method(channel_id="C1234")["method"]) await async_method(channel_id="C1234") elif method_name == "bookmarks_remove": - self.api_methods_to_call.remove( - method(bookmark_id="B1234", channel_id="C1234")["method"] - ) + self.api_methods_to_call.remove(method(bookmark_id="B1234", channel_id="C1234")["method"]) await async_method(bookmark_id="B1234", channel_id="C1234") elif method_name == "calls_add": self.api_methods_to_call.remove( @@ -479,71 +399,47 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(id="R111")["method"]) await async_method(id="R111") elif method_name == "chat_delete": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) await async_method(channel="C123", ts="123.123") elif method_name == "chat_deleteScheduledMessage": - self.api_methods_to_call.remove( - method(channel="C123", scheduled_message_id="123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", scheduled_message_id="123")["method"]) await async_method(channel="C123", scheduled_message_id="123") elif method_name == "chat_getPermalink": - self.api_methods_to_call.remove( - method(channel="C123", message_ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", message_ts="123.123")["method"]) await async_method(channel="C123", message_ts="123.123") elif method_name == "chat_meMessage": - self.api_methods_to_call.remove( - method(channel="C123", text=":wave: Hi there!")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", text=":wave: Hi there!")["method"]) await async_method(channel="C123", text=":wave: Hi there!") elif method_name == "chat_postEphemeral": - self.api_methods_to_call.remove( - method(channel="C123", user="U123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", user="U123")["method"]) await async_method(channel="C123", user="U123") elif method_name == "chat_postMessage": self.api_methods_to_call.remove(method(channel="C123")["method"]) await async_method(channel="C123") elif method_name == "chat_scheduleMessage": - self.api_methods_to_call.remove( - method(channel="C123", post_at=123, text="Hi")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", post_at=123, text="Hi")["method"]) await async_method(channel="C123", post_at=123, text="Hi") elif method_name == "chat_unfurl": self.api_methods_to_call.remove( method( channel="C123", ts="123.123", - unfurls={ - "https://example.com/": {"text": "Every day is the test."} - }, + unfurls={"https://example.com/": {"text": "Every day is the test."}}, )["method"] ) await async_method( channel="C123", ts="123.123", - unfurls={ - "https://example.com/": {"text": "Every day is the test."} - }, + unfurls={"https://example.com/": {"text": "Every day is the test."}}, ) elif method_name == "chat_update": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) await async_method(channel="C123", ts="123.123") elif method_name == "conversations_acceptSharedInvite": - self.api_methods_to_call.remove( - method(channel_name="test-channel-name", channel_id="C123")[ - "method" - ] - ) + self.api_methods_to_call.remove(method(channel_name="test-channel-name", channel_id="C123")["method"]) method(channel_name="test-channel-name", invite_id="123") # either invite_id or channel_id supplied or exception - self.assertRaises( - e.SlackRequestError, method, channel_name="test-channel-name" - ) + self.assertRaises(e.SlackRequestError, method, channel_name="test-channel-name") await async_method(channel_name="test-channel-name", channel_id="C123") await async_method(channel_name="test-channel-name", invite_id="123") with self.assertRaises(e.SlackRequestError): @@ -573,20 +469,12 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel="C123")["method"]) await async_method(channel="C123") elif method_name == "conversations_invite": - self.api_methods_to_call.remove( - method(channel="C123", users=["U2345678901", "U3456789012"])[ - "method" - ] - ) + self.api_methods_to_call.remove(method(channel="C123", users=["U2345678901", "U3456789012"])["method"]) method(channel="C123", users="U2345678901,U3456789012") await async_method(channel="C123", users=["U2345678901", "U3456789012"]) elif method_name == "conversations_inviteShared": - self.api_methods_to_call.remove( - method(channel="C123", emails="test@example.com")["method"] - ) - method( - channel="C123", emails=["test2@example.com", "test3@example.com"] - ) + self.api_methods_to_call.remove(method(channel="C123", emails="test@example.com")["method"]) + method(channel="C123", emails=["test2@example.com", "test3@example.com"]) method(channel="C123", user_ids="U2345678901") method(channel="C123", user_ids=["U2345678901", "U3456789012"]) self.assertRaises(e.SlackRequestError, method, channel="C123") @@ -597,9 +485,7 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel="C123")["method"]) await async_method(channel="C123") elif method_name == "conversations_kick": - self.api_methods_to_call.remove( - method(channel="C123", user="U123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", user="U123")["method"]) await async_method(channel="C123", user="U123") elif method_name == "conversations_listConnectInvites": self.api_methods_to_call.remove(method()["method"]) @@ -608,40 +494,28 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel="C123")["method"]) await async_method(channel="C123") elif method_name == "conversations_mark": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) await async_method(channel="C123", ts="123.123") elif method_name == "conversations_members": self.api_methods_to_call.remove(method(channel="C123")["method"]) await async_method(channel="C123") elif method_name == "conversations_rename": - self.api_methods_to_call.remove( - method(channel="C123", name="new-name")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", name="new-name")["method"]) await async_method(channel="C123", name="new-name") elif method_name == "conversations_replies": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) await async_method(channel="C123", ts="123.123") elif method_name == "conversations_setPurpose": - self.api_methods_to_call.remove( - method(channel="C123", purpose="The purpose")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", purpose="The purpose")["method"]) await async_method(channel="C123", purpose="The purpose") elif method_name == "conversations_setTopic": - self.api_methods_to_call.remove( - method(channel="C123", topic="The topic")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", topic="The topic")["method"]) await async_method(channel="C123", topic="The topic") elif method_name == "conversations_unarchive": self.api_methods_to_call.remove(method(channel="C123")["method"]) await async_method(channel="C123") elif method_name == "dialog_open": - self.api_methods_to_call.remove( - method(dialog={}, trigger_id="123")["method"] - ) + self.api_methods_to_call.remove(method(dialog={}, trigger_id="123")["method"]) await async_method(dialog={}, trigger_id="123") elif method_name == "dnd_setSnooze": self.api_methods_to_call.remove(method(num_minutes=120)["method"]) @@ -651,9 +525,7 @@ async def run_method(self, method_name, method, async_method): method(users="U123,U234") await async_method(users=["123", "U234"]) elif method_name == "files_comments_delete": - self.api_methods_to_call.remove( - method(file="F123", id="FC123")["method"] - ) + self.api_methods_to_call.remove(method(file="F123", id="FC123")["method"]) await async_method(file="F123", id="FC123") elif method_name == "files_delete": self.api_methods_to_call.remove(method(file="F123")["method"]) @@ -668,9 +540,7 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(file="F123")["method"]) await async_method(file="F123") elif method_name == "files_upload": - self.api_methods_to_call.remove( - method(content="This is the content")["method"] - ) + self.api_methods_to_call.remove(method(content="This is the content")["method"]) await async_method(content="This is the content") elif method_name == "files_remote_add": self.api_methods_to_call.remove( @@ -686,9 +556,7 @@ async def run_method(self, method_name, method, async_method): title="File title", ) elif method_name == "files_remote_share": - self.api_methods_to_call.remove( - method(external_id="xxx", channels="C123,G123")["method"] - ) + self.api_methods_to_call.remove(method(external_id="xxx", channels="C123,G123")["method"]) method(external_id="xxx", channels=["C123", "G123"]) method(external_id="xxx", channels="C123,G123") await async_method(external_id="xxx", channels="C123,G123") @@ -710,17 +578,13 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel="C123")["method"]) await async_method(channel="C123") elif method_name == "reactions_add": - self.api_methods_to_call.remove( - method(name="eyes", channel="C111", timestamp="111.222")["method"] - ) + self.api_methods_to_call.remove(method(name="eyes", channel="C111", timestamp="111.222")["method"]) await async_method(name="eyes", channel="C111", timestamp="111.222") elif method_name == "reactions_remove": self.api_methods_to_call.remove(method(name="eyes")["method"]) await async_method(name="eyes") elif method_name == "reminders_add": - self.api_methods_to_call.remove( - method(text="The task", time=123)["method"] - ) + self.api_methods_to_call.remove(method(text="The task", time=123)["method"]) await async_method(text="The task", time=123) elif method_name == "reminders_complete": self.api_methods_to_call.remove(method(reminder="R123")["method"]) @@ -741,9 +605,7 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(query="Slack")["method"]) await async_method(query="Slack") elif method_name == "usergroups_create": - self.api_methods_to_call.remove( - method(name="Engineering Team")["method"] - ) + self.api_methods_to_call.remove(method(name="Engineering Team")["method"]) await async_method(name="Engineering Team") elif method_name == "usergroups_disable": self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) @@ -758,9 +620,7 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) await async_method(usergroup="UG123") elif method_name == "usergroups_users_update": - self.api_methods_to_call.remove( - method(usergroup="UG123", users=["U123", "U234"])["method"] - ) + self.api_methods_to_call.remove(method(usergroup="UG123", users=["U123", "U234"])["method"]) method(usergroup="UG123", users="U123,U234") await async_method(usergroup="UG123", users="U123,U234") elif method_name == "users_getPresence": @@ -770,9 +630,7 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(user="U123")["method"]) await async_method(user="U123") elif method_name == "users_lookupByEmail": - self.api_methods_to_call.remove( - method(email="test@example.com")["method"] - ) + self.api_methods_to_call.remove(method(email="test@example.com")["method"]) await async_method(email="test@example.com") elif method_name == "users_setPhoto": self.api_methods_to_call.remove(method(image="README.md")["method"]) @@ -781,9 +639,7 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(presence="away")["method"]) await async_method(presence="away") elif method_name == "views_open": - self.api_methods_to_call.remove( - method(trigger_id="123123", view={})["method"] - ) + self.api_methods_to_call.remove(method(trigger_id="123123", view={})["method"]) method( trigger_id="123123", view=View(type="modal", blocks=[DividerBlock()]), @@ -793,36 +649,22 @@ async def run_method(self, method_name, method, async_method): view=View(type="modal", blocks=[DividerBlock()]), ) elif method_name == "views_publish": - self.api_methods_to_call.remove( - method(user_id="U123", view={})["method"] - ) + self.api_methods_to_call.remove(method(user_id="U123", view={})["method"]) await async_method(user_id="U123", view={}) elif method_name == "views_push": - self.api_methods_to_call.remove( - method(trigger_id="123123", view={})["method"] - ) + self.api_methods_to_call.remove(method(trigger_id="123123", view={})["method"]) await async_method(trigger_id="123123", view={}) elif method_name == "views_update": - self.api_methods_to_call.remove( - method(view_id="V123", view={})["method"] - ) + self.api_methods_to_call.remove(method(view_id="V123", view={})["method"]) await async_method(view_id="V123", view={}) elif method_name == "workflows_stepCompleted": - self.api_methods_to_call.remove( - method(workflow_step_execute_id="S123", outputs={})["method"] - ) + self.api_methods_to_call.remove(method(workflow_step_execute_id="S123", outputs={})["method"]) await async_method(workflow_step_execute_id="S123", outputs={}) elif method_name == "workflows_stepFailed": - self.api_methods_to_call.remove( - method(workflow_step_execute_id="S456", error={})["method"] - ) + self.api_methods_to_call.remove(method(workflow_step_execute_id="S456", error={})["method"]) await async_method(workflow_step_execute_id="S456", error={}) elif method_name == "workflows_updateStep": - self.api_methods_to_call.remove( - method(workflow_step_edit_id="S789", inputs={}, outputs=[])[ - "method" - ] - ) + self.api_methods_to_call.remove(method(workflow_step_edit_id="S789", inputs={}, outputs=[])["method"]) await async_method(workflow_step_edit_id="S789", inputs={}, outputs=[]) elif method_name == "channels_archive": self.api_methods_to_call.remove(method(channel="C123")["method"]) @@ -837,45 +679,31 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel="C123")["method"]) await async_method(channel="C123") elif method_name == "channels_invite": - self.api_methods_to_call.remove( - method(channel="C123", user="U123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", user="U123")["method"]) await async_method(channel="C123", user="U123") elif method_name == "channels_join": self.api_methods_to_call.remove(method(name="channel-name")["method"]) await async_method(name="channel-name") elif method_name == "channels_kick": - self.api_methods_to_call.remove( - method(channel="C123", user="U123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", user="U123")["method"]) await async_method(channel="C123", user="U123") elif method_name == "channels_leave": self.api_methods_to_call.remove(method(channel="C123")["method"]) await async_method(channel="C123") elif method_name == "channels_mark": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) await async_method(channel="C123", ts="123.123") elif method_name == "channels_rename": - self.api_methods_to_call.remove( - method(channel="C123", name="new-name")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", name="new-name")["method"]) await async_method(channel="C123", name="new-name") elif method_name == "channels_replies": - self.api_methods_to_call.remove( - method(channel="C123", thread_ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", thread_ts="123.123")["method"]) await async_method(channel="C123", thread_ts="123.123") elif method_name == "channels_setPurpose": - self.api_methods_to_call.remove( - method(channel="C123", purpose="The purpose")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", purpose="The purpose")["method"]) await async_method(channel="C123", purpose="The purpose") elif method_name == "channels_setTopic": - self.api_methods_to_call.remove( - method(channel="C123", topic="The topic")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", topic="The topic")["method"]) await async_method(channel="C123", topic="The topic") elif method_name == "channels_unarchive": self.api_methods_to_call.remove(method(channel="C123")["method"]) @@ -884,9 +712,7 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel="G123")["method"]) await async_method(channel="G123") elif method_name == "groups_create": - self.api_methods_to_call.remove( - method(name="private-channel-name")["method"] - ) + self.api_methods_to_call.remove(method(name="private-channel-name")["method"]) await async_method(name="private-channel-name") elif method_name == "groups_createChild": self.api_methods_to_call.remove(method(channel="G123")["method"]) @@ -898,45 +724,31 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel="G123")["method"]) await async_method(channel="G123") elif method_name == "groups_invite": - self.api_methods_to_call.remove( - method(channel="G123", user="U123")["method"] - ) + self.api_methods_to_call.remove(method(channel="G123", user="U123")["method"]) await async_method(channel="G123", user="U123") elif method_name == "groups_kick": - self.api_methods_to_call.remove( - method(channel="G123", user="U123")["method"] - ) + self.api_methods_to_call.remove(method(channel="G123", user="U123")["method"]) await async_method(channel="G123", user="U123") elif method_name == "groups_leave": self.api_methods_to_call.remove(method(channel="G123")["method"]) await async_method(channel="G123") elif method_name == "groups_mark": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) await async_method(channel="C123", ts="123.123") elif method_name == "groups_open": self.api_methods_to_call.remove(method(channel="G123")["method"]) await async_method(channel="G123") elif method_name == "groups_rename": - self.api_methods_to_call.remove( - method(channel="G123", name="new-name")["method"] - ) + self.api_methods_to_call.remove(method(channel="G123", name="new-name")["method"]) await async_method(channel="G123", name="x") elif method_name == "groups_replies": - self.api_methods_to_call.remove( - method(channel="G123", thread_ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="G123", thread_ts="123.123")["method"]) await async_method(channel="G123", thread_ts="x") elif method_name == "groups_setPurpose": - self.api_methods_to_call.remove( - method(channel="G123", purpose="The purpose")["method"] - ) + self.api_methods_to_call.remove(method(channel="G123", purpose="The purpose")["method"]) await async_method(channel="G123", purpose="x") elif method_name == "groups_setTopic": - self.api_methods_to_call.remove( - method(channel="G123", topic="The topic")["method"] - ) + self.api_methods_to_call.remove(method(channel="G123", topic="The topic")["method"]) await async_method(channel="G123", topic="x") elif method_name == "groups_unarchive": self.api_methods_to_call.remove(method(channel="G123")["method"]) @@ -948,17 +760,13 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel="D123")["method"]) await async_method(channel="D123") elif method_name == "im_mark": - self.api_methods_to_call.remove( - method(channel="D123", ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="D123", ts="123.123")["method"]) await async_method(channel="D123", ts="x") elif method_name == "im_open": self.api_methods_to_call.remove(method(user="U123")["method"]) await async_method(user="U123") elif method_name == "im_replies": - self.api_methods_to_call.remove( - method(channel="D123", thread_ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="D123", thread_ts="123.123")["method"]) await async_method(channel="D123", thread_ts="x") elif method_name == "mpim_close": self.api_methods_to_call.remove(method(channel="D123")["method"]) @@ -967,48 +775,32 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel="D123")["method"]) await async_method(channel="D123") elif method_name == "mpim_mark": - self.api_methods_to_call.remove( - method(channel="D123", ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="D123", ts="123.123")["method"]) await async_method(channel="D123", ts="x") elif method_name == "mpim_open": - self.api_methods_to_call.remove( - method(users=["U123", "U234"])["method"] - ) + self.api_methods_to_call.remove(method(users=["U123", "U234"])["method"]) method(users="U123,U234") await async_method(users=["U123", "U234"]) elif method_name == "mpim_replies": - self.api_methods_to_call.remove( - method(channel="D123", thread_ts="123.123")["method"] - ) + self.api_methods_to_call.remove(method(channel="D123", thread_ts="123.123")["method"]) await async_method(channel="D123", thread_ts="123.123") elif method_name == "admin_conversations_restrictAccess_addGroup": - self.api_methods_to_call.remove( - method(channel_id="D123", group_id="G123")["method"] - ) + self.api_methods_to_call.remove(method(channel_id="D123", group_id="G123")["method"]) await async_method(channel_id="D123", group_id="G123") elif method_name == "admin_conversations_restrictAccess_listGroups": - self.api_methods_to_call.remove( - method(channel_id="D123", group_id="G123")["method"] - ) + self.api_methods_to_call.remove(method(channel_id="D123", group_id="G123")["method"]) await async_method(channel_id="D123", group_id="G123") elif method_name == "admin_conversations_restrictAccess_removeGroup": - self.api_methods_to_call.remove( - method(channel_id="D123", group_id="G123", team_id="T13")["method"] - ) + self.api_methods_to_call.remove(method(channel_id="D123", group_id="G123", team_id="T13")["method"]) await async_method(channel_id="D123", group_id="G123", team_id="T123") elif method_name == "admin_conversations_create": - self.api_methods_to_call.remove( - method(is_private=False, name="Foo", team_id="T123")["method"] - ) + self.api_methods_to_call.remove(method(is_private=False, name="Foo", team_id="T123")["method"]) await async_method(is_private=False, name="Foo", team_id="T123") elif method_name == "admin_conversations_delete": self.api_methods_to_call.remove(method(channel_id="C123")["method"]) await async_method(channel_id="C123") elif method_name == "admin_conversations_invite": - self.api_methods_to_call.remove( - method(channel_id="C123", user_ids=["U123", "U456"])["method"] - ) + self.api_methods_to_call.remove(method(channel_id="C123", user_ids=["U123", "U456"])["method"]) await async_method(channel_id="C123", user_ids=["U123", "U456"]) elif method_name == "admin_conversations_archive": self.api_methods_to_call.remove(method(channel_id="C123")["method"]) @@ -1017,9 +809,7 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel_id="C123")["method"]) await async_method(channel_id="C123") elif method_name == "admin_conversations_rename": - self.api_methods_to_call.remove( - method(channel_id="C123", name="Foo")["method"] - ) + self.api_methods_to_call.remove(method(channel_id="C123", name="Foo")["method"]) await async_method(channel_id="C123", name="Foo") elif method_name == "admin_conversations_search": self.api_methods_to_call.remove(method()["method"]) @@ -1050,10 +840,7 @@ async def run_method(self, method_name, method, async_method): elif method_name == "admin_conversations_disconnectShared": self.api_methods_to_call.remove(method(channel_id="C123")["method"]) await async_method(channel_id="C123") - elif ( - method_name - == "admin_conversations_ekm_listOriginalConnectedChannelInfo" - ): + elif method_name == "admin_conversations_ekm_listOriginalConnectedChannelInfo": self.api_methods_to_call.remove(method()["method"]) await async_method() elif method_name == "admin_conversations_getCustomRetention": @@ -1063,9 +850,7 @@ async def run_method(self, method_name, method, async_method): self.api_methods_to_call.remove(method(channel_id="C123")["method"]) await async_method(channel_id="C123") elif method_name == "admin_conversations_setCustomRetention": - self.api_methods_to_call.remove( - method(channel_id="C123", duration_days=365)["method"] - ) + self.api_methods_to_call.remove(method(channel_id="C123", duration_days=365)["method"]) await async_method(channel_id="C123", duration_days=365) else: self.api_methods_to_call.remove(method(*{})["method"]) @@ -1085,9 +870,7 @@ async def test_coverage(self): async_method = getattr(self.async_client, method_name, None) await self.run_method(method_name, method, async_method) - self.assertEqual( - self.api_methods_to_call, [], "All methods should be supported" - ) + self.assertEqual(self.api_methods_to_call, [], "All methods should be supported") @async_test async def test_legacy_coverage(self): @@ -1099,6 +882,4 @@ async def test_legacy_coverage(self): async_method = getattr(self.async_client, method_name, None) await self.run_method(method_name, method, async_method) - self.assertEqual( - self.api_methods_to_call, [], "All methods should be supported" - ) + self.assertEqual(self.api_methods_to_call, [], "All methods should be supported") diff --git a/tests/slack_sdk_async/web/test_web_client_issue_891.py b/tests/slack_sdk_async/web/test_web_client_issue_891.py index 10d2d6a98..55e0cdb12 100644 --- a/tests/slack_sdk_async/web/test_web_client_issue_891.py +++ b/tests/slack_sdk_async/web/test_web_client_issue_891.py @@ -26,18 +26,14 @@ async def test_missing_text_warning_chat_postMessage(self): async def test_missing_text_warning_chat_postEphemeral(self): client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): - resp = await client.chat_postEphemeral( - channel="C111", user="U111", blocks=[] - ) + resp = await client.chat_postEphemeral(channel="C111", user="U111", blocks=[]) self.assertIsNone(resp["error"]) @async_test async def test_missing_text_warning_chat_scheduleMessage(self): client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): - resp = await client.chat_scheduleMessage( - channel="C111", post_at="299876400", text="", blocks=[] - ) + resp = await client.chat_scheduleMessage(channel="C111", post_at="299876400", text="", blocks=[]) self.assertIsNone(resp["error"]) @async_test @@ -51,18 +47,14 @@ async def test_missing_text_warning_chat_update(self): async def test_missing_fallback_warning_chat_postMessage(self): client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): - resp = await client.chat_postMessage( - channel="C111", blocks=[], attachments=[{"text": "hi"}] - ) + resp = await client.chat_postMessage(channel="C111", blocks=[], attachments=[{"text": "hi"}]) self.assertIsNone(resp["error"]) @async_test async def test_missing_fallback_warning_chat_postEphemeral(self): client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): - resp = await client.chat_postEphemeral( - channel="C111", user="U111", blocks=[], attachments=[{"text": "hi"}] - ) + resp = await client.chat_postEphemeral(channel="C111", user="U111", blocks=[], attachments=[{"text": "hi"}]) self.assertIsNone(resp["error"]) @async_test @@ -82,7 +74,5 @@ async def test_missing_fallback_warning_chat_scheduleMessage(self): async def test_missing_fallback_warning_chat_update(self): client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): - resp = await client.chat_update( - channel="C111", ts="111.222", blocks=[], attachments=[{"text": "hi"}] - ) + resp = await client.chat_update(channel="C111", ts="111.222", blocks=[], attachments=[{"text": "hi"}]) self.assertIsNone(resp["error"]) diff --git a/tests/slack_sdk_async/webhook/test_async_webhook.py b/tests/slack_sdk_async/webhook/test_async_webhook.py index 778d7e234..b2e0a64bd 100644 --- a/tests/slack_sdk_async/webhook/test_async_webhook.py +++ b/tests/slack_sdk_async/webhook/test_async_webhook.py @@ -131,12 +131,7 @@ async def test_send_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField( - title=f"field_{i}_title", value=f"field_{i}_value" - ) - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -166,9 +161,7 @@ async def test_timeout_issue_712(self): @async_test async def test_proxy_issue_714(self): - client = AsyncWebhookClient( - url="http://localhost:8888", proxy="http://invalid-host:9999" - ) + client = AsyncWebhookClient(url="http://localhost:8888", proxy="http://invalid-host:9999") with self.assertRaises(Exception): await client.send_dict({"text": "hello!"}) diff --git a/tests/web/classes/test_actions.py b/tests/web/classes/test_actions.py index 3042d8dbb..ed14b840e 100644 --- a/tests/web/classes/test_actions.py +++ b/tests/web/classes/test_actions.py @@ -47,9 +47,7 @@ def test_json(self): def test_value_length(self): with self.assertRaises(SlackObjectFormationError): - ActionButton( - name="button_1", text="Click me!", value=STRING_3001_CHARS - ).to_dict() + ActionButton(name="button_1", text="Click me!", value=STRING_3001_CHARS).to_dict() def test_style_validator(self): b = ActionButton(name="button_1", text="Click me!", value="btn_1") @@ -81,9 +79,7 @@ def setUp(self) -> None: def test_json(self): self.assertDictEqual( - ActionStaticSelector( - name="select_1", text="selector_1", options=self.options - ).to_dict(), + ActionStaticSelector(name="select_1", text="selector_1", options=self.options).to_dict(), { "name": "select_1", "text": "selector_1", @@ -94,9 +90,7 @@ def test_json(self): ) self.assertDictEqual( - ActionStaticSelector( - name="select_1", text="selector_1", options=self.option_group - ).to_dict(), + ActionStaticSelector(name="select_1", text="selector_1", options=self.option_group).to_dict(), { "name": "select_1", "text": "selector_1", @@ -108,9 +102,7 @@ def test_json(self): def test_options_length(self): with self.assertRaises(SlackObjectFormationError): - ActionStaticSelector( - name="select_1", text="selector_1", options=self.options * 34 - ).to_dict() + ActionStaticSelector(name="select_1", text="selector_1", options=self.options * 34).to_dict() class DynamicActionSelectorTests(unittest.TestCase): @@ -155,9 +147,7 @@ def test_json(self): option = Option.from_single_value("one") self.assertDictEqual( - ActionExternalSelector( - name="select_1", text="selector_1", min_query_length=3 - ).to_dict(), + ActionExternalSelector(name="select_1", text="selector_1", min_query_length=3).to_dict(), { "name": "select_1", "text": "selector_1", @@ -168,9 +158,7 @@ def test_json(self): ) self.assertDictEqual( - ActionExternalSelector( - name="select_1", text="selector_1", selected_option=option - ).to_dict(), + ActionExternalSelector(name="select_1", text="selector_1", selected_option=option).to_dict(), { "name": "select_1", "text": "selector_1", diff --git a/tests/web/classes/test_attachments.py b/tests/web/classes/test_attachments.py index 33ab4b2d9..ede2900fe 100644 --- a/tests/web/classes/test_attachments.py +++ b/tests/web/classes/test_attachments.py @@ -25,9 +25,7 @@ def setUp(self) -> None: self.simple = Attachment(text="some_text") def test_basic_json(self): - self.assertDictEqual( - Attachment(text="some text").to_dict(), {"text": "some text", "fields": []} - ) + self.assertDictEqual(Attachment(text="some text").to_dict(), {"text": "some text", "fields": []}) self.assertDictEqual( Attachment( @@ -36,10 +34,7 @@ def test_basic_json(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -138,9 +133,7 @@ def test_basic_json(self): ActionLinkButton(text="navigate", url="http://google.com"), ] self.assertDictEqual( - InteractiveAttachment( - text="some text", callback_id="abc123", actions=actions - ).to_dict(), + InteractiveAttachment(text="some text", callback_id="abc123", actions=actions).to_dict(), { "text": "some text", "fields": [], @@ -158,10 +151,7 @@ def test_basic_json(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -200,14 +190,10 @@ def test_basic_json(self): ) def test_actions_length(self): - actions = [ - ActionButton(name="button_1", text="Click me", value="button_value_1") - ] * 6 + actions = [ActionButton(name="button_1", text="Click me", value="button_value_1")] * 6 with self.assertRaises(SlackObjectFormationError): - InteractiveAttachment( - text="some text", callback_id="abc123", actions=actions - ).to_dict(), + InteractiveAttachment(text="some text", callback_id="abc123", actions=actions).to_dict(), class BlockAttachmentTests(unittest.TestCase): diff --git a/tests/web/classes/test_blocks.py b/tests/web/classes/test_blocks.py index f7f22e056..85b0e8acc 100644 --- a/tests/web/classes/test_blocks.py +++ b/tests/web/classes/test_blocks.py @@ -131,9 +131,7 @@ def test_json(self): ], "type": "section", }, - SectionBlock( - text="some text", fields=[f"field{i}" for i in range(5)] - ).to_dict(), + SectionBlock(text="some text", fields=[f"field{i}" for i in range(5)]).to_dict(), ) button = LinkButtonElement(text="Click me!", url="http://google.com") @@ -171,9 +169,7 @@ def build_slack_block(cls, msg1, msg2, data): {"type": "section", "fields": []}, ] names = list(set(data.keys()) - set("user_comments")) - fields = [ - {"type": "mrkdwn", "text": f"*{name}*:\n{data[name]}"} for name in names - ] + fields = [{"type": "mrkdwn", "text": f"*{name}*:\n{data[name]}"} for name in names] blocks[1]["fields"] = fields return blocks @@ -184,9 +180,7 @@ def build_slack_block_native(cls, msg1, msg2, data): SectionBlock(fields=[]), ] names: List[str] = list(set(data.keys()) - set("user_comments")) - fields = [ - MarkdownTextObject.parse(f"*{name}*:\n{data[name]}") for name in names - ] + fields = [MarkdownTextObject.parse(f"*{name}*:\n{data[name]}") for name in names] blocks[1].fields = fields return list(b.to_dict() for b in blocks) @@ -215,9 +209,7 @@ def test_document(self): def test_json(self): self.assertDictEqual({"type": "divider"}, DividerBlock().to_dict()) - self.assertDictEqual( - {"type": "divider"}, DividerBlock(**{"type": "divider"}).to_dict() - ) + self.assertDictEqual({"type": "divider"}, DividerBlock(**{"type": "divider"}).to_dict()) def test_json_with_block_id(self): self.assertDictEqual( @@ -257,9 +249,7 @@ def test_json(self): "alt_text": "not really an image", "type": "image", }, - ImageBlock( - image_url="http://google.com", alt_text="not really an image" - ).to_dict(), + ImageBlock(image_url="http://google.com", alt_text="not really an image").to_dict(), ) def test_image_url_length(self): @@ -268,15 +258,11 @@ def test_image_url_length(self): def test_alt_text_length(self): with self.assertRaises(SlackObjectFormationError): - ImageBlock( - image_url="http://google.com", alt_text=STRING_3001_CHARS - ).to_dict() + ImageBlock(image_url="http://google.com", alt_text=STRING_3001_CHARS).to_dict() def test_title_length(self): with self.assertRaises(SlackObjectFormationError): - ImageBlock( - image_url="http://google.com", alt_text="text", title=STRING_3001_CHARS - ).to_dict() + ImageBlock(image_url="http://google.com", alt_text="text", title=STRING_3001_CHARS).to_dict() # ---------------------------------------------- diff --git a/tests/web/classes/test_dialogs.py b/tests/web/classes/test_dialogs.py index 6c8162fc0..0c3a3226b 100644 --- a/tests/web/classes/test_dialogs.py +++ b/tests/web/classes/test_dialogs.py @@ -28,54 +28,34 @@ def test_json_validators(self): with self.assertRaises(SlackObjectFormationError, msg="label length"): component(name="dialog", label=STRING_51_CHARS).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="placeholder length" - ): - component( - name="dialog", label="Dialog", placeholder=STRING_301_CHARS - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="placeholder length"): + component(name="dialog", label="Dialog", placeholder=STRING_301_CHARS).to_dict() with self.assertRaises(SlackObjectFormationError, msg="hint length"): - component( - name="dialog", label="Dialog", hint=STRING_301_CHARS - ).to_dict() + component(name="dialog", label="Dialog", hint=STRING_301_CHARS).to_dict() with self.assertRaises(SlackObjectFormationError, msg="value length"): - component( - name="dialog", label="Dialog", value=STRING_3001_CHARS - ).to_dict() + component(name="dialog", label="Dialog", value=STRING_3001_CHARS).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="min_length out of bounds" - ): + with self.assertRaises(SlackObjectFormationError, msg="min_length out of bounds"): component( name="dialog", label="Dialog", min_length=component.max_value_length + 1, ).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="max_length out of bounds" - ): + with self.assertRaises(SlackObjectFormationError, msg="max_length out of bounds"): component( name="dialog", label="Dialog", max_length=component.max_value_length + 1, ).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="min_length > max length" - ): - component( - name="dialog", label="Dialog", min_length=100, max_length=50 - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="min_length > max length"): + component(name="dialog", label="Dialog", min_length=100, max_length=50).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="subtype invalid" - ): - component( - name="dialog", label="Dialog", subtype="abcdefg" - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="subtype invalid"): + component(name="dialog", label="Dialog", subtype="abcdefg").to_dict() class TextFieldComponentTests(unittest.TestCase): @@ -158,9 +138,7 @@ def test_basic_json_formation(self): Option.from_single_value("three"), ] self.assertDictEqual( - DialogStaticSelector( - name="dialog", label="Dialog", options=options - ).to_dict(), + DialogStaticSelector(name="dialog", label="Dialog", options=options).to_dict(), { "optional": False, "label": "Dialog", @@ -197,13 +175,9 @@ def test_json(self): }, ) - passing_obj = component( - name="select_1", label="selector_1", value=self.selected_opt - ).to_dict() + passing_obj = component(name="select_1", label="selector_1", value=self.selected_opt).to_dict() - passing_str = component( - name="select_1", label="selector_1", value="U12345" - ).to_dict() + passing_str = component(name="select_1", label="selector_1", value="U12345").to_dict() expected = { "name": "select_1", @@ -256,9 +230,7 @@ def setUp(self) -> None: optional=True, hint="Enter your signature", ) - .text_area( - name="message", label="Message", hint="Enter message to broadcast" - ) + .text_area(name="message", label="Message", hint="Enter message to broadcast") .conversation_selector(name="target", label="Choose Target") ) diff --git a/tests/web/classes/test_elements.py b/tests/web/classes/test_elements.py index 1d7b717e7..27f49ebab 100644 --- a/tests/web/classes/test_elements.py +++ b/tests/web/classes/test_elements.py @@ -33,9 +33,7 @@ class InteractiveElementTests(unittest.TestCase): def test_action_id(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="click me!", action_id=STRING_301_CHARS, value="clickable button" - ).to_dict() + ButtonElement(text="click me!", action_id=STRING_301_CHARS, value="clickable button").to_dict() class ButtonElementTests(unittest.TestCase): @@ -75,9 +73,7 @@ def test_json(self): "value": "button_123", "type": "button", }, - ButtonElement( - text="button text", action_id="some_button", value="button_123" - ).to_dict(), + ButtonElement(text="button text", action_id="some_button", value="button_123").to_dict(), ) confirm = ConfirmObject(title="really?", text="are you sure?") @@ -101,28 +97,20 @@ def test_json(self): def test_text_length(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text=STRING_301_CHARS, action_id="button", value="click_me" - ).to_dict() + ButtonElement(text=STRING_301_CHARS, action_id="button", value="click_me").to_dict() def test_value_length(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="Button", action_id="button", value=STRING_3001_CHARS - ).to_dict() + ButtonElement(text="Button", action_id="button", value=STRING_3001_CHARS).to_dict() def test_invalid_style(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="Button", action_id="button", value="button", style="invalid" - ).to_dict() + ButtonElement(text="Button", action_id="button", value="button", style="invalid").to_dict() class LinkButtonElementTests(unittest.TestCase): def test_json(self): - button = LinkButtonElement( - action_id="test", text="button text", url="http://google.com" - ) + button = LinkButtonElement(action_id="test", text="button text", url="http://google.com") self.assertDictEqual( { "text": {"emoji": True, "text": "button text", "type": "plain_text"}, @@ -148,9 +136,7 @@ def test_document(self): input = { "type": "checkboxes", "action_id": "this_is_an_action_id", - "initial_options": [ - {"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}} - ], + "initial_options": [{"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}}], "options": [ {"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}}, {"value": "A2", "text": {"type": "plain_text", "text": "Checkbox 2"}}, @@ -236,9 +222,7 @@ def test_json(self): "alt_text": "not really an image", "type": "image", }, - ImageElement( - image_url="http://google.com", alt_text="not really an image" - ).to_dict(), + ImageElement(image_url="http://google.com", alt_text="not really an image").to_dict(), ) def test_image_url_length(self): @@ -247,9 +231,7 @@ def test_image_url_length(self): def test_alt_text_length(self): with self.assertRaises(SlackObjectFormationError): - ImageElement( - image_url="http://google.com", alt_text=STRING_3001_CHARS - ).to_dict() + ImageElement(image_url="http://google.com", alt_text=STRING_3001_CHARS).to_dict() # ------------------------------------------------- @@ -495,9 +477,7 @@ def test_json(self): "min_query_length": 5, "type": "external_select", }, - ExternalDataSelectElement( - placeholder="selectedValue", action_id="dropdown", min_query_length=5 - ).to_dict(), + ExternalDataSelectElement(placeholder="selectedValue", action_id="dropdown", min_query_length=5).to_dict(), ) self.assertDictEqual( { diff --git a/tests/web/classes/test_objects.py b/tests/web/classes/test_objects.py index cd51d8958..1fd986c69 100644 --- a/tests/web/classes/test_objects.py +++ b/tests/web/classes/test_objects.py @@ -59,12 +59,8 @@ def __init__( initial: Union[dict, KeyValueObject], options: List[Union[dict, KeyValueObject]], ): - self.initial = ( - KeyValueObject(**initial) if isinstance(initial, dict) else initial - ) - self.options = [ - KeyValueObject(**o) if isinstance(o, dict) else o for o in options - ] + self.initial = KeyValueObject(**initial) if isinstance(initial, dict) else initial + self.options = [KeyValueObject(**o) if isinstance(o, dict) else o for o in options] class JsonObjectTests(unittest.TestCase): @@ -187,12 +183,8 @@ def setUp(self) -> None: self.epoch = 1234567890 def test_simple_formation(self): - datelink = DateLink( - date=self.epoch, date_format="{date_long}", fallback=f"{self.epoch}" - ) - self.assertEqual( - f"{datelink}", f"" - ) + datelink = DateLink(date=self.epoch, date_format="{date_long}", fallback=f"{self.epoch}") + self.assertEqual(f"{datelink}", f"") def test_with_url(self): datelink = DateLink( @@ -254,9 +246,7 @@ def test_basic_json(self): def test_from_string(self): plaintext = PlainTextObject(text="some text", emoji=True) - self.assertDictEqual( - plaintext.to_dict(), PlainTextObject.direct_from_string("some text") - ) + self.assertDictEqual(plaintext.to_dict(), PlainTextObject.direct_from_string("some text")) class MarkdownTextObjectTests(unittest.TestCase): @@ -273,9 +263,7 @@ def test_basic_json(self): def test_from_string(self): markdown = MarkdownTextObject(text="some text") - self.assertDictEqual( - markdown.to_dict(), MarkdownTextObject.direct_from_string("some text") - ) + self.assertDictEqual(markdown.to_dict(), MarkdownTextObject.direct_from_string("some text")) class ConfirmObjectTests(unittest.TestCase): @@ -366,15 +354,11 @@ def test_text_length_with_object(self): def test_confirm_length(self): with self.assertRaises(SlackObjectFormationError): - ConfirmObject( - title="title", text="Are you sure?", confirm=STRING_51_CHARS - ).to_dict() + ConfirmObject(title="title", text="Are you sure?", confirm=STRING_51_CHARS).to_dict() def test_deny_length(self): with self.assertRaises(SlackObjectFormationError): - ConfirmObject( - title="title", text="Are you sure?", deny=STRING_51_CHARS - ).to_dict() + ConfirmObject(title="title", text="Are you sure?", deny=STRING_51_CHARS).to_dict() class OptionTests(unittest.TestCase): @@ -474,15 +458,11 @@ def test_action_style_json(self): def test_label_length(self): with self.assertRaises(SlackObjectFormationError): - OptionGroup(label=STRING_301_CHARS, options=self.common_options).to_dict( - "text" - ) + OptionGroup(label=STRING_301_CHARS, options=self.common_options).to_dict("text") def test_options_length(self): with self.assertRaises(SlackObjectFormationError): - OptionGroup(label="option_group", options=self.common_options * 34).to_dict( - "text" - ) + OptionGroup(label="option_group", options=self.common_options * 34).to_dict("text") def test_confirm_style(self): obj = ConfirmObject.parse( diff --git a/tests/web/classes/test_views.py b/tests/web/classes/test_views.py index 1b9148f04..dd08426ff 100644 --- a/tests/web/classes/test_views.py +++ b/tests/web/classes/test_views.py @@ -68,9 +68,7 @@ def test_valid_construction(self): ), SectionBlock( block_id="sb-id", - text=MarkdownTextObject( - text="This is a mrkdwn text section block." - ), + text=MarkdownTextObject(text="This is a mrkdwn text section block."), fields=[ PlainTextObject(text="*this is plain_text text*", emoji=True), MarkdownTextObject(text="*this is mrkdwn text*"), @@ -80,31 +78,23 @@ def test_valid_construction(self): DividerBlock(), SectionBlock( block_id="rb-id", - text=MarkdownTextObject( - text="This is a section block with radio button accessory" - ), + text=MarkdownTextObject(text="This is a section block with radio button accessory"), accessory=RadioButtonsElement( initial_option=Option( text=PlainTextObject(text="Option 1"), value="option 1", - description=PlainTextObject( - text="Description for option 1" - ), + description=PlainTextObject(text="Description for option 1"), ), options=[ Option( text=PlainTextObject(text="Option 1"), value="option 1", - description=PlainTextObject( - text="Description for option 1" - ), + description=PlainTextObject(text="Description for option 1"), ), Option( text=PlainTextObject(text="Option 2"), value="option 2", - description=PlainTextObject( - text="Description for option 2" - ), + description=PlainTextObject(text="Description for option 2"), ), ], ), @@ -255,14 +245,8 @@ def test_all_state_values(self): } state = ViewState( values={ - "b1": { - "a1": ViewStateValue(type="datepicker", selected_date="1990-04-12") - }, - "b2": { - "a2": ViewStateValue( - type="plain_text_input", value="This is a test" - ) - }, + "b1": {"a1": ViewStateValue(type="datepicker", selected_date="1990-04-12")}, + "b2": {"a2": ViewStateValue(type="plain_text_input", value="This is a test")}, "b3": { "a3": ViewStateValue( type="plain_text_input", @@ -270,46 +254,26 @@ def test_all_state_values(self): ) }, "b4": {"a4": ViewStateValue(type="users_select", selected_user="U123")}, - "b4-2": { - "a4-2": ViewStateValue( - type="multi_users_select", selected_users=["U123", "U234"] - ) - }, - "b5": { - "a5": ViewStateValue( - type="conversations_select", selected_conversation="C123" - ) - }, + "b4-2": {"a4-2": ViewStateValue(type="multi_users_select", selected_users=["U123", "U234"])}, + "b5": {"a5": ViewStateValue(type="conversations_select", selected_conversation="C123")}, "b5-2": { "a5-2": ViewStateValue( type="multi_conversations_select", selected_conversations=["C123", "C234"], ) }, - "b6": { - "a6": ViewStateValue( - type="channels_select", selected_channel="C123" - ) - }, - "b6-2": { - "a6-2": ViewStateValue( - type="multi_channels_select", selected_channels=["C123", "C234"] - ) - }, + "b6": {"a6": ViewStateValue(type="channels_select", selected_channel="C123")}, + "b6-2": {"a6-2": ViewStateValue(type="multi_channels_select", selected_channels=["C123", "C234"])}, "b7": { "a7": ViewStateValue( type="multi_static_select", selected_options=[ Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-0", ), Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-1", ), ], @@ -320,15 +284,11 @@ def test_all_state_values(self): type="checkboxes", selected_options=[ Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-0", ), Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-1", ), ], @@ -340,9 +300,7 @@ def test_all_state_values(self): selected_option=Option( text=PlainTextObject(text="Option 1", emoji=True), value="option 1", - description=PlainTextObject( - text="Description for option 1", emoji=True - ), + description=PlainTextObject(text="Description for option 1", emoji=True), ), ) }, @@ -400,9 +358,7 @@ def test_home_tab_construction(self): type="home", blocks=[ SectionBlock( - text=MarkdownTextObject( - text="*Here's what you can do with Project Tracker:*" - ), + text=MarkdownTextObject(text="*Here's what you can do with Project Tracker:*"), ), ActionsBlock( elements=[ diff --git a/tests/web/mock_web_api_server.py b/tests/web/mock_web_api_server.py index 64e36429b..28c358b41 100644 --- a/tests/web/mock_web_api_server.py +++ b/tests/web/mock_web_api_server.py @@ -32,16 +32,12 @@ class MockHandler(SimpleHTTPRequestHandler): def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] - return self.pattern_for_language.search( - user_agent - ) and self.pattern_for_package_identifier.search(user_agent) + return self.pattern_for_language.search(user_agent) and self.pattern_for_package_identifier.search(user_agent) def is_valid_token(self): if self.path.startswith("oauth"): return True - return "Authorization" in self.headers and str( - self.headers["Authorization"] - ).startswith("Bearer xoxb-") + return "Authorization" in self.headers and str(self.headers["Authorization"]).startswith("Bearer xoxb-") def set_common_headers(self): self.send_header("content-type", "application/json;charset=utf-8") @@ -73,9 +69,7 @@ def _handle(self): self.wfile.write("""{"ok":true}""".encode("utf-8")) return else: - self.wfile.write( - """{"ok":false, "error":"invalid"}""".encode("utf-8") - ) + self.wfile.write("""{"ok":false, "error":"invalid"}""".encode("utf-8")) return if self.is_valid_token() and self.is_valid_user_agent(): @@ -91,16 +85,12 @@ def _handle(self): if post_body.startswith("{"): request_body = json.loads(post_body) else: - request_body = { - k: v[0] for k, v in parse_qs(post_body).items() - } + request_body = {k: v[0] for k, v in parse_qs(post_body).items()} except UnicodeDecodeError: pass else: if parsed_path and parsed_path.query: - request_body = { - k: v[0] for k, v in parse_qs(parsed_path.query).items() - } + request_body = {k: v[0] for k, v in parse_qs(parsed_path.query).items()} header = self.headers["authorization"] pattern = str(header).split("xoxb-", 1)[1] @@ -113,9 +103,7 @@ def _handle(self): self.send_response(429) self.send_header("retry-after", 1) self.set_common_headers() - self.wfile.write( - """{"ok":false,"error":"rate_limited"}""".encode("utf-8") - ) + self.wfile.write("""{"ok":false,"error":"rate_limited"}""".encode("utf-8")) self.wfile.close() return @@ -158,11 +146,7 @@ def _handle(self): else: self.send_response(400) self.set_common_headers() - self.wfile.write( - """{"ok":false, "error":"invalid_user_agent"}""".encode( - "utf-8" - ) - ) + self.wfile.write("""{"ok":false, "error":"invalid_user_agent"}""".encode("utf-8")) self.wfile.close() return @@ -182,12 +166,8 @@ def _handle(self): if request_body: for k, v in request_body.items(): if k in ids: - if not re.compile(r"^[^,\[\]]+?,[^,\[\]]+$").match( - v - ): - raise Exception( - f"The parameter {k} is not a comma-separated string value: {v}" - ) + if not re.compile(r"^[^,\[\]]+?,[^,\[\]]+$").match(v): + raise Exception(f"The parameter {k} is not a comma-separated string value: {v}") body = {"ok": True, "method": parsed_path.path.replace("/", "")} else: with open(f"tests/data/web_response_{pattern}.json") as file: @@ -237,9 +217,7 @@ def stop(self): class MonitorThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self, daemon=True) self.handler = handler self.test = test @@ -251,9 +229,7 @@ def run(self) -> None: try: req = Request(f"{self.test.server_url}/received_requests.json") resp = urlopen(req, timeout=1) - self.test.mock_received_requests = json.loads( - resp.read().decode("utf-8") - ) + self.test.mock_received_requests = json.loads(resp.read().decode("utf-8")) except Exception as e: # skip logging for the initial request if self.test.mock_received_requests is not None: @@ -266,9 +242,7 @@ def stop(self): class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self) self.handler = handler self.test = test diff --git a/tests/web/test_async_web_client.py b/tests/web/test_async_web_client.py index e09515586..3f00580da 100644 --- a/tests/web/test_async_web_client.py +++ b/tests/web/test_async_web_client.py @@ -105,14 +105,10 @@ async def test_issue_690_oauth_v2_access_async(self): @async_test async def test_issue_690_oauth_access_async(self): self.client.token = "" - resp = await self.client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = await self.client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - await self.client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + await self.client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_token_param_async(self): diff --git a/tests/web/test_web_client.py b/tests/web/test_web_client.py index 8d33495c4..7ed61b765 100644 --- a/tests/web/test_web_client.py +++ b/tests/web/test_web_client.py @@ -156,14 +156,10 @@ async def test_issue_560_bool_in_params_async(self): def test_issue_690_oauth_v2_access(self): self.client.token = "" - resp = self.client.oauth_v2_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = self.client.oauth_v2_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - self.client.oauth_v2_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + self.client.oauth_v2_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_issue_690_oauth_v2_access_async(self): @@ -183,26 +179,18 @@ async def test_issue_690_oauth_v2_access_async(self): def test_issue_690_oauth_access(self): self.client.token = "" - resp = self.client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = self.client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - self.client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + self.client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_issue_690_oauth_access_async(self): self.async_client.token = "" - resp = await self.async_client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = await self.async_client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - await self.async_client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + await self.async_client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") def test_issue_705_no_param_request_pagination(self): self.client.token = "xoxb-users_list_pagination" @@ -286,8 +274,7 @@ async def test_html_response_body_issue_718_async(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertEqual( - "The request to the Slack API failed.\n" - "The server responded with: {}", + "The request to the Slack API failed.\n" "The server responded with: {}", str(e), ) diff --git a/tests/web/test_web_client_functional.py b/tests/web/test_web_client_functional.py index 0f0c03d51..6bf3cd4bd 100644 --- a/tests/web/test_web_client_functional.py +++ b/tests/web/test_web_client_functional.py @@ -10,9 +10,7 @@ class TestWebClientFunctional(unittest.TestCase): def setUp(self): setup_mock_web_api_server(self) - self.client = slack.WebClient( - token="xoxb-api_test", base_url="http://localhost:8888" - ) + self.client = slack.WebClient(token="xoxb-api_test", base_url="http://localhost:8888") def tearDown(self): cleanup_mock_web_api_server(self) diff --git a/tests/web/test_web_client_issue_829.py b/tests/web/test_web_client_issue_829.py index 10ef4ce96..3e4b9c504 100644 --- a/tests/web/test_web_client_issue_829.py +++ b/tests/web/test_web_client_issue_829.py @@ -44,7 +44,6 @@ async def test_html_response_body_issue_829_async(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertEqual( - "The request to the Slack API failed.\n" - "The server responded with: {}", + "The request to the Slack API failed.\n" "The server responded with: {}", str(e), ) diff --git a/tests/web/test_web_client_issue_891.py b/tests/web/test_web_client_issue_891.py index d510e3744..6aca56049 100644 --- a/tests/web/test_web_client_issue_891.py +++ b/tests/web/test_web_client_issue_891.py @@ -29,9 +29,7 @@ def test_missing_text_warning_chat_postEphemeral(self): def test_missing_text_warning_chat_scheduleMessage(self): client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): - resp = client.chat_scheduleMessage( - channel="C111", post_at="299876400", text="", blocks=[] - ) + resp = client.chat_scheduleMessage(channel="C111", post_at="299876400", text="", blocks=[]) self.assertIsNone(resp["error"]) def test_missing_text_warning_chat_update(self): @@ -43,17 +41,13 @@ def test_missing_text_warning_chat_update(self): def test_missing_fallback_warning_chat_postMessage(self): client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): - resp = client.chat_postMessage( - channel="C111", blocks=[], attachments=[{"text": "hi"}] - ) + resp = client.chat_postMessage(channel="C111", blocks=[], attachments=[{"text": "hi"}]) self.assertIsNone(resp["error"]) def test_missing_fallback_warning_chat_postEphemeral(self): client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): - resp = client.chat_postEphemeral( - channel="C111", user="U111", blocks=[], attachments=[{"text": "hi"}] - ) + resp = client.chat_postEphemeral(channel="C111", user="U111", blocks=[], attachments=[{"text": "hi"}]) self.assertIsNone(resp["error"]) def test_missing_fallback_warning_chat_scheduleMessage(self): @@ -71,7 +65,5 @@ def test_missing_fallback_warning_chat_scheduleMessage(self): def test_missing_fallback_warning_chat_update(self): client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): - resp = client.chat_update( - channel="C111", ts="111.222", blocks=[], attachments=[{"text": "hi"}] - ) + resp = client.chat_update(channel="C111", ts="111.222", blocks=[], attachments=[{"text": "hi"}]) self.assertIsNone(resp["error"]) diff --git a/tests/webhook/mock_web_api_server.py b/tests/webhook/mock_web_api_server.py index 4a9ddfc28..cd0f33b07 100644 --- a/tests/webhook/mock_web_api_server.py +++ b/tests/webhook/mock_web_api_server.py @@ -27,9 +27,7 @@ class MockHandler(SimpleHTTPRequestHandler): def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] - return self.pattern_for_language.search( - user_agent - ) and self.pattern_for_package_identifier.search(user_agent) + return self.pattern_for_language.search(user_agent) and self.pattern_for_package_identifier.search(user_agent) def set_common_headers(self): self.send_header("content-type", "text/plain;charset=utf-8") @@ -107,9 +105,7 @@ def stop(self): class MonitorThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self, daemon=True) self.handler = handler self.test = test @@ -121,9 +117,7 @@ def run(self) -> None: try: req = Request(f"{self.test.server_url}/received_requests.json") resp = urlopen(req, timeout=1) - self.test.mock_received_requests = json.loads( - resp.read().decode("utf-8") - ) + self.test.mock_received_requests = json.loads(resp.read().decode("utf-8")) except Exception as e: # skip logging for the initial request if self.test.mock_received_requests is not None: @@ -136,9 +130,7 @@ def stop(self): class MonitorThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self, daemon=True) self.handler = handler self.test = test @@ -150,9 +142,7 @@ def run(self) -> None: try: req = Request(f"{self.test.server_url}/received_requests.json") resp = urlopen(req, timeout=1) - self.test.mock_received_requests = json.loads( - resp.read().decode("utf-8") - ) + self.test.mock_received_requests = json.loads(resp.read().decode("utf-8")) except Exception as e: # skip logging for the initial request if self.test.mock_received_requests is not None: @@ -165,9 +155,7 @@ def stop(self): class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): + def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler): threading.Thread.__init__(self) self.handler = handler self.test = test diff --git a/tests/webhook/test_async_webhook.py b/tests/webhook/test_async_webhook.py index 9ec27f6f0..e96244d0d 100644 --- a/tests/webhook/test_async_webhook.py +++ b/tests/webhook/test_async_webhook.py @@ -141,12 +141,7 @@ async def test_send_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField( - title=f"field_{i}_title", value=f"field_{i}_value" - ) - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -176,9 +171,7 @@ async def test_timeout_issue_712(self): @async_test async def test_proxy_issue_714(self): - client = AsyncWebhookClient( - url="http://localhost:8888", proxy="http://invalid-host:9999" - ) + client = AsyncWebhookClient(url="http://localhost:8888", proxy="http://invalid-host:9999") with self.assertRaises(Exception): await client.send_dict({"text": "hello!"}) diff --git a/tests/webhook/test_webhook.py b/tests/webhook/test_webhook.py index b54485904..3e2cf1a06 100644 --- a/tests/webhook/test_webhook.py +++ b/tests/webhook/test_webhook.py @@ -138,12 +138,7 @@ def test_send_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField( - title=f"field_{i}_title", value=f"field_{i}_value" - ) - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -176,9 +171,7 @@ def test_error_response(self): self.assertTrue(resp.body.startswith("")) def test_proxy_issue_714(self): - client = WebhookClient( - url="http://localhost:8888", proxy="http://invalid-host:9999" - ) + client = WebhookClient(url="http://localhost:8888", proxy="http://invalid-host:9999") with self.assertRaises(urllib.error.URLError): client.send_dict({"text": "hello!"})