Beispiel #1
0
    def test_reproduce_turn_off(self):
        """Test reproduce_state with SERVICE_TURN_OFF."""
        calls = mock_service(self.hass, 'light', SERVICE_TURN_OFF)

        self.hass.states.set('light.test', 'on')

        state.reproduce_state(self.hass, ha.State('light.test', 'off'))

        self.hass.block_till_done()

        self.assertTrue(len(calls) > 0)
        last_call = calls[-1]
        self.assertEqual('light', last_call.domain)
        self.assertEqual(SERVICE_TURN_OFF, last_call.service)
        self.assertEqual(['light.test'], last_call.data.get('entity_id'))
def test_from_event_to_db_state():
    """Test converting event to db state."""
    state = ha.State("sensor.temperature", "18")
    event = ha.Event(
        EVENT_STATE_CHANGED,
        {
            "entity_id": "sensor.temperature",
            "old_state": None,
            "new_state": state
        },
        context=state.context,
    )
    # We don't restore context unless we need it by joining the
    # events table on the event_id for state_changed events
    state.context = ha.Context(id=None)
    assert state == States.from_event(event).to_native()
Beispiel #3
0
def test_from_event_to_delete_state():
    """Test converting deleting state event to db state."""
    event = ha.Event(
        EVENT_STATE_CHANGED,
        {
            "entity_id": "sensor.temperature",
            "old_state": ha.State("sensor.temperature", "18"),
            "new_state": None,
        },
    )
    db_state = States.from_event(event)

    assert db_state.entity_id == "sensor.temperature"
    assert db_state.state == ""
    assert db_state.last_changed == event.time_fired
    assert db_state.last_updated == event.time_fired
Beispiel #4
0
    def test_reproduce_state_with_group(self):
        light_calls = mock_service(self.hass, 'light', SERVICE_TURN_ON)

        self.hass.states.set('group.test', 'off',
                             {'entity_id': ['light.test1', 'light.test2']})

        state.reproduce_state(self.hass, ha.State('group.test', 'on'))

        self.hass.pool.block_till_done()

        self.assertEqual(1, len(light_calls))
        last_call = light_calls[-1]
        self.assertEqual('light', last_call.domain)
        self.assertEqual(SERVICE_TURN_ON, last_call.service)
        self.assertEqual(['light.test1', 'light.test2'],
                         last_call.data.get('entity_id'))
Beispiel #5
0
async def test_run_select_service_optimistic_with_command_template(
        hass, mqtt_mock_entry_with_yaml_config):
    """Test that set_value service works in optimistic mode and with a command_template."""
    topic = "test/select"

    fake_state = ha.State("select.test", "milk")

    with patch(
            "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state",
            return_value=fake_state,
    ):
        assert await async_setup_component(
            hass,
            select.DOMAIN,
            {
                "select": {
                    "platform": "mqtt",
                    "command_topic": topic,
                    "name": "Test Select",
                    "options": ["milk", "beer"],
                    "command_template": '{"option": "{{ value }}"}',
                }
            },
        )
        await hass.async_block_till_done()
        mqtt_mock = await mqtt_mock_entry_with_yaml_config()

    state = hass.states.get("select.test_select")
    assert state.state == "milk"
    assert state.attributes.get(ATTR_ASSUMED_STATE)

    await hass.services.async_call(
        SELECT_DOMAIN,
        SERVICE_SELECT_OPTION,
        {
            ATTR_ENTITY_ID: "select.test_select",
            ATTR_OPTION: "beer"
        },
        blocking=True,
    )

    mqtt_mock.async_publish.assert_called_once_with(topic,
                                                    '{"option": "beer"}', 0,
                                                    False)
    mqtt_mock.async_publish.reset_mock()
    state = hass.states.get("select.test_select")
    assert state.state == "beer"
Beispiel #6
0
    def test_reproduce_group(self):
        """Test reproduce_state with group."""
        light_calls = mock_service(self.hass, 'light', SERVICE_TURN_ON)

        self.hass.states.set('group.test', 'off',
                             {'entity_id': ['light.test1', 'light.test2']})

        state.reproduce_state(self.hass, ha.State('group.test', 'on'))

        self.hass.block_till_done()

        assert 1 == len(light_calls)
        last_call = light_calls[-1]
        assert 'light' == last_call.domain
        assert SERVICE_TURN_ON == last_call.service
        assert ['light.test1', 'light.test2'] == \
            last_call.data.get('entity_id')
