From 585b2d43e974cbaf8bf57ef0bd71cee96261ef44 Mon Sep 17 00:00:00 2001 From: Olivier Bellone Date: Fri, 6 Jul 2018 14:14:46 +0200 Subject: [PATCH] Fix serialization of nested ListObjects --- stripe/stripe_object.py | 18 +++++++++--------- tests/api_resources/test_list_object.py | 13 +++++++++++++ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/stripe/stripe_object.py b/stripe/stripe_object.py index 640ef9ad5..b560f153e 100644 --- a/stripe/stripe_object.py +++ b/stripe/stripe_object.py @@ -40,13 +40,6 @@ def default(self, obj): return api_requestor._encode_datetime(obj) return super(StripeObject.ReprJSONEncoder, self).default(obj) - def encode(self, obj): - # ListObject has a custom __len__ method, but we want to serialize - # its attributes even if __len__ returns 0. - if isinstance(obj, stripe.ListObject): - obj = dict(obj) - return super(StripeObject.ReprJSONEncoder, self).encode(obj) - def __init__(self, id=None, api_key=None, stripe_version=None, stripe_account=None, last_response=None, **params): super(StripeObject, self).__init__() @@ -235,8 +228,8 @@ def __repr__(self): return unicode_repr def __str__(self): - return util.json.dumps(self, sort_keys=True, indent=2, - cls=self.ReprJSONEncoder) + return util.json.dumps(self.to_dict_recursive(), sort_keys=True, + indent=2, cls=self.ReprJSONEncoder) def to_dict(self): warnings.warn( @@ -247,6 +240,13 @@ def to_dict(self): return dict(self) + def to_dict_recursive(self): + d = dict(self) + for k, v in six.iteritems(d): + if isinstance(v, StripeObject): + d[k] = v.to_dict_recursive() + return d + @property def stripe_id(self): return self.id diff --git a/tests/api_resources/test_list_object.py b/tests/api_resources/test_list_object.py index 022bb19ba..ee09891df 100644 --- a/tests/api_resources/test_list_object.py +++ b/tests/api_resources/test_list_object.py @@ -125,6 +125,19 @@ def test_serialize_empty_list(self): json.loads(serialized), 'mykey') self.assertEqual(empty, deserialized) + def test_serialize_nested_empty_list(self): + empty = stripe.ListObject.construct_from({ + 'object': 'list', + 'data': [], + }, 'mykey') + obj = stripe.stripe_object.StripeObject.construct_from({ + 'nested': empty, + }, 'mykey') + serialized = str(obj) + deserialized = stripe.StripeObject.construct_from( + json.loads(serialized), 'mykey') + self.assertEqual(empty, deserialized.nested) + class AutoPagingTests(StripeTestCase):