Exemplo n.º 1
0
    def test_force_update_enabled(self):
        """Test force update option."""
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, sensor.DOMAIN, {
            sensor.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'test-topic',
                'unit_of_measurement': 'fav unit',
                'force_update': True
            }
        })

        events = []

        @ha.callback
        def callback(event):
            events.append(event)

        self.hass.bus.listen(EVENT_STATE_CHANGED, callback)

        fire_mqtt_message(self.hass, 'test-topic', '100')
        self.hass.block_till_done()
        self.assertEqual(1, len(events))

        fire_mqtt_message(self.hass, 'test-topic', '100')
        self.hass.block_till_done()
        self.assertEqual(2, len(events))
Exemplo n.º 2
0
def test_restore_state(hass):
    """Ensure states are restored on startup."""
    hass.data[DATA_RESTORE_CACHE] = {
        'sensor.test_template_sensor':
            State('sensor.test_template_sensor', 'It Test.'),
    }

    hass.state = CoreState.starting
    mock_component(hass, 'recorder')

    yield from async_setup_component(hass, 'sensor', {
        'sensor': {
            'platform': 'template',
            'sensors': {
                'test_template_sensor': {
                    'value_template':
                        "It {{ states.sensor.test_state.state }}."
                }
            }
        }
    })

    state = hass.states.get('sensor.test_template_sensor')
    assert state.state == 'It Test.'

    yield from hass.async_start()
    yield from hass.async_block_till_done()

    state = hass.states.get('sensor.test_template_sensor')
    assert state.state == 'It .'