Beispiel #7
0
    def test_reproduce_state_with_complex_service_data(self):
        calls = mock_service(self.hass, 'light', SERVICE_TURN_ON)

        self.hass.states.set('light.test', 'off')

        complex_data = ['hello', {'11': '22'}]

        state.reproduce_state(
            self.hass, ha.State('light.test', 'on', {'complex': complex_data}))

        self.hass.pool.block_till_done()

        self.assertTrue(len(calls) > 0)
        last_call = calls[-1]
        self.assertEqual('light', last_call.domain)
        self.assertEqual(SERVICE_TURN_ON, last_call.service)
        self.assertEqual(complex_data, last_call.data.get('complex'))
    def test_reproduce_media_pause(self):
        """Test reproduce_state with SERVICE_MEDIA_PAUSE."""
        calls = mock_service(self.hass, 'media_player', SERVICE_MEDIA_PAUSE)

        self.hass.states.set('media_player.test', 'playing')

        state.reproduce_state(self.hass, ha.State('media_player.test',
                                                  'paused'))

        self.hass.block_till_done()

        self.assertTrue(len(calls) > 0)
        last_call = calls[-1]
        self.assertEqual('media_player', last_call.domain)
        self.assertEqual(SERVICE_MEDIA_PAUSE, last_call.service)
        self.assertEqual(['media_player.test'],
                         last_call.data.get('entity_id'))
Beispiel #9
0
    def test_reproduce_media_pause(self):
        """Test reproduce_state with SERVICE_MEDIA_PAUSE."""
        calls = mock_service(self.hass, 'media_player', SERVICE_MEDIA_PAUSE)

        self.hass.states.set('media_player.test', 'playing')

        state.reproduce_state(self.hass, ha.State('media_player.test',
                                                  'paused'))

        self.hass.block_till_done()

        assert len(calls) > 0
        last_call = calls[-1]
        assert 'media_player' == last_call.domain
        assert SERVICE_MEDIA_PAUSE == last_call.service
        assert ['media_player.test'] == \
            last_call.data.get('entity_id')
Beispiel #10
0
    def test_event_listener_attr_details(self, mock_client):
        """Test event listener."""
        config = {
            'statsd': {
                'host': 'host',
                'log_attributes': True
            }
        }

        config['statsd'][statsd.CONF_RATE] = statsd.DEFAULT_RATE

        self.hass.bus.listen = mock.MagicMock()
        setup_component(self.hass, statsd.DOMAIN, config)
        self.assertTrue(self.hass.bus.listen.called)
        handler_method = self.hass.bus.listen.call_args_list[0][0][1]

        valid = {'1': 1,
                 '1.0': 1.0,
                 STATE_ON: 1,
                 STATE_OFF: 0}
        for in_, out in valid.items():
            state = mock.MagicMock(state=in_,
                                   attributes={"attribute key": 3.2})
            handler_method(mock.MagicMock(data={'new_state': state}))
            mock_client.return_value.gauge.assert_has_calls([
                mock.call("%s.state" % state.entity_id,
                          out, statsd.DEFAULT_RATE),
                mock.call("%s.attribute_key" % state.entity_id,
                          3.2, statsd.DEFAULT_RATE),
            ])

            mock_client.return_value.gauge.reset_mock()

            self.assertEqual(mock_client.return_value.incr.call_count, 1)
            self.assertEqual(
                mock_client.return_value.incr.call_args,
                mock.call(state.entity_id, rate=statsd.DEFAULT_RATE)
            )
            mock_client.return_value.incr.reset_mock()

        for invalid in ('foo', '', object):
            handler_method(mock.MagicMock(data={
                'new_state': ha.State('domain.test', invalid, {})}))
            self.assertFalse(mock_client.return_value.gauge.called)
            self.assertTrue(mock_client.return_value.incr.called)
