From 924c313c8a36579c812e0bbc87f0078b1c26f3d8 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 2 Mar 2020 01:22:01 -0600 Subject: [PATCH] =?UTF-8?q?Add=20application/xml=20as=20an=20XML=20to=20JS?= =?UTF-8?q?ON=20auto=20converted=20mime=20type=E2=80=A6=20(#32289)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Resolves issue #32280 --- homeassistant/components/rest/sensor.py | 5 +++- tests/components/rest/test_sensor.py | 33 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/rest/sensor.py b/homeassistant/components/rest/sensor.py index 7c8cfb9d3d0..dbe1d75f6af 100644 --- a/homeassistant/components/rest/sensor.py +++ b/homeassistant/components/rest/sensor.py @@ -206,7 +206,10 @@ class RestSensor(Entity): # If the http request failed, headers will be None content_type = self.rest.headers.get("content-type") - if content_type and content_type.startswith("text/xml"): + if content_type and ( + content_type.startswith("text/xml") + or content_type.startswith("application/xml") + ): try: value = json.dumps(xmltodict.parse(value)) _LOGGER.debug("JSON converted from XML: %s", value) diff --git a/tests/components/rest/test_sensor.py b/tests/components/rest/test_sensor.py index 5018418f493..74f7faae4b3 100644 --- a/tests/components/rest/test_sensor.py +++ b/tests/components/rest/test_sensor.py @@ -559,6 +559,39 @@ class TestRestSensor(unittest.TestCase): assert "12556" == self.sensor.device_state_attributes["ver"] assert "bogus" == self.sensor.state + def test_update_with_application_xml_convert_json_attrs_with_jsonattr_template( + self, + ): + """Test attributes get extracted from a JSON result that was converted from XML with application/xml mime type.""" + json_attrs_path = "$.main" + value_template = template("{{ value_json.main.dog }}") + value_template.hass = self.hass + + self.rest.update = Mock( + "rest.RestData.update", + side_effect=self.update_side_effect( + "
13
", + CaseInsensitiveDict({"Content-Type": "application/xml"}), + ), + ) + self.sensor = rest.RestSensor( + self.hass, + self.rest, + self.name, + self.unit_of_measurement, + self.device_class, + value_template, + ["dog", "cat"], + self.force_update, + self.resource_template, + json_attrs_path, + ) + + self.sensor.update() + assert "3" == self.sensor.device_state_attributes["cat"] + assert "1" == self.sensor.device_state_attributes["dog"] + assert "1" == self.sensor.state + @patch("homeassistant.components.rest.sensor._LOGGER") def test_update_with_xml_convert_bad_xml(self, mock_logger): """Test attributes get extracted from a XML result with bad xml."""