Skip to content

Commit

Permalink
Cleanup Discovergy a bit (home-assistant#104552)
Browse files Browse the repository at this point in the history
Co-authored-by: Joost Lekkerkerker <[email protected]>
  • Loading branch information
jpbede and joostlek authored Nov 26, 2023
1 parent ad17acc commit b314df2
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 67 deletions.
6 changes: 3 additions & 3 deletions homeassistant/components/discovergy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from dataclasses import dataclass

import pydiscovergy
from pydiscovergy import Discovergy
from pydiscovergy.authentication import BasicAuth
import pydiscovergy.error as discovergyError
from pydiscovergy.models import Meter
Expand All @@ -24,7 +24,7 @@
class DiscovergyData:
"""Discovergy data class to share meters and api client."""

api_client: pydiscovergy.Discovergy
api_client: Discovergy
meters: list[Meter]
coordinators: dict[str, DiscovergyUpdateCoordinator]

Expand All @@ -35,7 +35,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

# init discovergy data class
discovergy_data = DiscovergyData(
api_client=pydiscovergy.Discovergy(
api_client=Discovergy(
email=entry.data[CONF_EMAIL],
password=entry.data[CONF_PASSWORD],
httpx_client=get_async_client(hass),
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/discovergy/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import logging
from typing import Any

import pydiscovergy
from pydiscovergy import Discovergy
from pydiscovergy.authentication import BasicAuth
import pydiscovergy.error as discovergyError
import voluptuous as vol
Expand Down Expand Up @@ -70,7 +70,7 @@ async def _validate_and_save(

if user_input:
try:
await pydiscovergy.Discovergy(
await Discovergy(
email=user_input[CONF_EMAIL],
password=user_input[CONF_PASSWORD],
httpx_client=get_async_client(self.hass),
Expand Down
7 changes: 1 addition & 6 deletions homeassistant/components/discovergy/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,12 @@
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)


class DiscovergyUpdateCoordinator(DataUpdateCoordinator[Reading]):
"""The Discovergy update coordinator."""

discovergy_client: Discovergy
meter: Meter

def __init__(
self,
hass: HomeAssistant,
Expand All @@ -36,7 +31,7 @@ def __init__(
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
name=f"Discovergy meter {meter.meter_id}",
update_interval=timedelta(seconds=30),
)

Expand Down
5 changes: 1 addition & 4 deletions homeassistant/components/discovergy/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
from dataclasses import asdict
from typing import Any

from pydiscovergy.models import Meter

from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
Expand All @@ -30,9 +28,8 @@ async def async_get_config_entry_diagnostics(
flattened_meter: list[dict] = []
last_readings: dict[str, dict] = {}
data: DiscovergyData = hass.data[DOMAIN][entry.entry_id]
meters: list[Meter] = data.meters # always returns a list

for meter in meters:
for meter in data.meters:
# make a dict of meter data and redact some data
flattened_meter.append(async_redact_data(asdict(meter), TO_REDACT_METER))

Expand Down
5 changes: 1 addition & 4 deletions homeassistant/components/discovergy/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
from . import DiscovergyData, DiscovergyUpdateCoordinator
from .const import DOMAIN, MANUFACTURER

PARALLEL_UPDATES = 1


def _get_and_scale(reading: Reading, key: str, scale: int) -> datetime | float | None:
"""Get a value from a Reading and divide with scale it."""
Expand Down Expand Up @@ -168,10 +166,9 @@ async def async_setup_entry(
) -> None:
"""Set up the Discovergy sensors."""
data: DiscovergyData = hass.data[DOMAIN][entry.entry_id]
meters: list[Meter] = data.meters # always returns a list

entities: list[DiscovergySensor] = []
for meter in meters:
for meter in data.meters:
sensors: tuple[DiscovergySensorEntityDescription, ...] = ()
coordinator: DiscovergyUpdateCoordinator = data.coordinators[meter.meter_id]

Expand Down
15 changes: 8 additions & 7 deletions tests/components/discovergy/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from collections.abc import Generator
from unittest.mock import AsyncMock, patch

from pydiscovergy import Discovergy
from pydiscovergy.models import Reading
import pytest

Expand All @@ -27,14 +26,16 @@ def _meter_last_reading(meter_id: str) -> Reading:
@pytest.fixture(name="discovergy")
def mock_discovergy() -> Generator[AsyncMock, None, None]:
"""Mock the pydiscovergy client."""
mock = AsyncMock(spec=Discovergy)
mock.meters.return_value = GET_METERS
mock.meter_last_reading.side_effect = _meter_last_reading

with patch(
"homeassistant.components.discovergy.pydiscovergy.Discovergy",
return_value=mock,
"homeassistant.components.discovergy.Discovergy",
autospec=True,
) as mock_discovergy, patch(
"homeassistant.components.discovergy.config_flow.Discovergy",
new=mock_discovergy,
):
mock = mock_discovergy.return_value
mock.meters.return_value = GET_METERS
mock.meter_last_reading.side_effect = _meter_last_reading
yield mock


Expand Down
71 changes: 30 additions & 41 deletions tests/components/discovergy/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from homeassistant.core import HomeAssistant

from tests.common import MockConfigEntry
from tests.components.discovergy.const import GET_METERS


async def test_form(hass: HomeAssistant, discovergy: AsyncMock) -> None:
Expand All @@ -25,10 +24,7 @@ async def test_form(hass: HomeAssistant, discovergy: AsyncMock) -> None:
with patch(
"homeassistant.components.discovergy.async_setup_entry",
return_value=True,
) as mock_setup_entry, patch(
"homeassistant.components.discovergy.config_flow.pydiscovergy.Discovergy",
return_value=discovergy,
):
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
Expand Down Expand Up @@ -65,10 +61,7 @@ async def test_reauth(
with patch(
"homeassistant.components.discovergy.async_setup_entry",
return_value=True,
) as mock_setup_entry, patch(
"homeassistant.components.discovergy.config_flow.pydiscovergy.Discovergy",
return_value=discovergy,
):
) as mock_setup_entry:
configure_result = await hass.config_entries.flow.async_configure(
init_result["flow_id"],
{
Expand All @@ -92,38 +85,34 @@ async def test_reauth(
(Exception, "unknown"),
],
)
async def test_form_fail(hass: HomeAssistant, error: Exception, message: str) -> None:
async def test_form_fail(
hass: HomeAssistant, discovergy: AsyncMock, error: Exception, message: str
) -> None:
"""Test to handle exceptions."""
discovergy.meters.side_effect = error
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data={
CONF_EMAIL: "[email protected]",
CONF_PASSWORD: "test-password",
},
)

with patch(
"homeassistant.components.discovergy.config_flow.pydiscovergy.Discovergy.meters",
side_effect=error,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data={
CONF_EMAIL: "[email protected]",
CONF_PASSWORD: "test-password",
},
)

assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": message}

with patch(
"homeassistant.components.discovergy.config_flow.pydiscovergy.Discovergy.meters",
return_value=GET_METERS,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_EMAIL: "[email protected]",
CONF_PASSWORD: "test-password",
},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": message}

# reset and test for success
discovergy.meters.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_EMAIL: "[email protected]",
CONF_PASSWORD: "test-password",
},
)

assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "[email protected]"
assert "errors" not in result
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "[email protected]"
assert "errors" not in result

0 comments on commit b314df2

Please sign in to comment.