Refactor Anglian Water tests (#191103)

This commit is contained in:
Jordan Harvey
2026-11-08 08:01:14 +01:00
committed by GitHub
parent c87112a673
commit 9822af19be
5 changed files with 758 additions and 437 deletions
@@ -1,49 +0,0 @@
# serializer version: 1
# name: test_coordinator_first_run
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.025,
'sum': 50.0,
}),
]),
})
# ---
# name: test_coordinator_subsequent_run
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.025,
'sum': 50.0,
}),
]),
})
# ---
@@ -0,0 +1,211 @@
# serializer version: 1
# name: test_period_statistics_without_sum
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.025,
'sum': 50.0,
}),
dict({
'end': 1717279200.0,
'start': 1717275600.0,
'state': 0.02,
'sum': 70.0,
}),
]),
})
# ---
# name: test_statistics_invalid_readings[invalid_first_timestamp]
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.025,
'sum': 50.0,
}),
]),
})
# ---
# name: test_statistics_invalid_readings[invalid_later_timestamp]
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.025,
'sum': 50.0,
}),
]),
})
# ---
# name: test_statistics_invalid_readings[no_readings]
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.025,
'sum': 50.0,
}),
]),
})
# ---
# name: test_statistics_subsequent_run[corrected_reading]
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.035,
'sum': 70.0,
}),
]),
})
# ---
# name: test_statistics_subsequent_run[new_and_updated_readings]
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.025,
'sum': 50.0,
}),
dict({
'end': 1717279200.0,
'start': 1717275600.0,
'state': 0.02,
'sum': 90.0,
}),
]),
})
# ---
# name: test_statistics_subsequent_run[new_readings_only]
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.025,
'sum': 50.0,
}),
dict({
'end': 1717279200.0,
'start': 1717275600.0,
'state': 0.02,
'sum': 70.0,
}),
]),
})
# ---
# name: test_statistics_subsequent_run[no_new_readings]
defaultdict({
'anglian_water:171266493_testsn_usage': list([
dict({
'end': 1717268400.0,
'start': 1717264800.0,
'state': 0.01,
'sum': 10.0,
}),
dict({
'end': 1717272000.0,
'start': 1717268400.0,
'state': 0.015,
'sum': 25.0,
}),
dict({
'end': 1717275600.0,
'start': 1717272000.0,
'state': 0.025,
'sum': 50.0,
}),
]),
})
# ---
@@ -1,357 +0,0 @@
"""Tests for the Anglian Water coordinator."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from pyanglianwater.exceptions import (
ConsentRequiredError,
ExpiredAccessTokenError,
InvalidGrantError,
UnknownEndpointError,
)
from pyanglianwater.meter import SmartMeter
import pytest
from pytest_homeassistant.common import MockConfigEntry
from pytest_homeassistant.components.recorder.common import async_wait_recording_done
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.anglian_water.const import DOMAIN
from homeassistant.components.anglian_water.coordinator import (
AnglianWaterUpdateCoordinator,
)
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.statistics import (
get_last_statistics,
statistics_during_period,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.update_coordinator import UpdateFailed
from homeassistant.util import dt as dt_util
from .const import ACCOUNT_NUMBER, CONSENT_REQUIRED_ISSUE_ID
async def test_coordinator_first_run(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test the coordinator on its first run with no existing statistics."""
coordinator = AnglianWaterUpdateCoordinator(
hass, mock_anglian_water_client, mock_config_entry
)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
dt_util.utc_from_timestamp(0),
None,
{
f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage",
},
"hour",
None,
{"state", "sum"},
)
assert stats == snapshot
async def test_coordinator_subsequent_run(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_smart_meter: SmartMeter,
mock_anglian_water_client: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test the coordinator correctly updates statistics on subsequent runs."""
# 1st run
coordinator = AnglianWaterUpdateCoordinator(
hass, mock_anglian_water_client, mock_config_entry
)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# 2nd run with an updated reading for one read and a new read added.
mock_smart_meter.readings[-1] = {
"read_at": "2024-06-01T14:00:00Z",
"consumption": 35,
"read": 70,
}
mock_smart_meter.readings.append(
{"read_at": "2024-06-01T15:00:00Z", "consumption": 20, "read": 90}
)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# Check all stats
stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
dt_util.utc_from_timestamp(0),
None,
{
f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage",
},
"hour",
None,
{"state", "sum"},
)
assert stats == snapshot
async def test_coordinator_subsequent_run_no_energy_data(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_smart_meter: SmartMeter,
mock_anglian_water_client: AsyncMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the coordinator handles no recent usage/cost data."""
# 1st run
coordinator = AnglianWaterUpdateCoordinator(
hass, mock_anglian_water_client, mock_config_entry
)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# 2nd run with no readings
mock_smart_meter.readings = []
await coordinator._async_update_data()
assert "No recent usage statistics found, skipping update" in caplog.text
# Verify no new stats were added by checking the sum remains 50
statistic_id = f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage"
stats = await hass.async_add_executor_job(
get_last_statistics, hass, 1, statistic_id, True, {"sum"}
)
assert stats[statistic_id][0]["sum"] == 50
async def test_coordinator_invalid_readings(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_smart_meter: SmartMeter,
mock_anglian_water_client: AsyncMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the coordinator handles bad data / invalid readings correctly."""
coordinator = AnglianWaterUpdateCoordinator(
hass, mock_anglian_water_client, mock_config_entry
)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# Test that an invalid read_at on the first reading skips the entire update
mock_smart_meter.readings = [
{"read_at": "invalid-date-format", "consumption": 10, "read": 10},
]
await coordinator._async_update_data()
assert (
"Could not parse read_at time invalid-date-format, skipping update"
in caplog.text
)
# Test that individual invalid readings are skipped
mock_smart_meter.readings = [
{"read_at": "2024-06-01T12:00:00Z", "consumption": 10, "read": 10},
{"read_at": "also-invalid-date", "consumption": 15, "read": 25},
]
await coordinator._async_update_data()
assert (
"Could not parse read_at time also-invalid-date, skipping reading"
in caplog.text
)
async def test_coordinator_subsequent_run_missing_period_statistics(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_smart_meter: SmartMeter,
mock_anglian_water_client: AsyncMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the coordinator handles missing period lookup statistics."""
coordinator = AnglianWaterUpdateCoordinator(
hass, mock_anglian_water_client, mock_config_entry
)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# Correct the latest already-stored reading. Fallback should still update
# this hour instead of skipping it.
mock_smart_meter.readings[-1] = {
"read_at": "2024-06-01T14:00:00",
"consumption": 35,
"read": 70,
}
# Add a new later reading to ensure fallback also accepts newer entries.
mock_smart_meter.readings.append(
{"read_at": "2024-06-01T15:00:00", "consumption": 20, "read": 90}
)
with patch(
"homeassistant.components.anglian_water.coordinator.statistics_during_period",
return_value={},
):
await coordinator._async_update_data()
await async_wait_recording_done(hass)
assert "Could not find existing statistics during period lookup" in caplog.text
statistic_id = f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage"
stats = await hass.async_add_executor_job(
get_last_statistics, hass, 1, statistic_id, True, {"sum"}
)
assert stats[statistic_id][0]["sum"] >= 70
parsed_read_at = dt_util.parse_datetime("2024-06-01T14:00:00")
assert parsed_read_at is not None
corrected_start = dt_util.as_local(parsed_read_at) - timedelta(hours=1)
corrected_stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
corrected_start,
corrected_start + timedelta(seconds=1),
{
statistic_id,
},
"hour",
None,
{"sum"},
)
assert corrected_stats[statistic_id][0]["sum"] == 70
async def test_coordinator_period_statistics_without_sum(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
) -> None:
"""Test period lookup records without sum are handled safely."""
coordinator = AnglianWaterUpdateCoordinator(
hass, mock_anglian_water_client, mock_config_entry
)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
statistic_id = f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage"
with patch(
"homeassistant.components.anglian_water.coordinator.statistics_during_period",
return_value={statistic_id: [{"start": 0.0}]},
):
await coordinator._async_update_data()
await async_wait_recording_done(hass)
stats = await hass.async_add_executor_job(
get_last_statistics, hass, 1, statistic_id, True, {"sum"}
)
assert stats[statistic_id]
@pytest.mark.parametrize(
("side_effect", "translation_key", "retry_after"),
[
pytest.param(
UnknownEndpointError(status=500, response="Service Unavailable"),
"service_unavailable",
60.0,
id="service_unavailable",
),
],
)
async def test_coordinator_update_failed_errors(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
side_effect: Exception,
translation_key: str,
retry_after: float,
) -> None:
"""Test the coordinator maps transient API errors to UpdateFailed."""
coordinator = AnglianWaterUpdateCoordinator(
hass, mock_anglian_water_client, mock_config_entry
)
mock_anglian_water_client.update.side_effect = side_effect
with pytest.raises(UpdateFailed) as exc_info:
await coordinator._async_update_data()
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == translation_key
assert exc_info.value.retry_after == retry_after
async def test_coordinator_consent_required_error(
recorder_mock: Recorder,
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
) -> None:
"""Test the coordinator maps consent errors to UpdateFailed and creates a repair issue."""
mock_config_entry.add_to_hass(hass)
coordinator = AnglianWaterUpdateCoordinator(
hass, mock_anglian_water_client, mock_config_entry
)
mock_anglian_water_client.update.side_effect = ConsentRequiredError
with pytest.raises(UpdateFailed) as exc_info:
await coordinator._async_update_data()
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == "consent_required"
assert exc_info.value.retry_after == 900.0
issue = issue_registry.async_get_issue(DOMAIN, CONSENT_REQUIRED_ISSUE_ID)
assert issue is not None
assert issue.config_entry_id == mock_config_entry.entry_id
mock_anglian_water_client.update.side_effect = None
await coordinator._async_update_data()
await async_wait_recording_done(hass)
assert issue_registry.async_get_issue(DOMAIN, CONSENT_REQUIRED_ISSUE_ID) is None
@pytest.mark.parametrize(
("side_effect", "translation_key"),
[
pytest.param(
ExpiredAccessTokenError, "auth_expired", id="expired_access_token"
),
pytest.param(InvalidGrantError, "auth_expired", id="invalid_grant"),
],
)
async def test_coordinator_auth_failed_errors(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
side_effect: Exception,
translation_key: str,
) -> None:
"""Test the coordinator maps auth errors to ConfigEntryAuthFailed."""
coordinator = AnglianWaterUpdateCoordinator(
hass, mock_anglian_water_client, mock_config_entry
)
mock_anglian_water_client.update.side_effect = side_effect
with pytest.raises(ConfigEntryAuthFailed) as exc_info:
await coordinator._async_update_data()
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == translation_key
+261 -31
View File
@@ -1,7 +1,9 @@
"""Test Anglian Water init."""
from datetime import timedelta
from unittest.mock import AsyncMock, MagicMock
from freezegun.api import FrozenDateTimeFactory
from pyanglianwater.exceptions import (
ConsentRequiredError,
ExpiredAccessTokenError,
@@ -10,47 +12,30 @@ from pyanglianwater.exceptions import (
InvalidGrantError,
SelfAssertedError,
SmartMeterUnavailableError,
UnknownEndpointError,
)
import pytest
from pytest_homeassistant.common import MockConfigEntry
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
from homeassistant.components.anglian_water.const import DOMAIN
from homeassistant.components.recorder import Recorder
from homeassistant.config_entries import ConfigEntryState
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.update_coordinator import UpdateFailed
from .const import CONSENT_REQUIRED_ISSUE_ID
@pytest.mark.usefixtures("recorder_mock")
async def test_setup_hourly_readings_unavailable(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
) -> None:
"""Test setup fails with a translated error when hourly readings are unavailable."""
mock_anglian_water_client.update.side_effect = HourlyReadingsUnavailableError(
status=500, response="mock"
)
mock_config_entry.add_to_hass(hass)
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
assert mock_config_entry.error_reason_translation_domain == DOMAIN
assert (
mock_config_entry.error_reason_translation_key == "hourly_readings_unavailable"
)
LATEST_READING_ENTITY_ID = "sensor.testsn_latest_reading"
@pytest.mark.usefixtures(
"recorder_mock", "mock_anglian_water_client", "mock_anglian_water_authenticator"
)
async def test_setup_unload_entry(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
mock_anglian_water_authenticator: MagicMock,
) -> None:
"""Test successful setup and unload of the config entry."""
mock_config_entry.add_to_hass(hass)
@@ -90,10 +75,10 @@ async def test_setup_unload_entry(
),
],
)
@pytest.mark.usefixtures("mock_anglian_water_client")
async def test_setup_auth_failures(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
mock_anglian_water_authenticator: MagicMock,
exception_type: type[Exception],
expected_state: ConfigEntryState,
@@ -108,12 +93,11 @@ async def test_setup_auth_failures(
assert mock_config_entry.state is expected_state
@pytest.mark.usefixtures("recorder_mock", "mock_anglian_water_client")
async def test_setup_consent_required(
recorder_mock: Recorder,
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
mock_anglian_water_authenticator: MagicMock,
) -> None:
"""Test setup raises ConfigEntryNotReady and creates a repair issue when consent is required."""
@@ -161,11 +145,11 @@ async def test_consent_required_issue_removed_with_entry(
assert issue_registry.async_get_issue(DOMAIN, CONSENT_REQUIRED_ISSUE_ID) is None
@pytest.mark.usefixtures("mock_anglian_water_authenticator")
async def test_setup_smart_meter_unavailable(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
mock_anglian_water_authenticator: MagicMock,
) -> None:
"""Test setup fails when the smart meter is unavailable."""
mock_anglian_water_client.validate_smart_meter.side_effect = (
@@ -177,3 +161,249 @@ async def test_setup_smart_meter_unavailable(
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
@pytest.mark.usefixtures("recorder_mock")
async def test_setup_hourly_readings_unavailable(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
) -> None:
"""Test setup fails with a translated error when hourly readings are unavailable."""
mock_anglian_water_client.update.side_effect = HourlyReadingsUnavailableError(
status=500, response="mock"
)
mock_config_entry.add_to_hass(hass)
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
assert mock_config_entry.error_reason_translation_domain == DOMAIN
assert (
mock_config_entry.error_reason_translation_key == "hourly_readings_unavailable"
)
@pytest.mark.parametrize(
("side_effect", "exception_type", "translation_key", "retry_after"),
[
pytest.param(
UnknownEndpointError(status=500, response="Service Unavailable"),
UpdateFailed,
"service_unavailable",
60.0,
id="service_unavailable",
),
pytest.param(
ConsentRequiredError(),
UpdateFailed,
"consent_required",
900.0,
id="consent_required",
),
pytest.param(
ExpiredAccessTokenError(),
ConfigEntryAuthFailed,
"auth_expired",
None,
id="expired_access_token",
),
pytest.param(
InvalidGrantError(),
ConfigEntryAuthFailed,
"auth_expired",
None,
id="invalid_grant",
),
],
)
@pytest.mark.usefixtures("recorder_mock")
async def test_update_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
freezer: FrozenDateTimeFactory,
side_effect: Exception,
exception_type: type[HomeAssistantError],
translation_key: str,
retry_after: float | None,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test update errors retain translated exceptions and make sensors unavailable."""
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(LATEST_READING_ENTITY_ID)
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert mock_config_entry.state is ConfigEntryState.LOADED
caplog.clear()
mock_anglian_water_client.update.side_effect = side_effect
freezer.tick(timedelta(hours=1, seconds=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(LATEST_READING_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNAVAILABLE
assert mock_config_entry.state is ConfigEntryState.LOADED
errors = [
record.exc_info[1]
for record in caplog.records
if record.name == "homeassistant.components.anglian_water.coordinator"
and record.exc_info is not None
]
assert len(errors) == 1
error = errors[0]
assert isinstance(error, exception_type)
assert error.translation_domain == DOMAIN
assert error.translation_key == translation_key
assert getattr(error, "retry_after", None) == retry_after
@pytest.mark.parametrize(
("side_effect", "retry_after"),
[
pytest.param(
UnknownEndpointError(status=500, response="Service Unavailable"),
60,
id="service_unavailable",
),
pytest.param(ConsentRequiredError(), 900, id="consent_required"),
],
)
@pytest.mark.usefixtures("recorder_mock")
async def test_update_retries(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
freezer: FrozenDateTimeFactory,
side_effect: Exception,
retry_after: int,
) -> None:
"""Test transient failures retry automatically after the requested delay."""
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_anglian_water_client.update.side_effect = side_effect
freezer.tick(timedelta(hours=1, seconds=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(LATEST_READING_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNAVAILABLE
mock_anglian_water_client.update.side_effect = None
freezer.tick(timedelta(seconds=retry_after - 2))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(LATEST_READING_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNAVAILABLE
freezer.tick(timedelta(seconds=3))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(LATEST_READING_ENTITY_ID)
assert state is not None
assert state.state == "50.0"
assert mock_config_entry.state is ConfigEntryState.LOADED
@pytest.mark.parametrize(
"side_effect",
[
pytest.param(ExpiredAccessTokenError(), id="expired_access_token"),
pytest.param(InvalidGrantError(), id="invalid_grant"),
],
)
@pytest.mark.usefixtures("recorder_mock")
async def test_update_auth_failed(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
freezer: FrozenDateTimeFactory,
side_effect: Exception,
) -> None:
"""Test authentication failures during polling start reauthentication."""
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 hass.config_entries.flow.async_progress() == []
mock_anglian_water_client.update.side_effect = side_effect
freezer.tick(timedelta(hours=1, seconds=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["handler"] == DOMAIN
assert flows[0]["context"]["source"] == SOURCE_REAUTH
assert flows[0]["context"]["entry_id"] == mock_config_entry.entry_id
@pytest.mark.parametrize(
("side_effect", "issue_id", "translation_key", "retry_after"),
[
pytest.param(
ConsentRequiredError(),
CONSENT_REQUIRED_ISSUE_ID,
"consent_required",
900,
id="consent_required",
),
],
)
@pytest.mark.usefixtures("recorder_mock")
async def test_update_issues(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
issue_registry: ir.IssueRegistry,
freezer: FrozenDateTimeFactory,
side_effect: Exception,
issue_id: str,
translation_key: str,
retry_after: int,
) -> None:
"""Test update failures create repair issues and clear them after recovery."""
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 issue_registry.async_get_issue(DOMAIN, issue_id) is None
mock_anglian_water_client.update.side_effect = side_effect
freezer.tick(timedelta(hours=1, seconds=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
issue = issue_registry.async_get_issue(DOMAIN, issue_id)
assert issue is not None
assert issue.config_entry_id == mock_config_entry.entry_id
assert issue.translation_key == translation_key
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_anglian_water_client.update.side_effect = None
freezer.tick(timedelta(seconds=retry_after - 2))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert issue_registry.async_get_issue(DOMAIN, issue_id) is not None
freezer.tick(timedelta(seconds=3))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert issue_registry.async_get_issue(DOMAIN, issue_id) is None
assert mock_config_entry.state is ConfigEntryState.LOADED
@@ -0,0 +1,286 @@
"""Test Anglian Water statistics."""
from datetime import timedelta
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
from pyanglianwater.meter import SmartMeter
import pytest
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
from pytest_homeassistant.components.recorder.common import async_wait_recording_done
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.recorder.statistics import (
get_last_statistics,
statistics_during_period,
)
from homeassistant.core import HomeAssistant
from homeassistant.util import dt as dt_util
from .const import ACCOUNT_NUMBER
@pytest.mark.parametrize(
("readings"),
[
pytest.param([], id="no_new_readings"),
pytest.param(
[
{
"read_at": "2024-06-01T14:00:00",
"consumption": 35,
"read": 70,
},
{
"read_at": "2024-06-01T15:00:00",
"consumption": 20,
"read": 90,
},
],
id="new_and_updated_readings",
),
pytest.param(
[
{
"read_at": "2024-06-01T15:00:00",
"consumption": 20,
"read": 70,
},
],
id="new_readings_only",
),
pytest.param(
[
{
"read_at": "2024-06-01T13:00:00",
"consumption": 20,
"read": 40,
"corrected": False,
},
{
"read_at": "2024-06-01T14:00:00",
"consumption": 35,
"read": 70,
"corrected": True,
},
],
id="corrected_reading",
),
],
)
@pytest.mark.usefixtures("recorder_mock", "mock_anglian_water_client")
async def test_statistics_subsequent_run(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_smart_meter: SmartMeter,
readings: list[dict[str, str | int]],
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
) -> None:
"""Test the coordinator correctly updates statistics on subsequent runs."""
# 1st run
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(wait_background_tasks=True)
await async_wait_recording_done(hass)
# 2nd run
mock_smart_meter.readings = readings
freezer.tick(timedelta(hours=1, seconds=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
await async_wait_recording_done(hass)
# Check all stats
stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
dt_util.utc_from_timestamp(0),
None,
{
f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage",
},
"hour",
None,
{"state", "sum"},
)
assert stats == snapshot
@pytest.mark.parametrize(
("readings", "expected_log"),
[
pytest.param(
[
{
"read_at": "invalid-date-format",
"consumption": 10,
"read": 10,
},
],
"Could not parse read_at time invalid-date-format, skipping update",
id="invalid_first_timestamp",
),
pytest.param(
[
{
"read_at": "2024-06-01T12:00:00Z",
"consumption": 10,
"read": 10,
},
{
"read_at": "also-invalid-date",
"consumption": 15,
"read": 25,
},
],
"Could not parse read_at time also-invalid-date, skipping reading",
id="invalid_later_timestamp",
),
pytest.param(
[],
"No recent usage statistics found, skipping update",
id="no_readings",
),
],
)
@pytest.mark.usefixtures("recorder_mock", "mock_anglian_water_client")
async def test_statistics_invalid_readings(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_smart_meter: SmartMeter,
readings: list[dict[str, str | int]],
expected_log: str,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
snapshot: SnapshotAssertion,
) -> None:
"""Test invalid timestamps are skipped without changing stored statistics."""
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(wait_background_tasks=True)
await async_wait_recording_done(hass)
mock_smart_meter.readings = readings
freezer.tick(timedelta(hours=1, seconds=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
await async_wait_recording_done(hass)
assert expected_log in caplog.text
stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
dt_util.utc_from_timestamp(0),
None,
{f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage"},
"hour",
None,
{"state", "sum"},
)
assert stats == snapshot
@pytest.mark.usefixtures("recorder_mock", "mock_anglian_water_client")
async def test_statistics_missing_recorder_lookup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_smart_meter: SmartMeter,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the coordinator handles missing period lookup statistics."""
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(wait_background_tasks=True)
await async_wait_recording_done(hass)
# Correct the latest already-stored reading. Fallback should still update
# this hour instead of skipping it.
mock_smart_meter.readings[-1] = {
"read_at": "2024-06-01T14:00:00",
"consumption": 35,
"read": 70,
}
# Add a new later reading to ensure fallback also accepts newer entries.
mock_smart_meter.readings.append(
{"read_at": "2024-06-01T15:00:00", "consumption": 20, "read": 90}
)
with patch(
"homeassistant.components.anglian_water.coordinator.statistics_during_period",
return_value={},
):
freezer.tick(timedelta(hours=1, seconds=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
await async_wait_recording_done(hass)
assert "Could not find existing statistics during period lookup" in caplog.text
statistic_id = f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage"
stats = await hass.async_add_executor_job(
get_last_statistics, hass, 1, statistic_id, True, {"sum"}
)
assert stats[statistic_id][0]["sum"] == 90
parsed_read_at = dt_util.parse_datetime("2024-06-01T14:00:00")
assert parsed_read_at is not None
corrected_start = dt_util.as_local(parsed_read_at) - timedelta(hours=1)
corrected_stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
corrected_start,
corrected_start + timedelta(seconds=1),
{
statistic_id,
},
"hour",
None,
{"sum"},
)
assert corrected_stats[statistic_id][0]["sum"] == 70
@pytest.mark.usefixtures("recorder_mock", "mock_anglian_water_client")
async def test_period_statistics_without_sum(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_smart_meter: SmartMeter,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
) -> None:
"""Test period lookup records without sum are handled safely."""
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(wait_background_tasks=True)
await async_wait_recording_done(hass)
statistic_id = f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage"
mock_smart_meter.readings.append(
{"read_at": "2024-06-01T15:00:00", "consumption": 20, "read": 70}
)
with patch(
"homeassistant.components.anglian_water.coordinator.statistics_during_period",
return_value={statistic_id: [{"start": 0.0}]},
):
freezer.tick(timedelta(hours=1, seconds=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
await async_wait_recording_done(hass)
stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
dt_util.utc_from_timestamp(0),
None,
{statistic_id},
"hour",
None,
{"state", "sum"},
)
assert stats == snapshot