Exemplo n.º 3
0
def test_restore_state(hass):
    """Test state gets restored."""
    mock_component(hass, 'recorder')
    hass.state = CoreState.starting
    hass.data[DATA_RESTORE_CACHE] = {
        'light.bed_light': State('light.bed_light', 'on', {
            'brightness': 'value-brightness',
            'color_temp': 'value-color_temp',
            'rgb_color': 'value-rgb_color',
            'xy_color': 'value-xy_color',
            'white_value': 'value-white_value',
            'effect': 'value-effect',
        }),
    }

    yield from async_setup_component(hass, 'light', {
        'light': {
            'platform': 'demo',
        }})

    state = hass.states.get('light.bed_light')
    assert state is not None
    assert state.entity_id == 'light.bed_light'
    assert state.state == 'on'
    assert state.attributes.get('brightness') == 'value-brightness'
    assert state.attributes.get('color_temp') == 'value-color_temp'
    assert state.attributes.get('rgb_color') == 'value-rgb_color'
    assert state.attributes.get('xy_color') == 'value-xy_color'
    assert state.attributes.get('white_value') == 'value-white_value'
    assert state.attributes.get('effect') == 'value-effect'
    def setup_method(self):
        """Set up things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        mock_component(self.hass, 'zone')
        mock_component(self.hass, 'group')

        self.host = "127.0.0.1"
Exemplo n.º 5
0
def test_restore_state(hass):
    """Ensure states are restored on startup."""
    hass.data[DATA_RESTORE_CACHE] = {
        'input_slider.b1': State('input_slider.b1', '70'),
        'input_slider.b2': State('input_slider.b2', '200'),
    }

    hass.state = CoreState.starting
    mock_component(hass, 'recorder')

    yield from async_setup_component(hass, DOMAIN, {
        DOMAIN: {
            'b1': {
                'initial': 50,
                'min': 0,
                'max': 100,
            },
            'b2': {
                'initial': 60,
                'min': 0,
                'max': 100,
            },
        }})

    state = hass.states.get('input_slider.b1')
    assert state
    assert float(state.state) == 70

    state = hass.states.get('input_slider.b2')
    assert state
    assert float(state.state) == 60
Exemplo n.º 6
0
    def test_force_update_enabled(self):
        """Test force update option."""
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, binary_sensor.DOMAIN, {
            binary_sensor.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'test-topic',
                'payload_on': 'ON',
                'payload_off': 'OFF',
                'force_update': True
            }
        })

        events = []

        @ha.callback
        def callback(event):
            """Verify event got called."""
            events.append(event)

        self.hass.bus.listen(EVENT_STATE_CHANGED, callback)

        fire_mqtt_message(self.hass, 'test-topic', 'ON')
        self.hass.block_till_done()
        self.assertEqual(1, len(events))

        fire_mqtt_message(self.hass, 'test-topic', 'ON')
        self.hass.block_till_done()
        self.assertEqual(2, len(events))
Exemplo n.º 7
0
def test_restore_state(hass):
    """Ensure states are restored on startup."""
    hass.data[DATA_RESTORE_CACHE] = {
        'binary_sensor.test': State('binary_sensor.test', 'on'),
    }

    hass.state = CoreState.starting
    mock_component(hass, 'recorder')

    config = {
        'binary_sensor': {
            'platform': 'template',
            'sensors': {
                'test': {
                    'friendly_name': 'virtual thingy',
                    'value_template':
                        "{{ states.sensor.test_state.state == 'on' }}",
                    'device_class': 'motion',
                },
            },
        },
    }
    yield from setup.async_setup_component(hass, 'binary_sensor', config)

    state = hass.states.get('binary_sensor.test')
    assert state.state == 'on'

    yield from hass.async_start()
    yield from hass.async_block_till_done()

    state = hass.states.get('binary_sensor.test')
    assert state.state == 'off'
def test_caching_data(hass):
    """Test that we cache data."""
    mock_component(hass, 'recorder')
    hass.state = CoreState.starting

    states = [
        State('input_boolean.b0', 'on'),
        State('input_boolean.b1', 'on'),
        State('input_boolean.b2', 'on'),
    ]

    with patch('homeassistant.helpers.restore_state.last_recorder_run',
               return_value=MagicMock(end=dt_util.utcnow())), \
            patch('homeassistant.helpers.restore_state.get_states',
                  return_value=states), \
            patch('homeassistant.helpers.restore_state.wait_connection_ready',
                  return_value=mock_coro(True)):
        state = yield from async_get_last_state(hass, 'input_boolean.b1')

    assert DATA_RESTORE_CACHE in hass.data
    assert hass.data[DATA_RESTORE_CACHE] == {st.entity_id: st for st in states}

    assert state is not None
    assert state.entity_id == 'input_boolean.b1'
    assert state.state == 'on'

    hass.bus.async_fire(EVENT_HOMEASSISTANT_START)

    yield from hass.async_block_till_done()

    assert DATA_RESTORE_CACHE not in hass.data
Exemplo n.º 9
0
def setup_comp(hass):
    """Initialize components."""
    mock_component(hass, 'zone')
    yaml_devices = hass.config.path(device_tracker.YAML_DEVICES)
    yield
    if os.path.isfile(yaml_devices):
        os.remove(yaml_devices)
Exemplo n.º 10
0
def setup_comp(hass):
    """Initialize components."""
    mock_component(hass, 'group')
    hass.loop.run_until_complete(async_setup_component(hass, zone.DOMAIN, {
            'zone': {
                'name': 'test',
                'latitude': 32.880837,
                'longitude': -117.237561,
                'radius': 250,
            }
        }))
Exemplo n.º 11
0
    def test_receive_mqtt_temperature(self):
        """Test getting the current temperature via MQTT."""
        config = copy.deepcopy(DEFAULT_CONFIG)
        config['climate']['current_temperature_topic'] = 'current_temperature'
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, climate.DOMAIN, config)

        fire_mqtt_message(self.hass, 'current_temperature', '47')
        self.hass.block_till_done()
        state = self.hass.states.get(ENTITY_CLIMATE)
        assert 47 == state.attributes.get('current_temperature')
    def setUp(self):
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        mock_component(self.hass, 'group')
        self.calls = []

        @callback
        def record_call(service):
            """Helper to record calls."""
            self.calls.append(service)

        self.hass.services.register('test', 'automation', record_call)
def mock_client(hass, test_client):
    """Start the Hass HTTP component."""
    mock_component(hass, 'group')
    mock_component(hass, 'zone')
    with patch('homeassistant.components.device_tracker.async_load_config',
               return_value=mock_coro([])):
        hass.loop.run_until_complete(
            async_setup_component(hass, 'device_tracker', {
                'device_tracker': {
                    'platform': 'owntracks_http'
                }
            }))
    return hass.loop.run_until_complete(test_client(hass.http.app))
Exemplo n.º 14
0
def test_load_on_demand_already_loaded(hass, test_client):
    """Test getting suites."""
    mock_component(hass, 'zwave')

    with patch.object(config, 'SECTIONS', []), \
            patch.object(config, 'ON_DEMAND', ['zwave']), \
            patch('homeassistant.components.config.zwave.async_setup') as stp:
        stp.return_value = mock_coro(True)

        yield from async_setup_component(hass, 'config', {})

    yield from hass.async_block_till_done()
    assert 'config.zwave' in hass.config.components
    assert stp.called
def test_no_last_run_found(hass):
    """Test that cache cannot be accessed if no last run found."""
    mock_component(hass, 'recorder')
    hass.state = CoreState.starting

    states = [State('input_boolean.b1', 'on')]

    with patch('homeassistant.helpers.restore_state.last_recorder_run',
               return_value=None), \
            patch('homeassistant.helpers.restore_state.get_states',
                  return_value=states), \
            patch('homeassistant.helpers.restore_state.wait_connection_ready',
                  return_value=mock_coro(True)):
        state = yield from async_get_last_state(hass, 'input_boolean.b1')
    assert state is None
def test_not_connected(hass):
    """Test that cache cannot be accessed if db connection times out."""
    mock_component(hass, 'recorder')
    hass.state = CoreState.starting

    states = [State('input_boolean.b1', 'on')]

    with patch('homeassistant.helpers.restore_state.last_recorder_run',
               return_value=MagicMock(end=dt_util.utcnow())), \
            patch('homeassistant.helpers.restore_state.get_states',
                  return_value=states), \
            patch('homeassistant.helpers.restore_state.wait_connection_ready',
                  return_value=mock_coro(False)):
        state = yield from async_get_last_state(hass, 'input_boolean.b1')
    assert state is None
Exemplo n.º 17
0
    def setUp(self):
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        mock_component(self.hass, 'group')
        setup_component(self.hass, sun.DOMAIN, {
            sun.DOMAIN: {sun.CONF_ELEVATION: 0}})

        self.calls = []

        @callback
        def record_call(service):
            """Call recorder."""
            self.calls.append(service)

        self.hass.services.register('test', 'automation', record_call)
Exemplo n.º 18
0
    def setup_method(self, _):
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        mock_mqtt_component(self.hass)
        mock_component(self.hass, 'group')
        mock_component(self.hass, 'zone')

        patcher = patch('homeassistant.components.device_tracker.'
                        'DeviceTracker.async_update_config')
        patcher.start()
        self.addCleanup(patcher.stop)

        orig_context = owntracks.OwnTracksContext

        def store_context(*args):
            self.context = orig_context(*args)
            return self.context

        with patch('homeassistant.components.device_tracker.async_load_config',
                   return_value=mock_coro([])), \
                patch('homeassistant.components.device_tracker.'
                      'load_yaml_config_file', return_value=mock_coro({})), \
                patch.object(owntracks, 'OwnTracksContext', store_context), \
                assert_setup_component(1, device_tracker.DOMAIN):
            assert setup_component(self.hass, device_tracker.DOMAIN, {
                device_tracker.DOMAIN: {
                    CONF_PLATFORM: 'owntracks',
                    CONF_MAX_GPS_ACCURACY: 200,
                    CONF_WAYPOINT_IMPORT: True,
                    CONF_WAYPOINT_WHITELIST: ['jon', 'greg']
                }})

        self.hass.states.set(
            'zone.inner', 'zoning', INNER_ZONE)

        self.hass.states.set(
            'zone.inner_2', 'zoning', INNER_ZONE)

        self.hass.states.set(
            'zone.outer', 'zoning', OUTER_ZONE)

        # Clear state between tests
        # NB: state "None" is not a state that is created by Device
        # so when we compare state to None in the tests this
        # is really checking that it is still in its original
        # test case state. See Device.async_update.
        self.hass.states.set(DEVICE_TRACKER_STATE, None)
Exemplo n.º 19
0
    def setup_method(self, method):
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        mock_mqtt_component(self.hass)
        mock_component(self.hass, 'group')
        mock_component(self.hass, 'zone')

        patch_load = patch(
            'homeassistant.components.device_tracker.async_load_config',
            return_value=mock_coro([]))
        patch_load.start()
        self.addCleanup(patch_load.stop)

        patch_save = patch('homeassistant.components.device_tracker.'
                           'DeviceTracker.async_update_config')
        patch_save.start()
        self.addCleanup(patch_save.stop)
Exemplo n.º 20
0
    def test_setting_sensor_value_via_mqtt_json_message(self):
        """Test the setting of the value via MQTT with JSON payload."""
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, sensor.DOMAIN, {
            sensor.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'test-topic',
                'unit_of_measurement': 'fav unit',
                'value_template': '{{ value_json.val }}'
            }
        })

        fire_mqtt_message(self.hass, 'test-topic', '{ "val": "100" }')
        self.hass.block_till_done()
        state = self.hass.states.get('sensor.test')

        self.assertEqual('100', state.state)
def test_hass_running(hass):
    """Test that cache cannot be accessed while hass is running."""
    mock_component(hass, 'recorder')

    states = [
        State('input_boolean.b0', 'on'),
        State('input_boolean.b1', 'on'),
        State('input_boolean.b2', 'on'),
    ]

    with patch('homeassistant.helpers.restore_state.last_recorder_run',
               return_value=MagicMock(end=dt_util.utcnow())), \
            patch('homeassistant.helpers.restore_state.get_states',
                  return_value=states), \
            patch('homeassistant.helpers.restore_state.wait_connection_ready',
                  return_value=mock_coro(True)):
        state = yield from async_get_last_state(hass, 'input_boolean.b1')
    assert state is None
Exemplo n.º 22
0
def test_new_version_shows_entity_after_hour_hassio(
        hass, mock_get_uuid, mock_get_newest_version):
    """Test if new entity is created if new version is available / hass.io."""
    mock_get_uuid.return_value = MOCK_HUUID
    mock_get_newest_version.return_value = mock_coro((NEW_VERSION, ''))
    mock_component(hass, 'hassio')
    hass.data['hassio_hass_version'] = "999.0"

    res = yield from async_setup_component(
        hass, updater.DOMAIN, {updater.DOMAIN: {}})
    assert res, 'Updater failed to set up'

    with patch('homeassistant.components.updater.current_version',
               MOCK_VERSION):
        async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1))
        yield from hass.async_block_till_done()

    assert hass.states.is_state(updater.ENTITY_ID, "999.0")
Exemplo n.º 23
0
    def test_update_with_json_attrs_not_dict(self, mock_logger):
        """Test attributes get extracted from a JSON result."""
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, sensor.DOMAIN, {
            sensor.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'test-topic',
                'unit_of_measurement': 'fav unit',
                'json_attributes': 'val'
            }
        })

        fire_mqtt_message(self.hass, 'test-topic', '[ "list", "of", "things"]')
        self.hass.block_till_done()
        state = self.hass.states.get('sensor.test')

        assert state.attributes.get('val') is None
        assert mock_logger.warning.called
Exemplo n.º 24
0
    def test_setting_sensor_attribute_via_mqtt_json_message(self):
        """Test the setting of attribute via MQTT with JSON payload."""
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, sensor.DOMAIN, {
            sensor.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'test-topic',
                'unit_of_measurement': 'fav unit',
                'json_attributes': 'val'
            }
        })

        fire_mqtt_message(self.hass, 'test-topic', '{ "val": "100" }')
        self.hass.block_till_done()
        state = self.hass.states.get('sensor.test')

        assert '100' == \
            state.attributes.get('val')
Exemplo n.º 25
0
def test_restore_state(hass):
    """Ensure states are restored on startup."""
    hass.data[DATA_RESTORE_CACHE] = {
        'light.test_template_light':
            State('light.test_template_light', 'on'),
    }

    hass.state = CoreState.starting
    mock_component(hass, 'recorder')
    yield from setup.async_setup_component(hass, 'light', {
        'light': {
            'platform': 'template',
            'lights': {
                'test_template_light': {
                    'value_template':
                        "{{states.light.test_state.state}}",
                    'turn_on': {
                        'service': 'test.automation',
                    },
                    'turn_off': {
                        'service': 'light.turn_off',
                        'entity_id': 'light.test_state'
                    },
                    'set_level': {
                        'service': 'test.automation',
                        'data_template': {
                            'entity_id': 'light.test_state',
                            'brightness': '{{brightness}}'
                        }
                    }
                }
            }
        }
    })

    state = hass.states.get('light.test_template_light')
    assert state.state == 'on'

    yield from hass.async_start()
    yield from hass.async_block_till_done()

    state = hass.states.get('light.test_template_light')
    assert state.state == 'off'
def test_cache_timeout(hass):
    """Test that cache timeout returns none."""
    mock_component(hass, 'recorder')
    hass.state = CoreState.starting

    states = [State('input_boolean.b1', 'on')]

    @asyncio.coroutine
    def timeout_coro():
        raise asyncio.TimeoutError()

    with patch('homeassistant.helpers.restore_state.last_recorder_run',
               return_value=MagicMock(end=dt_util.utcnow())), \
            patch('homeassistant.helpers.restore_state.get_states',
                  return_value=states), \
            patch('homeassistant.helpers.restore_state.wait_connection_ready',
                  return_value=timeout_coro()):
        state = yield from async_get_last_state(hass, 'input_boolean.b1')
    assert state is None
Exemplo n.º 27
0
    def test_setting_sensor_value_via_mqtt_message(self):
        """Test the setting of the value via MQTT."""
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, sensor.DOMAIN, {
            sensor.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'test-topic',
                'unit_of_measurement': 'fav unit'
            }
        })

        fire_mqtt_message(self.hass, 'test-topic', '100')
        self.hass.block_till_done()
        state = self.hass.states.get('sensor.test')

        self.assertEqual('100', state.state)
        self.assertEqual('fav unit',
                         state.attributes.get('unit_of_measurement'))
Exemplo n.º 28
0
    def test_off_delay(self):
        """Test off_delay option."""
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, binary_sensor.DOMAIN, {
            binary_sensor.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'test-topic',
                'payload_on': 'ON',
                'payload_off': 'OFF',
                'off_delay': 30,
                'force_update': True
            }
        })

        events = []

        @ha.callback
        def callback(event):
            """Verify event got called."""
            events.append(event)

        self.hass.bus.listen(EVENT_STATE_CHANGED, callback)

        fire_mqtt_message(self.hass, 'test-topic', 'ON')
        self.hass.block_till_done()
        state = self.hass.states.get('binary_sensor.test')
        assert STATE_ON == state.state
        assert 1 == len(events)

        fire_mqtt_message(self.hass, 'test-topic', 'ON')
        self.hass.block_till_done()
        state = self.hass.states.get('binary_sensor.test')
        assert STATE_ON == state.state
        assert 2 == len(events)

        fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=30))
        self.hass.block_till_done()
        state = self.hass.states.get('binary_sensor.test')
        assert STATE_OFF == state.state
        assert 3 == len(events)
Exemplo n.º 29
0
    def test_update_with_json_attrs_and_template(self):
        """Test attributes get extracted from a JSON result."""
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, sensor.DOMAIN, {
            sensor.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'test-topic',
                'unit_of_measurement': 'fav unit',
                'value_template': '{{ value_json.val }}',
                'json_attributes': 'val'
            }
        })

        fire_mqtt_message(self.hass, 'test-topic', '{ "val": "100" }')
        self.hass.block_till_done()
        state = self.hass.states.get('sensor.test')

        self.assertEqual('100',
                         state.attributes.get('val'))
        self.assertEqual('100', state.state)
Exemplo n.º 30
0
    def test_update_with_json_attrs_bad_JSON(self, mock_logger):
        """Test attributes get extracted from a JSON result."""
        mock_component(self.hass, 'mqtt')
        assert setup_component(self.hass, sensor.DOMAIN, {
            sensor.DOMAIN: {
                'platform': 'mqtt',
                'name': 'test',
                'state_topic': 'test-topic',
                'unit_of_measurement': 'fav unit',
                'json_attributes': 'val'
            }
        })

        fire_mqtt_message(self.hass, 'test-topic', 'This is not JSON')
        self.hass.block_till_done()

        state = self.hass.states.get('sensor.test')
        self.assertEqual(None,
                         state.attributes.get('val'))
        self.assertTrue(mock_logger.warning.called)
        self.assertTrue(mock_logger.debug.called)
Exemplo n.º 31
0
def setup_comp(hass):
    """Initialize components."""
    mock_component(hass, 'group')
    hass.states.async_set('test.entity', 'hello')
Exemplo n.º 32
0
 def setup_method(self, _):
     """Setup things to be run when tests are started."""
     self.hass = get_test_home_assistant()
     mock_component(self.hass, 'zone')
Exemplo n.º 33
0
 def setUp(self):
     """Set up things to be run when tests are started."""
     self.hass = get_test_home_assistant()
     mock_component(self.hass, 'rfxtrx')
Exemplo n.º 34
0
def setup_comp(hass):
    """Initialize components."""
    mock_component(hass, "group")