diff --git a/urbantz/delivery.py b/urbantz/delivery.py index bf944c1..e548805 100644 --- a/urbantz/delivery.py +++ b/urbantz/delivery.py @@ -69,17 +69,26 @@ class Delivery(JSONSerializable): """ Fetch the latest delivery information from the API. + :raises urbantz.exceptions.APIError: If the API returned a JSON error. :raises requests.exceptions.HTTPError: If the response has an - HTTP 4xx or 5xx code. - :raises urbantz.exceptions.APIError: If the API returned an error. + HTTP 4xx or 5xx code, or an empty payload. """ resp = requests.get(self.api_url) - resp.raise_for_status() - data = resp.json() + data = {} + try: + data = resp.json() + except Exception: + pass if 'error' in data: raise APIError(data['error']) + resp.raise_for_status() + if not data: + # If requests does not raise anything and there is no data, + # raise our own error + raise APIError({'message': 'API returned an empty payload'}) + self.use(data) # TODO: See if the payload holds a last update value diff --git a/urbantz/tests/test_delivery.py b/urbantz/tests/test_delivery.py index 35b2f41..1ff8a20 100644 --- a/urbantz/tests/test_delivery.py +++ b/urbantz/tests/test_delivery.py @@ -55,9 +55,29 @@ class TestDelivery(TestCase): requests_mock.get.call_args, call(self.delivery.api_url), ) - self.assertEqual(requests_mock.get().raise_for_status.call_count, 1) self.assertEqual(requests_mock.get().json.call_count, 1) self.assertEqual( excinfo.exception, APIError({'code': 42, 'message': 'Oh snap!'}), ) + + @patch('urbantz.delivery.requests') + def test_update_error_empty(self, requests_mock): + """ + Test that a Delivery will raise an APIError with a failed JSON parsing + """ + requests_mock.get.return_value.json.side_effect = ValueError + with self.assertRaises(APIError) as excinfo: + self.delivery.update() + + self.assertEqual(requests_mock.get.call_count, 1) + self.assertEqual( + requests_mock.get.call_args, + call(self.delivery.api_url), + ) + self.assertEqual(requests_mock.get().raise_for_status.call_count, 1) + self.assertEqual(requests_mock.get().json.call_count, 1) + self.assertEqual( + excinfo.exception, + APIError({'message': 'API returned an empty payload'}), + )