Implement config flow in the Broadlink integration (#36914)

* Implement config flow in the Broadlink integration

* General improvements to the Broadlink config flow

* Remove unnecessary else after return

* Fix translations

* Rename device to device_entry

* Add tests for the config flow

* Improve docstrings

* Test we do not accept more than one config entry per device

* Improve helpers

* Allow empty packets

* Allow multiple config files for switches related to the same device

* Rename mock_device to mock_api

* General improvements

* Make new attempts before marking the device as unavailable

* Let the name be the template for the entity_id

* Handle OSError

* Test network unavailable in the configuration flow

* Rename lock attribute

* Update manifest.json

* Import devices from platforms

* Test import flow

* Add deprecation warnings

* General improvements

* Rename deprecate to discontinue

* Test device setup

* Add type attribute to mock api

* Test we handle an update failure at startup

* Remove BroadlinkDevice from tests

* Remove device.py from .coveragerc

* Add tests for the config flow

* Add tests for the device

* Test device registry and update listener

* Test MAC address validation

* Add tests for the device

* Extract domains and types to a helper function

* Do not patch integration details

* Add tests for the device

* Set device classes where appropriate

* Set an appropriate connection class

* Do not set device class for custom switches

* Fix tests and improve code readability

* Use RM4 to test authentication errors

* Handle BroadlinkException in the authentication
This commit is contained in:
Felipe Martins Diel authored and GitHub committed 2020-08-20 17:30:41 +02:00
1 parent eb4f667a1a
commit a2c1f08c8c
21 files changed
+2497 -795

No files matched your search

+86 -1
View File
@@ -1 +1,86 @@
"""The tests for broadlink platforms."""
"""Tests for the Broadlink integration."""
from homeassistant.components.broadlink.const import DOMAIN
from tests.async_mock import MagicMock
from tests.common import MockConfigEntry
# Do not edit/remove. Adding is ok.
BROADLINK_DEVICES = {
"Living Room": (
"192.168.0.12",
"34ea34b43b5a",
"RM mini 3",
"Broadlink",
"RM4",
0x5F36,
44017,
10,
),
"Office": (
"192.168.0.13",
"34ea34b43d22",
"RM pro",
"Broadlink",
"RM2",
0x2787,
20025,
7,
),
}
class BroadlinkDevice:
"""Representation of a Broadlink device."""
def __init__(
self, name, host, mac, model, manufacturer, type_, devtype, fwversion, timeout
):
"""Initialize the device."""
self.name: str = name
self.host: str = host
self.mac: str = mac
self.model: str = model
self.manufacturer: str = manufacturer
self.type: str = type_
self.devtype: int = devtype
self.timeout: int = timeout
self.fwversion: int = fwversion
def get_mock_api(self):
"""Return a mock device (API)."""
mock_api = MagicMock()
mock_api.name = self.name
mock_api.host = (self.host, 80)
mock_api.mac = bytes.fromhex(self.mac)
mock_api.model = self.model
mock_api.manufacturer = self.manufacturer
mock_api.type = self.type
mock_api.devtype = self.devtype
mock_api.timeout = self.timeout
mock_api.is_locked = False
mock_api.auth.return_value = True
mock_api.get_fwversion.return_value = self.fwversion
return mock_api
def get_mock_entry(self):
"""Return a mock config entry."""
return MockConfigEntry(
domain=DOMAIN,
unique_id=self.mac,
title=self.name,
data=self.get_entry_data(),
)
def get_entry_data(self):
"""Return entry data."""
return {
"host": self.host,
"mac": self.mac,
"type": self.devtype,
"timeout": self.timeout,
}
def get_device(name):
"""Get a device by name."""
return BroadlinkDevice(name, *BROADLINK_DEVICES[name])
@@ -0,0 +1,748 @@
"""Test the Broadlink config flow."""
import errno
import socket
import broadlink.exceptions as blke
import pytest
from homeassistant import config_entries
from homeassistant.components.broadlink.const import DOMAIN
from . import get_device
from tests.async_mock import call, patch
@pytest.fixture(autouse=True)
def broadlink_setup_fixture():
"""Mock broadlink entry setup."""
with patch(
"homeassistant.components.broadlink.async_setup_entry", return_value=True
):
yield
async def test_flow_user_works(hass):
"""Test a config flow initiated by the user.
Best case scenario with no errors or locks.
"""
device = get_device("Living Room")
mock_api = device.get_mock_api()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["errors"] == {}
with patch("broadlink.discover", return_value=[mock_api]) as mock_discover:
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
assert result["type"] == "form"
assert result["step_id"] == "finish"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"name": device.name},
)
assert result["type"] == "create_entry"
assert result["title"] == device.name
assert result["data"] == device.get_entry_data()
assert mock_discover.call_count == 1
assert mock_api.auth.call_count == 1
async def test_flow_user_already_in_progress(hass):
"""Test we do not accept more than one config flow per device."""
device = get_device("Living Room")
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[device.get_mock_api()]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[device.get_mock_api()]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
assert result["type"] == "abort"
assert result["reason"] == "already_in_progress"
async def test_flow_user_mac_already_configured(hass):
"""Test we do not accept more than one config entry per device.
We need to abort the flow and update the existing entry.
"""
device = get_device("Living Room")
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
device.host = "192.168.1.64"
device.timeout = 20
mock_api = device.get_mock_api()
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
assert dict(mock_entry.data) == device.get_entry_data()
assert mock_api.auth.call_count == 0
async def test_flow_user_invalid_ip_address(hass):
"""Test we handle an invalid IP address in the user step."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", side_effect=OSError(errno.EINVAL, None)):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": "0.0.0.1"},
)
assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["errors"] == {"base": "invalid_host"}
async def test_flow_user_invalid_hostname(hass):
"""Test we handle an invalid hostname in the user step."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", side_effect=OSError(socket.EAI_NONAME, None)):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": "pancakemaster.local"},
)
assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["errors"] == {"base": "invalid_host"}
async def test_flow_user_device_not_found(hass):
"""Test we handle a device not found in the user step."""
device = get_device("Living Room")
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host},
)
assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
async def test_flow_user_network_unreachable(hass):
"""Test we handle a network unreachable in the user step."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", side_effect=OSError(errno.ENETUNREACH, None)):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": "192.168.1.32"},
)
assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
async def test_flow_user_os_error(hass):
"""Test we handle an OS error in the user step."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", side_effect=OSError()):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": "192.168.1.32"},
)
assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["errors"] == {"base": "unknown"}
async def test_flow_auth_authentication_error(hass):
"""Test we handle an authentication error in the auth step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.AuthenticationError()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
assert result["type"] == "form"
assert result["step_id"] == "reset"
assert result["errors"] == {"base": "invalid_auth"}
async def test_flow_auth_device_offline(hass):
"""Test we handle a device offline in the auth step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.DeviceOfflineError()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host},
)
assert result["type"] == "form"
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "cannot_connect"}
async def test_flow_auth_firmware_error(hass):
"""Test we handle a firmware error in the auth step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.BroadlinkException()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host},
)
assert result["type"] == "form"
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "unknown"}
async def test_flow_auth_network_unreachable(hass):
"""Test we handle a network unreachable in the auth step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = OSError(errno.ENETUNREACH, None)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host},
)
assert result["type"] == "form"
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "cannot_connect"}
async def test_flow_auth_os_error(hass):
"""Test we handle an OS error in the auth step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = OSError()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host},
)
assert result["type"] == "form"
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "unknown"}
async def test_flow_reset_works(hass):
"""Test we finish a config flow after a factory reset."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.AuthenticationError()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
with patch("broadlink.discover", return_value=[device.get_mock_api()]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"name": device.name},
)
assert result["type"] == "create_entry"
assert result["title"] == device.name
assert result["data"] == device.get_entry_data()
async def test_flow_unlock_works(hass):
"""Test we finish a config flow with an unlock request."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.is_locked = True
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
assert result["type"] == "form"
assert result["step_id"] == "unlock"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"unlock": True},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"name": device.name},
)
assert result["type"] == "create_entry"
assert result["title"] == device.name
assert result["data"] == device.get_entry_data()
assert mock_api.set_lock.call_args == call(False)
assert mock_api.set_lock.call_count == 1
async def test_flow_unlock_device_offline(hass):
"""Test we handle a device offline in the unlock step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.is_locked = True
mock_api.set_lock.side_effect = blke.DeviceOfflineError
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"unlock": True},
)
assert result["type"] == "form"
assert result["step_id"] == "unlock"
assert result["errors"] == {"base": "cannot_connect"}
async def test_flow_unlock_firmware_error(hass):
"""Test we handle a firmware error in the unlock step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.is_locked = True
mock_api.set_lock.side_effect = blke.BroadlinkException
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"unlock": True},
)
assert result["type"] == "form"
assert result["step_id"] == "unlock"
assert result["errors"] == {"base": "unknown"}
async def test_flow_unlock_network_unreachable(hass):
"""Test we handle a network unreachable in the unlock step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.is_locked = True
mock_api.set_lock.side_effect = OSError(errno.ENETUNREACH, None)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"unlock": True},
)
assert result["type"] == "form"
assert result["step_id"] == "unlock"
assert result["errors"] == {"base": "cannot_connect"}
async def test_flow_unlock_os_error(hass):
"""Test we handle an OS error in the unlock step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.is_locked = True
mock_api.set_lock.side_effect = OSError()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"unlock": True},
)
assert result["type"] == "form"
assert result["step_id"] == "unlock"
assert result["errors"] == {"base": "unknown"}
async def test_flow_do_not_unlock(hass):
"""Test we do not unlock the device if the user does not want to."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.is_locked = True
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"unlock": False},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"name": device.name},
)
assert result["type"] == "create_entry"
assert result["title"] == device.name
assert result["data"] == device.get_entry_data()
assert mock_api.set_lock.call_count == 0
async def test_flow_import_works(hass):
"""Test an import flow."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
with patch("broadlink.discover", return_value=[mock_api]) as mock_discover:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"host": device.host},
)
assert result["type"] == "form"
assert result["step_id"] == "finish"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"name": device.name},
)
assert result["type"] == "create_entry"
assert result["title"] == device.name
assert result["data"]["host"] == device.host
assert result["data"]["mac"] == device.mac
assert result["data"]["type"] == device.devtype
assert mock_api.auth.call_count == 1
assert mock_discover.call_count == 1
async def test_flow_import_already_in_progress(hass):
"""Test we do not import more than one flow per device."""
device = get_device("Living Room")
data = {"host": device.host}
with patch("broadlink.discover", return_value=[device.get_mock_api()]):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=data
)
with patch("broadlink.discover", return_value=[device.get_mock_api()]):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=data
)
assert result["type"] == "abort"
assert result["reason"] == "already_in_progress"
async def test_flow_import_host_already_configured(hass):
"""Test we do not import a host that is already configured."""
device = get_device("Living Room")
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
mock_api = device.get_mock_api()
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"host": device.host},
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
async def test_flow_import_mac_already_configured(hass):
"""Test we do not import more than one config entry per device.
We need to abort the flow and update the existing entry.
"""
device = get_device("Living Room")
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
device.host = "192.168.1.16"
mock_api = device.get_mock_api()
with patch("broadlink.discover", return_value=[mock_api]):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"host": device.host},
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
assert mock_entry.data["host"] == device.host
assert mock_entry.data["mac"] == device.mac
assert mock_entry.data["type"] == device.devtype
assert mock_api.auth.call_count == 0
async def test_flow_import_device_not_found(hass):
"""Test we handle a device not found in the import step."""
with patch("broadlink.discover", return_value=[]):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"host": "192.168.1.32"},
)
assert result["type"] == "abort"
assert result["reason"] == "cannot_connect"
async def test_flow_import_invalid_ip_address(hass):
"""Test we handle an invalid IP address in the import step."""
with patch("broadlink.discover", side_effect=OSError(errno.EINVAL, None)):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"host": "0.0.0.1"},
)
assert result["type"] == "abort"
assert result["reason"] == "invalid_host"
async def test_flow_import_invalid_hostname(hass):
"""Test we handle an invalid hostname in the import step."""
with patch("broadlink.discover", side_effect=OSError(socket.EAI_NONAME, None)):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"host": "hotdog.local"},
)
assert result["type"] == "abort"
assert result["reason"] == "invalid_host"
async def test_flow_import_network_unreachable(hass):
"""Test we handle a network unreachable in the import step."""
with patch("broadlink.discover", side_effect=OSError(errno.ENETUNREACH, None)):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"host": "192.168.1.64"},
)
assert result["type"] == "abort"
assert result["reason"] == "cannot_connect"
async def test_flow_import_os_error(hass):
"""Test we handle an OS error in the import step."""
with patch("broadlink.discover", side_effect=OSError()):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"host": "192.168.1.64"},
)
assert result["type"] == "abort"
assert result["reason"] == "unknown"
async def test_flow_reauth_works(hass):
"""Test a reauthentication flow."""
device = get_device("Living Room")
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.AuthenticationError()
data = {"name": device.name, **device.get_entry_data()}
with patch("broadlink.gendevice", return_value=mock_api):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth"}, data=data
)
assert result["type"] == "form"
assert result["step_id"] == "reset"
mock_api = device.get_mock_api()
with patch("broadlink.discover", return_value=[mock_api]) as mock_discover:
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
assert dict(mock_entry.data) == device.get_entry_data()
assert mock_api.auth.call_count == 1
assert mock_discover.call_count == 1
async def test_flow_reauth_invalid_host(hass):
"""Test we do not accept an invalid host for reauthentication.
The MAC address cannot change.
"""
device = get_device("Living Room")
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.AuthenticationError()
data = {"name": device.name, **device.get_entry_data()}
with patch("broadlink.gendevice", return_value=mock_api):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth"}, data=data
)
device.mac = get_device("Office").mac
mock_api = device.get_mock_api()
with patch("broadlink.discover", return_value=[mock_api]) as mock_discover:
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["errors"] == {"base": "invalid_host"}
assert mock_discover.call_count == 1
assert mock_api.auth.call_count == 0
async def test_flow_reauth_valid_host(hass):
"""Test we accept a valid host for reauthentication.
The hostname/IP address may change. We need to update the entry.
"""
device = get_device("Living Room")
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.AuthenticationError()
data = {"name": device.name, **device.get_entry_data()}
with patch("broadlink.gendevice", return_value=mock_api):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth"}, data=data
)
device.host = "192.168.1.128"
mock_api = device.get_mock_api()
with patch("broadlink.discover", return_value=[mock_api]) as mock_discover:
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"host": device.host, "timeout": device.timeout},
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
assert mock_entry.data["host"] == device.host
assert mock_discover.call_count == 1
assert mock_api.auth.call_count == 1
+389
View File
@@ -0,0 +1,389 @@
"""Tests for Broadlink devices."""
import broadlink.exceptions as blke
from homeassistant.components.broadlink.const import DOMAIN
from homeassistant.components.broadlink.device import get_domains
from homeassistant.config_entries import (
ENTRY_STATE_LOADED,
ENTRY_STATE_NOT_LOADED,
ENTRY_STATE_SETUP_ERROR,
ENTRY_STATE_SETUP_RETRY,
)
from homeassistant.helpers.entity_registry import async_entries_for_device
from . import get_device
from tests.async_mock import patch
from tests.common import mock_device_registry, mock_registry
async def test_device_setup(hass):
"""Test a successful setup."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward, patch.object(
hass.config_entries.flow, "async_init"
) as mock_init:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_LOADED
assert mock_api.auth.call_count == 1
assert mock_api.get_fwversion.call_count == 1
forward_entries = {c[1][1] for c in mock_forward.mock_calls}
domains = get_domains(mock_api.type)
assert mock_forward.call_count == len(domains)
assert forward_entries == domains
assert mock_init.call_count == 0
async def test_device_setup_authentication_error(hass):
"""Test we handle an authentication error."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.AuthenticationError()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward, patch.object(
hass.config_entries.flow, "async_init"
) as mock_init:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_SETUP_ERROR
assert mock_api.auth.call_count == 1
assert mock_forward.call_count == 0
assert mock_init.call_count == 1
assert mock_init.mock_calls[0][2]["context"]["source"] == "reauth"
assert mock_init.mock_calls[0][2]["data"] == {
"name": device.name,
**device.get_entry_data(),
}
async def test_device_setup_device_offline(hass):
"""Test we handle a device offline."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.DeviceOfflineError()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward, patch.object(
hass.config_entries.flow, "async_init"
) as mock_init:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_SETUP_RETRY
assert mock_api.auth.call_count == 1
assert mock_forward.call_count == 0
assert mock_init.call_count == 0
async def test_device_setup_os_error(hass):
"""Test we handle an OS error."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = OSError()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward, patch.object(
hass.config_entries.flow, "async_init"
) as mock_init:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_SETUP_RETRY
assert mock_api.auth.call_count == 1
assert mock_forward.call_count == 0
assert mock_init.call_count == 0
async def test_device_setup_broadlink_exception(hass):
"""Test we handle a Broadlink exception."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.BroadlinkException()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward, patch.object(
hass.config_entries.flow, "async_init"
) as mock_init:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_SETUP_ERROR
assert mock_api.auth.call_count == 1
assert mock_forward.call_count == 0
assert mock_init.call_count == 0
async def test_device_setup_update_device_offline(hass):
"""Test we handle a device offline in the update step."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.check_sensors.side_effect = blke.DeviceOfflineError()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward, patch.object(
hass.config_entries.flow, "async_init"
) as mock_init:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_SETUP_RETRY
assert mock_api.auth.call_count == 1
assert mock_api.check_sensors.call_count == 1
assert mock_forward.call_count == 0
assert mock_init.call_count == 0
async def test_device_setup_update_authorization_error(hass):
"""Test we handle an authorization error in the update step."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.check_sensors.side_effect = (blke.AuthorizationError(), None)
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward, patch.object(
hass.config_entries.flow, "async_init"
) as mock_init:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_LOADED
assert mock_api.auth.call_count == 2
assert mock_api.check_sensors.call_count == 2
forward_entries = {c[1][1] for c in mock_forward.mock_calls}
domains = get_domains(mock_api.type)
assert mock_forward.call_count == len(domains)
assert forward_entries == domains
assert mock_init.call_count == 0
async def test_device_setup_update_authentication_error(hass):
"""Test we handle an authentication error in the update step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.check_sensors.side_effect = blke.AuthorizationError()
mock_api.auth.side_effect = (None, blke.AuthenticationError())
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward, patch.object(
hass.config_entries.flow, "async_init"
) as mock_init:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_SETUP_RETRY
assert mock_api.auth.call_count == 2
assert mock_api.check_sensors.call_count == 1
assert mock_forward.call_count == 0
assert mock_init.call_count == 1
assert mock_init.mock_calls[0][2]["context"]["source"] == "reauth"
assert mock_init.mock_calls[0][2]["data"] == {
"name": device.name,
**device.get_entry_data(),
}
async def test_device_setup_update_broadlink_exception(hass):
"""Test we handle a Broadlink exception in the update step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.check_sensors.side_effect = blke.BroadlinkException()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward, patch.object(
hass.config_entries.flow, "async_init"
) as mock_init:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_SETUP_RETRY
assert mock_api.auth.call_count == 1
assert mock_api.check_sensors.call_count == 1
assert mock_forward.call_count == 0
assert mock_init.call_count == 0
async def test_device_setup_get_fwversion_broadlink_exception(hass):
"""Test we load the device even if we cannot read the firmware version."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.get_fwversion.side_effect = blke.BroadlinkException()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_LOADED
forward_entries = {c[1][1] for c in mock_forward.mock_calls}
domains = get_domains(mock_api.type)
assert mock_forward.call_count == len(domains)
assert forward_entries == domains
async def test_device_setup_get_fwversion_os_error(hass):
"""Test we load the device even if we cannot read the firmware version."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.get_fwversion.side_effect = OSError()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward:
await hass.config_entries.async_setup(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_LOADED
forward_entries = {c[1][1] for c in mock_forward.mock_calls}
domains = get_domains(mock_api.type)
assert mock_forward.call_count == len(domains)
assert forward_entries == domains
async def test_device_setup_registry(hass):
"""Test we register the device and the entries correctly."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
with patch("broadlink.gendevice", return_value=mock_api):
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
assert len(device_registry.devices) == 1
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_entry.unique_id)}, set()
)
assert device_entry.identifiers == {(DOMAIN, device.mac)}
assert device_entry.name == device.name
assert device_entry.model == device.model
assert device_entry.manufacturer == device.manufacturer
assert device_entry.sw_version == device.fwversion
for entry in async_entries_for_device(entity_registry, device_entry.id):
assert entry.original_name.startswith(device.name)
async def test_device_unload_works(hass):
"""Test we unload the device."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
):
await hass.config_entries.async_setup(mock_entry.entry_id)
with patch.object(
hass.config_entries, "async_forward_entry_unload", return_value=True
) as mock_forward:
await hass.config_entries.async_unload(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_NOT_LOADED
forward_entries = {c[1][1] for c in mock_forward.mock_calls}
domains = get_domains(mock_api.type)
assert mock_forward.call_count == len(domains)
assert forward_entries == domains
async def test_device_unload_authentication_error(hass):
"""Test we unload a device that failed the authentication step."""
device = get_device("Living Room")
mock_api = device.get_mock_api()
mock_api.auth.side_effect = blke.AuthenticationError()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
), patch.object(hass.config_entries.flow, "async_init"):
await hass.config_entries.async_setup(mock_entry.entry_id)
with patch.object(
hass.config_entries, "async_forward_entry_unload", return_value=True
) as mock_forward:
await hass.config_entries.async_unload(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_NOT_LOADED
assert mock_forward.call_count == 0
async def test_device_unload_update_failed(hass):
"""Test we unload a device that failed the update step."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.check_sensors.side_effect = blke.DeviceOfflineError()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
with patch("broadlink.gendevice", return_value=mock_api), patch.object(
hass.config_entries, "async_forward_entry_setup"
):
await hass.config_entries.async_setup(mock_entry.entry_id)
with patch.object(
hass.config_entries, "async_forward_entry_unload", return_value=True
) as mock_forward:
await hass.config_entries.async_unload(mock_entry.entry_id)
assert mock_entry.state == ENTRY_STATE_NOT_LOADED
assert mock_forward.call_count == 0
async def test_device_update_listener(hass):
"""Test we update device and entity registry when the entry is renamed."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_entry = device.get_mock_entry()
mock_entry.add_to_hass(hass)
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
with patch("broadlink.gendevice", return_value=mock_api):
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
hass.config_entries.async_update_entry(mock_entry, title="New Name")
await hass.async_block_till_done()
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_entry.unique_id)}, set()
)
assert device_entry.name == "New Name"
for entry in async_entries_for_device(entity_registry, device_entry.id):
assert entry.original_name.startswith("New Name")
@@ -0,0 +1,54 @@
"""Tests for Broadlink helper functions."""
import pytest
import voluptuous as vol
from homeassistant.components.broadlink.helpers import data_packet, mac_address
async def test_padding(hass):
"""Verify that non padding strings are allowed."""
assert data_packet("Jg") == b"&"
assert data_packet("Jg=") == b"&"
assert data_packet("Jg==") == b"&"
async def test_valid_mac_address(hass):
"""Test we convert a valid MAC address to bytes."""
valid = [
"A1B2C3D4E5F6",
"a1b2c3d4e5f6",
"A1B2-C3D4-E5F6",
"a1b2-c3d4-e5f6",
"A1B2.C3D4.E5F6",
"a1b2.c3d4.e5f6",
"A1-B2-C3-D4-E5-F6",
"a1-b2-c3-d4-e5-f6",
"A1:B2:C3:D4:E5:F6",
"a1:b2:c3:d4:e5:f6",
]
for mac in valid:
assert mac_address(mac) == b"\xa1\xb2\xc3\xd4\xe5\xf6"
async def test_invalid_mac_address(hass):
"""Test we do not accept an invalid MAC address."""
invalid = [
None,
123,
["a", "b", "c"],
{"abc": "def"},
"a1b2c3d4e5f",
"a1b2.c3d4.e5f",
"a1-b2-c3-d4-e5-f",
"a1b2c3d4e5f66",
"a1b2.c3d4.e5f66",
"a1-b2-c3-d4-e5-f66",
"a1b2c3d4e5fg",
"a1b2.c3d4.e5fg",
"a1-b2-c3-d4-e5-fg",
"a1b.2c3d4.e5fg",
"a1b-2-c3-d4-e5-fg",
]
for mac in invalid:
with pytest.raises((ValueError, vol.Invalid)):
mac_address(mac)
-102
View File
@@ -1,102 +0,0 @@
"""The tests for the broadlink component."""
from base64 import b64decode
from datetime import timedelta
import pytest
from homeassistant.components.broadlink import async_setup_service, data_packet
from homeassistant.components.broadlink.const import DOMAIN, SERVICE_LEARN, SERVICE_SEND
from homeassistant.components.broadlink.device import BroadlinkDevice
from homeassistant.util.dt import utcnow
from tests.async_mock import MagicMock, call, patch
DUMMY_IR_PACKET = (
"JgBGAJKVETkRORA6ERQRFBEUERQRFBE5ETkQOhAVEBUQFREUEBUQ"
"OhEUERQRORE5EBURFBA6EBUQOhE5EBUQFRA6EDoRFBEADQUAAA=="
)
DUMMY_HOST = "192.168.0.2"
@pytest.fixture(autouse=True)
def dummy_broadlink():
"""Mock broadlink module so we don't have that dependency on tests."""
broadlink = MagicMock()
with patch.dict("sys.modules", {"broadlink": broadlink}):
yield broadlink
async def test_padding(hass):
"""Verify that non padding strings are allowed."""
assert data_packet("Jg") == b"&"
assert data_packet("Jg=") == b"&"
assert data_packet("Jg==") == b"&"
async def test_send(hass):
"""Test send service."""
mock_api = MagicMock()
mock_api.send_data.return_value = None
device = BroadlinkDevice(hass, mock_api)
await async_setup_service(hass, DUMMY_HOST, device)
await hass.services.async_call(
DOMAIN, SERVICE_SEND, {"host": DUMMY_HOST, "packet": (DUMMY_IR_PACKET)}
)
await hass.async_block_till_done()
assert device.api.send_data.call_count == 1
assert device.api.send_data.call_args == call(b64decode(DUMMY_IR_PACKET))
async def test_learn(hass):
"""Test learn service."""
mock_api = MagicMock()
mock_api.enter_learning.return_value = None
mock_api.check_data.return_value = b64decode(DUMMY_IR_PACKET)
device = BroadlinkDevice(hass, mock_api)
with patch.object(
hass.components.persistent_notification, "async_create"
) as mock_create:
await async_setup_service(hass, DUMMY_HOST, device)
await hass.services.async_call(DOMAIN, SERVICE_LEARN, {"host": DUMMY_HOST})
await hass.async_block_till_done()
assert device.api.enter_learning.call_count == 1
assert device.api.enter_learning.call_args == call()
assert mock_create.call_count == 1
assert mock_create.call_args == call(
f"Received packet is: {DUMMY_IR_PACKET}", title="Broadlink switch"
)
async def test_learn_timeout(hass):
"""Test learn service."""
mock_api = MagicMock()
mock_api.enter_learning.return_value = None
mock_api.check_data.return_value = None
device = BroadlinkDevice(hass, mock_api)
await async_setup_service(hass, DUMMY_HOST, device)
now = utcnow()
with patch.object(
hass.components.persistent_notification, "async_create"
) as mock_create, patch("homeassistant.components.broadlink.utcnow") as mock_utcnow:
mock_utcnow.side_effect = [now, now + timedelta(20)]
await hass.services.async_call(DOMAIN, SERVICE_LEARN, {"host": DUMMY_HOST})
await hass.async_block_till_done()
assert device.api.enter_learning.call_count == 1
assert device.api.enter_learning.call_args == call()
assert mock_create.call_count == 1
assert mock_create.call_args == call(
"No signal was received", title="Broadlink switch"
)