Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
Catch both JSONDecodeError and ValueError and add a unit test to conf…
Browse files Browse the repository at this point in the history
…irm that both are caught and the expected service exception gets raised.
  • Loading branch information
danielgtaylor committed Aug 1, 2013
1 parent d5a5c01 commit 954a50c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
12 changes: 10 additions & 2 deletions boto/cloudsearch/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,16 @@ class CommitMismatchError(Exception):
pass


try:
from simplejson import JSONDecodeError
except ImportError:
class FakeJSONDecodeError(Exception):
pass

JSONDecodeError = FakeJSONDecodeError


class SearchResults(object):

def __init__(self, **attrs):
self.rid = attrs['info']['rid']
# self.doc_coverage_pct = attrs['info']['doc-coverage-pct']
Expand Down Expand Up @@ -291,7 +299,7 @@ def __call__(self, query):
r = requests.get(url, params=params)
try:
data = json.loads(r.content)
except ValueError,e:
except (JSONDecodeError, ValueError), e:
if r.status_code == 403:
msg = ''
import re
Expand Down
43 changes: 43 additions & 0 deletions tests/unit/cloudsearch/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import mock
from boto.compat import json
from tests.unit import unittest

from .test_search import HOSTNAME, CloudSearchSearchBaseTest
from boto.cloudsearch.search import SearchConnection, SearchServiceException


def fake_loads_value_error(content, *args, **kwargs):
"""Callable to generate a fake ValueError"""
raise ValueError("HAHAHA! Totally not simplejson & you gave me bad JSON.")


def fake_loads_json_error(content, *args, **kwargs):
"""Callable to generate a fake JSONDecodeError"""
raise json.JSONDecodeError('Using simplejson & you gave me bad JSON.',
'', 0)


class CloudSearchJSONExceptionTest(CloudSearchSearchBaseTest):
response = '{}'

def test_no_simplejson_value_error(self):
with mock.patch.object(json, 'loads', fake_loads_value_error):
search = SearchConnection(endpoint=HOSTNAME)

try:
search.search(q='test')
self.fail('This should never run!')
except SearchServiceException, err:
self.assertTrue('non-json' in str(err))

@unittest.skipUnless(hasattr(json, 'JSONDecodeError'),
'requires simplejson')
def test_simplejson_jsondecodeerror(self):
with mock.patch.object(json, 'loads', fake_loads_json_error):
search = SearchConnection(endpoint=HOSTNAME)

try:
search.search(q='test')
self.fail('This should never run!')
except SearchServiceException, err:
self.assertTrue('non-json' in str(err))

0 comments on commit 954a50c

Please sign in to comment.