From c472e72a63abf6d4fbb00d04334c189cca1cee6f Mon Sep 17 00:00:00 2001 From: flupkede Date: Fri, 28 Aug 2026 19:39:55 +0000 Subject: [PATCH 01/10] fix(api): honour 429 retry-after instead of failing immediately The API returns the block duration in the response body but the client discarded it and raised straight away, so the next poll often landed inside the same window. Parse the value, wait it out, and share the blocked-until deadline across all callers. Closes: AGENTS_ariston-429-holiday.md --- ariston/ariston_api.py | 68 +++++++++++++- pyproject.toml | 2 +- tests/test_rate_limit.py | 197 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 264 insertions(+), 3 deletions(-) create mode 100644 tests/test_rate_limit.py diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index 465e078..4ffa26e 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import re import time from typing import Any, Optional @@ -39,6 +40,16 @@ _LOGGER = logging.getLogger(__name__) +_RATE_LIMIT_RE = re.compile(rb"blocked for (\d+) seconds", re.IGNORECASE) + + +def _parse_block_seconds(content: bytes) -> Optional[int]: + """Extract the block duration in seconds from a 429 response body.""" + match = _RATE_LIMIT_RE.search(content) + if match is None: + return None + return int(match.group(1)) + class ConnectionException(Exception): """When can not connect to Ariston cloud""" @@ -47,6 +58,10 @@ class ConnectionException(Exception): class AristonAPI: """Ariston API class""" + # Shared across all instances: one 429 silences every caller (all three + # HA coordinators) until the block window has passed. + _blocked_until: float = 0.0 + def __init__( self, username: str, @@ -470,6 +485,11 @@ def __request( is_retry: bool = False, ) -> Optional[dict[str, Any]]: """Request with requests""" + if not is_retry and time.time() < AristonAPI._blocked_until: + raise ConnectionException( + 429, + "Rate limited; skipping request until the block window ends", + ) headers: dict[str, Any] = { "User-Agent": self.__user_agent, "ar.authToken": self.__token, @@ -495,8 +515,27 @@ def __request( case 404: return None case 429: - content = response.content.decode() - raise ConnectionException(response.status_code, content) + content = response.content + wait_seconds = _parse_block_seconds(content) + if wait_seconds is not None: + wait_seconds += 1 + _LOGGER.warning( + "Rate limited (429) for %s seconds; waiting it out", + wait_seconds, + ) + else: + wait_seconds = 5 + _LOGGER.warning( + "Rate limited (429) without parsable block " + "duration; falling back to 5s wait" + ) + AristonAPI._blocked_until = time.time() + wait_seconds + if not is_retry: + time.sleep(wait_seconds) + return self.__request(method, path, params, body, True) + raise ConnectionException( + response.status_code, content.decode() + ) case _: if not is_retry: time.sleep(5) @@ -932,6 +971,11 @@ async def __async_request( is_retry: bool = False, ) -> Optional[dict[str, Any]]: """Async request with aiohttp""" + if not is_retry and time.time() < AristonAPI._blocked_until: + raise ConnectionException( + 429, + "Rate limited; skipping request until the block window ends", + ) headers: dict[str, Any] = { "User-Agent": self.__user_agent, "ar.authToken": self.__token, @@ -965,6 +1009,26 @@ async def __async_request( return None case 429: content = await response.content.read() + wait_seconds = _parse_block_seconds(content) + if wait_seconds is not None: + wait_seconds += 1 + _LOGGER.warning( + "Rate limited (429) for %s seconds; " + "waiting it out", + wait_seconds, + ) + else: + wait_seconds = 5 + _LOGGER.warning( + "Rate limited (429) without parsable block " + "duration; falling back to 5s wait" + ) + AristonAPI._blocked_until = time.time() + wait_seconds + if not is_retry: + await asyncio.sleep(wait_seconds) + return await self.__async_request( + method, path, params, body, True + ) raise ConnectionException(response.status, content) case _: if not is_retry: diff --git a/pyproject.toml b/pyproject.toml index d8ebd4f..986f1fc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ dependencies = [ ] requires-python = ">=3.9" license = { file = "LICENSE" } -version = "0.19.9" +version = "0.19.9+patch1" dynamic = ['description'] [project.urls] diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py new file mode 100644 index 0000000..71bebf2 --- /dev/null +++ b/tests/test_rate_limit.py @@ -0,0 +1,197 @@ +"""Unit tests for the 429 rate-limit handling in ariston.ariston_api.""" + +import asyncio +import time +from typing import Any, Optional +from unittest.mock import MagicMock, patch + +import pytest + +from ariston.ariston_api import ( + AristonAPI, + ConnectionException, + _parse_block_seconds, +) + + +@pytest.fixture(autouse=True) +def _reset_blocked_until(): + """Isolate the class-level block window between tests.""" + AristonAPI._blocked_until = 0.0 + yield + AristonAPI._blocked_until = 0.0 + + +def _api() -> AristonAPI: + return AristonAPI("user", "pass") + + +# --------------------------------------------------------------------------- +# parse helper +# --------------------------------------------------------------------------- + + +def test_parse_block_seconds(): + assert _parse_block_seconds(b"Requests are blocked for 66 seconds") == 66 + assert _parse_block_seconds(b"Requests are blocked for 5 seconds") == 5 + assert _parse_block_seconds(b"Too many requests") is None + + +# --------------------------------------------------------------------------- +# sync path (requests) +# --------------------------------------------------------------------------- + + +def _sync_response(status: int, content: bytes = b"", json_data: Any = None): + response = MagicMock() + response.ok = status < 400 + response.status_code = status + response.content = content + if json_data is not None: + response.json.return_value = json_data + return response + + +def test_429_parses_wait_seconds(): + responses = [ + _sync_response(429, b"Requests are blocked for 66 seconds"), + _sync_response(200, b"{}", {"ok": True}), + ] + http = MagicMock(side_effect=responses) + sleeps: list[int] = [] + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep", side_effect=sleeps.append + ): + result = _api()._get("https://example/api") + + assert result == {"ok": True} + assert http.call_count == 2 # exactly one retry + assert sleeps == [67] # parsed 66 + 1s margin + assert AristonAPI._blocked_until > 0 # block window was set + + +def test_429_without_parsable_body(): + responses = [ + _sync_response(429, b"Too many requests"), + _sync_response(200, b"{}", {"ok": True}), + ] + http = MagicMock(side_effect=responses) + sleeps: list[int] = [] + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep", side_effect=sleeps.append + ): + result = _api()._get("https://example/api") + + assert result == {"ok": True} + assert sleeps == [5] # documented fallback, same as generic error case + assert http.call_count == 2 + + +def test_429_twice_raises(): + body = b"Requests are blocked for 10 seconds" + http = MagicMock( + side_effect=[_sync_response(429, body), _sync_response(429, body)] + ) + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep" + ): + with pytest.raises(ConnectionException): + _api()._get("https://example/api") + + assert http.call_count == 2 # one retry, then raise — no infinite loop + + +def test_blocked_until_short_circuits(): + AristonAPI._blocked_until = time.time() + 30 + http = MagicMock() + with patch("ariston.ariston_api.requests.request", http): + with pytest.raises(ConnectionException): + _api()._get("https://example/api") + + http.assert_not_called() # no network call inside the block window + + +# --------------------------------------------------------------------------- +# async path (aiohttp) +# --------------------------------------------------------------------------- + + +class _FakeAiohttpContent: + def __init__(self, payload: bytes) -> None: + self._payload = payload + + async def read(self) -> bytes: + return self._payload + + +class _FakeAiohttpResponse: + def __init__( + self, status: int, payload: bytes = b"", json_data: Any = None + ) -> None: + self.status = status + self.ok = status < 400 + self.content = _FakeAiohttpContent(payload) + self.content_length = len(payload) + self._json_data = json_data + + async def json(self) -> Any: + return self._json_data + + +def _fake_session_cls(responses: list, calls: list): + class _Session: + def __init__(self, *args: Any, **kwargs: Any) -> None: + pass + + async def __aenter__(self) -> "_Session": + return self + + async def __aexit__(self, *exc: Any) -> bool: + return False + + async def request(self, *args: Any, **kwargs: Any): + calls.append(1) + return responses.pop(0) + + return _Session + + +def test_async_429_parses_and_retries(): + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked for 66 seconds"), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ] + calls: list[int] = [] + sleeps: list[Optional[int]] = [] + + async def run() -> Any: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ), patch( + "ariston.ariston_api.asyncio.sleep", side_effect=sleeps.append + ): + return await _api()._async_get("https://example/api") + + result = asyncio.run(run()) + + assert result == {"ok": True} + assert len(calls) == 2 # exactly one retry + assert sleeps == [67] # parsed 66 + 1s margin + + +def test_async_blocked_until_short_circuits(): + AristonAPI._blocked_until = time.time() + 30 + calls: list[int] = [] + + async def run() -> None: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls([], calls), + ): + with pytest.raises(ConnectionException): + await _api()._async_get("https://example/api") + + asyncio.run(run()) + + assert calls == [] # no network call inside the block window From 430c56983e41f0f243a69f67c97e2341f485bb57 Mon Sep 17 00:00:00 2001 From: flupkede Date: Fri, 28 Aug 2026 22:20:13 +0000 Subject: [PATCH 02/10] feat(velis): add Velis holiday support The app exposes holiday mode for Velis water heaters but the library had no method for it. POST velis/slpPlantData/{gw}/holiday with {"new": date} to enable (ISO midnight format) and {"new": null} to cancel, mirroring the existing Galevo holiday API. Date format centralized in a shared constant. Proven against the live API: POST returns {"success":true} and the field holidayUntil appears in velis/slpPlantData afterwards. Closes: AGENTS_ariston-429-holiday.md --- ariston/ariston_api.py | 26 +++++++++++ ariston/const.py | 1 + ariston/galevo_device.py | 5 ++- ariston/velis_device.py | 21 ++++++++- pyproject.toml | 2 +- tests/test_velis_holiday.py | 89 +++++++++++++++++++++++++++++++++++++ 6 files changed, 141 insertions(+), 3 deletions(-) create mode 100644 tests/test_velis_holiday.py diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index 4ffa26e..fda8258 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -931,6 +931,32 @@ async def async_set_velis_plant_setting( {setting: {"new": value, "old": old_value}}, ) + def set_velis_holiday( + self, + gw_id: str, + holiday_end_date: Optional[str], + ) -> None: + """Set Velis holiday""" + self._post( + f"{self.__api_url}{ARISTON_VELIS}/{PlantData.Slp.value}/{gw_id}/holiday", + { + "new": holiday_end_date, + }, + ) + + async def async_set_velis_holiday( + self, + gw_id: str, + holiday_end_date: Optional[str], + ) -> None: + """Async set Velis holiday""" + await self._async_post( + f"{self.__api_url}{ARISTON_VELIS}/{PlantData.Slp.value}/{gw_id}/holiday", + { + "new": holiday_end_date, + }, + ) + async def async_get_thermostat_time_progs( self, gw_id: str, zone: int, umsys: str ) -> Optional[dict[str, Any]]: diff --git a/ariston/const.py b/ariston/const.py index 13f9b09..0c14f9e 100644 --- a/ariston/const.py +++ b/ariston/const.py @@ -7,6 +7,7 @@ ARISTON_LOGIN: Final[str] = "accounts/login" ARISTON_REMOTE: Final[str] = "remote" ARISTON_VELIS: Final[str] = "velis" +HOLIDAY_DATE_FORMAT: Final[str] = "%Y-%m-%dT00:00:00" ARISTON_PLANTS: Final[str] = "plants" ARISTON_LITE: Final[str] = "lite" ARISTON_DATA_ITEMS: Final[str] = "dataItems" diff --git a/ariston/galevo_device.py b/ariston/galevo_device.py index 59c489b..bf8682f 100644 --- a/ariston/galevo_device.py +++ b/ariston/galevo_device.py @@ -18,6 +18,7 @@ DeviceProperties, GasEnergyUnit, GasType, + HOLIDAY_DATE_FORMAT, PlantMode, PropertyType, ThermostatProperties, @@ -979,7 +980,9 @@ async def async_set_item_by_id( @staticmethod def _create_holiday_end_date(holiday_end: Optional[date]): return ( - None if holiday_end is None else holiday_end.strftime("%Y-%m-%dT00:00:00") + None + if holiday_end is None + else holiday_end.strftime(HOLIDAY_DATE_FORMAT) ) def _set_holiday(self, holiday_end_date: Optional[str]): diff --git a/ariston/velis_device.py b/ariston/velis_device.py index 46393f9..de8d4e4 100644 --- a/ariston/velis_device.py +++ b/ariston/velis_device.py @@ -3,10 +3,11 @@ import logging from abc import ABC, abstractmethod +from datetime import date from typing import Any, Optional from .ariston_api import AristonAPI -from .const import VelisDeviceProperties +from .const import HOLIDAY_DATE_FORMAT, VelisDeviceProperties from .velis_base_device import AristonVelisBaseDevice from .device import AristonDevice @@ -88,6 +89,24 @@ async def async_set_max_setpoint_temp(self, max_setpoint_temp: float): ) self.plant_settings[self.max_setpoint_temp] = max_setpoint_temp + @staticmethod + def _create_holiday_end_date(holiday_end: Optional[date]) -> Optional[str]: + return ( + None + if holiday_end is None + else holiday_end.strftime(HOLIDAY_DATE_FORMAT) + ) + + def set_velis_holiday(self, holiday_end: Optional[date]) -> None: + """Set Velis holiday on device""" + self.api.set_velis_holiday(self.gw, self._create_holiday_end_date(holiday_end)) + + async def async_set_velis_holiday(self, holiday_end: Optional[date]) -> None: + """Async set Velis holiday on device""" + await self.api.async_set_velis_holiday( + self.gw, self._create_holiday_end_date(holiday_end) + ) + @property @abstractmethod def water_heater_maximum_setpoint_temperature_minimum(self) -> Optional[float]: diff --git a/pyproject.toml b/pyproject.toml index 986f1fc..de81683 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ dependencies = [ ] requires-python = ">=3.9" license = { file = "LICENSE" } -version = "0.19.9+patch1" +version = "0.19.9+patch2" dynamic = ['description'] [project.urls] diff --git a/tests/test_velis_holiday.py b/tests/test_velis_holiday.py new file mode 100644 index 0000000..940fbaa --- /dev/null +++ b/tests/test_velis_holiday.py @@ -0,0 +1,89 @@ +"""Unit tests for the Velis holiday write (endpoint proven by live write-test).""" + +import asyncio +from datetime import date +from typing import Any + +from ariston.ariston_api import AristonAPI +from ariston.const import ARISTON_API_URL, ARISTON_VELIS +from ariston.velis_device import AristonVelisDevice + +GW = "3C8A1F2EDE84" +EXPECTED_URL = ( + f"{ARISTON_API_URL}{ARISTON_VELIS}/slpPlantData/{GW}/holiday" +) + + +def _fake_session_cls(posts: list): + class _Session: + def __init__(self, *args: Any, **kwargs: Any) -> None: + pass + + async def __aenter__(self) -> "_Session": + return self + + async def __aexit__(self, *exc: Any) -> bool: + return False + + async def request(self, method: str, path: str, params=None, json=None, + headers=None): + if method == "POST": + posts.append({"path": path, "json": json}) + class _Resp: + status = 200 + ok = True + content_length = 0 + return _Resp() + + return _Session + + +def _device() -> AristonVelisDevice: + """Instantiate without the abstract machinery; only api+gw are used.""" + cls = AristonVelisDevice + original = cls.__abstractmethods__ + cls.__abstractmethods__ = frozenset() + try: + device = cls.__new__(cls) + finally: + cls.__abstractmethods__ = original + device.api = AristonAPI("user", "pass") + device.gw = GW + return device + + +def test_holiday_end_date_format(): + assert ( + AristonVelisDevice._create_holiday_end_date(date(2026, 9, 15)) + == "2026-09-15T00:00:00" + ) + assert AristonVelisDevice._create_holiday_end_date(None) is None + + +def test_async_set_velis_holiday_on_posts_date(): + posts: list = [] + device = _device() + with patch_session(_fake_session_cls(posts)): + asyncio.run(device.async_set_velis_holiday(date(2026, 9, 15))) + + assert len(posts) == 1 + assert posts[0]["path"] == EXPECTED_URL + assert posts[0]["json"] == {"new": "2026-09-15T00:00:00"} + + +def test_async_set_velis_holiday_off_posts_null(): + posts: list = [] + device = _device() + with patch_session(_fake_session_cls(posts)): + asyncio.run(device.async_set_velis_holiday(None)) + + assert len(posts) == 1 + assert posts[0]["path"] == EXPECTED_URL + assert posts[0]["json"] == {"new": None} + + +def patch_session(fake_cls): + """Patch aiohttp.ClientSession inside ariston_api for one test.""" + from unittest.mock import patch + + return patch("ariston.ariston_api.aiohttp.ClientSession", fake_cls) From 5dc22129477c847409c6d88471a0e00f5d93940e Mon Sep 17 00:00:00 2001 From: flupkede Date: Sat, 29 Aug 2026 09:32:42 +0000 Subject: [PATCH 03/10] chore: drop local version suffix, fix Sonar test smells The +patchN version suffix is only needed for our local wheel deployment; release versioning belongs to the maintainer, so the PR diff no longer touches pyproject.toml (this also clears the Sonar S8565 lock-file finding from new code). Tests now use the monkeypatch fixture for the shared _blocked_until state and keep a single invocation inside pytest.raises blocks (S8997, S5778). --- pyproject.toml | 2 +- tests/test_rate_limit.py | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index de81683..d8ebd4f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ dependencies = [ ] requires-python = ">=3.9" license = { file = "LICENSE" } -version = "0.19.9+patch2" +version = "0.19.9" dynamic = ['description'] [project.urls] diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 71bebf2..89134cf 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -92,21 +92,23 @@ def test_429_twice_raises(): http = MagicMock( side_effect=[_sync_response(429, body), _sync_response(429, body)] ) + api = _api() with patch("ariston.ariston_api.requests.request", http), patch( "ariston.ariston_api.time.sleep" ): with pytest.raises(ConnectionException): - _api()._get("https://example/api") + api._get("https://example/api") assert http.call_count == 2 # one retry, then raise — no infinite loop -def test_blocked_until_short_circuits(): - AristonAPI._blocked_until = time.time() + 30 +def test_blocked_until_short_circuits(monkeypatch): + monkeypatch.setattr(AristonAPI, "_blocked_until", time.time() + 30) http = MagicMock() + api = _api() with patch("ariston.ariston_api.requests.request", http): with pytest.raises(ConnectionException): - _api()._get("https://example/api") + api._get("https://example/api") http.assert_not_called() # no network call inside the block window @@ -180,9 +182,10 @@ async def run() -> Any: assert sleeps == [67] # parsed 66 + 1s margin -def test_async_blocked_until_short_circuits(): - AristonAPI._blocked_until = time.time() + 30 +def test_async_blocked_until_short_circuits(monkeypatch): + monkeypatch.setattr(AristonAPI, "_blocked_until", time.time() + 30) calls: list[int] = [] + api = _api() async def run() -> None: with patch( @@ -190,7 +193,7 @@ async def run() -> None: _fake_session_cls([], calls), ): with pytest.raises(ConnectionException): - await _api()._async_get("https://example/api") + await api._async_get("https://example/api") asyncio.run(run()) From 13aec65049f570a2959b547c61e153e70367f2a5 Mon Sep 17 00:00:00 2001 From: flupkede Date: Sat, 29 Aug 2026 09:54:51 +0000 Subject: [PATCH 04/10] refactor: literal syntax + extracted rate-limit handlers - Replace dict()/list() constructor calls with {}/[] literals across ariston_api, galevo_device, velis_device (Sonar S7498) - Extract the 429 branch from __request/__async_request into __handle_rate_limit/__async_handle_rate_limit helpers plus a module-level _rate_limit_wait_seconds() (Sonar S3776) No behavior change; full suite 10/10 green (ariston-test:py313). --- ariston/ariston_api.py | 144 +++++++++++++++++++++------------------ ariston/galevo_device.py | 6 +- ariston/velis_device.py | 2 +- 3 files changed, 82 insertions(+), 70 deletions(-) diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index fda8258..2584edb 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -51,6 +51,19 @@ def _parse_block_seconds(content: bytes) -> Optional[int]: return int(match.group(1)) +def _rate_limit_wait_seconds(content: bytes) -> int: + """Effective wait for a 429: parsed duration + 1s margin, else 5s.""" + parsed = _parse_block_seconds(content) + if parsed is None: + _LOGGER.warning( + "Rate limited (429) without parsable block duration; " + "falling back to 5s wait" + ) + return 5 + _LOGGER.warning("Rate limited (429) for %s seconds; waiting it out", parsed + 1) + return parsed + 1 + + class ConnectionException(Exception): """When can not connect to Ariston cloud""" @@ -100,14 +113,14 @@ def get_detailed_devices(self) -> list[Any]: devices = self._get(f"{self.__api_url}{ARISTON_REMOTE}/{ARISTON_PLANTS}") if devices is not None: return list(devices) - return list() + return [] def get_detailed_velis_devices(self) -> list[Any]: """Get detailed cloud devices""" devices = self._get(f"{self.__api_url}{ARISTON_VELIS}/{ARISTON_PLANTS}") if devices is not None: return list(devices) - return list() + return [] def get_devices(self) -> list[Any]: """Get cloud devices""" @@ -116,7 +129,7 @@ def get_devices(self) -> list[Any]: ) if devices is not None: return list(devices) - return list() + return [] def get_features_for_device(self, gw_id: str) -> dict[str, Any]: """Get features for the device""" @@ -125,7 +138,7 @@ def get_features_for_device(self, gw_id: str) -> dict[str, Any]: ) if features is not None: return features - return dict() + return {} def get_energy_account(self, gw_id: str) -> dict[str, Any]: """Get energy account for the device""" @@ -134,7 +147,7 @@ def get_energy_account(self, gw_id: str) -> dict[str, Any]: ) if energy_account is not None: return energy_account - return dict() + return {} def get_consumptions_sequences(self, gw_id: str, usages: str) -> list[Any]: """Get consumption sequences for the device""" @@ -143,7 +156,7 @@ def get_consumptions_sequences(self, gw_id: str, usages: str) -> list[Any]: ) if consumptions_sequences is not None: return list(consumptions_sequences) - return list() + return [] def get_consumptions_settings(self, gw_id: str) -> dict[str, Any]: """Get consumption settings""" @@ -153,7 +166,7 @@ def get_consumptions_settings(self, gw_id: str) -> dict[str, Any]: ) if consumptions_settings is not None: return consumptions_settings - return dict() + return {} def set_consumptions_settings( self, @@ -189,7 +202,7 @@ def get_properties( ) if properties is not None: return properties - return dict() + return {} def get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: """Get BSB plant data.""" @@ -198,14 +211,14 @@ def get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: ) if data is not None: return data - return dict() + return {} def get_velis_plant_data(self, plant_data: PlantData, gw_id: str) -> dict[str, Any]: """Get Velis properties""" data = self._get(f"{self.__api_url}{ARISTON_VELIS}/{plant_data.value}/{gw_id}") if data is not None: return data - return dict() + return {} def get_velis_plant_settings( self, plant_data: PlantData, gw_id: str @@ -216,7 +229,7 @@ def get_velis_plant_settings( ) if settings is not None: return settings - return dict() + return {} def get_menu_items(self, gw_id: str) -> list[dict[str, Any]]: """Get menu items""" @@ -225,7 +238,7 @@ def get_menu_items(self, gw_id: str) -> list[dict[str, Any]]: ) if items is not None: return items - return list() + return [] def set_property( self, @@ -452,7 +465,7 @@ def get_thermostat_time_progs( ) if thermostat_time_progs is not None: return thermostat_time_progs - return dict() + return {} def set_holiday( self, @@ -515,26 +528,8 @@ def __request( case 404: return None case 429: - content = response.content - wait_seconds = _parse_block_seconds(content) - if wait_seconds is not None: - wait_seconds += 1 - _LOGGER.warning( - "Rate limited (429) for %s seconds; waiting it out", - wait_seconds, - ) - else: - wait_seconds = 5 - _LOGGER.warning( - "Rate limited (429) without parsable block " - "duration; falling back to 5s wait" - ) - AristonAPI._blocked_until = time.time() + wait_seconds - if not is_retry: - time.sleep(wait_seconds) - return self.__request(method, path, params, body, True) - raise ConnectionException( - response.status_code, content.decode() + return self.__handle_rate_limit( + response, is_retry, method, path, params, body ) case _: if not is_retry: @@ -553,6 +548,24 @@ def _post(self, path: str, body: Any) -> Any: """POST request""" return self.__request("POST", path, None, body) + def __handle_rate_limit( + self, + response, + is_retry: bool, + method: str, + path: str, + params: Optional[dict[str, Any]], + body: Any, + ) -> Optional[dict[str, Any]]: + """Sleep out the 429 block window, retry once, share the deadline.""" + content = response.content + wait_seconds = _rate_limit_wait_seconds(content) + AristonAPI._blocked_until = time.time() + wait_seconds + if not is_retry: + time.sleep(wait_seconds) + return self.__request(method, path, params, body, True) + raise ConnectionException(response.status_code, content.decode()) + def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any: """GET request""" return self.__request("GET", path, params, None) @@ -583,7 +596,7 @@ async def async_get_detailed_devices(self) -> list[Any]: ) if detailed_devices is not None: return list(detailed_devices) - return list() + return [] async def async_get_detailed_velis_devices(self) -> list[Any]: """Async get detailed cloud devices""" @@ -592,7 +605,7 @@ async def async_get_detailed_velis_devices(self) -> list[Any]: ) if detailed_velis_devices is not None: return list(detailed_velis_devices) - return list() + return [] async def async_get_devices(self) -> list[Any]: """Async get cloud devices""" @@ -601,7 +614,7 @@ async def async_get_devices(self) -> list[Any]: ) if devices is not None: return list(devices) - return list() + return [] async def async_get_features_for_device( self, gw_id: str @@ -618,7 +631,7 @@ async def async_get_energy_account(self, gw_id: str) -> dict[str, Any]: ) if energy_account is not None: return energy_account - return dict() + return {} async def async_get_consumptions_sequences( self, gw_id: str, usages: str @@ -629,7 +642,7 @@ async def async_get_consumptions_sequences( ) if consumptions_sequences is not None: return list(consumptions_sequences) - return list() + return [] async def async_get_consumptions_settings(self, gw_id: str) -> dict[str, Any]: """Async get consumption settings""" @@ -639,7 +652,7 @@ async def async_get_consumptions_settings(self, gw_id: str) -> dict[str, Any]: ) if consumptions_settings is not None: return consumptions_settings - return dict() + return {} async def async_set_consumptions_settings( self, @@ -667,7 +680,7 @@ async def async_get_properties( ) if properties is not None: return properties - return dict() + return {} async def async_get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: """Get BSB plant data.""" @@ -676,7 +689,7 @@ async def async_get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: ) if data is not None: return data - return dict() + return {} async def async_get_velis_plant_data( self, plant_data: PlantData, gw_id: str @@ -687,7 +700,7 @@ async def async_get_velis_plant_data( ) if med_plant_data is not None: return med_plant_data - return dict() + return {} async def async_get_velis_plant_settings( self, plant_data: PlantData, gw_id: str @@ -698,7 +711,7 @@ async def async_get_velis_plant_settings( ) if med_plant_settings is not None: return med_plant_settings - return dict() + return {} async def async_get_menu_items(self, gw_id: str) -> list[dict[str, Any]]: """Async get menu items""" @@ -707,7 +720,7 @@ async def async_get_menu_items(self, gw_id: str) -> list[dict[str, Any]]: ) if items is not None: return items - return list() + return [] async def async_set_property( self, @@ -1034,28 +1047,9 @@ async def __async_request( case 404: return None case 429: - content = await response.content.read() - wait_seconds = _parse_block_seconds(content) - if wait_seconds is not None: - wait_seconds += 1 - _LOGGER.warning( - "Rate limited (429) for %s seconds; " - "waiting it out", - wait_seconds, - ) - else: - wait_seconds = 5 - _LOGGER.warning( - "Rate limited (429) without parsable block " - "duration; falling back to 5s wait" - ) - AristonAPI._blocked_until = time.time() + wait_seconds - if not is_retry: - await asyncio.sleep(wait_seconds) - return await self.__async_request( - method, path, params, body, True - ) - raise ConnectionException(response.status, content) + return await self.__async_handle_rate_limit( + response, is_retry, method, path, params, body + ) case _: if not is_retry: await asyncio.sleep(5) @@ -1075,6 +1069,24 @@ async def _async_post(self, path: str, body: Any) -> Any: """Async POST request""" return await self.__async_request("POST", path, None, body) + async def __async_handle_rate_limit( + self, + response, + is_retry: bool, + method: str, + path: str, + params: Optional[dict[str, Any]], + body: Any, + ) -> Optional[dict[str, Any]]: + """Sleep out the 429 block window, retry once, share the deadline.""" + content = await response.content.read() + wait_seconds = _rate_limit_wait_seconds(content) + AristonAPI._blocked_until = time.time() + wait_seconds + if not is_retry: + await asyncio.sleep(wait_seconds) + return await self.__async_request(method, path, params, body, True) + raise ConnectionException(response.status, content) + async def _async_get( self, path: str, params: Optional[dict[str, Any]] = None ) -> Any: diff --git a/ariston/galevo_device.py b/ariston/galevo_device.py index bf8682f..dfc3f3e 100644 --- a/ariston/galevo_device.py +++ b/ariston/galevo_device.py @@ -44,9 +44,9 @@ def __init__( super().__init__(api, attributes) self.umsys = "si" if is_metric else "us" self.language_tag = language_tag - self.consumptions_settings: dict[str, Any] = dict() - self.energy_account: dict[str, Any] = dict() - self.menu_items: list[dict[str, Any]] = list() + self.consumptions_settings: dict[str, Any] = {} + self.energy_account: dict[str, Any] = {} + self.menu_items: list[dict[str, Any]] = [] @property def consumption_type(self) -> str: diff --git a/ariston/velis_device.py b/ariston/velis_device.py index de8d4e4..4e954df 100644 --- a/ariston/velis_device.py +++ b/ariston/velis_device.py @@ -23,7 +23,7 @@ def __init__( attributes: dict[str, Any], ) -> None: super().__init__(api, attributes) - self.plant_settings: dict[str, Any] = dict() + self.plant_settings: dict[str, Any] = {} @property @abstractmethod From 853b5a489ef8355743edadd46d4fbfecb5215d13 Mon Sep 17 00:00:00 2001 From: flupkede Date: Sun, 18 Oct 2026 15:54:39 +0000 Subject: [PATCH 05/10] [feat] Nuos Split GREEN (0) via R2 web-app SetData; api/v2 operativeMode drops value 0 Review-fixes: - [Important] R2 read retry caught only ConnectionException; expired forms-auth session surfaces as ContentTypeError/KeyError (login-HTML as JSON) -> read+parse now wrapped, surfaces as ConnectionException so the fresh-login retry fires --- ariston/ariston_api.py | 141 +++++++++++++++++++++++++++++++++++ ariston/const.py | 24 +++++- ariston/nuos_split_device.py | 18 +++-- tests/test_nuos_green_r2.py | 87 +++++++++++++++++++++ 4 files changed, 261 insertions(+), 9 deletions(-) create mode 100644 tests/test_nuos_green_r2.py diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index 2584edb..cf50912 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -25,6 +25,11 @@ ARISTON_TIME_PROGS, ARISTON_VELIS, ARISTON_MENU_ITEMS, + ARISTON_R2_HOME, + ARISTON_R2_LOGIN_PAGE, + ARISTON_R2_SLP_GET_DATA, + ARISTON_R2_SLP_SET_DATA, + ARISTON_R2_USER_AGENT, BsbOperativeMode, BsbZoneMode, DeviceFeatures, @@ -88,6 +93,16 @@ def __init__( self.__api_url = api_url self.__token = "" self.__user_agent = user_agent + # Web-app (R2) cookie session; created lazily (aiohttp.CookieJar + # needs a running event loop) and logged in on first use. + self.__r2_cookies: Optional[aiohttp.CookieJar] = None + self.__r2_logged_in = False + + def _r2_cookies(self) -> aiohttp.CookieJar: + """Lazily create the R2 cookie jar (requires a running loop).""" + if self.__r2_cookies is None: + self.__r2_cookies = aiohttp.CookieJar() + return self.__r2_cookies def connect(self) -> bool: """Login to ariston cloud and get token""" @@ -788,6 +803,132 @@ async def async_set_nuos_mode( }, ) + @staticmethod + def _build_nuos_r2_payload(plant_data: dict[str, Any], op_mode: int) -> dict[str, Any]: + """Build the R2 PlantHomeSlp/SetData envelope for an operative mode. + + Mirrors the official web app: the cached plantData is echoed back + and only the viewModel fields change. + """ + return { + "plantData": { + "__type__": ["my.entities.entityiface", "my.entities.slpplantdata"], + "gatewayId": plant_data.get("gw"), + "on": plant_data.get("on"), + "mode": plant_data.get("mode"), + "waterTemp": plant_data.get("waterTemp"), + "comfortTemp": plant_data.get("comfortTemp"), + "reducedTemp": plant_data.get("reducedTemp"), + "procReqTemp": plant_data.get("procReqTemp"), + "opMode": plant_data.get("opMode"), + "holidayUntil": plant_data.get("holidayUntil"), + "boostOn": plant_data.get("boostOn"), + "hpState": plant_data.get("hpState"), + }, + "viewModel": { + "on": plant_data.get("on"), + "plantMode": plant_data.get("mode"), + "opMode": op_mode, + "boostOn": plant_data.get("boostOn"), + "comfortTemp": plant_data.get("comfortTemp"), + "holidayUntil": plant_data.get("holidayUntil"), + }, + } + + async def _async_r2_login(self) -> None: + """Log in to the R2 web app (form + anti-forgery token, cookie session).""" + self.__r2_logged_in = False + async with aiohttp.ClientSession( + cookie_jar=self._r2_cookies(), + headers={"User-Agent": ARISTON_R2_USER_AGENT}, + ) as session: + async with session.get(ARISTON_R2_LOGIN_PAGE) as response: + html = await response.text() + if response.status != 200: + raise ConnectionException( + f"R2 login page returned HTTP {response.status}" + ) + match = re.search( + r'name="__RequestVerificationToken"[^>]*value="([^"]+)"', html + ) + if match is None: + raise ConnectionException( + "R2 login page has no __RequestVerificationToken" + ) + verification_token = match.group(1) + + async with session.post( + ARISTON_R2_LOGIN_PAGE, + data={ + "__RequestVerificationToken": verification_token, + "email": self.__username, + "password": self.__password, + "rememberMe": "false", + }, + allow_redirects=False, + ) as response: + if response.status not in (200, 302): + raise ConnectionException( + f"R2 login returned HTTP {response.status}" + ) + self.__r2_logged_in = True + + async def _async_r2_get_slp_plant_data(self, gw_id: str) -> dict[str, Any]: + """Read the Nuos Split plant data through the R2 web app.""" + async with aiohttp.ClientSession( + cookie_jar=self._r2_cookies(), + headers={"User-Agent": ARISTON_R2_USER_AGENT}, + ) as session: + async with session.get( + ARISTON_R2_SLP_GET_DATA.format(gw_id) + ) as response: + if response.status != 200: + raise ConnectionException( + f"R2 GetData returned HTTP {response.status}" + ) + try: + body = await response.json() + return body["data"]["plantData"] + except (aiohttp.ContentTypeError, KeyError, ValueError) as err: + # An expired R2 forms-auth session redirects to the login + # page: HTTP 200 text/html. Surface as ConnectionException + # so the caller's fresh-login retry fires. + raise ConnectionException( + "R2 GetData returned no plant data (session expired?)" + ) from err + + async def async_set_nuos_mode_via_r2( + self, gw_id: str, value: NuosSplitOperativeMode + ) -> None: + """Set a Nuos Split operative mode through the R2 web app. + + api/v2 operativeMode accepts values 1+ but silently drops 0 (GREEN); + this endpoint applies every value — it is what the official app uses. + """ + if not self.__r2_logged_in: + await self._async_r2_login() + try: + plant_data = await self._async_r2_get_slp_plant_data(gw_id) + except ConnectionException: + # Session may have expired; one fresh login, then retry the read. + await self._async_r2_login() + plant_data = await self._async_r2_get_slp_plant_data(gw_id) + payload = self._build_nuos_r2_payload(plant_data, value.value) + async with aiohttp.ClientSession( + cookie_jar=self._r2_cookies(), + headers={ + "User-Agent": ARISTON_R2_USER_AGENT, + "X-Requested-With": "XMLHttpRequest", + }, + ) as session: + async with session.post( + ARISTON_R2_SLP_SET_DATA.format(gw_id), json=payload + ) as response: + if response.status != 200: + raise ConnectionException( + f"R2 SetData returned HTTP {response.status}" + ) + async def async_set_bsb_mode(self, gw_id: str, value: BsbOperativeMode) -> None: """Async set Bsb mode""" await self._async_post( diff --git a/ariston/const.py b/ariston/const.py index 0c14f9e..004a90e 100644 --- a/ariston/const.py +++ b/ariston/const.py @@ -5,6 +5,21 @@ ARISTON_API_URL: Final[str] = "https://www.ariston-net.remotethermo.com/api/v2/" ARISTON_LOGIN: Final[str] = "accounts/login" +# Web-app (R2) routes. The api/v2 operativeMode endpoint silently drops +# value 0 (GREEN) for Nuos Split — proven 2026-10-18 — while the web app's +# PlantHomeSlp/SetData applies it. GREEN writes go through these routes. +ARISTON_R2_BASE_URL: Final[str] = "https://www.ariston-net.remotethermo.com" +ARISTON_R2_LOGIN_PAGE: Final[str] = ARISTON_R2_BASE_URL + "/R2/Account/Login" +ARISTON_R2_HOME: Final[str] = ARISTON_R2_BASE_URL + "/R2/Home" +ARISTON_R2_SLP_GET_DATA: Final[str] = ( + ARISTON_R2_BASE_URL + + "/R2/PlantHomeSlp/GetData/{0}?fetchSettings=true&fetchTimeProg=true" +) +ARISTON_R2_SLP_SET_DATA: Final[str] = ARISTON_R2_BASE_URL + "/R2/PlantHomeSlp/SetData/{0}" +ARISTON_R2_USER_AGENT: Final[str] = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/128.0 Safari/537.36" +) ARISTON_REMOTE: Final[str] = "remote" ARISTON_VELIS: Final[str] = "velis" HOLIDAY_DATE_FORMAT: Final[str] = "%Y-%m-%dT00:00:00" @@ -227,12 +242,17 @@ class NuosSplitPlantMode(Enum): @unique class NuosSplitOperativeMode(WaterHeaterMode): - """NuosSplit operative mode enum""" + """NuosSplit operative mode enum. + + Official range (web app, 2026-10-18): Green=0, Comfort=1, Fast=2, + Auto=3, HcHp=4, Electric=5, GreenPlus=6. Only the modes the device + reliably accepts are exposed; IMEMORY was a mislabel of Auto=3. + """ GREEN = 0 COMFORT = 1 FAST = 2 - IMEMORY = 3 + AUTO = 3 @unique diff --git a/ariston/nuos_split_device.py b/ariston/nuos_split_device.py index bfc6fe7..eccb399 100644 --- a/ariston/nuos_split_device.py +++ b/ariston/nuos_split_device.py @@ -180,13 +180,17 @@ def set_water_heater_operation_mode(self, operation_mode: str): ].value async def async_set_water_heater_operation_mode(self, operation_mode: str): - """Async set water heater operation mode""" - await self.api.async_set_nuos_mode( - self.gw, NuosSplitOperativeMode[operation_mode] - ) - self.data[NuosSplitProperties.MODE] = NuosSplitOperativeMode[ - operation_mode - ].value + """Async set water heater operation mode. + + GREEN (0) goes through the R2 web-app endpoint: the api/v2 + operativeMode route silently drops value 0 (proven 2026-10-18). + """ + mode = NuosSplitOperativeMode[operation_mode] + if mode is NuosSplitOperativeMode.GREEN: + await self.api.async_set_nuos_mode_via_r2(self.gw, mode) + else: + await self.api.async_set_nuos_mode(self.gw, mode) + self.data[NuosSplitProperties.OP_MODE] = mode.value def set_min_setpoint_temp(self, min_setpoint_temp: float): """Set water heater minimum setpoint temperature""" diff --git a/tests/test_nuos_green_r2.py b/tests/test_nuos_green_r2.py new file mode 100644 index 0000000..42f2668 --- /dev/null +++ b/tests/test_nuos_green_r2.py @@ -0,0 +1,87 @@ +"""Unit tests for the Nuos Split GREEN write via the R2 web-app endpoint.""" + +import asyncio +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from ariston.ariston_api import AristonAPI +from ariston.const import NuosSplitOperativeMode +from ariston.nuos_split_device import AristonNuosSplitDevice + + +def _device() -> AristonNuosSplitDevice: + """Instantiate without the abstract machinery; only api+gw are used.""" + cls = AristonNuosSplitDevice + original = cls.__abstractmethods__ + cls.__abstractmethods__ = frozenset() + try: + device = cls.__new__(cls) + finally: + cls.__abstractmethods__ = original + device.api = AristonAPI("user", "pass") + device.gw = "3C8A1F2EDE84" + device.data = {} + return device + + +def test_build_nuos_r2_payload_green() -> None: + plant = { + "gw": "3C8A1F2EDE84", + "on": True, + "mode": 2, + "waterTemp": 49.0, + "comfortTemp": 54.0, + "reducedTemp": 16.0, + "procReqTemp": 54.0, + "opMode": 1, + "holidayUntil": None, + "boostOn": False, + "hpState": 2, + } + payload = AristonAPI._build_nuos_r2_payload(plant, NuosSplitOperativeMode.GREEN.value) + + assert payload["viewModel"]["opMode"] == 0 # GREEN — the value that must change + assert payload["viewModel"]["plantMode"] == 2 + assert payload["viewModel"]["comfortTemp"] == 54.0 + assert payload["plantData"]["gatewayId"] == "3C8A1F2EDE84" + assert payload["plantData"]["__type__"] == [ + "my.entities.entityiface", + "my.entities.slpplantdata", + ] + + +def test_green_write_routes_through_r2() -> None: + device = _device() + device.api.async_set_nuos_mode_via_r2 = AsyncMock() # type: ignore[method-assign] + device.api.async_set_nuos_mode = AsyncMock() # type: ignore[method-assign] + + asyncio.run(device.async_set_water_heater_operation_mode("GREEN")) + + device.api.async_set_nuos_mode_via_r2.assert_awaited_once_with( + device.gw, NuosSplitOperativeMode.GREEN + ) + device.api.async_set_nuos_mode.assert_not_awaited() + assert device.data["opMode"] == 0 + + +def test_comfort_write_keeps_direct_route() -> None: + device = _device() + device.api.async_set_nuos_mode_via_r2 = AsyncMock() # type: ignore[method-assign] + device.api.async_set_nuos_mode = AsyncMock() # type: ignore[method-assign] + + asyncio.run(device.async_set_water_heater_operation_mode("COMFORT")) + + device.api.async_set_nuos_mode.assert_awaited_once_with( + device.gw, NuosSplitOperativeMode.COMFORT + ) + device.api.async_set_nuos_mode_via_r2.assert_not_awaited() + assert device.data["opMode"] == 1 + + +def test_enum_values_match_official_range() -> None: + assert NuosSplitOperativeMode.GREEN.value == 0 + assert NuosSplitOperativeMode.COMFORT.value == 1 + assert NuosSplitOperativeMode.FAST.value == 2 + assert NuosSplitOperativeMode.AUTO.value == 3 # was mislabeled IMEMORY From 0d5daca0f68f50d0b753409caf8cd272fab6d8ae Mon Sep 17 00:00:00 2001 From: flupkede Date: Sun, 18 Oct 2026 16:29:01 +0000 Subject: [PATCH 06/10] [test] cover R2 read+parse failure shapes and fresh-login retry Round-2 review remark: the expired-session path fixed in 853b5a4 was executed by no test. Two hermetic guards: bad GetData body (KeyError/ ValueError) surfaces ConnectionException; one failed read triggers exactly one fresh login and one retry read. Suite 17/17. --- tests/test_nuos_green_r2.py | 88 ++++++++++++++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 2 deletions(-) diff --git a/tests/test_nuos_green_r2.py b/tests/test_nuos_green_r2.py index 42f2668..c049516 100644 --- a/tests/test_nuos_green_r2.py +++ b/tests/test_nuos_green_r2.py @@ -2,11 +2,11 @@ import asyncio from typing import Any -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, MagicMock, patch import pytest -from ariston.ariston_api import AristonAPI +from ariston.ariston_api import AristonAPI, ConnectionException from ariston.const import NuosSplitOperativeMode from ariston.nuos_split_device import AristonNuosSplitDevice @@ -85,3 +85,87 @@ def test_enum_values_match_official_range() -> None: assert NuosSplitOperativeMode.COMFORT.value == 1 assert NuosSplitOperativeMode.FAST.value == 2 assert NuosSplitOperativeMode.AUTO.value == 3 # was mislabeled IMEMORY + + +class _FakeAsyncCtx: + """Minimal async context manager yielding a fake response.""" + + def __init__(self, response: Any) -> None: + self._response = response + + async def __aenter__(self) -> Any: + return self._response + + async def __aexit__(self, *exc: Any) -> None: + return None + + +class _FakeSession: + """Stand-in for aiohttp.ClientSession used as an async context manager.""" + + def __init__(self, response: Any) -> None: + self._response = response + + async def __aenter__(self) -> "_FakeSession": + return self + + async def __aexit__(self, *exc: Any) -> None: + return None + + def get(self, *args: Any, **kwargs: Any) -> _FakeAsyncCtx: + return _FakeAsyncCtx(self._response) + + def post(self, *args: Any, **kwargs: Any) -> _FakeAsyncCtx: + return _FakeAsyncCtx(self._response) + + +class _FakeResponse: + def __init__(self, status: int, json_err: Exception | None = None) -> None: + self.status = status + self._json_err = json_err + + async def json(self) -> Any: + if self._json_err is not None: + raise self._json_err + return {} + + +@pytest.mark.parametrize( + "json_err", + [ + KeyError("plantData"), + ValueError("bad json"), + ], +) +def test_r2_read_surfaces_connection_exception_on_bad_body(json_err: Exception) -> None: + """Expired R2 session: GetData answers 200 with a non-plantData body. + + The read+parse must surface ConnectionException so the caller's + fresh-login retry fires (regression guard for the silent-drop bug). + """ + api = AristonAPI("user", "pass") + fake = _FakeSession(_FakeResponse(200, json_err=json_err)) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + with pytest.raises(ConnectionException, match="session expired"): + asyncio.run(api._async_r2_get_slp_plant_data("GW")) + + +def test_r2_retry_fires_fresh_login_after_failed_read() -> None: + """One failed read -> fresh login -> retry read -> SetData POST.""" + api = AristonAPI("user", "pass") + api._async_r2_login = AsyncMock() + api._async_r2_get_slp_plant_data = AsyncMock( + side_effect=[ConnectionException("expired"), {"any": "plant"}] + ) + api._build_nuos_r2_payload = MagicMock(return_value={}) + fake = _FakeSession(_FakeResponse(200)) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + asyncio.run( + api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + ) + assert api._async_r2_login.await_count == 2 + assert api._async_r2_get_slp_plant_data.await_count == 2 From f173bcbea3224bbdee998f9437caa38ea2a0694e Mon Sep 17 00:00:00 2001 From: flupkede Date: Sat, 14 Nov 2026 18:40:37 +0000 Subject: [PATCH 07/10] [fix] review round 2026-11-12: per-instance 429 window, sync R2 path, SetData validation, py3.9 test annotations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _blocked_until: class attribute -> instance attribute; a 429 on one account must not silence other AristonAPI instances (the three HA coordinators for one account still share one instance) - sync set_nuos_mode_via_r2 (requests twin of the async R2 flow); the sync device setter now routes GREEN through it and echoes into opMode like the async setter (was MODE) - R2 SetData response validated (sync + async): non-JSON body (expired session redirect to the login page) and success:false raise ConnectionException instead of reporting success; no POST retry — the read just before the write already validated the session - test module: from __future__ import annotations (py3.9 import TypeError); verified on a py3.9 interpreter Note: ariston/__init__.py uses match/case, so the package itself does not import on py3.9 despite requires-python = ">=3.9" (pre-existing, flagged in the PR thread). Suite 25/25. --- ariston/ariston_api.py | 130 +++++++++++++++++++++++++++--- ariston/nuos_split_device.py | 16 ++-- tests/test_device_models.py | 13 ++- tests/test_nuos_green_r2.py | 151 ++++++++++++++++++++++++++++++++++- tests/test_rate_limit.py | 65 +++++++++++---- 5 files changed, 342 insertions(+), 33 deletions(-) diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index cf50912..7879f9d 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -76,10 +76,6 @@ class ConnectionException(Exception): class AristonAPI: """Ariston API class""" - # Shared across all instances: one 429 silences every caller (all three - # HA coordinators) until the block window has passed. - _blocked_until: float = 0.0 - def __init__( self, username: str, @@ -97,6 +93,12 @@ def __init__( # needs a running event loop) and logged in on first use. self.__r2_cookies: Optional[aiohttp.CookieJar] = None self.__r2_logged_in = False + # Per-instance 429 block window: instances for different accounts or + # API URLs must not silence each other; the three coordinators for + # one account still share one API instance. + self._blocked_until = 0.0 + # Sync (requests) R2 web-app session; created lazily on first use. + self.__r2_requests_session: Optional[requests.Session] = None def _r2_cookies(self) -> aiohttp.CookieJar: """Lazily create the R2 cookie jar (requires a running loop).""" @@ -513,7 +515,7 @@ def __request( is_retry: bool = False, ) -> Optional[dict[str, Any]]: """Request with requests""" - if not is_retry and time.time() < AristonAPI._blocked_until: + if not is_retry and time.time() < self._blocked_until: raise ConnectionException( 429, "Rate limited; skipping request until the block window ends", @@ -572,10 +574,10 @@ def __handle_rate_limit( params: Optional[dict[str, Any]], body: Any, ) -> Optional[dict[str, Any]]: - """Sleep out the 429 block window, retry once, share the deadline.""" + """Sleep out the 429 block window, retry once, per-instance deadline.""" content = response.content wait_seconds = _rate_limit_wait_seconds(content) - AristonAPI._blocked_until = time.time() + wait_seconds + self._blocked_until = time.time() + wait_seconds if not is_retry: time.sleep(wait_seconds) return self.__request(method, path, params, body, True) @@ -585,6 +587,99 @@ def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any: """GET request""" return self.__request("GET", path, params, None) + def _r2_session(self) -> requests.Session: + """Lazily create the R2 requests session (holds the auth cookies).""" + if self.__r2_requests_session is None: + self.__r2_requests_session = requests.Session() + self.__r2_requests_session.headers["User-Agent"] = ARISTON_R2_USER_AGENT + return self.__r2_requests_session + + def _r2_login(self) -> None: + """Log in to the R2 web app (form + anti-forgery token, cookie session).""" + self.__r2_logged_in = False + session = self._r2_session() + login_page = session.get(ARISTON_R2_LOGIN_PAGE) + if login_page.status_code != 200: + raise ConnectionException( + f"R2 login page returned HTTP {login_page.status_code}" + ) + match = re.search( + r'name="__RequestVerificationToken"[^>]*value="([^"]+)"', login_page.text + ) + if match is None: + raise ConnectionException( + "R2 login page has no __RequestVerificationToken" + ) + login = session.post( + ARISTON_R2_LOGIN_PAGE, + data={ + "__RequestVerificationToken": match.group(1), + "email": self.__username, + "password": self.__password, + "rememberMe": "false", + }, + allow_redirects=False, + ) + if login.status_code not in (200, 302): + raise ConnectionException(f"R2 login returned HTTP {login.status_code}") + self.__r2_logged_in = True + + def _r2_get_slp_plant_data(self, gw_id: str) -> dict[str, Any]: + """Read the Nuos Split plant data through the R2 web app.""" + response = self._r2_session().get(ARISTON_R2_SLP_GET_DATA.format(gw_id)) + if response.status_code != 200: + raise ConnectionException( + f"R2 GetData returned HTTP {response.status_code}" + ) + try: + body = response.json() + return body["data"]["plantData"] + except (KeyError, ValueError) as err: + # An expired R2 forms-auth session redirects to the login page: + # HTTP 200 text/html. Surface as ConnectionException so the + # caller's fresh-login retry fires. + raise ConnectionException( + "R2 GetData returned no plant data (session expired?)" + ) from err + + def _r2_post_set_data(self, gw_id: str, payload: dict[str, Any]) -> None: + """POST the R2 SetData envelope and validate the response.""" + response = self._r2_session().post( + ARISTON_R2_SLP_SET_DATA.format(gw_id), + json=payload, + headers={"X-Requested-With": "XMLHttpRequest"}, + ) + if response.status_code != 200: + raise ConnectionException( + f"R2 SetData returned HTTP {response.status_code}" + ) + try: + body = response.json() + except ValueError as err: + raise ConnectionException( + "R2 SetData returned a non-JSON body (session expired?)" + ) from err + if isinstance(body, dict) and body.get("success") is False: + raise ConnectionException(f"R2 SetData reported failure: {body}") + + def set_nuos_mode_via_r2(self, gw_id: str, value: NuosSplitOperativeMode) -> None: + """Set a Nuos Split operative mode through the R2 web app. + + api/v2 operativeMode accepts values 1+ but silently drops 0 (GREEN); + this endpoint applies every value — it is what the official app uses. + """ + if not self.__r2_logged_in: + self._r2_login() + try: + plant_data = self._r2_get_slp_plant_data(gw_id) + except ConnectionException: + # Session may have expired; one fresh login, then retry the read. + self._r2_login() + plant_data = self._r2_get_slp_plant_data(gw_id) + self._r2_post_set_data( + gw_id, self._build_nuos_r2_payload(plant_data, value.value) + ) + async def async_connect(self) -> bool: """Async login to ariston cloud and get token""" @@ -914,6 +1009,12 @@ async def async_set_nuos_mode_via_r2( await self._async_r2_login() plant_data = await self._async_r2_get_slp_plant_data(gw_id) payload = self._build_nuos_r2_payload(plant_data, value.value) + await self._async_r2_post_set_data(gw_id, payload) + + async def _async_r2_post_set_data( + self, gw_id: str, payload: dict[str, Any] + ) -> None: + """POST the R2 SetData envelope and validate the response.""" async with aiohttp.ClientSession( cookie_jar=self._r2_cookies(), headers={ @@ -928,6 +1029,17 @@ async def async_set_nuos_mode_via_r2( raise ConnectionException( f"R2 SetData returned HTTP {response.status}" ) + try: + body = await response.json() + except (aiohttp.ContentTypeError, ValueError) as err: + # An expired session turns the POST into a redirect to + # the login page (HTTP 200 text/html) — auth failure, + # not success. + raise ConnectionException( + "R2 SetData returned a non-JSON body (session expired?)" + ) from err + if isinstance(body, dict) and body.get("success") is False: + raise ConnectionException(f"R2 SetData reported failure: {body}") async def async_set_bsb_mode(self, gw_id: str, value: BsbOperativeMode) -> None: """Async set Bsb mode""" @@ -1151,7 +1263,7 @@ async def __async_request( is_retry: bool = False, ) -> Optional[dict[str, Any]]: """Async request with aiohttp""" - if not is_retry and time.time() < AristonAPI._blocked_until: + if not is_retry and time.time() < self._blocked_until: raise ConnectionException( 429, "Rate limited; skipping request until the block window ends", @@ -1222,7 +1334,7 @@ async def __async_handle_rate_limit( """Sleep out the 429 block window, retry once, share the deadline.""" content = await response.content.read() wait_seconds = _rate_limit_wait_seconds(content) - AristonAPI._blocked_until = time.time() + wait_seconds + self._blocked_until = time.time() + wait_seconds if not is_retry: await asyncio.sleep(wait_seconds) return await self.__async_request(method, path, params, body, True) diff --git a/ariston/nuos_split_device.py b/ariston/nuos_split_device.py index eccb399..8d637da 100644 --- a/ariston/nuos_split_device.py +++ b/ariston/nuos_split_device.py @@ -173,11 +173,17 @@ async def async_set_water_heater_reduced_temperature(self, temperature: float): await self._async_set_water_heater_temperature(current, temperature) def set_water_heater_operation_mode(self, operation_mode: str): - """Set water heater operation mode""" - self.api.set_nuos_mode(self.gw, NuosSplitOperativeMode[operation_mode]) - self.data[NuosSplitProperties.MODE] = NuosSplitOperativeMode[ - operation_mode - ].value + """Set water heater operation mode. + + GREEN (0) goes through the R2 web-app endpoint: the api/v2 + operativeMode route silently drops value 0 (proven 2026-10-18). + """ + mode = NuosSplitOperativeMode[operation_mode] + if mode is NuosSplitOperativeMode.GREEN: + self.api.set_nuos_mode_via_r2(self.gw, mode) + else: + self.api.set_nuos_mode(self.gw, mode) + self.data[NuosSplitProperties.OP_MODE] = mode.value async def async_set_water_heater_operation_mode(self, operation_mode: str): """Async set water heater operation mode. diff --git a/tests/test_device_models.py b/tests/test_device_models.py index a36fd25..3298168 100644 --- a/tests/test_device_models.py +++ b/tests/test_device_models.py @@ -305,13 +305,19 @@ def test_nuos_split_properties_sync_async_and_missing_state_defaults(self): device.set_heating_rate(5) self.assertEqual(device.data[NuosSplitProperties.PROC_REQ_TEMP], 43) self.assertEqual(device.data[NuosSplitProperties.REDUCED_TEMP], 42) - self.assertEqual(device.data[NuosSplitProperties.MODE], NuosSplitOperativeMode.FAST.value) + # opMode (operative mode) is echoed, not mode (plant mode — never + # changes on an operativeMode write, proven against the live API) + self.assertEqual( + device.data[NuosSplitProperties.OP_MODE], + NuosSplitOperativeMode.FAST.value, + ) device.api.set_nuos_temperature.assert_called_with("gw-1", 43, 42, 55, 40) device.api.set_velis_plant_setting.assert_called() device.api.async_set_nous_boost = AsyncMock() device.api.async_set_nuos_temperature = AsyncMock() device.api.async_set_nuos_mode = AsyncMock() + device.api.async_set_nuos_mode_via_r2 = AsyncMock() device.api.async_set_velis_plant_setting = AsyncMock() async def set_values(): @@ -325,7 +331,10 @@ async def set_values(): asyncio.run(set_values()) self.assertTrue(device.data[NuosSplitProperties.BOOST_ON]) - self.assertEqual(device.data[NuosSplitProperties.MODE], NuosSplitOperativeMode.GREEN.value) + self.assertEqual( + device.data[NuosSplitProperties.OP_MODE], + NuosSplitOperativeMode.GREEN.value, + ) self.assertEqual(device.plant_settings[SlpDeviceSettings.SLP_HEATING_RATE], 4) self.assertEqual(device.api.async_set_velis_plant_setting.await_count, 3) diff --git a/tests/test_nuos_green_r2.py b/tests/test_nuos_green_r2.py index c049516..2438557 100644 --- a/tests/test_nuos_green_r2.py +++ b/tests/test_nuos_green_r2.py @@ -1,9 +1,12 @@ """Unit tests for the Nuos Split GREEN write via the R2 web-app endpoint.""" +from __future__ import annotations + import asyncio from typing import Any from unittest.mock import AsyncMock, MagicMock, patch +import aiohttp import pytest from ariston.ariston_api import AristonAPI, ConnectionException @@ -120,14 +123,20 @@ def post(self, *args: Any, **kwargs: Any) -> _FakeAsyncCtx: class _FakeResponse: - def __init__(self, status: int, json_err: Exception | None = None) -> None: + def __init__( + self, + status: int, + json_err: Exception | None = None, + json_data: Any = None, + ) -> None: self.status = status self._json_err = json_err + self._json_data = json_data async def json(self) -> Any: if self._json_err is not None: raise self._json_err - return {} + return self._json_data if self._json_data is not None else {} @pytest.mark.parametrize( @@ -169,3 +178,141 @@ def test_r2_retry_fires_fresh_login_after_failed_read() -> None: ) assert api._async_r2_login.await_count == 2 assert api._async_r2_get_slp_plant_data.await_count == 2 + + +def test_r2_setdata_success_false_raises() -> None: + """A 200 body with success:false is a failed write, not a success.""" + api = AristonAPI("user", "pass") + api._async_r2_login = AsyncMock() + api._async_r2_get_slp_plant_data = AsyncMock(return_value={"any": "plant"}) + fake = _FakeSession(_FakeResponse(200, json_data={"success": False})) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + with pytest.raises(ConnectionException, match="reported failure"): + asyncio.run( + api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + ) + + +def test_r2_setdata_non_json_body_raises() -> None: + """An expired session turns the POST into a 200 login page — auth failure.""" + api = AristonAPI("user", "pass") + api._async_r2_login = AsyncMock() + api._async_r2_get_slp_plant_data = AsyncMock(return_value={"any": "plant"}) + err = aiohttp.ContentTypeError(MagicMock(), ()) + fake = _FakeSession(_FakeResponse(200, json_err=err)) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + with pytest.raises(ConnectionException, match="non-JSON body"): + asyncio.run( + api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + ) + + +class _FakeRequestsSession: + """Stand-in for requests.Session with queued responses.""" + + def __init__(self) -> None: + self.headers: dict[str, str] = {} + self._responses: list[Any] = [] + self.posts: list[dict[str, Any]] = [] + + def queue(self, *responses: Any) -> None: + self._responses.extend(responses) + + def get(self, *args: Any, **kwargs: Any) -> Any: + return self._responses.pop(0) + + def post(self, *args: Any, **kwargs: Any) -> Any: + self.posts.append(kwargs) + return self._responses.pop(0) + + +class _FakeRequestsResponse: + def __init__( + self, + status_code: int = 200, + text: str = "", + json_data: Any = None, + ) -> None: + self.status_code = status_code + self.text = text + self.ok = status_code < 400 + self._json_data = json_data + + def json(self) -> Any: + return self._json_data if self._json_data is not None else {} + + +_LOGIN_HTML = '' + + +def test_sync_green_write_full_r2_flow() -> None: + """Sync GREEN: login -> read -> write, opMode 0 in the SetData envelope.""" + api = AristonAPI("user", "pass") + session = _FakeRequestsSession() + session.queue( + _FakeRequestsResponse(200, text=_LOGIN_HTML), + _FakeRequestsResponse(302), + _FakeRequestsResponse( + json_data={"data": {"plantData": {"mode": 2, "on": True}}} + ), + _FakeRequestsResponse(json_data={"success": True}), + ) + with patch("ariston.ariston_api.requests.Session", lambda: session): + api.set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + + assert len(session.posts) == 2 + login_form = session.posts[0]["data"] + assert login_form["__RequestVerificationToken"] == "TOKEN123" + setdata_body = session.posts[1]["json"] + assert setdata_body["viewModel"]["opMode"] == 0 + assert setdata_body["plantData"]["mode"] == 2 # plant data echoed back + + +def test_sync_r2_retry_fires_fresh_login() -> None: + """Sync twin of the async retry: one failed read -> fresh login -> retry.""" + api = AristonAPI("user", "pass") + api._r2_login = MagicMock() + api._r2_get_slp_plant_data = MagicMock( + side_effect=[ConnectionException("expired"), {"any": "plant"}] + ) + session = _FakeRequestsSession() + session.queue(_FakeRequestsResponse(json_data={"success": True})) + with patch("ariston.ariston_api.requests.Session", lambda: session): + api.set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + + assert api._r2_login.call_count == 2 + assert api._r2_get_slp_plant_data.call_count == 2 + + +def test_sync_green_write_routes_through_r2() -> None: + """Device sync setter: GREEN must not hit the api/v2 direct route.""" + device = _device() + device.api.set_nuos_mode_via_r2 = MagicMock() + device.api.set_nuos_mode = MagicMock() + + device.set_water_heater_operation_mode("GREEN") + + device.api.set_nuos_mode_via_r2.assert_called_once_with( + device.gw, NuosSplitOperativeMode.GREEN + ) + device.api.set_nuos_mode.assert_not_called() + assert device.data["opMode"] == 0 + + +def test_sync_comfort_write_keeps_direct_route() -> None: + """Device sync setter: COMFORT keeps the proven api/v2 direct route.""" + device = _device() + device.api.set_nuos_mode_via_r2 = MagicMock() + device.api.set_nuos_mode = MagicMock() + + device.set_water_heater_operation_mode("COMFORT") + + device.api.set_nuos_mode.assert_called_once_with( + device.gw, NuosSplitOperativeMode.COMFORT + ) + device.api.set_nuos_mode_via_r2.assert_not_called() + assert device.data["opMode"] == 1 diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 89134cf..5a242cc 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -14,14 +14,6 @@ ) -@pytest.fixture(autouse=True) -def _reset_blocked_until(): - """Isolate the class-level block window between tests.""" - AristonAPI._blocked_until = 0.0 - yield - AristonAPI._blocked_until = 0.0 - - def _api() -> AristonAPI: return AristonAPI("user", "pass") @@ -59,15 +51,16 @@ def test_429_parses_wait_seconds(): ] http = MagicMock(side_effect=responses) sleeps: list[int] = [] + api = _api() with patch("ariston.ariston_api.requests.request", http), patch( "ariston.ariston_api.time.sleep", side_effect=sleeps.append ): - result = _api()._get("https://example/api") + result = api._get("https://example/api") assert result == {"ok": True} assert http.call_count == 2 # exactly one retry assert sleeps == [67] # parsed 66 + 1s margin - assert AristonAPI._blocked_until > 0 # block window was set + assert api._blocked_until > 0 # block window was set def test_429_without_parsable_body(): @@ -102,10 +95,10 @@ def test_429_twice_raises(): assert http.call_count == 2 # one retry, then raise — no infinite loop -def test_blocked_until_short_circuits(monkeypatch): - monkeypatch.setattr(AristonAPI, "_blocked_until", time.time() + 30) - http = MagicMock() +def test_blocked_until_short_circuits(): api = _api() + api._blocked_until = time.time() + 30 + http = MagicMock() with patch("ariston.ariston_api.requests.request", http): with pytest.raises(ConnectionException): api._get("https://example/api") @@ -113,6 +106,25 @@ def test_blocked_until_short_circuits(monkeypatch): http.assert_not_called() # no network call inside the block window +def test_block_window_is_per_instance(): + """A 429 on one instance must not silence other instances.""" + blocked = _api() + other = _api() + http = MagicMock( + side_effect=[ + _sync_response(429, b"Requests are blocked for 30 seconds"), + _sync_response(200, b"{}", {"ok": True}), + ] + ) + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep" + ): + assert blocked._get("https://example/api") == {"ok": True} + + assert blocked._blocked_until > 0 + assert other._blocked_until == 0.0 # untouched by the other instance's 429 + + # --------------------------------------------------------------------------- # async path (aiohttp) # --------------------------------------------------------------------------- @@ -182,10 +194,10 @@ async def run() -> Any: assert sleeps == [67] # parsed 66 + 1s margin -def test_async_blocked_until_short_circuits(monkeypatch): - monkeypatch.setattr(AristonAPI, "_blocked_until", time.time() + 30) +def test_async_blocked_until_short_circuits(): calls: list[int] = [] api = _api() + api._blocked_until = time.time() + 30 async def run() -> None: with patch( @@ -198,3 +210,26 @@ async def run() -> None: asyncio.run(run()) assert calls == [] # no network call inside the block window + + +def test_async_block_window_is_per_instance(): + """Async twin: a 429 on one instance must not silence other instances.""" + blocked = _api() + other = _api() + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked for 30 seconds"), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ] + calls: list[int] = [] + + async def run() -> Any: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ), patch("ariston.ariston_api.asyncio.sleep"): + return await blocked._async_get("https://example/api") + + assert asyncio.run(run()) == {"ok": True} + + assert blocked._blocked_until > 0 + assert other._blocked_until == 0.0 # untouched by the other instance's 429 From ace3bb82248e4d92a7a6815254a1d8c061d07028 Mon Sep 17 00:00:00 2001 From: flupkede Date: Sat, 14 Nov 2026 19:26:06 +0000 Subject: [PATCH 08/10] [refactor] drop duplicated Velis holiday API pair; delegate to main's set_velis_slp_holiday main gained set_velis_slp_holiday/async_set_velis_slp_holiday (same velis/slpPlantData holiday endpoint) after this branch introduced set_velis_holiday/async_set_velis_holiday. Keep main's pair as the canonical API; this branch keeps only the device-level wrapper (AristonVelisDevice.set_velis_holiday, which adds HOLIDAY_DATE_FORMAT date handling and is what the HA integration calls) and now delegates to main's methods. Suite 83 tests + 150 subtests green. --- ariston/ariston_api.py | 26 -------------------------- ariston/velis_device.py | 6 ++++-- 2 files changed, 4 insertions(+), 28 deletions(-) diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index d0f2093..d9160fd 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -1214,32 +1214,6 @@ async def async_set_velis_plant_setting( {setting: {"new": value, "old": old_value}}, ) - def set_velis_holiday( - self, - gw_id: str, - holiday_end_date: Optional[str], - ) -> None: - """Set Velis holiday""" - self._post( - f"{self.__api_url}{ARISTON_VELIS}/{PlantData.Slp.value}/{gw_id}/holiday", - { - "new": holiday_end_date, - }, - ) - - async def async_set_velis_holiday( - self, - gw_id: str, - holiday_end_date: Optional[str], - ) -> None: - """Async set Velis holiday""" - await self._async_post( - f"{self.__api_url}{ARISTON_VELIS}/{PlantData.Slp.value}/{gw_id}/holiday", - { - "new": holiday_end_date, - }, - ) - async def async_get_thermostat_time_progs( self, gw_id: str, zone: int, umsys: str ) -> Optional[dict[str, Any]]: diff --git a/ariston/velis_device.py b/ariston/velis_device.py index 4e954df..6029ccf 100644 --- a/ariston/velis_device.py +++ b/ariston/velis_device.py @@ -99,11 +99,13 @@ def _create_holiday_end_date(holiday_end: Optional[date]) -> Optional[str]: def set_velis_holiday(self, holiday_end: Optional[date]) -> None: """Set Velis holiday on device""" - self.api.set_velis_holiday(self.gw, self._create_holiday_end_date(holiday_end)) + self.api.set_velis_slp_holiday( + self.gw, self._create_holiday_end_date(holiday_end) + ) async def async_set_velis_holiday(self, holiday_end: Optional[date]) -> None: """Async set Velis holiday on device""" - await self.api.async_set_velis_holiday( + await self.api.async_set_velis_slp_holiday( self.gw, self._create_holiday_end_date(holiday_end) ) From 52a017e4f99fbc6f12fcbe2c7c34bd52f9ef7f07 Mon Sep 17 00:00:00 2001 From: flupkede Date: Sat, 14 Nov 2026 19:34:50 +0000 Subject: [PATCH 09/10] [fix] run the PR's test modules under the CI unittest runner (no pytest) The Tests workflow installs only locked runtime deps (no pytest) and runs 'coverage run -m unittest discover'. Two of this branch's test modules imported pytest (ModuleNotFoundError in CI) and the third used module-level functions, which unittest discovery silently skips. Converted test_rate_limit.py, test_nuos_green_r2.py and test_velis_holiday.py to stdlib unittest.TestCase style; the pytest parametrize became a subTest loop, pytest.raises became assertRaises/assertRaisesRegex. No test logic changed. Verified with the exact CI commands on a pytest-less interpreter: 82 tests OK, coverage 99% (gate is 90%). Suite also still passes under pytest. --- tests/test_nuos_green_r2.py | 403 ++++++++++++++++++------------------ tests/test_rate_limit.py | 299 +++++++++++++------------- tests/test_velis_holiday.py | 60 +++--- 3 files changed, 379 insertions(+), 383 deletions(-) diff --git a/tests/test_nuos_green_r2.py b/tests/test_nuos_green_r2.py index 2438557..ad52096 100644 --- a/tests/test_nuos_green_r2.py +++ b/tests/test_nuos_green_r2.py @@ -3,11 +3,11 @@ from __future__ import annotations import asyncio +import unittest from typing import Any from unittest.mock import AsyncMock, MagicMock, patch import aiohttp -import pytest from ariston.ariston_api import AristonAPI, ConnectionException from ariston.const import NuosSplitOperativeMode @@ -29,67 +29,6 @@ def _device() -> AristonNuosSplitDevice: return device -def test_build_nuos_r2_payload_green() -> None: - plant = { - "gw": "3C8A1F2EDE84", - "on": True, - "mode": 2, - "waterTemp": 49.0, - "comfortTemp": 54.0, - "reducedTemp": 16.0, - "procReqTemp": 54.0, - "opMode": 1, - "holidayUntil": None, - "boostOn": False, - "hpState": 2, - } - payload = AristonAPI._build_nuos_r2_payload(plant, NuosSplitOperativeMode.GREEN.value) - - assert payload["viewModel"]["opMode"] == 0 # GREEN — the value that must change - assert payload["viewModel"]["plantMode"] == 2 - assert payload["viewModel"]["comfortTemp"] == 54.0 - assert payload["plantData"]["gatewayId"] == "3C8A1F2EDE84" - assert payload["plantData"]["__type__"] == [ - "my.entities.entityiface", - "my.entities.slpplantdata", - ] - - -def test_green_write_routes_through_r2() -> None: - device = _device() - device.api.async_set_nuos_mode_via_r2 = AsyncMock() # type: ignore[method-assign] - device.api.async_set_nuos_mode = AsyncMock() # type: ignore[method-assign] - - asyncio.run(device.async_set_water_heater_operation_mode("GREEN")) - - device.api.async_set_nuos_mode_via_r2.assert_awaited_once_with( - device.gw, NuosSplitOperativeMode.GREEN - ) - device.api.async_set_nuos_mode.assert_not_awaited() - assert device.data["opMode"] == 0 - - -def test_comfort_write_keeps_direct_route() -> None: - device = _device() - device.api.async_set_nuos_mode_via_r2 = AsyncMock() # type: ignore[method-assign] - device.api.async_set_nuos_mode = AsyncMock() # type: ignore[method-assign] - - asyncio.run(device.async_set_water_heater_operation_mode("COMFORT")) - - device.api.async_set_nuos_mode.assert_awaited_once_with( - device.gw, NuosSplitOperativeMode.COMFORT - ) - device.api.async_set_nuos_mode_via_r2.assert_not_awaited() - assert device.data["opMode"] == 1 - - -def test_enum_values_match_official_range() -> None: - assert NuosSplitOperativeMode.GREEN.value == 0 - assert NuosSplitOperativeMode.COMFORT.value == 1 - assert NuosSplitOperativeMode.FAST.value == 2 - assert NuosSplitOperativeMode.AUTO.value == 3 # was mislabeled IMEMORY - - class _FakeAsyncCtx: """Minimal async context manager yielding a fake response.""" @@ -139,78 +78,6 @@ async def json(self) -> Any: return self._json_data if self._json_data is not None else {} -@pytest.mark.parametrize( - "json_err", - [ - KeyError("plantData"), - ValueError("bad json"), - ], -) -def test_r2_read_surfaces_connection_exception_on_bad_body(json_err: Exception) -> None: - """Expired R2 session: GetData answers 200 with a non-plantData body. - - The read+parse must surface ConnectionException so the caller's - fresh-login retry fires (regression guard for the silent-drop bug). - """ - api = AristonAPI("user", "pass") - fake = _FakeSession(_FakeResponse(200, json_err=json_err)) - with patch( - "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake - ): - with pytest.raises(ConnectionException, match="session expired"): - asyncio.run(api._async_r2_get_slp_plant_data("GW")) - - -def test_r2_retry_fires_fresh_login_after_failed_read() -> None: - """One failed read -> fresh login -> retry read -> SetData POST.""" - api = AristonAPI("user", "pass") - api._async_r2_login = AsyncMock() - api._async_r2_get_slp_plant_data = AsyncMock( - side_effect=[ConnectionException("expired"), {"any": "plant"}] - ) - api._build_nuos_r2_payload = MagicMock(return_value={}) - fake = _FakeSession(_FakeResponse(200)) - with patch( - "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake - ): - asyncio.run( - api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) - ) - assert api._async_r2_login.await_count == 2 - assert api._async_r2_get_slp_plant_data.await_count == 2 - - -def test_r2_setdata_success_false_raises() -> None: - """A 200 body with success:false is a failed write, not a success.""" - api = AristonAPI("user", "pass") - api._async_r2_login = AsyncMock() - api._async_r2_get_slp_plant_data = AsyncMock(return_value={"any": "plant"}) - fake = _FakeSession(_FakeResponse(200, json_data={"success": False})) - with patch( - "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake - ): - with pytest.raises(ConnectionException, match="reported failure"): - asyncio.run( - api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) - ) - - -def test_r2_setdata_non_json_body_raises() -> None: - """An expired session turns the POST into a 200 login page — auth failure.""" - api = AristonAPI("user", "pass") - api._async_r2_login = AsyncMock() - api._async_r2_get_slp_plant_data = AsyncMock(return_value={"any": "plant"}) - err = aiohttp.ContentTypeError(MagicMock(), ()) - fake = _FakeSession(_FakeResponse(200, json_err=err)) - with patch( - "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake - ): - with pytest.raises(ConnectionException, match="non-JSON body"): - asyncio.run( - api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) - ) - - class _FakeRequestsSession: """Stand-in for requests.Session with queued responses.""" @@ -249,70 +116,204 @@ def json(self) -> Any: _LOGIN_HTML = '' -def test_sync_green_write_full_r2_flow() -> None: - """Sync GREEN: login -> read -> write, opMode 0 in the SetData envelope.""" - api = AristonAPI("user", "pass") - session = _FakeRequestsSession() - session.queue( - _FakeRequestsResponse(200, text=_LOGIN_HTML), - _FakeRequestsResponse(302), - _FakeRequestsResponse( - json_data={"data": {"plantData": {"mode": 2, "on": True}}} - ), - _FakeRequestsResponse(json_data={"success": True}), - ) - with patch("ariston.ariston_api.requests.Session", lambda: session): - api.set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) - - assert len(session.posts) == 2 - login_form = session.posts[0]["data"] - assert login_form["__RequestVerificationToken"] == "TOKEN123" - setdata_body = session.posts[1]["json"] - assert setdata_body["viewModel"]["opMode"] == 0 - assert setdata_body["plantData"]["mode"] == 2 # plant data echoed back - - -def test_sync_r2_retry_fires_fresh_login() -> None: - """Sync twin of the async retry: one failed read -> fresh login -> retry.""" - api = AristonAPI("user", "pass") - api._r2_login = MagicMock() - api._r2_get_slp_plant_data = MagicMock( - side_effect=[ConnectionException("expired"), {"any": "plant"}] - ) - session = _FakeRequestsSession() - session.queue(_FakeRequestsResponse(json_data={"success": True})) - with patch("ariston.ariston_api.requests.Session", lambda: session): - api.set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) - - assert api._r2_login.call_count == 2 - assert api._r2_get_slp_plant_data.call_count == 2 - - -def test_sync_green_write_routes_through_r2() -> None: - """Device sync setter: GREEN must not hit the api/v2 direct route.""" - device = _device() - device.api.set_nuos_mode_via_r2 = MagicMock() - device.api.set_nuos_mode = MagicMock() - - device.set_water_heater_operation_mode("GREEN") - - device.api.set_nuos_mode_via_r2.assert_called_once_with( - device.gw, NuosSplitOperativeMode.GREEN - ) - device.api.set_nuos_mode.assert_not_called() - assert device.data["opMode"] == 0 - - -def test_sync_comfort_write_keeps_direct_route() -> None: - """Device sync setter: COMFORT keeps the proven api/v2 direct route.""" - device = _device() - device.api.set_nuos_mode_via_r2 = MagicMock() - device.api.set_nuos_mode = MagicMock() - - device.set_water_heater_operation_mode("COMFORT") - - device.api.set_nuos_mode.assert_called_once_with( - device.gw, NuosSplitOperativeMode.COMFORT - ) - device.api.set_nuos_mode_via_r2.assert_not_called() - assert device.data["opMode"] == 1 +class NuosGreenR2Tests(unittest.TestCase): + """GREEN (0) must go through the R2 web-app route, sync and async.""" + + def test_build_nuos_r2_payload_green(self) -> None: + plant = { + "gw": "3C8A1F2EDE84", + "on": True, + "mode": 2, + "waterTemp": 49.0, + "comfortTemp": 54.0, + "reducedTemp": 16.0, + "procReqTemp": 54.0, + "opMode": 1, + "holidayUntil": None, + "boostOn": False, + "hpState": 2, + } + payload = AristonAPI._build_nuos_r2_payload( + plant, NuosSplitOperativeMode.GREEN.value + ) + + self.assertEqual(payload["viewModel"]["opMode"], 0) # the value that changes + self.assertEqual(payload["viewModel"]["plantMode"], 2) + self.assertEqual(payload["viewModel"]["comfortTemp"], 54.0) + self.assertEqual(payload["plantData"]["gatewayId"], "3C8A1F2EDE84") + self.assertEqual( + payload["plantData"]["__type__"], + ["my.entities.entityiface", "my.entities.slpplantdata"], + ) + + def test_enum_values_match_official_range(self) -> None: + self.assertEqual(NuosSplitOperativeMode.GREEN.value, 0) + self.assertEqual(NuosSplitOperativeMode.COMFORT.value, 1) + self.assertEqual(NuosSplitOperativeMode.FAST.value, 2) + self.assertEqual(NuosSplitOperativeMode.AUTO.value, 3) # was mislabeled + + # -- async device setter routing -- + + def test_green_write_routes_through_r2(self) -> None: + device = _device() + device.api.async_set_nuos_mode_via_r2 = AsyncMock() # type: ignore[method-assign] + device.api.async_set_nuos_mode = AsyncMock() # type: ignore[method-assign] + + asyncio.run(device.async_set_water_heater_operation_mode("GREEN")) + + device.api.async_set_nuos_mode_via_r2.assert_awaited_once_with( + device.gw, NuosSplitOperativeMode.GREEN + ) + device.api.async_set_nuos_mode.assert_not_awaited() + self.assertEqual(device.data["opMode"], 0) + + def test_comfort_write_keeps_direct_route(self) -> None: + device = _device() + device.api.async_set_nuos_mode_via_r2 = AsyncMock() # type: ignore[method-assign] + device.api.async_set_nuos_mode = AsyncMock() # type: ignore[method-assign] + + asyncio.run(device.async_set_water_heater_operation_mode("COMFORT")) + + device.api.async_set_nuos_mode.assert_awaited_once_with( + device.gw, NuosSplitOperativeMode.COMFORT + ) + device.api.async_set_nuos_mode_via_r2.assert_not_awaited() + self.assertEqual(device.data["opMode"], 1) + + # -- async API R2 flow -- + + def test_r2_read_surfaces_connection_exception_on_bad_body(self) -> None: + """Expired R2 session: GetData answers 200 with a non-plantData body. + + The read+parse must surface ConnectionException so the caller's + fresh-login retry fires (regression guard for the silent-drop bug). + """ + for json_err in (KeyError("plantData"), ValueError("bad json")): + with self.subTest(json_err=type(json_err).__name__): + api = AristonAPI("user", "pass") + fake = _FakeSession(_FakeResponse(200, json_err=json_err)) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + with self.assertRaisesRegex( + ConnectionException, "session expired" + ): + asyncio.run(api._async_r2_get_slp_plant_data("GW")) + + def test_r2_retry_fires_fresh_login_after_failed_read(self) -> None: + """One failed read -> fresh login -> retry read -> SetData POST.""" + api = AristonAPI("user", "pass") + api._async_r2_login = AsyncMock() + api._async_r2_get_slp_plant_data = AsyncMock( + side_effect=[ConnectionException("expired"), {"any": "plant"}] + ) + api._build_nuos_r2_payload = MagicMock(return_value={}) + fake = _FakeSession(_FakeResponse(200)) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + asyncio.run( + api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + ) + self.assertEqual(api._async_r2_login.await_count, 2) + self.assertEqual(api._async_r2_get_slp_plant_data.await_count, 2) + + def test_r2_setdata_success_false_raises(self) -> None: + """A 200 body with success:false is a failed write, not a success.""" + api = AristonAPI("user", "pass") + api._async_r2_login = AsyncMock() + api._async_r2_get_slp_plant_data = AsyncMock(return_value={"any": "plant"}) + fake = _FakeSession(_FakeResponse(200, json_data={"success": False})) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + with self.assertRaisesRegex(ConnectionException, "reported failure"): + asyncio.run( + api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + ) + + def test_r2_setdata_non_json_body_raises(self) -> None: + """An expired session turns the POST into a 200 login page.""" + api = AristonAPI("user", "pass") + api._async_r2_login = AsyncMock() + api._async_r2_get_slp_plant_data = AsyncMock(return_value={"any": "plant"}) + err = aiohttp.ContentTypeError(MagicMock(), ()) + fake = _FakeSession(_FakeResponse(200, json_err=err)) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + with self.assertRaisesRegex(ConnectionException, "non-JSON body"): + asyncio.run( + api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + ) + + # -- sync twin (requests) -- + + def test_sync_green_write_full_r2_flow(self) -> None: + """Sync GREEN: login -> read -> write, opMode 0 in the SetData envelope.""" + api = AristonAPI("user", "pass") + session = _FakeRequestsSession() + session.queue( + _FakeRequestsResponse(200, text=_LOGIN_HTML), + _FakeRequestsResponse(302), + _FakeRequestsResponse( + json_data={"data": {"plantData": {"mode": 2, "on": True}}} + ), + _FakeRequestsResponse(json_data={"success": True}), + ) + with patch("ariston.ariston_api.requests.Session", lambda: session): + api.set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + + self.assertEqual(len(session.posts), 2) + login_form = session.posts[0]["data"] + self.assertEqual(login_form["__RequestVerificationToken"], "TOKEN123") + setdata_body = session.posts[1]["json"] + self.assertEqual(setdata_body["viewModel"]["opMode"], 0) + self.assertEqual(setdata_body["plantData"]["mode"], 2) # echoed back + + def test_sync_r2_retry_fires_fresh_login(self) -> None: + """Sync twin of the async retry: one failed read -> fresh login -> retry.""" + api = AristonAPI("user", "pass") + api._r2_login = MagicMock() + api._r2_get_slp_plant_data = MagicMock( + side_effect=[ConnectionException("expired"), {"any": "plant"}] + ) + session = _FakeRequestsSession() + session.queue(_FakeRequestsResponse(json_data={"success": True})) + with patch("ariston.ariston_api.requests.Session", lambda: session): + api.set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + + self.assertEqual(api._r2_login.call_count, 2) + self.assertEqual(api._r2_get_slp_plant_data.call_count, 2) + + def test_sync_green_write_routes_through_r2(self) -> None: + """Device sync setter: GREEN must not hit the api/v2 direct route.""" + device = _device() + device.api.set_nuos_mode_via_r2 = MagicMock() + device.api.set_nuos_mode = MagicMock() + + device.set_water_heater_operation_mode("GREEN") + + device.api.set_nuos_mode_via_r2.assert_called_once_with( + device.gw, NuosSplitOperativeMode.GREEN + ) + device.api.set_nuos_mode.assert_not_called() + self.assertEqual(device.data["opMode"], 0) + + def test_sync_comfort_write_keeps_direct_route(self) -> None: + """Device sync setter: COMFORT keeps the proven api/v2 direct route.""" + device = _device() + device.api.set_nuos_mode_via_r2 = MagicMock() + device.api.set_nuos_mode = MagicMock() + + device.set_water_heater_operation_mode("COMFORT") + + device.api.set_nuos_mode.assert_called_once_with( + device.gw, NuosSplitOperativeMode.COMFORT + ) + device.api.set_nuos_mode_via_r2.assert_not_called() + self.assertEqual(device.data["opMode"], 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 5a242cc..951952e 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -2,11 +2,10 @@ import asyncio import time +import unittest from typing import Any, Optional from unittest.mock import MagicMock, patch -import pytest - from ariston.ariston_api import ( AristonAPI, ConnectionException, @@ -18,22 +17,6 @@ def _api() -> AristonAPI: return AristonAPI("user", "pass") -# --------------------------------------------------------------------------- -# parse helper -# --------------------------------------------------------------------------- - - -def test_parse_block_seconds(): - assert _parse_block_seconds(b"Requests are blocked for 66 seconds") == 66 - assert _parse_block_seconds(b"Requests are blocked for 5 seconds") == 5 - assert _parse_block_seconds(b"Too many requests") is None - - -# --------------------------------------------------------------------------- -# sync path (requests) -# --------------------------------------------------------------------------- - - def _sync_response(status: int, content: bytes = b"", json_data: Any = None): response = MagicMock() response.ok = status < 400 @@ -44,92 +27,6 @@ def _sync_response(status: int, content: bytes = b"", json_data: Any = None): return response -def test_429_parses_wait_seconds(): - responses = [ - _sync_response(429, b"Requests are blocked for 66 seconds"), - _sync_response(200, b"{}", {"ok": True}), - ] - http = MagicMock(side_effect=responses) - sleeps: list[int] = [] - api = _api() - with patch("ariston.ariston_api.requests.request", http), patch( - "ariston.ariston_api.time.sleep", side_effect=sleeps.append - ): - result = api._get("https://example/api") - - assert result == {"ok": True} - assert http.call_count == 2 # exactly one retry - assert sleeps == [67] # parsed 66 + 1s margin - assert api._blocked_until > 0 # block window was set - - -def test_429_without_parsable_body(): - responses = [ - _sync_response(429, b"Too many requests"), - _sync_response(200, b"{}", {"ok": True}), - ] - http = MagicMock(side_effect=responses) - sleeps: list[int] = [] - with patch("ariston.ariston_api.requests.request", http), patch( - "ariston.ariston_api.time.sleep", side_effect=sleeps.append - ): - result = _api()._get("https://example/api") - - assert result == {"ok": True} - assert sleeps == [5] # documented fallback, same as generic error case - assert http.call_count == 2 - - -def test_429_twice_raises(): - body = b"Requests are blocked for 10 seconds" - http = MagicMock( - side_effect=[_sync_response(429, body), _sync_response(429, body)] - ) - api = _api() - with patch("ariston.ariston_api.requests.request", http), patch( - "ariston.ariston_api.time.sleep" - ): - with pytest.raises(ConnectionException): - api._get("https://example/api") - - assert http.call_count == 2 # one retry, then raise — no infinite loop - - -def test_blocked_until_short_circuits(): - api = _api() - api._blocked_until = time.time() + 30 - http = MagicMock() - with patch("ariston.ariston_api.requests.request", http): - with pytest.raises(ConnectionException): - api._get("https://example/api") - - http.assert_not_called() # no network call inside the block window - - -def test_block_window_is_per_instance(): - """A 429 on one instance must not silence other instances.""" - blocked = _api() - other = _api() - http = MagicMock( - side_effect=[ - _sync_response(429, b"Requests are blocked for 30 seconds"), - _sync_response(200, b"{}", {"ok": True}), - ] - ) - with patch("ariston.ariston_api.requests.request", http), patch( - "ariston.ariston_api.time.sleep" - ): - assert blocked._get("https://example/api") == {"ok": True} - - assert blocked._blocked_until > 0 - assert other._blocked_until == 0.0 # untouched by the other instance's 429 - - -# --------------------------------------------------------------------------- -# async path (aiohttp) -# --------------------------------------------------------------------------- - - class _FakeAiohttpContent: def __init__(self, payload: bytes) -> None: self._payload = payload @@ -170,66 +67,160 @@ async def request(self, *args: Any, **kwargs: Any): return _Session -def test_async_429_parses_and_retries(): - responses = [ - _FakeAiohttpResponse(429, b"Requests are blocked for 66 seconds"), - _FakeAiohttpResponse(200, b"{}", {"ok": True}), - ] - calls: list[int] = [] - sleeps: list[Optional[int]] = [] - - async def run() -> Any: - with patch( - "ariston.ariston_api.aiohttp.ClientSession", - _fake_session_cls(responses, calls), - ), patch( - "ariston.ariston_api.asyncio.sleep", side_effect=sleeps.append - ): - return await _api()._async_get("https://example/api") +class RateLimitTests(unittest.TestCase): + """429 handling: parse, sleep-out with a single retry, per-instance window.""" - result = asyncio.run(run()) + # -- parse helper -- - assert result == {"ok": True} - assert len(calls) == 2 # exactly one retry - assert sleeps == [67] # parsed 66 + 1s margin + def test_parse_block_seconds(self): + self.assertEqual( + _parse_block_seconds(b"Requests are blocked for 66 seconds"), 66 + ) + self.assertEqual(_parse_block_seconds(b"Requests are blocked for 5 seconds"), 5) + self.assertIsNone(_parse_block_seconds(b"Too many requests")) + # -- sync path (requests) -- -def test_async_blocked_until_short_circuits(): - calls: list[int] = [] - api = _api() - api._blocked_until = time.time() + 30 + def test_429_parses_wait_seconds(self): + responses = [ + _sync_response(429, b"Requests are blocked for 66 seconds"), + _sync_response(200, b"{}", {"ok": True}), + ] + http = MagicMock(side_effect=responses) + sleeps: list[int] = [] + api = _api() + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep", side_effect=sleeps.append + ): + result = api._get("https://example/api") + + self.assertEqual(result, {"ok": True}) + self.assertEqual(http.call_count, 2) # exactly one retry + self.assertEqual(sleeps, [67]) # parsed 66 + 1s margin + self.assertGreater(api._blocked_until, 0) # block window was set - async def run() -> None: - with patch( - "ariston.ariston_api.aiohttp.ClientSession", - _fake_session_cls([], calls), + def test_429_without_parsable_body(self): + responses = [ + _sync_response(429, b"Too many requests"), + _sync_response(200, b"{}", {"ok": True}), + ] + http = MagicMock(side_effect=responses) + sleeps: list[int] = [] + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep", side_effect=sleeps.append + ): + result = _api()._get("https://example/api") + + self.assertEqual(result, {"ok": True}) + self.assertEqual(sleeps, [5]) # documented fallback + self.assertEqual(http.call_count, 2) + + def test_429_twice_raises(self): + body = b"Requests are blocked for 10 seconds" + http = MagicMock( + side_effect=[_sync_response(429, body), _sync_response(429, body)] + ) + api = _api() + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep" + ): + with self.assertRaises(ConnectionException): + api._get("https://example/api") + + self.assertEqual(http.call_count, 2) # one retry, then raise + + def test_blocked_until_short_circuits(self): + api = _api() + api._blocked_until = time.time() + 30 + http = MagicMock() + with patch("ariston.ariston_api.requests.request", http): + with self.assertRaises(ConnectionException): + api._get("https://example/api") + + http.assert_not_called() # no network call inside the block window + + def test_block_window_is_per_instance(self): + """A 429 on one instance must not silence other instances.""" + blocked = _api() + other = _api() + http = MagicMock( + side_effect=[ + _sync_response(429, b"Requests are blocked for 30 seconds"), + _sync_response(200, b"{}", {"ok": True}), + ] + ) + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep" ): - with pytest.raises(ConnectionException): - await api._async_get("https://example/api") + self.assertEqual(blocked._get("https://example/api"), {"ok": True}) - asyncio.run(run()) + self.assertGreater(blocked._blocked_until, 0) + self.assertEqual(other._blocked_until, 0.0) # untouched by the 429 - assert calls == [] # no network call inside the block window + # -- async path (aiohttp) -- + + def test_async_429_parses_and_retries(self): + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked for 66 seconds"), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ] + calls: list[int] = [] + sleeps: list[Optional[int]] = [] + + async def run() -> Any: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ), patch( + "ariston.ariston_api.asyncio.sleep", side_effect=sleeps.append + ): + return await _api()._async_get("https://example/api") + + result = asyncio.run(run()) + + self.assertEqual(result, {"ok": True}) + self.assertEqual(len(calls), 2) # exactly one retry + self.assertEqual(sleeps, [67]) # parsed 66 + 1s margin + + def test_async_blocked_until_short_circuits(self): + calls: list[int] = [] + api = _api() + api._blocked_until = time.time() + 30 + + async def run() -> None: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls([], calls), + ): + with self.assertRaises(ConnectionException): + await api._async_get("https://example/api") + + asyncio.run(run()) + + self.assertEqual(calls, []) # no network call inside the block window + + def test_async_block_window_is_per_instance(self): + """Async twin: a 429 on one instance must not silence other instances.""" + blocked = _api() + other = _api() + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked for 30 seconds"), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ] + calls: list[int] = [] + async def run() -> Any: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ), patch("ariston.ariston_api.asyncio.sleep"): + return await blocked._async_get("https://example/api") -def test_async_block_window_is_per_instance(): - """Async twin: a 429 on one instance must not silence other instances.""" - blocked = _api() - other = _api() - responses = [ - _FakeAiohttpResponse(429, b"Requests are blocked for 30 seconds"), - _FakeAiohttpResponse(200, b"{}", {"ok": True}), - ] - calls: list[int] = [] + self.assertEqual(asyncio.run(run()), {"ok": True}) - async def run() -> Any: - with patch( - "ariston.ariston_api.aiohttp.ClientSession", - _fake_session_cls(responses, calls), - ), patch("ariston.ariston_api.asyncio.sleep"): - return await blocked._async_get("https://example/api") + self.assertGreater(blocked._blocked_until, 0) + self.assertEqual(other._blocked_until, 0.0) # untouched by the 429 - assert asyncio.run(run()) == {"ok": True} - assert blocked._blocked_until > 0 - assert other._blocked_until == 0.0 # untouched by the other instance's 429 +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_velis_holiday.py b/tests/test_velis_holiday.py index 940fbaa..f0aadb8 100644 --- a/tests/test_velis_holiday.py +++ b/tests/test_velis_holiday.py @@ -1,8 +1,10 @@ """Unit tests for the Velis holiday write (endpoint proven by live write-test).""" import asyncio +import unittest from datetime import date from typing import Any +from unittest.mock import patch from ariston.ariston_api import AristonAPI from ariston.const import ARISTON_API_URL, ARISTON_VELIS @@ -52,38 +54,40 @@ def _device() -> AristonVelisDevice: return device -def test_holiday_end_date_format(): - assert ( - AristonVelisDevice._create_holiday_end_date(date(2026, 9, 15)) - == "2026-09-15T00:00:00" - ) - assert AristonVelisDevice._create_holiday_end_date(None) is None +class VelisHolidayTests(unittest.TestCase): + """Device wrapper delegates to the API holiday pair with date formatting.""" + def test_holiday_end_date_format(self): + self.assertEqual( + AristonVelisDevice._create_holiday_end_date(date(2026, 9, 15)), + "2026-09-15T00:00:00", + ) + self.assertIsNone(AristonVelisDevice._create_holiday_end_date(None)) -def test_async_set_velis_holiday_on_posts_date(): - posts: list = [] - device = _device() - with patch_session(_fake_session_cls(posts)): - asyncio.run(device.async_set_velis_holiday(date(2026, 9, 15))) + def test_async_set_velis_holiday_on_posts_date(self): + posts: list = [] + device = _device() + with patch( + "ariston.ariston_api.aiohttp.ClientSession", _fake_session_cls(posts) + ): + asyncio.run(device.async_set_velis_holiday(date(2026, 9, 15))) - assert len(posts) == 1 - assert posts[0]["path"] == EXPECTED_URL - assert posts[0]["json"] == {"new": "2026-09-15T00:00:00"} + self.assertEqual(len(posts), 1) + self.assertEqual(posts[0]["path"], EXPECTED_URL) + self.assertEqual(posts[0]["json"], {"new": "2026-09-15T00:00:00"}) + def test_async_set_velis_holiday_off_posts_null(self): + posts: list = [] + device = _device() + with patch( + "ariston.ariston_api.aiohttp.ClientSession", _fake_session_cls(posts) + ): + asyncio.run(device.async_set_velis_holiday(None)) -def test_async_set_velis_holiday_off_posts_null(): - posts: list = [] - device = _device() - with patch_session(_fake_session_cls(posts)): - asyncio.run(device.async_set_velis_holiday(None)) + self.assertEqual(len(posts), 1) + self.assertEqual(posts[0]["path"], EXPECTED_URL) + self.assertEqual(posts[0]["json"], {"new": None}) - assert len(posts) == 1 - assert posts[0]["path"] == EXPECTED_URL - assert posts[0]["json"] == {"new": None} - -def patch_session(fake_cls): - """Patch aiohttp.ClientSession inside ariston_api for one test.""" - from unittest.mock import patch - - return patch("ariston.ariston_api.aiohttp.ClientSession", fake_cls) +if __name__ == "__main__": + unittest.main() From 9ab0a1a1b6e583cbdb4d6e2ca2df9e3a9f6ac135 Mon Sep 17 00:00:00 2001 From: flupkede Date: Sat, 14 Nov 2026 19:40:33 +0000 Subject: [PATCH 10/10] [fix] keep IMEMORY as a deprecated alias of AUTO (public API compat) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Renaming the mislabeled IMEMORY=3 to AUTO removed an existing public enum member: callers using NuosSplitOperativeMode.IMEMORY or passing "IMEMORY" to the string-based setter would break. AUTO stays the canonical name; IMEMORY is retained as an enum alias (same value 3), so attribute access and NuosSplitOperativeMode["IMEMORY"] keep working. Iteration and the mode options only expose AUTO — no duplicate value in water_heater_mode_options. The @unique decorator was dropped for this enum only (an alias is a duplicate value by definition); all other enums keep it. Tests: alias identity, string lookup, no duplicate option value, and the device setter accepting "IMEMORY". Suite: 84 tests + 152 subtests green under both unittest (CI, coverage 99%) and pytest. --- ariston/const.py | 7 +++++-- tests/test_nuos_green_r2.py | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/ariston/const.py b/ariston/const.py index a64de63..d927305 100644 --- a/ariston/const.py +++ b/ariston/const.py @@ -240,19 +240,22 @@ class NuosSplitPlantMode(Enum): PROGRAM = 2 -@unique class NuosSplitOperativeMode(WaterHeaterMode): """NuosSplit operative mode enum. Official range (web app, 2026-10-18): Green=0, Comfort=1, Fast=2, Auto=3, HcHp=4, Electric=5, GreenPlus=6. Only the modes the device - reliably accepts are exposed; IMEMORY was a mislabel of Auto=3. + reliably accepts are exposed; value 3 was mislabeled IMEMORY before. + IMEMORY is kept as a deprecated alias of AUTO so existing callers + (attribute access and the string-based device setter) keep working; + iteration and the mode options stay on the canonical AUTO name. """ GREEN = 0 COMFORT = 1 FAST = 2 AUTO = 3 + IMEMORY = 3 # deprecated alias of AUTO (pre-rename public name) GREEN_PLUS = 6 diff --git a/tests/test_nuos_green_r2.py b/tests/test_nuos_green_r2.py index ad52096..5f0829a 100644 --- a/tests/test_nuos_green_r2.py +++ b/tests/test_nuos_green_r2.py @@ -152,6 +152,26 @@ def test_enum_values_match_official_range(self) -> None: self.assertEqual(NuosSplitOperativeMode.FAST.value, 2) self.assertEqual(NuosSplitOperativeMode.AUTO.value, 3) # was mislabeled + def test_imemory_alias_preserved(self) -> None: + """IMEMORY (the pre-rename public name) still resolves to AUTO = 3.""" + self.assertIs(NuosSplitOperativeMode.IMEMORY, NuosSplitOperativeMode.AUTO) + self.assertEqual(NuosSplitOperativeMode["IMEMORY"].value, 3) + values = [mode.value for mode in NuosSplitOperativeMode] + self.assertEqual(values.count(3), 1) # alias adds no duplicate option + self.assertNotIn("IMEMORY", [mode.name for mode in NuosSplitOperativeMode]) + + def test_imemory_string_still_sets_auto(self) -> None: + """The string-based setter accepts the old name and writes value 3.""" + device = _device() + device.api.set_nuos_mode = MagicMock() + + device.set_water_heater_operation_mode("IMEMORY") + + device.api.set_nuos_mode.assert_called_once_with( + device.gw, NuosSplitOperativeMode.AUTO + ) + self.assertEqual(device.data["opMode"], 3) + # -- async device setter routing -- def test_green_write_routes_through_r2(self) -> None: