mirror of
https://github.com/home-assistant/core.git
synced 2025-07-23 05:07:41 +00:00
Added checks for empty replies from REST calls and supporting tests (#12904)
This commit is contained in:
parent
3682080da2
commit
03225cf20f
@ -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:
|
||||
|
@ -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."""
|
||||
|
Loading…
x
Reference in New Issue
Block a user