Move MQTT platforms under the component (#20050)

* Move MQTT platforms under the component
This commit is contained in:
emontnemery authored and GitHub committed 2019-01-15 17:31:06 +01:00
1 parent 5fd1053a38
commit 5b53bd6aa0
27 files changed
+6 -5

No files matched your search

@@ -0,0 +1,449 @@
"""The tests the MQTT alarm control panel component."""
import json
import unittest
from unittest.mock import ANY
from homeassistant.setup import setup_component
from homeassistant.const import (
STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY,
STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED, STATE_UNAVAILABLE,
STATE_UNKNOWN)
from homeassistant.components import alarm_control_panel, mqtt
from homeassistant.components.mqtt.discovery import async_start
from tests.common import (
assert_setup_component, async_fire_mqtt_message, async_mock_mqtt_component,
async_setup_component, fire_mqtt_message, get_test_home_assistant,
mock_mqtt_component, MockConfigEntry, mock_registry)
from tests.components.alarm_control_panel import common
CODE = 'HELLO_CODE'
class TestAlarmControlPanelMQTT(unittest.TestCase):
"""Test the manual alarm module."""
# pylint: disable=invalid-name
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
def tearDown(self): # pylint: disable=invalid-name
"""Stop down stuff we started."""
self.hass.stop()
def test_fail_setup_without_state_topic(self):
"""Test for failing with no state topic."""
with assert_setup_component(0) as config:
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'command_topic': 'alarm/command'
}
})
assert not config[alarm_control_panel.DOMAIN]
def test_fail_setup_without_command_topic(self):
"""Test failing with no command topic."""
with assert_setup_component(0):
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'state_topic': 'alarm/state'
}
})
def test_update_state_via_state_topic(self):
"""Test updating with via state topic."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
}
})
entity_id = 'alarm_control_panel.test'
assert STATE_UNKNOWN == \
self.hass.states.get(entity_id).state
for state in (STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME,
STATE_ALARM_ARMED_AWAY, STATE_ALARM_PENDING,
STATE_ALARM_TRIGGERED):
fire_mqtt_message(self.hass, 'alarm/state', state)
self.hass.block_till_done()
assert state == self.hass.states.get(entity_id).state
def test_ignore_update_state_if_unknown_via_state_topic(self):
"""Test ignoring updates via state topic."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
}
})
entity_id = 'alarm_control_panel.test'
assert STATE_UNKNOWN == \
self.hass.states.get(entity_id).state
fire_mqtt_message(self.hass, 'alarm/state', 'unsupported state')
self.hass.block_till_done()
assert STATE_UNKNOWN == self.hass.states.get(entity_id).state
def test_arm_home_publishes_mqtt(self):
"""Test publishing of MQTT messages while armed."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
}
})
common.alarm_arm_home(self.hass)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'alarm/command', 'ARM_HOME', 0, False)
def test_arm_home_not_publishes_mqtt_with_invalid_code(self):
"""Test not publishing of MQTT messages with invalid code."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
'code': '1234'
}
})
call_count = self.mock_publish.call_count
common.alarm_arm_home(self.hass, 'abcd')
self.hass.block_till_done()
assert call_count == self.mock_publish.call_count
def test_arm_away_publishes_mqtt(self):
"""Test publishing of MQTT messages while armed."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
}
})
common.alarm_arm_away(self.hass)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'alarm/command', 'ARM_AWAY', 0, False)
def test_arm_away_not_publishes_mqtt_with_invalid_code(self):
"""Test not publishing of MQTT messages with invalid code."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
'code': '1234'
}
})
call_count = self.mock_publish.call_count
common.alarm_arm_away(self.hass, 'abcd')
self.hass.block_till_done()
assert call_count == self.mock_publish.call_count
def test_disarm_publishes_mqtt(self):
"""Test publishing of MQTT messages while disarmed."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
}
})
common.alarm_disarm(self.hass)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'alarm/command', 'DISARM', 0, False)
def test_disarm_not_publishes_mqtt_with_invalid_code(self):
"""Test not publishing of MQTT messages with invalid code."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
'code': '1234'
}
})
call_count = self.mock_publish.call_count
common.alarm_disarm(self.hass, 'abcd')
self.hass.block_till_done()
assert call_count == self.mock_publish.call_count
def test_default_availability_payload(self):
"""Test availability by default payload with defined topic."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
'code': '1234',
'availability_topic': 'availability-topic'
}
})
state = self.hass.states.get('alarm_control_panel.test')
assert STATE_UNAVAILABLE == state.state
fire_mqtt_message(self.hass, 'availability-topic', 'online')
self.hass.block_till_done()
state = self.hass.states.get('alarm_control_panel.test')
assert STATE_UNAVAILABLE != state.state
fire_mqtt_message(self.hass, 'availability-topic', 'offline')
self.hass.block_till_done()
state = self.hass.states.get('alarm_control_panel.test')
assert STATE_UNAVAILABLE == state.state
def test_custom_availability_payload(self):
"""Test availability by custom payload with defined topic."""
assert setup_component(self.hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'alarm/state',
'command_topic': 'alarm/command',
'code': '1234',
'availability_topic': 'availability-topic',
'payload_available': 'good',
'payload_not_available': 'nogood'
}
})
state = self.hass.states.get('alarm_control_panel.test')
assert STATE_UNAVAILABLE == state.state
fire_mqtt_message(self.hass, 'availability-topic', 'good')
async def test_unique_id(hass):
"""Test unique id option only creates one alarm per unique_id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'command_topic': 'test_topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'state_topic': 'test-topic',
'command_topic': 'test_topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(alarm_control_panel.DOMAIN)) == 1
async def test_discovery_removal_alarm(hass, mqtt_mock, caplog):
"""Test removal of discovered alarm_control_panel."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data = (
'{ "name": "Beer",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass,
'homeassistant/alarm_control_panel/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('alarm_control_panel.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass,
'homeassistant/alarm_control_panel/bla/config',
'')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('alarm_control_panel.beer')
assert state is None
async def test_discovery_update_alarm(hass, mqtt_mock, caplog):
"""Test update of discovered alarm_control_panel."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
data2 = (
'{ "name": "Milk",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass,
'homeassistant/alarm_control_panel/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('alarm_control_panel.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass,
'homeassistant/alarm_control_panel/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('alarm_control_panel.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('alarm_control_panel.milk')
assert state is None
async def test_discovery_broken(hass, mqtt_mock, caplog):
"""Test handling of bad discovery message."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer" }'
)
data2 = (
'{ "name": "Milk",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass,
'homeassistant/alarm_control_panel/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('alarm_control_panel.beer')
assert state is None
async_fire_mqtt_message(hass,
'homeassistant/alarm_control_panel/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('alarm_control_panel.milk')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('alarm_control_panel.beer')
assert state is None
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT alarm control panel device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'command_topic': 'test-topic',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(
hass, 'homeassistant/alarm_control_panel/bla/config', data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, alarm_control_panel.DOMAIN, {
alarm_control_panel.DOMAIN: [{
'platform': 'mqtt',
'name': 'beer',
'state_topic': 'test-topic',
'command_topic': 'command-topic',
'availability_topic': 'avty-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
state = hass.states.get('alarm_control_panel.beer')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.reset_mock()
registry.async_update_entity(
'alarm_control_panel.beer', new_entity_id='alarm_control_panel.milk')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('alarm_control_panel.beer')
assert state is None
state = hass.states.get('alarm_control_panel.milk')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
+528
View File
@@ -0,0 +1,528 @@
"""The tests for the MQTT binary sensor platform."""
import json
import unittest
from unittest.mock import ANY, Mock, patch
from datetime import timedelta
import homeassistant.core as ha
from homeassistant.setup import setup_component, async_setup_component
from homeassistant.components import binary_sensor, mqtt
from homeassistant.components.mqtt.discovery import async_start
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.const import EVENT_STATE_CHANGED, STATE_UNAVAILABLE
import homeassistant.util.dt as dt_util
from tests.common import (
get_test_home_assistant, fire_mqtt_message, async_fire_mqtt_message,
fire_time_changed, mock_component, mock_mqtt_component, mock_registry,
async_mock_mqtt_component, MockConfigEntry)
class TestSensorMQTT(unittest.TestCase):
"""Test the MQTT sensor."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config_entries._async_schedule_save = Mock()
mock_mqtt_component(self.hass)
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
def test_setting_sensor_value_via_mqtt_message(self):
"""Test the setting of the value via 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',
}
})
state = self.hass.states.get('binary_sensor.test')
assert STATE_OFF == state.state
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
fire_mqtt_message(self.hass, 'test-topic', 'OFF')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert STATE_OFF == state.state
def test_setting_sensor_value_via_mqtt_message_and_template(self):
"""Test the setting of the value via 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',
'value_template': '{%if is_state(entity_id,\"on\")-%}OFF'
'{%-else-%}ON{%-endif%}'
}
})
state = self.hass.states.get('binary_sensor.test')
assert STATE_OFF == state.state
fire_mqtt_message(self.hass, 'test-topic', '')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert STATE_ON == state.state
fire_mqtt_message(self.hass, 'test-topic', '')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert STATE_OFF == state.state
def test_valid_device_class(self):
"""Test the setting of a valid sensor class."""
assert setup_component(self.hass, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'device_class': 'motion',
'state_topic': 'test-topic',
}
})
state = self.hass.states.get('binary_sensor.test')
assert 'motion' == state.attributes.get('device_class')
def test_invalid_device_class(self):
"""Test the setting of an invalid sensor class."""
assert setup_component(self.hass, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'device_class': 'abc123',
'state_topic': 'test-topic',
}
})
state = self.hass.states.get('binary_sensor.test')
assert state is None
def test_availability_without_topic(self):
"""Test availability without defined availability topic."""
assert setup_component(self.hass, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
}
})
state = self.hass.states.get('binary_sensor.test')
assert STATE_UNAVAILABLE != state.state
def test_availability_by_defaults(self):
"""Test availability by defaults with defined topic."""
assert setup_component(self.hass, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'availability_topic': 'availability-topic'
}
})
state = self.hass.states.get('binary_sensor.test')
assert STATE_UNAVAILABLE == state.state
fire_mqtt_message(self.hass, 'availability-topic', 'online')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert STATE_UNAVAILABLE != state.state
fire_mqtt_message(self.hass, 'availability-topic', 'offline')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert STATE_UNAVAILABLE == state.state
def test_availability_by_custom_payload(self):
"""Test availability by custom payload with defined topic."""
assert setup_component(self.hass, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'availability_topic': 'availability-topic',
'payload_available': 'good',
'payload_not_available': 'nogood'
}
})
state = self.hass.states.get('binary_sensor.test')
assert STATE_UNAVAILABLE == state.state
fire_mqtt_message(self.hass, 'availability-topic', 'good')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert STATE_UNAVAILABLE != state.state
fire_mqtt_message(self.hass, 'availability-topic', 'nogood')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert STATE_UNAVAILABLE == state.state
def test_force_update_disabled(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'
}
})
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()
assert 1 == len(events)
fire_mqtt_message(self.hass, 'test-topic', 'ON')
self.hass.block_till_done()
assert 1 == len(events)
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()
assert 1 == len(events)
fire_mqtt_message(self.hass, 'test-topic', 'ON')
self.hass.block_till_done()
assert 2 == len(events)
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)
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, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test-topic',
'json_attributes_topic': 'attr-topic'
}
})
fire_mqtt_message(self.hass, 'attr-topic', '{ "val": "100" }')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert '100' == \
state.attributes.get('val')
@patch('homeassistant.components.mqtt._LOGGER')
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, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test-topic',
'json_attributes_topic': 'attr-topic'
}
})
fire_mqtt_message(self.hass, 'attr-topic', '[ "list", "of", "things"]')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert state.attributes.get('val') is None
mock_logger.warning.assert_called_with(
'JSON result was not a dictionary')
@patch('homeassistant.components.mqtt._LOGGER')
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, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test-topic',
'json_attributes_topic': 'attr-topic'
}
})
fire_mqtt_message(self.hass, 'attr-topic', 'This is not JSON')
self.hass.block_till_done()
state = self.hass.states.get('binary_sensor.test')
assert state.attributes.get('val') is None
mock_logger.warning.assert_called_with(
'Erroneous JSON: %s', 'This is not JSON')
async def test_unique_id(hass):
"""Test unique id option only creates one sensor per unique_id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'state_topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 1
async def test_discovery_removal_binary_sensor(hass, mqtt_mock, caplog):
"""Test removal of discovered binary_sensor."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data = (
'{ "name": "Beer",'
' "state_topic": "test_topic",'
' "availability_topic": "availability_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/binary_sensor/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/binary_sensor/bla/config',
'')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.beer')
assert state is None
async def test_discovery_update_binary_sensor(hass, mqtt_mock, caplog):
"""Test update of discovered binary_sensor."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "state_topic": "test_topic",'
' "availability_topic": "availability_topic1" }'
)
data2 = (
'{ "name": "Milk",'
' "state_topic": "test_topic2",'
' "availability_topic": "availability_topic2" }'
)
async_fire_mqtt_message(hass, 'homeassistant/binary_sensor/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/binary_sensor/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('binary_sensor.milk')
assert state is None
async def test_discovery_broken(hass, mqtt_mock, caplog):
"""Test handling of bad discovery message."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "off_delay": -1 }'
)
data2 = (
'{ "name": "Milk",'
' "state_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/binary_sensor/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.beer')
assert state is None
async_fire_mqtt_message(hass, 'homeassistant/binary_sensor/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.milk')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('binary_sensor.beer')
assert state is None
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT binary sensor device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/binary_sensor/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, binary_sensor.DOMAIN, {
binary_sensor.DOMAIN: [{
'platform': 'mqtt',
'name': 'beer',
'state_topic': 'test-topic',
'availability_topic': 'avty-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
state = hass.states.get('binary_sensor.beer')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.reset_mock()
registry.async_update_entity(
'binary_sensor.beer', new_entity_id='binary_sensor.milk')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('binary_sensor.beer')
assert state is None
state = hass.states.get('binary_sensor.milk')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
+54
View File
@@ -0,0 +1,54 @@
"""The tests for mqtt camera component."""
import asyncio
from homeassistant.setup import async_setup_component
from tests.common import (
async_mock_mqtt_component, async_fire_mqtt_message)
@asyncio.coroutine
def test_run_camera_setup(hass, aiohttp_client):
"""Test that it fetches the given payload."""
topic = 'test/camera'
yield from async_mock_mqtt_component(hass)
yield from async_setup_component(hass, 'camera', {
'camera': {
'platform': 'mqtt',
'topic': topic,
'name': 'Test Camera',
}})
url = hass.states.get('camera.test_camera').attributes['entity_picture']
async_fire_mqtt_message(hass, topic, 'beer')
yield from hass.async_block_till_done()
client = yield from aiohttp_client(hass.http.app)
resp = yield from client.get(url)
assert resp.status == 200
body = yield from resp.text()
assert body == 'beer'
@asyncio.coroutine
def test_unique_id(hass):
"""Test unique id option only creates one camera per unique_id."""
yield from async_mock_mqtt_component(hass)
yield from async_setup_component(hass, 'camera', {
'camera': [{
'platform': 'mqtt',
'name': 'Test Camera 1',
'topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test Camera 2',
'topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
yield from hass.async_block_till_done()
assert len(hass.states.async_all()) == 1
+856
View File
@@ -0,0 +1,856 @@
"""The tests for the mqtt climate component."""
import copy
import json
import unittest
from unittest.mock import ANY
import pytest
import voluptuous as vol
from homeassistant.util.unit_system import (
METRIC_SYSTEM
)
from homeassistant.setup import setup_component
from homeassistant.components import climate, mqtt
from homeassistant.const import STATE_OFF, STATE_UNAVAILABLE
from homeassistant.components.climate import (
SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE,
SUPPORT_FAN_MODE, SUPPORT_SWING_MODE, SUPPORT_HOLD_MODE,
SUPPORT_AWAY_MODE, SUPPORT_AUX_HEAT, DEFAULT_MIN_TEMP, DEFAULT_MAX_TEMP)
from homeassistant.components.mqtt.discovery import async_start
from tests.common import (
async_fire_mqtt_message, async_mock_mqtt_component, async_setup_component,
fire_mqtt_message, get_test_home_assistant, mock_component,
mock_mqtt_component, MockConfigEntry, mock_registry)
from tests.components.climate import common
ENTITY_CLIMATE = 'climate.test'
DEFAULT_CONFIG = {
'climate': {
'platform': 'mqtt',
'name': 'test',
'mode_command_topic': 'mode-topic',
'temperature_command_topic': 'temperature-topic',
'fan_mode_command_topic': 'fan-mode-topic',
'swing_mode_command_topic': 'swing-mode-topic',
'away_mode_command_topic': 'away-mode-topic',
'hold_command_topic': 'hold-topic',
'aux_command_topic': 'aux-topic'
}}
class TestMQTTClimate(unittest.TestCase):
"""Test the mqtt climate hvac."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_publish = mock_mqtt_component(self.hass)
self.hass.config.units = METRIC_SYSTEM
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_setup_params(self):
"""Test the initial parameters."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 21 == state.attributes.get('temperature')
assert "low" == state.attributes.get('fan_mode')
assert "off" == state.attributes.get('swing_mode')
assert "off" == state.attributes.get('operation_mode')
assert DEFAULT_MIN_TEMP == state.attributes.get('min_temp')
assert DEFAULT_MAX_TEMP == state.attributes.get('max_temp')
def test_supported_features(self):
"""Test the supported_features."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
support = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE |
SUPPORT_SWING_MODE | SUPPORT_FAN_MODE | SUPPORT_AWAY_MODE |
SUPPORT_HOLD_MODE | SUPPORT_AUX_HEAT)
assert state.attributes.get("supported_features") == support
def test_get_operation_modes(self):
"""Test that the operation list returns the correct modes."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
modes = state.attributes.get('operation_list')
assert [
climate.STATE_AUTO, STATE_OFF, climate.STATE_COOL,
climate.STATE_HEAT, climate.STATE_DRY, climate.STATE_FAN_ONLY
] == modes
def test_set_operation_bad_attr_and_state(self):
"""Test setting operation mode without required attribute.
Also check the state.
"""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert "off" == state.attributes.get('operation_mode')
assert "off" == state.state
with pytest.raises(vol.Invalid):
common.set_operation_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "off" == state.attributes.get('operation_mode')
assert "off" == state.state
def test_set_operation(self):
"""Test setting of new operation mode."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert "off" == state.attributes.get('operation_mode')
assert "off" == state.state
common.set_operation_mode(self.hass, "cool", ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "cool" == state.attributes.get('operation_mode')
assert "cool" == state.state
self.mock_publish.async_publish.assert_called_once_with(
'mode-topic', 'cool', 0, False)
def test_set_operation_pessimistic(self):
"""Test setting operation mode in pessimistic mode."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['mode_state_topic'] = 'mode-state'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('operation_mode') is None
assert "unknown" == state.state
common.set_operation_mode(self.hass, "cool", ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('operation_mode') is None
assert "unknown" == state.state
fire_mqtt_message(self.hass, 'mode-state', 'cool')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "cool" == state.attributes.get('operation_mode')
assert "cool" == state.state
fire_mqtt_message(self.hass, 'mode-state', 'bogus mode')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "cool" == state.attributes.get('operation_mode')
assert "cool" == state.state
def test_set_operation_with_power_command(self):
"""Test setting of new operation mode with power command enabled."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['power_command_topic'] = 'power-command'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
assert "off" == state.attributes.get('operation_mode')
assert "off" == state.state
common.set_operation_mode(self.hass, "on", ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "on" == state.attributes.get('operation_mode')
assert "on" == state.state
self.mock_publish.async_publish.assert_has_calls([
unittest.mock.call('power-command', 'ON', 0, False),
unittest.mock.call('mode-topic', 'on', 0, False)
])
self.mock_publish.async_publish.reset_mock()
common.set_operation_mode(self.hass, "off", ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "off" == state.attributes.get('operation_mode')
assert "off" == state.state
self.mock_publish.async_publish.assert_has_calls([
unittest.mock.call('power-command', 'OFF', 0, False),
unittest.mock.call('mode-topic', 'off', 0, False)
])
self.mock_publish.async_publish.reset_mock()
def test_set_fan_mode_bad_attr(self):
"""Test setting fan mode without required attribute."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert "low" == state.attributes.get('fan_mode')
with pytest.raises(vol.Invalid):
common.set_fan_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "low" == state.attributes.get('fan_mode')
def test_set_fan_mode_pessimistic(self):
"""Test setting of new fan mode in pessimistic mode."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['fan_mode_state_topic'] = 'fan-state'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('fan_mode') is None
common.set_fan_mode(self.hass, 'high', ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('fan_mode') is None
fire_mqtt_message(self.hass, 'fan-state', 'high')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'high' == state.attributes.get('fan_mode')
fire_mqtt_message(self.hass, 'fan-state', 'bogus mode')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'high' == state.attributes.get('fan_mode')
def test_set_fan_mode(self):
"""Test setting of new fan mode."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert "low" == state.attributes.get('fan_mode')
common.set_fan_mode(self.hass, 'high', ENTITY_CLIMATE)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'fan-mode-topic', 'high', 0, False)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'high' == state.attributes.get('fan_mode')
def test_set_swing_mode_bad_attr(self):
"""Test setting swing mode without required attribute."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert "off" == state.attributes.get('swing_mode')
with pytest.raises(vol.Invalid):
common.set_swing_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "off" == state.attributes.get('swing_mode')
def test_set_swing_pessimistic(self):
"""Test setting swing mode in pessimistic mode."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['swing_mode_state_topic'] = 'swing-state'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('swing_mode') is None
common.set_swing_mode(self.hass, 'on', ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('swing_mode') is None
fire_mqtt_message(self.hass, 'swing-state', 'on')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "on" == state.attributes.get('swing_mode')
fire_mqtt_message(self.hass, 'swing-state', 'bogus state')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "on" == state.attributes.get('swing_mode')
def test_set_swing(self):
"""Test setting of new swing mode."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert "off" == state.attributes.get('swing_mode')
common.set_swing_mode(self.hass, 'on', ENTITY_CLIMATE)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'swing-mode-topic', 'on', 0, False)
state = self.hass.states.get(ENTITY_CLIMATE)
assert "on" == state.attributes.get('swing_mode')
def test_set_target_temperature(self):
"""Test setting the target temperature."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 21 == state.attributes.get('temperature')
common.set_operation_mode(self.hass, 'heat', ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'heat' == state.attributes.get('operation_mode')
self.mock_publish.async_publish.assert_called_once_with(
'mode-topic', 'heat', 0, False)
self.mock_publish.async_publish.reset_mock()
common.set_temperature(self.hass, temperature=47,
entity_id=ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 47 == state.attributes.get('temperature')
self.mock_publish.async_publish.assert_called_once_with(
'temperature-topic', 47, 0, False)
# also test directly supplying the operation mode to set_temperature
self.mock_publish.async_publish.reset_mock()
common.set_temperature(self.hass, temperature=21,
operation_mode="cool",
entity_id=ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'cool' == state.attributes.get('operation_mode')
assert 21 == state.attributes.get('temperature')
self.mock_publish.async_publish.assert_has_calls([
unittest.mock.call('mode-topic', 'cool', 0, False),
unittest.mock.call('temperature-topic', 21, 0, False)
])
self.mock_publish.async_publish.reset_mock()
def test_set_target_temperature_pessimistic(self):
"""Test setting the target temperature."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['temperature_state_topic'] = 'temperature-state'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('temperature') is None
common.set_operation_mode(self.hass, 'heat', ENTITY_CLIMATE)
self.hass.block_till_done()
common.set_temperature(self.hass, temperature=47,
entity_id=ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('temperature') is None
fire_mqtt_message(self.hass, 'temperature-state', '1701')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 1701 == state.attributes.get('temperature')
fire_mqtt_message(self.hass, 'temperature-state', 'not a number')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 1701 == state.attributes.get('temperature')
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 test_set_away_mode_pessimistic(self):
"""Test setting of the away mode."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['away_mode_state_topic'] = 'away-state'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('away_mode')
common.set_away_mode(self.hass, True, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('away_mode')
fire_mqtt_message(self.hass, 'away-state', 'ON')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'on' == state.attributes.get('away_mode')
fire_mqtt_message(self.hass, 'away-state', 'OFF')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('away_mode')
fire_mqtt_message(self.hass, 'away-state', 'nonsense')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('away_mode')
def test_set_away_mode(self):
"""Test setting of the away mode."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['payload_on'] = 'AN'
config['climate']['payload_off'] = 'AUS'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('away_mode')
common.set_away_mode(self.hass, True, ENTITY_CLIMATE)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'away-mode-topic', 'AN', 0, False)
self.mock_publish.async_publish.reset_mock()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'on' == state.attributes.get('away_mode')
common.set_away_mode(self.hass, False, ENTITY_CLIMATE)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'away-mode-topic', 'AUS', 0, False)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('away_mode')
def test_set_hold_pessimistic(self):
"""Test setting the hold mode in pessimistic mode."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['hold_state_topic'] = 'hold-state'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('hold_mode') is None
common.set_hold_mode(self.hass, 'on', ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('hold_mode') is None
fire_mqtt_message(self.hass, 'hold-state', 'on')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'on' == state.attributes.get('hold_mode')
fire_mqtt_message(self.hass, 'hold-state', 'off')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('hold_mode')
def test_set_hold(self):
"""Test setting the hold mode."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('hold_mode') is None
common.set_hold_mode(self.hass, 'on', ENTITY_CLIMATE)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'hold-topic', 'on', 0, False)
self.mock_publish.async_publish.reset_mock()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'on' == state.attributes.get('hold_mode')
common.set_hold_mode(self.hass, 'off', ENTITY_CLIMATE)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'hold-topic', 'off', 0, False)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('hold_mode')
def test_set_aux_pessimistic(self):
"""Test setting of the aux heating in pessimistic mode."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['aux_state_topic'] = 'aux-state'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('aux_heat')
common.set_aux_heat(self.hass, True, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('aux_heat')
fire_mqtt_message(self.hass, 'aux-state', 'ON')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'on' == state.attributes.get('aux_heat')
fire_mqtt_message(self.hass, 'aux-state', 'OFF')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('aux_heat')
fire_mqtt_message(self.hass, 'aux-state', 'nonsense')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('aux_heat')
def test_set_aux(self):
"""Test setting of the aux heating."""
assert setup_component(self.hass, climate.DOMAIN, DEFAULT_CONFIG)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('aux_heat')
common.set_aux_heat(self.hass, True, ENTITY_CLIMATE)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'aux-topic', 'ON', 0, False)
self.mock_publish.async_publish.reset_mock()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'on' == state.attributes.get('aux_heat')
common.set_aux_heat(self.hass, False, ENTITY_CLIMATE)
self.hass.block_till_done()
self.mock_publish.async_publish.assert_called_once_with(
'aux-topic', 'OFF', 0, False)
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('aux_heat')
def test_custom_availability_payload(self):
"""Test availability by custom payload with defined topic."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['availability_topic'] = 'availability-topic'
config['climate']['payload_available'] = 'good'
config['climate']['payload_not_available'] = 'nogood'
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get('climate.test')
assert STATE_UNAVAILABLE == state.state
fire_mqtt_message(self.hass, 'availability-topic', 'good')
self.hass.block_till_done()
state = self.hass.states.get('climate.test')
assert STATE_UNAVAILABLE != state.state
fire_mqtt_message(self.hass, 'availability-topic', 'nogood')
self.hass.block_till_done()
state = self.hass.states.get('climate.test')
assert STATE_UNAVAILABLE == state.state
def test_set_with_templates(self):
"""Test setting of new fan mode in pessimistic mode."""
config = copy.deepcopy(DEFAULT_CONFIG)
# By default, just unquote the JSON-strings
config['climate']['value_template'] = '{{ value_json }}'
# Something more complicated for hold mode
config['climate']['hold_state_template'] = \
'{{ value_json.attribute }}'
# Rendering to a bool for aux heat
config['climate']['aux_state_template'] = \
"{{ value == 'switchmeon' }}"
config['climate']['mode_state_topic'] = 'mode-state'
config['climate']['fan_mode_state_topic'] = 'fan-state'
config['climate']['swing_mode_state_topic'] = 'swing-state'
config['climate']['temperature_state_topic'] = 'temperature-state'
config['climate']['away_mode_state_topic'] = 'away-state'
config['climate']['hold_state_topic'] = 'hold-state'
config['climate']['aux_state_topic'] = 'aux-state'
config['climate']['current_temperature_topic'] = 'current-temperature'
assert setup_component(self.hass, climate.DOMAIN, config)
# Operation Mode
state = self.hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get('operation_mode') is None
fire_mqtt_message(self.hass, 'mode-state', '"cool"')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "cool" == state.attributes.get('operation_mode')
# Fan Mode
assert state.attributes.get('fan_mode') is None
fire_mqtt_message(self.hass, 'fan-state', '"high"')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'high' == state.attributes.get('fan_mode')
# Swing Mode
assert state.attributes.get('swing_mode') is None
fire_mqtt_message(self.hass, 'swing-state', '"on"')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert "on" == state.attributes.get('swing_mode')
# Temperature - with valid value
assert state.attributes.get('temperature') is None
fire_mqtt_message(self.hass, 'temperature-state', '"1031"')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 1031 == state.attributes.get('temperature')
# Temperature - with invalid value
with self.assertLogs(level='ERROR') as log:
fire_mqtt_message(self.hass, 'temperature-state', '"-INVALID-"')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
# make sure, the invalid value gets logged...
assert len(log.output) == 1
assert len(log.records) == 1
assert "Could not parse temperature from -INVALID-" in \
log.output[0]
# ... but the actual value stays unchanged.
assert 1031 == state.attributes.get('temperature')
# Away Mode
assert 'off' == state.attributes.get('away_mode')
fire_mqtt_message(self.hass, 'away-state', '"ON"')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'on' == state.attributes.get('away_mode')
# Away Mode with JSON values
fire_mqtt_message(self.hass, 'away-state', 'false')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('away_mode')
fire_mqtt_message(self.hass, 'away-state', 'true')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'on' == state.attributes.get('away_mode')
# Hold Mode
assert state.attributes.get('hold_mode') is None
fire_mqtt_message(self.hass, 'hold-state', """
{ "attribute": "somemode" }
""")
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'somemode' == state.attributes.get('hold_mode')
# Aux mode
assert 'off' == state.attributes.get('aux_heat')
fire_mqtt_message(self.hass, 'aux-state', 'switchmeon')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'on' == state.attributes.get('aux_heat')
# anything other than 'switchmeon' should turn Aux mode off
fire_mqtt_message(self.hass, 'aux-state', 'somerandomstring')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 'off' == state.attributes.get('aux_heat')
# Current temperature
fire_mqtt_message(self.hass, 'current-temperature', '"74656"')
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
assert 74656 == state.attributes.get('current_temperature')
def test_min_temp_custom(self):
"""Test a custom min temp."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['min_temp'] = 26
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
min_temp = state.attributes.get('min_temp')
assert isinstance(min_temp, float)
assert 26 == state.attributes.get('min_temp')
def test_max_temp_custom(self):
"""Test a custom max temp."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['max_temp'] = 60
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
max_temp = state.attributes.get('max_temp')
assert isinstance(max_temp, float)
assert 60 == max_temp
def test_temp_step_custom(self):
"""Test a custom temp step."""
config = copy.deepcopy(DEFAULT_CONFIG)
config['climate']['temp_step'] = 0.01
assert setup_component(self.hass, climate.DOMAIN, config)
state = self.hass.states.get(ENTITY_CLIMATE)
temp_step = state.attributes.get('target_temp_step')
assert isinstance(temp_step, float)
assert 0.01 == temp_step
async def test_unique_id(hass):
"""Test unique id option only creates one climate per unique_id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, climate.DOMAIN, {
climate.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'status_topic': 'test-topic',
'command_topic': 'test_topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'status_topic': 'test-topic',
'command_topic': 'test_topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(climate.DOMAIN)) == 1
async def test_discovery_removal_climate(hass, mqtt_mock, caplog):
"""Test removal of discovered climate."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data = (
'{ "name": "Beer" }'
)
async_fire_mqtt_message(hass, 'homeassistant/climate/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('climate.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/climate/bla/config',
'')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('climate.beer')
assert state is None
async def test_discovery_update_climate(hass, mqtt_mock, caplog):
"""Test update of discovered climate."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer" }'
)
data2 = (
'{ "name": "Milk" }'
)
async_fire_mqtt_message(hass, 'homeassistant/climate/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('climate.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/climate/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('climate.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('climate.milk')
assert state is None
async def test_discovery_broken(hass, mqtt_mock, caplog):
"""Test handling of bad discovery message."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "power_command_topic": "test_topic#" }'
)
data2 = (
'{ "name": "Milk", '
' "power_command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/climate/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('climate.beer')
assert state is None
async_fire_mqtt_message(hass, 'homeassistant/climate/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('climate.milk')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('climate.beer')
assert state is None
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT climate device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'command_topic': 'test-topic',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/climate/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, climate.DOMAIN, {
climate.DOMAIN: [{
'platform': 'mqtt',
'name': 'beer',
'mode_state_topic': 'test-topic',
'availability_topic': 'avty-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
state = hass.states.get('climate.beer')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.reset_mock()
registry.async_update_entity('climate.beer', new_entity_id='climate.milk')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('climate.beer')
assert state is None
state = hass.states.get('climate.milk')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
File diff suppressed because it is too large. Load diff
+295
View File
@@ -0,0 +1,295 @@
"""Test MQTT fans."""
import json
from unittest.mock import ANY
from homeassistant.setup import async_setup_component
from homeassistant.components import fan, mqtt
from homeassistant.components.mqtt.discovery import async_start
from homeassistant.const import ATTR_ASSUMED_STATE, STATE_UNAVAILABLE
from tests.common import async_fire_mqtt_message, MockConfigEntry, \
async_mock_mqtt_component, mock_registry
async def test_fail_setup_if_no_command_topic(hass, mqtt_mock):
"""Test if command fails with command topic."""
assert await async_setup_component(hass, fan.DOMAIN, {
fan.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
}
})
assert hass.states.get('fan.test') is None
async def test_default_availability_payload(hass, mqtt_mock):
"""Test the availability payload."""
assert await async_setup_component(hass, fan.DOMAIN, {
fan.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'availability_topic': 'availability_topic'
}
})
state = hass.states.get('fan.test')
assert state.state is STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'availability_topic', 'online')
await hass.async_block_till_done()
state = hass.states.get('fan.test')
assert state.state is not STATE_UNAVAILABLE
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, 'availability_topic', 'offline')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('fan.test')
assert state.state is STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'state-topic', '1')
await hass.async_block_till_done()
state = hass.states.get('fan.test')
assert state.state is STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'availability_topic', 'online')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('fan.test')
assert state.state is not STATE_UNAVAILABLE
async def test_custom_availability_payload(hass, mqtt_mock):
"""Test the availability payload."""
assert await async_setup_component(hass, fan.DOMAIN, {
fan.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'availability_topic': 'availability_topic',
'payload_available': 'good',
'payload_not_available': 'nogood'
}
})
state = hass.states.get('fan.test')
assert state.state is STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'availability_topic', 'good')
await hass.async_block_till_done()
state = hass.states.get('fan.test')
assert state.state is not STATE_UNAVAILABLE
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, 'availability_topic', 'nogood')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('fan.test')
assert state.state is STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'state-topic', '1')
await hass.async_block_till_done()
state = hass.states.get('fan.test')
assert state.state is STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'availability_topic', 'good')
await hass.async_block_till_done()
state = hass.states.get('fan.test')
assert state.state is not STATE_UNAVAILABLE
async def test_discovery_removal_fan(hass, mqtt_mock, caplog):
"""Test removal of discovered fan."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data = (
'{ "name": "Beer",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/fan/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('fan.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/fan/bla/config',
'')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('fan.beer')
assert state is None
async def test_discovery_update_fan(hass, mqtt_mock, caplog):
"""Test update of discovered fan."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "command_topic": "test_topic" }'
)
data2 = (
'{ "name": "Milk",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/fan/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('fan.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/fan/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('fan.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('fan.milk')
assert state is None
async def test_discovery_broken(hass, mqtt_mock, caplog):
"""Test handling of bad discovery message."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer" }'
)
data2 = (
'{ "name": "Milk",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/fan/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('fan.beer')
assert state is None
async_fire_mqtt_message(hass, 'homeassistant/fan/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('fan.milk')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('fan.beer')
assert state is None
async def test_unique_id(hass):
"""Test unique_id option only creates one fan per id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, fan.DOMAIN, {
fan.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'command_topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'state_topic': 'test-topic',
'command_topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(fan.DOMAIN)) == 1
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT fan device registry integration."""
entry = MockConfigEntry(domain='mqtt')
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'command_topic': 'test-command-topic',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/fan/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, fan.DOMAIN, {
fan.DOMAIN: [{
'platform': 'mqtt',
'name': 'beer',
'state_topic': 'test-topic',
'command_topic': 'command-topic',
'availability_topic': 'avty-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
state = hass.states.get('fan.beer')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.reset_mock()
registry.async_update_entity('fan.beer', new_entity_id='fan.milk')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('fan.beer')
assert state is None
state = hass.states.get('fan.milk')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
File diff suppressed because it is too large. Load diff
+716
View File
@@ -0,0 +1,716 @@
"""The tests for the MQTT JSON light platform.
Configuration with RGB, brightness, color temp, effect, white value and XY:
light:
platform: mqtt_json
name: mqtt_json_light_1
state_topic: "home/rgb1"
command_topic: "home/rgb1/set"
brightness: true
color_temp: true
effect: true
rgb: true
white_value: true
xy: true
Configuration with RGB, brightness, color temp, effect, white value:
light:
platform: mqtt_json
name: mqtt_json_light_1
state_topic: "home/rgb1"
command_topic: "home/rgb1/set"
brightness: true
color_temp: true
effect: true
rgb: true
white_value: true
Configuration with RGB, brightness, color temp and effect:
light:
platform: mqtt_json
name: mqtt_json_light_1
state_topic: "home/rgb1"
command_topic: "home/rgb1/set"
brightness: true
color_temp: true
effect: true
rgb: true
Configuration with RGB, brightness and color temp:
light:
platform: mqtt_json
name: mqtt_json_light_1
state_topic: "home/rgb1"
command_topic: "home/rgb1/set"
brightness: true
rgb: true
color_temp: true
Configuration with RGB, brightness:
light:
platform: mqtt_json
name: mqtt_json_light_1
state_topic: "home/rgb1"
command_topic: "home/rgb1/set"
brightness: true
rgb: true
Config without RGB:
light:
platform: mqtt_json
name: mqtt_json_light_1
state_topic: "home/rgb1"
command_topic: "home/rgb1/set"
brightness: true
Config without RGB and brightness:
light:
platform: mqtt_json
name: mqtt_json_light_1
state_topic: "home/rgb1"
command_topic: "home/rgb1/set"
Config with brightness and scale:
light:
platform: mqtt_json
name: test
state_topic: "mqtt_json_light_1"
command_topic: "mqtt_json_light_1/set"
brightness: true
brightness_scale: 99
"""
import json
from unittest.mock import ANY, patch
from homeassistant.setup import async_setup_component
from homeassistant.const import (
STATE_ON, STATE_OFF, STATE_UNAVAILABLE, ATTR_ASSUMED_STATE,
ATTR_SUPPORTED_FEATURES)
from homeassistant.components import light, mqtt
from homeassistant.components.mqtt.discovery import async_start
import homeassistant.core as ha
from tests.common import (
mock_coro, async_fire_mqtt_message, async_mock_mqtt_component,
MockConfigEntry, mock_registry)
async def test_fail_setup_if_no_command_topic(hass, mqtt_mock):
"""Test if setup fails with no command topic."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
}
})
assert hass.states.get('light.test') is None
async def test_no_color_brightness_color_temp_white_val_if_no_topics(
hass, mqtt_mock):
"""Test for no RGB, brightness, color temp, effect, white val or XY."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
'state_topic': 'test_light_rgb',
'command_topic': 'test_light_rgb/set',
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
assert 40 == state.attributes.get(ATTR_SUPPORTED_FEATURES)
assert state.attributes.get('rgb_color') is None
assert state.attributes.get('brightness') is None
assert state.attributes.get('color_temp') is None
assert state.attributes.get('effect') is None
assert state.attributes.get('white_value') is None
assert state.attributes.get('xy_color') is None
assert state.attributes.get('hs_color') is None
async_fire_mqtt_message(hass, 'test_light_rgb', '{"state":"ON"}')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert state.attributes.get('rgb_color') is None
assert state.attributes.get('brightness') is None
assert state.attributes.get('color_temp') is None
assert state.attributes.get('effect') is None
assert state.attributes.get('white_value') is None
assert state.attributes.get('xy_color') is None
assert state.attributes.get('hs_color') is None
async def test_controlling_state_via_topic(hass, mqtt_mock):
"""Test the controlling of the state via topic."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
'state_topic': 'test_light_rgb',
'command_topic': 'test_light_rgb/set',
'brightness': True,
'color_temp': True,
'effect': True,
'rgb': True,
'white_value': True,
'xy': True,
'hs': True,
'qos': '0'
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
assert 191 == state.attributes.get(ATTR_SUPPORTED_FEATURES)
assert state.attributes.get('rgb_color') is None
assert state.attributes.get('brightness') is None
assert state.attributes.get('color_temp') is None
assert state.attributes.get('effect') is None
assert state.attributes.get('white_value') is None
assert state.attributes.get('xy_color') is None
assert state.attributes.get('hs_color') is None
assert not state.attributes.get(ATTR_ASSUMED_STATE)
# Turn on the light, full white
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON",'
'"color":{"r":255,"g":255,"b":255},'
'"brightness":255,'
'"color_temp":155,'
'"effect":"colorloop",'
'"white_value":150}')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert (255, 255, 255) == state.attributes.get('rgb_color')
assert 255 == state.attributes.get('brightness')
assert 155 == state.attributes.get('color_temp')
assert 'colorloop' == state.attributes.get('effect')
assert 150 == state.attributes.get('white_value')
assert (0.323, 0.329) == state.attributes.get('xy_color')
assert (0.0, 0.0) == state.attributes.get('hs_color')
# Turn the light off
async_fire_mqtt_message(hass, 'test_light_rgb', '{"state":"OFF"}')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_OFF == state.state
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON", "brightness":100}')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert 100 == \
light_state.attributes['brightness']
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON", '
'"color":{"r":125,"g":125,"b":125}}')
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert (255, 255, 255) == \
light_state.attributes.get('rgb_color')
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON", "color":{"x":0.135,"y":0.135}}')
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert (0.141, 0.14) == \
light_state.attributes.get('xy_color')
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON", "color":{"h":180,"s":50}}')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert (180.0, 50.0) == \
light_state.attributes.get('hs_color')
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON", "color_temp":155}')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert 155 == light_state.attributes.get('color_temp')
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON", "effect":"colorloop"}')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert 'colorloop' == light_state.attributes.get('effect')
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON", "white_value":155}')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert 155 == light_state.attributes.get('white_value')
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)
async def test_sending_hs_color(hass, mqtt_mock):
"""Test light.turn_on with hs color sends hs color parameters."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
'command_topic': 'test_light_rgb/set',
'hs': True,
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
async def test_flash_short_and_long(hass, mqtt_mock):
"""Test for flash length being sent when included."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
'state_topic': 'test_light_rgb',
'command_topic': 'test_light_rgb/set',
'flash_time_short': 5,
'flash_time_long': 15,
'qos': 0
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
assert 40 == state.attributes.get(ATTR_SUPPORTED_FEATURES)
async def test_transition(hass, mqtt_mock):
"""Test for transition time being sent when included."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
'state_topic': 'test_light_rgb',
'command_topic': 'test_light_rgb/set',
'qos': 0
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
assert 40 == state.attributes.get(ATTR_SUPPORTED_FEATURES)
async def test_brightness_scale(hass, mqtt_mock):
"""Test for brightness scaling."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
'state_topic': 'test_light_bright_scale',
'command_topic': 'test_light_bright_scale/set',
'brightness': True,
'brightness_scale': 99
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
assert state.attributes.get('brightness') is None
assert not state.attributes.get(ATTR_ASSUMED_STATE)
# Turn on the light
async_fire_mqtt_message(hass, 'test_light_bright_scale', '{"state":"ON"}')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert 255 == state.attributes.get('brightness')
# Turn on the light with brightness
async_fire_mqtt_message(hass, 'test_light_bright_scale',
'{"state":"ON", "brightness": 99}')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert 255 == state.attributes.get('brightness')
async def test_invalid_color_brightness_and_white_values(hass, mqtt_mock):
"""Test that invalid color/brightness/white values are ignored."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
'state_topic': 'test_light_rgb',
'command_topic': 'test_light_rgb/set',
'brightness': True,
'rgb': True,
'white_value': True,
'qos': '0'
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
assert 185 == state.attributes.get(ATTR_SUPPORTED_FEATURES)
assert state.attributes.get('rgb_color') is None
assert state.attributes.get('brightness') is None
assert state.attributes.get('white_value') is None
assert not state.attributes.get(ATTR_ASSUMED_STATE)
# Turn on the light
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON",'
'"color":{"r":255,"g":255,"b":255},'
'"brightness": 255,'
'"white_value": 255}')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert (255, 255, 255) == state.attributes.get('rgb_color')
assert 255 == state.attributes.get('brightness')
assert 255 == state.attributes.get('white_value')
# Bad color values
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON",'
'"color":{"r":"bad","g":"val","b":"test"}}')
await hass.async_block_till_done()
# Color should not have changed
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert (255, 255, 255) == state.attributes.get('rgb_color')
# Bad brightness values
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON",'
'"brightness": "badValue"}')
await hass.async_block_till_done()
# Brightness should not have changed
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert 255 == state.attributes.get('brightness')
# Bad white value
async_fire_mqtt_message(hass, 'test_light_rgb',
'{"state":"ON",'
'"white_value": "badValue"}')
await hass.async_block_till_done()
# White value should not have changed
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert 255 == state.attributes.get('white_value')
async def test_default_availability_payload(hass, mqtt_mock):
"""Test availability by default payload with defined topic."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
'state_topic': 'test_light_rgb',
'command_topic': 'test_light_rgb/set',
'availability_topic': 'availability-topic'
}
})
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability-topic', 'online')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE != state.state
async_fire_mqtt_message(hass, 'availability-topic', 'offline')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE == state.state
async def test_custom_availability_payload(hass, mqtt_mock):
"""Test availability by custom payload with defined topic."""
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'json',
'name': 'test',
'state_topic': 'test_light_rgb',
'command_topic': 'test_light_rgb/set',
'availability_topic': 'availability-topic',
'payload_available': 'good',
'payload_not_available': 'nogood'
}
})
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability-topic', 'good')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE != state.state
async_fire_mqtt_message(hass, 'availability-topic', 'nogood')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE == state.state
async def test_unique_id(hass):
"""Test unique id option only creates one light per unique_id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'schema': 'json',
'status_topic': 'test-topic',
'command_topic': 'test_topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'schema': 'json',
'status_topic': 'test-topic',
'command_topic': 'test_topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(light.DOMAIN)) == 1
async def test_discovery_removal(hass, mqtt_mock, caplog):
"""Test removal of discovered mqtt_json lights."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {'mqtt': {}}, entry)
data = (
'{ "name": "Beer",'
' "schema": "json",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
'')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is None
async def test_discovery_deprecated(hass, mqtt_mock, caplog):
"""Test discovery of mqtt_json light with deprecated platform option."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {'mqtt': {}}, entry)
data = (
'{ "name": "Beer",'
' "platform": "mqtt_json",'
' "command_topic": "test_topic"}'
)
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is not None
assert state.name == 'Beer'
async def test_discovery_update_light(hass, mqtt_mock, caplog):
"""Test removal of discovered light."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "schema": "json",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
data2 = (
'{ "name": "Milk",'
' "schema": "json",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('light.milk')
assert state is None
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT light device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'schema': 'json',
'state_topic': 'test-topic',
'command_topic': 'test-topic',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: [{
'platform': 'mqtt',
'name': 'beer',
'schema': 'json',
'state_topic': 'test-topic',
'command_topic': 'command-topic',
'availability_topic': 'avty-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
state = hass.states.get('light.beer')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.reset_mock()
registry.async_update_entity('light.beer', new_entity_id='light.milk')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is None
state = hass.states.get('light.milk')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
@@ -0,0 +1,673 @@
"""The tests for the MQTT Template light platform.
Configuration example with all features:
light:
platform: mqtt_template
name: mqtt_template_light_1
state_topic: 'home/rgb1'
command_topic: 'home/rgb1/set'
command_on_template: >
on,{{ brightness|d }},{{ red|d }}-{{ green|d }}-{{ blue|d }}
command_off_template: 'off'
state_template: '{{ value.split(",")[0] }}'
brightness_template: '{{ value.split(",")[1] }}'
color_temp_template: '{{ value.split(",")[2] }}'
white_value_template: '{{ value.split(",")[3] }}'
red_template: '{{ value.split(",")[4].split("-")[0] }}'
green_template: '{{ value.split(",")[4].split("-")[1] }}'
blue_template: '{{ value.split(",")[4].split("-")[2] }}'
If your light doesn't support brightness feature, omit `brightness_template`.
If your light doesn't support color temp feature, omit `color_temp_template`.
If your light doesn't support white value feature, omit `white_value_template`.
If your light doesn't support RGB feature, omit `(red|green|blue)_template`.
"""
import json
from unittest.mock import ANY, patch
from homeassistant.setup import async_setup_component
from homeassistant.const import (
STATE_ON, STATE_OFF, STATE_UNAVAILABLE, ATTR_ASSUMED_STATE)
from homeassistant.components import light, mqtt
from homeassistant.components.mqtt.discovery import async_start
import homeassistant.core as ha
from tests.common import (
async_fire_mqtt_message, assert_setup_component, mock_coro,
async_mock_mqtt_component, MockConfigEntry, mock_registry)
async def test_setup_fails(hass, mqtt_mock):
"""Test that setup fails with missing required configuration items."""
with assert_setup_component(0, light.DOMAIN):
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'template',
'name': 'test',
}
})
assert hass.states.get('light.test') is None
with assert_setup_component(0, light.DOMAIN):
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'template',
'name': 'test',
'command_topic': 'test_topic',
}
})
assert hass.states.get('light.test') is None
with assert_setup_component(0, light.DOMAIN):
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'template',
'name': 'test',
'command_topic': 'test_topic',
'command_on_template': 'on',
}
})
assert hass.states.get('light.test') is None
with assert_setup_component(0, light.DOMAIN):
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'template',
'name': 'test',
'command_topic': 'test_topic',
'command_off_template': 'off',
}
})
assert hass.states.get('light.test') is None
async def test_state_change_via_topic(hass, mqtt_mock):
"""Test state change via topic."""
with assert_setup_component(1, light.DOMAIN):
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'template',
'name': 'test',
'state_topic': 'test_light_rgb',
'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',
'state_template': '{{ value.split(",")[0] }}'
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
assert state.attributes.get('rgb_color') is None
assert state.attributes.get('brightness') is None
assert state.attributes.get('color_temp') is None
assert state.attributes.get('white_value') is None
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, 'test_light_rgb', 'on')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert state.attributes.get('rgb_color') is None
assert state.attributes.get('brightness') is None
assert state.attributes.get('color_temp') is None
assert state.attributes.get('white_value') is None
async def test_state_brightness_color_effect_temp_white_change_via_topic(
hass, mqtt_mock):
"""Test state, bri, color, effect, color temp, white val change."""
with assert_setup_component(1, light.DOMAIN):
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'template',
'name': 'test',
'effect_list': ['rainbow', 'colorloop'],
'state_topic': 'test_light_rgb',
'command_topic': 'test_light_rgb/set',
'command_on_template': 'on,'
'{{ brightness|d }},'
'{{ color_temp|d }},'
'{{ white_value|d }},'
'{{ red|d }}-'
'{{ green|d }}-'
'{{ blue|d }},'
'{{ effect|d }}',
'command_off_template': 'off',
'state_template': '{{ value.split(",")[0] }}',
'brightness_template': '{{ value.split(",")[1] }}',
'color_temp_template': '{{ value.split(",")[2] }}',
'white_value_template': '{{ value.split(",")[3] }}',
'red_template': '{{ value.split(",")[4].'
'split("-")[0] }}',
'green_template': '{{ value.split(",")[4].'
'split("-")[1] }}',
'blue_template': '{{ value.split(",")[4].'
'split("-")[2] }}',
'effect_template': '{{ value.split(",")[5] }}'
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
assert state.attributes.get('rgb_color') is None
assert state.attributes.get('brightness') is None
assert state.attributes.get('effect') is None
assert state.attributes.get('color_temp') is None
assert state.attributes.get('white_value') is None
assert not state.attributes.get(ATTR_ASSUMED_STATE)
# turn on the light, full white
async_fire_mqtt_message(hass, 'test_light_rgb',
'on,255,145,123,255-128-64,')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert (255, 128, 63) == state.attributes.get('rgb_color')
assert 255 == state.attributes.get('brightness')
assert 145 == state.attributes.get('color_temp')
assert 123 == state.attributes.get('white_value')
assert state.attributes.get('effect') is None
# turn the light off
async_fire_mqtt_message(hass, 'test_light_rgb', 'off')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_OFF == state.state
# lower the brightness
async_fire_mqtt_message(hass, 'test_light_rgb', 'on,100')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert 100 == light_state.attributes['brightness']
# change the color temp
async_fire_mqtt_message(hass, 'test_light_rgb', 'on,,195')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert 195 == light_state.attributes['color_temp']
# change the color
async_fire_mqtt_message(hass, 'test_light_rgb', 'on,,,,41-42-43')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert (243, 249, 255) == \
light_state.attributes.get('rgb_color')
# change the white value
async_fire_mqtt_message(hass, 'test_light_rgb', 'on,,,134')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert 134 == light_state.attributes['white_value']
# change the effect
async_fire_mqtt_message(hass, 'test_light_rgb',
'on,,,,41-42-43,rainbow')
await hass.async_block_till_done()
await hass.async_block_till_done()
light_state = hass.states.get('light.test')
assert 'rainbow' == light_state.attributes.get('effect')
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)
async def test_flash(hass, mqtt_mock):
"""Test flash."""
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,{{ flash }}',
'command_off_template': 'off',
'qos': 0
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
async def test_transition(hass, mqtt_mock):
"""Test for transition time being sent when included."""
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,{{ transition }}',
'command_off_template': 'off,{{ transition|d }}'
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
async def test_invalid_values(hass, mqtt_mock):
"""Test that invalid values are ignored."""
with assert_setup_component(1, light.DOMAIN):
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: {
'platform': 'mqtt',
'schema': 'template',
'name': 'test',
'effect_list': ['rainbow', 'colorloop'],
'state_topic': 'test_light_rgb',
'command_topic': 'test_light_rgb/set',
'command_on_template': 'on,'
'{{ brightness|d }},'
'{{ color_temp|d }},'
'{{ red|d }}-'
'{{ green|d }}-'
'{{ blue|d }},'
'{{ effect|d }}',
'command_off_template': 'off',
'state_template': '{{ value.split(",")[0] }}',
'brightness_template': '{{ value.split(",")[1] }}',
'color_temp_template': '{{ value.split(",")[2] }}',
'white_value_template': '{{ value.split(",")[3] }}',
'red_template': '{{ value.split(",")[4].'
'split("-")[0] }}',
'green_template': '{{ value.split(",")[4].'
'split("-")[1] }}',
'blue_template': '{{ value.split(",")[4].'
'split("-")[2] }}',
'effect_template': '{{ value.split(",")[5] }}',
}
})
state = hass.states.get('light.test')
assert STATE_OFF == state.state
assert state.attributes.get('rgb_color') is None
assert state.attributes.get('brightness') is None
assert state.attributes.get('color_temp') is None
assert state.attributes.get('effect') is None
assert state.attributes.get('white_value') is None
assert not state.attributes.get(ATTR_ASSUMED_STATE)
# turn on the light, full white
async_fire_mqtt_message(hass, 'test_light_rgb',
'on,255,215,222,255-255-255,rainbow')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_ON == state.state
assert 255 == state.attributes.get('brightness')
assert 215 == state.attributes.get('color_temp')
assert (255, 255, 255) == state.attributes.get('rgb_color')
assert 222 == state.attributes.get('white_value')
assert 'rainbow' == state.attributes.get('effect')
# bad state value
async_fire_mqtt_message(hass, 'test_light_rgb', 'offf')
await hass.async_block_till_done()
# state should not have changed
state = hass.states.get('light.test')
assert STATE_ON == state.state
# bad brightness values
async_fire_mqtt_message(hass, 'test_light_rgb', 'on,off,255-255-255')
await hass.async_block_till_done()
# brightness should not have changed
state = hass.states.get('light.test')
assert 255 == state.attributes.get('brightness')
# bad color temp values
async_fire_mqtt_message(hass, 'test_light_rgb', 'on,,off,255-255-255')
await hass.async_block_till_done()
# color temp should not have changed
state = hass.states.get('light.test')
assert 215 == state.attributes.get('color_temp')
# bad color values
async_fire_mqtt_message(hass, 'test_light_rgb', 'on,255,a-b-c')
await hass.async_block_till_done()
# color should not have changed
state = hass.states.get('light.test')
assert (255, 255, 255) == state.attributes.get('rgb_color')
# bad white value values
async_fire_mqtt_message(hass, 'test_light_rgb', 'on,,,off,255-255-255')
await hass.async_block_till_done()
# white value should not have changed
state = hass.states.get('light.test')
assert 222 == state.attributes.get('white_value')
# bad effect value
async_fire_mqtt_message(hass, 'test_light_rgb', 'on,255,a-b-c,white')
await hass.async_block_till_done()
# effect should not have changed
state = hass.states.get('light.test')
assert 'rainbow' == state.attributes.get('effect')
async def test_default_availability_payload(hass, mqtt_mock):
"""Test availability by default payload with defined topic."""
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,{{ transition }}',
'command_off_template': 'off,{{ transition|d }}',
'availability_topic': 'availability-topic'
}
})
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability-topic', 'online')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE != state.state
async_fire_mqtt_message(hass, 'availability-topic', 'offline')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE == state.state
async def test_custom_availability_payload(hass, mqtt_mock):
"""Test availability by custom payload with defined topic."""
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,{{ transition }}',
'command_off_template': 'off,{{ transition|d }}',
'availability_topic': 'availability-topic',
'payload_available': 'good',
'payload_not_available': 'nogood'
}
})
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability-topic', 'good')
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE != state.state
async_fire_mqtt_message(hass, 'availability-topic', 'nogood')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.test')
assert STATE_UNAVAILABLE == state.state
async def test_unique_id(hass):
"""Test unique id option only creates one light per unique_id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'schema': 'template',
'status_topic': 'test-topic',
'command_topic': 'test_topic',
'command_on_template': 'on,{{ transition }}',
'command_off_template': 'off,{{ transition|d }}',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'schema': 'template',
'status_topic': 'test-topic',
'command_topic': 'test_topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(light.DOMAIN)) == 1
async def test_discovery(hass, mqtt_mock, caplog):
"""Test removal of discovered mqtt_json lights."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {'mqtt': {}}, entry)
data = (
'{ "name": "Beer",'
' "schema": "template",'
' "command_topic": "test_topic",'
' "command_on_template": "on",'
' "command_off_template": "off"}'
)
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is not None
assert state.name == 'Beer'
async def test_discovery_deprecated(hass, mqtt_mock, caplog):
"""Test discovery of mqtt template light with deprecated option."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {'mqtt': {}}, entry)
data = (
'{ "name": "Beer",'
' "platform": "mqtt_template",'
' "command_topic": "test_topic",'
' "command_on_template": "on",'
' "command_off_template": "off"}'
)
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is not None
assert state.name == 'Beer'
async def test_discovery_update_light(hass, mqtt_mock, caplog):
"""Test removal of discovered light."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "schema": "template",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic",'
' "command_on_template": "on",'
' "command_off_template": "off"}'
)
data2 = (
'{ "name": "Milk",'
' "schema": "template",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic",'
' "command_on_template": "on",'
' "command_off_template": "off"}'
)
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('light.milk')
assert state is None
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT light device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'schema': 'template',
'state_topic': 'test-topic',
'command_topic': 'test-topic',
'command_on_template': 'on,{{ transition }}',
'command_off_template': 'off,{{ transition|d }}',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/light/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, light.DOMAIN, {
light.DOMAIN: [{
'platform': 'mqtt',
'name': 'beer',
'schema': 'template',
'state_topic': 'test-topic',
'command_topic': 'command-topic',
'command_on_template': 'on,{{ transition }}',
'command_off_template': 'off,{{ transition|d }}',
'availability_topic': 'avty-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
state = hass.states.get('light.beer')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.reset_mock()
registry.async_update_entity('light.beer', new_entity_id='light.milk')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('light.beer')
assert state is None
state = hass.states.get('light.milk')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
+325
View File
@@ -0,0 +1,325 @@
"""The tests for the MQTT lock platform."""
import json
from unittest.mock import ANY
from homeassistant.setup import async_setup_component
from homeassistant.const import (
STATE_LOCKED, STATE_UNLOCKED, STATE_UNAVAILABLE, ATTR_ASSUMED_STATE)
from homeassistant.components import lock, mqtt
from homeassistant.components.mqtt.discovery import async_start
from tests.common import (
async_fire_mqtt_message, async_mock_mqtt_component, MockConfigEntry,
mock_registry)
async def test_controlling_state_via_topic(hass, mqtt_mock):
"""Test the controlling state via topic."""
assert await async_setup_component(hass, lock.DOMAIN, {
lock.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'payload_lock': 'LOCK',
'payload_unlock': 'UNLOCK'
}
})
state = hass.states.get('lock.test')
assert state.state is STATE_UNLOCKED
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, 'state-topic', 'LOCK')
await hass.async_block_till_done()
state = hass.states.get('lock.test')
assert state.state is STATE_LOCKED
async_fire_mqtt_message(hass, 'state-topic', 'UNLOCK')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('lock.test')
assert state.state is STATE_UNLOCKED
async def test_controlling_state_via_topic_and_json_message(hass, mqtt_mock):
"""Test the controlling state via topic and JSON message."""
assert await async_setup_component(hass, lock.DOMAIN, {
lock.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'payload_lock': 'LOCK',
'payload_unlock': 'UNLOCK',
'value_template': '{{ value_json.val }}'
}
})
state = hass.states.get('lock.test')
assert state.state is STATE_UNLOCKED
async_fire_mqtt_message(hass, 'state-topic', '{"val":"LOCK"}')
await hass.async_block_till_done()
state = hass.states.get('lock.test')
assert state.state is STATE_LOCKED
async_fire_mqtt_message(hass, 'state-topic', '{"val":"UNLOCK"}')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('lock.test')
assert state.state is STATE_UNLOCKED
async def test_default_availability_payload(hass, mqtt_mock):
"""Test availability by default payload with defined topic."""
assert await async_setup_component(hass, lock.DOMAIN, {
lock.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'payload_lock': 'LOCK',
'payload_unlock': 'UNLOCK',
'availability_topic': 'availability-topic'
}
})
state = hass.states.get('lock.test')
assert state.state is STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'availability-topic', 'online')
await hass.async_block_till_done()
state = hass.states.get('lock.test')
assert state.state is not STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'availability-topic', 'offline')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('lock.test')
assert state.state is STATE_UNAVAILABLE
async def test_custom_availability_payload(hass, mqtt_mock):
"""Test availability by custom payload with defined topic."""
assert await async_setup_component(hass, lock.DOMAIN, {
lock.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'payload_lock': 'LOCK',
'payload_unlock': 'UNLOCK',
'availability_topic': 'availability-topic',
'payload_available': 'good',
'payload_not_available': 'nogood'
}
})
state = hass.states.get('lock.test')
assert state.state is STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'availability-topic', 'good')
await hass.async_block_till_done()
state = hass.states.get('lock.test')
assert state.state is not STATE_UNAVAILABLE
async_fire_mqtt_message(hass, 'availability-topic', 'nogood')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('lock.test')
assert state.state is STATE_UNAVAILABLE
async def test_unique_id(hass):
"""Test unique id option only creates one light per unique_id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, lock.DOMAIN, {
lock.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'status_topic': 'test-topic',
'command_topic': 'test_topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'status_topic': 'test-topic',
'command_topic': 'test_topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(lock.DOMAIN)) == 1
async def test_discovery_removal_lock(hass, mqtt_mock, caplog):
"""Test removal of discovered lock."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data = (
'{ "name": "Beer",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/lock/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('lock.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/lock/bla/config',
'')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('lock.beer')
assert state is None
async def test_discovery_broken(hass, mqtt_mock, caplog):
"""Test handling of bad discovery message."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer" }'
)
data2 = (
'{ "name": "Milk",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/lock/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('lock.beer')
assert state is None
async_fire_mqtt_message(hass, 'homeassistant/lock/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('lock.milk')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('lock.beer')
assert state is None
async def test_discovery_update_lock(hass, mqtt_mock, caplog):
"""Test update of discovered lock."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "state_topic": "test_topic",'
' "command_topic": "command_topic",'
' "availability_topic": "availability_topic1" }'
)
data2 = (
'{ "name": "Milk",'
' "state_topic": "test_topic2",'
' "command_topic": "command_topic",'
' "availability_topic": "availability_topic2" }'
)
async_fire_mqtt_message(hass, 'homeassistant/lock/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('lock.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/lock/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('lock.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('lock.milk')
assert state is None
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT lock device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'command_topic': 'test-topic',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/lock/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, lock.DOMAIN, {
lock.DOMAIN: [{
'platform': 'mqtt',
'name': 'beer',
'state_topic': 'test-topic',
'command_topic': 'test-topic',
'availability_topic': 'avty-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
state = hass.states.get('lock.beer')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.reset_mock()
registry.async_update_entity('lock.beer', new_entity_id='lock.milk')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('lock.beer')
assert state is None
state = hass.states.get('lock.milk')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
+645
View File
@@ -0,0 +1,645 @@
"""The tests for the MQTT sensor platform."""
import json
import unittest
from datetime import timedelta, datetime
from unittest.mock import ANY, patch
import homeassistant.core as ha
from homeassistant.setup import setup_component, async_setup_component
from homeassistant.components import mqtt
from homeassistant.components.mqtt.discovery import async_start
import homeassistant.components.sensor as sensor
from homeassistant.const import EVENT_STATE_CHANGED, STATE_UNAVAILABLE
import homeassistant.util.dt as dt_util
from tests.common import mock_mqtt_component, fire_mqtt_message, \
assert_setup_component, async_fire_mqtt_message, \
async_mock_mqtt_component, MockConfigEntry, mock_registry
from tests.common import get_test_home_assistant, mock_component
class TestSensorMQTT(unittest.TestCase):
"""Test the MQTT sensor."""
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_mqtt_component(self.hass)
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
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')
assert '100' == state.state
assert 'fav unit' == \
state.attributes.get('unit_of_measurement')
@patch('homeassistant.core.dt_util.utcnow')
def test_setting_sensor_value_expires(self, mock_utcnow):
"""Test the expiration of the value."""
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',
'expire_after': '4',
'force_update': True
}
})
state = self.hass.states.get('sensor.test')
assert 'unknown' == state.state
now = datetime(2017, 1, 1, 1, tzinfo=dt_util.UTC)
mock_utcnow.return_value = now
fire_mqtt_message(self.hass, 'test-topic', '100')
self.hass.block_till_done()
# Value was set correctly.
state = self.hass.states.get('sensor.test')
assert '100' == state.state
# Time jump +3s
now = now + timedelta(seconds=3)
self._send_time_changed(now)
self.hass.block_till_done()
# Value is not yet expired
state = self.hass.states.get('sensor.test')
assert '100' == state.state
# Next message resets timer
mock_utcnow.return_value = now
fire_mqtt_message(self.hass, 'test-topic', '101')
self.hass.block_till_done()
# Value was updated correctly.
state = self.hass.states.get('sensor.test')
assert '101' == state.state
# Time jump +3s
now = now + timedelta(seconds=3)
self._send_time_changed(now)
self.hass.block_till_done()
# Value is not yet expired
state = self.hass.states.get('sensor.test')
assert '101' == state.state
# Time jump +2s
now = now + timedelta(seconds=2)
self._send_time_changed(now)
self.hass.block_till_done()
# Value is expired now
state = self.hass.states.get('sensor.test')
assert 'unknown' == state.state
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')
assert '100' == state.state
def test_force_update_disabled(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'
}
})
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()
assert 1 == len(events)
fire_mqtt_message(self.hass, 'test-topic', '100')
self.hass.block_till_done()
assert 1 == len(events)
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()
assert 1 == len(events)
fire_mqtt_message(self.hass, 'test-topic', '100')
self.hass.block_till_done()
assert 2 == len(events)
def test_default_availability_payload(self):
"""Test availability by default payload with defined topic."""
assert setup_component(self.hass, sensor.DOMAIN, {
sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test-topic',
'availability_topic': 'availability-topic'
}
})
state = self.hass.states.get('sensor.test')
assert STATE_UNAVAILABLE == state.state
fire_mqtt_message(self.hass, 'availability-topic', 'online')
self.hass.block_till_done()
state = self.hass.states.get('sensor.test')
assert STATE_UNAVAILABLE != state.state
fire_mqtt_message(self.hass, 'availability-topic', 'offline')
self.hass.block_till_done()
state = self.hass.states.get('sensor.test')
assert STATE_UNAVAILABLE == state.state
def test_custom_availability_payload(self):
"""Test availability by custom payload with defined topic."""
assert setup_component(self.hass, sensor.DOMAIN, {
sensor.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'test-topic',
'availability_topic': 'availability-topic',
'payload_available': 'good',
'payload_not_available': 'nogood'
}
})
state = self.hass.states.get('sensor.test')
assert STATE_UNAVAILABLE == state.state
fire_mqtt_message(self.hass, 'availability-topic', 'good')
self.hass.block_till_done()
state = self.hass.states.get('sensor.test')
assert STATE_UNAVAILABLE != state.state
fire_mqtt_message(self.hass, 'availability-topic', 'nogood')
self.hass.block_till_done()
state = self.hass.states.get('sensor.test')
assert STATE_UNAVAILABLE == state.state
def _send_time_changed(self, now):
"""Send a time changed event."""
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: now})
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')
@patch('homeassistant.components.mqtt.sensor._LOGGER')
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
@patch('homeassistant.components.mqtt.sensor._LOGGER')
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')
assert state.attributes.get('val') is None
assert mock_logger.warning.called
assert mock_logger.debug.called
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')
assert '100' == \
state.attributes.get('val')
assert '100' == state.state
def test_setting_sensor_attribute_via_mqtt_json_topic(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',
'json_attributes_topic': 'attr-topic'
}
})
fire_mqtt_message(self.hass, 'attr-topic', '{ "val": "100" }')
self.hass.block_till_done()
state = self.hass.states.get('sensor.test')
assert '100' == \
state.attributes.get('val')
@patch('homeassistant.components.mqtt._LOGGER')
def test_update_with_json_attrs_topic_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',
'json_attributes_topic': 'attr-topic'
}
})
fire_mqtt_message(self.hass, 'attr-topic', '[ "list", "of", "things"]')
self.hass.block_till_done()
state = self.hass.states.get('sensor.test')
assert state.attributes.get('val') is None
mock_logger.warning.assert_called_with(
'JSON result was not a dictionary')
@patch('homeassistant.components.mqtt._LOGGER')
def test_update_with_json_attrs_topic_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',
'json_attributes_topic': 'attr-topic'
}
})
fire_mqtt_message(self.hass, 'attr-topic', 'This is not JSON')
self.hass.block_till_done()
state = self.hass.states.get('sensor.test')
assert state.attributes.get('val') is None
mock_logger.warning.assert_called_with(
'Erroneous JSON: %s', 'This is not JSON')
def test_invalid_device_class(self):
"""Test device_class option with invalid value."""
with assert_setup_component(0):
assert setup_component(self.hass, 'sensor', {
'sensor': {
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'device_class': 'foobarnotreal'
}
})
def test_valid_device_class(self):
"""Test device_class option with valid values."""
assert setup_component(self.hass, 'sensor', {
'sensor': [{
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'device_class': 'temperature'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'state_topic': 'test-topic',
}]
})
self.hass.block_till_done()
state = self.hass.states.get('sensor.test_1')
assert state.attributes['device_class'] == 'temperature'
state = self.hass.states.get('sensor.test_2')
assert 'device_class' not in state.attributes
async def test_unique_id(hass):
"""Test unique id option only creates one sensor per unique_id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, sensor.DOMAIN, {
sensor.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'state_topic': 'test-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 1
async def test_discovery_removal_sensor(hass, mqtt_mock, caplog):
"""Test removal of discovered sensor."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data = (
'{ "name": "Beer",'
' "status_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/sensor/bla/config',
data)
await hass.async_block_till_done()
state = hass.states.get('sensor.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/sensor/bla/config',
'')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('sensor.beer')
assert state is None
async def test_discovery_update_sensor(hass, mqtt_mock, caplog):
"""Test update of discovered sensor."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "status_topic": "test_topic" }'
)
data2 = (
'{ "name": "Milk",'
' "status_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/sensor/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('sensor.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/sensor/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('sensor.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('sensor.milk')
assert state is None
async def test_discovery_broken(hass, mqtt_mock, caplog):
"""Test handling of bad discovery message."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "state_topic": "test_topic#" }'
)
data2 = (
'{ "name": "Milk",'
' "state_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/sensor/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('sensor.beer')
assert state is None
async_fire_mqtt_message(hass, 'homeassistant/sensor/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('sensor.milk')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('sensor.beer')
assert state is None
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT sensor device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/sensor/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, sensor.DOMAIN, {
sensor.DOMAIN: [{
'platform': 'mqtt',
'name': 'beer',
'state_topic': 'test-topic',
'availability_topic': 'avty-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
state = hass.states.get('sensor.beer')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.reset_mock()
registry.async_update_entity('sensor.beer', new_entity_id='sensor.milk')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('sensor.beer')
assert state is None
state = hass.states.get('sensor.milk')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
async def test_entity_device_info_with_hub(hass, mqtt_mock):
"""Test MQTT sensor device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
hub = registry.async_get_or_create(
config_entry_id='123',
connections=set(),
identifiers={('mqtt', 'hub-id')},
manufacturer='manufacturer', model='hub'
)
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'device': {
'identifiers': ['helloworld'],
'via_hub': 'hub-id',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/sensor/bla/config', data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.hub_device_id == hub.id
+457
View File
@@ -0,0 +1,457 @@
"""The tests for the MQTT switch platform."""
import json
from asynctest import patch
import pytest
from unittest.mock import ANY
from homeassistant.setup import async_setup_component
from homeassistant.const import STATE_ON, STATE_OFF, STATE_UNAVAILABLE,\
ATTR_ASSUMED_STATE
import homeassistant.core as ha
from homeassistant.components import switch, mqtt
from homeassistant.components.mqtt.discovery import async_start
from tests.common import (
mock_coro, async_mock_mqtt_component, async_fire_mqtt_message,
MockConfigEntry, mock_registry)
from tests.components.switch import common
@pytest.fixture
def mock_publish(hass):
"""Initialize components."""
yield hass.loop.run_until_complete(async_mock_mqtt_component(hass))
async def test_controlling_state_via_topic(hass, mock_publish):
"""Test the controlling state via topic."""
assert await async_setup_component(hass, switch.DOMAIN, {
switch.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'payload_on': 1,
'payload_off': 0
}
})
state = hass.states.get('switch.test')
assert STATE_OFF == state.state
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, 'state-topic', '1')
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_ON == state.state
async_fire_mqtt_message(hass, 'state-topic', '0')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_OFF == state.state
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_controlling_state_via_topic_and_json_message(
hass, mock_publish):
"""Test the controlling state via topic and JSON message."""
assert await async_setup_component(hass, switch.DOMAIN, {
switch.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'payload_on': 'beer on',
'payload_off': 'beer off',
'value_template': '{{ value_json.val }}'
}
})
state = hass.states.get('switch.test')
assert STATE_OFF == state.state
async_fire_mqtt_message(hass, 'state-topic', '{"val":"beer on"}')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_ON == state.state
async_fire_mqtt_message(hass, 'state-topic', '{"val":"beer off"}')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_OFF == state.state
async def test_default_availability_payload(hass, mock_publish):
"""Test the availability payload."""
assert await async_setup_component(hass, switch.DOMAIN, {
switch.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'availability_topic': 'availability_topic',
'payload_on': 1,
'payload_off': 0
}
})
state = hass.states.get('switch.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability_topic', 'online')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_OFF == state.state
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, 'availability_topic', 'offline')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'state-topic', '1')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability_topic', 'online')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_ON == state.state
async def test_custom_availability_payload(hass, mock_publish):
"""Test the availability payload."""
assert await async_setup_component(hass, switch.DOMAIN, {
switch.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'availability_topic': 'availability_topic',
'payload_on': 1,
'payload_off': 0,
'payload_available': 'good',
'payload_not_available': 'nogood'
}
})
state = hass.states.get('switch.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability_topic', 'good')
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_OFF == state.state
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, 'availability_topic', 'nogood')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'state-topic', '1')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability_topic', 'good')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_ON == state.state
async def test_custom_state_payload(hass, mock_publish):
"""Test the state payload."""
assert await async_setup_component(hass, switch.DOMAIN, {
switch.DOMAIN: {
'platform': 'mqtt',
'name': 'test',
'state_topic': 'state-topic',
'command_topic': 'command-topic',
'payload_on': 1,
'payload_off': 0,
'state_on': "HIGH",
'state_off': "LOW",
}
})
state = hass.states.get('switch.test')
assert STATE_OFF == state.state
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, 'state-topic', 'HIGH')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_ON == state.state
async_fire_mqtt_message(hass, 'state-topic', 'LOW')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.test')
assert STATE_OFF == state.state
async def test_unique_id(hass):
"""Test unique id option only creates one switch per unique_id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, switch.DOMAIN, {
switch.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'command_topic': 'command-topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'state_topic': 'test-topic',
'command_topic': 'command-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids()) == 2
# all switches group is 1, unique id created is 1
async def test_discovery_removal_switch(hass, mqtt_mock, caplog):
"""Test removal of discovered switch."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data = (
'{ "name": "Beer",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/switch/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/switch/bla/config',
'')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.beer')
assert state is None
async def test_discovery_update_switch(hass, mqtt_mock, caplog):
"""Test update of discovered switch."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
data2 = (
'{ "name": "Milk",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/switch/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('switch.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/switch/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('switch.milk')
assert state is None
async def test_discovery_broken(hass, mqtt_mock, caplog):
"""Test handling of bad discovery message."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer" }'
)
data2 = (
'{ "name": "Milk",'
' "status_topic": "test_topic",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/switch/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('switch.beer')
assert state is None
async_fire_mqtt_message(hass, 'homeassistant/switch/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.milk')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('switch.beer')
assert state is None
async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT switch device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'state_topic': 'test-topic',
'command_topic': 'test-command-topic',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/switch/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'
async def test_entity_id_update(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
registry = mock_registry(hass, {})
mock_mqtt = await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, switch.DOMAIN, {
switch.DOMAIN: [{
'platform': 'mqtt',
'name': 'beer',
'state_topic': 'test-topic',
'command_topic': 'command-topic',
'availability_topic': 'avty-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
state = hass.states.get('switch.beer')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.reset_mock()
registry.async_update_entity('switch.beer', new_entity_id='switch.milk')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('switch.beer')
assert state is None
state = hass.states.get('switch.milk')
assert state is not None
assert mock_mqtt.async_subscribe.call_count == 2
mock_mqtt.async_subscribe.assert_any_call('test-topic', ANY, 0, 'utf-8')
mock_mqtt.async_subscribe.assert_any_call('avty-topic', ANY, 0, 'utf-8')
+396
View File
@@ -0,0 +1,396 @@
"""The tests for the Mqtt vacuum platform."""
import json
import pytest
from homeassistant.setup import async_setup_component
from homeassistant.const import (
CONF_PLATFORM, STATE_OFF, STATE_ON, STATE_UNAVAILABLE, CONF_NAME)
from homeassistant.components import vacuum, mqtt
from homeassistant.components.vacuum import (
ATTR_BATTERY_LEVEL, ATTR_BATTERY_ICON, ATTR_STATUS,
ATTR_FAN_SPEED)
from homeassistant.components.mqtt import (
CONF_COMMAND_TOPIC, vacuum as mqttvacuum)
from homeassistant.components.mqtt.discovery import async_start
from tests.common import (
async_mock_mqtt_component,
async_fire_mqtt_message, MockConfigEntry)
from tests.components.vacuum import common
default_config = {
CONF_PLATFORM: 'mqtt',
CONF_NAME: 'mqtttest',
CONF_COMMAND_TOPIC: 'vacuum/command',
mqttvacuum.CONF_SEND_COMMAND_TOPIC: 'vacuum/send_command',
mqttvacuum.CONF_BATTERY_LEVEL_TOPIC: 'vacuum/state',
mqttvacuum.CONF_BATTERY_LEVEL_TEMPLATE:
'{{ value_json.battery_level }}',
mqttvacuum.CONF_CHARGING_TOPIC: 'vacuum/state',
mqttvacuum.CONF_CHARGING_TEMPLATE: '{{ value_json.charging }}',
mqttvacuum.CONF_CLEANING_TOPIC: 'vacuum/state',
mqttvacuum.CONF_CLEANING_TEMPLATE: '{{ value_json.cleaning }}',
mqttvacuum.CONF_DOCKED_TOPIC: 'vacuum/state',
mqttvacuum.CONF_DOCKED_TEMPLATE: '{{ value_json.docked }}',
mqttvacuum.CONF_STATE_TOPIC: 'vacuum/state',
mqttvacuum.CONF_STATE_TEMPLATE: '{{ value_json.state }}',
mqttvacuum.CONF_FAN_SPEED_TOPIC: 'vacuum/state',
mqttvacuum.CONF_FAN_SPEED_TEMPLATE: '{{ value_json.fan_speed }}',
mqttvacuum.CONF_SET_FAN_SPEED_TOPIC: 'vacuum/set_fan_speed',
mqttvacuum.CONF_FAN_SPEED_LIST: ['min', 'medium', 'high', 'max'],
}
@pytest.fixture
def mock_publish(hass):
"""Initialize components."""
yield hass.loop.run_until_complete(async_mock_mqtt_component(hass))
async def test_default_supported_features(hass, mock_publish):
"""Test that the correct supported features."""
assert await async_setup_component(hass, vacuum.DOMAIN, {
vacuum.DOMAIN: default_config,
})
entity = hass.states.get('vacuum.mqtttest')
entity_features = \
entity.attributes.get(mqttvacuum.CONF_SUPPORTED_FEATURES, 0)
assert sorted(mqttvacuum.services_to_strings(entity_features)) == \
sorted(['turn_on', 'turn_off', 'stop',
'return_home', 'battery', 'status',
'clean_spot'])
async def test_all_commands(hass, mock_publish):
"""Test simple commands to the vacuum."""
default_config[mqttvacuum.CONF_SUPPORTED_FEATURES] = \
mqttvacuum.services_to_strings(mqttvacuum.ALL_SERVICES)
assert await async_setup_component(hass, vacuum.DOMAIN, {
vacuum.DOMAIN: default_config,
})
common.turn_on(hass, 'vacuum.mqtttest')
await hass.async_block_till_done()
await hass.async_block_till_done()
mock_publish.async_publish.assert_called_once_with(
'vacuum/command', 'turn_on', 0, False)
mock_publish.async_publish.reset_mock()
common.turn_off(hass, 'vacuum.mqtttest')
await hass.async_block_till_done()
await hass.async_block_till_done()
mock_publish.async_publish.assert_called_once_with(
'vacuum/command', 'turn_off', 0, False)
mock_publish.async_publish.reset_mock()
common.stop(hass, 'vacuum.mqtttest')
await hass.async_block_till_done()
await hass.async_block_till_done()
mock_publish.async_publish.assert_called_once_with(
'vacuum/command', 'stop', 0, False)
mock_publish.async_publish.reset_mock()
common.clean_spot(hass, 'vacuum.mqtttest')
await hass.async_block_till_done()
await hass.async_block_till_done()
mock_publish.async_publish.assert_called_once_with(
'vacuum/command', 'clean_spot', 0, False)
mock_publish.async_publish.reset_mock()
common.locate(hass, 'vacuum.mqtttest')
await hass.async_block_till_done()
await hass.async_block_till_done()
mock_publish.async_publish.assert_called_once_with(
'vacuum/command', 'locate', 0, False)
mock_publish.async_publish.reset_mock()
common.start_pause(hass, 'vacuum.mqtttest')
await hass.async_block_till_done()
await hass.async_block_till_done()
mock_publish.async_publish.assert_called_once_with(
'vacuum/command', 'start_pause', 0, False)
mock_publish.async_publish.reset_mock()
common.return_to_base(hass, 'vacuum.mqtttest')
await hass.async_block_till_done()
await hass.async_block_till_done()
mock_publish.async_publish.assert_called_once_with(
'vacuum/command', 'return_to_base', 0, False)
mock_publish.async_publish.reset_mock()
common.set_fan_speed(hass, 'high', 'vacuum.mqtttest')
await hass.async_block_till_done()
await hass.async_block_till_done()
mock_publish.async_publish.assert_called_once_with(
'vacuum/set_fan_speed', 'high', 0, False)
mock_publish.async_publish.reset_mock()
common.send_command(hass, '44 FE 93', entity_id='vacuum.mqtttest')
await hass.async_block_till_done()
await hass.async_block_till_done()
mock_publish.async_publish.assert_called_once_with(
'vacuum/send_command', '44 FE 93', 0, False)
async def test_status(hass, mock_publish):
"""Test status updates from the vacuum."""
default_config[mqttvacuum.CONF_SUPPORTED_FEATURES] = \
mqttvacuum.services_to_strings(mqttvacuum.ALL_SERVICES)
assert await async_setup_component(hass, vacuum.DOMAIN, {
vacuum.DOMAIN: default_config,
})
message = """{
"battery_level": 54,
"cleaning": true,
"docked": false,
"charging": false,
"fan_speed": "max"
}"""
async_fire_mqtt_message(hass, 'vacuum/state', message)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('vacuum.mqtttest')
assert STATE_ON == state.state
assert 'mdi:battery-50' == \
state.attributes.get(ATTR_BATTERY_ICON)
assert 54 == state.attributes.get(ATTR_BATTERY_LEVEL)
assert 'max' == state.attributes.get(ATTR_FAN_SPEED)
message = """{
"battery_level": 61,
"docked": true,
"cleaning": false,
"charging": true,
"fan_speed": "min"
}"""
async_fire_mqtt_message(hass, 'vacuum/state', message)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('vacuum.mqtttest')
assert STATE_OFF == state.state
assert 'mdi:battery-charging-60' == \
state.attributes.get(ATTR_BATTERY_ICON)
assert 61 == state.attributes.get(ATTR_BATTERY_LEVEL)
assert 'min' == state.attributes.get(ATTR_FAN_SPEED)
async def test_battery_template(hass, mock_publish):
"""Test that you can use non-default templates for battery_level."""
default_config.update({
mqttvacuum.CONF_SUPPORTED_FEATURES:
mqttvacuum.services_to_strings(mqttvacuum.ALL_SERVICES),
mqttvacuum.CONF_BATTERY_LEVEL_TOPIC: "retroroomba/battery_level",
mqttvacuum.CONF_BATTERY_LEVEL_TEMPLATE: "{{ value }}"
})
assert await async_setup_component(hass, vacuum.DOMAIN, {
vacuum.DOMAIN: default_config,
})
async_fire_mqtt_message(hass, 'retroroomba/battery_level', '54')
await hass.async_block_till_done()
state = hass.states.get('vacuum.mqtttest')
assert 54 == state.attributes.get(ATTR_BATTERY_LEVEL)
assert state.attributes.get(ATTR_BATTERY_ICON) == \
'mdi:battery-50'
async def test_status_invalid_json(hass, mock_publish):
"""Test to make sure nothing breaks if the vacuum sends bad JSON."""
default_config[mqttvacuum.CONF_SUPPORTED_FEATURES] = \
mqttvacuum.services_to_strings(mqttvacuum.ALL_SERVICES)
assert await async_setup_component(hass, vacuum.DOMAIN, {
vacuum.DOMAIN: default_config,
})
async_fire_mqtt_message(hass, 'vacuum/state', '{"asdfasas false}')
await hass.async_block_till_done()
state = hass.states.get('vacuum.mqtttest')
assert STATE_OFF == state.state
assert "Stopped" == state.attributes.get(ATTR_STATUS)
async def test_default_availability_payload(hass, mock_publish):
"""Test availability by default payload with defined topic."""
default_config.update({
'availability_topic': 'availability-topic'
})
assert await async_setup_component(hass, vacuum.DOMAIN, {
vacuum.DOMAIN: default_config,
})
state = hass.states.get('vacuum.mqtttest')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability-topic', 'online')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('vacuum.mqtttest')
assert STATE_UNAVAILABLE != state.state
async_fire_mqtt_message(hass, 'availability-topic', 'offline')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('vacuum.mqtttest')
assert STATE_UNAVAILABLE == state.state
async def test_custom_availability_payload(hass, mock_publish):
"""Test availability by custom payload with defined topic."""
default_config.update({
'availability_topic': 'availability-topic',
'payload_available': 'good',
'payload_not_available': 'nogood'
})
assert await async_setup_component(hass, vacuum.DOMAIN, {
vacuum.DOMAIN: default_config,
})
state = hass.states.get('vacuum.mqtttest')
assert STATE_UNAVAILABLE == state.state
async_fire_mqtt_message(hass, 'availability-topic', 'good')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('vacuum.mqtttest')
assert STATE_UNAVAILABLE != state.state
async_fire_mqtt_message(hass, 'availability-topic', 'nogood')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('vacuum.mqtttest')
assert STATE_UNAVAILABLE == state.state
async def test_discovery_removal_vacuum(hass, mock_publish):
"""Test removal of discovered vacuum."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data = (
'{ "name": "Beer",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/vacuum/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('vacuum.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/vacuum/bla/config', '')
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('vacuum.beer')
assert state is None
async def test_discovery_update_vacuum(hass, mock_publish):
"""Test update of discovered vacuum."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
await async_start(hass, 'homeassistant', {}, entry)
data1 = (
'{ "name": "Beer",'
' "command_topic": "test_topic" }'
)
data2 = (
'{ "name": "Milk",'
' "command_topic": "test_topic" }'
)
async_fire_mqtt_message(hass, 'homeassistant/vacuum/bla/config',
data1)
await hass.async_block_till_done()
state = hass.states.get('vacuum.beer')
assert state is not None
assert state.name == 'Beer'
async_fire_mqtt_message(hass, 'homeassistant/vacuum/bla/config',
data2)
await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get('vacuum.beer')
assert state is not None
assert state.name == 'Milk'
state = hass.states.get('vacuum.milk')
assert state is None
async def test_unique_id(hass, mock_publish):
"""Test unique id option only creates one vacuum per unique_id."""
await async_mock_mqtt_component(hass)
assert await async_setup_component(hass, vacuum.DOMAIN, {
vacuum.DOMAIN: [{
'platform': 'mqtt',
'name': 'Test 1',
'command_topic': 'command-topic',
'unique_id': 'TOTALLY_UNIQUE'
}, {
'platform': 'mqtt',
'name': 'Test 2',
'command_topic': 'command-topic',
'unique_id': 'TOTALLY_UNIQUE'
}]
})
async_fire_mqtt_message(hass, 'test-topic', 'payload')
await hass.async_block_till_done()
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids()) == 2
# all vacuums group is 1, unique id created is 1
async def test_entity_device_info_with_identifier(hass, mock_publish):
"""Test MQTT vacuum device registry integration."""
entry = MockConfigEntry(domain=mqtt.DOMAIN)
entry.add_to_hass(hass)
await async_start(hass, 'homeassistant', {}, entry)
registry = await hass.helpers.device_registry.async_get_registry()
data = json.dumps({
'platform': 'mqtt',
'name': 'Test 1',
'command_topic': 'test-command-topic',
'device': {
'identifiers': ['helloworld'],
'connections': [
["mac", "02:5b:26:a8:dc:12"],
],
'manufacturer': 'Whatever',
'name': 'Beer',
'model': 'Glass',
'sw_version': '0.1-beta',
},
'unique_id': 'veryunique'
})
async_fire_mqtt_message(hass, 'homeassistant/vacuum/bla/config',
data)
await hass.async_block_till_done()
await hass.async_block_till_done()
device = registry.async_get_device({('mqtt', 'helloworld')}, set())
assert device is not None
assert device.identifiers == {('mqtt', 'helloworld')}
assert device.connections == {('mac', "02:5b:26:a8:dc:12")}
assert device.manufacturer == 'Whatever'
assert device.name == 'Beer'
assert device.model == 'Glass'
assert device.sw_version == '0.1-beta'