From 73cdf00512fd24e961656afb012a02e371626f39 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sat, 9 Jan 2016 16:01:27 -0800 Subject: [PATCH] More service helper tests --- homeassistant/helpers/service.py | 9 +++++++-- tests/helpers/test_service.py | 33 ++++++++++++++++++++++++++++++-- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/homeassistant/helpers/service.py b/homeassistant/helpers/service.py index 530f72fa22f..15cfe9b97c6 100644 --- a/homeassistant/helpers/service.py +++ b/homeassistant/helpers/service.py @@ -13,11 +13,16 @@ _LOGGER = logging.getLogger(__name__) def call_from_config(hass, config, blocking=False): """Call a service based on a config hash.""" - if CONF_SERVICE not in config: + if not isinstance(config, dict) or CONF_SERVICE not in config: _LOGGER.error('Missing key %s: %s', CONF_SERVICE, config) return - domain, service = split_entity_id(config[CONF_SERVICE]) + try: + domain, service = split_entity_id(config[CONF_SERVICE]) + except ValueError: + _LOGGER.error('Invalid service specified: %s', config[CONF_SERVICE]) + return + service_data = config.get(CONF_SERVICE_DATA) if service_data is None: diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index 32a36edc5f1..aa2cab07d0d 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -4,11 +4,9 @@ tests.helpers.test_service Test service helpers. """ -from datetime import timedelta import unittest from unittest.mock import patch -import homeassistant.core as ha from homeassistant.const import SERVICE_TURN_ON from homeassistant.helpers import service @@ -37,3 +35,34 @@ class TestServiceHelpers(unittest.TestCase): self.hass.pool.block_till_done() self.assertEqual(['hello.world', 'sensor.beer'], self.calls[-1].data.get('entity_id')) + + def test_not_mutate_input(self): + orig = { + 'service': 'test_domain.test_service', + 'entity_id': 'hello.world, sensor.beer', + 'data': { + 'hello': 1, + }, + } + service.call_from_config(self.hass, orig) + self.hass.pool.block_till_done() + self.assertEqual({ + 'service': 'test_domain.test_service', + 'entity_id': 'hello.world, sensor.beer', + 'data': { + 'hello': 1, + }, + }, orig) + + @patch('homeassistant.helpers.service._LOGGER.error') + def test_fail_silently_if_no_service(self, mock_log): + service.call_from_config(self.hass, None) + self.assertEqual(1, mock_log.call_count) + + service.call_from_config(self.hass, {}) + self.assertEqual(2, mock_log.call_count) + + service.call_from_config(self.hass, { + 'service': 'invalid' + }) + self.assertEqual(3, mock_log.call_count)