Beispiel #11
0
async def test_reproduce_complex_data(hass):
    """Test reproduce_state with complex service data."""
    calls = async_mock_service(hass, 'light', SERVICE_TURN_ON)

    hass.states.async_set('light.test', 'off')

    complex_data = ['hello', {'11': '22'}]

    await state.async_reproduce_state(
        hass, ha.State('light.test', 'on', {'complex': complex_data}))

    await hass.async_block_till_done()

    assert len(calls) > 0
    last_call = calls[-1]
    assert last_call.domain == 'light'
    assert SERVICE_TURN_ON == last_call.service
    assert complex_data == last_call.data.get('complex')
Beispiel #12
0
async def test_reproduce_complex_data(hass):
    """Test reproduce_state with complex service data."""
    calls = async_mock_service(hass, "light", SERVICE_TURN_ON)

    hass.states.async_set("light.test", "off")

    complex_data = [255, 100, 100]

    await state.async_reproduce_state(
        hass, ha.State("light.test", "on", {"rgb_color": complex_data}))

    await hass.async_block_till_done()

    assert len(calls) > 0
    last_call = calls[-1]
    assert last_call.domain == "light"
    assert last_call.service == SERVICE_TURN_ON
    assert last_call.data.get("rgb_color") == complex_data
Beispiel #13
0
async def test_reproduce_complex_data(hass):
    """Test reproduce_state with complex service data."""
    calls = async_mock_service(hass, "light", SERVICE_TURN_ON)

    hass.states.async_set("light.test", "off")

    complex_data = ["hello", {"11": "22"}]

    await state.async_reproduce_state(
        hass, ha.State("light.test", "on", {"complex": complex_data}))

    await hass.async_block_till_done()

    assert len(calls) > 0
    last_call = calls[-1]
    assert last_call.domain == "light"
    assert SERVICE_TURN_ON == last_call.service
    assert complex_data == last_call.data.get("complex")
Beispiel #14
0
    def test_report_with_binary_state(self, mock_time):
        """Test the reporting with binary state."""
        mock_time.return_value = 12345
        state = ha.State('domain.entity', STATE_ON, {'foo': 1.0})
        with mock.patch.object(self.gf, '_send_to_graphite') as mock_send:
            self.gf._report_attributes('entity', state)
            expected = ['ha.entity.foo 1.000000 12345',
                        'ha.entity.state 1.000000 12345']
            actual = mock_send.call_args_list[0][0][0].split('\n')
            self.assertEqual(sorted(expected), sorted(actual))

        state.state = STATE_OFF
        with mock.patch.object(self.gf, '_send_to_graphite') as mock_send:
            self.gf._report_attributes('entity', state)
            expected = ['ha.entity.foo 1.000000 12345',
                        'ha.entity.state 0.000000 12345']
            actual = mock_send.call_args_list[0][0][0].split('\n')
            self.assertEqual(sorted(expected), sorted(actual))
Beispiel #15
0
    def test_reproduce_complex_data(self):
        """Test reproduce_state with complex service data."""
        calls = mock_service(self.hass, 'light', SERVICE_TURN_ON)

        self.hass.states.set('light.test', 'off')

        complex_data = ['hello', {'11': '22'}]

        state.reproduce_state(
            self.hass, ha.State('light.test', 'on', {'complex': complex_data}))

        self.hass.block_till_done()

        assert len(calls) > 0
        last_call = calls[-1]
        assert 'light' == last_call.domain
        assert SERVICE_TURN_ON == last_call.service
        assert complex_data == last_call.data.get('complex')
Beispiel #16
0
async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock):
    """Test the sending MQTT commands in optimistic mode."""
    fake_state = ha.State("switch.test", "on")

    with patch(
        "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state",
        return_value=fake_state,
    ):
        assert await async_setup_component(
            hass,
            switch.DOMAIN,
            {
                switch.DOMAIN: {
                    "platform": "mqtt",
                    "name": "test",
                    "command_topic": "command-topic",
                    "payload_on": "beer on",
                    "payload_off": "beer off",
                    "qos": "2",
                }
            },
        )
        await hass.async_block_till_done()

    state = hass.states.get("switch.test")
    assert state.state == STATE_ON
    assert state.attributes.get(ATTR_ASSUMED_STATE)

    await common.async_turn_on(hass, "switch.test")

    mqtt_mock.async_publish.assert_called_once_with(
        "command-topic", "beer on", 2, False
    )
    mqtt_mock.async_publish.reset_mock()
    state = hass.states.get("switch.test")
    assert state.state == STATE_ON

    await common.async_turn_off(hass, "switch.test")

    mqtt_mock.async_publish.assert_called_once_with(
        "command-topic", "beer off", 2, False
    )
    state = hass.states.get("switch.test")
    assert state.state == STATE_OFF
