From 672fca6dbfff9de0a43af67e0bb53619e2971bae Mon Sep 17 00:00:00 2001 From: Kevin Fronczak Date: Tue, 26 May 2020 20:44:24 +0000 Subject: [PATCH] Handle json decode error --- blinkpy/auth.py | 10 +++++++++- tests/test_auth.py | 7 ++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/blinkpy/auth.py b/blinkpy/auth.py index 778daf3..2f07048 100644 --- a/blinkpy/auth.py +++ b/blinkpy/auth.py @@ -111,12 +111,14 @@ class Auth: if not json_resp: return response - json_data = response.json() try: + json_data = response.json() if json_data["code"] in ERROR.BLINK_ERRORS: raise exceptions.ConnectionError except KeyError: pass + except (AttributeError, ValueError): + raise BlinkBadResponse return json_data @@ -161,6 +163,8 @@ class Auth: ) except (TokenRefreshFailed, LoginError): _LOGGER.error("Endpoint %s failed. Unable to refresh login tokens", url) + except BlinkBadResponse: + _LOGGER.error("Expected json response, but received: %s", response) _LOGGER.error("Endpoint %s failed", url) return None @@ -192,3 +196,7 @@ class TokenRefreshFailed(Exception): class LoginError(Exception): """Class to throw failed login exception.""" + + +class BlinkBadResponse(Exception): + """Class to throw bad json response exception.""" diff --git a/tests/test_auth.py b/tests/test_auth.py index 88f9d7d..8086267 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -3,7 +3,7 @@ import unittest from unittest import mock from requests import exceptions -from blinkpy.auth import Auth, LoginError, TokenRefreshFailed +from blinkpy.auth import Auth, LoginError, TokenRefreshFailed, BlinkBadResponse import blinkpy.helpers.constants as const import tests.mock_responses as mresp @@ -100,6 +100,11 @@ class TestAuth(unittest.TestCase): fake_resp = "foobar" self.assertEqual(self.auth.validate_response(fake_resp, False), "foobar") + def test_response_bad_json(self): + """Check response when not json but expecting json.""" + with self.assertRaises(BlinkBadResponse): + self.auth.validate_response(None, True) + def test_header(self): """Test header data.""" self.auth.token = "bar"