From cfd8695aaa2b9b41a1207a1d8d956cae4e2aebda Mon Sep 17 00:00:00 2001 From: Steven Rollason <2099542+gadgetchnnel@users.noreply.github.com> Date: Thu, 6 Apr 2023 20:06:31 +0100 Subject: [PATCH] Fix command_template sensor value_template not being used if json_attributes set (#90603) * Allow value_template to be used if json_attributes set * Set state to None if no value_template and json_attributes used * Refactor check for no value_template when json_attributes used * Updated and additional unit test * Updated to set _attr_native_value and return if value_template is None * Update unit test docstring * Updated test docstring based on feedback --- .../components/command_line/sensor.py | 5 ++++- tests/components/command_line/test_sensor.py | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/command_line/sensor.py b/homeassistant/components/command_line/sensor.py index f459e415661..b6a2b8d83fa 100644 --- a/homeassistant/components/command_line/sensor.py +++ b/homeassistant/components/command_line/sensor.py @@ -137,8 +137,11 @@ class CommandSensor(SensorEntity): _LOGGER.warning("Unable to parse output as JSON: %s", value) else: _LOGGER.warning("Empty reply found when expecting JSON data") + if self._value_template is None: + self._attr_native_value = None + return - elif self._value_template is not None: + if self._value_template is not None: self._attr_native_value = ( self._value_template.async_render_with_possible_json_value( value, diff --git a/tests/components/command_line/test_sensor.py b/tests/components/command_line/test_sensor.py index 4643891691f..188f4aac062 100644 --- a/tests/components/command_line/test_sensor.py +++ b/tests/components/command_line/test_sensor.py @@ -169,6 +169,28 @@ async def test_update_with_json_attrs(hass: HomeAssistant) -> None: ) entity_state = hass.states.get("sensor.test") assert entity_state + assert entity_state.state == "unknown" + assert entity_state.attributes["key"] == "some_json_value" + assert entity_state.attributes["another_key"] == "another_json_value" + assert entity_state.attributes["key_three"] == "value_three" + + +async def test_update_with_json_attrs_and_value_template(hass: HomeAssistant) -> None: + """Test json_attributes can be used together with value_template.""" + await setup_test_entities( + hass, + { + "command": ( + 'echo { \\"key\\": \\"some_json_value\\", \\"another_key\\": ' + '\\"another_json_value\\", \\"key_three\\": \\"value_three\\" }' + ), + "json_attributes": ["key", "another_key", "key_three"], + "value_template": '{{ value_json["key"] }}', + }, + ) + entity_state = hass.states.get("sensor.test") + assert entity_state + assert entity_state.state == "some_json_value" assert entity_state.attributes["key"] == "some_json_value" assert entity_state.attributes["another_key"] == "another_json_value" assert entity_state.attributes["key_three"] == "value_three"