Beispiel #17
0
def test_json_encoder(hass):
    """Test the JSON Encoder."""
    ha_json_enc = JSONEncoder()
    state = core.State("test.test", "hello")

    # Test serializing a datetime
    now = dt_util.utcnow()
    assert ha_json_enc.default(now) == now.isoformat()

    # Test serializing a set()
    data = {"milk", "beer"}
    assert sorted(ha_json_enc.default(data)) == sorted(data)

    # Test serializing an object which implements as_dict
    assert ha_json_enc.default(state) == state.as_dict()

    # Default method raises TypeError if non HA object
    with pytest.raises(TypeError):
        ha_json_enc.default(1)
    def create_state_changed_event(self,
                                   event_time_fired,
                                   entity_id,
                                   state,
                                   attributes=None,
                                   last_changed=None,
                                   last_updated=None):
        """Create state changed event."""
        # Logbook only cares about state change events that
        # contain an old state but will not actually act on it.
        state = ha.State(entity_id, state, attributes, last_changed,
                         last_updated).as_dict()

        return ha.Event(EVENT_STATE_CHANGED, {
            'entity_id': entity_id,
            'old_state': state,
            'new_state': state,
        },
                        time_fired=event_time_fired)
Beispiel #19
0
    def test_reproduce_media_data(self):
        """Test reproduce_state with SERVICE_PLAY_MEDIA."""
        calls = mock_service(self.hass, 'media_player', SERVICE_PLAY_MEDIA)

        self.hass.states.set('media_player.test', 'off')

        media_attributes = {'media_content_type': 'movie',
                            'media_content_id': 'batman'}

        state.reproduce_state(self.hass, ha.State('media_player.test', 'None',
                                                  media_attributes))

        self.hass.pool.block_till_done()

        self.assertTrue(len(calls) > 0)
        last_call = calls[-1]
        self.assertEqual('media_player', last_call.domain)
        self.assertEqual(SERVICE_PLAY_MEDIA, last_call.service)
        self.assertEqual('movie', last_call.data.get('media_content_type'))
        self.assertEqual('batman', last_call.data.get('media_content_id'))
Beispiel #20
0
async def test_sending_mqtt_commands_and_optimistic(
        hass, mqtt_mock_entry_with_yaml_config):
    """Test the sending MQTT commands in optimistic mode."""
    fake_state = ha.State("switch.test", "on")
    mock_restore_cache(hass, (fake_state, ))

    assert await async_setup_component(
        hass,
        switch.DOMAIN,
        {
            switch.DOMAIN: {
                "platform": "mqtt",
                "name": "test",
                "command_topic": "command-topic",
                "payload_on": "beer on",
                "payload_off": "beer off",
                "qos": "2",
            }
        },
    )
    await hass.async_block_till_done()
    mqtt_mock = await mqtt_mock_entry_with_yaml_config()

    state = hass.states.get("switch.test")
    assert state.state == STATE_ON
    assert state.attributes.get(ATTR_ASSUMED_STATE)

    await common.async_turn_on(hass, "switch.test")

    mqtt_mock.async_publish.assert_called_once_with("command-topic", "beer on",
                                                    2, False)
    mqtt_mock.async_publish.reset_mock()
    state = hass.states.get("switch.test")
    assert state.state == STATE_ON

    await common.async_turn_off(hass, "switch.test")

    mqtt_mock.async_publish.assert_called_once_with("command-topic",
                                                    "beer off", 2, False)
    state = hass.states.get("switch.test")
    assert state.state == STATE_OFF
