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

Refactor tests for discovergy #103667

Merged
merged 3 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
25 changes: 25 additions & 0 deletions tests/components/discovergy/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,26 @@
"""Test the Discovergy integration."""
from tests.components.discovergy.const import GET_METERS, LAST_READING, LAST_READING_GAS


class MockDiscovergy:
jpbede marked this conversation as resolved.
Show resolved Hide resolved
"""Mock Discovergy class."""

_thrown_error: Exception | None = None

async def meters(self):
"""Return mock meters."""
return GET_METERS

async def meter_last_reading(self, meter_id: str):
"""Return mock meter last reading."""
if self._thrown_error:
raise self._thrown_error
return (
LAST_READING_GAS
if meter_id == "d81a652fe0824f9a9d336016587d3b9d"
else LAST_READING
)

def set_thrown_exception(self, exception: Exception) -> None:
"""Set thrown exception for testing purposes."""
self._thrown_error = exception
43 changes: 30 additions & 13 deletions tests/components/discovergy/conftest.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,50 @@
"""Fixtures for Discovergy integration tests."""
from unittest.mock import AsyncMock, Mock, patch
from collections.abc import Callable, Coroutine
from typing import Any
from unittest.mock import patch

import pytest

from homeassistant.components.discovergy import DOMAIN
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component

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

ComponentSetup = Callable[[], Coroutine[Any, Any, MockDiscovergy]]

@pytest.fixture
def mock_meters() -> Mock:
"""Patch libraries."""
with patch("pydiscovergy.Discovergy.meters") as discovergy:
discovergy.side_effect = AsyncMock(return_value=GET_METERS)
yield discovergy


@pytest.fixture
@pytest.fixture(name="config_entry")
async def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Return a MockConfigEntry for testing."""
entry = MockConfigEntry(
return MockConfigEntry(
domain=DOMAIN,
title="user@example.org",
unique_id="user@example.org",
data={CONF_EMAIL: "user@example.org", CONF_PASSWORD: "supersecretpassword"},
)
entry.add_to_hass(hass)

return entry

@pytest.fixture(name="setup_integration")
async def mock_setup_integration(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> Callable[[], Coroutine[Any, Any, MockDiscovergy]]:
"""Fixture for setting up the component."""
config_entry.add_to_hass(hass)

async def func() -> MockDiscovergy:
mock = MockDiscovergy()
with patch(
"homeassistant.components.discovergy.coordinator.Discovergy",
return_value=mock,
), patch(
"homeassistant.components.discovergy.pydiscovergy.Discovergy",
return_value=mock,
):
jpbede marked this conversation as resolved.
Show resolved Hide resolved
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
return mock

return func
31 changes: 31 additions & 0 deletions tests/components/discovergy/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,32 @@
"last_measurement_time": 1678430543742,
},
),
Meter(
meter_id="d81a652fe0824f9a9d336016587d3b9d",
serial_number="def456",
full_serial_number="def456",
type="PIP",
measurement_type="GAS",
load_profile_type="SLP",
location=Location(
zip=12345,
city="Testhause",
street="Teststraße",
street_number="1",
country="Germany",
),
additional={
"manufacturer_id": "TST",
"printed_full_serial_number": "def456",
"administration_number": "12345",
"scaling_factor": 1,
"current_scaling_factor": 1,
"voltage_scaling_factor": 1,
"internal_meters": 1,
"first_measurement_time": 1517569090926,
"last_measurement_time": 1678430543742,
},
),
]

LAST_READING = Reading(
Expand All @@ -50,3 +76,8 @@
"voltage3": 239000.0,
},
)

LAST_READING_GAS = Reading(
time=datetime.datetime(2023, 3, 10, 7, 32, 6, 702000),
values={"actualityDuration": 52000.0, "storageNumber": 0.0, "volume": 21064800.0},
)
28 changes: 28 additions & 0 deletions tests/components/discovergy/snapshots/test_diagnostics.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,36 @@
'serial_number': '**REDACTED**',
'type': 'TST',
}),
dict({
'additional': dict({
'administration_number': '**REDACTED**',
'current_scaling_factor': 1,
'first_measurement_time': 1517569090926,
'internal_meters': 1,
'last_measurement_time': 1678430543742,
'manufacturer_id': 'TST',
'printed_full_serial_number': '**REDACTED**',
'scaling_factor': 1,
'voltage_scaling_factor': 1,
}),
'full_serial_number': '**REDACTED**',
'load_profile_type': 'SLP',
'location': '**REDACTED**',
'measurement_type': 'GAS',
'meter_id': 'd81a652fe0824f9a9d336016587d3b9d',
'serial_number': '**REDACTED**',
'type': 'PIP',
}),
]),
'readings': dict({
'd81a652fe0824f9a9d336016587d3b9d': dict({
'time': '2023-03-10T07:32:06.702000',
'values': dict({
'actualityDuration': 52000.0,
'storageNumber': 0.0,
'volume': 21064800.0,
}),
}),
'f8d610b7a8cc4e73939fa33b990ded54': dict({
'time': '2023-03-10T07:32:06.702000',
'values': dict({
Expand Down
30 changes: 20 additions & 10 deletions tests/components/discovergy/test_config_flow.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Test the Discovergy config flow."""
from unittest.mock import Mock, patch
from unittest.mock import patch

