From 63f1660b8f79b9975c0044fab400c9fcbb928953 Mon Sep 17 00:00:00 2001 From: Jesse Rosalia Date: Mon, 16 Dec 2024 11:39:52 -0800 Subject: [PATCH 1/2] fixed an issue where string http_body values passed into StripeError were discarded --- stripe/_error.py | 23 +++++++++++++++-------- tests/test_error.py | 17 +++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/stripe/_error.py b/stripe/_error.py index 3b486ee79..7fd84b412 100644 --- a/stripe/_error.py +++ b/stripe/_error.py @@ -26,14 +26,21 @@ def __init__( super(StripeError, self).__init__(message) body: Optional[str] = None - if http_body and hasattr(http_body, "decode"): - try: - body = cast(bytes, http_body).decode("utf-8") - except BaseException: - body = ( - "" - ) + if http_body: + # http_body can sometimes be a memoryview which must be cast + # to a "bytes" before calling decode, so we check for the + # decode attribute and then cast + if hasattr(http_body, "decode"): + try: + body = cast(bytes, http_body).decode("utf-8") + except BaseException: + body = ( + "" + ) + elif isinstance(http_body, str): + body = http_body + pass self._message = message self.http_body = body diff --git a/tests/test_error.py b/tests/test_error.py index 6f96227a4..fe0e4a45b 100644 --- a/tests/test_error.py +++ b/tests/test_error.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- +import json from stripe import error @@ -28,6 +29,22 @@ def test_repr(self): "request_id='123')" ) + def test_error_string_body(self): + http_body = '{"error": {"code": "some_error"}}' + err = error.StripeError( + "message", http_body=http_body, json_body=json.loads(http_body) + ) + assert err.http_body is not None + assert err.http_body == json.dumps(err.json_body) + + def test_error_bytes_body(self): + http_body = '{"error": {"code": "some_error"}}'.encode("utf-8") + err = error.StripeError( + "message", http_body=http_body, json_body=json.loads(http_body) + ) + assert err.http_body is not None + assert err.http_body == json.dumps(err.json_body) + def test_error_object(self): err = error.StripeError( "message", json_body={"error": {"code": "some_error"}} From 263a5d7e356a9beca0f26d4c63b01d6f4dc44ef5 Mon Sep 17 00:00:00 2001 From: jar-stripe Date: Mon, 16 Dec 2024 12:04:10 -0800 Subject: [PATCH 2/2] Update _error.py removed extraneous pass --- stripe/_error.py | 1 - 1 file changed, 1 deletion(-) diff --git a/stripe/_error.py b/stripe/_error.py index 7fd84b412..14bc2f9a9 100644 --- a/stripe/_error.py +++ b/stripe/_error.py @@ -40,7 +40,6 @@ def __init__( ) elif isinstance(http_body, str): body = http_body - pass self._message = message self.http_body = body