From 7c030cfffaa56b975a491eafae072b6d3634ea08 Mon Sep 17 00:00:00 2001 From: Jan-Philipp Benecke Date: Thu, 16 Nov 2023 16:13:15 +0100 Subject: [PATCH] Add tests for Discovergy to reach full test coverage (#104039) * Add tests for Discovergy to reach full test coverage * Use snapshots and freezer --- .coveragerc | 3 - .../discovergy/snapshots/test_sensor.ambr | 154 ++++++++++++++++++ tests/components/discovergy/test_init.py | 62 +++++++ tests/components/discovergy/test_sensor.py | 71 ++++++++ 4 files changed, 287 insertions(+), 3 deletions(-) create mode 100644 tests/components/discovergy/snapshots/test_sensor.ambr create mode 100644 tests/components/discovergy/test_init.py create mode 100644 tests/components/discovergy/test_sensor.py diff --git a/.coveragerc b/.coveragerc index d6809f4301d..13de6cb29c8 100644 --- a/.coveragerc +++ b/.coveragerc @@ -218,9 +218,6 @@ omit = homeassistant/components/discogs/sensor.py homeassistant/components/discord/__init__.py homeassistant/components/discord/notify.py - homeassistant/components/discovergy/__init__.py - homeassistant/components/discovergy/sensor.py - homeassistant/components/discovergy/coordinator.py homeassistant/components/dlib_face_detect/image_processing.py homeassistant/components/dlib_face_identify/image_processing.py homeassistant/components/dlink/data.py diff --git a/tests/components/discovergy/snapshots/test_sensor.ambr b/tests/components/discovergy/snapshots/test_sensor.ambr new file mode 100644 index 00000000000..36af1276fe1 --- /dev/null +++ b/tests/components/discovergy/snapshots/test_sensor.ambr @@ -0,0 +1,154 @@ +# serializer version: 1 +# name: test_sensor[electricity total consumption] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.electricity_teststrasse_1_total_consumption', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 4, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Total consumption', + 'platform': 'discovergy', + 'previous_unique_id': None, + 'supported_features': 0, + 'translation_key': 'total_consumption', + 'unique_id': 'abc123-energy', + 'unit_of_measurement': , + }) +# --- +# name: test_sensor[electricity total consumption].1 + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'energy', + 'friendly_name': 'Electricity Teststraße 1 Total consumption', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.electricity_teststrasse_1_total_consumption', + 'last_changed': , + 'last_updated': , + 'state': '11934.8699715', + }) +# --- +# name: test_sensor[electricity total power] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.electricity_teststrasse_1_total_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 3, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Total power', + 'platform': 'discovergy', + 'previous_unique_id': None, + 'supported_features': 0, + 'translation_key': 'total_power', + 'unique_id': 'abc123-power', + 'unit_of_measurement': , + }) +# --- +# name: test_sensor[electricity total power].1 + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'power', + 'friendly_name': 'Electricity Teststraße 1 Total power', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.electricity_teststrasse_1_total_power', + 'last_changed': , + 'last_updated': , + 'state': '531.75', + }) +# --- +# name: test_sensor[gas total consumption] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.gas_teststrasse_1_total_gas_consumption', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 4, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Total gas consumption', + 'platform': 'discovergy', + 'previous_unique_id': None, + 'supported_features': 0, + 'translation_key': 'total_gas_consumption', + 'unique_id': 'def456-volume', + 'unit_of_measurement': , + }) +# --- +# name: test_sensor[gas total consumption].1 + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'gas', + 'friendly_name': 'Gas Teststraße 1 Total gas consumption', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.gas_teststrasse_1_total_gas_consumption', + 'last_changed': , + 'last_updated': , + 'state': '21064.8', + }) +# --- diff --git a/tests/components/discovergy/test_init.py b/tests/components/discovergy/test_init.py new file mode 100644 index 00000000000..ac8f79540f5 --- /dev/null +++ b/tests/components/discovergy/test_init.py @@ -0,0 +1,62 @@ +"""Test Discovergy component setup.""" +from unittest.mock import AsyncMock + +from pydiscovergy.error import DiscovergyClientError, HTTPError, InvalidLogin +import pytest + +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import HomeAssistant + +from tests.common import MockConfigEntry + + +@pytest.mark.usefixtures("discovergy") +async def test_config_setup( + hass: HomeAssistant, + config_entry: MockConfigEntry, +) -> None: + """Test for setup success.""" + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + assert config_entry.state is ConfigEntryState.LOADED + + +@pytest.mark.parametrize( + ("error", "expected_state"), + [ + (InvalidLogin, ConfigEntryState.SETUP_ERROR), + (HTTPError, ConfigEntryState.SETUP_RETRY), + (DiscovergyClientError, ConfigEntryState.SETUP_RETRY), + (Exception, ConfigEntryState.SETUP_RETRY), + ], +) +async def test_config_not_ready( + hass: HomeAssistant, + config_entry: MockConfigEntry, + discovergy: AsyncMock, + error: Exception, + expected_state: ConfigEntryState, +) -> None: + """Test for setup failure.""" + config_entry.add_to_hass(hass) + + discovergy.meters.side_effect = error + + await hass.config_entries.async_setup(config_entry.entry_id) + assert config_entry.state is expected_state + + +@pytest.mark.usefixtures("setup_integration") +async def test_reload_config_entry( + hass: HomeAssistant, + config_entry: MockConfigEntry, +) -> None: + """Test config entry reload.""" + new_data = {"email": "abc@example.com", "password": "password"} + + assert config_entry.state is ConfigEntryState.LOADED + + assert hass.config_entries.async_update_entry(config_entry, data=new_data) + + assert config_entry.state is ConfigEntryState.LOADED + assert config_entry.data == new_data diff --git a/tests/components/discovergy/test_sensor.py b/tests/components/discovergy/test_sensor.py new file mode 100644 index 00000000000..33fb1a37cd9 --- /dev/null +++ b/tests/components/discovergy/test_sensor.py @@ -0,0 +1,71 @@ +"""Tests Discovergy sensor component.""" +from datetime import timedelta +from unittest.mock import AsyncMock + +from freezegun.api import FrozenDateTimeFactory +from pydiscovergy.error import DiscovergyClientError, HTTPError, InvalidLogin +import pytest +from syrupy import SnapshotAssertion + +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + + +@pytest.mark.parametrize( + "state_name", + [ + "sensor.electricity_teststrasse_1_total_consumption", + "sensor.electricity_teststrasse_1_total_power", + "sensor.gas_teststrasse_1_total_gas_consumption", + ], + ids=[ + "electricity total consumption", + "electricity total power", + "gas total consumption", + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_sensor( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + state_name: str, + snapshot: SnapshotAssertion, +) -> None: + """Test sensor setup and update.""" + + entry = entity_registry.async_get(state_name) + assert entry == snapshot + + state = hass.states.get(state_name) + assert state == snapshot + + +@pytest.mark.parametrize( + "error", + [ + InvalidLogin, + HTTPError, + DiscovergyClientError, + Exception, + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_sensor_update_fail( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + discovergy: AsyncMock, + error: Exception, +) -> None: + """Test sensor errors.""" + state = hass.states.get("sensor.electricity_teststrasse_1_total_consumption") + assert state + assert state.state == "11934.8699715" + + discovergy.meter_last_reading.side_effect = error + + freezer.tick(timedelta(minutes=1)) + await hass.async_block_till_done() + + state = hass.states.get("sensor.electricity_teststrasse_1_total_consumption") + assert state + assert state.state == "unavailable"