Add zwave mqtt (#34987)

This commit is contained in:
Martin Hjelmare authored and GitHub committed 2020-05-03 02:54:16 +02:00
1 parent 984a2769db
commit aeb891649e
26 files changed
+1578 -3

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Tests for the Z-Wave MQTT integration."""
+57
View File
@@ -0,0 +1,57 @@
"""Helpers for tests."""
import json
from homeassistant import config_entries
from homeassistant.components.zwave_mqtt.const import DOMAIN
from tests.async_mock import Mock, patch
from tests.common import MockConfigEntry
async def setup_zwave(hass, entry=None, fixture=None):
"""Set up Z-Wave and load a dump."""
hass.config.components.add("mqtt")
if entry is None:
entry = MockConfigEntry(
domain=DOMAIN,
title="Z-Wave",
connection_class=config_entries.CONN_CLASS_LOCAL_PUSH,
)
entry.add_to_hass(hass)
with patch("homeassistant.components.mqtt.async_subscribe") as mock_subscribe:
mock_subscribe.return_value = Mock()
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert "zwave_mqtt" in hass.config.components
assert len(mock_subscribe.mock_calls) == 1
receive_message = mock_subscribe.mock_calls[0][1][2]
if fixture is not None:
for line in fixture.split("\n"):
topic, payload = line.strip().split(",", 1)
receive_message(Mock(topic=topic, payload=payload))
await hass.async_block_till_done()
return receive_message
class MQTTMessage:
"""Represent a mock MQTT message."""
def __init__(self, topic, payload):
"""Set up message."""
self.topic = topic
self.payload = payload
def decode(self):
"""Decode message payload from a string to a json dict."""
self.payload = json.loads(self.payload)
def encode(self):
"""Encode message payload into a string."""
self.payload = json.dumps(self.payload)
+40
View File
@@ -0,0 +1,40 @@
"""Helpers for tests."""
import json
import pytest
from .common import MQTTMessage
from tests.async_mock import patch
from tests.common import load_fixture
@pytest.fixture(name="generic_data", scope="session")
def generic_data_fixture():
"""Load generic MQTT data and return it."""
return load_fixture(f"zwave_mqtt/generic_network_dump.csv")
@pytest.fixture(name="sent_messages")
def sent_messages_fixture():
"""Fixture to capture sent messages."""
sent_messages = []
with patch(
"homeassistant.components.mqtt.async_publish",
side_effect=lambda hass, topic, payload: sent_messages.append(
{"topic": topic, "payload": json.loads(payload)}
),
):
yield sent_messages
@pytest.fixture(name="switch_msg")
async def switch_msg_fixture(hass):
"""Return a mock MQTT msg with a switch actuator message."""
switch_json = json.loads(
await hass.async_add_executor_job(load_fixture, "zwave_mqtt/switch.json")
)
message = MQTTMessage(topic=switch_json["topic"], payload=switch_json["payload"])
message.encode()
return message
@@ -0,0 +1,53 @@
"""Test the Z-Wave over MQTT config flow."""
from homeassistant import config_entries, setup
from homeassistant.components.zwave_mqtt.config_flow import TITLE
from homeassistant.components.zwave_mqtt.const import DOMAIN
from tests.async_mock import patch
from tests.common import MockConfigEntry
async def test_user_create_entry(hass):
"""Test the user step creates an entry."""
hass.config.components.add("mqtt")
await setup.async_setup_component(hass, "persistent_notification", {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] is None
with patch(
"homeassistant.components.zwave_mqtt.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.zwave_mqtt.async_setup_entry", return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result2["type"] == "create_entry"
assert result2["title"] == TITLE
assert result2["data"] == {}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_mqtt_not_setup(hass):
"""Test that mqtt is required."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "abort"
assert result["reason"] == "mqtt_required"
async def test_one_instance_allowed(hass):
"""Test that only one instance is allowed."""
entry = MockConfigEntry(domain=DOMAIN, data={}, title=TITLE)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "abort"
assert result["reason"] == "one_instance_allowed"
+62
View File
@@ -0,0 +1,62 @@
"""Test integration initialization."""
from homeassistant import config_entries
from homeassistant.components.zwave_mqtt import DOMAIN, PLATFORMS, const
from .common import setup_zwave
from tests.common import MockConfigEntry
async def test_init_entry(hass, generic_data):
"""Test setting up config entry."""
await setup_zwave(hass, fixture=generic_data)
# Verify integration + platform loaded.
assert "zwave_mqtt" in hass.config.components
for platform in PLATFORMS:
assert platform in hass.config.components, platform
assert f"{platform}.{DOMAIN}" in hass.config.components, f"{platform}.{DOMAIN}"
# Verify services registered
assert hass.services.has_service(DOMAIN, const.SERVICE_ADD_NODE)
assert hass.services.has_service(DOMAIN, const.SERVICE_REMOVE_NODE)
async def test_unload_entry(hass, generic_data, switch_msg, caplog):
"""Test unload the config entry."""
entry = MockConfigEntry(
domain=DOMAIN,
title="Z-Wave",
connection_class=config_entries.CONN_CLASS_LOCAL_PUSH,
)
entry.add_to_hass(hass)
assert entry.state == config_entries.ENTRY_STATE_NOT_LOADED
receive_message = await setup_zwave(hass, entry=entry, fixture=generic_data)
assert entry.state == config_entries.ENTRY_STATE_LOADED
assert len(hass.states.async_entity_ids("switch")) == 1
await hass.config_entries.async_unload(entry.entry_id)
assert entry.state == config_entries.ENTRY_STATE_NOT_LOADED
assert len(hass.states.async_entity_ids("switch")) == 0
# Send a message for a switch from the broker to check that
# all entity topic subscribers are unsubscribed.
receive_message(switch_msg)
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids("switch")) == 0
# Load the integration again and check that there are no errors when
# adding the entities.
# This asserts that we have unsubscribed the entity addition signals
# when unloading the integration previously.
await setup_zwave(hass, entry=entry, fixture=generic_data)
await hass.async_block_till_done()
assert entry.state == config_entries.ENTRY_STATE_LOADED
assert len(hass.states.async_entity_ids("switch")) == 1
for record in caplog.records:
assert record.levelname != "ERROR"
@@ -0,0 +1,88 @@
"""Test Z-Wave (central) Scenes."""
from .common import MQTTMessage, setup_zwave
from tests.common import async_capture_events
async def test_scenes(hass, generic_data, sent_messages):
"""Test setting up config entry."""
receive_message = await setup_zwave(hass, fixture=generic_data)
events = async_capture_events(hass, "zwave_mqtt.scene_activated")
# Publish fake scene event on mqtt
message = MQTTMessage(
topic="OpenZWave/1/node/39/instance/1/commandclass/43/value/562950622511127/",
payload={
"Label": "Scene",
"Value": 16,
"Units": "",
"Min": -2147483648,
"Max": 2147483647,
"Type": "Int",
"Instance": 1,
"CommandClass": "COMMAND_CLASS_SCENE_ACTIVATION",
"Index": 0,
"Node": 7,
"Genre": "User",
"Help": "",
"ValueIDKey": 122339347,
"ReadOnly": False,
"WriteOnly": False,
"ValueSet": False,
"ValuePolled": False,
"ChangeVerified": False,
"Event": "valueChanged",
"TimeStamp": 1579630367,
},
)
message.encode()
receive_message(message)
# wait for the event
await hass.async_block_till_done()
assert len(events) == 1
assert events[0].data["scene_value_id"] == 16
# Publish fake central scene event on mqtt
message = MQTTMessage(
topic="OpenZWave/1/node/39/instance/1/commandclass/91/value/281476005806100/",
payload={
"Label": "Scene 1",
"Value": {
"List": [
{"Value": 0, "Label": "Inactive"},
{"Value": 1, "Label": "Pressed 1 Time"},
{"Value": 2, "Label": "Key Released"},
{"Value": 3, "Label": "Key Held down"},
],
"Selected": "Pressed 1 Time",
"Selected_id": 1,
},
"Units": "",
"Min": 0,
"Max": 0,
"Type": "List",
"Instance": 1,
"CommandClass": "COMMAND_CLASS_CENTRAL_SCENE",
"Index": 1,
"Node": 61,
"Genre": "User",
"Help": "",
"ValueIDKey": 281476005806100,
"ReadOnly": False,
"WriteOnly": False,
"ValueSet": False,
"ValuePolled": False,
"ChangeVerified": False,
"Event": "valueChanged",
"TimeStamp": 1579640710,
},
)
message.encode()
receive_message(message)
# wait for the event
await hass.async_block_till_done()
assert len(events) == 2
assert events[1].data["scene_id"] == 1
assert events[1].data["scene_label"] == "Scene 1"
assert events[1].data["scene_value_label"] == "Pressed 1 Time"
@@ -0,0 +1,41 @@
"""Test Z-Wave Switches."""
from .common import setup_zwave
async def test_switch(hass, generic_data, sent_messages, switch_msg):
"""Test setting up config entry."""
receive_message = await setup_zwave(hass, fixture=generic_data)
# Test loaded
state = hass.states.get("switch.smart_plug_switch")
assert state is not None
assert state.state == "off"
# Test turning on
await hass.services.async_call(
"switch", "turn_on", {"entity_id": "switch.smart_plug_switch"}, blocking=True
)
assert len(sent_messages) == 1
msg = sent_messages[0]
assert msg["topic"] == "OpenZWave/1/command/setvalue/"
assert msg["payload"] == {"Value": True, "ValueIDKey": 541671440}
# Feedback on state
switch_msg.decode()
switch_msg.payload["Value"] = True
switch_msg.encode()
receive_message(switch_msg)
await hass.async_block_till_done()
state = hass.states.get("switch.smart_plug_switch")
assert state is not None
assert state.state == "on"
# Test turning off
await hass.services.async_call(
"switch", "turn_off", {"entity_id": "switch.smart_plug_switch"}, blocking=True
)
assert len(sent_messages) == 2
msg = sent_messages[1]
assert msg["topic"] == "OpenZWave/1/command/setvalue/"
assert msg["payload"] == {"Value": False, "ValueIDKey": 541671440}