diff --git a/homeassistant/components/sensor/rest.py b/homeassistant/components/sensor/rest.py index c295dcf16dc..74bfaa38f02 100644 --- a/homeassistant/components/sensor/rest.py +++ b/homeassistant/components/sensor/rest.py @@ -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: diff --git a/tests/components/sensor/test_rest.py b/tests/components/sensor/test_rest.py index eddab8caf4d..f2362867979 100644 --- a/tests/components/sensor/test_rest.py +++ b/tests/components/sensor/test_rest.py @@ -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."""