init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
"""Tests for the wemo component."""
import pytest
pytest.register_assert_rewrite("tests.components.wemo.entity_test_helpers")

View File

@@ -0,0 +1,160 @@
"""Fixtures for pywemo."""
from collections.abc import Generator
import contextlib
from unittest.mock import MagicMock, create_autospec, patch
import pytest
import pywemo
from homeassistant.components.wemo import CONF_DISCOVERY, CONF_STATIC
from homeassistant.components.wemo.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
MOCK_HOST = "127.0.0.1"
MOCK_PORT = 50000
MOCK_NAME = "WemoDeviceName"
MOCK_SERIAL_NUMBER = "WemoSerialNumber"
MOCK_FIRMWARE_VERSION = "WeMo_WW_2.00.XXXXX.PVT-OWRT"
MOCK_INSIGHT_CURRENT_WATTS = 0.01
MOCK_INSIGHT_TODAY_KWH = 3.33
MOCK_INSIGHT_STATE_THRESHOLD_POWER = 8.0
@pytest.fixture(name="pywemo_model")
def pywemo_model_fixture() -> str:
"""Fixture containing a pywemo class name used by pywemo_device_fixture."""
return "LightSwitch"
@pytest.fixture(name="pywemo_registry", autouse=True)
def async_pywemo_registry_fixture() -> Generator[MagicMock]:
"""Fixture for SubscriptionRegistry instances."""
registry = create_autospec(pywemo.SubscriptionRegistry, instance=True)
registry.callbacks = {}
def on_func(device, type_filter, callback):
registry.callbacks[device.name] = callback
registry.on.side_effect = on_func
registry.is_subscribed.return_value = False
with patch("pywemo.SubscriptionRegistry", return_value=registry):
yield registry
@pytest.fixture(name="pywemo_discovery_responder", autouse=True)
def pywemo_discovery_responder_fixture():
"""Fixture for the DiscoveryResponder instance."""
with patch("pywemo.ssdp.DiscoveryResponder", autospec=True):
yield
@contextlib.contextmanager
def create_pywemo_device(
pywemo_registry: MagicMock, pywemo_model: str
) -> pywemo.WeMoDevice:
"""Create a WeMoDevice instance."""
cls = getattr(pywemo, pywemo_model)
device = create_autospec(cls, instance=True)
device.host = MOCK_HOST
device.port = MOCK_PORT
device.name = MOCK_NAME
device.serial_number = MOCK_SERIAL_NUMBER
device.model_name = pywemo_model.replace("LongPress", "")
device.model = device.model_name
device.udn = f"uuid:{device.model_name}-1_0-{device.serial_number}"
device.firmware_version = MOCK_FIRMWARE_VERSION
device.get_state.return_value = 0 # Default to Off
device.supports_long_press.return_value = cls.supports_long_press()
if issubclass(cls, pywemo.Insight):
device.standby_state = pywemo.StandbyState.OFF
device.current_power_watts = MOCK_INSIGHT_CURRENT_WATTS
device.today_kwh = MOCK_INSIGHT_TODAY_KWH
device.threshold_power_watts = MOCK_INSIGHT_STATE_THRESHOLD_POWER
device.on_for = 1234
device.today_on_time = 5678
device.total_on_time = 9012
if issubclass(cls, pywemo.Maker):
device.has_sensor = 1
device.sensor_state = 1
device.switch_mode = 1
device.switch_state = 0
url = f"http://{MOCK_HOST}:{MOCK_PORT}/setup.xml"
with (
patch("pywemo.setup_url_for_address", return_value=url),
patch("pywemo.discovery.device_from_description", return_value=device),
):
yield device
@pytest.fixture(name="pywemo_device")
def pywemo_device_fixture(
pywemo_registry: MagicMock, pywemo_model: str
) -> Generator[pywemo.WeMoDevice]:
"""Fixture for WeMoDevice instances."""
with create_pywemo_device(pywemo_registry, pywemo_model) as pywemo_device:
yield pywemo_device
@pytest.fixture(name="pywemo_dli_device")
def pywemo_dli_device_fixture(
pywemo_registry: MagicMock, pywemo_model: str
) -> Generator[pywemo.WeMoDevice]:
"""Fixture for Digital Loggers emulated instances."""
with create_pywemo_device(pywemo_registry, pywemo_model) as pywemo_dli_device:
pywemo_dli_device.model_name = "DLI emulated Belkin Socket"
pywemo_dli_device.serial_number = "1234567891"
yield pywemo_dli_device
@pytest.fixture(name="wemo_entity_suffix")
def wemo_entity_suffix_fixture() -> str:
"""Fixture to select a specific entity for wemo_entity."""
return ""
async def async_create_wemo_entity(
hass: HomeAssistant, pywemo_device: pywemo.WeMoDevice, wemo_entity_suffix: str
) -> er.RegistryEntry | None:
"""Create a hass entity for a wemo device."""
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_DISCOVERY: False,
CONF_STATIC: [f"{MOCK_HOST}:{MOCK_PORT}"],
},
},
)
await hass.async_block_till_done()
entity_registry = er.async_get(hass)
for entry in entity_registry.entities.values():
if entry.entity_id.endswith(wemo_entity_suffix or pywemo_device.name.lower()):
return entry
return None
@pytest.fixture(name="wemo_entity")
async def async_wemo_entity_fixture(
hass: HomeAssistant, pywemo_device: pywemo.WeMoDevice, wemo_entity_suffix: str
) -> er.RegistryEntry | None:
"""Fixture for a Wemo entity in hass."""
return await async_create_wemo_entity(hass, pywemo_device, wemo_entity_suffix)
@pytest.fixture(name="wemo_dli_entity")
async def async_wemo_dli_entity_fixture(
hass: HomeAssistant, pywemo_dli_device: pywemo.WeMoDevice, wemo_entity_suffix: str
) -> er.RegistryEntry | None:
"""Fixture for a Wemo entity in hass."""
return await async_create_wemo_entity(hass, pywemo_dli_device, wemo_entity_suffix)

View File

