Skip to content

Commit

Permalink
Merge pull request #541 from stripe/ob-fix-219
Browse files Browse the repository at this point in the history
Add convert_to_dict method
  • Loading branch information
ob-stripe authored Mar 14, 2019
2 parents c9aed00 + 14fcc64 commit 08d0597
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
20 changes: 20 additions & 0 deletions stripe/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,26 @@ def convert_to_stripe_object(
return resp


def convert_to_dict(obj):
"""Converts a StripeObject back to a regular dict.
Nested StripeObjects are also converted back to regular dicts.
:param obj: The StripeObject to convert.
:returns: The StripeObject as a dict.
"""
if isinstance(obj, list):
return [convert_to_dict(i) for i in obj]
# This works by virtue of the fact that StripeObjects _are_ dicts. The dict
# comprehension returns a regular dict and recursively applies the
# conversion to each value.
elif isinstance(obj, dict):
return {k: convert_to_dict(v) for k, v in six.iteritems(obj)}
else:
return obj


def populate_headers(idempotency_key):
if idempotency_key is not None:
return {"Idempotency-Key": idempotency_key}
Expand Down
26 changes: 26 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import sys
from collections import namedtuple

import stripe
from stripe import util
from stripe.six.moves import builtins

Expand Down Expand Up @@ -125,3 +126,28 @@ def test_logfmt(self):
for case in cases:
result = util.logfmt(case.props)
assert result == case.expected

def test_convert_to_stripe_object_and_back(self):
resp = {
"object": "balance",
"available": [
{
"amount": 234,
"currency": "usd",
"source_types": {"card": 234},
}
],
"livemode": False,
}

obj = util.convert_to_stripe_object(resp)
assert type(obj) == stripe.Balance
assert type(obj.available) == list
assert type(obj.available[0]) == stripe.stripe_object.StripeObject

d = util.convert_to_dict(obj)
assert type(d) == dict
assert type(d["available"]) == list
assert type(d["available"][0]) == dict

assert d == resp

0 comments on commit 08d0597

Please sign in to comment.