Allow rest sensor list responses (#28835)

* Make rest sensor a little bit more flexible and allow the response to be a list with 0th element being a dictionary

* Black formatter wanted a different formatting

* Added test case for a list response with dict as 0th element

* Fixed lint error - it thinks a + STRING is an avoidance of using % sequences for log messages; I generally prefer explicit + rather than string juxtaposition for combining string literals, but sounds like that's not the standard

* Fixed test case -- I added it to the wrong scenario and need to use the one with json_attrs.
pull/29004/head^2
gjbadros 2019-11-26 13:10:58 -08:00 committed by Fabian Affolter
parent b72c6c4424
commit 5f1b0fb15c
2 changed files with 26 additions and 1 deletions

View File

@ -197,13 +197,18 @@ class RestSensor(Entity):
if value:
try:
json_dict = json.loads(value)
if isinstance(json_dict, list):
json_dict = json_dict[0]
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")
_LOGGER.warning(
"JSON result was not a dictionary"
" or list with 0th element a dictionary"
)
except ValueError:
_LOGGER.warning("REST result could not be parsed as JSON")
_LOGGER.debug("Erroneous JSON: %s", value)

View File

@ -284,6 +284,26 @@ class TestRestSensor(unittest.TestCase):
self.sensor.update()
assert "some_json_value" == self.sensor.device_state_attributes["key"]
def test_update_with_json_attrs_list_dict(self):
"""Test attributes get extracted from a JSON list[0] result."""
self.rest.update = Mock(
"rest.RestData.update",
side_effect=self.update_side_effect('[{ "key": "another_value" }]'),
)
self.sensor = rest.RestSensor(
self.hass,
self.rest,
self.name,
self.unit_of_measurement,
self.device_class,
None,
["key"],
self.force_update,
self.resource_template,
)
self.sensor.update()
assert "another_value" == self.sensor.device_state_attributes["key"]
@patch("homeassistant.components.rest.sensor._LOGGER")
def test_update_with_json_attrs_no_data(self, mock_logger):
"""Test attributes when no JSON result fetched."""