@@ -0,0 +1,205 @@
"""Test cases that are in common among wemo platform modules.
This is not a test module. These test methods are used by the platform test modules.
"""
import asyncio
from collections.abc import Callable, Coroutine
import threading
from typing import Any
import pywemo
from homeassistant.components.homeassistant import DOMAIN as HA_DOMAIN
from homeassistant.components.wemo.coordinator import async_get_coordinator
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
def _perform_registry_callback(coordinator):
"""Return a callable method to trigger a state callback from the device."""
async def async_callback():
await coordinator.hass.async_add_executor_job(
coordinator.subscription_callback, coordinator.wemo, "", ""
)
return async_callback
def _perform_async_update(coordinator):
"""Return a callable method to cause hass to update the state of the entity."""
async def async_callback():
await coordinator._async_update_data()
return async_callback
async def _async_multiple_call_helper(
hass: HomeAssistant,
pywemo_device: pywemo.WeMoDevice,
call1: Callable[[], Coroutine[Any, Any, None]],
call2: Callable[[], Coroutine[Any, Any, None]],
) -> None:
"""Create two calls (call1 & call2) in parallel; verify only one polls the device.
There should only be one poll on the device at a time. Any parallel updates
# that happen at the same time should be ignored. This is verified by blocking
in the get_state method. The polling method should only be called once as a
result of calling call1 & call2 simultaneously.
"""
event = threading.Event()
waiting = asyncio.Event()
call_count = 0
def get_state(force_update=None):
if force_update is None:
return
nonlocal call_count
call_count += 1
hass.loop.call_soon_threadsafe(waiting.set)
event.wait()
# Danger! Do not use a Mock side_effect here. The test will deadlock. When
# called though hass.async_add_executor_job, Mock objects !surprisingly!
# run in the same thread as the asyncio event loop.
# https://github.com/home-assistant/core/blob/1ba5c1c9fb1e380549cb655986b5f4d3873d7352/tests/common.py#L179
pywemo_device.get_state = get_state
# One of these two calls will block on `event`. The other will return right
# away because the `_update_lock` is held.
done, pending = await asyncio.wait(
[asyncio.create_task(call1()), asyncio.create_task(call2())],
return_when=asyncio.FIRST_COMPLETED,
)
_ = [d.result() for d in done] # Allow any exceptions to be raised.
# Allow the blocked call to return.
await waiting.wait()
event.set()
if pending:
done, _ = await asyncio.wait(pending)
_ = [d.result() for d in done] # Allow any exceptions to be raised.
# Make sure the state update only happened once.
assert call_count == 1
async def test_async_update_locked_callback_and_update(
hass: HomeAssistant, pywemo_device: pywemo.WeMoDevice, wemo_entity: er.RegistryEntry
) -> None:
"""Test that a callback and a state update request can't both happen at the same time.
When a state update is received via a callback from the device at the same time
as hass is calling `async_update`, verify that only one of the updates proceeds.
"""
coordinator = async_get_coordinator(hass, wemo_entity.device_id)
await async_setup_component(hass, HA_DOMAIN, {})
callback = _perform_registry_callback(coordinator)
update = _perform_async_update(coordinator)
await _async_multiple_call_helper(hass, pywemo_device, callback, update)
async def test_async_update_locked_multiple_updates(
hass: HomeAssistant, pywemo_device: pywemo.WeMoDevice, wemo_entity: er.RegistryEntry
) -> None:
"""Test that two hass async_update state updates do not proceed at the same time."""
coordinator = async_get_coordinator(hass, wemo_entity.device_id)
await async_setup_component(hass, HA_DOMAIN, {})
update = _perform_async_update(coordinator)
await _async_multiple_call_helper(hass, pywemo_device, update, update)
async def test_async_update_locked_multiple_callbacks(
hass: HomeAssistant, pywemo_device: pywemo.WeMoDevice, wemo_entity: er.RegistryEntry
) -> None:
"""Test that two device callback state updates do not proceed at the same time."""
coordinator = async_get_coordinator(hass, wemo_entity.device_id)
await async_setup_component(hass, HA_DOMAIN, {})
callback = _perform_registry_callback(coordinator)
await _async_multiple_call_helper(hass, pywemo_device, callback, callback)
async def test_avaliable_after_update(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity, domain
) -> None:
"""Test the availability when an On call fails and after an update.
This test expects that the pywemo_device Mock has been setup to raise an
ActionException when the SERVICE_TURN_ON method is called and that the
state will be On after the update.
"""
await hass.services.async_call(
domain,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_UNAVAILABLE
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
async def test_turn_off_state(hass: HomeAssistant, wemo_entity, domain) -> None:
"""Test that the device state is updated after turning off."""
await hass.services.async_call(
domain,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
class EntityTestHelpers:
"""Common state update helpers."""
async def test_async_update_locked_multiple_updates(
self,
hass: HomeAssistant,
pywemo_device: pywemo.WeMoDevice,
wemo_entity: er.RegistryEntry,
) -> None:
"""Test that two hass async_update state updates do not proceed at the same time."""
await test_async_update_locked_multiple_updates(
hass, pywemo_device, wemo_entity
)
async def test_async_update_locked_multiple_callbacks(
self,
hass: HomeAssistant,
pywemo_device: pywemo.WeMoDevice,
wemo_entity: er.RegistryEntry,
) -> None:
"""Test that two device callback state updates do not proceed at the same time."""
await test_async_update_locked_multiple_callbacks(
hass, pywemo_device, wemo_entity
)
async def test_async_update_locked_callback_and_update(
self,
hass: HomeAssistant,
pywemo_device: pywemo.WeMoDevice,
wemo_entity: er.RegistryEntry,
) -> None:
"""Test that a callback and a state update request can't both happen at the same time.
When a state update is received via a callback from the device at the same time
as hass is calling `async_update`, verify that only one of the updates proceeds.
"""
await test_async_update_locked_callback_and_update(
hass, pywemo_device, wemo_entity
)

View File

@@ -0,0 +1,156 @@
"""Tests for the Wemo binary_sensor entity."""
import pytest
import pywemo
from pywemo import StandbyState
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.wemo.binary_sensor import (
InsightBinarySensor,
MakerBinarySensor,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from .entity_test_helpers import EntityTestHelpers
class TestMotion(EntityTestHelpers):
"""Test for the pyWeMo Motion device."""
@pytest.fixture
def pywemo_model(self):
"""Pywemo Motion models use the binary_sensor platform."""
return "Motion"
async def test_binary_sensor_registry_state_callback(
self,
hass: HomeAssistant,
pywemo_registry: pywemo.SubscriptionRegistry,
pywemo_device: pywemo.WeMoDevice,
wemo_entity: er.RegistryEntry,
) -> None:
"""Verify that the binary_sensor receives state updates from the registry."""
# On state.
pywemo_device.get_state.return_value = 1
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Off state.
pywemo_device.get_state.return_value = 0
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
async def test_binary_sensor_update_entity(
self,
hass: HomeAssistant,
pywemo_registry: pywemo.SubscriptionRegistry,
pywemo_device: pywemo.WeMoDevice,
wemo_entity: er.RegistryEntry,
) -> None:
"""Verify that the binary_sensor performs state updates."""
await async_setup_component(hass, HA_DOMAIN, {})
# On state.
pywemo_device.get_state.return_value = 1
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Off state.
pywemo_device.get_state.return_value = 0
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
class TestMaker(EntityTestHelpers):
"""Test for the pyWeMo Maker device."""
@pytest.fixture
def pywemo_model(self):
"""Pywemo Motion models use the binary_sensor platform."""
return "Maker"
@pytest.fixture
def wemo_entity_suffix(self):
"""Select the MakerBinarySensor entity."""
return MakerBinarySensor._name_suffix.lower()
async def test_registry_state_callback(
self,
hass: HomeAssistant,
pywemo_registry: pywemo.SubscriptionRegistry,
pywemo_device: pywemo.WeMoDevice,
wemo_entity: er.RegistryEntry,
) -> None:
"""Verify that the binary_sensor receives state updates from the registry."""
# On state.
pywemo_device.sensor_state = 0
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Off state.
pywemo_device.sensor_state = 1
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
class TestInsight(EntityTestHelpers):
"""Test for the pyWeMo Insight device."""
@pytest.fixture
def pywemo_model(self):
"""Pywemo Motion models use the binary_sensor platform."""
return "Insight"
@pytest.fixture
def wemo_entity_suffix(self):
"""Select the InsightBinarySensor entity."""
return InsightBinarySensor._name_suffix.lower()
async def test_registry_state_callback(
self,
hass: HomeAssistant,
pywemo_registry: pywemo.SubscriptionRegistry,
pywemo_device: pywemo.WeMoDevice,
wemo_entity: er.RegistryEntry,
) -> None:
"""Verify that the binary_sensor receives state updates from the registry."""
# On state.
pywemo_device.get_state.return_value = 1
pywemo_device.standby_state = StandbyState.ON
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Standby (Off) state.
pywemo_device.get_state.return_value = 1
pywemo_device.standby_state = StandbyState.STANDBY
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
# Off state.
pywemo_device.get_state.return_value = 0
pywemo_device.standby_state = StandbyState.OFF
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF

View File

@@ -0,0 +1,63 @@
"""Tests for Wemo config flow."""
from dataclasses import asdict
from homeassistant.components.wemo.const import DOMAIN
from homeassistant.components.wemo.coordinator import Options
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry, patch
async def test_not_discovered(hass: HomeAssistant) -> None:
"""Test setting up with no devices discovered."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
with patch("homeassistant.components.wemo.config_flow.pywemo") as mock_pywemo:
mock_pywemo.discover_devices.return_value = []
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"
async def test_options(hass: HomeAssistant) -> None:
"""Test updating options."""
options = Options(enable_subscription=False, enable_long_press=False)
entry = MockConfigEntry(domain=DOMAIN, title="Wemo")
entry.add_to_hass(hass)
result = await hass.config_entries.options.async_init(entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"], user_input=asdict(options)
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert Options(**result["data"]) == options
async def test_invalid_options(hass: HomeAssistant) -> None:
"""Test invalid option combinations."""
entry = MockConfigEntry(domain=DOMAIN, title="Wemo")
entry.add_to_hass(hass)
result = await hass.config_entries.options.async_init(entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
# enable_subscription must be True if enable_long_press is True (default).
result = await hass.config_entries.options.async_configure(
result["flow_id"], user_input={"enable_subscription": False}
)
assert result["errors"] == {
"enable_subscription": "long_press_requires_subscription"
}

View File

@@ -0,0 +1,267 @@
"""Tests for wemo_device.py."""
import asyncio
from dataclasses import asdict
from datetime import timedelta
from unittest.mock import _Call, call, patch
import pytest
import pywemo
from pywemo.exceptions import ActionException, PyWeMoException
from pywemo.subscribe import EVENT_TYPE_LONG_PRESS
from homeassistant import runner
from homeassistant.components.wemo import CONF_DISCOVERY, CONF_STATIC
from homeassistant.components.wemo.const import DOMAIN, WEMO_SUBSCRIPTION_EVENT
from homeassistant.components.wemo.coordinator import Options, async_get_coordinator
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.update_coordinator import UpdateFailed
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow
from .conftest import MOCK_FIRMWARE_VERSION, MOCK_HOST, MOCK_SERIAL_NUMBER
from tests.common import async_fire_time_changed
asyncio.set_event_loop_policy(runner.HassEventLoopPolicy(True))
@pytest.fixture
def pywemo_model():
"""Pywemo LightSwitch models use the switch platform."""
return "LightSwitchLongPress"
async def test_async_register_device_longpress_fails(
hass: HomeAssistant, pywemo_device, device_registry: dr.DeviceRegistry
) -> None:
"""Device is still registered if ensure_long_press_virtual_device fails."""
with patch.object(pywemo_device, "ensure_long_press_virtual_device") as elp:
elp.side_effect = PyWeMoException
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_DISCOVERY: False,
CONF_STATIC: [MOCK_HOST],
},
},
)
await hass.async_block_till_done()
device_entries = list(device_registry.devices.values())
assert len(device_entries) == 1
device = async_get_coordinator(hass, device_entries[0].id)
assert device.supports_long_press is False
async def test_long_press_event(
hass: HomeAssistant, pywemo_registry, wemo_entity
) -> None:
"""Device fires a long press event."""
device = async_get_coordinator(hass, wemo_entity.device_id)
got_event = asyncio.Event()
event_data = {}
@callback
def async_event_received(event):
nonlocal event_data
event_data = event.data
got_event.set()
hass.bus.async_listen_once(WEMO_SUBSCRIPTION_EVENT, async_event_received)
await hass.async_add_executor_job(
pywemo_registry.callbacks[device.wemo.name],
device.wemo,
EVENT_TYPE_LONG_PRESS,
"testing_params",
)
async with asyncio.timeout(8):
await got_event.wait()
assert event_data == {
"device_id": wemo_entity.device_id,
"name": device.wemo.name,
"params": "testing_params",
"type": EVENT_TYPE_LONG_PRESS,
"unique_id": device.wemo.serial_number,
}
async def test_subscription_callback(
hass: HomeAssistant, pywemo_registry, wemo_entity
) -> None:
"""Device processes a registry subscription callback."""
device = async_get_coordinator(hass, wemo_entity.device_id)
device.last_update_success = False
got_callback = asyncio.Event()
@callback
def async_received_callback():
got_callback.set()
device.async_add_listener(async_received_callback)
await hass.async_add_executor_job(
pywemo_registry.callbacks[device.wemo.name], device.wemo, "", ""
)
async with asyncio.timeout(8):
await got_callback.wait()
assert device.last_update_success
async def test_subscription_update_action_exception(
hass: HomeAssistant, pywemo_device, wemo_entity
) -> None:
"""Device handles ActionException on get_state properly."""
device = async_get_coordinator(hass, wemo_entity.device_id)
device.last_update_success = True
pywemo_device.subscription_update.return_value = False
pywemo_device.get_state.reset_mock()
pywemo_device.get_state.side_effect = ActionException
await hass.async_add_executor_job(
device.subscription_callback, pywemo_device, "", ""
)
await hass.async_block_till_done()
pywemo_device.get_state.assert_called_once_with(True)
assert device.last_update_success is False
assert isinstance(device.last_exception, UpdateFailed)
async def test_subscription_update_exception(
hass: HomeAssistant, pywemo_device, wemo_entity
) -> None:
"""Device handles Exception on get_state properly."""
device = async_get_coordinator(hass, wemo_entity.device_id)
device.last_update_success = True
pywemo_device.subscription_update.return_value = False
pywemo_device.get_state.reset_mock()
pywemo_device.get_state.side_effect = Exception
await hass.async_add_executor_job(
device.subscription_callback, pywemo_device, "", ""
)
await hass.async_block_till_done()
pywemo_device.get_state.assert_called_once_with(True)
assert device.last_update_success is False
assert isinstance(device.last_exception, Exception)
async def test_async_update_data_subscribed(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""No update happens when the device is subscribed."""
device = async_get_coordinator(hass, wemo_entity.device_id)
pywemo_registry.is_subscribed.return_value = True
pywemo_device.get_state.reset_mock()
await device._async_update_data()
pywemo_device.get_state.assert_not_called()
async def test_device_info(
hass: HomeAssistant, wemo_entity, device_registry: dr.DeviceRegistry
) -> None:
"""Verify the DeviceInfo data is set properly."""
device_entries = list(device_registry.devices.values())
assert len(device_entries) == 1
assert device_entries[0].connections == {
("upnp", f"uuid:LightSwitch-1_0-{MOCK_SERIAL_NUMBER}")
}
assert device_entries[0].manufacturer == "Belkin"
assert device_entries[0].model == "LightSwitch"
assert device_entries[0].model_id == "LightSwitch"
assert device_entries[0].sw_version == MOCK_FIRMWARE_VERSION
async def test_dli_device_info(
hass: HomeAssistant, wemo_dli_entity, device_registry: dr.DeviceRegistry
) -> None:
"""Verify the DeviceInfo data for Digital Loggers emulated wemo device."""
device_entries = list(device_registry.devices.values())
assert device_entries[0].configuration_url == "http://127.0.0.1"
assert device_entries[0].identifiers == {(DOMAIN, "123456789")}
async def test_options_enable_subscription_false(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Test setting Options.enable_subscription = False."""
config_entry = hass.config_entries.async_get_entry(wemo_entity.config_entry_id)
assert hass.config_entries.async_update_entry(
config_entry,
options=asdict(Options(enable_subscription=False, enable_long_press=False)),
)
await hass.async_block_till_done()
pywemo_registry.unregister.assert_called_once_with(pywemo_device)
async def test_options_enable_long_press_false(
hass: HomeAssistant, pywemo_device, wemo_entity
) -> None:
"""Test setting Options.enable_long_press = False."""
config_entry = hass.config_entries.async_get_entry(wemo_entity.config_entry_id)
assert hass.config_entries.async_update_entry(
config_entry, options=asdict(Options(enable_long_press=False))
)
await hass.async_block_till_done()
pywemo_device.remove_long_press_virtual_device.assert_called_once_with()
class TestInsight:
"""Tests specific to the WeMo Insight device."""
@pytest.fixture
def pywemo_model(self):
"""Pywemo Dimmer models use the light platform (WemoDimmer class)."""
return "Insight"
@pytest.fixture(name="pywemo_device")
def pywemo_device_fixture(self, pywemo_device):
"""Fixture for WeMoDevice instances."""
pywemo_device.insight_params = {
"currentpower": 1.0,
"todaymw": 200000000.0,
"state": 0,
"onfor": 0,
"ontoday": 0,
"ontotal": 0,
"powerthreshold": 0,
}
return pywemo_device
@pytest.mark.parametrize(
("subscribed", "state", "expected_calls"),
[
(False, 0, [call(), call(True), call(), call()]),
(False, 1, [call(), call(True), call(), call()]),
(True, 0, [call(), call(True), call(), call()]),
(True, 1, [call(), call(), call()]),
],
)
async def test_should_poll(
self,
hass: HomeAssistant,
subscribed: bool,
state: int,
expected_calls: list[_Call],
wemo_entity: er.RegistryEntry,
pywemo_device: pywemo.WeMoDevice,
pywemo_registry: pywemo.SubscriptionRegistry,
) -> None:
"""Validate the should_poll returns the correct value."""
pywemo_registry.is_subscribed.return_value = subscribed
pywemo_device.get_state.reset_mock()
pywemo_device.get_state.return_value = state
async_fire_time_changed(hass, utcnow() + timedelta(seconds=31))
await hass.async_block_till_done()
pywemo_device.get_state.assert_has_calls(expected_calls)

View File

@@ -0,0 +1,113 @@
"""Verify that WeMo device triggers work as expected."""
import pytest
from pytest_unordered import unordered
from pywemo.subscribe import EVENT_TYPE_LONG_PRESS
from homeassistant.components.automation import DOMAIN as AUTOMATION_DOMAIN
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.wemo.const import DOMAIN, WEMO_SUBSCRIPTION_EVENT
from homeassistant.const import (
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ENTITY_ID,
CONF_PLATFORM,
CONF_TYPE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import async_get_device_automations, async_mock_service
DATA_MESSAGE = {"message": "service-called"}
@pytest.fixture
def pywemo_model():
"""Pywemo LightSwitch models use the switch platform."""
return "LightSwitchLongPress"
async def setup_automation(
hass: HomeAssistant, device_id: str, trigger_type: str
) -> None:
"""Set up an automation trigger for testing triggering."""
return await async_setup_component(
hass,
AUTOMATION_DOMAIN,
{
AUTOMATION_DOMAIN: [
{
"trigger": {
CONF_PLATFORM: "device",
CONF_DOMAIN: DOMAIN,
CONF_DEVICE_ID: device_id,
CONF_TYPE: trigger_type,
},
"action": {
"service": "test.automation",
"data": DATA_MESSAGE,
},
},
]
},
)
async def test_get_triggers(hass: HomeAssistant, wemo_entity) -> None:
"""Test that the triggers appear for a supported device."""
assert wemo_entity.device_id is not None
expected_triggers = [
{
CONF_DEVICE_ID: wemo_entity.device_id,
CONF_DOMAIN: DOMAIN,
CONF_PLATFORM: "device",
CONF_TYPE: EVENT_TYPE_LONG_PRESS,
"metadata": {},
},
{
CONF_DEVICE_ID: wemo_entity.device_id,
CONF_DOMAIN: Platform.SWITCH,
CONF_ENTITY_ID: wemo_entity.id,
CONF_PLATFORM: "device",
CONF_TYPE: "changed_states",
"metadata": {"secondary": False},
},
{
CONF_DEVICE_ID: wemo_entity.device_id,
CONF_DOMAIN: Platform.SWITCH,
CONF_ENTITY_ID: wemo_entity.id,
CONF_PLATFORM: "device",
CONF_TYPE: "turned_off",
"metadata": {"secondary": False},
},
{
CONF_DEVICE_ID: wemo_entity.device_id,
CONF_DOMAIN: Platform.SWITCH,
CONF_ENTITY_ID: wemo_entity.id,
CONF_PLATFORM: "device",
CONF_TYPE: "turned_on",
"metadata": {"secondary": False},
},
]
triggers = await async_get_device_automations(
hass, DeviceAutomationType.TRIGGER, wemo_entity.device_id
)
assert triggers == unordered(expected_triggers)
async def test_fires_on_long_press(
hass: HomeAssistant, wemo_entity: er.RegistryEntry
) -> None:
"""Test wemo long press trigger firing."""
assert await setup_automation(hass, wemo_entity.device_id, EVENT_TYPE_LONG_PRESS)
calls = async_mock_service(hass, "test", "automation")
message = {CONF_DEVICE_ID: wemo_entity.device_id, CONF_TYPE: EVENT_TYPE_LONG_PRESS}
hass.bus.async_fire(WEMO_SUBSCRIPTION_EVENT, message)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data == DATA_MESSAGE

View File

@@ -0,0 +1,180 @@
"""Tests for the Wemo fan entity."""
import pytest
from pywemo.exceptions import ActionException
from pywemo.ouimeaux_device.humidifier import DesiredHumidity, FanMode
from homeassistant.components.fan import (
ATTR_PERCENTAGE,
DOMAIN as FAN_DOMAIN,
SERVICE_SET_PERCENTAGE,
)
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.wemo import fan
from homeassistant.components.wemo.const import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_ON, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import entity_test_helpers
from .conftest import async_create_wemo_entity
@pytest.fixture
def pywemo_model():
"""Pywemo Humidifier models use the fan platform."""
return "Humidifier"
# Tests that are in common among wemo platforms. These test methods will be run
# in the scope of this test module. They will run using the pywemo_model from
# this test module (Humidifier).
test_async_update_locked_multiple_updates = (
entity_test_helpers.test_async_update_locked_multiple_updates
)
test_async_update_locked_multiple_callbacks = (
entity_test_helpers.test_async_update_locked_multiple_callbacks
)
test_async_update_locked_callback_and_update = (
entity_test_helpers.test_async_update_locked_callback_and_update
)
async def test_fan_registry_state_callback(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Verify that the fan receives state updates from the registry."""
# On state.
pywemo_device.get_state.return_value = 1
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Off state.
pywemo_device.get_state.return_value = 0
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
async def test_fan_update_entity(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Verify that the fan performs state updates."""
await async_setup_component(hass, HA_DOMAIN, {})
# On state.
pywemo_device.get_state.return_value = 1
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Off state.
pywemo_device.get_state.return_value = 0
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
async def test_available_after_update(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Test the availability when an On call fails and after an update."""
pywemo_device.set_state.side_effect = ActionException
pywemo_device.get_state.return_value = 1
await entity_test_helpers.test_avaliable_after_update(
hass, pywemo_registry, pywemo_device, wemo_entity, FAN_DOMAIN
)
async def test_turn_off_state(hass: HomeAssistant, wemo_entity) -> None:
"""Test that the device state is updated after turning off."""
await entity_test_helpers.test_turn_off_state(hass, wemo_entity, FAN_DOMAIN)
async def test_fan_reset_filter_service(
hass: HomeAssistant, pywemo_device, wemo_entity
) -> None:
"""Verify that SERVICE_RESET_FILTER_LIFE is registered and works."""
await hass.services.async_call(
DOMAIN,
fan.SERVICE_RESET_FILTER_LIFE,
{ATTR_ENTITY_ID: wemo_entity.entity_id},
blocking=True,
)
pywemo_device.reset_filter_life.assert_called_with()
@pytest.mark.parametrize(
("test_input", "expected"),
[
(0, DesiredHumidity.FortyFivePercent),
(45, DesiredHumidity.FortyFivePercent),
(50, DesiredHumidity.FiftyPercent),
(55, DesiredHumidity.FiftyFivePercent),
(60, DesiredHumidity.SixtyPercent),
(100, DesiredHumidity.OneHundredPercent),
],
)
async def test_fan_set_humidity_service(
hass: HomeAssistant, pywemo_device, wemo_entity, test_input, expected
) -> None:
"""Verify that SERVICE_SET_HUMIDITY is registered and works."""
await hass.services.async_call(
DOMAIN,
fan.SERVICE_SET_HUMIDITY,
{
ATTR_ENTITY_ID: wemo_entity.entity_id,
fan.ATTR_TARGET_HUMIDITY: test_input,
},
blocking=True,
)
pywemo_device.set_humidity.assert_called_with(expected)
@pytest.mark.parametrize(
("percentage", "expected_fan_mode"),
[
(0, FanMode.Off),
(10, FanMode.Minimum),
(30, FanMode.Low),
(50, FanMode.Medium),
(70, FanMode.High),
(100, FanMode.Maximum),
],
)
async def test_fan_set_percentage(
hass: HomeAssistant, pywemo_device, wemo_entity, percentage, expected_fan_mode
) -> None:
"""Verify set_percentage works properly through the entire range of FanModes."""
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_PERCENTAGE,
{ATTR_ENTITY_ID: [wemo_entity.entity_id], ATTR_PERCENTAGE: percentage},
blocking=True,
)
pywemo_device.set_state.assert_called_with(expected_fan_mode)
async def test_fan_mode_high_initially(hass: HomeAssistant, pywemo_device) -> None:
"""Verify the FanMode is set to High when turned on."""
pywemo_device.fan_mode = FanMode.Off
wemo_entity = await async_create_wemo_entity(hass, pywemo_device, "")
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
pywemo_device.set_state.assert_called_with(FanMode.High)

View File

@@ -0,0 +1,253 @@
"""Tests for the wemo component."""
import asyncio
from datetime import timedelta
from unittest.mock import create_autospec, patch
import pywemo
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.components.wemo import (
CONF_DISCOVERY,
CONF_STATIC,
WemoDiscovery,
async_wemo_dispatcher_connect,
)
from homeassistant.components.wemo.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from . import entity_test_helpers
from .conftest import (
MOCK_FIRMWARE_VERSION,
MOCK_HOST,
MOCK_NAME,
MOCK_PORT,
MOCK_SERIAL_NUMBER,
)
from tests.common import async_fire_time_changed
async def test_config_no_config(hass: HomeAssistant) -> None:
"""Component setup succeeds when there are no config entry for the domain."""
assert await async_setup_component(hass, DOMAIN, {})
async def test_config_no_static(hass: HomeAssistant) -> None:
"""Component setup succeeds when there are no static config entries."""
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_DISCOVERY: False}})
async def test_static_duplicate_static_entry(
hass: HomeAssistant, entity_registry: er.EntityRegistry, pywemo_device
) -> None:
"""Duplicate static entries are merged into a single entity."""
static_config_entry = f"{MOCK_HOST}:{MOCK_PORT}"
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_DISCOVERY: False,
CONF_STATIC: [
static_config_entry,
static_config_entry,
],
},
},
)
await hass.async_block_till_done()
entity_entries = list(entity_registry.entities.values())
assert len(entity_entries) == 1
async def test_static_config_with_port(
hass: HomeAssistant, entity_registry: er.EntityRegistry, pywemo_device
) -> None:
"""Static device with host and port is added and removed."""
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_DISCOVERY: False,
CONF_STATIC: [f"{MOCK_HOST}:{MOCK_PORT}"],
},
},
)
await hass.async_block_till_done()
entity_entries = list(entity_registry.entities.values())
assert len(entity_entries) == 1
async def test_static_config_without_port(
hass: HomeAssistant, entity_registry: er.EntityRegistry, pywemo_device
) -> None:
"""Static device with host and no port is added and removed."""
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_DISCOVERY: False,
CONF_STATIC: [MOCK_HOST],
},
},
)
await hass.async_block_till_done()
entity_entries = list(entity_registry.entities.values())
assert len(entity_entries) == 1
async def test_reload_config_entry(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
pywemo_device: pywemo.WeMoDevice,
pywemo_registry: pywemo.SubscriptionRegistry,
) -> None:
"""Config entry can be reloaded without errors."""
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_DISCOVERY: False,
CONF_STATIC: [MOCK_HOST],
},
},
)
async def _async_test_entry_and_entity() -> tuple[str, str]:
await hass.async_block_till_done()
pywemo_device.get_state.assert_called()
pywemo_device.get_state.reset_mock()
pywemo_registry.register.assert_called_once_with(pywemo_device)
pywemo_registry.register.reset_mock()
entity_entries = list(entity_registry.entities.values())
assert len(entity_entries) == 1
await entity_test_helpers.test_turn_off_state(
hass, entity_entries[0], SWITCH_DOMAIN
)
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
return entries[0].entry_id, entity_entries[0].entity_id
entry_id, entity_id = await _async_test_entry_and_entity()
pywemo_registry.unregister.assert_not_called()
assert await hass.config_entries.async_reload(entry_id)
ids = await _async_test_entry_and_entity()
pywemo_registry.unregister.assert_called_once_with(pywemo_device)
assert ids == (entry_id, entity_id)
async def test_static_config_with_invalid_host(hass: HomeAssistant) -> None:
"""Component setup fails if a static host is invalid."""
setup_success = await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_DISCOVERY: False,
CONF_STATIC: [""],
},
},
)
assert not setup_success
async def test_static_with_upnp_failure(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
pywemo_device: pywemo.WeMoDevice,
) -> None:
"""Device that fails to get state is not added."""
pywemo_device.get_state.side_effect = pywemo.exceptions.ActionException("Failed")
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_DISCOVERY: False,
CONF_STATIC: [f"{MOCK_HOST}:{MOCK_PORT}"],
},
},
)
await hass.async_block_till_done()
entity_entries = list(entity_registry.entities.values())
assert len(entity_entries) == 0
pywemo_device.get_state.assert_called_once()
async def test_discovery(
hass: HomeAssistant, entity_registry: er.EntityRegistry, pywemo_registry
) -> None:
"""Verify that discovery dispatches devices to the platform for setup."""
def create_device(counter):
"""Create a unique mock Motion detector device for each counter value."""
device = create_autospec(pywemo.Motion, instance=True)
device.host = f"{MOCK_HOST}_{counter}"
device.port = MOCK_PORT + counter
device.name = f"{MOCK_NAME}_{counter}"
device.serial_number = f"{MOCK_SERIAL_NUMBER}_{counter}"
device.model_name = "Motion"
device.model = "Motion"
device.udn = f"uuid:{device.model_name}-1_0-{device.serial_number}"
device.firmware_version = MOCK_FIRMWARE_VERSION
device.get_state.return_value = 0 # Default to Off
device.supports_long_press.return_value = False
return device
semaphore = asyncio.Semaphore(value=0)
async def async_connect(*args):
await async_wemo_dispatcher_connect(*args)
semaphore.release()
pywemo_devices = [create_device(0), create_device(1)]
# Setup the component and start discovery.
with (
patch("pywemo.discover_devices", return_value=pywemo_devices) as mock_discovery,
patch(
"homeassistant.components.wemo.WemoDiscovery.discover_statics"
) as mock_discover_statics,
patch(
"homeassistant.components.wemo.binary_sensor.async_wemo_dispatcher_connect",
side_effect=async_connect,
),
):
assert await async_setup_component(
hass, DOMAIN, {DOMAIN: {CONF_DISCOVERY: True}}
)
await semaphore.acquire() # Returns after platform setup.
mock_discovery.assert_called()
mock_discover_statics.assert_called()
pywemo_devices.append(create_device(2))
# Test that discovery runs periodically and the async_dispatcher_send code works.
async_fire_time_changed(
hass,
dt_util.utcnow()
+ timedelta(seconds=WemoDiscovery.ADDITIONAL_SECONDS_BETWEEN_SCANS + 1),
)
await hass.async_block_till_done()
# Test that discover_statics runs during discovery
assert mock_discover_statics.call_count == 3
# Verify that the expected number of devices were setup.
entity_entries = list(entity_registry.entities.values())
assert len(entity_entries) == 3
# Verify that hass stops cleanly.
await hass.async_stop()
await hass.async_block_till_done()

