Skip to content

Commit

Permalink
Merge pull request #698 from stripe/ob-fix-695
Browse files Browse the repository at this point in the history
Fix issue where StripeObjects in lists would not be converted to dicts
  • Loading branch information
remi-stripe authored Dec 1, 2020
2 parents 5f06879 + 78e3d0a commit 5714996
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
19 changes: 14 additions & 5 deletions stripe/stripe_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,11 +278,20 @@ 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
def maybe_to_dict_recursive(value):
if value is None:
return None
elif isinstance(value, StripeObject):
return value.to_dict_recursive()
else:
return value

return {
key: list(map(maybe_to_dict_recursive, value))
if isinstance(value, list)
else maybe_to_dict_recursive(value)
for key, value in six.iteritems(dict(self))
}

@property
def stripe_id(self):
Expand Down
24 changes: 24 additions & 0 deletions tests/test_stripe_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,30 @@ def test_deepcopy(self):
# Verify that we're actually deep copying nested values.
assert id(nested) != id(copied.nested)

def test_to_dict_recursive(self):
foo = stripe.stripe_object.StripeObject.construct_from(
{"value": "foo"}, "mykey"
)
bar = stripe.stripe_object.StripeObject.construct_from(
{"value": "bar"}, "mykey"
)
obj = stripe.stripe_object.StripeObject.construct_from(
{"empty": "", "value": "foobar", "nested": [foo, bar]}, "mykey"
)

d = obj.to_dict_recursive()
assert d == {
"empty": "",
"value": "foobar",
"nested": [{"value": "foo"}, {"value": "bar"}],
}
assert not isinstance(
d["nested"][0], stripe.stripe_object.StripeObject
)
assert not isinstance(
d["nested"][1], stripe.stripe_object.StripeObject
)

def test_serialize_empty_string_unsets(self):
class SerializeToEmptyString(stripe.stripe_object.StripeObject):
def serialize(self, previous):
Expand Down

0 comments on commit 5714996

Please sign in to comment.