Beispiel #21
0
async def test_sending_mqtt_commands_and_optimistic(hass, mock_publish):
    """Test the sending MQTT commands in optimistic mode."""
    fake_state = ha.State('switch.test', 'on')

    with patch(
            'homeassistant.helpers.restore_state.RestoreEntity'
            '.async_get_last_state',
            return_value=mock_coro(fake_state)):
        assert await async_setup_component(
            hass, switch.DOMAIN, {
                switch.DOMAIN: {
                    'platform': 'mqtt',
                    'name': 'test',
                    'command_topic': 'command-topic',
                    'payload_on': 'beer on',
                    'payload_off': 'beer off',
                    'qos': '2'
                }
            })

    state = hass.states.get('switch.test')
    assert STATE_ON == state.state
    assert state.attributes.get(ATTR_ASSUMED_STATE)

    common.turn_on(hass, 'switch.test')
    await hass.async_block_till_done()

    mock_publish.async_publish.assert_called_once_with('command-topic',
                                                       'beer on', 2, False)
    mock_publish.async_publish.reset_mock()
    state = hass.states.get('switch.test')
    assert STATE_ON == state.state

    common.turn_off(hass, 'switch.test')
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    mock_publish.async_publish.assert_called_once_with('command-topic',
                                                       'beer off', 2, False)
    state = hass.states.get('switch.test')
    assert STATE_OFF == state.state
async def test_optimistic(hass, mqtt_mock):
    """Test optimistic mode."""
    fake_state = ha.State('light.test', 'on', {'brightness': 95,
                                               'hs_color': [100, 100],
                                               'effect': 'random',
                                               'color_temp': 100,
                                               'white_value': 50})

    with patch('homeassistant.helpers.restore_state.RestoreEntity'
               '.async_get_last_state',
               return_value=mock_coro(fake_state)):
        with assert_setup_component(1, light.DOMAIN):
            assert await async_setup_component(hass, light.DOMAIN, {
                light.DOMAIN: {
                    'platform': 'mqtt',
                    'schema': 'template',
                    'name': 'test',
                    'command_topic': 'test_light_rgb/set',
                    'command_on_template': 'on,'
                                           '{{ brightness|d }},'
                                           '{{ color_temp|d }},'
                                           '{{ white_value|d }},'
                                           '{{ red|d }}-'
                                           '{{ green|d }}-'
                                           '{{ blue|d }}',
                    'command_off_template': 'off',
                    'effect_list': ['colorloop', 'random'],
                    'effect_command_topic': 'test_light_rgb/effect/set',
                    'qos': 2
                }
            })

    state = hass.states.get('light.test')
    assert STATE_ON == state.state
    assert 95 == state.attributes.get('brightness')
    assert (100, 100) == state.attributes.get('hs_color')
    assert 'random' == state.attributes.get('effect')
    assert 100 == state.attributes.get('color_temp')
    assert 50 == state.attributes.get('white_value')
    assert state.attributes.get(ATTR_ASSUMED_STATE)
Beispiel #23
0
async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock):
    """Test the sending of command in optimistic mode."""
    fake_state = ha.State(
        'light.test', 'on', {
            'brightness': 95,
            'hs_color': [100, 100],
            'effect': 'random',
            'color_temp': 100,
            'white_value': 50
        })

    with patch(
            'homeassistant.helpers.restore_state.RestoreEntity'
            '.async_get_last_state',
            return_value=mock_coro(fake_state)):
        assert await async_setup_component(
            hass, light.DOMAIN, {
                light.DOMAIN: {
                    'platform': 'mqtt',
                    'schema': 'json',
                    'name': 'test',
                    'command_topic': 'test_light_rgb/set',
                    'brightness': True,
                    'color_temp': True,
                    'effect': True,
                    'rgb': True,
                    'white_value': True,
                    'qos': 2
                }
            })

    state = hass.states.get('light.test')
    assert STATE_ON == state.state
    assert 95 == state.attributes.get('brightness')
    assert (100, 100) == state.attributes.get('hs_color')
    assert 'random' == state.attributes.get('effect')
    assert 100 == state.attributes.get('color_temp')
    assert 50 == state.attributes.get('white_value')
    assert 191 == state.attributes.get(ATTR_SUPPORTED_FEATURES)
    assert state.attributes.get(ATTR_ASSUMED_STATE)
