Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix serialization of nested ListObjects #441

Merged
merged 1 commit into from
Jul 6, 2018
Merged
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
18 changes: 9 additions & 9 deletions stripe/stripe_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__()
Expand Down Expand Up @@ -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(
Expand All @@ -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
Expand Down
13 changes: 13 additions & 0 deletions tests/api_resources/test_list_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand Down