Merge branch 'dev' into nuheat

This commit is contained in:
Derek Brooks committed 2017-12-24 09:40:21 -07:00
commit bdf64ccbbb
122 files changed
+5592 -1210

No files matched your search

+213 -26
View File
@@ -2,7 +2,8 @@
import unittest
from homeassistant.setup import setup_component
from homeassistant.const import (ATTR_UNIT_OF_MEASUREMENT, TEMP_CELSIUS)
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT, STATE_UNKNOWN, TEMP_CELSIUS)
from tests.common import get_test_home_assistant
@@ -23,8 +24,7 @@ class TestThresholdSensor(unittest.TestCase):
config = {
'binary_sensor': {
'platform': 'threshold',
'threshold': '15',
'type': 'upper',
'upper': '15',
'entity_id': 'sensor.test_monitored',
}
}
@@ -37,12 +37,14 @@ class TestThresholdSensor(unittest.TestCase):
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('upper', state.attributes.get('type'))
self.assertEqual('sensor.test_monitored',
state.attributes.get('entity_id'))
self.assertEqual(16, state.attributes.get('sensor_value'))
self.assertEqual(float(config['binary_sensor']['threshold']),
state.attributes.get('threshold'))
self.assertEqual('above', state.attributes.get('position'))
self.assertEqual(float(config['binary_sensor']['upper']),
state.attributes.get('upper'))
self.assertEqual(0.0, state.attributes.get('hysteresis'))
self.assertEqual('upper', state.attributes.get('type'))
assert state.state == 'on'
@@ -65,9 +67,7 @@ class TestThresholdSensor(unittest.TestCase):
config = {
'binary_sensor': {
'platform': 'threshold',
'threshold': '15',
'name': 'Test_threshold',
'type': 'lower',
'lower': '15',
'entity_id': 'sensor.test_monitored',
}
}
@@ -77,8 +77,12 @@ class TestThresholdSensor(unittest.TestCase):
self.hass.states.set('sensor.test_monitored', 16)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_threshold')
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('above', state.attributes.get('position'))
self.assertEqual(float(config['binary_sensor']['lower']),
state.attributes.get('lower'))
self.assertEqual(0.0, state.attributes.get('hysteresis'))
self.assertEqual('lower', state.attributes.get('type'))
assert state.state == 'off'
@@ -86,26 +90,17 @@ class TestThresholdSensor(unittest.TestCase):
self.hass.states.set('sensor.test_monitored', 14)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_threshold')
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 15)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_threshold')
assert state.state == 'off'
def test_sensor_hysteresis(self):
"""Test if source is above threshold using hysteresis."""
config = {
'binary_sensor': {
'platform': 'threshold',
'threshold': '15',
'upper': '15',
'hysteresis': '2.5',
'name': 'Test_threshold',
'type': 'upper',
'entity_id': 'sensor.test_monitored',
}
}
@@ -115,34 +110,226 @@ class TestThresholdSensor(unittest.TestCase):
self.hass.states.set('sensor.test_monitored', 20)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_threshold')
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('above', state.attributes.get('position'))
self.assertEqual(float(config['binary_sensor']['upper']),
state.attributes.get('upper'))
self.assertEqual(2.5, state.attributes.get('hysteresis'))
self.assertEqual('upper', state.attributes.get('type'))
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 13)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_threshold')
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 12)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_threshold')
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 17)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_threshold')
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 18)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test_threshold')
state = self.hass.states.get('binary_sensor.threshold')
assert state.state == 'on'
def test_sensor_in_range_no_hysteresis(self):
"""Test if source is within the range."""
config = {
'binary_sensor': {
'platform': 'threshold',
'lower': '10',
'upper': '20',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 16,
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('sensor.test_monitored',
state.attributes.get('entity_id'))
self.assertEqual(16, state.attributes.get('sensor_value'))
self.assertEqual('in_range', state.attributes.get('position'))
self.assertEqual(float(config['binary_sensor']['lower']),
state.attributes.get('lower'))
self.assertEqual(float(config['binary_sensor']['upper']),
state.attributes.get('upper'))
self.assertEqual(0.0, state.attributes.get('hysteresis'))
self.assertEqual('range', state.attributes.get('type'))
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 9)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('below', state.attributes.get('position'))
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 21)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('above', state.attributes.get('position'))
assert state.state == 'off'
def test_sensor_in_range_with_hysteresis(self):
"""Test if source is within the range."""
config = {
'binary_sensor': {
'platform': 'threshold',
'lower': '10',
'upper': '20',
'hysteresis': '2',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 16,
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('sensor.test_monitored',
state.attributes.get('entity_id'))
self.assertEqual(16, state.attributes.get('sensor_value'))
self.assertEqual('in_range', state.attributes.get('position'))
self.assertEqual(float(config['binary_sensor']['lower']),
state.attributes.get('lower'))
self.assertEqual(float(config['binary_sensor']['upper']),
state.attributes.get('upper'))
self.assertEqual(float(config['binary_sensor']['hysteresis']),
state.attributes.get('hysteresis'))
self.assertEqual('range', state.attributes.get('type'))
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 8)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('in_range', state.attributes.get('position'))
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 7)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('below', state.attributes.get('position'))
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 12)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('below', state.attributes.get('position'))
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 13)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('in_range', state.attributes.get('position'))
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 22)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('in_range', state.attributes.get('position'))
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', 23)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('above', state.attributes.get('position'))
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 18)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('above', state.attributes.get('position'))
assert state.state == 'off'
self.hass.states.set('sensor.test_monitored', 17)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('in_range', state.attributes.get('position'))
assert state.state == 'on'
def test_sensor_in_range_unknown_state(self):
"""Test if source is within the range."""
config = {
'binary_sensor': {
'platform': 'threshold',
'lower': '10',
'upper': '20',
'entity_id': 'sensor.test_monitored',
}
}
assert setup_component(self.hass, 'binary_sensor', config)
self.hass.states.set('sensor.test_monitored', 16,
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('sensor.test_monitored',
state.attributes.get('entity_id'))
self.assertEqual(16, state.attributes.get('sensor_value'))
self.assertEqual('in_range', state.attributes.get('position'))
self.assertEqual(float(config['binary_sensor']['lower']),
state.attributes.get('lower'))
self.assertEqual(float(config['binary_sensor']['upper']),
state.attributes.get('upper'))
self.assertEqual(0.0, state.attributes.get('hysteresis'))
self.assertEqual('range', state.attributes.get('type'))
assert state.state == 'on'
self.hass.states.set('sensor.test_monitored', STATE_UNKNOWN)
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.threshold')
self.assertEqual('unknown', state.attributes.get('position'))
assert state.state == 'off'
+305
View File
@@ -0,0 +1,305 @@
"""The tests for the webdav calendar component."""
# pylint: disable=protected-access
import datetime
import logging
import unittest
from unittest.mock import (patch, Mock, MagicMock)
import homeassistant.components.calendar as calendar_base
import homeassistant.components.calendar.caldav as caldav
from caldav.objects import Event
from homeassistant.const import CONF_PLATFORM, STATE_OFF, STATE_ON
from homeassistant.util import dt
from tests.common import get_test_home_assistant
TEST_PLATFORM = {calendar_base.DOMAIN: {CONF_PLATFORM: 'test'}}
_LOGGER = logging.getLogger(__name__)
DEVICE_DATA = {
"name": "Private Calendar",
"device_id": "Private Calendar"
}
EVENTS = [
"""BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//E-Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:1
DTSTAMP:20171125T000000Z
DTSTART:20171127T170000Z
DTEND:20171127T180000Z
SUMMARY:This is a normal event
LOCATION:Hamburg
DESCRIPTION:Surprisingly rainy
END:VEVENT
END:VCALENDAR
""",
"""BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Global Dynamics.//CalDAV Client//EN
BEGIN:VEVENT
UID:2
DTSTAMP:20171125T000000Z
DTSTART:20171127T100000Z
DTEND:20171127T110000Z
SUMMARY:This is an offset event !!-02:00
LOCATION:Hamburg
DESCRIPTION:Surprisingly shiny
END:VEVENT
END:VCALENDAR
""",
"""BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Global Corp.//CalDAV Client//EN
BEGIN:VEVENT
UID:3
DTSTAMP:20171125T000000Z
DTSTART:20171127
DTEND:20171128
SUMMARY:This is an all day event
LOCATION:Hamburg
DESCRIPTION:What a beautiful day
END:VEVENT
END:VCALENDAR
"""
]
def _local_datetime(hours, minutes):
"""Build a datetime object for testing in the correct timezone."""
return dt.as_local(datetime.datetime(2017, 11, 27, hours, minutes, 0))
def _mocked_dav_client(*args, **kwargs):
"""Mock requests.get invocations."""
calendars = [
_mock_calendar("First"),
_mock_calendar("Second")
]
principal = Mock()
principal.calendars = MagicMock(return_value=calendars)
client = Mock()
client.principal = MagicMock(return_value=principal)
return client
def _mock_calendar(name):
events = []
for idx, event in enumerate(EVENTS):
events.append(Event(None, "%d.ics" % idx, event, None, str(idx)))
calendar = Mock()
calendar.date_search = MagicMock(return_value=events)
calendar.name = name
return calendar
class TestComponentsWebDavCalendar(unittest.TestCase):
"""Test the WebDav calendar."""
hass = None # HomeAssistant
# pylint: disable=invalid-name
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.calendar = _mock_calendar("Private")
# pylint: disable=invalid-name
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
@patch('caldav.DAVClient', side_effect=_mocked_dav_client)
def test_setup_component(self, req_mock):
"""Test setup component with calendars."""
def _add_device(devices):
assert len(devices) == 2
assert devices[0].name == "First"
assert devices[0].dev_id == "First"
self.assertFalse(devices[0].data.include_all_day)
assert devices[1].name == "Second"
assert devices[1].dev_id == "Second"
self.assertFalse(devices[1].data.include_all_day)
caldav.setup_platform(self.hass,
{
"url": "http://test.local",
"custom_calendars": []
},
_add_device)
@patch('caldav.DAVClient', side_effect=_mocked_dav_client)
def test_setup_component_with_no_calendar_matching(self, req_mock):
"""Test setup component with wrong calendar."""
def _add_device(devices):
assert not devices
caldav.setup_platform(self.hass,
{
"url": "http://test.local",
"calendars": ["none"],
"custom_calendars": []
},
_add_device)
@patch('caldav.DAVClient', side_effect=_mocked_dav_client)
def test_setup_component_with_a_calendar_match(self, req_mock):
"""Test setup component with right calendar."""
def _add_device(devices):
assert len(devices) == 1
assert devices[0].name == "Second"
caldav.setup_platform(self.hass,
{
"url": "http://test.local",
"calendars": ["Second"],
"custom_calendars": []
},
_add_device)
@patch('caldav.DAVClient', side_effect=_mocked_dav_client)
def test_setup_component_with_one_custom_calendar(self, req_mock):
"""Test setup component with custom calendars."""
def _add_device(devices):
assert len(devices) == 1
assert devices[0].name == "HomeOffice"
assert devices[0].dev_id == "Second HomeOffice"
self.assertTrue(devices[0].data.include_all_day)
caldav.setup_platform(self.hass,
{
"url": "http://test.local",
"custom_calendars": [
{
"name": "HomeOffice",
"calendar": "Second",
"filter": "HomeOffice"
}]
},
_add_device)
@patch('homeassistant.util.dt.now', return_value=_local_datetime(17, 30))
def test_ongoing_event(self, mock_now):
"""Test that the ongoing event is returned."""
cal = caldav.WebDavCalendarEventDevice(self.hass,
DEVICE_DATA,
self.calendar)
self.assertEqual(cal.name, DEVICE_DATA["name"])
self.assertEqual(cal.state, STATE_ON)
self.assertEqual(cal.device_state_attributes, {
"message": "This is a normal event",
"all_day": False,
"offset_reached": False,
"start_time": "2017-11-27 17:00:00",
"end_time": "2017-11-27 18:00:00",
"location": "Hamburg",
"description": "Surprisingly rainy"
})
@patch('homeassistant.util.dt.now', return_value=_local_datetime(8, 30))
def test_ongoing_event_with_offset(self, mock_now):
"""Test that the offset is taken into account."""
cal = caldav.WebDavCalendarEventDevice(self.hass,
DEVICE_DATA,
self.calendar)
self.assertEqual(cal.state, STATE_OFF)
self.assertEqual(cal.device_state_attributes, {
"message": "This is an offset event",
"all_day": False,
"offset_reached": True,
"start_time": "2017-11-27 10:00:00",
"end_time": "2017-11-27 11:00:00",
"location": "Hamburg",
"description": "Surprisingly shiny"
})
@patch('homeassistant.util.dt.now', return_value=_local_datetime(12, 00))
def test_matching_filter(self, mock_now):
"""Test that the matching event is returned."""
cal = caldav.WebDavCalendarEventDevice(self.hass,
DEVICE_DATA,
self.calendar,
False,
"This is a normal event")
self.assertEqual(cal.state, STATE_OFF)
self.assertFalse(cal.offset_reached())
self.assertEqual(cal.device_state_attributes, {
"message": "This is a normal event",
"all_day": False,
"offset_reached": False,
"start_time": "2017-11-27 17:00:00",
"end_time": "2017-11-27 18:00:00",
"location": "Hamburg",
"description": "Surprisingly rainy"
})
@patch('homeassistant.util.dt.now', return_value=_local_datetime(12, 00))
def test_matching_filter_real_regexp(self, mock_now):
"""Test that the event matching the regexp is returned."""
cal = caldav.WebDavCalendarEventDevice(self.hass,
DEVICE_DATA,
self.calendar,
False,
"^This.*event")
self.assertEqual(cal.state, STATE_OFF)
self.assertFalse(cal.offset_reached())
self.assertEqual(cal.device_state_attributes, {
"message": "This is a normal event",
"all_day": False,
"offset_reached": False,
"start_time": "2017-11-27 17:00:00",
"end_time": "2017-11-27 18:00:00",
"location": "Hamburg",
"description": "Surprisingly rainy"
})
@patch('homeassistant.util.dt.now', return_value=_local_datetime(20, 00))
def test_filter_matching_past_event(self, mock_now):
"""Test that the matching past event is not returned."""
cal = caldav.WebDavCalendarEventDevice(self.hass,
DEVICE_DATA,
self.calendar,
False,
"This is a normal event")
self.assertEqual(cal.data.event, None)
@patch('homeassistant.util.dt.now', return_value=_local_datetime(12, 00))
def test_no_result_with_filtering(self, mock_now):
"""Test that nothing is returned since nothing matches."""
cal = caldav.WebDavCalendarEventDevice(self.hass,
DEVICE_DATA,
self.calendar,
False,
"This is a non-existing event")
self.assertEqual(cal.data.event, None)
@patch('homeassistant.util.dt.now', return_value=_local_datetime(17, 30))
def test_all_day_event_returned(self, mock_now):
"""Test that the event lasting the whole day is returned."""
cal = caldav.WebDavCalendarEventDevice(self.hass,
DEVICE_DATA,
self.calendar,
True)
self.assertEqual(cal.name, DEVICE_DATA["name"])
self.assertEqual(cal.state, STATE_ON)
self.assertEqual(cal.device_state_attributes, {
"message": "This is an all day event",
"all_day": True,
"offset_reached": False,
"start_time": "2017-11-27 00:00:00",
"end_time": "2017-11-28 00:00:00",
"location": "Hamburg",
"description": "What a beautiful day"
})
-9
View File
@@ -132,15 +132,6 @@ def test_write_user_info():
}
@asyncio.coroutine
def test_subscription_not_expired_without_sub_in_claim():
"""Test that we do not enforce subscriptions yet."""
cl = cloud.Cloud(None, cloud.MODE_DEV)
cl.id_token = jwt.encode({}, 'test')
assert not cl.subscription_expired
@asyncio.coroutine
def test_subscription_expired():
"""Test subscription being expired."""
@@ -144,7 +144,7 @@ class TestComponentsDeviceTrackerASUSWRT(unittest.TestCase):
update_mock.start()
self.addCleanup(update_mock.stop)
asuswrt = device_tracker.asuswrt.AsusWrtDeviceScanner(conf_dict)
asuswrt.connection.get_result()
asuswrt.connection.run_command('ls')
self.assertEqual(ssh.login.call_count, 1)
self.assertEqual(
ssh.login.call_args,
@@ -170,7 +170,7 @@ class TestComponentsDeviceTrackerASUSWRT(unittest.TestCase):
update_mock.start()
self.addCleanup(update_mock.stop)
asuswrt = device_tracker.asuswrt.AsusWrtDeviceScanner(conf_dict)
asuswrt.connection.get_result()
asuswrt.connection.run_command('ls')
self.assertEqual(ssh.login.call_count, 1)
self.assertEqual(
ssh.login.call_args,
@@ -225,9 +225,9 @@ class TestComponentsDeviceTrackerASUSWRT(unittest.TestCase):
update_mock.start()
self.addCleanup(update_mock.stop)
asuswrt = device_tracker.asuswrt.AsusWrtDeviceScanner(conf_dict)
asuswrt.connection.get_result()
self.assertEqual(telnet.read_until.call_count, 5)
self.assertEqual(telnet.write.call_count, 4)
asuswrt.connection.run_command('ls')
self.assertEqual(telnet.read_until.call_count, 4)
self.assertEqual(telnet.write.call_count, 3)
self.assertEqual(
telnet.read_until.call_args_list[0],
mock.call(b'login: ')
+541
View File
@@ -0,0 +1,541 @@
"""Philips Hue lights platform tests."""
import logging
import unittest
import unittest.mock as mock
from unittest.mock import call, MagicMock, patch
from homeassistant.components import hue
import homeassistant.components.light.hue as hue_light
from tests.common import get_test_home_assistant, MockDependency
_LOGGER = logging.getLogger(__name__)
class TestSetup(unittest.TestCase):
"""Test the Hue light platform."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.skip_teardown_stop = False
def tearDown(self):
"""Stop everything that was started."""
if not self.skip_teardown_stop:
self.hass.stop()
def setup_mocks_for_update_lights(self):
"""Set up all mocks for update_lights tests."""
self.mock_bridge = MagicMock()
self.mock_bridge.allow_hue_groups = False
self.mock_api = MagicMock()
self.mock_bridge.get_api.return_value = self.mock_api
self.mock_bridge_type = MagicMock()
self.mock_lights = []
self.mock_groups = []
self.mock_add_devices = MagicMock()
def setup_mocks_for_process_lights(self):
"""Set up all mocks for process_lights tests."""
self.mock_bridge = self.create_mock_bridge('host')
self.mock_api = MagicMock()
self.mock_api.get.return_value = {}
self.mock_bridge.get_api.return_value = self.mock_api
self.mock_bridge_type = MagicMock()
def setup_mocks_for_process_groups(self):
"""Set up all mocks for process_groups tests."""
self.mock_bridge = self.create_mock_bridge('host')
self.mock_bridge.get_group.return_value = {
'name': 'Group 0', 'state': {'any_on': True}}
self.mock_api = MagicMock()
self.mock_api.get.return_value = {}
self.mock_bridge.get_api.return_value = self.mock_api
self.mock_bridge_type = MagicMock()
def create_mock_bridge(self, host, allow_hue_groups=True):
"""Return a mock HueBridge with reasonable defaults."""
mock_bridge = MagicMock()
mock_bridge.host = host
mock_bridge.allow_hue_groups = allow_hue_groups
mock_bridge.lights = {}
mock_bridge.lightgroups = {}
return mock_bridge
def create_mock_lights(self, lights):
"""Return a dict suitable for mocking api.get('lights')."""
mock_bridge_lights = lights
for light_id, info in mock_bridge_lights.items():
if 'state' not in info:
info['state'] = {'on': False}
return mock_bridge_lights
def test_setup_platform_no_discovery_info(self):
"""Test setup_platform without discovery info."""
self.hass.data[hue.DOMAIN] = {}
mock_add_devices = MagicMock()
hue_light.setup_platform(self.hass, {}, mock_add_devices)
mock_add_devices.assert_not_called()
def test_setup_platform_no_bridge_id(self):
"""Test setup_platform without a bridge."""
self.hass.data[hue.DOMAIN] = {}
mock_add_devices = MagicMock()
hue_light.setup_platform(self.hass, {}, mock_add_devices, {})
mock_add_devices.assert_not_called()
def test_setup_platform_one_bridge(self):
"""Test setup_platform with one bridge."""
mock_bridge = MagicMock()
self.hass.data[hue.DOMAIN] = {'10.0.0.1': mock_bridge}
mock_add_devices = MagicMock()
with patch('homeassistant.components.light.hue.' +
'unthrottled_update_lights') as mock_update_lights:
hue_light.setup_platform(
self.hass, {}, mock_add_devices,
{'bridge_id': '10.0.0.1'})
mock_update_lights.assert_called_once_with(
self.hass, mock_bridge, mock_add_devices)
def test_setup_platform_multiple_bridges(self):
"""Test setup_platform wuth multiple bridges."""
mock_bridge = MagicMock()
mock_bridge2 = MagicMock()
self.hass.data[hue.DOMAIN] = {
'10.0.0.1': mock_bridge,
'192.168.0.10': mock_bridge2,
}
mock_add_devices = MagicMock()
with patch('homeassistant.components.light.hue.' +
'unthrottled_update_lights') as mock_update_lights:
hue_light.setup_platform(
self.hass, {}, mock_add_devices,
{'bridge_id': '10.0.0.1'})
hue_light.setup_platform(
self.hass, {}, mock_add_devices,
{'bridge_id': '192.168.0.10'})
mock_update_lights.assert_has_calls([
call(self.hass, mock_bridge, mock_add_devices),
call(self.hass, mock_bridge2, mock_add_devices),
])
@MockDependency('phue')
def test_update_lights_with_no_lights(self, mock_phue):
"""Test the update_lights function when no lights are found."""
self.setup_mocks_for_update_lights()
with patch('homeassistant.components.light.hue.get_bridge_type',
return_value=self.mock_bridge_type):
with patch('homeassistant.components.light.hue.process_lights',
return_value=[]) as mock_process_lights:
with patch('homeassistant.components.light.hue.process_groups',
return_value=self.mock_groups) \
as mock_process_groups:
hue_light.unthrottled_update_lights(
self.hass, self.mock_bridge, self.mock_add_devices)
mock_process_lights.assert_called_once_with(
self.hass, self.mock_api, self.mock_bridge,
self.mock_bridge_type, mock.ANY)
mock_process_groups.assert_not_called()
self.mock_add_devices.assert_not_called()
@MockDependency('phue')
def test_update_lights_with_some_lights(self, mock_phue):
"""Test the update_lights function with some lights."""
self.setup_mocks_for_update_lights()
self.mock_lights = ['some', 'light']
with patch('homeassistant.components.light.hue.get_bridge_type',
return_value=self.mock_bridge_type):
with patch('homeassistant.components.light.hue.process_lights',
return_value=self.mock_lights) as mock_process_lights:
with patch('homeassistant.components.light.hue.process_groups',
return_value=self.mock_groups) \
as mock_process_groups:
hue_light.unthrottled_update_lights(
self.hass, self.mock_bridge, self.mock_add_devices)
mock_process_lights.assert_called_once_with(
self.hass, self.mock_api, self.mock_bridge,
self.mock_bridge_type, mock.ANY)
mock_process_groups.assert_not_called()
self.mock_add_devices.assert_called_once_with(
self.mock_lights)
@MockDependency('phue')
def test_update_lights_no_groups(self, mock_phue):
"""Test the update_lights function when no groups are found."""
self.setup_mocks_for_update_lights()
self.mock_bridge.allow_hue_groups = True
self.mock_lights = ['some', 'light']
with patch('homeassistant.components.light.hue.get_bridge_type',
return_value=self.mock_bridge_type):
with patch('homeassistant.components.light.hue.process_lights',
return_value=self.mock_lights) as mock_process_lights:
with patch('homeassistant.components.light.hue.process_groups',
return_value=self.mock_groups) \
as mock_process_groups:
hue_light.unthrottled_update_lights(
self.hass, self.mock_bridge, self.mock_add_devices)
mock_process_lights.assert_called_once_with(
self.hass, self.mock_api, self.mock_bridge,
self.mock_bridge_type, mock.ANY)
mock_process_groups.assert_called_once_with(
self.hass, self.mock_api, self.mock_bridge,
self.mock_bridge_type, mock.ANY)
self.mock_add_devices.assert_called_once_with(
self.mock_lights)
@MockDependency('phue')
def test_update_lights_with_lights_and_groups(self, mock_phue):
"""Test the update_lights function with both lights and groups."""
self.setup_mocks_for_update_lights()
self.mock_bridge.allow_hue_groups = True
self.mock_lights = ['some', 'light']
self.mock_groups = ['and', 'groups']
with patch('homeassistant.components.light.hue.get_bridge_type',
return_value=self.mock_bridge_type):
with patch('homeassistant.components.light.hue.process_lights',
return_value=self.mock_lights) as mock_process_lights:
with patch('homeassistant.components.light.hue.process_groups',
return_value=self.mock_groups) \
as mock_process_groups:
hue_light.unthrottled_update_lights(
self.hass, self.mock_bridge, self.mock_add_devices)
mock_process_lights.assert_called_once_with(
self.hass, self.mock_api, self.mock_bridge,
self.mock_bridge_type, mock.ANY)
mock_process_groups.assert_called_once_with(
self.hass, self.mock_api, self.mock_bridge,
self.mock_bridge_type, mock.ANY)
self.mock_add_devices.assert_called_once_with(
self.mock_lights)
@MockDependency('phue')
def test_update_lights_with_two_bridges(self, mock_phue):
"""Test the update_lights function with two bridges."""
self.setup_mocks_for_update_lights()
mock_bridge_one = self.create_mock_bridge('one', False)
mock_bridge_one_lights = self.create_mock_lights(
{1: {'name': 'b1l1'}, 2: {'name': 'b1l2'}})
mock_bridge_two = self.create_mock_bridge('two', False)
mock_bridge_two_lights = self.create_mock_lights(
{1: {'name': 'b2l1'}, 3: {'name': 'b2l3'}})
with patch('homeassistant.components.light.hue.get_bridge_type',
return_value=self.mock_bridge_type):
with patch('homeassistant.components.light.hue.HueLight.'
'schedule_update_ha_state'):
mock_api = MagicMock()
mock_api.get.return_value = mock_bridge_one_lights
with patch.object(mock_bridge_one, 'get_api',
return_value=mock_api):
hue_light.unthrottled_update_lights(
self.hass, mock_bridge_one, self.mock_add_devices)
mock_api = MagicMock()
mock_api.get.return_value = mock_bridge_two_lights
with patch.object(mock_bridge_two, 'get_api',
return_value=mock_api):
hue_light.unthrottled_update_lights(
self.hass, mock_bridge_two, self.mock_add_devices)
self.assertEquals(sorted(mock_bridge_one.lights.keys()), [1, 2])
self.assertEquals(sorted(mock_bridge_two.lights.keys()), [1, 3])
self.assertEquals(len(self.mock_add_devices.mock_calls), 2)
# first call
name, args, kwargs = self.mock_add_devices.mock_calls[0]
self.assertEquals(len(args), 1)
self.assertEquals(len(kwargs), 0)
# one argument, a list of lights in bridge one; each of them is an
# object of type HueLight so we can't straight up compare them
lights = args[0]
self.assertEquals(
lights[0].unique_id,
'{}.b1l1.Light.1'.format(hue_light.HueLight))
self.assertEquals(
lights[1].unique_id,
'{}.b1l2.Light.2'.format(hue_light.HueLight))
# second call works the same
name, args, kwargs = self.mock_add_devices.mock_calls[1]
self.assertEquals(len(args), 1)
self.assertEquals(len(kwargs), 0)
lights = args[0]
self.assertEquals(
lights[0].unique_id,
'{}.b2l1.Light.1'.format(hue_light.HueLight))
self.assertEquals(
lights[1].unique_id,
'{}.b2l3.Light.3'.format(hue_light.HueLight))
def test_process_lights_api_error(self):
"""Test the process_lights function when the bridge errors out."""
self.setup_mocks_for_process_lights()
self.mock_api.get.return_value = None
ret = hue_light.process_lights(
self.hass, self.mock_api, self.mock_bridge, self.mock_bridge_type,
None)
self.assertEquals([], ret)
self.assertEquals(self.mock_bridge.lights, {})
def test_process_lights_no_lights(self):
"""Test the process_lights function when bridge returns no lights."""
self.setup_mocks_for_process_lights()
ret = hue_light.process_lights(
self.hass, self.mock_api, self.mock_bridge, self.mock_bridge_type,
None)
self.assertEquals([], ret)
self.assertEquals(self.mock_bridge.lights, {})
@patch('homeassistant.components.light.hue.HueLight')
def test_process_lights_some_lights(self, mock_hue_light):
"""Test the process_lights function with multiple groups."""
self.setup_mocks_for_process_lights()
self.mock_api.get.return_value = {
1: {'state': 'on'}, 2: {'state': 'off'}}
ret = hue_light.process_lights(
self.hass, self.mock_api, self.mock_bridge, self.mock_bridge_type,
None)
self.assertEquals(len(ret), 2)
mock_hue_light.assert_has_calls([
call(
1, {'state': 'on'}, self.mock_bridge, mock.ANY,
self.mock_bridge_type, self.mock_bridge.allow_unreachable,
self.mock_bridge.allow_in_emulated_hue),
call(
2, {'state': 'off'}, self.mock_bridge, mock.ANY,
self.mock_bridge_type, self.mock_bridge.allow_unreachable,
self.mock_bridge.allow_in_emulated_hue),
])
self.assertEquals(len(self.mock_bridge.lights), 2)
@patch('homeassistant.components.light.hue.HueLight')
def test_process_lights_new_light(self, mock_hue_light):
"""
Test the process_lights function with new groups.
Test what happens when we already have a light and a new one shows up.
"""
self.setup_mocks_for_process_lights()
self.mock_api.get.return_value = {
1: {'state': 'on'}, 2: {'state': 'off'}}
self.mock_bridge.lights = {1: MagicMock()}
ret = hue_light.process_lights(
self.hass, self.mock_api, self.mock_bridge, self.mock_bridge_type,
None)
self.assertEquals(len(ret), 1)
mock_hue_light.assert_has_calls([
call(
2, {'state': 'off'}, self.mock_bridge, mock.ANY,
self.mock_bridge_type, self.mock_bridge.allow_unreachable,
self.mock_bridge.allow_in_emulated_hue),
])
self.assertEquals(len(self.mock_bridge.lights), 2)
self.mock_bridge.lights[1]\
.schedule_update_ha_state.assert_called_once_with()
def test_process_groups_api_error(self):
"""Test the process_groups function when the bridge errors out."""
self.setup_mocks_for_process_groups()
self.mock_api.get.return_value = None
ret = hue_light.process_groups(
self.hass, self.mock_api, self.mock_bridge, self.mock_bridge_type,
None)
self.assertEquals([], ret)
self.assertEquals(self.mock_bridge.lightgroups, {})
def test_process_groups_no_state(self):
"""Test the process_groups function when bridge returns no status."""
self.setup_mocks_for_process_groups()
self.mock_bridge.get_group.return_value = {'name': 'Group 0'}
ret = hue_light.process_groups(
self.hass, self.mock_api, self.mock_bridge, self.mock_bridge_type,
None)
self.assertEquals([], ret)
self.assertEquals(self.mock_bridge.lightgroups, {})
@patch('homeassistant.components.light.hue.HueLight')
def test_process_groups_some_groups(self, mock_hue_light):
"""Test the process_groups function with multiple groups."""
self.setup_mocks_for_process_groups()
self.mock_api.get.return_value = {
1: {'state': 'on'}, 2: {'state': 'off'}}
ret = hue_light.process_groups(
self.hass, self.mock_api, self.mock_bridge, self.mock_bridge_type,
None)
self.assertEquals(len(ret), 2)
mock_hue_light.assert_has_calls([
call(
1, {'state': 'on'}, self.mock_bridge, mock.ANY,
self.mock_bridge_type, self.mock_bridge.allow_unreachable,
self.mock_bridge.allow_in_emulated_hue, True),
call(
2, {'state': 'off'}, self.mock_bridge, mock.ANY,
self.mock_bridge_type, self.mock_bridge.allow_unreachable,
self.mock_bridge.allow_in_emulated_hue, True),
])
self.assertEquals(len(self.mock_bridge.lightgroups), 2)
@patch('homeassistant.components.light.hue.HueLight')
def test_process_groups_new_group(self, mock_hue_light):
"""
Test the process_groups function with new groups.
Test what happens when we already have a light and a new one shows up.
"""
self.setup_mocks_for_process_groups()
self.mock_api.get.return_value = {
1: {'state': 'on'}, 2: {'state': 'off'}}
self.mock_bridge.lightgroups = {1: MagicMock()}
ret = hue_light.process_groups(
self.hass, self.mock_api, self.mock_bridge, self.mock_bridge_type,
None)
self.assertEquals(len(ret), 1)
mock_hue_light.assert_has_calls([
call(
2, {'state': 'off'}, self.mock_bridge, mock.ANY,
self.mock_bridge_type, self.mock_bridge.allow_unreachable,
self.mock_bridge.allow_in_emulated_hue, True),
])
self.assertEquals(len(self.mock_bridge.lightgroups), 2)
self.mock_bridge.lightgroups[1]\
.schedule_update_ha_state.assert_called_once_with()
class TestHueLight(unittest.TestCase):
"""Test the HueLight class."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.skip_teardown_stop = False
self.light_id = 42
self.mock_info = MagicMock()
self.mock_bridge = MagicMock()
self.mock_update_lights = MagicMock()
self.mock_bridge_type = MagicMock()
self.mock_allow_unreachable = MagicMock()
self.mock_is_group = MagicMock()
self.mock_allow_in_emulated_hue = MagicMock()
self.mock_is_group = False
def tearDown(self):
"""Stop everything that was started."""
if not self.skip_teardown_stop:
self.hass.stop()
def buildLight(
self, light_id=None, info=None, update_lights=None, is_group=None):
"""Helper to build a HueLight object with minimal fuss."""
return hue_light.HueLight(
light_id if light_id is not None else self.light_id,
info if info is not None else self.mock_info,
self.mock_bridge,
(update_lights
if update_lights is not None
else self.mock_update_lights),
self.mock_bridge_type,
self.mock_allow_unreachable, self.mock_allow_in_emulated_hue,
is_group if is_group is not None else self.mock_is_group)
def test_unique_id_for_light(self):
"""Test the unique_id method with lights."""
class_name = "<class 'homeassistant.components.light.hue.HueLight'>"
light = self.buildLight(info={'uniqueid': 'foobar'})
self.assertEquals(
class_name+'.foobar',
light.unique_id)
light = self.buildLight(info={})
self.assertEquals(
class_name+'.Unnamed Device.Light.42',
light.unique_id)
light = self.buildLight(info={'name': 'my-name'})
self.assertEquals(
class_name+'.my-name.Light.42',
light.unique_id)
light = self.buildLight(info={'type': 'my-type'})
self.assertEquals(
class_name+'.Unnamed Device.my-type.42',
light.unique_id)
light = self.buildLight(info={'name': 'a name', 'type': 'my-type'})
self.assertEquals(
class_name+'.a name.my-type.42',
light.unique_id)
def test_unique_id_for_group(self):
"""Test the unique_id method with groups."""
class_name = "<class 'homeassistant.components.light.hue.HueLight'>"
light = self.buildLight(info={'uniqueid': 'foobar'}, is_group=True)
self.assertEquals(
class_name+'.foobar',
light.unique_id)
light = self.buildLight(info={}, is_group=True)
self.assertEquals(
class_name+'.Unnamed Device.Group.42',
light.unique_id)
light = self.buildLight(info={'name': 'my-name'}, is_group=True)
self.assertEquals(
class_name+'.my-name.Group.42',
light.unique_id)
light = self.buildLight(info={'type': 'my-type'}, is_group=True)
self.assertEquals(
class_name+'.Unnamed Device.my-type.42',
light.unique_id)
light = self.buildLight(
info={'name': 'a name', 'type': 'my-type'},
is_group=True)
self.assertEquals(
class_name+'.a name.my-type.42',
light.unique_id)
+67 -1
View File
@@ -60,7 +60,8 @@ class TestMochadLight(unittest.TestCase):
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
controller_mock = mock.MagicMock()
dev_dict = {'address': 'a1', 'name': 'fake_light'}
dev_dict = {'address': 'a1', 'name': 'fake_light',
'brightness_levels': 32}
self.light = mochad.MochadLight(self.hass, controller_mock,
dev_dict)
@@ -72,6 +73,39 @@ class TestMochadLight(unittest.TestCase):
"""Test the name."""
self.assertEqual('fake_light', self.light.name)
def test_turn_on_with_no_brightness(self):
"""Test turn_on."""
self.light.turn_on()
self.light.device.send_cmd.assert_called_once_with('on')
def test_turn_on_with_brightness(self):
"""Test turn_on."""
self.light.turn_on(brightness=45)
self.light.device.send_cmd.assert_has_calls(
[mock.call('on'), mock.call('dim 25')])
def test_turn_off(self):
"""Test turn_off."""
self.light.turn_off()
self.light.device.send_cmd.assert_called_once_with('off')
class TestMochadLight256Levels(unittest.TestCase):
"""Test for mochad light platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
controller_mock = mock.MagicMock()
dev_dict = {'address': 'a1', 'name': 'fake_light',
'brightness_levels': 256}
self.light = mochad.MochadLight(self.hass, controller_mock,
dev_dict)
def teardown_method(self, method):
"""Stop everything that was started."""
self.hass.stop()
def test_turn_on_with_no_brightness(self):
"""Test turn_on."""
self.light.turn_on()
@@ -86,3 +120,35 @@ class TestMochadLight(unittest.TestCase):
"""Test turn_off."""
self.light.turn_off()
self.light.device.send_cmd.assert_called_once_with('off')
class TestMochadLight64Levels(unittest.TestCase):
"""Test for mochad light platform."""
def setUp(self):
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
controller_mock = mock.MagicMock()
dev_dict = {'address': 'a1', 'name': 'fake_light',
'brightness_levels': 64}
self.light = mochad.MochadLight(self.hass, controller_mock,
dev_dict)
def teardown_method(self, method):
"""Stop everything that was started."""
self.hass.stop()
def test_turn_on_with_no_brightness(self):
"""Test turn_on."""
self.light.turn_on()
self.light.device.send_cmd.assert_called_once_with('xdim 63')
def test_turn_on_with_brightness(self):
"""Test turn_on."""
self.light.turn_on(brightness=45)
self.light.device.send_cmd.assert_called_once_with('xdim 11')
def test_turn_off(self):
"""Test turn_off."""
self.light.turn_off()
self.light.device.send_cmd.assert_called_once_with('off')
+162 -17
View File
@@ -1,27 +1,30 @@
"""The tests for Monoprice Media player platform."""
import unittest
from unittest import mock
import voluptuous as vol
from collections import defaultdict
from homeassistant.components.media_player import (
SUPPORT_TURN_ON, SUPPORT_TURN_OFF, SUPPORT_VOLUME_MUTE,
DOMAIN, SUPPORT_TURN_ON, SUPPORT_TURN_OFF, SUPPORT_VOLUME_MUTE,
SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, SUPPORT_SELECT_SOURCE)
from homeassistant.const import STATE_ON, STATE_OFF
import tests.common
from homeassistant.components.media_player.monoprice import (
MonopriceZone, PLATFORM_SCHEMA)
DATA_MONOPRICE, PLATFORM_SCHEMA, SERVICE_SNAPSHOT,
SERVICE_RESTORE, setup_platform)
class MockState(object):
"""Mock for zone state object."""
class AttrDict(dict):
"""Helper class for mocking attributes."""
def __init__(self):
"""Init zone state."""
self.power = True
self.volume = 0
self.mute = True
self.source = 1
def __setattr__(self, name, value):
"""Set attribute."""
self[name] = value
def __getattr__(self, item):
"""Get attribute."""
return self[item]
class MockMonoprice(object):
@@ -29,11 +32,16 @@ class MockMonoprice(object):
def __init__(self):
"""Init mock object."""
self.zones = defaultdict(lambda *a: MockState())
self.zones = defaultdict(lambda: AttrDict(power=True,
volume=0,
mute=True,
source=1))
def zone_status(self, zone_id):
"""Get zone status."""
return self.zones[zone_id]
status = self.zones[zone_id]
status.zone = zone_id
return AttrDict(status)
def set_source(self, zone_id, source_idx):
"""Set source for zone."""
@@ -51,6 +59,10 @@ class MockMonoprice(object):
"""Set volume for zone."""
self.zones[zone_id].volume = volume
def restore_zone(self, zone):
"""Restore zone status."""
self.zones[zone.zone] = AttrDict(zone)
class TestMonopriceSchema(unittest.TestCase):
"""Test Monoprice schema."""
@@ -147,11 +159,144 @@ class TestMonopriceMediaPlayer(unittest.TestCase):
def setUp(self):
"""Set up the test case."""
self.monoprice = MockMonoprice()
self.hass = tests.common.get_test_home_assistant()
self.hass.start()
# Note, source dictionary is unsorted!
self.media_player = MonopriceZone(self.monoprice, {1: 'one',
3: 'three',
2: 'two'},
12, 'Zone name')
with mock.patch('pymonoprice.get_monoprice',
new=lambda *a: self.monoprice):
setup_platform(self.hass, {
'platform': 'monoprice',
'port': '/dev/ttyS0',
'name': 'Name',
'zones': {12: {'name': 'Zone name'}},
'sources': {1: {'name': 'one'},
3: {'name': 'three'},
2: {'name': 'two'}},
}, lambda *args, **kwargs: None, {})
self.hass.block_till_done()
self.media_player = self.hass.data[DATA_MONOPRICE][0]
self.media_player.hass = self.hass
self.media_player.entity_id = 'media_player.zone_1'
def tearDown(self):
"""Tear down the test case."""
self.hass.stop()
def test_setup_platform(self, *args):
"""Test setting up platform."""
# Two services must be registered
self.assertTrue(self.hass.services.has_service(DOMAIN,
SERVICE_RESTORE))
self.assertTrue(self.hass.services.has_service(DOMAIN,
SERVICE_SNAPSHOT))
self.assertEqual(len(self.hass.data[DATA_MONOPRICE]), 1)
self.assertEqual(self.hass.data[DATA_MONOPRICE][0].name, 'Zone name')
def test_service_calls_with_entity_id(self):
"""Test snapshot save/restore service calls."""
self.media_player.update()
self.assertEqual('Zone name', self.media_player.name)
self.assertEqual(STATE_ON, self.media_player.state)
self.assertEqual(0.0, self.media_player.volume_level, 0.0001)
self.assertTrue(self.media_player.is_volume_muted)
self.assertEqual('one', self.media_player.source)
# Saving default values
self.hass.services.call(DOMAIN, SERVICE_SNAPSHOT,
{'entity_id': 'media_player.zone_1'},
blocking=True)
# self.hass.block_till_done()
# Changing media player to new state
self.media_player.set_volume_level(1)
self.media_player.select_source('two')
self.media_player.mute_volume(False)
self.media_player.turn_off()
# Checking that values were indeed changed
self.media_player.update()
self.assertEqual('Zone name', self.media_player.name)
self.assertEqual(STATE_OFF, self.media_player.state)
self.assertEqual(1.0, self.media_player.volume_level, 0.0001)
self.assertFalse(self.media_player.is_volume_muted)
self.assertEqual('two', self.media_player.source)
# Restoring wrong media player to its previous state
# Nothing should be done
self.hass.services.call(DOMAIN, SERVICE_RESTORE,
{'entity_id': 'not_existing'},
blocking=True)
# self.hass.block_till_done()
# Checking that values were not (!) restored
self.media_player.update()
self.assertEqual('Zone name', self.media_player.name)
self.assertEqual(STATE_OFF, self.media_player.state)
self.assertEqual(1.0, self.media_player.volume_level, 0.0001)
self.assertFalse(self.media_player.is_volume_muted)
self.assertEqual('two', self.media_player.source)
# Restoring media player to its previous state
self.hass.services.call(DOMAIN, SERVICE_RESTORE,
{'entity_id': 'media_player.zone_1'},
blocking=True)
self.hass.block_till_done()
# Checking that values were restored
self.assertEqual('Zone name', self.media_player.name)
self.assertEqual(STATE_ON, self.media_player.state)
self.assertEqual(0.0, self.media_player.volume_level, 0.0001)
self.assertTrue(self.media_player.is_volume_muted)
self.assertEqual('one', self.media_player.source)
def test_service_calls_without_entity_id(self):
"""Test snapshot save/restore service calls."""
self.media_player.update()
self.assertEqual('Zone name', self.media_player.name)
self.assertEqual(STATE_ON, self.media_player.state)
self.assertEqual(0.0, self.media_player.volume_level, 0.0001)
self.assertTrue(self.media_player.is_volume_muted)
self.assertEqual('one', self.media_player.source)
# Restoring media player
# since there is no snapshot, nothing should be done
self.hass.services.call(DOMAIN, SERVICE_RESTORE, blocking=True)
self.hass.block_till_done()
self.media_player.update()
self.assertEqual('Zone name', self.media_player.name)
self.assertEqual(STATE_ON, self.media_player.state)
self.assertEqual(0.0, self.media_player.volume_level, 0.0001)
self.assertTrue(self.media_player.is_volume_muted)
self.assertEqual('one', self.media_player.source)
# Saving default values
self.hass.services.call(DOMAIN, SERVICE_SNAPSHOT, blocking=True)
self.hass.block_till_done()
# Changing media player to new state
self.media_player.set_volume_level(1)
self.media_player.select_source('two')
self.media_player.mute_volume(False)
self.media_player.turn_off()
# Checking that values were indeed changed
self.media_player.update()
self.assertEqual('Zone name', self.media_player.name)
self.assertEqual(STATE_OFF, self.media_player.state)
self.assertEqual(1.0, self.media_player.volume_level, 0.0001)
self.assertFalse(self.media_player.is_volume_muted)
self.assertEqual('two', self.media_player.source)
# Restoring media player to its previous state
self.hass.services.call(DOMAIN, SERVICE_RESTORE, blocking=True)
self.hass.block_till_done()
# Checking that values were restored
self.assertEqual('Zone name', self.media_player.name)
self.assertEqual(STATE_ON, self.media_player.state)
self.assertEqual(0.0, self.media_player.volume_level, 0.0001)
self.assertTrue(self.media_player.is_volume_muted)
self.assertEqual('one', self.media_player.source)
def test_update(self):
"""Test updating values from monoprice."""
@@ -281,6 +281,20 @@ class TestSonosMediaPlayer(unittest.TestCase):
self.assertEqual(unjoinMock.call_count, 1)
self.assertEqual(unjoinMock.call_args, mock.call())
@mock.patch('soco.SoCo', new=SoCoMock)
@mock.patch('socket.create_connection', side_effect=socket.error())
def test_set_shuffle(self, shuffle_set_mock, *args):
"""Ensuring soco methods called for sonos_snapshot service."""
sonos.setup_platform(self.hass, {}, fake_add_device, {
'host': '192.0.2.1'
})
device = self.hass.data[sonos.DATA_SONOS][-1]
device.hass = self.hass
device.set_shuffle(True)
self.assertEqual(shuffle_set_mock.call_count, 1)
self.assertEqual(device._player.play_mode, 'SHUFFLE')
@mock.patch('soco.SoCo', new=SoCoMock)
@mock.patch('socket.create_connection', side_effect=socket.error())
@mock.patch.object(SoCoMock, 'set_sleep_timer')
@@ -375,3 +389,21 @@ class TestSonosMediaPlayer(unittest.TestCase):
device.restore()
self.assertEqual(restoreMock.call_count, 1)
self.assertEqual(restoreMock.call_args, mock.call(False))
@mock.patch('soco.SoCo', new=SoCoMock)
@mock.patch('socket.create_connection', side_effect=socket.error())
def test_sonos_set_option(self, option_mock, *args):
"""Ensuring soco methods called for sonos_set_option service."""
sonos.setup_platform(self.hass, {}, fake_add_device, {
'host': '192.0.2.1'
})
device = self.hass.data[sonos.DATA_SONOS][-1]
device.hass = self.hass
option_mock.return_value = True
device._snapshot_coordinator = mock.MagicMock()
device._snapshot_coordinator.soco_device = SoCoMock('192.0.2.17')
device.update_option(night_sound=True, speech_enhance=True)
self.assertEqual(option_mock.call_count, 1)
@@ -0,0 +1,60 @@
"""The tests for the LG webOS media player platform."""
import unittest
from unittest import mock
from homeassistant.components.media_player import webostv
class FakeLgWebOSDevice(webostv.LgWebOSDevice):
"""A fake device without the client setup required for the real one."""
def __init__(self, *args, **kwargs):
"""Initialise parameters needed for tests with fake values."""
self._source_list = {}
self._client = mock.MagicMock()
self._name = 'fake_device'
self._current_source = None
class TestLgWebOSDevice(unittest.TestCase):
"""Test the LgWebOSDevice class."""
def setUp(self):
"""Configure a fake device for each test."""
self.device = FakeLgWebOSDevice()
def test_select_source_with_empty_source_list(self):
"""Ensure we don't call client methods when we don't have sources."""
self.device.select_source('nonexistent')
assert 0 == self.device._client.launch_app.call_count
assert 0 == self.device._client.set_input.call_count
def test_select_source_with_titled_entry(self):
"""Test that a titled source is treated as an app."""
self.device._source_list = {
'existent': {
'id': 'existent_id',
'title': 'existent_title',
},
}
self.device.select_source('existent')
assert 'existent_title' == self.device._current_source
assert [mock.call('existent_id')] == (
self.device._client.launch_app.call_args_list)
def test_select_source_with_labelled_entry(self):
"""Test that a labelled source is treated as an input source."""
self.device._source_list = {
'existent': {
'id': 'existent_id',
'label': 'existent_label',
},
}
self.device.select_source('existent')
assert 'existent_label' == self.device._current_source
assert [mock.call('existent_id')] == (
self.device._client.set_input.call_args_list)
+125
View File
@@ -0,0 +1,125 @@
"""The tests for the Canary sensor platform."""
import copy
import unittest
from unittest.mock import patch, Mock
from canary.api import SensorType
from homeassistant.components import canary as base_canary
from homeassistant.components.canary import DATA_CANARY
from homeassistant.components.sensor import canary
from homeassistant.components.sensor.canary import CanarySensor
from tests.common import (get_test_home_assistant)
from tests.components.test_canary import mock_device, mock_reading, \
mock_location
VALID_CONFIG = {
"canary": {
"username": "foo@bar.org",
"password": "bar",
}
}
class TestCanarySensorSetup(unittest.TestCase):
"""Test the Canary platform."""
DEVICES = []
def add_devices(self, devices, action):
"""Mock add devices."""
for device in devices:
self.DEVICES.append(device)
def setUp(self):
"""Initialize values for this testcase class."""
self.hass = get_test_home_assistant()
self.config = copy.deepcopy(VALID_CONFIG)
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
@patch('homeassistant.components.canary.CanaryData')
def test_setup_sensors(self, mock_canary):
"""Test the sensor setup."""
base_canary.setup(self.hass, self.config)
online_device_at_home = mock_device(20, "Dining Room", True)
offline_device_at_home = mock_device(21, "Front Yard", False)
online_device_at_work = mock_device(22, "Office", True)
self.hass.data[DATA_CANARY] = mock_canary()
self.hass.data[DATA_CANARY].locations = [
mock_location("Home", True, devices=[online_device_at_home,
offline_device_at_home]),
mock_location("Work", True, devices=[online_device_at_work]),
]
canary.setup_platform(self.hass, self.config, self.add_devices, None)
self.assertEqual(6, len(self.DEVICES))
def test_celsius_temperature_sensor(self):
"""Test temperature sensor with celsius."""
device = mock_device(10, "Family Room")
location = mock_location("Home", True)
data = Mock()
data.get_readings.return_value = [
mock_reading(SensorType.TEMPERATURE, 21.1234)]
sensor = CanarySensor(data, SensorType.TEMPERATURE, location, device)
sensor.update()
self.assertEqual("Home Family Room Temperature", sensor.name)
self.assertEqual("sensor_canary_10_temperature", sensor.unique_id)
self.assertEqual("°C", sensor.unit_of_measurement)
self.assertEqual(21.1, sensor.state)
def test_fahrenheit_temperature_sensor(self):
"""Test temperature sensor with fahrenheit."""
device = mock_device(10, "Family Room")
location = mock_location("Home", False)
data = Mock()
data.get_readings.return_value = [
mock_reading(SensorType.TEMPERATURE, 21.1567)]
sensor = CanarySensor(data, SensorType.TEMPERATURE, location, device)
sensor.update()
self.assertEqual("Home Family Room Temperature", sensor.name)
self.assertEqual("°F", sensor.unit_of_measurement)
self.assertEqual(21.2, sensor.state)
def test_humidity_sensor(self):
"""Test humidity sensor."""
device = mock_device(10, "Family Room")
location = mock_location("Home")
data = Mock()
data.get_readings.return_value = [
mock_reading(SensorType.HUMIDITY, 50.4567)]
sensor = CanarySensor(data, SensorType.HUMIDITY, location, device)
sensor.update()
self.assertEqual("Home Family Room Humidity", sensor.name)
self.assertEqual("%", sensor.unit_of_measurement)
self.assertEqual(50.5, sensor.state)
def test_air_quality_sensor(self):
"""Test air quality sensor."""
device = mock_device(10, "Family Room")
location = mock_location("Home")
data = Mock()
data.get_readings.return_value = [
mock_reading(SensorType.AIR_QUALITY, 50.4567)]
sensor = CanarySensor(data, SensorType.AIR_QUALITY, location, device)
sensor.update()
self.assertEqual("Home Family Room Air Quality", sensor.name)
self.assertEqual("", sensor.unit_of_measurement)
self.assertEqual(50.5, sensor.state)
@@ -0,0 +1,89 @@
"""The test for the hydroquebec sensor platform."""
import asyncio
import logging
import sys
from unittest.mock import MagicMock
from homeassistant.bootstrap import async_setup_component
from homeassistant.components.sensor import hydroquebec
from tests.common import assert_setup_component
CONTRACT = "123456789"
class HydroQuebecClientMock():
"""Fake Hydroquebec client."""
def __init__(self, username, password, contract=None):
"""Fake Hydroquebec client init."""
pass
def get_data(self, contract):
"""Return fake hydroquebec data."""
return {CONTRACT: {"balance": 160.12}}
def get_contracts(self):
"""Return fake hydroquebec contracts."""
return [CONTRACT]
@asyncio.coroutine
def fetch_data(self):
"""Return fake fetching data."""
pass
class HydroQuebecClientMockError(HydroQuebecClientMock):
"""Fake Hydroquebec client error."""
@asyncio.coroutine
def fetch_data(self):
"""Return fake fetching data."""
raise hydroquebec.PyHydroQuebecError("Fake Error")
class PyHydroQuebecErrorMock(BaseException):
"""Fake PyHydroquebec Error."""
@asyncio.coroutine
def test_hydroquebec_sensor(loop, hass):
"""Test the Hydroquebec number sensor."""
sys.modules['pyhydroquebec'] = MagicMock()
sys.modules['pyhydroquebec.client'] = MagicMock()
sys.modules['pyhydroquebec.client.PyHydroQuebecError'] = \
PyHydroQuebecErrorMock
import pyhydroquebec.client
pyhydroquebec.HydroQuebecClient = HydroQuebecClientMock
pyhydroquebec.client.PyHydroQuebecError = PyHydroQuebecErrorMock
config = {
'sensor': {
'platform': 'hydroquebec',
'name': 'hydro',
'contract': CONTRACT,
'username': 'myusername',
'password': 'password',
'monitored_variables': [
'balance',
],
}
}
with assert_setup_component(1):
yield from async_setup_component(hass, 'sensor', config)
state = hass.states.get('sensor.hydro_balance')
assert state.state == "160.12"
assert state.attributes.get('unit_of_measurement') == "CAD"
@asyncio.coroutine
def test_error(hass, caplog):
"""Test the Hydroquebec sensor errors."""
caplog.set_level(logging.ERROR)
sys.modules['pyhydroquebec'] = MagicMock()
sys.modules['pyhydroquebec.client'] = MagicMock()
import pyhydroquebec.client
pyhydroquebec.HydroQuebecClient = HydroQuebecClientMockError
pyhydroquebec.client.PyHydroQuebecError = BaseException
hydro_data = hydroquebec.HydroquebecData('username', 'password')
yield from hydro_data._fetch_data()
assert "Error on receive last Hydroquebec data: " in caplog.text
+22 -9
View File
@@ -132,10 +132,12 @@ class TestRestSensor(unittest.TestCase):
self.unit_of_measurement = 'MB'
self.value_template = template('{{ value_json.key }}')
self.value_template.hass = self.hass
self.force_update = False
self.sensor = rest.RestSensor(self.hass, self.rest, self.name,
self.unit_of_measurement,
self.value_template, [])
self.sensor = rest.RestSensor(
self.hass, self.rest, self.name, self.unit_of_measurement,
self.value_template, [], self.force_update
)
def tearDown(self):
"""Stop everything that was started."""
@@ -154,6 +156,11 @@ class TestRestSensor(unittest.TestCase):
self.assertEqual(
self.unit_of_measurement, self.sensor.unit_of_measurement)
def test_force_update(self):
"""Test the unit of measurement."""
self.assertEqual(
self.force_update, self.sensor.force_update)
def test_state(self):
"""Test the initial state."""
self.sensor.update()
@@ -182,7 +189,8 @@ class TestRestSensor(unittest.TestCase):
side_effect=self.update_side_effect(
'plain_state'))
self.sensor = rest.RestSensor(self.hass, self.rest, self.name,
self.unit_of_measurement, None, [])
self.unit_of_measurement, None, [],
self.force_update)
self.sensor.update()
self.assertEqual('plain_state', self.sensor.state)
self.assertTrue(self.sensor.available)
@@ -193,7 +201,8 @@ class TestRestSensor(unittest.TestCase):
side_effect=self.update_side_effect(
'{ "key": "some_json_value" }'))
self.sensor = rest.RestSensor(self.hass, self.rest, self.name,
self.unit_of_measurement, None, ['key'])
self.unit_of_measurement, None, ['key'],
self.force_update)
self.sensor.update()
self.assertEqual('some_json_value',
self.sensor.device_state_attributes['key'])
@@ -205,7 +214,8 @@ class TestRestSensor(unittest.TestCase):
side_effect=self.update_side_effect(
'["list", "of", "things"]'))
self.sensor = rest.RestSensor(self.hass, self.rest, self.name,
self.unit_of_measurement, None, ['key'])
self.unit_of_measurement, None, ['key'],
self.force_update)
self.sensor.update()
self.assertEqual({}, self.sensor.device_state_attributes)
self.assertTrue(mock_logger.warning.called)
@@ -217,7 +227,8 @@ class TestRestSensor(unittest.TestCase):
side_effect=self.update_side_effect(
'This is text rather than JSON data.'))
self.sensor = rest.RestSensor(self.hass, self.rest, self.name,
self.unit_of_measurement, None, ['key'])
self.unit_of_measurement, None, ['key'],
self.force_update)
self.sensor.update()
self.assertEqual({}, self.sensor.device_state_attributes)
self.assertTrue(mock_logger.warning.called)
@@ -230,12 +241,14 @@ class TestRestSensor(unittest.TestCase):
'{ "key": "json_state_updated_value" }'))
self.sensor = rest.RestSensor(self.hass, self.rest, self.name,
self.unit_of_measurement,
self.value_template, ['key'])
self.value_template, ['key'],
self.force_update)
self.sensor.update()
self.assertEqual('json_state_updated_value', self.sensor.state)
self.assertEqual('json_state_updated_value',
self.sensor.device_state_attributes['key'])
self.sensor.device_state_attributes['key'],
self.force_update)
class TestRestData(unittest.TestCase):
+34 -1
View File
@@ -3,7 +3,8 @@ import unittest
import statistics
from homeassistant.setup import setup_component
from homeassistant.const import (ATTR_UNIT_OF_MEASUREMENT, TEMP_CELSIUS)
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT, TEMP_CELSIUS, STATE_UNKNOWN)
from homeassistant.util import dt as dt_util
from tests.common import get_test_home_assistant
from unittest.mock import patch
@@ -106,6 +107,38 @@ class TestStatisticsSensor(unittest.TestCase):
self.assertEqual(3.8, state.attributes.get('min_value'))
self.assertEqual(14, state.attributes.get('max_value'))
def test_sampling_size_1(self):
"""Test validity of stats requiring only one sample."""
assert setup_component(self.hass, 'sensor', {
'sensor': {
'platform': 'statistics',
'name': 'test',
'entity_id': 'sensor.test_monitored',
'sampling_size': 1,
}
})
for value in self.values[-3:]: # just the last 3 will do
self.hass.states.set('sensor.test_monitored', value,
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS})
self.hass.block_till_done()
state = self.hass.states.get('sensor.test_mean')
# require only one data point
self.assertEqual(self.values[-1], state.attributes.get('min_value'))
self.assertEqual(self.values[-1], state.attributes.get('max_value'))
self.assertEqual(self.values[-1], state.attributes.get('mean'))
self.assertEqual(self.values[-1], state.attributes.get('median'))
self.assertEqual(self.values[-1], state.attributes.get('total'))
self.assertEqual(0, state.attributes.get('change'))
self.assertEqual(0, state.attributes.get('average_change'))
# require at least two data points
self.assertEqual(STATE_UNKNOWN, state.attributes.get('variance'))
self.assertEqual(STATE_UNKNOWN,
state.attributes.get('standard_deviation'))
def test_max_age(self):
"""Test value deprecation."""
mock_data = {
+85
View File
@@ -0,0 +1,85 @@
"""The tests for the Canary component."""
import unittest
from unittest.mock import patch, MagicMock, PropertyMock
import homeassistant.components.canary as canary
from homeassistant import setup
from tests.common import (
get_test_home_assistant)
def mock_device(device_id, name, is_online=True):
"""Mock Canary Device class."""
device = MagicMock()
type(device).device_id = PropertyMock(return_value=device_id)
type(device).name = PropertyMock(return_value=name)
type(device).is_online = PropertyMock(return_value=is_online)
return device
def mock_location(name, is_celsius=True, devices=[]):
"""Mock Canary Location class."""
location = MagicMock()
type(location).name = PropertyMock(return_value=name)
type(location).is_celsius = PropertyMock(return_value=is_celsius)
type(location).devices = PropertyMock(return_value=devices)
return location
def mock_reading(sensor_type, sensor_value):
"""Mock Canary Reading class."""
reading = MagicMock()
type(reading).sensor_type = PropertyMock(return_value=sensor_type)
type(reading).value = PropertyMock(return_value=sensor_value)
return reading
class TestCanary(unittest.TestCase):
"""Tests the Canary component."""
def setUp(self):
"""Initialize values for this test case class."""
self.hass = get_test_home_assistant()
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
@patch('homeassistant.components.canary.CanaryData.update')
@patch('canary.api.Api.login')
def test_setup_with_valid_config(self, mock_login, mock_update):
"""Test setup component."""
config = {
"canary": {
"username": "foo@bar.org",
"password": "bar",
}
}
self.assertTrue(
setup.setup_component(self.hass, canary.DOMAIN, config))
mock_update.assert_called_once_with()
mock_login.assert_called_once_with()
def test_setup_with_missing_password(self):
"""Test setup component."""
config = {
"canary": {
"username": "foo@bar.org",
}
}
self.assertFalse(
setup.setup_component(self.hass, canary.DOMAIN, config))
def test_setup_with_missing_username(self):
"""Test setup component."""
config = {
"canary": {
"password": "bar",
}
}
self.assertFalse(
setup.setup_component(self.hass, canary.DOMAIN, config))
+402
View File
@@ -0,0 +1,402 @@
"""Generic Philips Hue component tests."""
import logging
import unittest
from unittest.mock import call, MagicMock, patch
from homeassistant.components import configurator, hue
from homeassistant.const import CONF_FILENAME, CONF_HOST
from homeassistant.setup import setup_component
from tests.common import (
assert_setup_component, get_test_home_assistant, get_test_config_dir,
MockDependency
)
_LOGGER = logging.getLogger(__name__)
class TestSetup(unittest.TestCase):
"""Test the Hue component."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.skip_teardown_stop = False
def tearDown(self):
"""Stop everything that was started."""
if not self.skip_teardown_stop:
self.hass.stop()
@MockDependency('phue')
def test_setup_no_domain(self, mock_phue):
"""If it's not in the config we won't even try."""
with assert_setup_component(0):
self.assertTrue(setup_component(
self.hass, hue.DOMAIN, {}))
mock_phue.Bridge.assert_not_called()
self.assertEquals({}, self.hass.data[hue.DOMAIN])
@MockDependency('phue')
def test_setup_no_host(self, mock_phue):
"""No host specified in any way."""
with assert_setup_component(1):
self.assertTrue(setup_component(
self.hass, hue.DOMAIN, {hue.DOMAIN: {}}))
mock_phue.Bridge.assert_not_called()
self.assertEquals({}, self.hass.data[hue.DOMAIN])
@MockDependency('phue')
def test_setup_with_host(self, mock_phue):
"""Host specified in the config file."""
mock_bridge = mock_phue.Bridge
with assert_setup_component(1):
with patch('homeassistant.helpers.discovery.load_platform') \
as mock_load:
self.assertTrue(setup_component(
self.hass, hue.DOMAIN,
{hue.DOMAIN: {hue.CONF_BRIDGES: [
{CONF_HOST: 'localhost'}]}}))
mock_bridge.assert_called_once_with(
'localhost',
config_file_path=get_test_config_dir(hue.PHUE_CONFIG_FILE))
mock_load.assert_called_once_with(
self.hass, 'light', hue.DOMAIN,
{'bridge_id': '127.0.0.1'})
self.assertTrue(hue.DOMAIN in self.hass.data)
self.assertEquals(1, len(self.hass.data[hue.DOMAIN]))
@MockDependency('phue')
def test_setup_with_phue_conf(self, mock_phue):
"""No host in the config file, but one is cached in phue.conf."""
mock_bridge = mock_phue.Bridge
with assert_setup_component(1):
with patch(
'homeassistant.components.hue._find_host_from_config',
return_value='localhost'):
with patch('homeassistant.helpers.discovery.load_platform') \
as mock_load:
self.assertTrue(setup_component(
self.hass, hue.DOMAIN,
{hue.DOMAIN: {hue.CONF_BRIDGES: [
{CONF_FILENAME: 'phue.conf'}]}}))
mock_bridge.assert_called_once_with(
'localhost',
config_file_path=get_test_config_dir(
hue.PHUE_CONFIG_FILE))
mock_load.assert_called_once_with(
self.hass, 'light', hue.DOMAIN,
{'bridge_id': '127.0.0.1'})
self.assertTrue(hue.DOMAIN in self.hass.data)
self.assertEquals(1, len(self.hass.data[hue.DOMAIN]))
@MockDependency('phue')
def test_setup_with_multiple_hosts(self, mock_phue):
"""Multiple hosts specified in the config file."""
mock_bridge = mock_phue.Bridge
with assert_setup_component(1):
with patch('homeassistant.helpers.discovery.load_platform') \
as mock_load:
self.assertTrue(setup_component(
self.hass, hue.DOMAIN,
{hue.DOMAIN: {hue.CONF_BRIDGES: [
{CONF_HOST: 'localhost'},
{CONF_HOST: '192.168.0.1'}]}}))
mock_bridge.assert_has_calls([
call(
'localhost',
config_file_path=get_test_config_dir(
hue.PHUE_CONFIG_FILE)),
call(
'192.168.0.1',
config_file_path=get_test_config_dir(
hue.PHUE_CONFIG_FILE))])
mock_load.mock_bridge.assert_not_called()
mock_load.assert_has_calls([
call(
self.hass, 'light', hue.DOMAIN,
{'bridge_id': '127.0.0.1'}),
call(
self.hass, 'light', hue.DOMAIN,
{'bridge_id': '192.168.0.1'}),
], any_order=True)
self.assertTrue(hue.DOMAIN in self.hass.data)
self.assertEquals(2, len(self.hass.data[hue.DOMAIN]))
@MockDependency('phue')
def test_bridge_discovered(self, mock_phue):
"""Bridge discovery."""
mock_bridge = mock_phue.Bridge
mock_service = MagicMock()
discovery_info = {'host': '192.168.0.10', 'serial': 'foobar'}
with patch('homeassistant.helpers.discovery.load_platform') \
as mock_load:
self.assertTrue(setup_component(
self.hass, hue.DOMAIN, {}))
hue.bridge_discovered(self.hass, mock_service, discovery_info)
mock_bridge.assert_called_once_with(
'192.168.0.10',
config_file_path=get_test_config_dir('phue-foobar.conf'))
mock_load.assert_called_once_with(
self.hass, 'light', hue.DOMAIN,
{'bridge_id': '192.168.0.10'})
self.assertTrue(hue.DOMAIN in self.hass.data)
self.assertEquals(1, len(self.hass.data[hue.DOMAIN]))
@MockDependency('phue')
def test_bridge_configure_and_discovered(self, mock_phue):
"""Bridge is in the config file, then we discover it."""
mock_bridge = mock_phue.Bridge
mock_service = MagicMock()
discovery_info = {'host': '192.168.1.10', 'serial': 'foobar'}
with assert_setup_component(1):
with patch('homeassistant.helpers.discovery.load_platform') \
as mock_load:
# First we set up the component from config
self.assertTrue(setup_component(
self.hass, hue.DOMAIN,
{hue.DOMAIN: {hue.CONF_BRIDGES: [
{CONF_HOST: '192.168.1.10'}]}}))
mock_bridge.assert_called_once_with(
'192.168.1.10',
config_file_path=get_test_config_dir(
hue.PHUE_CONFIG_FILE))
calls_to_mock_load = [
call(
self.hass, 'light', hue.DOMAIN,
{'bridge_id': '192.168.1.10'}),
]
mock_load.assert_has_calls(calls_to_mock_load)
self.assertTrue(hue.DOMAIN in self.hass.data)
self.assertEquals(1, len(self.hass.data[hue.DOMAIN]))
# Then we discover the same bridge
hue.bridge_discovered(self.hass, mock_service, discovery_info)
# No additional calls
mock_bridge.assert_called_once_with(
'192.168.1.10',
config_file_path=get_test_config_dir(
hue.PHUE_CONFIG_FILE))
mock_load.assert_has_calls(calls_to_mock_load)
# Still only one
self.assertTrue(hue.DOMAIN in self.hass.data)
self.assertEquals(1, len(self.hass.data[hue.DOMAIN]))
class TestHueBridge(unittest.TestCase):
"""Test the HueBridge class."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.data[hue.DOMAIN] = {}
self.skip_teardown_stop = False
def tearDown(self):
"""Stop everything that was started."""
if not self.skip_teardown_stop:
self.hass.stop()
@MockDependency('phue')
def test_setup_bridge_connection_refused(self, mock_phue):
"""Test a registration failed with a connection refused exception."""
mock_bridge = mock_phue.Bridge
mock_bridge.side_effect = ConnectionRefusedError()
bridge = hue.HueBridge('localhost', self.hass, hue.PHUE_CONFIG_FILE)
bridge.setup()
self.assertFalse(bridge.configured)
self.assertTrue(bridge.config_request_id is None)
mock_bridge.assert_called_once_with(
'localhost',
config_file_path=get_test_config_dir(hue.PHUE_CONFIG_FILE))
@MockDependency('phue')
def test_setup_bridge_registration_exception(self, mock_phue):
"""Test a registration failed with an exception."""
mock_bridge = mock_phue.Bridge
mock_phue.PhueRegistrationException = Exception
mock_bridge.side_effect = mock_phue.PhueRegistrationException(1, 2)
bridge = hue.HueBridge('localhost', self.hass, hue.PHUE_CONFIG_FILE)
bridge.setup()
self.assertFalse(bridge.configured)
self.assertFalse(bridge.config_request_id is None)
self.assertTrue(isinstance(bridge.config_request_id, str))
mock_bridge.assert_called_once_with(
'localhost',
config_file_path=get_test_config_dir(hue.PHUE_CONFIG_FILE))
@MockDependency('phue')
def test_setup_bridge_registration_succeeds(self, mock_phue):
"""Test a registration success sequence."""
mock_bridge = mock_phue.Bridge
mock_phue.PhueRegistrationException = Exception
mock_bridge.side_effect = [
# First call, raise because not registered
mock_phue.PhueRegistrationException(1, 2),
# Second call, registration is done
None,
]
bridge = hue.HueBridge('localhost', self.hass, hue.PHUE_CONFIG_FILE)
bridge.setup()
self.assertFalse(bridge.configured)
self.assertFalse(bridge.config_request_id is None)
# Simulate the user confirming the registration
self.hass.services.call(
configurator.DOMAIN, configurator.SERVICE_CONFIGURE,
{configurator.ATTR_CONFIGURE_ID: bridge.config_request_id})
self.hass.block_till_done()
self.assertTrue(bridge.configured)
self.assertTrue(bridge.config_request_id is None)
# We should see a total of two identical calls
args = call(
'localhost',
config_file_path=get_test_config_dir(hue.PHUE_CONFIG_FILE))
mock_bridge.assert_has_calls([args, args])
# Make sure the request is done
self.assertEqual(1, len(self.hass.states.all()))
self.assertEqual('configured', self.hass.states.all()[0].state)
@MockDependency('phue')
def test_setup_bridge_registration_fails(self, mock_phue):
"""
Test a registration failure sequence.
This may happen when we start the registration process, the user
responds to the request but the bridge has become unreachable.
"""
mock_bridge = mock_phue.Bridge
mock_phue.PhueRegistrationException = Exception
mock_bridge.side_effect = [
# First call, raise because not registered
mock_phue.PhueRegistrationException(1, 2),
# Second call, the bridge has gone away
ConnectionRefusedError(),
]
bridge = hue.HueBridge('localhost', self.hass, hue.PHUE_CONFIG_FILE)
bridge.setup()
self.assertFalse(bridge.configured)
self.assertFalse(bridge.config_request_id is None)
# Simulate the user confirming the registration
self.hass.services.call(
configurator.DOMAIN, configurator.SERVICE_CONFIGURE,
{configurator.ATTR_CONFIGURE_ID: bridge.config_request_id})
self.hass.block_till_done()
self.assertFalse(bridge.configured)
self.assertFalse(bridge.config_request_id is None)
# We should see a total of two identical calls
args = call(
'localhost',
config_file_path=get_test_config_dir(hue.PHUE_CONFIG_FILE))
mock_bridge.assert_has_calls([args, args])
# The request should still be pending
self.assertEqual(1, len(self.hass.states.all()))
self.assertEqual('configure', self.hass.states.all()[0].state)
@MockDependency('phue')
def test_setup_bridge_registration_retry(self, mock_phue):
"""
Test a registration retry sequence.
This may happen when we start the registration process, the user
responds to the request but we fail to confirm it with the bridge.
"""
mock_bridge = mock_phue.Bridge
mock_phue.PhueRegistrationException = Exception
mock_bridge.side_effect = [
# First call, raise because not registered
mock_phue.PhueRegistrationException(1, 2),
# Second call, for whatever reason authentication fails
mock_phue.PhueRegistrationException(1, 2),
]
bridge = hue.HueBridge('localhost', self.hass, hue.PHUE_CONFIG_FILE)
bridge.setup()
self.assertFalse(bridge.configured)
self.assertFalse(bridge.config_request_id is None)
# Simulate the user confirming the registration
self.hass.services.call(
configurator.DOMAIN, configurator.SERVICE_CONFIGURE,
{configurator.ATTR_CONFIGURE_ID: bridge.config_request_id})
self.hass.block_till_done()
self.assertFalse(bridge.configured)
self.assertFalse(bridge.config_request_id is None)
# We should see a total of two identical calls
args = call(
'localhost',
config_file_path=get_test_config_dir(hue.PHUE_CONFIG_FILE))
mock_bridge.assert_has_calls([args, args])
# Make sure the request is done
self.assertEqual(1, len(self.hass.states.all()))
self.assertEqual('configure', self.hass.states.all()[0].state)
self.assertEqual(
'Failed to register, please try again.',
self.hass.states.all()[0].attributes.get(configurator.ATTR_ERRORS))
@MockDependency('phue')
def test_hue_activate_scene(self, mock_phue):
"""Test the hue_activate_scene service."""
with patch('homeassistant.helpers.discovery.load_platform'):
bridge = hue.HueBridge('localhost', self.hass,
hue.PHUE_CONFIG_FILE)
bridge.setup()
# No args
self.hass.services.call(hue.DOMAIN, hue.SERVICE_HUE_SCENE,
blocking=True)
bridge.bridge.run_scene.assert_not_called()
# Only one arg
self.hass.services.call(
hue.DOMAIN, hue.SERVICE_HUE_SCENE,
{hue.ATTR_GROUP_NAME: 'group'},
blocking=True)
bridge.bridge.run_scene.assert_not_called()
self.hass.services.call(
hue.DOMAIN, hue.SERVICE_HUE_SCENE,
{hue.ATTR_SCENE_NAME: 'scene'},
blocking=True)
bridge.bridge.run_scene.assert_not_called()
# Both required args
self.hass.services.call(
hue.DOMAIN, hue.SERVICE_HUE_SCENE,
{hue.ATTR_GROUP_NAME: 'group', hue.ATTR_SCENE_NAME: 'scene'},
blocking=True)
bridge.bridge.run_scene.assert_called_once_with('group', 'scene')
+1 -1
View File
@@ -34,7 +34,7 @@ def test_snips_call_action(hass, mqtt_mock):
intents = async_mock_intent(hass, 'Lights')
async_fire_mqtt_message(hass, 'hermes/nlu/intentParsed',
async_fire_mqtt_message(hass, 'hermes/intent/activateLights',
EXAMPLE_MSG)
yield from hass.async_block_till_done()
assert len(intents) == 1