Beispiel #24
0
    def test_report_with_binary_state(self, mock_time):
        """Test the reporting with binary state."""
        mock_time.return_value = 12345
        state = ha.State("domain.entity", STATE_ON, {"foo": 1.0})
        with mock.patch.object(self.gf, "_send_to_graphite") as mock_send:
            self.gf._report_attributes("entity", state)
            expected = [
                "ha.entity.foo 1.000000 12345",
                "ha.entity.state 1.000000 12345",
            ]
            actual = mock_send.call_args_list[0][0][0].split("\n")
            assert sorted(expected) == sorted(actual)

        state.state = STATE_OFF
        with mock.patch.object(self.gf, "_send_to_graphite") as mock_send:
            self.gf._report_attributes("entity", state)
            expected = [
                "ha.entity.foo 1.000000 12345",
                "ha.entity.state 0.000000 12345",
            ]
            actual = mock_send.call_args_list[0][0][0].split("\n")
            assert sorted(expected) == sorted(actual)
Beispiel #25
0
    def test_reproduce_media_data(self):
        """Test reproduce_state with SERVICE_PLAY_MEDIA."""
        calls = mock_service(self.hass, 'media_player', SERVICE_PLAY_MEDIA)

        self.hass.states.set('media_player.test', 'off')

        media_attributes = {
            'media_content_type': 'movie',
            'media_content_id': 'batman'
        }

        state.reproduce_state(
            self.hass, ha.State('media_player.test', 'None', media_attributes))

        self.hass.block_till_done()

        assert len(calls) > 0
        last_call = calls[-1]
        assert 'media_player' == last_call.domain
        assert SERVICE_PLAY_MEDIA == last_call.service
        assert 'movie' == last_call.data.get('media_content_type')
        assert 'batman' == last_call.data.get('media_content_id')
async def test_event_listener_attr_details(hass, mock_client):
    """Test event listener."""
    config = {"statsd": {"host": "host", "log_attributes": True}}

    config["statsd"][statsd.CONF_RATE] = statsd.DEFAULT_RATE

    hass.bus.listen = MagicMock()
    await async_setup_component(hass, statsd.DOMAIN, config)
    assert hass.bus.listen.called
    handler_method = hass.bus.listen.call_args_list[0][0][1]

    valid = {"1": 1, "1.0": 1.0, STATE_ON: 1, STATE_OFF: 0}
    for in_, out in valid.items():
        state = MagicMock(state=in_, attributes={"attribute key": 3.2})
        handler_method(MagicMock(data={"new_state": state}))
        mock_client.gauge.assert_has_calls(
            [
                mock.call("%s.state" % state.entity_id, out, statsd.DEFAULT_RATE),
                mock.call(
                    "%s.attribute_key" % state.entity_id, 3.2, statsd.DEFAULT_RATE
                ),
            ]
        )

        mock_client.gauge.reset_mock()

        assert mock_client.incr.call_count == 1
        assert mock_client.incr.call_args == mock.call(
            state.entity_id, rate=statsd.DEFAULT_RATE
        )
        mock_client.incr.reset_mock()

    for invalid in ("foo", "", object):
        handler_method(
            MagicMock(data={"new_state": ha.State("domain.test", invalid, {})})
        )
        assert not mock_client.gauge.called
        assert mock_client.incr.called
Beispiel #27
0
    def test_sending_mqtt_commands_and_optimistic(self):
        """Test the sending MQTT commands in optimistic mode."""
        fake_state = ha.State('switch.test', 'on')

        with patch('homeassistant.components.switch.mqtt.async_get_last_state',
                   return_value=mock_coro(fake_state)):
            assert setup_component(
                self.hass, switch.DOMAIN, {
                    switch.DOMAIN: {
                        'platform': 'mqtt',
                        'name': 'test',
                        'command_topic': 'command-topic',
                        'payload_on': 'beer on',
                        'payload_off': 'beer off',
                        'qos': '2'
                    }
                })

        state = self.hass.states.get('switch.test')
        self.assertEqual(STATE_ON, state.state)
        self.assertTrue(state.attributes.get(ATTR_ASSUMED_STATE))

        switch.turn_on(self.hass, 'switch.test')
        self.hass.block_till_done()

        self.mock_publish.async_publish.assert_called_once_with(
            'command-topic', 'beer on', 2, False)
        self.mock_publish.async_publish.reset_mock()
        state = self.hass.states.get('switch.test')
        self.assertEqual(STATE_ON, state.state)

        switch.turn_off(self.hass, 'switch.test')
        self.hass.block_till_done()

        self.mock_publish.async_publish.assert_called_once_with(
            'command-topic', 'beer off', 2, False)
        state = self.hass.states.get('switch.test')
        self.assertEqual(STATE_OFF, state.state)
