Added checks for empty replies from REST calls and supporting tests (#12904)

This commit is contained in:
Nicko van Someren 2018-03-05 16:30:28 -07:00 committed by Paulus Schoutsen
parent 3682080da2
commit 03225cf20f
2 changed files with 26 additions and 12 deletions

View File

@ -130,18 +130,20 @@ class RestSensor(Entity):
if self._json_attrs:
self._attributes = {}
try:
json_dict = json.loads(value)
if isinstance(json_dict, dict):
attrs = {k: json_dict[k] for k in self._json_attrs
if k in json_dict}
self._attributes = attrs
else:
_LOGGER.warning("JSON result was not a dictionary")
except ValueError:
_LOGGER.warning("REST result could not be parsed as JSON")
_LOGGER.debug("Erroneous JSON: %s", value)
if value:
try:
json_dict = json.loads(value)
if isinstance(json_dict, dict):
attrs = {k: json_dict[k] for k in self._json_attrs
if k in json_dict}
self._attributes = attrs
else:
_LOGGER.warning("JSON result was not a dictionary")
except ValueError:
_LOGGER.warning("REST result could not be parsed as JSON")
_LOGGER.debug("Erroneous JSON: %s", value)
else:
_LOGGER.warning("Empty reply found when expecting JSON data")
if value is None:
value = STATE_UNKNOWN
elif self._value_template is not None:

View File

@ -207,6 +207,18 @@ class TestRestSensor(unittest.TestCase):
self.assertEqual('some_json_value',
self.sensor.device_state_attributes['key'])
@patch('homeassistant.components.sensor.rest._LOGGER')
def test_update_with_json_attrs_no_data(self, mock_logger):
"""Test attributes when no JSON result fetched."""
self.rest.update = Mock('rest.RestData.update',
side_effect=self.update_side_effect(None))
self.sensor = rest.RestSensor(self.hass, self.rest, self.name,
self.unit_of_measurement, None, ['key'],
self.force_update)
self.sensor.update()
self.assertEqual({}, self.sensor.device_state_attributes)
self.assertTrue(mock_logger.warning.called)
@patch('homeassistant.components.sensor.rest._LOGGER')
def test_update_with_json_attrs_not_dict(self, mock_logger):
"""Test attributes get extracted from a JSON result."""