Raise an error when a myStrom plug action fails (#182782)

This commit is contained in:
Abdellatif Anaflous
2026-09-21 08:05:58 +02:00
committed by GitHub
parent e7a6ca803c
commit 35024dd563
3 changed files with 57 additions and 6 deletions
@@ -34,5 +34,10 @@
"name": "Last restart"
}
}
},
"exceptions": {
"switch_action_failed": {
"message": "Failed to perform the action on the myStrom plug."
}
}
}
+11 -6
View File
@@ -7,6 +7,7 @@ from pymystrom.exceptions import MyStromConnectionError
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.device_registry import DeviceInfo, format_mac
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
@@ -52,18 +53,22 @@ class MyStromSwitch(SwitchEntity):
"""Turn the switch on."""
try:
await self.plug.turn_on()
# pylint: disable-next=home-assistant-action-swallowed-exception
except MyStromConnectionError:
_LOGGER.error("No route to myStrom plug")
except MyStromConnectionError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="switch_action_failed",
) from err
@override
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
try:
await self.plug.turn_off()
# pylint: disable-next=home-assistant-action-swallowed-exception
except MyStromConnectionError:
_LOGGER.error("No route to myStrom plug")
except MyStromConnectionError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="switch_action_failed",
) from err
async def async_update(self) -> None:
"""Get the latest data from the device and update the data."""
+41
View File
@@ -0,0 +1,41 @@
"""Test the myStrom switch."""
from unittest.mock import AsyncMock
from pymystrom.exceptions import MyStromConnectionError
import pytest
from homeassistant.components.mystrom.const import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from .test_init import init_integration
from tests.common import MockConfigEntry
@pytest.mark.parametrize("service", [SERVICE_TURN_ON, SERVICE_TURN_OFF])
async def test_switch_action_raises_when_plug_unreachable(
hass: HomeAssistant,
config_entry: MockConfigEntry,
service: str,
) -> None:
"""Test the switch action reports the failure to the caller."""
await init_integration(hass, config_entry, 106)
device = config_entry.runtime_data.device
device._state["on"] = True
device.turn_on = AsyncMock(side_effect=MyStromConnectionError())
device.turn_off = AsyncMock(side_effect=MyStromConnectionError())
with pytest.raises(HomeAssistantError) as exc_info:
await hass.services.async_call(
"switch",
service,
{ATTR_ENTITY_ID: "switch.mystrom_device"},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == "switch_action_failed"