Beispiel #28
0
async def test_skip_restoring_state_with_over_due_expire_trigger(
        hass, mqtt_mock, caplog, freezer):
    """Test restoring a state with over due expire timer."""

    freezer.move_to("2022-02-02 12:02:00+01:00")
    domain = sensor.DOMAIN
    config3 = copy.deepcopy(DEFAULT_CONFIG[domain])
    config3["name"] = "test3"
    config3["expire_after"] = 10
    config3["state_topic"] = "test-topic3"
    fake_state = ha.State(
        "sensor.test3",
        "300",
        {},
        last_changed=datetime.fromisoformat("2022-02-02 12:01:35+01:00"),
    )
    with patch(
            "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state",
            return_value=fake_state,
    ), assert_setup_component(1, domain):
        assert await async_setup_component(hass, domain, {domain: config3})
        await hass.async_block_till_done()
    assert "Skip state recovery after reload for sensor.test3" in caplog.text
    def test_event_listener_defaults(self, mock_client):
        """Test event listener."""
        config = {
            'statsd': {
                'host': 'host',
            }
        }

        config['statsd'][statsd.CONF_RATE] = statsd.DEFAULT_RATE

        hass = mock.MagicMock()
        hass.pool.worker_count = 2
        setup_component(hass, statsd.DOMAIN, config)
        self.assertTrue(hass.bus.listen.called)
        handler_method = hass.bus.listen.call_args_list[0][0][1]

        valid = {'1': 1, '1.0': 1.0, STATE_ON: 1, STATE_OFF: 0}
        for in_, out in valid.items():
            state = mock.MagicMock(state=in_,
                                   attributes={"attribute key": 3.2})
            handler_method(mock.MagicMock(data={'new_state': state}))
            mock_client.return_value.gauge.assert_has_calls([
                mock.call(state.entity_id, out, statsd.DEFAULT_RATE),
            ])

            mock_client.return_value.gauge.reset_mock()

            mock_client.return_value.incr.assert_called_once_with(
                state.entity_id, rate=statsd.DEFAULT_RATE)
            mock_client.return_value.incr.reset_mock()

        for invalid in ('foo', '', object):
            handler_method(
                mock.MagicMock(
                    data={'new_state': ha.State('domain.test', invalid, {})}))
            self.assertFalse(mock_client.return_value.gauge.called)
            self.assertFalse(mock_client.return_value.incr.called)
Beispiel #30
0
async def test_run_select_service_optimistic(hass, mqtt_mock_entry_with_yaml_config):
    """Test that set_value service works in optimistic mode."""
    topic = "test/select"

    fake_state = ha.State("select.test_select", "milk")
    mock_restore_cache(hass, (fake_state,))

    assert await async_setup_component(
        hass,
        select.DOMAIN,
        {
            "select": {
                "platform": "mqtt",
                "command_topic": topic,
                "name": "Test Select",
                "options": ["milk", "beer"],
            }
        },
    )
    await hass.async_block_till_done()
    mqtt_mock = await mqtt_mock_entry_with_yaml_config()

    state = hass.states.get("select.test_select")
    assert state.state == "milk"
    assert state.attributes.get(ATTR_ASSUMED_STATE)

    await hass.services.async_call(
        SELECT_DOMAIN,
        SERVICE_SELECT_OPTION,
        {ATTR_ENTITY_ID: "select.test_select", ATTR_OPTION: "beer"},
        blocking=True,
    )

    mqtt_mock.async_publish.assert_called_once_with(topic, "beer", 0, False)
    mqtt_mock.async_publish.reset_mock()
    state = hass.states.get("select.test_select")
    assert state.state == "beer"