mirror of
https://github.com/home-assistant/core.git
synced 2025-07-26 22:57:17 +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:
|
if self._json_attrs:
|
||||||
self._attributes = {}
|
self._attributes = {}
|
||||||
try:
|
if value:
|
||||||
json_dict = json.loads(value)
|
try:
|
||||||
if isinstance(json_dict, dict):
|
json_dict = json.loads(value)
|
||||||
attrs = {k: json_dict[k] for k in self._json_attrs
|
if isinstance(json_dict, dict):
|
||||||
if k in json_dict}
|
attrs = {k: json_dict[k] for k in self._json_attrs
|
||||||
self._attributes = attrs
|
if k in json_dict}
|
||||||
else:
|
self._attributes = attrs
|
||||||
_LOGGER.warning("JSON result was not a dictionary")
|
else:
|
||||||
except ValueError:
|
_LOGGER.warning("JSON result was not a dictionary")
|
||||||
_LOGGER.warning("REST result could not be parsed as JSON")
|
except ValueError:
|
||||||
_LOGGER.debug("Erroneous JSON: %s", value)
|
_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:
|
if value is None:
|
||||||
value = STATE_UNKNOWN
|
value = STATE_UNKNOWN
|
||||||
elif self._value_template is not None:
|
elif self._value_template is not None:
|
||||||
|
@ -207,6 +207,18 @@ class TestRestSensor(unittest.TestCase):
|
|||||||
self.assertEqual('some_json_value',
|
self.assertEqual('some_json_value',
|
||||||
self.sensor.device_state_attributes['key'])
|
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')
|
@patch('homeassistant.components.sensor.rest._LOGGER')
|
||||||
def test_update_with_json_attrs_not_dict(self, mock_logger):
|
def test_update_with_json_attrs_not_dict(self, mock_logger):
|
||||||
"""Test attributes get extracted from a JSON result."""
|
"""Test attributes get extracted from a JSON result."""
|
||||||
|
Loading…
x
Reference in New Issue
Block a user