Skip to content
Browse files

pep8, catch deserialization errors

  • Loading branch information...
1 parent 0f7f8aa commit 8cf0523271d0da62d25099eb9eee3a645df6c329 Pound Marshall committed
Showing with 29 additions and 4 deletions.
  1. +7 −2 balanced/http_client.py
  2. +3 −2 balanced/resources.py
  3. +1 −0 test-requirements.txt
  4. +18 −0 tests/test_client.py
View
9 balanced/http_client.py
@@ -7,7 +7,7 @@
from balanced.config import Config
from balanced.utils import to_json
-from balanced.exc import HTTPError
+from balanced.exc import HTTPError, BalancedError
serializers = {
'application/json': to_json
@@ -148,7 +148,12 @@ def delete(self, uri, **kwargs):
return resp
def deserialize(self, resp):
- return deserializers[resp.headers['Content-Type']](resp.content)
+ try:
+ return deserializers[resp.headers['Content-Type']](resp.content)
+ except KeyError:
+ raise BalancedError('Invalid content type "{}": {}'.format(
+ resp.headers['Content-Type'], resp.content,
+ ))
def serialize(self, kwargs):
content_type = self.config.requests['base_headers']['Content-Type']
View
5 balanced/resources.py
@@ -451,8 +451,9 @@ def create_buyer(self, email_address, card_uri, name=None, meta=None):
meta=meta,
).save()
- def create_merchant(self, email_address, merchant=None, bank_account_uri=None,
- name=None, meta=None, merchant_uri=None):
+ def create_merchant(self, email_address, merchant=None,
+ bank_account_uri=None, name=None, meta=None,
+ merchant_uri=None):
if not any([merchant, merchant_uri]):
raise ResourceError('Must have merchant or merchant_uri')
meta = meta or {}
View
1 test-requirements.txt
@@ -1,3 +1,4 @@
nose==1.1.2
bottle==0.10.9
nose-setenv
+mock==0.8.0
View
18 tests/test_client.py
@@ -1,6 +1,7 @@
import unittest
import balanced
+import mock
class TestConfig(unittest.TestCase):
@@ -49,3 +50,20 @@ def test_client_key_switch(self):
with balanced.key_switcher('new_key'):
self.assertEqual(the_config.api_key_secret, 'new_key')
self.assertEqual(the_config.api_key_secret, current_key)
+
+
+class TestHTTPClient(unittest.TestCase):
+
+ def test_deserialization(self):
+ resp = mock.Mock()
+ resp.headers = {
+ 'Content-Type': 'text/html',
+ }
+ resp.content = 'Unhandled Exception'
+ client = balanced.HTTPClient()
+ with self.assertRaises(balanced.exc.BalancedError):
+ client.deserialize(resp)
+ resp.headers['Content-Type'] = 'application/json'
+ resp.content = '{"hi": "world"}'
+ deserialized = client.deserialize(resp)
+ self.assertItemsEqual(deserialized, {u'hi': u'world'})

0 comments on commit 8cf0523

Please sign in to comment.
Something went wrong with that request. Please try again.