from pydiscovergy.error import DiscovergyClientError, HTTPError, InvalidLogin
import pytest
Expand All @@ -11,10 +11,11 @@
from homeassistant.core import HomeAssistant

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


async def test_form(hass: HomeAssistant, mock_meters: Mock) -> None:
async def test_form(hass: HomeAssistant) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
Expand All @@ -25,7 +26,10 @@ async def test_form(hass: HomeAssistant, mock_meters: Mock) -> None:
with patch(
"homeassistant.components.discovergy.async_setup_entry",
return_value=True,
) as mock_setup_entry:
) as mock_setup_entry, patch(
"homeassistant.components.discovergy.config_flow.pydiscovergy.Discovergy",
return_value=MockDiscovergy(),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
Expand All @@ -44,13 +48,13 @@ async def test_form(hass: HomeAssistant, mock_meters: Mock) -> None:
assert len(mock_setup_entry.mock_calls) == 1


async def test_reauth(
hass: HomeAssistant, mock_meters: Mock, mock_config_entry: MockConfigEntry
) -> None:
async def test_reauth(hass: HomeAssistant, config_entry: MockConfigEntry) -> None:
"""Test reauth flow."""
config_entry.add_to_hass(hass)

init_result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_REAUTH, "unique_id": mock_config_entry.unique_id},
context={"source": SOURCE_REAUTH, "unique_id": config_entry.unique_id},
data=None,
)

Expand All @@ -60,7 +64,10 @@ async def test_reauth(
with patch(
"homeassistant.components.discovergy.async_setup_entry",
return_value=True,
) as mock_setup_entry:
) as mock_setup_entry, patch(
"homeassistant.components.discovergy.config_flow.pydiscovergy.Discovergy",
return_value=MockDiscovergy(),
):
configure_result = await hass.config_entries.flow.async_configure(
init_result["flow_id"],
{
Expand Down Expand Up @@ -88,7 +95,7 @@ async def test_form_fail(hass: HomeAssistant, error: Exception, message: str) ->
"""Test to handle exceptions."""

with patch(
"pydiscovergy.Discovergy.meters",
"homeassistant.components.discovergy.config_flow.pydiscovergy.Discovergy.meters",
side_effect=error,
):
result = await hass.config_entries.flow.async_init(
Expand All @@ -104,7 +111,10 @@ async def test_form_fail(hass: HomeAssistant, error: Exception, message: str) ->
assert result["step_id"] == "user"
assert result["errors"] == {"base": message}

with patch("pydiscovergy.Discovergy.meters", return_value=GET_METERS):
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"],
{
Expand Down
16 changes: 5 additions & 11 deletions tests/components/discovergy/test_diagnostics.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,25 @@
"""Test Discovergy diagnostics."""
from unittest.mock import patch

from syrupy import SnapshotAssertion

from homeassistant.core import HomeAssistant

from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.components.discovergy.const import GET_METERS, LAST_READING
from tests.components.discovergy.conftest import ComponentSetup
from tests.typing import ClientSessionGenerator


async def test_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
config_entry: MockConfigEntry,
setup_integration: ComponentSetup,
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry diagnostics."""
with patch("pydiscovergy.Discovergy.meters", return_value=GET_METERS), patch(
"pydiscovergy.Discovergy.meter_last_reading", return_value=LAST_READING
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await setup_integration()

result = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
result = await get_diagnostics_for_config_entry(hass, hass_client, config_entry)

assert result == snapshot