mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 04:08:19 -04:00
Add tests for the Electra Smart integration (#187973)
Signed-off-by: Noam Okman <noamokman@users.noreply.github.com>
This commit is contained in:
@@ -31,7 +31,6 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from . import ElectraSmartConfigEntry
|
||||
from .const import (
|
||||
API_DELAY,
|
||||
CONSECUTIVE_FAILURE_THRESHOLD,
|
||||
DOMAIN,
|
||||
PRESET_NONE,
|
||||
PRESET_SHABAT,
|
||||
@@ -160,7 +159,7 @@ class ElectraClimateEntity(ClimateEntity):
|
||||
self._skip_update = True
|
||||
self._was_available = True
|
||||
|
||||
_LOGGER.debug("Added %s Electra AC device", self._attr_name)
|
||||
_LOGGER.debug("Added %s Electra AC device", device.name)
|
||||
|
||||
@property
|
||||
@override
|
||||
@@ -199,7 +198,7 @@ class ElectraClimateEntity(ClimateEntity):
|
||||
_LOGGER.warning(
|
||||
"Electra AC %s (%s) is not available, check"
|
||||
" its status in the Electra Smart mobile app",
|
||||
self.name,
|
||||
self.entity_id,
|
||||
self._electra_ac_device.mac,
|
||||
)
|
||||
self._was_available = False
|
||||
@@ -208,15 +207,15 @@ class ElectraClimateEntity(ClimateEntity):
|
||||
if not self._was_available:
|
||||
_LOGGER.debug(
|
||||
"%s (%s) is now available",
|
||||
self.entity_id,
|
||||
self._electra_ac_device.mac,
|
||||
self.name,
|
||||
)
|
||||
self._was_available = True
|
||||
|
||||
_LOGGER.debug(
|
||||
"%s (%s) state updated: %s",
|
||||
self.entity_id,
|
||||
self._electra_ac_device.mac,
|
||||
self.name,
|
||||
self._electra_ac_device.__dict__,
|
||||
)
|
||||
except ElectraApiError as exp:
|
||||
@@ -224,17 +223,11 @@ class ElectraClimateEntity(ClimateEntity):
|
||||
_LOGGER.warning(
|
||||
"Failed to get %s state: %s"
|
||||
" (try #%i since last success), keeping old state",
|
||||
self.name,
|
||||
self.entity_id,
|
||||
exp,
|
||||
self._consecutive_failures,
|
||||
)
|
||||
|
||||
if self._consecutive_failures >= CONSECUTIVE_FAILURE_THRESHOLD:
|
||||
raise HomeAssistantError(
|
||||
f"Failed to get {self.name} state: {exp}"
|
||||
f" for the {self._consecutive_failures} time",
|
||||
) from ElectraApiError
|
||||
|
||||
self._consecutive_failures = 0
|
||||
self._update_device_attrs()
|
||||
|
||||
@@ -269,12 +262,13 @@ class ElectraClimateEntity(ClimateEntity):
|
||||
|
||||
@override
|
||||
async def async_set_temperature(self, **kwargs: Any) -> None:
|
||||
"""Set new target temperature."""
|
||||
"""Set new target temperature.
|
||||
|
||||
if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None:
|
||||
raise ValueError("No target temperature provided")
|
||||
|
||||
self._electra_ac_device.set_temperature(int(temperature))
|
||||
The climate service schema requires one of the temperature attributes
|
||||
and this entity only supports a target temperature, so the value is
|
||||
always there.
|
||||
"""
|
||||
self._electra_ac_device.set_temperature(int(kwargs[ATTR_TEMPERATURE]))
|
||||
await self._async_operate_electra_ac()
|
||||
|
||||
def _update_device_attrs(self) -> None:
|
||||
@@ -353,7 +347,9 @@ class ElectraClimateEntity(ClimateEntity):
|
||||
and resp[Attributes.DATA][Attributes.RES] == STATUS_SUCCESS
|
||||
):
|
||||
self._async_write_ha_state()
|
||||
raise HomeAssistantError(f"Failed to update {self.name}, error: {resp}")
|
||||
raise HomeAssistantError(
|
||||
f"Failed to update {self.entity_id}, error: {resp}"
|
||||
)
|
||||
|
||||
self._update_device_attrs()
|
||||
self._last_state_update = int(time.time())
|
||||
|
||||
@@ -7,7 +7,6 @@ CONF_OTP = "one_time_password"
|
||||
CONF_IMEI = "imei"
|
||||
SCAN_INTERVAL_SEC = 30
|
||||
API_DELAY = 5
|
||||
CONSECUTIVE_FAILURE_THRESHOLD = 4
|
||||
UNAVAILABLE_THRESH_SEC = 120
|
||||
PRESET_NONE = "None"
|
||||
PRESET_SHABAT = "Shabat"
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
from electrasmart.device import OperationMode
|
||||
from electrasmart.device.const import Feature
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
|
||||
@@ -22,7 +23,7 @@ def mock_device_fixture() -> Mock:
|
||||
mac="a8032ab12345",
|
||||
model="Electra A/C",
|
||||
manufactor="Electra",
|
||||
features=[],
|
||||
features=[Feature.V_SWING, Feature.H_SWING],
|
||||
is_disconnected=Mock(return_value=False),
|
||||
is_on=Mock(return_value=False),
|
||||
is_horizontal_swing=Mock(return_value=False),
|
||||
@@ -34,7 +35,12 @@ def mock_device_fixture() -> Mock:
|
||||
get_shabat_mode=Mock(return_value=False),
|
||||
turn_on=Mock(return_value=True),
|
||||
turn_off=Mock(return_value=None),
|
||||
set_fan_speed=Mock(return_value=None),
|
||||
set_horizontal_swing=Mock(return_value=None),
|
||||
set_mode=Mock(return_value=None),
|
||||
set_shabat_mode=Mock(return_value=None),
|
||||
set_temperature=Mock(return_value=None),
|
||||
set_vertical_swing=Mock(return_value=None),
|
||||
)
|
||||
# `name` is a reserved Mock kwarg, so it must be set after construction.
|
||||
device.name = "Living Room"
|
||||
@@ -47,6 +53,7 @@ def mock_api_fixture(mock_device: Mock) -> Mock:
|
||||
return Mock(
|
||||
devices=[mock_device],
|
||||
fetch_devices=AsyncMock(),
|
||||
get_last_telemtry=AsyncMock(),
|
||||
set_state=AsyncMock(return_value={"status": 0, "data": {"res": 0}}),
|
||||
)
|
||||
|
||||
|
||||
@@ -1,17 +1,41 @@
|
||||
"""Tests for the Electra Smart climate entity."""
|
||||
|
||||
from unittest.mock import Mock
|
||||
import logging
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
from electrasmart.api import ElectraApiError
|
||||
from electrasmart.device import OperationMode
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.climate import (
|
||||
ATTR_FAN_MODE,
|
||||
ATTR_HVAC_MODE,
|
||||
ATTR_PRESET_MODE,
|
||||
ATTR_SWING_MODE,
|
||||
DOMAIN as CLIMATE_DOMAIN,
|
||||
FAN_HIGH,
|
||||
SERVICE_SET_FAN_MODE,
|
||||
SERVICE_SET_HVAC_MODE,
|
||||
SERVICE_SET_PRESET_MODE,
|
||||
SERVICE_SET_SWING_MODE,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
SWING_BOTH,
|
||||
SWING_HORIZONTAL,
|
||||
SWING_OFF,
|
||||
SWING_VERTICAL,
|
||||
HVACMode,
|
||||
)
|
||||
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON
|
||||
from homeassistant.components.electrasmart.const import PRESET_NONE, PRESET_SHABAT
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
ATTR_TEMPERATURE,
|
||||
SERVICE_TURN_OFF,
|
||||
SERVICE_TURN_ON,
|
||||
STATE_UNAVAILABLE,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers.entity_component import async_update_entity
|
||||
|
||||
ENTITY_ID = "climate.living_room"
|
||||
|
||||
@@ -70,3 +94,218 @@ async def test_set_hvac_mode_still_selects_the_requested_mode(
|
||||
mock_device.set_mode.assert_called_once_with(OperationMode.MODE_COOL)
|
||||
mock_device.turn_on.assert_called_once_with()
|
||||
mock_api.set_state.assert_awaited_once_with(mock_device)
|
||||
|
||||
|
||||
async def test_set_fan_mode(
|
||||
hass: HomeAssistant, mock_api: Mock, mock_device: Mock, setup_integration: None
|
||||
) -> None:
|
||||
"""Setting a fan mode sends the new speed to the API."""
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_FAN_MODE,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_FAN_MODE: FAN_HIGH},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
mock_device.set_fan_speed.assert_called_once_with(OperationMode.FAN_SPEED_HIGH)
|
||||
mock_api.set_state.assert_awaited_once_with(mock_device)
|
||||
|
||||
|
||||
async def test_set_temperature(
|
||||
hass: HomeAssistant, mock_api: Mock, mock_device: Mock, setup_integration: None
|
||||
) -> None:
|
||||
"""Setting a target temperature sends it to the API."""
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_TEMPERATURE: 25},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
mock_device.set_temperature.assert_called_once_with(25)
|
||||
mock_api.set_state.assert_awaited_once_with(mock_device)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("swing_mode", "horizontal", "vertical"),
|
||||
[
|
||||
(SWING_BOTH, True, True),
|
||||
(SWING_VERTICAL, False, True),
|
||||
(SWING_HORIZONTAL, True, False),
|
||||
(SWING_OFF, False, False),
|
||||
],
|
||||
)
|
||||
async def test_set_swing_mode(
|
||||
hass: HomeAssistant,
|
||||
mock_api: Mock,
|
||||
mock_device: Mock,
|
||||
setup_integration: None,
|
||||
swing_mode: str,
|
||||
horizontal: bool,
|
||||
vertical: bool,
|
||||
) -> None:
|
||||
"""Each swing mode sets both swing axes on the device."""
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_SWING_MODE,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_SWING_MODE: swing_mode},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
mock_device.set_horizontal_swing.assert_called_once_with(horizontal)
|
||||
mock_device.set_vertical_swing.assert_called_once_with(vertical)
|
||||
mock_api.set_state.assert_awaited_once_with(mock_device)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("preset_mode", "shabat"), [(PRESET_SHABAT, True), (PRESET_NONE, False)]
|
||||
)
|
||||
async def test_set_preset_mode(
|
||||
hass: HomeAssistant,
|
||||
mock_api: Mock,
|
||||
mock_device: Mock,
|
||||
setup_integration: None,
|
||||
preset_mode: str,
|
||||
shabat: bool,
|
||||
) -> None:
|
||||
"""Selecting a preset switches the Shabat mode on the device."""
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_PRESET_MODE,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: preset_mode},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
mock_device.set_shabat_mode.assert_called_once_with(shabat)
|
||||
mock_api.set_state.assert_awaited_once_with(mock_device)
|
||||
|
||||
|
||||
async def test_command_failure_raises(
|
||||
hass: HomeAssistant, mock_api: Mock, setup_integration: None
|
||||
) -> None:
|
||||
"""A failing command surfaces as a Home Assistant error."""
|
||||
mock_api.set_state = AsyncMock(side_effect=ElectraApiError("Failed to set state"))
|
||||
|
||||
with pytest.raises(
|
||||
HomeAssistantError, match="Error communicating with Electra API"
|
||||
):
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_TURN_ON,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
async def test_rejected_command_raises(
|
||||
hass: HomeAssistant, mock_api: Mock, setup_integration: None
|
||||
) -> None:
|
||||
"""A command the API refuses surfaces as a Home Assistant error."""
|
||||
mock_api.set_state = AsyncMock(return_value={"status": 1, "data": {"res": 0}})
|
||||
|
||||
with pytest.raises(
|
||||
HomeAssistantError, match="Failed to update climate.living_room"
|
||||
):
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_TURN_ON,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
async def test_update_polls_the_cloud(
|
||||
hass: HomeAssistant, mock_api: Mock, setup_integration: None
|
||||
) -> None:
|
||||
"""A scheduled update asks the API for the latest telemetry."""
|
||||
await async_update_entity(hass, ENTITY_ID)
|
||||
|
||||
mock_api.get_last_telemtry.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_update_is_skipped_right_after_a_command(
|
||||
hass: HomeAssistant, mock_api: Mock, setup_integration: None
|
||||
) -> None:
|
||||
"""A command is not followed by a poll, as the API lags behind it."""
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: ENTITY_ID}, blocking=True
|
||||
)
|
||||
|
||||
await async_update_entity(hass, ENTITY_ID)
|
||||
|
||||
mock_api.get_last_telemtry.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("horizontal", "vertical", "expected"),
|
||||
[
|
||||
(True, True, SWING_BOTH),
|
||||
(True, False, SWING_HORIZONTAL),
|
||||
(False, True, SWING_VERTICAL),
|
||||
(False, False, SWING_OFF),
|
||||
],
|
||||
)
|
||||
async def test_swing_mode_reflects_the_device(
|
||||
hass: HomeAssistant,
|
||||
mock_device: Mock,
|
||||
setup_integration: None,
|
||||
horizontal: bool,
|
||||
vertical: bool,
|
||||
expected: str,
|
||||
) -> None:
|
||||
"""The reported swing mode follows the swing state of the device."""
|
||||
mock_device.is_horizontal_swing = Mock(return_value=horizontal)
|
||||
mock_device.is_vertical_swing = Mock(return_value=vertical)
|
||||
|
||||
await async_update_entity(hass, ENTITY_ID)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).attributes[ATTR_SWING_MODE] == expected
|
||||
|
||||
|
||||
async def test_unavailable_device_warns_once_and_recovers(
|
||||
hass: HomeAssistant,
|
||||
mock_device: Mock,
|
||||
setup_integration: None,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""An offline AC is unavailable, and the warning is logged once per outage."""
|
||||
caplog.set_level(logging.DEBUG)
|
||||
warning = (
|
||||
"Electra AC climate.living_room (a8032ab12345) is not available,"
|
||||
" check its status in the Electra Smart mobile app"
|
||||
)
|
||||
mock_device.is_disconnected = Mock(return_value=True)
|
||||
|
||||
await async_update_entity(hass, ENTITY_ID)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
|
||||
assert caplog.text.count(warning) == 1
|
||||
|
||||
await async_update_entity(hass, ENTITY_ID)
|
||||
|
||||
assert caplog.text.count(warning) == 1
|
||||
|
||||
mock_device.is_disconnected = Mock(return_value=False)
|
||||
|
||||
await async_update_entity(hass, ENTITY_ID)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state != STATE_UNAVAILABLE
|
||||
assert "is now available" in caplog.text
|
||||
|
||||
|
||||
async def test_update_failure_keeps_the_old_state(
|
||||
hass: HomeAssistant,
|
||||
mock_api: Mock,
|
||||
setup_integration: None,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""A failed poll keeps the last known state and logs the failure."""
|
||||
mock_api.get_last_telemtry = AsyncMock(
|
||||
side_effect=ElectraApiError("Failed to retrieve telemetry")
|
||||
)
|
||||
|
||||
await async_update_entity(hass, ENTITY_ID)
|
||||
|
||||
assert "Failed to get climate.living_room state" in caplog.text
|
||||
assert "Failed to retrieve telemetry" in caplog.text
|
||||
assert hass.states.get(ENTITY_ID).attributes[ATTR_TEMPERATURE] == 22
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from json import loads
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
|
||||
from electrasmart.api import ElectraIntruderLockoutError
|
||||
from electrasmart.api import ElectraApiError, ElectraIntruderLockoutError
|
||||
from pytest_homeassistant.common import MockConfigEntry, async_load_fixture
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
@@ -59,3 +59,42 @@ async def test_reauth_on_intruder_lockout(
|
||||
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
|
||||
assert len(flows) == 1
|
||||
assert flows[0]["context"]["source"] == config_entries.SOURCE_REAUTH
|
||||
|
||||
|
||||
async def test_setup_retries_when_the_api_cannot_be_reached(
|
||||
hass: HomeAssistant, config_entry: MockConfigEntry
|
||||
) -> None:
|
||||
"""An API error during setup asks Home Assistant to retry."""
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
mock_api = Mock(
|
||||
devices=[],
|
||||
fetch_devices=AsyncMock(side_effect=ElectraApiError("Cannot reach the API")),
|
||||
)
|
||||
with patch(
|
||||
"homeassistant.components.electrasmart.ElectraAPI", return_value=mock_api
|
||||
):
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
|
||||
async def test_update_listener_reloads_the_entry(
|
||||
hass: HomeAssistant, config_entry: MockConfigEntry, mock_api: Mock
|
||||
) -> None:
|
||||
"""An updated config entry reloads the integration."""
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.electrasmart.ElectraAPI", return_value=mock_api
|
||||
):
|
||||
assert await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
assert hass.config_entries.async_update_entry(config_entry, title="Electra")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
assert mock_api.fetch_devices.await_count == 2
|
||||
|
||||
Reference in New Issue
Block a user