Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests for Discovergy to reach full test coverage #104039

Merged
merged 2 commits into from Nov 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 0 additions & 3 deletions .coveragerc
Expand Up @@ -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
Expand Down
154 changes: 154 additions & 0 deletions 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': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'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': <ANY>,
'name': None,
'options': dict({
'sensor': dict({
'suggested_display_precision': 4,
}),
}),
'original_device_class': <SensorDeviceClass.ENERGY: 'energy'>,
'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': <UnitOfEnergy.KILO_WATT_HOUR: 'kWh'>,
})
# ---
# name: test_sensor[electricity total consumption].1
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'energy',
'friendly_name': 'Electricity Teststraße 1 Total consumption',
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
'unit_of_measurement': <UnitOfEnergy.KILO_WATT_HOUR: 'kWh'>,
}),
'context': <ANY>,
'entity_id': 'sensor.electricity_teststrasse_1_total_consumption',
'last_changed': <ANY>,
'last_updated': <ANY>,
'state': '11934.8699715',
})
# ---
# name: test_sensor[electricity total power]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'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': <ANY>,
'name': None,
'options': dict({
'sensor': dict({
'suggested_display_precision': 3,
}),
}),
'original_device_class': <SensorDeviceClass.POWER: 'power'>,
'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': <UnitOfPower.WATT: 'W'>,
})
# ---
# name: test_sensor[electricity total power].1
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'power',
'friendly_name': 'Electricity Teststraße 1 Total power',
'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>,
'unit_of_measurement': <UnitOfPower.WATT: 'W'>,
}),
'context': <ANY>,
'entity_id': 'sensor.electricity_teststrasse_1_total_power',
'last_changed': <ANY>,
'last_updated': <ANY>,
'state': '531.75',
})
# ---
# name: test_sensor[gas total consumption]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
}),
'config_entry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'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': <ANY>,
'name': None,
'options': dict({
'sensor': dict({
'suggested_display_precision': 4,
}),
}),
'original_device_class': <SensorDeviceClass.GAS: 'gas'>,
'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': <UnitOfVolume.CUBIC_METERS: 'm³'>,
})
# ---
# name: test_sensor[gas total consumption].1
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'gas',
'friendly_name': 'Gas Teststraße 1 Total gas consumption',
'state_class': <SensorStateClass.TOTAL_INCREASING: 'total_increasing'>,
'unit_of_measurement': <UnitOfVolume.CUBIC_METERS: 'm³'>,
}),
'context': <ANY>,
'entity_id': 'sensor.gas_teststrasse_1_total_gas_consumption',
'last_changed': <ANY>,
'last_updated': <ANY>,
'state': '21064.8',
})
# ---
62 changes: 62 additions & 0 deletions 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
71 changes: 71 additions & 0 deletions 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(
jpbede marked this conversation as resolved.
Show resolved Hide resolved
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
jpbede marked this conversation as resolved.
Show resolved Hide resolved

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"