From 5f1b0fb15cae2480c60a3318f987e02a1b2a2c1f Mon Sep 17 00:00:00 2001 From: gjbadros Date: Tue, 26 Nov 2019 13:10:58 -0800 Subject: [PATCH] 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. --- homeassistant/components/rest/sensor.py | 7 ++++++- tests/components/rest/test_sensor.py | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/rest/sensor.py b/homeassistant/components/rest/sensor.py index b89e96a0f34..6fdf5ce7221 100644 --- a/homeassistant/components/rest/sensor.py +++ b/homeassistant/components/rest/sensor.py @@ -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) diff --git a/tests/components/rest/test_sensor.py b/tests/components/rest/test_sensor.py index c6cfce90a20..d770f21a403 100644 --- a/tests/components/rest/test_sensor.py +++ b/tests/components/rest/test_sensor.py @@ -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."""