Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions slack_sdk/web/base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,11 +414,15 @@ def _perform_urllib_http_request(self, *, url: str, args: Dict[str, Dict[str, An
retry_request = RetryHttpRequest.from_urllib_http_request(req)
body_string = resp["body"] if isinstance(resp["body"], str) else None
body_bytes = body_string.encode("utf-8") if body_string is not None else resp["body"]
parsed_body = {}
if body_string is not None and body_string.startswith("{"):
parsed_body = json.loads(body_string)
resp["parsed_body"] = parsed_body
else:
parsed_body = {}
try:
parsed_body = json.loads(body_string)
resp["parsed_body"] = parsed_body
except json.decoder.JSONDecodeError:
# Leave "parsed_body" unset so that _urllib_api_call() reports the malformed body
# as a SlackApiError, the same as it does when no retry handler is set
pass
retry_response = RetryHttpResponse(
status_code=resp["status"],
headers=resp["headers"],
Expand Down
34 changes: 34 additions & 0 deletions tests/slack_sdk/web/test_web_client_malformed_json_body.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import unittest
from unittest.mock import patch

from slack_sdk.errors import SlackApiError
from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
from slack_sdk.web import WebClient


class TestWebClient_MalformedJsonBody(unittest.TestCase):
"""A 200 response whose body looks like JSON but is truncated must surface as a SlackApiError,
no matter whether retry handlers are configured."""

malformed_response = {"status": 200, "headers": {}, "body": '{"ok": tru'}

def _assert_non_json_error(self, client: WebClient):
with patch.object(client, "_perform_urllib_http_request_internal", return_value=dict(self.malformed_response)):
with self.assertRaises(SlackApiError) as ctx:
client.api_test()
self.assertTrue(ctx.exception.response["error"].startswith("Received a response in a non-JSON format"))

def test_default_retry_handlers(self):
self._assert_non_json_error(WebClient(token="xoxb-test"))

def test_custom_retry_handlers(self):
self._assert_non_json_error(WebClient(token="xoxb-test", retry_handlers=[RateLimitErrorRetryHandler()]))

def test_no_retry_handlers(self):
self._assert_non_json_error(WebClient(token="xoxb-test", retry_handlers=[]))

def test_well_formed_json_body_is_still_parsed(self):
client = WebClient(token="xoxb-test")
response = {"status": 200, "headers": {}, "body": '{"ok": true}'}
with patch.object(client, "_perform_urllib_http_request_internal", return_value=response):
self.assertTrue(client.api_test()["ok"])