Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions ariston/galevo_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from datetime import date
from typing import Any, Optional

from .ariston_api import AristonAPI
from .ariston_api import AristonAPI, ConnectionException
from .const import (
ConsumptionProperties,
ConsumptionTimeInterval,
Expand Down Expand Up @@ -99,7 +99,11 @@ def update_state(self) -> None:
self.language_tag,
self.umsys,
)
self.menu_items = self.api.get_menu_items(self.gw)
try:
self.menu_items = self.api.get_menu_items(self.gw)
except ConnectionException as error:
if not self._should_retain_menu_items_after_error(error):
raise
self._update_state()

async def async_update_state(self) -> None:
Expand All @@ -114,10 +118,35 @@ async def async_update_state(self) -> None:
self.language_tag,
self.umsys,
),
self.api.async_get_menu_items(self.gw),
self._async_get_menu_items(),
)
self._update_state()

async def _async_get_menu_items(self) -> list[dict[str, Any]]:
"""Get menu items while retaining the last values for server errors."""
try:
return await self.api.async_get_menu_items(self.gw)
except ConnectionException as error:
if not self._should_retain_menu_items_after_error(error):
raise
return self.menu_items

def _should_retain_menu_items_after_error(
self, error: ConnectionException
) -> bool:
"""Log and identify menu server errors that can use cached values."""
status = error.args[0] if error.args else None
if status not in (500, 550):
return False

_LOGGER.warning(
"Could not fetch menu items for gateway %s (HTTP %s); "
"retaining the last successful values",
self.gw,
status,
)
return True

def _get_features(self) -> None:
"""Set custom features"""
self.custom_features[CustomDeviceFeatures.HAS_DHW] = (
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ dependencies = [
]
requires-python = ">=3.11"
license = { file = "LICENSE" }
version = "0.19.11"
version = "0.19.12"
dynamic = ['description']

[project.urls]
Expand Down
88 changes: 88 additions & 0 deletions tests/test_galevo_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from datetime import date
from unittest.mock import AsyncMock, Mock

from ariston.ariston_api import ConnectionException
from ariston.const import (
ConsumptionProperties,
ConsumptionTimeInterval,
Expand Down Expand Up @@ -294,6 +295,93 @@
asyncio.run(refresh_without_features())
async_no_features.api.async_get_features_for_device.assert_awaited_once_with("gw-1")

def test_menu_http_500_and_550_preserve_previous_items_and_refresh_state(self):
for status in (500, 550):
with self.subTest(status=status):
device = self.make_device()
previous_menu_items = list(device.menu_items)
fresh_data = self.make_data()
fresh_data["items"][0][PropertyType.VALUE] = 42
device.api.async_get_properties = AsyncMock(return_value=fresh_data)
device.api.async_get_menu_items = AsyncMock(
side_effect=ConnectionException(status)
)

async def refresh():
await device.async_update_state()

with self.assertLogs("ariston.galevo_device", level="WARNING"):
asyncio.run(refresh())

self.assertEqual(device.data, fresh_data)
self.assertEqual(device.menu_items, previous_menu_items)
self.assertEqual(device.signal_strength_value, 4)

def test_menu_http_failure_on_first_refresh_and_recovery(self):
device = self.make_device()
device.menu_items = []
device.api.async_get_properties = AsyncMock(return_value=self.make_data())
device.api.async_get_menu_items = AsyncMock(
side_effect=[ConnectionException(500), [{"id": 1, PropertyType.VALUE: 3}]]
)

async def refresh_twice():
await device.async_update_state()
self.assertEqual(device.menu_items, [])
self.assertEqual(device.data, self.make_data())
await device.async_update_state()

with self.assertLogs("ariston.galevo_device", level="WARNING"):
asyncio.run(refresh_twice())

self.assertEqual(device.menu_items, [{"id": 1, PropertyType.VALUE: 3}])

def test_primary_properties_and_non_transient_menu_errors_still_raise(self):
device = self.make_device()
device.api.async_get_properties = AsyncMock(
side_effect=ConnectionException(500)
)
device.api.async_get_menu_items = AsyncMock(return_value=device.menu_items)

async def refresh_primary_failure():
await device.async_update_state()

with self.assertRaises(ConnectionException):

Check warning on line 349 in tests/test_galevo_device.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this exception test to have only one invocation possibly throwing an exception.

See more on https://sonarcloud.io/project/issues?id=fustom_python-ariston-api&issues=AaHbVlDvoCt6TAwwOu7L&open=AaHbVlDvoCt6TAwwOu7L&pullRequest=192
asyncio.run(refresh_primary_failure())

device.api.async_get_properties = AsyncMock(return_value=self.make_data())
device.api.async_get_menu_items = AsyncMock(
side_effect=ConnectionException(401)
)

async def refresh_menu_auth_failure():
await device.async_update_state()

with self.assertRaises(ConnectionException):

Check warning on line 360 in tests/test_galevo_device.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this exception test to have only one invocation possibly throwing an exception.

See more on https://sonarcloud.io/project/issues?id=fustom_python-ariston-api&issues=AaHbVlDvoCt6TAwwOu7M&open=AaHbVlDvoCt6TAwwOu7M&pullRequest=192
asyncio.run(refresh_menu_auth_failure())

def test_sync_menu_http_failure_preserves_previous_items(self):
device = self.make_device()
previous_menu_items = list(device.menu_items)
fresh_data = self.make_data()
fresh_data["items"][0][PropertyType.VALUE] = 42
device.api.get_properties.return_value = fresh_data
device.api.get_menu_items.side_effect = ConnectionException(500)

with self.assertLogs("ariston.galevo_device", level="WARNING"):
device.update_state()

self.assertEqual(device.data, fresh_data)
self.assertEqual(device.menu_items, previous_menu_items)

def test_sync_non_transient_menu_errors_still_raise(self):
device = self.make_device()
device.api.get_properties.return_value = self.make_data()
device.api.get_menu_items.side_effect = ConnectionException(401)

with self.assertRaises(ConnectionException):
device.update_state()

def test_consumption_settings_and_energy_account_paths(self):
device = self.make_device()
device.consumptions_settings = {
Expand Down
Loading