Add integration for my-PV devices (#169872)

Co-authored-by: Robert Resch <robert@resch.dev>
This commit is contained in:
rrooggiieerr
2026-09-08 17:46:18 +02:00
committed by GitHub
co-authored by Robert Resch
parent 2b385bb0d7
commit 87da2fb0da
22 changed files with 2012 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
"""The tests for the my-PV component."""
ELWA2_SERIAL_NUMBER = "1601500000000000"
+78
View File
@@ -0,0 +1,78 @@
"""Common fixtures for the my-PV tests."""
from collections.abc import Generator
from unittest.mock import AsyncMock, Mock, patch
import pytest
from homeassistant.components.my_pv.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_PASSWORD
from . import ELWA2_SERIAL_NUMBER
from tests.common import MockConfigEntry
SETUP_CONFIGURATION = {
"ww1target": {"step": 0.1, "unit": "°C", "min": 5.0, "max": 95.0}
}
def _setup_configuration_lookup(key):
return SETUP_CONFIGURATION.get(key)
@pytest.fixture
def mock_config_entry() -> MockConfigEntry:
"""Return the my-PV mocked config entry for local devices."""
return MockConfigEntry(
title="my-PV AC ELWA 2 0000000000",
domain=DOMAIN,
data={
CONF_HOST: "127.0.0.1",
CONF_PASSWORD: "test-password",
},
unique_id=ELWA2_SERIAL_NUMBER,
)
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Prevent running the real integration setup during tests."""
with patch(
"homeassistant.components.my_pv.async_setup_entry",
return_value=True,
) as mock_setup:
yield mock_setup
@pytest.fixture
def mock_my_pv_client() -> Generator[AsyncMock]:
"""Mock the my-PV client across the integration."""
with (
patch(
"homeassistant.components.my_pv.MyPVLocalDevice",
autospec=True,
) as mock_client,
patch(
"homeassistant.components.my_pv.coordinator.MyPVDevice",
new=mock_client,
) as mock_client,
patch(
"homeassistant.components.my_pv.config_flow.MyPVLocalDevice",
new=mock_client,
),
):
client = mock_client.return_value
client.connect = AsyncMock(return_value=True)
client.disconnect = AsyncMock(return_value=True)
client.serial_number = ELWA2_SERIAL_NUMBER
client.model = "AC ELWA 2"
client.mac_address = "98:6d:35:c0:00:00"
client.setup_uri = "http://127.0.0.1/"
client.hardware_version = "v1.5A"
client.firmware_version = "e0002200"
client.current_temperature = 54.3
client.target_temperature = 62.1
client.get_setup_configuration = Mock(side_effect=_setup_configuration_lookup)
yield client
@@ -0,0 +1,72 @@
# serializer version: 1
# name: test_water_heater[water_heater.my_pv_ac_elwa_2-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
<WaterHeaterCapabilityAttribute.MAX_TEMP: 'max_temp'>: 95.0,
<WaterHeaterCapabilityAttribute.MIN_TEMP: 'min_temp'>: 5.0,
<WaterHeaterCapabilityAttribute.OPERATION_LIST: 'operation_list'>: list([
'off',
'electric',
]),
<WaterHeaterCapabilityAttribute.TARGET_TEMP_STEP: 'target_temp_step'>: 0.1,
}),
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'water_heater',
'entity_category': None,
'entity_id': 'water_heater.my_pv_ac_elwa_2',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': None,
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': None,
'platform': 'my_pv',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': <WaterHeaterEntityFeature: 11>,
'translation_key': None,
'unique_id': '1601500000000000-temp1',
'unit_of_measurement': None,
})
# ---
# name: test_water_heater[water_heater.my_pv_ac_elwa_2-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<WaterHeaterStateAttribute.CURRENT_TEMPERATURE: 'current_temperature'>: 54.3,
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'my-PV AC ELWA 2',
<WaterHeaterCapabilityAttribute.MAX_TEMP: 'max_temp'>: 95.0,
<WaterHeaterCapabilityAttribute.MIN_TEMP: 'min_temp'>: 5.0,
<WaterHeaterCapabilityAttribute.OPERATION_LIST: 'operation_list'>: list([
'off',
'electric',
]),
<WaterHeaterStateAttribute.OPERATION_MODE: 'operation_mode'>: 'electric',
<EntityStateAttribute.SUPPORTED_FEATURES: 'supported_features'>: <WaterHeaterEntityFeature: 11>,
<WaterHeaterStateAttribute.TARGET_TEMP_HIGH: 'target_temp_high'>: None,
<WaterHeaterStateAttribute.TARGET_TEMP_LOW: 'target_temp_low'>: None,
<WaterHeaterCapabilityAttribute.TARGET_TEMP_STEP: 'target_temp_step'>: 0.1,
<WaterHeaterStateAttribute.TARGET_TEMPERATURE: 'temperature'>: 62.1,
}),
'context': <ANY>,
'entity_id': 'water_heater.my_pv_ac_elwa_2',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'electric',
})
# ---
+444
View File
@@ -0,0 +1,444 @@
"""Test the my-PV config flow."""
from ipaddress import ip_address
from unittest.mock import AsyncMock
from my_pv.exceptions import MyPVAuthenticationError
import pytest
from homeassistant import config_entries
from homeassistant.components.my_pv.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import BaseServiceInfo, FlowResultType
from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from . import ELWA2_SERIAL_NUMBER
from tests.common import MockConfigEntry
DHCP_DISCOVERY = DhcpServiceInfo(
"127.0.0.1",
macaddress="986d35cabcde",
hostname=f"my-pv-ac-elwa-2-{ELWA2_SERIAL_NUMBER}.local.",
)
ZEROCONF_DISCOVERY = ZeroconfServiceInfo(
ip_address=ip_address("127.0.0.1"),
ip_addresses=[ip_address("127.0.0.1")],
hostname=f"my-pv-ac-elwa-2-{ELWA2_SERIAL_NUMBER}.local.",
name=f"my-pv-ac-elwa-2-{ELWA2_SERIAL_NUMBER}._mypv._tcp.local.",
port=443,
type="_mypv._tcp.local.",
properties={"": None},
)
@pytest.mark.usefixtures("mock_my_pv_client", "mock_setup_entry")
async def test_step_user(
hass: HomeAssistant,
) -> None:
"""Test if we get the local setup form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "127.0.0.1",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "my-PV AC ELWA 2 0000000000"
assert result["data"] == {
CONF_HOST: "127.0.0.1",
}
assert result["result"].unique_id == ELWA2_SERIAL_NUMBER
@pytest.mark.usefixtures("mock_my_pv_client")
async def test_step_user_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test for user configuration that is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "127.0.0.1",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_step_user_cannot_connect(
hass: HomeAssistant,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test if we get the local setup form with error if we can not connect to device."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
mock_my_pv_client.connect.return_value = False
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "127.0.0.1",
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"]["base"] == "cannot_connect"
mock_my_pv_client.connect.return_value = True
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "127.0.0.1",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "my-PV AC ELWA 2 0000000000"
assert result["data"] == {
CONF_HOST: "127.0.0.1",
}
assert result["result"].unique_id == ELWA2_SERIAL_NUMBER
@pytest.mark.usefixtures("mock_setup_entry")
async def test_step_auth(
hass: HomeAssistant,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test we get the authentication form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
mock_my_pv_client.connect.side_effect = MyPVAuthenticationError()
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "127.0.0.1",
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
assert not result["errors"]
mock_my_pv_client.connect.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PASSWORD: "test-password",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "my-PV AC ELWA 2 0000000000"
assert result["data"] == {
CONF_HOST: "127.0.0.1",
CONF_PASSWORD: "test-password",
}
assert result["result"].unique_id == ELWA2_SERIAL_NUMBER
async def test_step_auth_cannot_connect(
hass: HomeAssistant,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test we get the authentication form with error if we can not connect to device."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
mock_my_pv_client.connect.side_effect = MyPVAuthenticationError()
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "127.0.0.1",
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
assert not result["errors"]
mock_my_pv_client.connect.return_value = False
mock_my_pv_client.connect.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PASSWORD: "test-password",
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"]["base"] == "cannot_connect"
mock_my_pv_client.connect.return_value = True
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PASSWORD: "test-password",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "my-PV AC ELWA 2 0000000000"
assert result["data"] == {
CONF_HOST: "127.0.0.1",
CONF_PASSWORD: "test-password",
}
assert result["result"].unique_id == ELWA2_SERIAL_NUMBER
@pytest.mark.usefixtures("mock_setup_entry", "mock_my_pv_client")
async def test_step_dhcp(
hass: HomeAssistant,
) -> None:
"""Test for DHCP discovery that does not require a password."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURCE_DHCP,
},
data=DHCP_DISCOVERY,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "my-PV AC ELWA 2 0000000000"
assert result["data"] == {
CONF_HOST: "127.0.0.1",
}
assert result["result"].unique_id == ELWA2_SERIAL_NUMBER
@pytest.mark.parametrize(
("source", "data"),
[
(
config_entries.SOURCE_DHCP,
DHCP_DISCOVERY,
),
(
config_entries.SOURCE_ZEROCONF,
ZEROCONF_DISCOVERY,
),
],
)
@pytest.mark.usefixtures("mock_my_pv_client")
async def test_step_discovery_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
source: str,
data: BaseServiceInfo,
) -> None:
"""Test for discovery that is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": source,
},
data=data,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("source", "data"),
[
(
config_entries.SOURCE_DHCP,
DHCP_DISCOVERY,
),
(
config_entries.SOURCE_ZEROCONF,
ZEROCONF_DISCOVERY,
),
],
)
async def test_step_discovery_cannot_connect(
hass: HomeAssistant,
mock_my_pv_client: AsyncMock,
source: str,
data: BaseServiceInfo,
) -> None:
"""Test for discovery that can not connect."""
mock_my_pv_client.connect.return_value = False
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": source,
},
data=data,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
@pytest.mark.parametrize(
("source", "data"),
[
(
config_entries.SOURCE_DHCP,
DHCP_DISCOVERY,
),
(
config_entries.SOURCE_ZEROCONF,
ZEROCONF_DISCOVERY,
),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_step_discovery_auth(
hass: HomeAssistant,
mock_my_pv_client: AsyncMock,
source: str,
data: BaseServiceInfo,
) -> None:
"""Test for discovery that requires a password."""
mock_my_pv_client.connect.side_effect = MyPVAuthenticationError()
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": source,
},
data=data,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_auth"
assert not result["errors"]
mock_my_pv_client.connect.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "test-password"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "my-PV AC ELWA 2 0000000000"
assert result["data"] == {
CONF_HOST: "127.0.0.1",
CONF_PASSWORD: "test-password",
}
assert result["result"].unique_id == ELWA2_SERIAL_NUMBER
@pytest.mark.parametrize(
("source", "data"),
[
(
config_entries.SOURCE_DHCP,
DHCP_DISCOVERY,
),
(
config_entries.SOURCE_ZEROCONF,
ZEROCONF_DISCOVERY,
),
],
)
async def test_step_discovery_auth_wrong_password(
hass: HomeAssistant,
mock_my_pv_client: AsyncMock,
source: str,
data: BaseServiceInfo,
) -> None:
"""Test for discovery with an incorrect password."""
mock_my_pv_client.connect.side_effect = MyPVAuthenticationError()
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": source,
},
data=data,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_auth"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "wrong-password"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_auth"
assert result["errors"]["password"] == "invalid_password"
mock_my_pv_client.connect.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_PASSWORD: "test-password"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "my-PV AC ELWA 2 0000000000"
assert result["data"] == {
CONF_HOST: "127.0.0.1",
CONF_PASSWORD: "test-password",
}
assert result["result"].unique_id == ELWA2_SERIAL_NUMBER
+116
View File
@@ -0,0 +1,116 @@
"""Test the my-PV coordinator."""
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
from my_pv.exceptions import MyPVTooManyRequestsError
import pytest
from homeassistant.components.my_pv.coordinator import UPDATE_INTERVAL
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, async_fire_time_changed
@pytest.mark.usefixtures("mock_my_pv_client")
async def test_coordinator_update_data(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test a coordinator update."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
# Test successful setup and first data fetch
await hass.async_block_till_done()
states = hass.states.async_all()
assert False not in [state.state != STATE_UNAVAILABLE for state in states]
# Test successful data fetch
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
states = hass.states.async_all()
assert False not in [state.state != STATE_UNAVAILABLE for state in states]
async def test_coordinator_update_data_not_connected(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test coordinator update when client not connected."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
# Test successful setup and first data fetch
await hass.async_block_till_done()
states = hass.states.async_all()
assert False not in [state.state != STATE_UNAVAILABLE for state in states]
# Test states get unavailable when not connected
freezer.tick(UPDATE_INTERVAL)
mock_my_pv_client.connected = False
mock_my_pv_client.connect = AsyncMock(return_value=False)
async_fire_time_changed(hass)
await hass.async_block_till_done()
mock_my_pv_client.connect.assert_awaited_once_with()
states = hass.states.async_all()
assert False not in [state.state == STATE_UNAVAILABLE for state in states]
# Test successful data fetch
freezer.tick(UPDATE_INTERVAL)
mock_my_pv_client.connected = False
mock_my_pv_client.connect.reset_mock()
async def reconnect() -> bool:
mock_my_pv_client.connected = True
return True
mock_my_pv_client.connect.side_effect = reconnect
async_fire_time_changed(hass)
await hass.async_block_till_done()
mock_my_pv_client.connect.assert_awaited_once_with()
states = hass.states.async_all()
assert False not in [state.state != STATE_UNAVAILABLE for state in states]
async def test_coordinator_update_data_rate_limiting(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test coordinator update when client is rate limiting."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
# Test successful setup and first data fetch
await hass.async_block_till_done()
states = hass.states.async_all()
assert False not in [state.state != STATE_UNAVAILABLE for state in states]
# Test states stay available when rate limiting
freezer.tick(UPDATE_INTERVAL)
mock_my_pv_client.fetch_data = AsyncMock(side_effect=MyPVTooManyRequestsError)
async_fire_time_changed(hass)
await hass.async_block_till_done()
mock_my_pv_client.fetch_data.assert_awaited_once_with()
states = hass.states.async_all()
assert False not in [state.state != STATE_UNAVAILABLE for state in states]
# Test successful data fetch
freezer.tick(2 * UPDATE_INTERVAL)
mock_my_pv_client.fetch_data.reset_mock(side_effect=True)
async_fire_time_changed(hass)
await hass.async_block_till_done()
mock_my_pv_client.fetch_data.assert_awaited_once_with()
states = hass.states.async_all()
assert False not in [state.state != STATE_UNAVAILABLE for state in states]
+91
View File
@@ -0,0 +1,91 @@
"""Test the my-PV init."""
from unittest.mock import AsyncMock
from my_pv.exceptions import MyPVAuthenticationError, MyPVConnectionError
import pytest
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_my_pv_client")
async def test_setup_entry_success(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test successful setup of a config entry."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
async def test_setup_entry_cannot_connect(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test setup of a config entry when unable to connect."""
mock_config_entry.add_to_hass(hass)
mock_my_pv_client.connect.return_value = False
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_setup_entry_auth_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test setup of a config entry when authentication fails."""
mock_config_entry.add_to_hass(hass)
mock_my_pv_client.connect.side_effect = MyPVAuthenticationError()
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_setup_entry_failed_first_refresh(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test setup of a config entry when first refresh fails."""
mock_config_entry.add_to_hass(hass)
mock_my_pv_client.fetch_data.side_effect = MyPVConnectionError()
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
@pytest.mark.usefixtures("mock_my_pv_client")
async def test_unload_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test unloading a config entry."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
+411
View File
@@ -0,0 +1,411 @@
"""Test the my-PV water heater."""
from unittest.mock import AsyncMock, patch
from my_pv.exceptions import MyPVAuthenticationError, MyPVConnectionError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.water_heater import (
ATTR_OPERATION_MODE,
ATTR_TEMPERATURE,
DOMAIN as WATER_HEATER_DOMAIN,
SERVICE_SET_OPERATION_MODE,
SERVICE_SET_TEMPERATURE,
STATE_ELECTRIC,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("mock_my_pv_client")
async def test_water_heater(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test successful setup of a water heater."""
with patch("homeassistant.components.my_pv.PLATFORMS", [Platform.WATER_HEATER]):
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_water_heater_unavailable_not_connected(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test if a water_heater is unavailable when not connected."""
mock_config_entry.add_to_hass(hass)
mock_my_pv_client.connected = False
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_UNAVAILABLE
async def test_water_heater_unavailable_data_value_none(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test if a water_heater is unavailable when data value is None."""
mock_config_entry.add_to_hass(hass)
mock_my_pv_client.get_data_value.return_value = None
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_UNAVAILABLE
async def test_water_heater_turn_off(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test turning the water heater off."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_ELECTRIC
mock_my_pv_client.is_on = False
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_TURN_OFF,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
},
blocking=True,
)
mock_my_pv_client.turn_off.assert_awaited_once_with()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_OFF
async def test_water_heater_turn_off_false(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test turning off returns false."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_ELECTRIC
mock_my_pv_client.turn_off = AsyncMock(return_value=False)
with (
pytest.raises(HomeAssistantError),
):
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_TURN_OFF,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
},
blocking=True,
)
mock_my_pv_client.turn_off.assert_awaited_once_with()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_ELECTRIC
async def test_water_heater_turn_on(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test turning the water heater on."""
mock_config_entry.add_to_hass(hass)
mock_my_pv_client.is_on = False
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_OFF
mock_my_pv_client.is_on = True
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
},
blocking=True,
)
mock_my_pv_client.turn_on.assert_awaited_once_with()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_ELECTRIC
async def test_water_heater_turn_on_false(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test turning on returns false."""
mock_config_entry.add_to_hass(hass)
mock_my_pv_client.is_on = False
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_OFF
mock_my_pv_client.turn_on = AsyncMock(return_value=False)
with (
pytest.raises(HomeAssistantError),
):
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
},
blocking=True,
)
mock_my_pv_client.turn_on.assert_awaited_once_with()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_OFF
async def test_water_heater_set_operation_off(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test setting the operation mode to off."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_ELECTRIC
mock_my_pv_client.is_on = False
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_OPERATION_MODE,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
ATTR_OPERATION_MODE: STATE_OFF,
},
blocking=True,
)
mock_my_pv_client.turn_off.assert_awaited_once_with()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_OFF
async def test_water_heater_set_operation_electric(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test setting the operation mode to electric."""
mock_config_entry.add_to_hass(hass)
mock_my_pv_client.is_on = False
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_OFF
mock_my_pv_client.is_on = True
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_OPERATION_MODE,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
ATTR_OPERATION_MODE: STATE_ELECTRIC,
},
blocking=True,
)
mock_my_pv_client.turn_on.assert_awaited_once_with()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.state == STATE_ELECTRIC
async def test_water_heater_set_temp(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test setting the target temperature."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.attributes[ATTR_TEMPERATURE] == 62.1
mock_my_pv_client.target_temperature = 35
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
ATTR_TEMPERATURE: 35,
},
blocking=True,
)
mock_my_pv_client.set_target_temperature.assert_awaited_once_with(35)
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.attributes[ATTR_TEMPERATURE] == 35
async def test_water_heater_set_temp_false(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test setting the target temperature returns false."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
mock_my_pv_client.set_target_temperature = AsyncMock(return_value=False)
with (
pytest.raises(HomeAssistantError),
):
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
ATTR_TEMPERATURE: 35,
},
blocking=True,
)
mock_my_pv_client.set_target_temperature.assert_awaited_once_with(35)
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.attributes[ATTR_TEMPERATURE] == 62.1
async def test_water_heater_set_temp_connection_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test connection error when setting the target temperature."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
mock_my_pv_client.set_target_temperature.side_effect = MyPVConnectionError()
with (
pytest.raises(HomeAssistantError),
):
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
ATTR_TEMPERATURE: 35,
},
blocking=True,
)
mock_my_pv_client.set_target_temperature.assert_awaited_once_with(35)
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.attributes[ATTR_TEMPERATURE] == 62.1
async def test_water_heater_set_temp_authentication_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_my_pv_client: AsyncMock,
) -> None:
"""Test authentication error when setting the target temperature."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
mock_my_pv_client.set_target_temperature.side_effect = MyPVAuthenticationError()
with (
pytest.raises(ConfigEntryAuthFailed),
):
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "water_heater.my_pv_ac_elwa_2",
ATTR_TEMPERATURE: 35,
},
blocking=True,
)
mock_my_pv_client.set_target_temperature.assert_awaited_once_with(35)
state = hass.states.get("water_heater.my_pv_ac_elwa_2")
assert state.attributes[ATTR_TEMPERATURE] == 62.1