View File

@@ -0,0 +1,132 @@
"""Tests for the Wemo light entity via the bridge."""
from unittest.mock import create_autospec
import pytest
import pywemo
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.light import (
ATTR_COLOR_MODE,
ATTR_COLOR_TEMP_KELVIN,
ATTR_SUPPORTED_COLOR_MODES,
DOMAIN as LIGHT_DOMAIN,
ColorMode,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import entity_test_helpers
@pytest.fixture
def pywemo_model():
"""Pywemo Bridge models use the light platform (WemoLight class)."""
return "Bridge"
# Note: The ordering of where the pywemo_bridge_light comes in test arguments matters.
# In test methods, the pywemo_bridge_light fixture argument must come before the
# wemo_entity fixture argument.
@pytest.fixture(name="pywemo_bridge_light")
def pywemo_bridge_light_fixture(pywemo_device):
"""Fixture for Bridge.Light WeMoDevice instances."""
light = create_autospec(pywemo.ouimeaux_device.bridge.Light, instance=True)
light.uniqueID = pywemo_device.serial_number
light.name = pywemo_device.name
light.bridge = pywemo_device
light.state = {"onoff": 0, "available": True}
light.capabilities = ["onoff", "levelcontrol", "colortemperature"]
pywemo_device.Lights = {pywemo_device.serial_number: light}
return light
async def test_async_update_locked_callback_and_update(
hass: HomeAssistant, pywemo_bridge_light, wemo_entity, pywemo_device
) -> None:
"""Test that a callback and a state update request can't both happen at the same time."""
await entity_test_helpers.test_async_update_locked_callback_and_update(
hass,
pywemo_device,
wemo_entity,
)
async def test_async_update_locked_multiple_updates(
hass: HomeAssistant, pywemo_bridge_light, wemo_entity, pywemo_device
) -> None:
"""Test that two state updates do not proceed at the same time."""
await entity_test_helpers.test_async_update_locked_multiple_updates(
hass,
pywemo_device,
wemo_entity,
)
async def test_async_update_locked_multiple_callbacks(
hass: HomeAssistant, pywemo_bridge_light, wemo_entity, pywemo_device
) -> None:
"""Test that two device callback state updates do not proceed at the same time."""
await entity_test_helpers.test_async_update_locked_multiple_callbacks(
hass,
pywemo_device,
wemo_entity,
)
async def test_available_after_update(
hass: HomeAssistant,
pywemo_registry,
pywemo_device,
pywemo_bridge_light,
wemo_entity,
) -> None:
"""Test the availability when an On call fails and after an update."""
pywemo_bridge_light.turn_on.side_effect = pywemo.exceptions.ActionException
pywemo_bridge_light.state["onoff"] = 1
await entity_test_helpers.test_avaliable_after_update(
hass, pywemo_registry, pywemo_device, wemo_entity, LIGHT_DOMAIN
)
async def test_turn_off_state(
hass: HomeAssistant, pywemo_bridge_light, wemo_entity
) -> None:
"""Test that the device state is updated after turning off."""
await entity_test_helpers.test_turn_off_state(hass, wemo_entity, LIGHT_DOMAIN)
async def test_light_update_entity(
hass: HomeAssistant, pywemo_registry, pywemo_bridge_light, wemo_entity
) -> None:
"""Verify that the light performs state updates."""
await async_setup_component(hass, HA_DOMAIN, {})
# On state.
pywemo_bridge_light.state["onoff"] = 1
pywemo_bridge_light.state["temperature_mireds"] = 432
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
state = hass.states.get(wemo_entity.entity_id)
assert state.attributes.get(ATTR_COLOR_TEMP_KELVIN) == 2314
assert state.attributes.get(ATTR_SUPPORTED_COLOR_MODES) == [ColorMode.COLOR_TEMP]
assert state.attributes.get(ATTR_COLOR_MODE) == ColorMode.COLOR_TEMP
assert state.state == STATE_ON
# Off state.
pywemo_bridge_light.state["onoff"] = 0
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF

View File

@@ -0,0 +1,124 @@
"""Tests for the Wemo standalone/non-bridge light entity."""
import pytest
from pywemo.exceptions import ActionException
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.light import ATTR_BRIGHTNESS, DOMAIN as LIGHT_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_ON, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import entity_test_helpers
@pytest.fixture
def pywemo_model():
"""Pywemo Dimmer models use the light platform (WemoDimmer class)."""
return "Dimmer"
# Tests that are in common among wemo platforms. These test methods will be run
# in the scope of this test module. They will run using the pywemo_model from
# this test module (Dimmer).
test_async_update_locked_multiple_updates = (
entity_test_helpers.test_async_update_locked_multiple_updates
)
test_async_update_locked_multiple_callbacks = (
entity_test_helpers.test_async_update_locked_multiple_callbacks
)
test_async_update_locked_callback_and_update = (
entity_test_helpers.test_async_update_locked_callback_and_update
)
async def test_available_after_update(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Test the availability when an On call fails and after an update."""
pywemo_device.on.side_effect = ActionException
pywemo_device.get_state.return_value = 1
await entity_test_helpers.test_avaliable_after_update(
hass, pywemo_registry, pywemo_device, wemo_entity, LIGHT_DOMAIN
)
async def test_turn_off_state(hass: HomeAssistant, wemo_entity) -> None:
"""Test that the device state is updated after turning off."""
await entity_test_helpers.test_turn_off_state(hass, wemo_entity, LIGHT_DOMAIN)
async def test_turn_on_brightness(
hass: HomeAssistant, pywemo_device, wemo_entity
) -> None:
"""Test setting the brightness value of the light."""
brightness = 0
state = 0
def set_brightness(b):
nonlocal brightness
nonlocal state
brightness, state = (b, int(bool(b)))
pywemo_device.get_state.side_effect = lambda: state
pywemo_device.get_brightness.side_effect = lambda: brightness
pywemo_device.set_brightness.side_effect = set_brightness
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: [wemo_entity.entity_id], ATTR_BRIGHTNESS: 204},
blocking=True,
)
pywemo_device.set_brightness.assert_called_once_with(80)
states = hass.states.get(wemo_entity.entity_id)
assert states.state == STATE_ON
assert states.attributes[ATTR_BRIGHTNESS] == 204
async def test_light_registry_state_callback(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Verify that the light receives state updates from the registry."""
# On state.
pywemo_device.get_state.return_value = 1
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Off state.
pywemo_device.get_state.return_value = 0
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
async def test_light_update_entity(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Verify that the light performs state updates."""
await async_setup_component(hass, HA_DOMAIN, {})
# On state.
pywemo_device.get_state.return_value = 1
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Off state.
pywemo_device.get_state.return_value = 0
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF

View File

@@ -0,0 +1,46 @@
"""Tests for the Wemo sensor entity."""
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .conftest import MOCK_INSIGHT_CURRENT_WATTS, MOCK_INSIGHT_TODAY_KWH
from .entity_test_helpers import EntityTestHelpers
@pytest.fixture
def pywemo_model():
"""Pywemo LightSwitch models use the switch platform."""
return "Insight"
class InsightTestTemplate(EntityTestHelpers):
"""Base class for testing WeMo Insight Sensors."""
ENTITY_ID_SUFFIX: str
EXPECTED_STATE_VALUE: str
@pytest.fixture(name="wemo_entity_suffix")
@classmethod
def wemo_entity_suffix_fixture(cls):
"""Select the appropriate entity for the test."""
return cls.ENTITY_ID_SUFFIX
def test_state(self, hass: HomeAssistant, wemo_entity: er.RegistryEntry) -> None:
"""Test the sensor state."""
assert hass.states.get(wemo_entity.entity_id).state == self.EXPECTED_STATE_VALUE
class TestInsightCurrentPower(InsightTestTemplate):
"""Test the InsightCurrentPower class."""
ENTITY_ID_SUFFIX = "_current_power"
EXPECTED_STATE_VALUE = str(MOCK_INSIGHT_CURRENT_WATTS)
class TestInsightTodayEnergy(InsightTestTemplate):
"""Test the InsightTodayEnergy class."""
ENTITY_ID_SUFFIX = "_today_energy"
EXPECTED_STATE_VALUE = str(MOCK_INSIGHT_TODAY_KWH)

View File

@@ -0,0 +1,177 @@
"""Tests for the Wemo switch entity."""
import pytest
import pywemo
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.components.wemo.switch import (
ATTR_CURRENT_STATE_DETAIL,
ATTR_ON_LATEST_TIME,
ATTR_ON_TODAY_TIME,
ATTR_ON_TOTAL_TIME,
ATTR_POWER_THRESHOLD,
ATTR_SENSOR_STATE,
ATTR_SWITCH_MODE,
MAKER_SWITCH_MOMENTARY,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_OFF,
STATE_ON,
STATE_STANDBY,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import entity_test_helpers
from .conftest import (
MOCK_INSIGHT_STATE_THRESHOLD_POWER,
async_create_wemo_entity,
create_pywemo_device,
)
@pytest.fixture
def pywemo_model():
"""Pywemo LightSwitch models use the switch platform."""
return "LightSwitch"
# Tests that are in common among wemo platforms. These test methods will be run
# in the scope of this test module. They will run using the pywemo_model from
# this test module (LightSwitch).
test_async_update_locked_multiple_updates = (
entity_test_helpers.test_async_update_locked_multiple_updates
)
test_async_update_locked_multiple_callbacks = (
entity_test_helpers.test_async_update_locked_multiple_callbacks
)
test_async_update_locked_callback_and_update = (
entity_test_helpers.test_async_update_locked_callback_and_update
)
async def test_switch_registry_state_callback(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Verify that the switch receives state updates from the registry."""
# On state.
pywemo_device.get_state.return_value = 1
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Off state.
pywemo_device.get_state.return_value = 0
pywemo_registry.callbacks[pywemo_device.name](pywemo_device, "", "")
await hass.async_block_till_done()
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
async def test_switch_update_entity(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Verify that the switch performs state updates."""
await async_setup_component(hass, HA_DOMAIN, {})
# On state.
pywemo_device.get_state.return_value = 1
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_ON
# Off state.
pywemo_device.get_state.return_value = 0
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
async def test_available_after_update(
hass: HomeAssistant, pywemo_registry, pywemo_device, wemo_entity
) -> None:
"""Test the availability when an On call fails and after an update."""
pywemo_device.on.side_effect = pywemo.exceptions.ActionException
pywemo_device.get_state.return_value = 1
await entity_test_helpers.test_avaliable_after_update(
hass, pywemo_registry, pywemo_device, wemo_entity, SWITCH_DOMAIN
)
async def test_turn_off_state(hass: HomeAssistant, wemo_entity) -> None:
"""Test that the device state is updated after turning off."""
await entity_test_helpers.test_turn_off_state(hass, wemo_entity, SWITCH_DOMAIN)
async def test_insight_state_attributes(hass: HomeAssistant, pywemo_registry) -> None:
"""Verify the switch attributes are set for the Insight device."""
await async_setup_component(hass, HA_DOMAIN, {})
with create_pywemo_device(pywemo_registry, "Insight") as insight:
wemo_entity = await async_create_wemo_entity(hass, insight, "")
attributes = hass.states.get(wemo_entity.entity_id).attributes
assert attributes[ATTR_ON_LATEST_TIME] == "00d 00h 20m 34s"
assert attributes[ATTR_ON_TODAY_TIME] == "00d 01h 34m 38s"
assert attributes[ATTR_ON_TOTAL_TIME] == "00d 02h 30m 12s"
assert attributes[ATTR_POWER_THRESHOLD] == MOCK_INSIGHT_STATE_THRESHOLD_POWER
assert attributes[ATTR_CURRENT_STATE_DETAIL] == STATE_OFF
async def async_update():
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
# Test 'ON' state detail value.
insight.standby_state = pywemo.StandbyState.ON
await async_update()
attributes = hass.states.get(wemo_entity.entity_id).attributes
assert attributes[ATTR_CURRENT_STATE_DETAIL] == STATE_ON
# Test 'STANDBY' state detail value.
insight.standby_state = pywemo.StandbyState.STANDBY
await async_update()
attributes = hass.states.get(wemo_entity.entity_id).attributes
assert attributes[ATTR_CURRENT_STATE_DETAIL] == STATE_STANDBY
# Test 'UNKNOWN' state detail value.
insight.standby_state = None
await async_update()
attributes = hass.states.get(wemo_entity.entity_id).attributes
assert attributes[ATTR_CURRENT_STATE_DETAIL] == STATE_UNKNOWN
async def test_maker_state_attributes(hass: HomeAssistant, pywemo_registry) -> None:
"""Verify the switch attributes are set for the Insight device."""
await async_setup_component(hass, HA_DOMAIN, {})
with create_pywemo_device(pywemo_registry, "Maker") as maker:
wemo_entity = await async_create_wemo_entity(hass, maker, "")
attributes = hass.states.get(wemo_entity.entity_id).attributes
assert attributes[ATTR_SENSOR_STATE] == STATE_OFF
assert attributes[ATTR_SWITCH_MODE] == MAKER_SWITCH_MOMENTARY
# Test 'ON' sensor state and 'TOGGLE' switch mode values.
maker.sensor_state = 0
maker.switch_mode = 0
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blocking=True,
)
attributes = hass.states.get(wemo_entity.entity_id).attributes
assert attributes[ATTR_SENSOR_STATE] == STATE_ON