Fix command line sensors removing quotes with template (#35559)

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Xiaonan Shen 2020-06-10 09:31:59 -07:00 committed by GitHub
parent e13f206a06
commit c65e72886c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 2 deletions

View File

@ -3,7 +3,6 @@ from collections.abc import Mapping
from datetime import timedelta from datetime import timedelta
import json import json
import logging import logging
import shlex
import subprocess import subprocess
import voluptuous as vol import voluptuous as vol
@ -171,7 +170,7 @@ class CommandSensorData:
pass pass
else: else:
# Template used. Construct the string used in the shell # Template used. Construct the string used in the shell
command = str(" ".join([prog] + shlex.split(rendered_args))) command = f"{prog} {rendered_args}"
try: try:
_LOGGER.debug("Running command: %s", command) _LOGGER.debug("Running command: %s", command)
return_value = subprocess.check_output( return_value = subprocess.check_output(

View File

@ -70,6 +70,23 @@ class TestCommandSensorSensor(unittest.TestCase):
assert data.value == "Works" assert data.value == "Works"
def test_template_render_with_quote(self):
"""Ensure command with templates and quotes get rendered properly."""
self.hass.states.set("sensor.test_state", "Works 2")
with patch(
"homeassistant.components.command_line.sensor.subprocess.check_output",
return_value=b"Works\n",
) as check_output:
data = command_line.CommandSensorData(
self.hass, 'echo "{{ states.sensor.test_state.state }}" "3 4"', 15,
)
data.update()
assert data.value == "Works"
check_output.assert_called_once_with(
'echo "Works 2" "3 4"', shell=True, timeout=15 # nosec # shell by design
)
def test_bad_command(self): def test_bad_command(self):
"""Test bad command.""" """Test bad command."""
data = command_line.CommandSensorData(self.hass, "asdfasdf", 15) data = command_line.CommandSensorData(self.hass, "asdfasdf", 15)