Skip to content
This repository has been archived by the owner on Nov 25, 2017. It is now read-only.

Commit

Permalink
Fixed JSON encoding of request bodies.
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobian committed Jul 12, 2010
1 parent 786e560 commit 8394f00
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 4 deletions.
1 change: 1 addition & 0 deletions storymarket/__init__.py
Expand Up @@ -2,6 +2,7 @@

__version__ = '1.0'

from . import exceptions
from .client import StorymarketClient
from .categories import Category, CategoryManager, SubcategoryManager
from .content import (Audio, Data, Photo, Text, Video, AudioManager,
Expand Down
16 changes: 14 additions & 2 deletions storymarket/client.py
Expand Up @@ -36,9 +36,21 @@ def request(self, url, method, *args, **kwargs):
return resp, body

def _storymarket_request(self, url, method, *args, **kwargs):
# Separate method for mocking and testing.
"""Real request method for mocking and testing."""
# Encode the body as JSON unless otherwise specified
if 'body' in kwargs:
ctype = kwargs['headers'].setdefault('Content-Type', 'application/json')
if ctype == 'application/json':
kwargs['body'] = json.dumps(kwargs['body'])

resp, body = super(StorymarketClient, self).request(url, method, *args, **kwargs)
body = json.loads(body) if body else None
try:
body = json.loads(body) if body else None
except ValueError:
# Raised by simplejson if the body can't be decoded.
# This almost always is accompanied by an error status,
# which'll get raised above.
pass
return resp, body

def get(self, url, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion storymarket/exceptions.py
Expand Up @@ -22,6 +22,6 @@ def from_response(response, body):
"""
cls = _code_map.get(response.status, StorymarketError)
if body:
return cls(code=response.status, message=body['errors'][0]['message'])
return cls(code=response.status, message=body)
else:
return cls(code=response.status)
37 changes: 37 additions & 0 deletions tests/test_client.py
@@ -0,0 +1,37 @@
"""
Tests for the parts of StorymarketClient not otherwise covered.
"""

import mock
import storymarket
import httplib2
from nose.tools import assert_raises

client = storymarket.StorymarketClient('APIKEY')

def test_json_encoding():
mock_resp = httplib2.Response({"status": 200})
mock_body = '{"hi": "there"}'
mock_req = mock.Mock(return_value=(mock_resp, mock_body))

with mock.patch('httplib2.Http.request', mock_req):
client.request('/url/', 'POST', body={"hello": ["world"]})
mock_req.assert_called_with(
'%surl/' % client.BASE_URL,
'POST',
body = '{"hello": ["world"]}',
headers = {
'Authorization': client.apikey,
'Content-Type': 'application/json',
'User-Agent': client.USER_AGENT,
},
)

def test_error_response():
mock_resp = httplib2.Response({"status": 400})
mock_body = 'oops!'
mock_req = mock.Mock(return_value=(mock_resp, mock_body))

with mock.patch('httplib2.Http.request', mock_req):
assert_raises(storymarket.exceptions.StorymarketError, client.request, '/url/', 'GET')

2 changes: 1 addition & 1 deletion tests/test_exceptions.py
Expand Up @@ -9,7 +9,7 @@ def test_exception_from_response():
resp = mock.Mock()
resp.status = 500
# FIXME: what do error responses actually look like?
exc = storymarket.exceptions.from_response(resp, {'errors':[{'message': 'Oops!'}]})
exc = storymarket.exceptions.from_response(resp, "Oops!")
assert_isinstance(exc, storymarket.exceptions.StorymarketError)
assert_equal(str(exc), 'Oops! (HTTP 500)')

Expand Down

0 comments on commit 8394f00

Please sign in to comment.