diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 8d4b37b..30f1fce 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -38,11 +38,11 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v7 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v4 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@v2 + uses: github/codeql-action/autobuild@v4 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -69,6 +69,6 @@ jobs: # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v4 with: category: "/language:${{matrix.language}}" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..a9ee0e3 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,27 @@ +name: Tests + +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: "3.11" + - name: Install locked dependencies + env: + PIP_CONFIG_FILE: "${{ github.workspace }}/pip.conf" + run: python -m pip install --require-hashes -r requirements.txt + - name: Run unit tests + run: python -m coverage run --source=ariston -m unittest discover --start-directory tests --verbose + - name: Report coverage + run: python -m coverage report --show-missing --fail-under=90 diff --git a/README.md b/README.md index baeb66d..37c3cd8 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,12 @@ Use pip3 to install the latest version of this module. pip3 install ariston ``` +## Tests +Run the unit test suite with Python 3.11 or newer: +``` +python -m unittest discover --start-directory tests --verbose +``` + ## The easy way (recommended for testing the module) First, open Python 3 and import ariston module. ``` diff --git a/ariston/lux_device.py b/ariston/lux_device.py index 43da5c2..1113194 100644 --- a/ariston/lux_device.py +++ b/ariston/lux_device.py @@ -36,7 +36,7 @@ async def async_set_water_heater_operation_mode(self, operation_mode: str): @property def water_heater_target_temperature(self) -> Optional[float]: """Get water heater target temperature""" - if self.data.get(EvoDeviceProperties.MODE) == LuxPlantMode.BOOST: + if self.data.get(EvoDeviceProperties.MODE) == LuxPlantMode.BOOST.value: return self.water_heater_maximum_setpoint_temperature_maximum else: return self.data.get(EvoLydosDeviceProperties.REQ_TEMP, None) diff --git a/pip.conf b/pip.conf new file mode 100644 index 0000000..2ac45a0 --- /dev/null +++ b/pip.conf @@ -0,0 +1,2 @@ +[global] +only-binary = :all: diff --git a/pyproject.toml b/pyproject.toml index d8ebd4f..2965fd5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ dependencies = [ "aiohttp", "requests" ] -requires-python = ">=3.9" +requires-python = ">=3.11" license = { file = "LICENSE" } version = "0.19.9" dynamic = ['description'] diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..78ff722 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,33 @@ +# Hash-locked Linux x86_64 dependencies for the Python 3.11 CI runner. +aiohappyeyeballs==2.7.1 \ + --hash=sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472 +aiohttp==3.14.5 \ + --hash=sha256:50a195903119008fe9cc68710535eb37f556ffffd6a7759afe70a2c145587045 +aiosignal==1.4.0 \ + --hash=sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e +attrs==26.1.0 \ + --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 +certifi==2026.10.19 \ + --hash=sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b +coverage==7.17.2 \ + --hash=sha256:01303d9e68b6e6bdc5459b54e3bd0e3539c94c25b50ac7362b7cbcacbc815fbc +charset-normalizer==3.5.2 \ + --hash=sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f +flit_core==3.12.0 \ + --hash=sha256:e7a0304069ea895172e3c7bb703292e992c5d1555dd1233ab7b5621b5b69e62c +frozenlist==1.8.0 \ + --hash=sha256:2552f44204b744fba866e573be4c1f9048d6a324dfe14475103fd51613eb1d1f +idna==3.20 \ + --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c +multidict==7.2.1 \ + --hash=sha256:3b7542fad2706595c1b1853b46f2c3c4ae5cc5a6252b7225f294d607a29e1bdf +propcache==0.5.4 \ + --hash=sha256:6e9368e87a3efc285e559131092c5db643eb8e56de4ee42064d5baec22ef2bb5 +requests==2.34.2 \ + --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 +typing_extensions==4.16.0 \ + --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 +urllib3==2.8.0 \ + --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 +yarl==1.25.1 \ + --hash=sha256:d5add7b4ca7afeea91d52e4d4e4db3b1fe9885b71f07054560d8c4296b7441a2 diff --git a/tests/test_ariston_api.py b/tests/test_ariston_api.py new file mode 100644 index 0000000..c603d0f --- /dev/null +++ b/tests/test_ariston_api.py @@ -0,0 +1,473 @@ +"""Tests for authenticated cloud API requests.""" + +import asyncio +import unittest +from unittest.mock import AsyncMock, patch + +from ariston.ariston_api import AristonAPI, ConnectionException +from ariston.const import ( + BsbOperativeMode, + BsbZoneMode, + DeviceFeatures, + EvoPlantMode, + LydosPlantMode, + NuosSplitOperativeMode, + PlantData, + ZoneAttribute, +) + + +class FakeResponse: + def __init__(self, payload=None, status_code=200, content=None): + self.status_code = status_code + self.ok = 200 <= status_code < 400 + self._payload = payload + self.content = content if content is not None else ( + b"response" if payload is not None else b"" + ) + + def json(self): + return self._payload + + +class FakeAsyncResponse(FakeResponse): + def __init__(self, payload=None, status_code=200, content=None): + super().__init__(payload, status_code, content) + self.status = status_code + self.content_length = len(self.content) + + async def json(self): + return self._payload + + +class FakeAsyncSession: + def __init__(self, response): + self.response = response + self.calls = [] + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_value, traceback): + return None + + async def request(self, *args, **kwargs): + self.calls.append((args, kwargs)) + return self.response + + +class FakeAsyncContent: + def __init__(self, payload): + self.payload = payload + + async def read(self): + return self.payload + + +class FakeAsyncRateLimitedResponse(FakeAsyncResponse): + def __init__(self): + super().__init__(status_code=429, content=b"rate limited") + self.content = FakeAsyncContent(b"rate limited") + + +class AristonAPIRequestTests(unittest.TestCase): + def test_login_token_is_sent_with_followup_request(self): + api = AristonAPI( + "user@example.com", + "password", + api_url="https://example.test/api/", + user_agent="test-agent", + ) + responses = [ + FakeResponse({"token": "session-token"}), + FakeResponse([{"gw": "gateway-1"}]), + ] + + with patch( + "ariston.ariston_api.requests.request", side_effect=responses + ) as request: + self.assertTrue(api.connect()) + devices = api.get_detailed_devices() + + self.assertEqual(devices, [{"gw": "gateway-1"}]) + login_call, devices_call = request.call_args_list + self.assertEqual(login_call.args[0], "POST") + self.assertEqual( + login_call.kwargs["json"], + {"usr": "user@example.com", "pwd": "password"}, + ) + self.assertEqual(login_call.kwargs["headers"]["User-Agent"], "test-agent") + self.assertEqual(login_call.kwargs["headers"]["ar.authToken"], "") + self.assertEqual(devices_call.args[0], "GET") + self.assertEqual( + devices_call.args[1], "https://example.test/api/remote/plants" + ) + self.assertEqual(devices_call.kwargs["headers"]["ar.authToken"], "session-token") + + def test_async_login_token_is_sent_with_followup_request(self): + api = AristonAPI( + "user@example.com", + "password", + api_url="https://example.test/api/", + user_agent="test-agent", + ) + login_session = FakeAsyncSession( + FakeAsyncResponse({"token": "async-session-token"}) + ) + devices_session = FakeAsyncSession(FakeAsyncResponse([{"gw": "gateway-1"}])) + + async def connect_and_discover(): + self.assertTrue(await api.async_connect()) + return await api.async_get_detailed_devices() + + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + side_effect=[login_session, devices_session], + ): + devices = asyncio.run(connect_and_discover()) + + self.assertEqual(devices, [{"gw": "gateway-1"}]) + self.assertEqual( + login_session.calls[0][0], + ("POST", "https://example.test/api/accounts/login"), + ) + self.assertEqual( + login_session.calls[0][1]["json"], + {"usr": "user@example.com", "pwd": "password"}, + ) + self.assertEqual( + devices_session.calls[0][0], + ("GET", "https://example.test/api/remote/plants"), + ) + self.assertEqual( + devices_session.calls[0][1]["headers"]["ar.authToken"], + "async-session-token", + ) + + def test_not_found_device_endpoint_returns_empty_list(self): + api = AristonAPI("user", "password") + + with patch( + "ariston.ariston_api.requests.request", + return_value=FakeResponse(status_code=404), + ): + self.assertEqual(api.get_detailed_devices(), []) + + def test_expired_token_is_refreshed_and_request_retried(self): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + responses = [ + FakeResponse(status_code=405), + FakeResponse({"token": "refreshed-token"}), + FakeResponse([{"gw": "gateway-1"}]), + ] + + with patch( + "ariston.ariston_api.requests.request", side_effect=responses + ) as request: + devices = api.get_detailed_devices() + + self.assertEqual(devices, [{"gw": "gateway-1"}]) + self.assertEqual(request.call_count, 3) + self.assertEqual( + request.call_args_list[-1].kwargs["headers"]["ar.authToken"], + "refreshed-token", + ) + + def test_rate_limit_is_reported_as_connection_exception(self): + api = AristonAPI("user", "password") + + with patch( + "ariston.ariston_api.requests.request", + return_value=FakeResponse(status_code=429, content=b"rate limited"), + ): + with self.assertRaises(ConnectionException) as error: + api.get_detailed_devices() + + self.assertEqual(error.exception.args, (429, "rate limited")) + + def test_sync_read_endpoints_return_payloads_and_empty_defaults(self): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + features = {DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]} + endpoints = ( + ("get_detailed_devices", (), "_get", "/remote/plants", [], []), + ("get_detailed_velis_devices", (), "_get", "/velis/plants", [], []), + ("get_devices", (), "_get", "/remote/plants/lite", [], []), + ("get_features_for_device", ("gw-1",), "_get", "/gw-1/features", {}, {}), + ("get_energy_account", ("gw-1",), "_get", "/energyAccount", {}, {}), + ("get_consumptions_sequences", ("gw-1", "Dhw"), "_get", "/consSequencesApi8?usages=Dhw", [], []), + ("get_consumptions_settings", ("gw-1",), "_post", "/getConsumptionsSettings", {}, {}), + ("get_properties", ("gw-1", features, "en", "metric"), "_post", "/get?umsys=metric", {}, {}), + ("get_bsb_plant_data", ("gw-1",), "_get", "/gw-1", {}, {}), + ("get_velis_plant_data", (PlantData.Med, "gw-1"), "_get", "/gw-1", {}, {}), + ("get_velis_plant_settings", (PlantData.Med, "gw-1"), "_get", "/plantSettings", {}, {}), + ("get_menu_items", ("gw-1",), "_get", "/gw-1?menuItems=", [], []), + ("get_thermostat_time_progs", ("gw-1", 2, "metric"), "_get", "/ChZn2?umsys=metric", {}, {}), + ("get_bus_errors", ("gw-1",), "_get", "gatewayId=gw-1", [], []), + ) + payload = [{"sample": "value"}] + + for name, args, transport, path_part, nonempty_default, empty_default in endpoints: + with self.subTest(endpoint=name, response="payload"): + response = payload if isinstance(nonempty_default, list) else payload[0] + with patch.object(api, transport, return_value=response) as request: + result = getattr(api, name)(*args) + self.assertEqual(result, response) + self.assertIn(path_part, request.call_args.args[0]) + with self.subTest(endpoint=name, response="empty"): + with patch.object(api, transport, return_value=None) as request: + result = getattr(api, name)(*args) + self.assertEqual(result, empty_default) + self.assertIn(path_part, request.call_args.args[0]) + + items = api.get_items(features) + self.assertTrue(any(item["id"].startswith("Zone") for item in items)) + + def test_sync_write_endpoints_send_values_to_transport(self): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + writes = ( + ("set_consumptions_settings", ("gw-1", {"elecCost": 0.2})), + ("set_property", ("gw-1", 2, {"x": True}, "ZoneDesiredTemp", 20, 19, "metric")), + ("set_evo_number_of_showers", ("gw-1", 2)), + ("set_evo_mode", ("gw-1", EvoPlantMode.MANUAL)), + ("set_lydos_mode", ("gw-1", LydosPlantMode.GREEN)), + ("set_nuos_mode", ("gw-1", NuosSplitOperativeMode.FAST)), + ("set_bsb_mode", ("gw-1", BsbOperativeMode.ON)), + ("set_bsb_zone_mode", ("gw-1", 2, BsbZoneMode.MANUAL, BsbZoneMode.OFF, False)), + ("set_evo_temperature", ("gw-1", 55)), + ("set_lydos_temperature", ("gw-1", 54)), + ("set_nuos_temperature", ("gw-1", 55, 40, 50, 35)), + ("set_bsb_temperature", ("gw-1", 55, 40, 50, 35)), + ("set_bsb_zone_temperature", ("gw-1", 2, 22, 18, 21, 17, False)), + ("set_nous_boost", ("gw-1", True)), + ("set_evo_eco_mode", ("gw-1", True)), + ("set_lux_power_option", ("gw-1", False)), + ("set_velis_power", (PlantData.Med, "gw-1", True)), + ("set_velis_plant_setting", (PlantData.Med, "gw-1", "setting", 2, 1)), + ("set_holiday", ("gw-1", "2026-12-31")), + ) + for name, args in writes: + with self.subTest(endpoint=name): + with patch.object(api, "_post") as post: + result = getattr(api, name)(*args) + self.assertIsNone(result) + post.assert_called_once() + self.assertIn("gw-1", post.call_args.args[0]) + + def test_sync_request_empty_response_and_retry_failure_paths(self): + api = AristonAPI("user", "password") + request = api._AristonAPI__request + + with patch("ariston.ariston_api.requests.request", return_value=FakeResponse()): + self.assertIsNone(request("GET", "https://example.test/empty")) + + with patch("ariston.ariston_api.time.sleep") as sleep, patch( + "ariston.ariston_api.requests.request", + side_effect=[FakeResponse(status_code=500), FakeResponse({"ok": True})], + ) as send: + self.assertEqual(request("GET", "https://example.test/retry"), {"ok": True}) + sleep.assert_called_once_with(5) + self.assertEqual(send.call_count, 2) + + with patch( + "ariston.ariston_api.requests.request", + return_value=FakeResponse(status_code=503), + ): + with self.assertRaises(ConnectionException) as error: + request("GET", "https://example.test/retry-fails", is_retry=True) + self.assertEqual(error.exception.args, (503,)) + + with patch.object(api, "connect", return_value=False), patch( + "ariston.ariston_api.requests.request", + return_value=FakeResponse(status_code=405), + ): + with self.assertRaisesRegex(ConnectionException, "Login failed"): + request("GET", "https://example.test/login-retry") + + with patch( + "ariston.ariston_api.requests.request", + return_value=FakeResponse(status_code=405), + ): + with self.assertRaisesRegex(ConnectionException, "Invalid token"): + request("GET", "https://example.test/invalid-token", is_retry=True) + + def test_sync_connect_returns_false_and_wraps_transport_errors(self): + api = AristonAPI("user", "password") + with patch.object(api, "_post", return_value=None): + self.assertFalse(api.connect()) + with patch.object(api, "_post", side_effect=RuntimeError("offline")): + with self.assertRaises(ConnectionException) as error: + api.connect() + self.assertIsInstance(error.exception.__cause__, RuntimeError) + + def test_async_connect_returns_false_and_wraps_transport_errors(self): + api = AristonAPI("user", "password") + + async def exercise(): + with patch.object(api, "_async_post", new=AsyncMock(return_value=None)): + self.assertFalse(await api.async_connect()) + with patch.object(api, "_async_post", new=AsyncMock(side_effect=RuntimeError("offline"))): + with self.assertRaises(ConnectionException) as error: + await api.async_connect() + self.assertIsInstance(error.exception.__cause__, RuntimeError) + + asyncio.run(exercise()) + + def test_async_read_endpoints_return_payloads_and_empty_defaults(self): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + features = {DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]} + endpoints = ( + ("async_get_detailed_devices", (), "/remote/plants", [], []), + ("async_get_detailed_velis_devices", (), "/velis/plants", [], []), + ("async_get_devices", (), "/remote/plants/lite", [], []), + ("async_get_features_for_device", ("gw-1",), "/gw-1/features", None, None), + ("async_get_energy_account", ("gw-1",), "/energyAccount", {}, {}), + ("async_get_consumptions_sequences", ("gw-1", "Dhw"), "/consSequencesApi8?usages=Dhw", [], []), + ("async_get_consumptions_settings", ("gw-1",), "/getConsumptionsSettings", {}, {}), + ("async_get_properties", ("gw-1", features, "en", "metric"), "/get?umsys=metric", {}, {}), + ("async_get_bsb_plant_data", ("gw-1",), "/gw-1", {}, {}), + ("async_get_velis_plant_data", (PlantData.Med, "gw-1"), "/gw-1", {}, {}), + ("async_get_velis_plant_settings", (PlantData.Med, "gw-1"), "/plantSettings", {}, {}), + ("async_get_menu_items", ("gw-1",), "/gw-1?menuItems=", [], []), + ("async_get_thermostat_time_progs", ("gw-1", 2, "metric"), "/ChZn2?umsys=metric", None, None), + ("async_get_bus_errors", ("gw-1",), "gatewayId=gw-1", [], []), + ) + payload = [{"sample": "value"}] + + async def exercise(name, args, response, empty): + transport = ( + "_async_post" + if name in {"async_get_consumptions_settings", "async_get_properties"} + else "_async_get" + ) + if empty is None: + expected_nonempty = response + elif isinstance(empty, list): + expected_nonempty = response + else: + expected_nonempty = response + for value, expected in ((response, expected_nonempty), (None, empty)): + with patch.object(api, transport, new=AsyncMock(return_value=value)) as request: + result = await getattr(api, name)(*args) + self.assertEqual(result, expected) + self.assertIn(next(path for method, method_args, path, _, _ in endpoints if method == name), request.await_args.args[0]) + + async def run_all(): + for name, args, _, nonempty_default, empty_default in endpoints: + response = ( + {"sample": "value"} + if nonempty_default is None or isinstance(empty_default, dict) + else payload + ) + await exercise(name, args, response, empty_default) + + asyncio.run(run_all()) + + def test_async_write_endpoints_send_values_to_transport(self): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + writes = ( + ("async_set_consumptions_settings", ("gw-1", {"elecCost": 0.2})), + ("async_set_property", ("gw-1", 2, {"x": True}, "ZoneDesiredTemp", 20, 19, "metric")), + ("async_set_evo_number_of_showers", ("gw-1", 2)), + ("async_set_evo_mode", ("gw-1", EvoPlantMode.MANUAL)), + ("async_set_lydos_mode", ("gw-1", LydosPlantMode.GREEN)), + ("async_set_nuos_mode", ("gw-1", NuosSplitOperativeMode.FAST)), + ("async_set_bsb_mode", ("gw-1", BsbOperativeMode.ON)), + ("async_set_bsb_zone_mode", ("gw-1", 2, BsbZoneMode.MANUAL, BsbZoneMode.OFF, False)), + ("async_set_evo_temperature", ("gw-1", 55)), + ("async_set_lydos_temperature", ("gw-1", 54)), + ("async_set_nuos_temperature", ("gw-1", 55, 40, 50, 35)), + ("async_set_bsb_temperature", ("gw-1", 55, 40, 50, 35)), + ("async_set_bsb_zone_temperature", ("gw-1", 2, 22, 18, 21, 17, False)), + ("async_set_nous_boost", ("gw-1", True)), + ("async_set_evo_eco_mode", ("gw-1", True)), + ("async_set_lux_power_option", ("gw-1", False)), + ("async_set_velis_power", (PlantData.Med, "gw-1", True)), + ("async_set_velis_plant_setting", (PlantData.Med, "gw-1", "setting", 2, 1)), + ("async_set_holiday", ("gw-1", "2026-12-31")), + ) + + async def run_all(): + for name, args in writes: + with self.subTest(endpoint=name): + with patch.object(api, "_async_post", new=AsyncMock()) as post: + result = await getattr(api, name)(*args) + self.assertIsNone(result) + post.assert_awaited_once() + self.assertIn("gw-1", post.await_args.args[0]) + + asyncio.run(run_all()) + + def test_async_request_empty_response_and_retry_failure_paths(self): + api = AristonAPI("user", "password") + request = api._AristonAPI__async_request + + async def exercise(): + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + side_effect=[FakeAsyncSession(FakeAsyncResponse())], + ): + self.assertIsNone(await request("GET", "https://example.test/empty")) + + with patch("ariston.ariston_api.asyncio.sleep", new=AsyncMock()) as sleep, patch( + "ariston.ariston_api.aiohttp.ClientSession", + side_effect=[ + FakeAsyncSession(FakeAsyncResponse(status_code=500)), + FakeAsyncSession(FakeAsyncResponse({"ok": True})), + ], + ): + self.assertEqual(await request("GET", "https://example.test/retry"), {"ok": True}) + sleep.assert_awaited_once_with(5) + + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + return_value=FakeAsyncSession(FakeAsyncResponse(status_code=503)), + ): + with self.assertRaises(ConnectionException) as error: + await request("GET", "https://example.test/retry-fails", is_retry=True) + self.assertEqual(error.exception.args, (503,)) + + with patch.object(api, "async_connect", new=AsyncMock(return_value=False)), patch( + "ariston.ariston_api.aiohttp.ClientSession", + return_value=FakeAsyncSession(FakeAsyncResponse(status_code=405)), + ): + with self.assertRaisesRegex(ConnectionException, "Login failed"): + await request("GET", "https://example.test/login-retry") + + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + return_value=FakeAsyncSession(FakeAsyncResponse(status_code=405)), + ): + with self.assertRaisesRegex(ConnectionException, "Invalid token"): + await request("GET", "https://example.test/invalid-token", is_retry=True) + + with patch.object(api, "async_connect", new=AsyncMock(return_value=True)), patch( + "ariston.ariston_api.aiohttp.ClientSession", + side_effect=[ + FakeAsyncSession(FakeAsyncResponse(status_code=405)), + FakeAsyncSession(FakeAsyncResponse({"ok": True})), + ], + ): + self.assertEqual( + await request("GET", "https://example.test/refreshed-token"), + {"ok": True}, + ) + + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + return_value=FakeAsyncSession(FakeAsyncResponse(status_code=404)), + ): + self.assertIsNone(await request("GET", "https://example.test/not-found")) + + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + return_value=FakeAsyncSession(FakeAsyncRateLimitedResponse()), + ): + with self.assertRaises(ConnectionException) as error: + await request("GET", "https://example.test/rate-limited") + self.assertEqual(error.exception.args, (429, b"rate limited")) + + asyncio.run(exercise()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_base_device.py b/tests/test_base_device.py new file mode 100644 index 0000000..0400427 --- /dev/null +++ b/tests/test_base_device.py @@ -0,0 +1,273 @@ +"""Contracts shared by every Ariston device implementation.""" + +import asyncio +import unittest +from datetime import datetime, timedelta, timezone +from unittest.mock import AsyncMock, Mock + +from ariston.base_device import AristonBaseDevice +from ariston.const import ( + ConsumptionTimeInterval, + ConsumptionType, + CustomDeviceFeatures, + DeviceAttribute, + DeviceFeatures, + GalevoDeviceAttribute, + SystemType, + VelisDeviceAttribute, + WheType, +) +from ariston.device import AristonDevice +from ariston.evo_one_device import AristonEvoOneDevice + + +class AristonBaseDeviceTests(unittest.TestCase): + def make_device(self, attributes=None): + return AristonEvoOneDevice(Mock(), attributes or {DeviceAttribute.GW: "gw-1"}) + + def test_metadata_properties_return_values_and_defaults(self): + device = self.make_device( + { + DeviceAttribute.GW: "gateway-1", + DeviceAttribute.SYS: SystemType.BSB.value, + DeviceAttribute.NAME: "Living room", + DeviceAttribute.SN: "serial-1", + DeviceAttribute.HPMP_SYS: True, + VelisDeviceAttribute.WHE_TYPE: WheType.Evo.value, + VelisDeviceAttribute.WHE_MODEL_TYPE: 7, + GalevoDeviceAttribute.FW_VER: "1.2.3", + } + ) + device.features = { + DeviceFeatures.HAS_METERING: True, + DeviceFeatures.DHW_MODE_CHANGEABLE: False, + } + device.custom_features[CustomDeviceFeatures.HAS_DHW] = True + errors = [{"code": 1}] + device.bus_errors_list = errors + + self.assertEqual(device.system_type, SystemType.BSB) + self.assertEqual(device.whe_type, WheType.Evo) + self.assertEqual(device.whe_model_type, 7) + self.assertEqual(device.gateway, "gateway-1") + self.assertTrue(device.has_metering) + self.assertEqual(device.name, "Living room") + self.assertTrue(device.has_dhw) + self.assertFalse(device.dhw_mode_changeable) + self.assertEqual(device.serial_number, "serial-1") + self.assertEqual(device.firmware_version, "1.2.3") + self.assertIs(device.bus_errors, errors) + self.assertTrue(device.hpmp_sys) + + defaults = self.make_device() + self.assertEqual(defaults.system_type, SystemType.UNKNOWN) + self.assertEqual(defaults.whe_type, WheType.Unknown) + self.assertEqual(defaults.whe_model_type, 0) + self.assertEqual(defaults.gateway, "gw-1") + self.assertIsNone(defaults.has_metering) + self.assertIsNone(defaults.name) + self.assertIsNone(defaults.has_dhw) + self.assertIsNone(defaults.dhw_mode_changeable) + self.assertIsNone(defaults.serial_number) + self.assertIsNone(defaults.firmware_version) + self.assertEqual(defaults.bus_errors, []) + self.assertIsNone(defaults.hpmp_sys) + + def test_sync_and_async_feature_loading(self): + device = self.make_device() + expected = {DeviceFeatures.HAS_METERING: True} + device.api.get_features_for_device.return_value = expected + AristonBaseDevice.get_features(device) + device.api.get_features_for_device.assert_called_once_with("gw-1") + self.assertEqual(device.features, expected) + + device.api.async_get_features_for_device = AsyncMock(return_value=None) + asyncio.run(AristonBaseDevice.async_get_features(device)) + device.api.async_get_features_for_device.assert_awaited_once_with("gw-1") + self.assertEqual(device.features, expected) + + device.api.async_get_features_for_device = AsyncMock(return_value={"new": 1}) + asyncio.run(AristonBaseDevice.async_get_features(device)) + self.assertEqual(device.features, {"new": 1}) + + def test_consumption_accessors_select_the_last_sample_for_each_type(self): + device = self.make_device() + interval = ConsumptionTimeInterval.LAST_DAY + device.consumptions_sequences = [ + {"k": kind.value, "p": interval.value, "v": [index, index + 1]} + for index, kind in enumerate(ConsumptionType) + ] + + properties = ( + "central_heating_total_energy_consumption", + "domestic_hot_water_total_energy_consumption", + "central_heating_gas_consumption", + "domestic_hot_water_heating_pump_electricity_consumption", + "domestic_hot_water_resistor_electricity_consumption", + "domestic_hot_water_gas_consumption", + "central_heating_electricity_consumption", + "domestic_hot_water_electricity_consumption", + ) + for property_name in properties: + with self.subTest(property_name=property_name): + self.assertIsNotNone(getattr(device, property_name)) + + self.assertIsNone( + device._get_consumption_sequence_last_value( + ConsumptionType.CENTRAL_HEATING_TOTAL_ENERGY, + ConsumptionTimeInterval.LAST_MONTH, + ) + ) + + def test_energy_feature_flags_and_change_timestamp(self): + device = self.make_device() + new_sequences = [ + { + "k": ConsumptionType.DOMESTIC_HOT_WATER_ELECTRICITY.value, + "p": ConsumptionTimeInterval.LAST_DAY.value, + "v": [2.5], + } + ] + device.consumptions_sequences = new_sequences + device._update_energy( + [{"k": "old", "p": "old", "v": [1]}] + ) + + self.assertTrue( + device.custom_features[ + ConsumptionType.DOMESTIC_HOT_WATER_ELECTRICITY.name + ] + ) + self.assertTrue( + all( + device.custom_features[kind.name] + is (kind is ConsumptionType.DOMESTIC_HOT_WATER_ELECTRICITY) + for kind in ConsumptionType + ) + ) + self.assertGreater( + device.consumption_sequence_last_changed_utc, + datetime.now(timezone.utc) - timedelta(days=1), + ) + + timestamp = device.consumption_sequence_last_changed_utc + device._update_energy(new_sequences) + self.assertEqual(device.consumption_sequence_last_changed_utc, timestamp) + device._update_energy(None) + device._update_energy([]) + + def test_sync_and_async_energy_and_bus_error_updates(self): + device = self.make_device() + sequences = [ + { + "k": ConsumptionType.CENTRAL_HEATING_GAS.value, + "p": ConsumptionTimeInterval.LAST_DAY.value, + "v": [1], + } + ] + device.api.get_consumptions_sequences.return_value = sequences + device.update_energy() + device.api.get_consumptions_sequences.assert_called_once_with("gw-1", "Dhw") + self.assertEqual(device.consumptions_sequences, sequences) + + device.api.async_get_consumptions_sequences = AsyncMock(return_value=[]) + asyncio.run(device.async_update_energy()) + device.api.async_get_consumptions_sequences.assert_awaited_once_with("gw-1", "Dhw") + self.assertEqual(device.consumptions_sequences, []) + + errors = [{"code": "sync"}] + device.api.get_bus_errors.return_value = errors + device.get_bus_errors() + self.assertEqual(device.bus_errors, errors) + device.api.async_get_bus_errors = AsyncMock(return_value=[{"code": "async"}]) + asyncio.run(device.async_get_bus_errors()) + self.assertEqual(device.bus_errors, [{"code": "async"}]) + + def test_feature_availability_checks_system_whe_and_feature_sources(self): + device = self.make_device( + { + DeviceAttribute.GW: "gw-1", + DeviceAttribute.SYS: SystemType.VELIS.value, + VelisDeviceAttribute.WHE_TYPE: WheType.Evo.value, + "from_attribute": True, + } + ) + device.features["from_feature"] = True + device.custom_features["from_custom"] = True + + self.assertTrue(device.are_device_features_available(None, None, None)) + self.assertTrue( + device.are_device_features_available( + ["from_feature", "from_custom", "from_attribute"], + [SystemType.VELIS], + [WheType.Evo], + ) + ) + self.assertFalse( + device.are_device_features_available(None, [SystemType.BSB], None) + ) + self.assertFalse( + device.are_device_features_available(None, None, [WheType.Lux]) + ) + self.assertFalse( + device.are_device_features_available(["missing"], None, None) + ) + + def test_abstract_device_contracts_raise_not_implemented(self): + device = self.make_device() + base_properties = ( + "water_heater_current_temperature", + "water_heater_mode_operation_texts", + "water_heater_mode_options", + "water_heater_mode_value", + ) + for property_name in base_properties: + with self.subTest(property_name=property_name): + property_getter = getattr(AristonBaseDevice, property_name).fget + with self.assertRaises(NotImplementedError): + property_getter(device) + + for method_name, arguments in ( + ("update_state", ()), + ("set_water_heater_operation_mode", ("AUTO",)), + ): + with self.subTest(method_name=method_name): + with self.assertRaises(NotImplementedError): + getattr(AristonBaseDevice, method_name)(device, *arguments) + + for method_name, arguments in ( + ("async_update_state", ()), + ("async_set_water_heater_operation_mode", ("AUTO",)), + ): + with self.subTest(method_name=method_name): + with self.assertRaises(NotImplementedError): + asyncio.run(getattr(AristonBaseDevice, method_name)(device, *arguments)) + + device_properties = ( + "water_heater_temperature_decimals", + "water_heater_temperature_unit", + "water_heater_temperature_step", + "water_heater_minimum_temperature", + "water_heater_target_temperature", + "water_heater_maximum_temperature", + ) + for property_name in device_properties: + with self.subTest(property_name=property_name): + property_getter = getattr(AristonDevice, property_name).fget + with self.assertRaises(NotImplementedError): + property_getter(device) + + for method_name in ( + "set_water_heater_temperature", + "async_set_water_heater_temperature", + ): + with self.subTest(method_name=method_name): + call = getattr(AristonDevice, method_name) + with self.assertRaises(NotImplementedError): + result = call(device, 50) + if method_name.startswith("async_"): + asyncio.run(result) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_bsb_device.py b/tests/test_bsb_device.py new file mode 100644 index 0000000..45bd66b --- /dev/null +++ b/tests/test_bsb_device.py @@ -0,0 +1,285 @@ +"""Behavioral tests for BSB plant and zone controls.""" + +import asyncio +import unittest +from unittest.mock import AsyncMock, Mock + +from ariston.bsb_device import AristonBsbDevice +from ariston.const import ( + BsbDeviceProperties, + BsbOperativeMode, + BsbZoneMode, + BsbZoneProperties, + DeviceAttribute, + PropertyType, +) + + +class AristonBsbDeviceTests(unittest.TestCase): + def make_data(self): + return { + BsbDeviceProperties.DHW_COMF_TEMP: { + PropertyType.MIN: 40, + PropertyType.MAX: 65, + PropertyType.STEP: 1, + PropertyType.VALUE: 55, + }, + BsbDeviceProperties.DHW_REDU_TEMP: { + PropertyType.MIN: 30, + PropertyType.MAX: 50, + PropertyType.STEP: 0.5, + PropertyType.VALUE: 40, + }, + BsbDeviceProperties.DHW_MODE: {PropertyType.VALUE: BsbOperativeMode.ON.value}, + BsbDeviceProperties.DHW_TEMP: 48, + BsbDeviceProperties.FLAME: True, + BsbDeviceProperties.OUT_TEMP: 12.5, + BsbDeviceProperties.ZONES: { + "1": { + BsbZoneProperties.MODE: { + PropertyType.VALUE: BsbZoneMode.MANUAL.value, + PropertyType.ALLOWED_OPTIONS: [ + BsbZoneMode.OFF.value, + BsbZoneMode.TIME_PROGRAM.value, + BsbZoneMode.MANUAL.value, + ], + }, + BsbZoneProperties.CH_COMF_TEMP: { + PropertyType.MIN: 15, + PropertyType.MAX: 24, + PropertyType.STEP: 0.5, + PropertyType.VALUE: 21, + }, + BsbZoneProperties.CH_RED_TEMP: { + PropertyType.MIN: 10, + PropertyType.MAX: 18, + PropertyType.STEP: 0.5, + PropertyType.VALUE: 17, + }, + BsbZoneProperties.COOLING_ON: False, + BsbZoneProperties.ROOM_TEMP: 20.5, + } + }, + } + + def make_device(self, data=None): + api = Mock() + device = AristonBsbDevice(api, {DeviceAttribute.GW: "gw-1"}) + device.data = data if data is not None else self.make_data() + return device + + def test_properties_modes_and_zone_temperature_metadata(self): + device = self.make_device() + self.assertEqual(device.consumption_type, "Ch%2CDhw") + self.assertFalse(device.plant_mode_supported) + self.assertEqual(device.zone_numbers, [1]) + self.assertEqual(device.get_zone(1), device.zones["1"]) + self.assertEqual(device.get_zone(2), {}) + self.assertEqual(device.get_zone_ch_comf_temp(1)[PropertyType.VALUE], 21) + self.assertEqual(device.get_zone_ch_red_temp(1)[PropertyType.VALUE], 17) + self.assertEqual(device.get_zone_mode(1), BsbZoneMode.MANUAL) + self.assertEqual(device.get_zone_mode(2), BsbZoneMode.UNDEFINED) + self.assertEqual(device.get_zone_mode_options(1), [0, 1, 3]) + self.assertTrue(device.is_zone_in_manual_mode(1)) + self.assertFalse(device.is_zone_in_time_program_mode(1)) + self.assertTrue(device.is_zone_mode_options_contains_manual(1)) + self.assertTrue(device.is_zone_mode_options_contains_time_program(1)) + self.assertTrue(device.is_zone_mode_options_contains_off(1)) + self.assertTrue(device.is_plant_in_heat_mode) + self.assertFalse(device.is_plant_in_cool_mode) + self.assertTrue(device.is_flame_on_value) + self.assertEqual(device.water_heater_current_temperature, 48) + self.assertEqual(device.water_heater_minimum_temperature, 40) + self.assertEqual(device.water_heater_reduced_minimum_temperature, 30) + self.assertEqual(device.water_heater_target_temperature, 55) + self.assertEqual(device.water_heater_reduced_temperature, 40) + self.assertEqual(device.water_heater_maximum_temperature, 65) + self.assertEqual(device.water_heater_reduced_maximum_temperature, 50) + self.assertEqual(device.water_heater_temperature_step, 1) + self.assertEqual(device.water_heater_reduced_temperature_step, 0.5) + self.assertEqual(device.water_heater_temperature_decimals, 1) + self.assertEqual(device.water_heater_temperature_unit, "°C") + self.assertEqual(device.water_heater_mode_operation_texts, [mode.name for mode in BsbOperativeMode]) + self.assertEqual(device.water_heater_mode_options, [mode.value for mode in BsbOperativeMode]) + self.assertEqual(device.water_heater_mode_value, BsbOperativeMode.ON.value) + self.assertEqual(device.get_comfort_temp_min(1), 15) + self.assertEqual(device.get_comfort_temp_max(1), 24) + self.assertEqual(device.get_target_temp_step(1), 0.5) + self.assertEqual(device.get_comfort_temp_step(1), 0.5) + self.assertEqual(device.get_target_temp_value(1), 21) + self.assertEqual(device.get_comfort_temp_value(1), 21) + self.assertEqual(device.get_reduced_temp_min(1), 10) + self.assertEqual(device.get_reduced_temp_max(1), 18) + self.assertEqual(device.get_reduced_temp_step(1), 0.5) + self.assertEqual(device.get_reduced_temp_value(1), 17) + self.assertEqual(device.get_measured_temp_value(1), 20.5) + self.assertEqual(device.get_measured_temp_decimals(1), 1) + self.assertEqual(device.get_measured_temp_unit(1), "°C") + self.assertEqual(device.outside_temp_value, 12.5) + self.assertEqual(device.outside_temp_unit, "°C") + + device.data[BsbDeviceProperties.ZONES]["1"][BsbZoneProperties.MODE][PropertyType.VALUE] = BsbZoneMode.TIME_PROGRAM.value + self.assertTrue(device.is_zone_in_time_program_mode(1)) + device.data[BsbDeviceProperties.ZONES]["1"][BsbZoneProperties.COOLING_ON] = True + self.assertTrue(device.is_plant_in_cool_mode) + self.assertFalse(device.is_plant_in_heat_mode) + + def test_sync_and_async_state_feature_and_control_updates(self): + device = self.make_device({}) + expected_data = self.make_data() + device.api.get_bsb_plant_data.return_value = expected_data + device.api.get_features_for_device.return_value = {"hasMetering": True} + device.update_state() + device.get_features() + self.assertEqual(device.data, expected_data) + self.assertTrue(device.features["hasMetering"]) + self.assertTrue(device.custom_features["hasDhw"]) + self.assertTrue(device.custom_features["hasOutsideTemp"]) + + device.set_water_heater_temperature(56) + device.set_water_heater_reduced_temperature(41) + device.set_water_heater_operation_mode("OFF") + device.set_zone_mode(BsbZoneMode.MANUAL_NIGHT, 1) + device.set_comfort_temp(22, 1) + device.set_reduced_temp(16, 1) + self.assertEqual(device.data[BsbDeviceProperties.DHW_COMF_TEMP][PropertyType.VALUE], 48) + self.assertEqual(device.data[BsbDeviceProperties.DHW_REDU_TEMP][PropertyType.VALUE], 41) + self.assertEqual(device.data[BsbDeviceProperties.DHW_MODE][PropertyType.VALUE], BsbOperativeMode.OFF.value) + self.assertEqual(device.get_zone_mode(1), BsbZoneMode.MANUAL_NIGHT) + self.assertEqual(device.get_comfort_temp_value(1), 22) + self.assertEqual(device.get_reduced_temp_value(1), 16) + device.api.set_bsb_temperature.assert_called() + device.api.set_bsb_mode.assert_called_once_with("gw-1", BsbOperativeMode.OFF) + device.api.set_bsb_zone_mode.assert_called_once() + self.assertEqual(device.api.set_bsb_zone_temperature.call_count, 2) + + device.api.async_get_bsb_plant_data = AsyncMock(return_value=self.make_data()) + device.api.async_get_features_for_device = AsyncMock(return_value={"async": True}) + device.api.async_set_bsb_temperature = AsyncMock() + device.api.async_set_bsb_mode = AsyncMock() + device.api.async_set_bsb_zone_mode = AsyncMock() + device.api.async_set_bsb_zone_temperature = AsyncMock() + + async def async_updates(): + await device.async_update_state() + await device.async_get_features() + await device.async_set_water_heater_temperature(57) + await device.async_set_water_heater_reduced_temperature(42) + await device.async_set_water_heater_operation_mode("ON") + await device.async_set_zone_mode(BsbZoneMode.OFF, 1) + await device.async_set_comfort_temp(23, 1) + await device.async_set_reduced_temp(15, 1) + + asyncio.run(async_updates()) + self.assertEqual(device.features, {"async": True}) + self.assertEqual(device.data[BsbDeviceProperties.DHW_COMF_TEMP][PropertyType.VALUE], 48) + self.assertEqual(device.data[BsbDeviceProperties.DHW_REDU_TEMP][PropertyType.VALUE], 42) + self.assertEqual(device.data[BsbDeviceProperties.DHW_MODE][PropertyType.VALUE], BsbOperativeMode.ON.value) + self.assertEqual(device.get_zone_mode(1), BsbZoneMode.OFF) + device.api.async_set_bsb_temperature.assert_awaited() + device.api.async_set_bsb_zone_temperature.assert_awaited() + + def test_zone_metadata_defaults_and_empty_state_setter_fallbacks(self): + device = self.make_device({}) + self.assertEqual(device.zones, {}) + self.assertEqual(device.zone_numbers, []) + self.assertEqual(device.get_zone_ch_comf_temp(8), {}) + self.assertEqual(device.get_zone_ch_red_temp(8), {}) + self.assertEqual(device.get_comfort_temp_min(8), 15) + self.assertEqual(device.get_comfort_temp_max(8), 24) + self.assertEqual(device.get_comfort_temp_step(8), 0.5) + self.assertEqual(device.get_comfort_temp_value(8), 0) + self.assertEqual(device.get_reduced_temp_min(8), 10) + self.assertEqual(device.get_reduced_temp_max(8), 18) + self.assertEqual(device.get_reduced_temp_step(8), 0.5) + self.assertEqual(device.get_reduced_temp_value(8), 0) + self.assertEqual(device.get_measured_temp_value(8), 0) + self.assertFalse(device.is_flame_on_value) + self.assertEqual(device.water_heater_current_temperature, None) + self.assertEqual(device.outside_temp_value, 0) + + device.api.get_bsb_plant_data.return_value = self.make_data() + device.set_comfort_temp(20, 1) + self.assertEqual(device.data[BsbDeviceProperties.ZONES]["1"][BsbZoneProperties.CH_COMF_TEMP][PropertyType.VALUE], 20) + + async_device = self.make_device({}) + async_device.api.async_get_bsb_plant_data = AsyncMock(return_value=self.make_data()) + async_device.api.async_set_bsb_zone_temperature = AsyncMock() + + async def update_before_setting(): + await async_device.async_set_reduced_temp(14, 1) + + asyncio.run(update_before_setting()) + async_device.api.async_get_bsb_plant_data.assert_awaited_once_with("gw-1") + self.assertEqual( + async_device.data[BsbDeviceProperties.ZONES]["1"][BsbZoneProperties.CH_RED_TEMP][PropertyType.VALUE], + 14, + ) + + def test_dhw_and_zone_setters_load_empty_state_and_apply_zero_fallbacks(self): + sparse_data = self.make_data() + sparse_data.pop(BsbDeviceProperties.DHW_TEMP) + sparse_data[BsbDeviceProperties.DHW_REDU_TEMP].pop(PropertyType.VALUE) + + sync_temperature = self.make_device({}) + sync_temperature.api.get_bsb_plant_data.return_value = sparse_data + sync_temperature.set_water_heater_temperature(53) + self.assertEqual( + sync_temperature.api.set_bsb_temperature.call_args.args[1:3], + (53, 0), + ) + + sync_reduced = self.make_device({}) + sync_reduced.api.get_bsb_plant_data.return_value = self.make_data() + sync_reduced.data = {} + sync_reduced.api.get_bsb_plant_data.return_value.pop(BsbDeviceProperties.DHW_TEMP) + sync_reduced.set_water_heater_reduced_temperature(39) + self.assertEqual( + sync_reduced.api.set_bsb_temperature.call_args.args[1:3], + (0, 39), + ) + + sync_zone_reduced = self.make_device({}) + sync_zone_reduced.api.get_bsb_plant_data.return_value = self.make_data() + sync_zone_reduced.set_reduced_temp(13, 1) + self.assertEqual( + sync_zone_reduced.api.set_bsb_zone_temperature.call_args.args[2:4], + (21, 13), + ) + + async_temperature = self.make_device({}) + async_sparse_data = self.make_data() + async_sparse_data.pop(BsbDeviceProperties.DHW_TEMP) + async_sparse_data[BsbDeviceProperties.DHW_REDU_TEMP].pop(PropertyType.VALUE) + async_temperature.api.async_get_bsb_plant_data = AsyncMock(return_value=async_sparse_data) + async_temperature.api.async_set_bsb_temperature = AsyncMock() + async_reduced = self.make_device({}) + async_reduced_data = self.make_data() + async_reduced_data.pop(BsbDeviceProperties.DHW_TEMP) + async_reduced.api.async_get_bsb_plant_data = AsyncMock(return_value=async_reduced_data) + async_reduced.api.async_set_bsb_temperature = AsyncMock() + async_zone_comfort = self.make_device({}) + async_zone_comfort.api.async_get_bsb_plant_data = AsyncMock(return_value=self.make_data()) + async_zone_comfort.api.async_set_bsb_zone_temperature = AsyncMock() + + async def set_after_load(): + await async_temperature.async_set_water_heater_temperature(52) + await async_reduced.async_set_water_heater_reduced_temperature(38) + await async_zone_comfort.async_set_comfort_temp(22, 1) + + asyncio.run(set_after_load()) + async_temperature.api.async_set_bsb_temperature.assert_awaited_once() + self.assertEqual( + async_temperature.api.async_set_bsb_temperature.await_args.args[1:3], + (52, 0), + ) + self.assertEqual( + async_reduced.api.async_set_bsb_temperature.await_args.args[1:3], + (0, 38), + ) + async_zone_comfort.api.async_get_bsb_plant_data.assert_awaited_once_with("gw-1") + async_zone_comfort.api.async_set_bsb_zone_temperature.assert_awaited_once() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_device_models.py b/tests/test_device_models.py new file mode 100644 index 0000000..a36fd25 --- /dev/null +++ b/tests/test_device_models.py @@ -0,0 +1,455 @@ +"""Behavioral tests for the water-heater device models.""" + +import asyncio +import unittest +from unittest.mock import AsyncMock, Mock + +from ariston.const import ( + ConsumptionTimeInterval, + ConsumptionType, + DeviceAttribute, + EvoDeviceProperties, + EvoLydosDeviceProperties, + EvoOneDeviceProperties, + EvoPlantMode, + LuxPlantMode, + LydosDeviceProperties, + LydosPlantMode, + MedDeviceSettings, + NuosSplitOperativeMode, + NuosSplitProperties, + SeDeviceSettings, + SlpDeviceSettings, + VelisBaseDeviceProperties, + VelisDeviceProperties, + VelisPlantMode, +) +from ariston.evo_device import AristonEvoDevice +from ariston.evo_one_device import AristonEvoOneDevice +from ariston.lux2_device import AristonLux2Device +from ariston.lux_device import AristonLuxDevice +from ariston.lydos_device import AristonLydosDevice +from ariston.lydos_hybrid_device import AristonLydosHybridDevice +from ariston.nuos_split_device import AristonNuosSplitDevice +from ariston.velis_device import AristonVelisDevice + + +class AristonDeviceModelTests(unittest.TestCase): + def make_device(self, device_type, data=None): + api = Mock() + device = device_type(api, {DeviceAttribute.GW: "gw-1"}) + device.data = data or {} + return device + + def test_evo_and_evo_lydos_properties_and_setters(self): + device = self.make_device( + AristonEvoDevice, + { + EvoDeviceProperties.ECO: True, + EvoDeviceProperties.RM_TM: "01:35:00", + EvoDeviceProperties.PWR_OPT: False, + EvoDeviceProperties.MODE: EvoPlantMode.PROGRAM.value, + EvoDeviceProperties.REQ_TEMP: 54, + EvoLydosDeviceProperties.TEMP: 47, + EvoLydosDeviceProperties.AV_SHW: 2, + EvoLydosDeviceProperties.HEAT_REQ: True, + EvoLydosDeviceProperties.ANTI_LEG: False, + }, + ) + device.plant_settings = { + MedDeviceSettings.MED_MAX_SETPOINT_TEMPERATURE_MIN: 40, + MedDeviceSettings.MED_MAX_SETPOINT_TEMPERATURE_MAX: 80, + } + + self.assertEqual(device.water_heater_eco_value, True) + self.assertEqual(device.rm_tm_value, "01:35:00") + self.assertEqual(device.rm_tm_in_minutes, 95) + self.assertFalse(device.water_heater_power_option_value) + self.assertEqual(device.water_heater_current_temperature, 47) + self.assertEqual(device.water_heater_target_temperature, 54) + self.assertEqual(device.av_shw_value, 2) + self.assertTrue(device.is_heating) + self.assertFalse(device.is_antileg) + self.assertEqual(device.water_heater_maximum_setpoint_temperature_minimum, 40) + self.assertEqual(device.water_heater_maximum_setpoint_temperature_maximum, 80) + self.assertEqual(device.water_heater_mode, EvoPlantMode) + self.assertEqual(device.consumption_type, "Dhw") + device.data.pop(EvoDeviceProperties.RM_TM) + self.assertEqual(device.rm_tm_in_minutes, -1) + + device.set_eco_mode(False) + device.set_water_heater_operation_mode("MANUAL") + device.set_water_heater_temperature(50) + self.assertEqual(device.data[EvoDeviceProperties.ECO], False) + self.assertEqual(device.data[EvoDeviceProperties.MODE], EvoPlantMode.MANUAL.value) + self.assertEqual(device.data[EvoDeviceProperties.REQ_TEMP], 50) + device.api.set_evo_eco_mode.assert_called_once_with("gw-1", False) + device.api.set_evo_mode.assert_called_once_with("gw-1", EvoPlantMode.MANUAL) + device.api.set_evo_temperature.assert_called_once_with("gw-1", 50) + + device.api.async_set_evo_eco_mode = AsyncMock() + device.api.async_set_evo_mode = AsyncMock() + device.api.async_set_evo_temperature = AsyncMock() + + async def set_values(): + await device.async_set_eco_mode(True) + await device.async_set_water_heater_operation_mode("PROGRAM") + await device.async_set_water_heater_temperature(58) + + asyncio.run(set_values()) + self.assertTrue(device.data[EvoDeviceProperties.ECO]) + self.assertEqual(device.data[EvoDeviceProperties.MODE], EvoPlantMode.PROGRAM.value) + self.assertEqual(device.data[EvoDeviceProperties.REQ_TEMP], 58) + device.api.async_set_evo_eco_mode.assert_awaited_once_with("gw-1", True) + device.api.async_set_evo_mode.assert_awaited_once_with("gw-1", EvoPlantMode.PROGRAM) + device.api.async_set_evo_temperature.assert_awaited_once_with("gw-1", 58) + + def test_evo_one_properties_and_sync_async_commands(self): + device = self.make_device( + AristonEvoOneDevice, + { + EvoOneDeviceProperties.TEMP: 46, + EvoOneDeviceProperties.AV_SHW: 3, + EvoOneDeviceProperties.ECO: 1, + EvoOneDeviceProperties.RM_TM: "00:45:00", + EvoOneDeviceProperties.STATE: True, + EvoOneDeviceProperties.MAX_REQ_SHW: "3", + EvoOneDeviceProperties.REQ_SHW: "2", + VelisBaseDeviceProperties.MODE: VelisPlantMode.NIGHT.value, + VelisBaseDeviceProperties.ON: True, + }, + ) + + self.assertEqual(device.water_heater_current_temperature, 46) + self.assertEqual(device.consumption_type, "Dhw") + self.assertEqual(device.av_shw_value, 3) + self.assertEqual(device.water_heater_eco_value, 1) + self.assertEqual(device.rm_tm_in_minutes, 45) + device.data.pop(EvoOneDeviceProperties.RM_TM) + self.assertEqual(device.rm_tm_in_minutes, -1) + self.assertTrue(device.is_heating) + self.assertEqual(device.max_req_shower, "3") + self.assertEqual(device.req_shower, "2") + self.assertEqual(device.water_heater_mode_value, VelisPlantMode.NIGHT.value) + self.assertTrue(device.water_heater_power_value) + self.assertEqual(device.water_heater_mode_options, [mode.value for mode in VelisPlantMode]) + + device.set_eco_mode(False) + device.set_water_heater_operation_mode("MANUAL") + device.set_water_heater_number_of_showers(1) + self.assertFalse(device.data[EvoOneDeviceProperties.ECO]) + self.assertEqual(device.data[VelisBaseDeviceProperties.MODE], VelisPlantMode.MANUAL.value) + self.assertEqual(device.data[EvoOneDeviceProperties.REQ_SHW], 1) + device.api.set_evo_number_of_showers.assert_called_once_with("gw-1", 1) + + device.api.async_set_evo_eco_mode = AsyncMock() + device.api.async_set_evo_mode = AsyncMock() + device.api.async_set_evo_number_of_showers = AsyncMock() + + async def set_values(): + await device.async_set_eco_mode(True) + await device.async_set_water_heater_operation_mode("NIGHT") + await device.async_set_water_heater_number_of_showers(2) + + asyncio.run(set_values()) + self.assertTrue(device.data[EvoOneDeviceProperties.ECO]) + self.assertEqual(device.data[VelisBaseDeviceProperties.MODE], VelisPlantMode.NIGHT.value) + self.assertEqual(device.data[EvoOneDeviceProperties.REQ_SHW], 2) + device.api.async_set_evo_number_of_showers.assert_awaited_once_with("gw-1", 2) + + def test_velis_update_settings_power_and_antilegionella(self): + device = self.make_device(AristonEvoDevice) + device.api.get_features_for_device.return_value = {"feature": True} + device.api.get_velis_plant_data.return_value = { + "state": "ready", + VelisDeviceProperties.PROC_REQ_TEMP: 53, + } + device.api.get_velis_plant_settings.return_value = { + MedDeviceSettings.MED_ANTILEGIONELLA_ON_OFF: True, + MedDeviceSettings.MED_MAX_SETPOINT_TEMPERATURE: 75, + } + device.get_features() + device.update_state() + self.assertTrue(device.custom_features["hasDhw"]) + self.assertTrue(device.features["dhwModeChangeable"]) + self.assertEqual(device.data, {"state": "ready", VelisDeviceProperties.PROC_REQ_TEMP: 53}) + self.assertTrue(device.water_anti_leg_value) + self.assertEqual(device.proc_req_temp_value, 53) + self.assertEqual(device.water_heater_maximum_setpoint_temperature, 75) + self.assertEqual(device.water_heater_maximum_temperature, 75) + self.assertEqual(device.water_heater_minimum_temperature, 40) + self.assertEqual(device.water_heater_temperature_step, 1) + self.assertEqual(device.water_heater_temperature_decimals, 0) + self.assertEqual(device.water_heater_temperature_unit, "°C") + device.set_power(False) + self.assertFalse(device.data[VelisBaseDeviceProperties.ON]) + device.set_antilegionella(False) + self.assertFalse(device.plant_settings[MedDeviceSettings.MED_ANTILEGIONELLA_ON_OFF]) + device.set_max_setpoint_temp(70) + self.assertEqual(device.plant_settings[MedDeviceSettings.MED_MAX_SETPOINT_TEMPERATURE], 70) + + device.api.async_get_features_for_device = AsyncMock(return_value={"async": True}) + device.api.async_get_velis_plant_data = AsyncMock(return_value={"state": "async"}) + device.api.async_get_velis_plant_settings = AsyncMock(return_value={ + MedDeviceSettings.MED_ANTILEGIONELLA_ON_OFF: False, + MedDeviceSettings.MED_MAX_SETPOINT_TEMPERATURE: 65, + }) + device.api.async_set_velis_power = AsyncMock() + device.api.async_set_velis_plant_setting = AsyncMock() + + async def update_and_set(): + await device.async_get_features() + await device.async_update_state() + await device.async_set_power(True) + await device.async_set_antilegionella(True) + await device.async_set_max_setpoint_temp(72) + + asyncio.run(update_and_set()) + self.assertEqual(device.features, {"async": True, "dhwModeChangeable": True}) + self.assertEqual(device.data, {"state": "async", VelisBaseDeviceProperties.ON: True}) + self.assertTrue(device.plant_settings[MedDeviceSettings.MED_ANTILEGIONELLA_ON_OFF]) + self.assertEqual(device.plant_settings[MedDeviceSettings.MED_MAX_SETPOINT_TEMPERATURE], 72) + device.api.async_set_velis_power.assert_awaited_once() + self.assertEqual(device.water_heater_mode_operation_texts, [mode.name for mode in EvoPlantMode]) + for property_name in ( + "water_heater_maximum_setpoint_temperature_minimum", + "water_heater_maximum_setpoint_temperature_maximum", + ): + with self.subTest(abstract_property=property_name): + property_getter = getattr(AristonVelisDevice, property_name).fget + with self.assertRaises(NotImplementedError): + property_getter(device) + + def test_lux_lux2_and_lydos_special_modes_and_power_option(self): + lux = self.make_device( + AristonLuxDevice, + { + EvoDeviceProperties.MODE: LuxPlantMode.BOOST.value, + EvoDeviceProperties.REQ_TEMP: 52, + }, + ) + lux.plant_settings[MedDeviceSettings.MED_MAX_SETPOINT_TEMPERATURE_MAX] = 78 + self.assertEqual(lux.water_heater_target_temperature, 78) + self.assertEqual(lux.water_heater_mode, LuxPlantMode) + lux.data[EvoDeviceProperties.MODE] = LuxPlantMode.MANUAL.value + self.assertEqual(lux.water_heater_target_temperature, 52) + lux.set_water_heater_operation_mode("BOOST") + self.assertEqual(lux.data[EvoDeviceProperties.MODE], LuxPlantMode.BOOST.value) + lux.api.async_set_evo_mode = AsyncMock() + asyncio.run(lux.async_set_water_heater_operation_mode("PROGRAM")) + self.assertEqual(lux.data[EvoDeviceProperties.MODE], LuxPlantMode.PROGRAM.value) + lux.api.async_set_evo_mode.assert_awaited_once_with("gw-1", LuxPlantMode.PROGRAM) + + lux2 = self.make_device(AristonLux2Device) + lux2.set_water_heater_power_option(True) + self.assertTrue(lux2.water_heater_power_option_value) + lux2.api.async_set_lux_power_option = AsyncMock() + asyncio.run(lux2.async_set_water_heater_power_option(False)) + self.assertFalse(lux2.water_heater_power_option_value) + lux2.api.async_set_lux_power_option.assert_awaited_once_with("gw-1", False) + + lydos = self.make_device(AristonLydosDevice) + lydos.set_water_heater_operation_mode("BOOST") + self.assertEqual(lydos.data[EvoDeviceProperties.MODE], LuxPlantMode.BOOST.value) + lydos.api.async_set_evo_mode = AsyncMock() + asyncio.run(lydos.async_set_water_heater_operation_mode("MANUAL")) + self.assertEqual(lydos.data[EvoDeviceProperties.MODE], LuxPlantMode.MANUAL.value) + + def test_nuos_split_properties_sync_async_and_missing_state_defaults(self): + device = self.make_device( + AristonNuosSplitDevice, + { + NuosSplitProperties.WATER_TEMP: 43, + NuosSplitProperties.COMFORT_TEMP: 55, + NuosSplitProperties.REDUCED_TEMP: 40, + NuosSplitProperties.BOOST_ON: True, + NuosSplitProperties.OP_MODE: NuosSplitOperativeMode.COMFORT.value, + }, + ) + device.plant_settings = { + key: index for index, key in enumerate( + ( + SlpDeviceSettings.SLP_MAX_SETPOINT_TEMPERATURE_MIN, + SlpDeviceSettings.SLP_MAX_SETPOINT_TEMPERATURE_MAX, + SlpDeviceSettings.SLP_MIN_SETPOINT_TEMPERATURE, + SlpDeviceSettings.SLP_MIN_SETPOINT_TEMPERATURE_MIN, + SlpDeviceSettings.SLP_MIN_SETPOINT_TEMPERATURE_MAX, + SlpDeviceSettings.SLP_PRE_HEATING_ON_OFF, + SlpDeviceSettings.SLP_HEATING_RATE, + ), 40 + ) + } + self.assertEqual(device.water_heater_current_temperature, 43) + self.assertEqual(device.water_heater_target_temperature, 55) + self.assertEqual(device.water_heater_reduced_temperature, 40) + self.assertEqual(device.water_heater_maximum_setpoint_temperature_minimum, 40) + self.assertEqual(device.water_heater_maximum_setpoint_temperature_maximum, 41) + self.assertEqual(device.water_heater_minimum_setpoint_temperature, 42) + self.assertEqual(device.water_heater_minimum_setpoint_temperature_minimum, 43) + self.assertEqual(device.water_heater_minimum_setpoint_temperature_maximum, 44) + self.assertEqual(device.water_heater_preheating_on_off, 45) + self.assertEqual(device.water_heater_heating_rate, 46) + self.assertTrue(device.water_heater_boost) + self.assertEqual(device.water_heater_mode_value, NuosSplitOperativeMode.COMFORT.value) + self.assertEqual(device.consumption_type, "DhwHeatingPumpElec%2CDhwResistorElec") + self.assertEqual(device.anti_legionella_on_off, SlpDeviceSettings.SLP_ANTILEGIONELLA_ON_OFF) + self.assertEqual(device.max_setpoint_temp, SlpDeviceSettings.SLP_MAX_SETPOINT_TEMPERATURE) + self.assertEqual(device.water_heater_mode, NuosSplitOperativeMode) + + device.set_water_heater_boost(False) + device.set_water_heater_temperature(60) + device.set_water_heater_reduced_temperature(42) + device.set_water_heater_operation_mode("FAST") + device.set_min_setpoint_temp(35) + device.set_preheating(True) + 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) + 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_velis_plant_setting = AsyncMock() + + async def set_values(): + await device.async_set_water_heater_boost(True) + await device.async_set_water_heater_temperature(62) + await device.async_set_water_heater_reduced_temperature(39) + await device.async_set_water_heater_operation_mode("GREEN") + await device.async_set_min_setpoint_temp(36) + await device.async_set_preheating(False) + await device.async_set_heating_rate(4) + + asyncio.run(set_values()) + self.assertTrue(device.data[NuosSplitProperties.BOOST_ON]) + self.assertEqual(device.data[NuosSplitProperties.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) + + missing = self.make_device(AristonNuosSplitDevice) + missing.api.get_velis_plant_data.return_value = {} + missing.set_water_heater_reduced_temperature(38) + self.assertEqual(missing.api.set_nuos_temperature.call_args.args[1:3], (0, 38)) + + async_missing = self.make_device(AristonNuosSplitDevice) + async_missing.api.async_get_velis_plant_data = AsyncMock(return_value={}) + async_missing.api.async_set_nuos_temperature = AsyncMock() + asyncio.run(async_missing.async_set_water_heater_reduced_temperature(37)) + self.assertEqual( + async_missing.api.async_set_nuos_temperature.await_args.args[1:3], + (40.0, 37), + ) + + missing_temperature = self.make_device(AristonNuosSplitDevice) + missing_temperature.api.get_velis_plant_data.return_value = {} + missing_temperature.set_water_heater_temperature(59) + self.assertEqual( + missing_temperature.api.set_nuos_temperature.call_args.args[1:3], + (59, 0), + ) + + async_missing_temperature = self.make_device(AristonNuosSplitDevice) + async_missing_temperature.api.async_get_velis_plant_data = AsyncMock(return_value={}) + async_missing_temperature.api.async_set_nuos_temperature = AsyncMock() + asyncio.run(async_missing_temperature.async_set_water_heater_temperature(61)) + self.assertEqual( + async_missing_temperature.api.async_set_nuos_temperature.await_args.args[1:3], + (61, 0), + ) + + def test_lydos_hybrid_settings_accessors_and_all_commands(self): + setting_keys = ( + SeDeviceSettings.SE_MAX_SETPOINT_TEMPERATURE_MIN, + SeDeviceSettings.SE_MAX_SETPOINT_TEMPERATURE_MAX, + SeDeviceSettings.SE_PERMANENT_BOOST_ON_OFF, + SeDeviceSettings.SE_ANTI_COOLING_ON_OFF, + SeDeviceSettings.SE_ANTI_COOLING_TEMPERATURE, + SeDeviceSettings.SE_ANTI_COOLING_TEMPERATURE_MAX, + SeDeviceSettings.SE_ANTI_COOLING_TEMPERATURE_MIN, + SeDeviceSettings.SE_NIGHT_MODE_ON_OFF, + SeDeviceSettings.SE_NIGHT_BEGIN_AS_MINUTES, + SeDeviceSettings.SE_NIGHT_BEGIN_MAX_AS_MINUTES, + SeDeviceSettings.SE_NIGHT_BEGIN_MIN_AS_MINUTES, + SeDeviceSettings.SE_NIGHT_END_AS_MINUTES, + SeDeviceSettings.SE_NIGHT_END_MAX_AS_MINUTES, + SeDeviceSettings.SE_NIGHT_END_MIN_AS_MINUTES, + SeDeviceSettings.SE_ANTILEGIONELLA_ON_OFF, + ) + device = self.make_device(AristonLydosHybridDevice) + device.plant_settings = {key: 1 for key in setting_keys} + device.consumptions_sequences = [] + for index, property_name in enumerate( + ( + "water_heater_maximum_setpoint_temperature_minimum", + "water_heater_maximum_setpoint_temperature_maximum", + "permanent_boost_value", + "anti_cooling_value", + "anti_cooling_temperature_value", + "anti_cooling_temperature_maximum", + "anti_cooling_temperature_minimum", + "night_mode_value", + "night_mode_begin_as_minutes_value", + "night_mode_begin_max_as_minutes_value", + "night_mode_begin_min_as_minutes_value", + "night_mode_end_as_minutes_value", + "night_mode_end_max_as_minutes_value", + "night_mode_end_min_as_minutes_value", + ) + ): + with self.subTest(property_name=property_name): + self.assertEqual(getattr(device, property_name), 1) + self.assertEqual(device.water_heater_mode, LydosPlantMode) + self.assertEqual(device.plant_data.value, "sePlantData") + self.assertEqual(device.anti_legionella_on_off, SeDeviceSettings.SE_ANTILEGIONELLA_ON_OFF) + self.assertEqual(device.consumption_type, "DhwHeatingPumpElec%2CDhwResistorElec") + self.assertEqual(device.max_setpoint_temp, SeDeviceSettings.SE_MAX_SETPOINT_TEMPERATURE) + device.consumptions_sequences = [{ + "k": ConsumptionType.DOMESTIC_HOT_WATER_HEATING_PUMP_ELECTRICITY.value, + "p": ConsumptionTimeInterval.LAST_DAY.value, + "v": [3, 8], + }] + self.assertEqual(device.electric_consumption_for_water_last_two_hours, 8) + + operations = ( + ("set_water_heater_operation_mode", "async_set_water_heater_operation_mode", "BOOST"), + ("set_water_heater_temperature", "async_set_water_heater_temperature", 55), + ("set_permanent_boost_value", "async_set_permanent_boost_value", False), + ("set_anti_cooling_value", "async_set_anti_cooling_value", False), + ("set_cooling_temperature_value", "async_set_cooling_temperature_value", 12), + ("set_night_mode_value", "async_set_night_mode_value", False), + ("set_night_mode_begin_as_minutes_value", "async_set_night_mode_begin_as_minutes_value", 450), + ("set_night_mode_end_as_minutes_value", "async_set_night_mode_end_as_minutes_value", 390), + ) + for sync_name, async_name, value in operations: + with self.subTest(command=sync_name): + getattr(device, sync_name)(value) + if sync_name == "set_water_heater_operation_mode": + self.assertTrue(device.api.set_lydos_mode.called) + elif sync_name == "set_water_heater_temperature": + self.assertTrue(device.api.set_lydos_temperature.called) + else: + self.assertTrue(device.api.set_velis_plant_setting.called) + + async_methods = ( + "async_set_lydos_mode", + "async_set_lydos_temperature", + "async_set_velis_plant_setting", + ) + for method_name in async_methods: + setattr(device.api, method_name, AsyncMock()) + + async def set_values(): + for _, async_name, value in operations: + await getattr(device, async_name)(value) + + asyncio.run(set_values()) + self.assertEqual(device.data[LydosDeviceProperties.MODE], LydosPlantMode.BOOST.value) + self.assertEqual(device.data[LydosDeviceProperties.REQ_TEMP], 55) + self.assertEqual(device.api.async_set_velis_plant_setting.await_count, 6) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_device_selection.py b/tests/test_device_selection.py new file mode 100644 index 0000000..8d2154f --- /dev/null +++ b/tests/test_device_selection.py @@ -0,0 +1,126 @@ +"""Tests for cloud discovery and device selection.""" + +import asyncio +import unittest +from unittest.mock import AsyncMock, Mock, patch + +import ariston +from ariston import Ariston +from ariston.bsb_device import AristonBsbDevice +from ariston.const import DeviceAttribute, SystemType, VelisDeviceAttribute, WheType +from ariston.evo_device import AristonEvoDevice +from ariston.evo_one_device import AristonEvoOneDevice +from ariston.galevo_device import AristonGalevoDevice +from ariston.lux2_device import AristonLux2Device +from ariston.lux_device import AristonLuxDevice +from ariston.lydos_device import AristonLydosDevice +from ariston.lydos_hybrid_device import AristonLydosHybridDevice +from ariston.nuos_split_device import AristonNuosSplitDevice + + +class DeviceSelectionTests(unittest.TestCase): + def test_selects_device_class_for_each_supported_system(self): + cases = [ + (SystemType.GALEVO.value, None, AristonGalevoDevice), + (SystemType.BSB.value, None, AristonBsbDevice), + (SystemType.VELIS.value, WheType.Evo.value, AristonEvoOneDevice), + ( + SystemType.VELIS.value, + WheType.LydosHybrid.value, + AristonLydosHybridDevice, + ), + (SystemType.VELIS.value, WheType.Lydos.value, AristonLydosDevice), + ( + SystemType.VELIS.value, + WheType.NuosSplit.value, + AristonNuosSplitDevice, + ), + (SystemType.VELIS.value, WheType.Andris2.value, AristonEvoDevice), + (SystemType.VELIS.value, WheType.Evo2.value, AristonEvoDevice), + (SystemType.VELIS.value, WheType.Lux2.value, AristonLux2Device), + (SystemType.VELIS.value, WheType.Lux.value, AristonLuxDevice), + ] + + for system, whe_type, expected_class in cases: + with self.subTest(system=system, whe_type=whe_type): + attributes = { + DeviceAttribute.GW: "gateway", + DeviceAttribute.SYS: system, + } + if whe_type is not None: + attributes[VelisDeviceAttribute.WHE_TYPE] = whe_type + + with patch("ariston._connect", return_value=Mock()), patch( + "ariston._discover", return_value=[attributes] + ): + device = ariston.hello("user", "password", "gateway") + + self.assertIsInstance(device, expected_class) + + def test_returns_none_for_unknown_gateway_or_unsupported_device(self): + api = Mock() + + with patch("ariston._connect", return_value=api): + with patch("ariston._discover", return_value=[]): + with self.assertLogs("ariston", level="ERROR"): + self.assertIsNone(ariston.hello("user", "password", "missing")) + + unsupported_devices = [ + {DeviceAttribute.GW: "gateway", DeviceAttribute.SYS: 999}, + { + DeviceAttribute.GW: "gateway", + DeviceAttribute.SYS: SystemType.VELIS.value, + VelisDeviceAttribute.WHE_TYPE: 999, + }, + ] + for attributes in unsupported_devices: + with patch("ariston._discover", return_value=[attributes]): + with self.assertLogs("ariston", level="ERROR"): + self.assertIsNone( + ariston.hello("user", "password", "gateway") + ) + + def test_discovery_combines_remote_and_velis_devices(self): + api = Mock() + api.get_detailed_devices.return_value = [{"gw": "remote"}] + api.get_detailed_velis_devices.return_value = [{"gw": "velis"}] + + with patch("ariston._connect", return_value=api): + devices = ariston.discover("user", "password") + + self.assertEqual(devices, [{"gw": "remote"}, {"gw": "velis"}]) + + def test_async_discovery_combines_both_device_sources(self): + api = Mock() + api.async_get_detailed_devices = AsyncMock(return_value=[{"gw": "remote"}]) + api.async_get_detailed_velis_devices = AsyncMock( + return_value=[{"gw": "velis"}] + ) + + with patch("ariston._async_connect", new=AsyncMock(return_value=api)): + devices = asyncio.run(ariston.async_discover("user", "password")) + + self.assertEqual(devices, [{"gw": "remote"}, {"gw": "velis"}]) + + def test_async_client_discovers_devices_and_selects_requested_device(self): + client = Ariston() + client.api = Mock() + client.api.async_get_detailed_devices = AsyncMock(return_value=[]) + client.api.async_get_detailed_velis_devices = AsyncMock( + return_value=[ + { + DeviceAttribute.GW: "gateway", + DeviceAttribute.SYS: SystemType.VELIS.value, + VelisDeviceAttribute.WHE_TYPE: WheType.Evo.value, + } + ] + ) + + device = asyncio.run(client.async_hello("gateway")) + + self.assertIsInstance(device, AristonEvoOneDevice) + self.assertEqual(client.cloud_devices[0][DeviceAttribute.GW], "gateway") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_device_state.py b/tests/test_device_state.py new file mode 100644 index 0000000..113a0ba --- /dev/null +++ b/tests/test_device_state.py @@ -0,0 +1,106 @@ +"""Tests for device state and command behavior.""" + +import asyncio +import unittest +from unittest.mock import AsyncMock, Mock + +from ariston.ariston_api import ConnectionException +from ariston.const import ( + ConsumptionTimeInterval, + ConsumptionType, + EvoOneDeviceProperties, + PlantData, + VelisPlantMode, +) +from ariston.evo_one_device import AristonEvoOneDevice + + +class AristonEvoOneDeviceTests(unittest.TestCase): + def setUp(self): + self.api = Mock() + self.device = AristonEvoOneDevice(self.api, {"gw": "gateway-1"}) + + def test_properties_read_values_from_latest_state(self): + self.device.data = { + EvoOneDeviceProperties.TEMP: 48.5, + EvoOneDeviceProperties.MODE: VelisPlantMode.NIGHT.value, + EvoOneDeviceProperties.STATE: True, + EvoOneDeviceProperties.RM_TM: "02:45:00", + } + + self.assertEqual(self.device.water_heater_current_temperature, 48.5) + self.assertEqual(self.device.water_heater_current_mode_text, "NIGHT") + self.assertTrue(self.device.is_heating) + self.assertEqual(self.device.rm_tm_in_minutes, 165) + + def test_invalid_mode_value_has_unknown_text(self): + self.device.data[EvoOneDeviceProperties.MODE] = 999 + + self.assertEqual(self.device.water_heater_current_mode_text, "UNKNOWN") + + def test_sync_mode_command_updates_state_after_api_success(self): + self.device.set_water_heater_operation_mode("PROGRAM") + + self.api.set_evo_mode.assert_called_once_with( + "gateway-1", VelisPlantMode.PROGRAM + ) + self.assertEqual( + self.device.water_heater_mode_value, + VelisPlantMode.PROGRAM.value, + ) + + def test_sync_mode_command_leaves_state_unchanged_when_api_fails(self): + self.device.data[EvoOneDeviceProperties.MODE] = VelisPlantMode.NIGHT.value + self.api.set_evo_mode.side_effect = ConnectionException("offline") + + with self.assertRaises(ConnectionException): + self.device.set_water_heater_operation_mode("PROGRAM") + + self.assertEqual( + self.device.water_heater_mode_value, + VelisPlantMode.NIGHT.value, + ) + + def test_async_mode_command_updates_state_after_api_success(self): + self.api.async_set_evo_mode = AsyncMock() + + asyncio.run(self.device.async_set_water_heater_operation_mode("PROGRAM")) + + self.api.async_set_evo_mode.assert_awaited_once_with( + "gateway-1", VelisPlantMode.PROGRAM + ) + self.assertEqual( + self.device.water_heater_mode_value, + VelisPlantMode.PROGRAM.value, + ) + + def test_async_state_refresh_replaces_cached_state(self): + self.api.async_get_velis_plant_data = AsyncMock( + return_value={EvoOneDeviceProperties.TEMP: 51.0} + ) + + asyncio.run(self.device.async_update_state()) + + self.api.async_get_velis_plant_data.assert_awaited_once_with( + PlantData.PD, "gateway-1" + ) + self.assertEqual( + self.device.data, + {EvoOneDeviceProperties.TEMP: 51.0}, + ) + + def test_energy_value_uses_last_sample_for_requested_interval(self): + self.device.consumptions_sequences = [ + { + "k": ConsumptionType.DOMESTIC_HOT_WATER_ELECTRICITY.value, + "p": ConsumptionTimeInterval.LAST_DAY.value, + "v": [0.6, 1.2], + } + ] + + self.assertEqual(self.device.domestic_hot_water_electricity_consumption, 1.2) + self.assertIsNone(self.device.central_heating_total_energy_consumption) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_galevo_device.py b/tests/test_galevo_device.py new file mode 100644 index 0000000..09510fe --- /dev/null +++ b/tests/test_galevo_device.py @@ -0,0 +1,381 @@ +"""Behavioral tests for Galevo property access and controls.""" + +import asyncio +import unittest +from datetime import date +from unittest.mock import AsyncMock, Mock + +from ariston.const import ( + ConsumptionProperties, + ConsumptionTimeInterval, + ConsumptionType, + Currency, + CustomDeviceFeatures, + DeviceAttribute, + DeviceFeatures, + DeviceProperties, + GasEnergyUnit, + GasType, + MenuItemNames, + PlantMode, + PropertyType, + ThermostatProperties, + ZoneAttribute, + ZoneMode, +) +from ariston.galevo_device import AristonGalevoDevice + + +class AristonGalevoDeviceTests(unittest.TestCase): + def make_device(self, metric=True): + api = Mock() + device = AristonGalevoDevice( + api, + {DeviceAttribute.GW: "gw-1", DeviceAttribute.HPMP_SYS: True}, + is_metric=metric, + language_tag="pt-PT", + ) + device.features = { + DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1, ZoneAttribute.NAME: "Living"}] + } + device.data = self.make_data() + device.menu_items = [ + {"id": MenuItemNames.SIGNAL_STRENGTH.value, PropertyType.VALUE: 4, PropertyType.UNIT: "%"}, + {"id": MenuItemNames.CH_RETURN_TEMP.value, PropertyType.VALUE: 38, PropertyType.UNIT: "°C"}, + ] + return device + + def make_data(self): + items = [] + for item in DeviceProperties: + row = { + "id": item.value, + PropertyType.ZONE: 0, + PropertyType.VALUE: 1, + PropertyType.MIN: 0, + PropertyType.MAX: 99, + PropertyType.STEP: 0.5, + PropertyType.DECIMALS: 1, + PropertyType.UNIT: "°C", + PropertyType.OPTIONS: [mode.value for mode in PlantMode], + PropertyType.OPT_TEXTS: [mode.name for mode in PlantMode], + PropertyType.EXPIRES_ON: "2026-12-31", + } + if item is DeviceProperties.PLANT_MODE: + row[PropertyType.VALUE] = PlantMode.WINTER.value + elif item is DeviceProperties.DHW_MODE: + row[PropertyType.VALUE] = 1 + row[PropertyType.OPTIONS] = [0, 1] + row[PropertyType.OPT_TEXTS] = ["Off", "On"] + elif item is DeviceProperties.HYBRID_MODE: + row[PropertyType.VALUE] = 1 + row[PropertyType.OPTIONS] = [0, 1] + row[PropertyType.OPT_TEXTS] = ["Eco", "Auto"] + elif item is DeviceProperties.BUFFER_CONTROL_MODE: + row[PropertyType.VALUE] = 0 + row[PropertyType.OPTIONS] = [0, 1] + row[PropertyType.OPT_TEXTS] = ["Disabled", "Enabled"] + items.append(row) + + for item in ThermostatProperties: + row = { + "id": item.value, + PropertyType.ZONE: 1, + PropertyType.VALUE: 1, + PropertyType.MIN: 10, + PropertyType.MAX: 30, + PropertyType.STEP: 0.5, + PropertyType.DECIMALS: 1, + PropertyType.UNIT: "°C", + PropertyType.OPTIONS: [mode.value for mode in ZoneMode], + PropertyType.OPT_TEXTS: [mode.name for mode in ZoneMode], + } + if item is ThermostatProperties.ZONE_MODE: + row[PropertyType.VALUE] = ZoneMode.MANUAL.value + items.append(row) + return {"items": items} + + def test_metadata_properties_zone_controls_and_item_lookup_defaults(self): + device = self.make_device() + self.assertTrue(device.plant_mode_supported) + self.assertEqual(device.consumption_type, "Ch%2CCooling") + self.assertEqual(device.umsys, "si") + self.assertEqual(device.language_tag, "pt-PT") + self.assertEqual(device.zones, device.features[DeviceFeatures.ZONES]) + self.assertEqual(device.zone_numbers, [1]) + self.assertEqual(device.water_heater_current_temperature, 1) + device._set_item_by_id(DeviceProperties.DHW_TEMP, 48) + device._set_item_by_id(DeviceProperties.DHW_STORAGE_TEMPERATURE, 62) + self.assertEqual(device.water_heater_current_temperature, 48) + device.custom_features[DeviceProperties.DHW_STORAGE_TEMPERATURE] = True + self.assertEqual(device.water_heater_current_temperature, 62) + device.custom_features[DeviceProperties.DHW_STORAGE_TEMPERATURE] = False + self.assertEqual(device.water_heater_minimum_temperature, 0) + self.assertEqual(device.water_heater_maximum_temperature, 99) + self.assertEqual(device.water_heater_target_temperature, 48) + self.assertEqual(device.water_heater_temperature_decimals, 1) + self.assertEqual(device.water_heater_temperature_unit, "°C") + self.assertEqual(device.water_heater_temperature_step, 0.5) + self.assertEqual(device.water_heater_mode_operation_texts, ["Off", "On"]) + self.assertEqual(device.water_heater_mode_options, [0, 1]) + self.assertEqual(device.water_heater_mode_value, 1) + self.assertEqual(device.get_zone_heat_request_value(1), 1) + self.assertEqual(device.get_zone_economy_temp_value(1), 1) + self.assertTrue(device.is_plant_in_heat_mode) + self.assertFalse(device.is_plant_in_cool_mode) + self.assertTrue(device.is_zone_in_manual_mode(1)) + self.assertFalse(device.is_zone_in_time_program_mode(1)) + self.assertTrue(device.is_zone_mode_options_contains_manual(1)) + self.assertTrue(device.is_zone_mode_options_contains_time_program(1)) + self.assertTrue(device.is_zone_mode_options_contains_off(1)) + self.assertTrue(device.is_plant_mode_options_contains_off) + self.assertTrue(device.is_plant_mode_options_contains_cooling) + self.assertEqual(device.holiday_expires_on, "2026-12-31") + self.assertEqual(device.automatic_thermoregulation, 1) + self.assertEqual(device.heating_circuit_pressure_value, 1) + self.assertEqual(device.heating_circuit_pressure_unit, "°C") + self.assertEqual(device.hybrid_mode, "Auto") + self.assertEqual(device.hybrid_mode_value, 1) + self.assertEqual(device.hybrid_mode_options, [0, 1]) + self.assertEqual(device.hybrid_mode_opt_texts, ["Eco", "Auto"]) + self.assertEqual(device.buffer_control_mode, "Disabled") + self.assertEqual(device.buffer_control_mode_value, 0) + self.assertEqual(device.buffer_control_mode_options, [0, 1]) + self.assertEqual(device.buffer_control_mode_opt_texts, ["Disabled", "Enabled"]) + self.assertEqual(device.is_quiet_value, 1) + self.assertEqual(device.ch_flow_setpoint_temp_value, 1) + self.assertEqual(device.ch_flow_temp_value, 1) + self.assertEqual(device.outside_temp_value, 1) + self.assertEqual(device.outside_temp_unit, "°C") + self.assertEqual(device.ch_flow_setpoint_temp_unit, "°C") + self.assertEqual(device.ch_flow_temp_unit, "°C") + self.assertEqual(device.is_flame_on_value, 1) + self.assertEqual(device.is_heating_pump_on_value, 1) + self.assertEqual(device.holiday_mode_value, 1) + self.assertEqual(device.get_zone_mode(1), ZoneMode.MANUAL) + self.assertEqual(device.get_zone_mode_options(1), [mode.value for mode in ZoneMode]) + self.assertEqual(device.plant_mode, PlantMode.WINTER) + self.assertEqual(device.plant_mode_options, [mode.value for mode in PlantMode]) + self.assertEqual(device.plant_mode_opt_texts, [mode.name for mode in PlantMode]) + self.assertEqual(device.plant_mode_text, PlantMode.WINTER.name) + plant_mode_item = next( + item for item in device.data["items"] if item["id"] == DeviceProperties.PLANT_MODE + ) + plant_mode_item[PropertyType.VALUE] = PlantMode.UNDEFINED.value + plant_mode_item[PropertyType.OPTIONS] = [ + mode.value for mode in PlantMode if mode is not PlantMode.UNDEFINED + ] + self.assertEqual(device.plant_mode_text, PlantMode.UNDEFINED.name) + self.assertEqual(device.signal_strength_value, 4) + self.assertEqual(device.signal_strength_unit, "%") + self.assertEqual(device.ch_return_temp_value, 38) + self.assertEqual(device.ch_return_temp_unit, "°C") + self.assertEqual(device.get_measured_temp_unit(1), "°C") + self.assertEqual(device.get_measured_temp_decimals(1), 1) + self.assertEqual(device.get_measured_temp_value(1), 1) + self.assertEqual(device.get_comfort_temp_min(1), 10) + self.assertEqual(device.get_comfort_temp_max(1), 30) + self.assertEqual(device.get_comfort_temp_step(1), 0.5) + self.assertEqual(device.get_comfort_temp_value(1), 1) + self.assertEqual(device.get_target_temp_step(1), 0.5) + self.assertEqual(device.get_target_temp_value(1), 1) + + for property_name in ( + "get_heating_flow_offset_value", + "get_heating_flow_offset_unit", + "get_heating_flow_offset_step", + "get_heating_flow_offset_max", + "get_heating_flow_offset_min", + "get_heating_flow_offset_decimals", + "get_heating_flow_temp_value", + "get_heating_flow_temp_unit", + "get_heating_flow_temp_step", + "get_heating_flow_temp_max", + "get_heating_flow_temp_min", + "get_heating_flow_temp_decimals", + ): + with self.subTest(property_name=property_name): + self.assertIsNotNone(getattr(device, property_name)(1)) + + self.assertEqual(device._get_item_by_id("missing", PropertyType.VALUE), None) + self.assertEqual(device._get_item_by_id("missing", PropertyType.VALUE, default=7), 7) + self.assertIsNone(device._get_menu_item_by_id(-1, PropertyType.VALUE)) + device.data["items"].append({"id": "Other", PropertyType.ZONE: 2, PropertyType.VALUE: 9}) + self.assertIsNone(device._get_item_by_id("Other", PropertyType.VALUE, 1)) + + us_device = self.make_device(metric=False) + self.assertEqual(us_device.umsys, "us") + us_device.custom_features[CustomDeviceFeatures.HAS_DHW] = False + self.assertEqual(us_device.consumption_type, "Ch%2CCooling") + + def test_features_state_updates_and_sync_async_control_commands(self): + device = self.make_device() + device.features = {DeviceFeatures.HAS_BOILER: True, DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]} + device._get_features() + self.assertTrue(device.custom_features[CustomDeviceFeatures.HAS_DHW]) + device.api.get_features_for_device.return_value = {DeviceFeatures.DHW_PROG_SUPPORTED: True} + device.api.get_properties.return_value = self.make_data() + device.api.get_menu_items.return_value = device.menu_items + device.get_features() + self.assertTrue(device.custom_features[CustomDeviceFeatures.HAS_DHW]) + device.update_state() + self.assertTrue(device.custom_features[CustomDeviceFeatures.HAS_OUTSIDE_TEMP]) + self.assertTrue(device.custom_features[DeviceProperties.DHW_STORAGE_TEMPERATURE]) + self.assertTrue(device.custom_features[DeviceProperties.CH_FLOW_TEMP]) + self.assertTrue(device.custom_features[DeviceProperties.IS_QUIET]) + + device.set_water_heater_temperature(54) + device.set_water_heater_operation_mode("On") + device.set_automatic_thermoregulation(False) + device.set_hybrid_mode("Eco") + device.set_buffer_control_mode("Enabled") + device.set_is_quiet(False) + device.set_plant_mode(PlantMode.COOLING) + device.set_zone_mode(ZoneMode.TIME_PROGRAM, 1) + device.set_comfort_temp(22, 1) + device.set_heating_flow_temp(35, 1) + device.set_heating_flow_offset(2, 1) + device.set_holiday(date(2026, 12, 25)) + self.assertEqual(device.api.set_property.call_count, 11) + self.assertTrue(device.data["items"]) + self.assertTrue(device.api.set_holiday.called) + self.assertTrue(device.holiday_mode_value) + self.assertEqual(device.holiday_expires_on, "2026-12-25T00:00:00") + + no_features = self.make_device() + no_features.features = {} + no_features.api.get_features_for_device.return_value = { + DeviceFeatures.DHW_MODE_CHANGEABLE: True, + DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}], + } + no_features.api.get_properties.return_value = self.make_data() + no_features.api.get_menu_items.return_value = no_features.menu_items + no_features.update_state() + no_features.api.get_features_for_device.assert_called_once_with("gw-1") + + device.api.async_get_features_for_device = AsyncMock(return_value={DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]}) + device.api.async_get_properties = AsyncMock(return_value=self.make_data()) + device.api.async_get_menu_items = AsyncMock(return_value=device.menu_items) + device.api.async_set_property = AsyncMock() + device.api.async_set_holiday = AsyncMock() + + async def async_updates(): + await device.async_get_features() + await device.async_update_state() + await device.async_set_water_heater_temperature(53) + await device.async_set_water_heater_operation_mode("Off") + await device.async_set_automatic_thermoregulation(True) + await device.async_set_hybrid_mode("Auto") + await device.async_set_buffer_control_mode("Disabled") + await device.async_set_is_quiet(True) + await device.async_set_plant_mode(PlantMode.WINTER) + await device.async_set_zone_mode(ZoneMode.MANUAL, 1) + await device.async_set_comfort_temp(21, 1) + await device.async_set_heating_flow_temp(36, 1) + await device.async_set_heating_flow_offset(3, 1) + await device.async_set_holiday(date(2026, 12, 31)) + + asyncio.run(async_updates()) + self.assertEqual(device.api.async_set_property.await_count, 11) + self.assertEqual(device.holiday_expires_on, "2026-12-31T00:00:00") + + async_no_features = self.make_device() + async_no_features.features = {} + async_no_features.api.async_get_features_for_device = AsyncMock(return_value={ + DeviceFeatures.DHW_PROG_SUPPORTED: True, + DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}], + }) + async_no_features.api.async_get_properties = AsyncMock(return_value=self.make_data()) + async_no_features.api.async_get_menu_items = AsyncMock(return_value=async_no_features.menu_items) + + async def refresh_without_features(): + await async_no_features.async_update_state() + + asyncio.run(refresh_without_features()) + async_no_features.api.async_get_features_for_device.assert_awaited_once_with("gw-1") + + def test_consumption_settings_and_energy_account_paths(self): + device = self.make_device() + device.consumptions_settings = { + ConsumptionProperties.ELEC_COST: 0.25, + ConsumptionProperties.GAS_COST: 0.1, + ConsumptionProperties.GAS_TYPE: GasType.NATURAL_GAS.value, + ConsumptionProperties.CURRENCY: Currency.EUR.value, + ConsumptionProperties.GAS_ENERGY_UNIT: GasEnergyUnit.KWH.value, + } + self.assertEqual(device.elect_cost, 0.25) + self.assertEqual(device.gas_cost, 0.1) + self.assertEqual(device.gas_type, GasType.NATURAL_GAS.name) + self.assertEqual(device.currency, Currency.EUR.name) + self.assertEqual(device.gas_energy_unit, GasEnergyUnit.KWH.name) + self.assertEqual(device.get_gas_types(), [item.name for item in GasType]) + self.assertEqual(device.get_currencies(), [item.name for item in Currency]) + self.assertEqual(device.get_gas_energy_units(), [item.name for item in GasEnergyUnit]) + device.consumptions_settings[ConsumptionProperties.GAS_TYPE] = 999 + device.consumptions_settings[ConsumptionProperties.CURRENCY] = 999 + device.consumptions_settings[ConsumptionProperties.GAS_ENERGY_UNIT] = 999 + self.assertIsNone(device.gas_type) + self.assertIsNone(device.currency) + self.assertIsNone(device.gas_energy_unit) + + device.set_gas_type("LPG") + device.set_currency("USD") + device.set_gas_energy_unit("THERM") + device.set_elect_cost(0.3) + device.set_gas_cost(0.2) + self.assertEqual(device.consumptions_settings[ConsumptionProperties.ELEC_COST], 0.3) + self.assertEqual(device.api.set_consumptions_settings.call_count, 5) + device.api.async_set_consumptions_settings = AsyncMock() + + async def update_settings(): + await device.async_set_gas_type("PROPANE") + await device.async_set_currency("EUR") + await device.async_set_gas_energy_unit("MEGA_BTU") + await device.async_set_elect_cost(0.4) + await device.async_set_gas_cost(0.3) + + asyncio.run(update_settings()) + self.assertEqual(device.api.async_set_consumptions_settings.await_count, 5) + self.assertEqual(device.consumptions_settings[ConsumptionProperties.GAS_COST], 0.3) + + device.energy_account = {"LastMonth": [{"gas": 3, "elect": 4, "cool": 5}, {"gas": 6, "elect": 7}]} + self.assertEqual(device.gas_consumption_for_heating_last_month, 3) + self.assertEqual(device.electricity_consumption_for_heating_last_month, 4) + self.assertEqual(device.electricity_consumption_for_cooling_last_month, 5) + self.assertEqual(device.gas_consumption_for_water_last_month, 6) + self.assertEqual(device.electricity_consumption_for_water_last_month, 7) + device.energy_account = {"LastMonth": [{"gas": 1, "elect": 2}]} + self.assertIsNone(device.gas_consumption_for_water_last_month) + self.assertIsNone(device.electricity_consumption_for_water_last_month) + device.energy_account = {} + self.assertIsNone(device.gas_consumption_for_heating_last_month) + self.assertIsNone(device.electricity_consumption_for_heating_last_month) + self.assertIsNone(device.electricity_consumption_for_cooling_last_month) + + sequences = [ + {"k": ConsumptionType.CENTRAL_HEATING_TOTAL_ENERGY.value, "p": ConsumptionTimeInterval.LAST_MONTH.value, "v": [1, 2]}, + {"k": ConsumptionType.CENTRAL_COOLING_TOTAL_ENERGY.value, "p": ConsumptionTimeInterval.LAST_MONTH.value, "v": [3, 4]}, + {"k": ConsumptionType.CENTRAL_HEATING_TOTAL_ENERGY.value, "p": ConsumptionTimeInterval.LAST_DAY.value, "v": [99]}, + ] + device.consumptions_sequences = sequences + self.assertEqual(device._calc_energy_account(), {"LastMonth": [{"elect": 3, "cool": 7}]}) + device.api.get_consumptions_sequences.return_value = sequences + device.api.get_consumptions_settings.return_value = {"saved": True} + device.api.get_energy_account.return_value = {} + device.update_energy() + self.assertEqual(device.energy_account, {"LastMonth": [{"elect": 3, "cool": 7}]}) + self.assertEqual(device.consumptions_settings, {"saved": True}) + + device.api.async_get_consumptions_sequences = AsyncMock(return_value=sequences) + device.api.async_get_consumptions_settings = AsyncMock(return_value={"async": True}) + device.api.async_get_energy_account = AsyncMock(return_value={"LastMonth": [{"gas": 1}]}) + asyncio.run(device.async_update_energy()) + self.assertEqual(device.energy_account, {"LastMonth": [{"gas": 1}]}) + self.assertEqual(device.consumptions_settings, {"async": True}) + device.api.async_get_energy_account.return_value = {"LastMonth": []} + asyncio.run(device.async_update_energy()) + self.assertEqual(device.energy_account, {"LastMonth": [{"elect": 3, "cool": 7}]}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_public_api.py b/tests/test_public_api.py new file mode 100644 index 0000000..6dd0819 --- /dev/null +++ b/tests/test_public_api.py @@ -0,0 +1,180 @@ +"""Tests for the synchronous and asynchronous public discovery helpers.""" + +import asyncio +import unittest +from unittest.mock import AsyncMock, Mock, patch + +import ariston +from ariston.const import DeviceAttribute, SystemType, VelisDeviceAttribute, WheType +from ariston.evo_device import AristonEvoDevice +from ariston.evo_one_device import AristonEvoOneDevice +from ariston.galevo_device import AristonGalevoDevice +from ariston.lux2_device import AristonLux2Device +from ariston.lux_device import AristonLuxDevice +from ariston.lydos_device import AristonLydosDevice +from ariston.lydos_hybrid_device import AristonLydosHybridDevice +from ariston.nuos_split_device import AristonNuosSplitDevice +from ariston.bsb_device import AristonBsbDevice + + +class AristonPublicApiTests(unittest.TestCase): + def test_device_factory_selects_each_supported_system_and_water_heater(self): + api = Mock() + self.assertIsNone(ariston._get_device([], api, "missing")) + + galevo = ariston._get_device( + [{DeviceAttribute.GW: "gw-1", DeviceAttribute.SYS: SystemType.GALEVO.value}], + api, + "gw-1", + False, + "pt-PT", + ) + self.assertIsInstance(galevo, AristonGalevoDevice) + self.assertEqual(galevo.umsys, "us") + self.assertEqual(galevo.language_tag, "pt-PT") + + bsb = ariston._get_device( + [{DeviceAttribute.GW: "gw-2", DeviceAttribute.SYS: SystemType.BSB.value}], + api, + "gw-2", + ) + self.assertIsInstance(bsb, AristonBsbDevice) + + expected_types = { + WheType.Evo: AristonEvoOneDevice, + WheType.LydosHybrid: AristonLydosHybridDevice, + WheType.Lydos: AristonLydosDevice, + WheType.NuosSplit: AristonNuosSplitDevice, + WheType.Andris2: AristonEvoDevice, + WheType.Evo2: AristonEvoDevice, + WheType.Lux2: AristonLux2Device, + WheType.Lux: AristonLuxDevice, + } + for whe_type, expected_class in expected_types.items(): + with self.subTest(whe_type=whe_type): + device = ariston._get_device( + [ + { + DeviceAttribute.GW: "velis-1", + DeviceAttribute.SYS: SystemType.VELIS.value, + VelisDeviceAttribute.WHE_TYPE: whe_type.value, + } + ], + api, + "velis-1", + ) + self.assertIsInstance(device, expected_class) + + unsupported_type = ariston._get_device( + [ + { + DeviceAttribute.GW: "bad-velis", + DeviceAttribute.SYS: SystemType.VELIS.value, + VelisDeviceAttribute.WHE_TYPE: 999, + } + ], + api, + "bad-velis", + ) + self.assertIsNone(unsupported_type) + unsupported_system = ariston._get_device( + [{DeviceAttribute.GW: "unknown", DeviceAttribute.SYS: -1}], api, "unknown" + ) + self.assertIsNone(unsupported_system) + + def test_sync_connect_discover_and_hello_helpers(self): + api = Mock() + api.get_detailed_devices.return_value = [{"gw": "remote"}] + api.get_detailed_velis_devices.return_value = [{"gw": "velis"}] + with patch.object(ariston, "AristonAPI", return_value=api) as constructor: + connected_api = ariston._connect("user", "secret", "https://api.test/", "agent") + constructor.assert_called_once_with("user", "secret", "https://api.test/", "agent") + api.connect.assert_called_once_with() + self.assertIs(connected_api, api) + + self.assertEqual(ariston._discover(api), [{"gw": "remote"}, {"gw": "velis"}]) + api.get_detailed_devices.assert_called_once_with() + api.get_detailed_velis_devices.assert_called_once_with() + + with patch.object(ariston, "_connect", return_value=api) as connect: + self.assertEqual(ariston.discover("user", "secret", "https://api.test/"), [{"gw": "remote"}, {"gw": "velis"}]) + connect.assert_called_once_with("user", "secret", "https://api.test/") + + with patch.object(ariston, "_connect", return_value=api), patch.object( + ariston, "_discover", return_value=[ + {DeviceAttribute.GW: "gw-1", DeviceAttribute.SYS: SystemType.BSB.value} + ] + ): + device = ariston.hello("user", "secret", "gw-1", api_url="https://api.test/") + self.assertIsInstance(device, AristonBsbDevice) + + def test_async_facade_and_discovery_helpers(self): + api = Mock() + api.async_connect = AsyncMock(return_value=True) + api.async_get_detailed_devices = AsyncMock(return_value=[{"gw": "remote"}]) + api.async_get_detailed_velis_devices = AsyncMock(return_value=[{"gw": "velis"}]) + + async def exercise_helpers(): + connected = await ariston._async_connect("user", "secret") + self.assertIs(connected, api) + self.assertEqual(await ariston._async_discover(api), [{"gw": "remote"}, {"gw": "velis"}]) + self.assertEqual(await ariston.async_discover("user", "secret"), [{"gw": "remote"}, {"gw": "velis"}]) + + with patch.object(ariston, "AristonAPI", return_value=api): + asyncio.run(exercise_helpers()) + self.assertGreaterEqual(api.async_connect.await_count, 2) + + failed_api = Mock() + failed_api.async_connect = AsyncMock(return_value=False) + + async def assert_failed_connect(): + with self.assertRaises(ariston.ConnectionException): + await ariston._async_connect("user", "wrong") + + with patch.object(ariston, "AristonAPI", return_value=failed_api): + asyncio.run(assert_failed_connect()) + + facade = ariston.Ariston() + self.assertIsNone(facade.api) + self.assertEqual(facade.cloud_devices, []) + self.assertEqual(asyncio.run(facade.async_discover()), []) + self.assertIsNone(asyncio.run(facade.async_hello("gw-1"))) + + facade.api = api + api.async_connect = AsyncMock(return_value=True) + api.async_get_detailed_devices = AsyncMock(return_value=[]) + api.async_get_detailed_velis_devices = AsyncMock(return_value=[]) + api.async_get_features_for_device = AsyncMock(return_value=None) + + async def facade_connect_discover(): + self.assertTrue(await facade.async_connect("user", "secret")) + self.assertEqual(await facade.async_discover(), []) + self.assertIsNone(await facade.async_hello("missing")) + + with patch.object(ariston, "AristonAPI", return_value=api): + asyncio.run(facade_connect_discover()) + + def test_async_hello_builds_selected_device(self): + api = Mock() + api.async_connect = AsyncMock(return_value=True) + api.async_get_detailed_devices = AsyncMock(return_value=[]) + api.async_get_detailed_velis_devices = AsyncMock( + return_value=[ + { + DeviceAttribute.GW: "gw-1", + DeviceAttribute.SYS: SystemType.VELIS.value, + VelisDeviceAttribute.WHE_TYPE: WheType.Evo.value, + } + ] + ) + + async def run(): + return await ariston.async_hello("user", "secret", "gw-1") + + with patch.object(ariston, "AristonAPI", return_value=api): + device = asyncio.run(run()) + self.assertIsInstance(device, AristonEvoOneDevice) + + +if __name__ == "__main__": + unittest.main()