'Test event listener.'

@MockDependency('datadog')
def test_state_changed(self, mock_datadog):

    self.hass.bus.listen = mock.MagicMock()
    mock_client = mock_datadog.statsd
    assert setup_component(self.hass, datadog.DOMAIN, {datadog.DOMAIN: {'host': 'host', 'prefix': 'ha', 'rate': datadog.DEFAULT_RATE}})
    self.assertTrue(self.hass.bus.listen.called)
    handler_method = self.hass.bus.listen.call_args_list[1][0][1]
    valid = {'1': 1, '1.0': 1.0, STATE_ON: 1, STATE_OFF: 0}
    attributes = {'elevation': 3.2, 'temperature': 5.0}
    for (in_, out) in valid.items():
        state = mock.MagicMock(domain='sensor', entity_id='sensor.foo.bar', state=in_, attributes=attributes)
        handler_method(mock.MagicMock(data={'new_state': state}))
        self.assertEqual(mock_client.gauge.call_count, 3)
        for (attribute, value) in attributes.items():
            mock_client.gauge.assert_has_calls([mock.call('ha.sensor.{}'.format(attribute), value, sample_rate=1, tags=['entity:{}'.format(state.entity_id)])])
        self.assertEqual(mock_client.gauge.call_args, mock.call('ha.sensor', out, sample_rate=1, tags=['entity:{}'.format(state.entity_id)]))
        mock_client.gauge.reset_mock()
    for invalid in ('foo', '', object):
        handler_method(mock.MagicMock(data={'new_state': ha.State('domain.test', invalid, {})}))
        self.assertFalse(mock_client.gauge.called)
