From 1effa7bf6697e278d095558ce9dd4db9df953842 Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:26:40 +0200 Subject: [PATCH] Add dynamic devices to Renault (#187301) --- .../components/renault/binary_sensor.py | 5 +- homeassistant/components/renault/button.py | 5 +- homeassistant/components/renault/const.py | 4 + .../components/renault/coordinator.py | 65 ++- .../components/renault/device_tracker.py | 5 +- homeassistant/components/renault/number.py | 5 +- .../components/renault/quality_scale.yaml | 2 +- .../components/renault/renault_hub.py | 159 +++++-- homeassistant/components/renault/select.py | 5 +- homeassistant/components/renault/sensor.py | 5 +- tests/components/renault/test_init.py | 432 +++++++++++++++++- tests/components/renault/test_sensor.py | 22 +- 12 files changed, 659 insertions(+), 55 deletions(-) diff --git a/homeassistant/components/renault/binary_sensor.py b/homeassistant/components/renault/binary_sensor.py index 5c782bd2b4fd..d4d407a17cff 100644 --- a/homeassistant/components/renault/binary_sensor.py +++ b/homeassistant/components/renault/binary_sensor.py @@ -63,8 +63,9 @@ async def async_setup_entry( if description.coordinator in vehicle.coordinators ) - for vehicle in config_entry.runtime_data.vehicles.values(): - _async_add_vehicle(vehicle) + config_entry.async_on_unload( + config_entry.runtime_data.async_add_vehicle_listener(_async_add_vehicle) + ) class RenaultBinarySensor[T: KamereonVehicleDataAttributes]( diff --git a/homeassistant/components/renault/button.py b/homeassistant/components/renault/button.py index e78db15b0d22..c27d3e40dec2 100644 --- a/homeassistant/components/renault/button.py +++ b/homeassistant/components/renault/button.py @@ -40,8 +40,9 @@ async def async_setup_entry( if description.is_supported(vehicle) ) - for vehicle in config_entry.runtime_data.vehicles.values(): - _async_add_vehicle(vehicle) + config_entry.async_on_unload( + config_entry.runtime_data.async_add_vehicle_listener(_async_add_vehicle) + ) class RenaultButtonEntity(RenaultEntity, ButtonEntity): diff --git a/homeassistant/components/renault/const.py b/homeassistant/components/renault/const.py index 7ad5167fc710..64870309d5cd 100644 --- a/homeassistant/components/renault/const.py +++ b/homeassistant/components/renault/const.py @@ -1,5 +1,6 @@ """Constants for the Renault component.""" +from datetime import timedelta from typing import Final from homeassistant.const import Platform @@ -22,6 +23,9 @@ class RenaultConfigurationKeys: # for a single car and the 7 coordinator, it is a scan every 7mn MAX_CALLS_PER_HOURS = 60 +# Interval to check the account for added or removed vehicles +VEHICLE_LIST_SCAN_INTERVAL = timedelta(hours=1) + # If throttled time to pause the updates, in seconds COOLING_UPDATES_SECONDS = 60 * 15 # 15 minutes diff --git a/homeassistant/components/renault/coordinator.py b/homeassistant/components/renault/coordinator.py index 363a07fc4964..5a52243655f1 100644 --- a/homeassistant/components/renault/coordinator.py +++ b/homeassistant/components/renault/coordinator.py @@ -13,18 +13,24 @@ from renault_api.kamereon.exceptions import ( NotSupportedException, QuotaLimitException, ) -from renault_api.kamereon.models import KamereonVehicleDataAttributes +from renault_api.kamereon.models import ( + KamereonVehicleDataAttributes, + KamereonVehiclesLink, +) +from renault_api.renault_account import RenaultAccount from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed -from .const import DOMAIN +from .const import DOMAIN, VEHICLE_LIST_SCAN_INTERVAL if TYPE_CHECKING: from . import RenaultConfigEntry from .renault_hub import RenaultHub +_LOGGER = logging.getLogger(__name__) + # We have potentially 7 coordinators per vehicle _PARALLEL_SEMAPHORE = asyncio.Semaphore(1) @@ -143,3 +149,58 @@ class RenaultDataUpdateCoordinator[T: KamereonVehicleDataAttributes]( but only updating the `access_denied` and `not_supported` flags. """ await self._async_refresh(log_failures=False, raise_on_auth_failed=True) + + +class RenaultVehicleListCoordinator(DataUpdateCoordinator[list[KamereonVehiclesLink]]): + """Handle the list of vehicles linked to the Kamereon account.""" + + config_entry: RenaultConfigEntry + + def __init__( + self, + hass: HomeAssistant, + config_entry: RenaultConfigEntry, + hub: RenaultHub, + account: RenaultAccount, + ) -> None: + """Initialise coordinator.""" + super().__init__( + hass, + _LOGGER, + config_entry=config_entry, + name=f"{account.account_id} vehicles", + update_interval=VEHICLE_LIST_SCAN_INTERVAL, + ) + self._account = account + self._hub = hub + + @override + async def _async_update_data(self) -> list[KamereonVehiclesLink]: + """Fetch the latest vehicle list from the source.""" + if self._hub.is_throttled(): + return self.data + + try: + async with _PARALLEL_SEMAPHORE: + vehicles = await self._account.get_vehicles() + + except QuotaLimitException as err: + self._hub.set_throttled() + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="throttled", + ) from err + + except NotAuthenticatedException as err: + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, + translation_key="authentication_expired", + ) from err + + except KamereonResponseException as err: + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="communication_error", + ) from err + + return vehicles.vehicleLinks or [] diff --git a/homeassistant/components/renault/device_tracker.py b/homeassistant/components/renault/device_tracker.py index 12bc32d7f459..24a75a817323 100644 --- a/homeassistant/components/renault/device_tracker.py +++ b/homeassistant/components/renault/device_tracker.py @@ -42,8 +42,9 @@ async def async_setup_entry( if description.coordinator in vehicle.coordinators ) - for vehicle in config_entry.runtime_data.vehicles.values(): - _async_add_vehicle(vehicle) + config_entry.async_on_unload( + config_entry.runtime_data.async_add_vehicle_listener(_async_add_vehicle) + ) class RenaultDeviceTracker( diff --git a/homeassistant/components/renault/number.py b/homeassistant/components/renault/number.py index 215da34ce25a..0d06bb991e0f 100644 --- a/homeassistant/components/renault/number.py +++ b/homeassistant/components/renault/number.py @@ -104,8 +104,9 @@ async def async_setup_entry( if description.coordinator in vehicle.coordinators ) - for vehicle in config_entry.runtime_data.vehicles.values(): - _async_add_vehicle(vehicle) + config_entry.async_on_unload( + config_entry.runtime_data.async_add_vehicle_listener(_async_add_vehicle) + ) class RenaultNumberEntity[T: KamereonVehicleDataAttributes]( diff --git a/homeassistant/components/renault/quality_scale.yaml b/homeassistant/components/renault/quality_scale.yaml index e29fe278377d..9d6579e0735e 100644 --- a/homeassistant/components/renault/quality_scale.yaml +++ b/homeassistant/components/renault/quality_scale.yaml @@ -53,7 +53,7 @@ rules: docs-supported-functions: done docs-troubleshooting: done docs-use-cases: done - dynamic-devices: todo + dynamic-devices: done entity-category: done entity-device-class: done entity-disabled-by-default: done diff --git a/homeassistant/components/renault/renault_hub.py b/homeassistant/components/renault/renault_hub.py index 727debad6d95..a0c0c1834ce0 100644 --- a/homeassistant/components/renault/renault_hub.py +++ b/homeassistant/components/renault/renault_hub.py @@ -1,14 +1,17 @@ """Proxy to handle account communication with Renault servers.""" import asyncio +from collections.abc import Callable import contextlib from datetime import timedelta import logging from time import time from typing import TYPE_CHECKING +import aiohttp from renault_api.exceptions import NotAuthenticatedException from renault_api.gigya.exceptions import ( + GigyaException, InvalidCredentialsException, PendingTwoFactorAuthenticationException, ) @@ -18,8 +21,8 @@ from renault_api.kamereon.models import KamereonVehiclesLink from renault_api.renault_account import RenaultAccount from renault_api.renault_client import RenaultClient -from homeassistant.core import HomeAssistant, callback -from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback +from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers import device_registry as dr from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -29,6 +32,7 @@ from .const import ( MAX_CALLS_PER_HOURS, RenaultConfigurationKeys, ) +from .coordinator import RenaultVehicleListCoordinator from .renault_vehicle import COORDINATORS, RenaultVehicleProxy if TYPE_CHECKING: @@ -40,17 +44,22 @@ LOGGER = logging.getLogger(__name__) async def _get_filtered_vehicles(account: RenaultAccount) -> list[KamereonVehiclesLink]: """Get the vehicles, filtering out those with missing details.""" vehicles = await account.get_vehicles() - return await _filter_vehicles_with_details(account, vehicles.vehicleLinks or []) + return await _filter_vehicles_with_details( + account, vehicles.vehicleLinks or [], set() + ) async def _filter_vehicles_with_details( - account: RenaultAccount, vehicle_links: list[KamereonVehiclesLink] + account: RenaultAccount, + vehicle_links: list[KamereonVehiclesLink], + missing_details_vins: set[str | None], ) -> list[KamereonVehiclesLink]: """Filter out the vehicles with missing details. The vehicle list sometimes omits the details, so they are requested separately. They may still be missing for new purchases, or due to an - issue with the Renault servers. + issue with the Renault servers. A warning is logged once for each vehicle, + `missing_details_vins` keeps track of the vehicles already logged. """ result: list[KamereonVehiclesLink] = [] for link in vehicle_links: @@ -59,12 +68,22 @@ async def _filter_vehicles_with_details( with contextlib.suppress(KamereonResponseException): link.vehicleDetails = await vehicle.get_details() if link.vehicleDetails is None: - LOGGER.warning("Ignoring vehicle with missing details: %s", link.vin) + if link.vin in missing_details_vins: + LOGGER.debug("Ignoring vehicle with missing details: %s", link.vin) + else: + LOGGER.warning("Ignoring vehicle with missing details: %s", link.vin) + missing_details_vins.add(link.vin) continue result.append(link) return result +def _get_scan_interval(num_call_per_scan: int) -> timedelta: + """Get the scan interval that keeps the calls within the hourly limit.""" + # One call per hour is kept for the vehicle list. + return timedelta(seconds=(3600 * num_call_per_scan) / (MAX_CALLS_PER_HOURS - 1)) + + class RenaultHub: """Handle account communication with Renault servers.""" @@ -75,7 +94,11 @@ class RenaultHub: websession=async_get_clientsession(self._hass), locale=locale ) self._account: RenaultAccount | None = None + self._config_entry: RenaultConfigEntry | None = None self._vehicles: dict[str, RenaultVehicleProxy] = {} + self._vehicle_listeners: list[Callable[[RenaultVehicleProxy], None]] = [] + self._vehicles_lock = asyncio.Lock() + self._missing_details_vins: set[str | None] = set() self._got_throttled_at_time: float | None = None @@ -167,11 +190,12 @@ class RenaultHub: RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID ] + self._config_entry = config_entry self._account = await self._client.get_api_account(account_id) vehicles = await self._account.get_vehicles() all_vehicle_links = vehicles.vehicleLinks or [] vehicle_links = await _filter_vehicles_with_details( - self._account, all_vehicle_links + self._account, all_vehicle_links, self._missing_details_vins ) # An empty list is more likely a server issue than all vehicles removed. if vins := {link.vin for link in all_vehicle_links if link.vin}: @@ -185,39 +209,110 @@ class RenaultHub: translation_key="no_vehicle_details", ) - num_call_per_scan = len(COORDINATORS) * len(vehicle_links) - scan_interval = timedelta( - seconds=(3600 * num_call_per_scan) / MAX_CALLS_PER_HOURS + await self._async_add_vehicles(vehicle_links) + + vehicle_list = RenaultVehicleListCoordinator( + self._hass, config_entry, self, self._account + ) + vehicle_list.async_set_updated_data(all_vehicle_links) + config_entry.async_on_unload( + vehicle_list.async_add_listener( + lambda: self._async_vehicle_list_updated(vehicle_list.data) + ) + ) + + async def _async_add_vehicles( + self, vehicle_links: list[KamereonVehiclesLink] + ) -> None: + """Set up vehicles and adjust the scan interval of all vehicles.""" + assert self._account is not None + assert self._config_entry is not None + # Assume all coordinators until the endpoints of the new vehicles are checked. + scan_interval = _get_scan_interval( + sum(len(vehicle.coordinators) for vehicle in self._vehicles.values()) + + len(COORDINATORS) * len(vehicle_links) ) device_registry = dr.async_get(self._hass) - await asyncio.gather( + results = await asyncio.gather( *( self.async_initialise_vehicle( vehicle_link, self._account, scan_interval, - config_entry, + self._config_entry, device_registry, ) for vehicle_link in vehicle_links - ) + ), + return_exceptions=True, + ) + self._async_update_scan_interval() + for result in results: + if isinstance(result, BaseException): + raise result + + @callback + def _async_update_scan_interval(self) -> None: + """Set the scan interval of all vehicles from their active coordinators.""" + scan_interval = _get_scan_interval( + sum(len(vehicle.coordinators) for vehicle in self._vehicles.values()) + ) + for vehicle in self._vehicles.values(): + vehicle.update_scan_interval(scan_interval) + + @callback + def _async_vehicle_list_updated( + self, vehicle_links: list[KamereonVehiclesLink] + ) -> None: + """Add and remove vehicles when the vehicle list changes.""" + # Listeners are also called with the previous list while throttled. + if self.is_throttled(): + return + if {link.vin for link in vehicle_links if link.vin} == set(self._vehicles): + return + assert self._config_entry is not None + self._config_entry.async_create_background_task( + self._hass, + self._async_update_vehicles(vehicle_links), + "renault_update_vehicles", ) - # all vehicles have been initiated with the right number of active coordinators - num_call_per_scan = 0 - for vehicle_link in vehicle_links: - vehicle = self._vehicles[str(vehicle_link.vin)] - num_call_per_scan += len(vehicle.coordinators) + async def _async_update_vehicles( + self, vehicle_links: list[KamereonVehiclesLink] + ) -> None: + """Add new vehicles and remove the vehicles no longer in the account.""" + assert self._account is not None + assert self._config_entry is not None + async with self._vehicles_lock: + # An empty list is more likely a server issue than all vehicles removed. + if vins := {link.vin for link in vehicle_links if link.vin}: + self._async_remove_stale_devices(self._config_entry, vins) + for vin in set(self._vehicles) - vins: + vehicle = self._vehicles.pop(vin) + for coordinator in vehicle.coordinators.values(): + await coordinator.async_shutdown() + self._async_update_scan_interval() - new_scan_interval = timedelta( - seconds=(3600 * num_call_per_scan) / MAX_CALLS_PER_HOURS - ) - if new_scan_interval != scan_interval: - # we need to change the vehicles with the right scan interval - for vehicle_link in vehicle_links: - vehicle = self._vehicles[str(vehicle_link.vin)] - vehicle.update_scan_interval(new_scan_interval) + try: + new_vehicle_links = await _filter_vehicles_with_details( + self._account, + [ + link + for link in vehicle_links + if link.vin and link.vin not in self._vehicles + ], + self._missing_details_vins, + ) + if new_vehicle_links: + await self._async_add_vehicles(new_vehicle_links) + except ConfigEntryAuthFailed, NotAuthenticatedException: + self._config_entry.async_start_reauth(self._hass) + except (aiohttp.ClientError, TimeoutError, GigyaException) as err: + LOGGER.debug( + "Failed to update the vehicles, retrying at the next check: %s", + err, + ) @callback def _async_remove_stale_devices( @@ -234,6 +329,16 @@ class RenaultHub: ): device_registry.async_remove_device(device_entry.id) + @callback + def async_add_vehicle_listener( + self, add_vehicle: Callable[[RenaultVehicleProxy], None] + ) -> CALLBACK_TYPE: + """Call add_vehicle for the current vehicles and each vehicle added later.""" + for vehicle in self._vehicles.values(): + add_vehicle(vehicle) + self._vehicle_listeners.append(add_vehicle) + return lambda: self._vehicle_listeners.remove(add_vehicle) + async def async_initialise_vehicle( self, vehicle_link: KamereonVehiclesLink, @@ -265,6 +370,8 @@ class RenaultHub: sw_version=None, # cleanup from PR #125399 ) self._vehicles[vehicle_link.vin] = vehicle + for add_vehicle in self._vehicle_listeners: + add_vehicle(vehicle) async def get_account_ids(self) -> list[str]: """Get Kamereon account ids.""" diff --git a/homeassistant/components/renault/select.py b/homeassistant/components/renault/select.py index dabec383b24f..3d58e9229d07 100644 --- a/homeassistant/components/renault/select.py +++ b/homeassistant/components/renault/select.py @@ -47,8 +47,9 @@ async def async_setup_entry( if description.coordinator in vehicle.coordinators ) - for vehicle in config_entry.runtime_data.vehicles.values(): - _async_add_vehicle(vehicle) + config_entry.async_on_unload( + config_entry.runtime_data.async_add_vehicle_listener(_async_add_vehicle) + ) class RenaultSelectEntity[T: KamereonVehicleDataAttributes]( diff --git a/homeassistant/components/renault/sensor.py b/homeassistant/components/renault/sensor.py index 266f0ef3eb9f..f06deb789bab 100644 --- a/homeassistant/components/renault/sensor.py +++ b/homeassistant/components/renault/sensor.py @@ -76,8 +76,9 @@ async def async_setup_entry( ) ) - for vehicle in config_entry.runtime_data.vehicles.values(): - _async_add_vehicle(vehicle) + config_entry.async_on_unload( + config_entry.runtime_data.async_add_vehicle_listener(_async_add_vehicle) + ) class RenaultSensor[T: KamereonVehicleDataAttributes]( diff --git a/tests/components/renault/test_init.py b/tests/components/renault/test_init.py index fa8bbfe7c2a1..477718a1066d 100644 --- a/tests/components/renault/test_init.py +++ b/tests/components/renault/test_init.py @@ -1,11 +1,17 @@ """Tests for Renault setup process.""" from collections.abc import Generator +from datetime import timedelta from unittest.mock import AsyncMock, Mock, patch import aiohttp +from freezegun.api import FrozenDateTimeFactory import pytest -from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.common import ( + MockConfigEntry, + async_fire_time_changed, + load_fixture, +) from pytest_homeassistant.typing import WebSocketGenerator from renault_api.exceptions import NotAuthenticatedException from renault_api.gigya.exceptions import ( @@ -13,19 +19,30 @@ from renault_api.gigya.exceptions import ( InvalidCredentialsException, PendingTwoFactorAuthenticationException, ) -from renault_api.kamereon import models +from renault_api.kamereon import exceptions, models, schemas +from renault_api.kamereon.models import KamereonVehicleCockpitData from renault_api.renault_session import RenaultSession +from renault_api.renault_vehicle import RenaultVehicle from syrupy.assertion import SnapshotAssertion -from homeassistant.components.renault.const import DOMAIN, RenaultConfigurationKeys +from homeassistant.components.renault.const import ( + DOMAIN, + VEHICLE_LIST_SCAN_INTERVAL, + RenaultConfigurationKeys, +) from homeassistant.config_entries import ( SOURCE_REAUTH, SOURCE_USER, ConfigEntry, ConfigEntryState, ) +from homeassistant.const import Platform from homeassistant.core import HomeAssistant -from homeassistant.helpers import device_registry as dr, issue_registry as ir +from homeassistant.helpers import ( + device_registry as dr, + entity_registry as er, + issue_registry as ir, +) from homeassistant.setup import async_setup_component from .const import ( @@ -503,3 +520,410 @@ async def test_registry_cleanup( device_registry.async_get_device_by_identifier((DOMAIN, dead_id), entry_id) is None ) + + +ZOE_VIN = "VF1ZOE40VIN" +CAPTUR_VIN = "VF1CAPTURFUELVIN" +ZOE_50_VIN = "VF1ZOE50VIN" +# Listed in the zoe_40 fixture, without vehicle details. +MISSING_DETAILS_VIN = "VYSP0100875XXXXXX" + + +def _get_vehicles(*vins: str) -> models.KamereonVehiclesResponse: + """Return a vehicle list with the given vehicles.""" + response: models.KamereonVehiclesResponse = ( + schemas.KamereonVehiclesResponseSchema.loads( + load_fixture("renault/vehicle_zoe_40.json") + ) + ) + links = [ + *(response.vehicleLinks or []), + *( + link + for fixture in ("captur_fuel", "zoe_50") + for link in schemas.KamereonVehiclesResponseSchema.loads( + load_fixture(f"renault/vehicle_{fixture}.json") + ).vehicleLinks + or [] + ), + ] + response.vehicleLinks = [link for link in links if link.vin in vins] + return response + + +@pytest.fixture(name="sensor_platform") +def override_sensor_platform() -> Generator[None]: + """Set up the sensor platform only.""" + with patch("homeassistant.components.renault.PLATFORMS", [Platform.SENSOR]): + yield + + +@pytest.fixture(name="mock_get_vehicles") +def patch_get_vehicles() -> Generator[AsyncMock]: + """Mock the vehicle list, with the Zoe only.""" + with patch( + "renault_api.renault_account.RenaultAccount.get_vehicles", + return_value=_get_vehicles(ZOE_VIN), + ) as mock_get_vehicles: + yield mock_get_vehicles + + +async def _async_poll_vehicle_list( + hass: HomeAssistant, freezer: FrozenDateTimeFactory +) -> None: + """Trigger the next vehicle list update.""" + freezer.tick(VEHICLE_LIST_SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + +def _device_vins( + device_registry: dr.DeviceRegistry, config_entry: ConfigEntry +) -> set[str]: + """Return the VINs of the vehicle devices of the config entry.""" + return { + identifier + for device in dr.async_entries_for_config_entry( + device_registry, config_entry.entry_id + ) + for domain, identifier in device.identifiers + if domain == DOMAIN + } + + +def _vehicle_entities( + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + config_entry: ConfigEntry, + vin: str, +) -> list[er.RegistryEntry]: + """Return the entities of a vehicle, after checking its device exists.""" + device = device_registry.async_get_device_by_identifier( + (DOMAIN, vin), config_entry.entry_id + ) + assert device is not None + return er.async_entries_for_device(entity_registry, device.id) + + +@pytest.mark.usefixtures( + "patch_renault_account", "fixtures_with_data", "sensor_platform" +) +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +async def test_vehicle_added( + hass: HomeAssistant, + config_entry: ConfigEntry, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, +) -> None: + """Test a vehicle added to the account is set up without a reload.""" + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + assert ( + device_registry.async_get_device_by_identifier( + (DOMAIN, CAPTUR_VIN), config_entry.entry_id + ) + is None + ) + + mock_get_vehicles.return_value = _get_vehicles(ZOE_VIN, CAPTUR_VIN) + await _async_poll_vehicle_list(hass, freezer) + + assert _device_vins(device_registry, config_entry) == {ZOE_VIN, CAPTUR_VIN} + entities = _vehicle_entities( + device_registry, entity_registry, config_entry, CAPTUR_VIN + ) + assert entities + assert all(hass.states.get(entity.entity_id) for entity in entities) + + +@pytest.mark.usefixtures("patch_renault_account", "sensor_platform") +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +async def test_vehicle_added_with_failed_sibling( + hass: HomeAssistant, + config_entry: ConfigEntry, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, + fixtures_with_data: dict[str, AsyncMock], +) -> None: + """Test a vehicle added to the account gets its entities when another fails.""" + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + cockpit = fixtures_with_data["cockpit"].return_value + + async def _get_cockpit(vehicle: RenaultVehicle) -> KamereonVehicleCockpitData: + if vehicle.vin == ZOE_50_VIN: + raise NotAuthenticatedException("Not logged in") + return cockpit + + mock_get_vehicles.return_value = _get_vehicles(ZOE_VIN, CAPTUR_VIN, ZOE_50_VIN) + with patch.object(RenaultVehicle, "get_cockpit", _get_cockpit): + await _async_poll_vehicle_list(hass, freezer) + + assert _device_vins(device_registry, config_entry) == {ZOE_VIN, CAPTUR_VIN} + entities = _vehicle_entities( + device_registry, entity_registry, config_entry, CAPTUR_VIN + ) + assert entities + assert all(hass.states.get(entity.entity_id) for entity in entities) + # The scan interval of all vehicles is adjusted despite the failure. + assert ( + len( + { + coordinator.update_interval + for vehicle in config_entry.runtime_data.vehicles.values() + for coordinator in vehicle.coordinators.values() + } + ) + == 1 + ) + flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN) + assert len(flows) == 1 + assert flows[0]["context"]["source"] == SOURCE_REAUTH + + +@pytest.mark.usefixtures( + "patch_renault_account", "fixtures_with_data", "sensor_platform" +) +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +async def test_vehicle_removed( + hass: HomeAssistant, + config_entry: ConfigEntry, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, +) -> None: + """Test a vehicle removed from the account is removed without a reload.""" + mock_get_vehicles.return_value = _get_vehicles(ZOE_VIN, CAPTUR_VIN) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + entities = _vehicle_entities( + device_registry, entity_registry, config_entry, CAPTUR_VIN + ) + assert entities + + mock_get_vehicles.return_value = _get_vehicles(ZOE_VIN) + await _async_poll_vehicle_list(hass, freezer) + + assert _device_vins(device_registry, config_entry) == {ZOE_VIN} + assert ( + device_registry.async_get_device_by_identifier( + (DOMAIN, CAPTUR_VIN), config_entry.entry_id + ) + is None + ) + assert not any(entity_registry.async_get(entity.entity_id) for entity in entities) + assert not any(hass.states.get(entity.entity_id) for entity in entities) + assert _vehicle_entities(device_registry, entity_registry, config_entry, ZOE_VIN) + + +@pytest.mark.usefixtures("patch_renault_account", "fixtures_with_data") +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +async def test_vehicle_list_empty( + hass: HomeAssistant, + config_entry: ConfigEntry, + device_registry: dr.DeviceRegistry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, +) -> None: + """Test an empty vehicle list does not remove the vehicles.""" + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + mock_get_vehicles.return_value = _get_vehicles() + await _async_poll_vehicle_list(hass, freezer) + + assert _device_vins(device_registry, config_entry) == {ZOE_VIN} + assert device_registry.async_get_device_by_identifier( + (DOMAIN, ZOE_VIN), config_entry.entry_id + ) + + +@pytest.mark.usefixtures("patch_renault_account", "fixtures_with_data") +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +async def test_vehicle_missing_details_retried( + hass: HomeAssistant, + config_entry: ConfigEntry, + device_registry: dr.DeviceRegistry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, + mock_get_vehicle_details: AsyncMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test the details of a vehicle are requested again at the next update.""" + mock_get_vehicles.return_value = _get_vehicles(ZOE_VIN, MISSING_DETAILS_VIN) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + assert mock_get_vehicle_details.await_count == 1 + assert [ + record.levelname + for record in caplog.records + if record.getMessage() + == f"Ignoring vehicle with missing details: {MISSING_DETAILS_VIN}" + ] == ["WARNING"] + + caplog.clear() + await _async_poll_vehicle_list(hass, freezer) + + assert mock_get_vehicle_details.await_count == 2 + # The warning is only logged once for each vehicle. + assert [ + record.levelname + for record in caplog.records + if record.getMessage() + == f"Ignoring vehicle with missing details: {MISSING_DETAILS_VIN}" + ] == ["DEBUG"] + assert _device_vins(device_registry, config_entry) == {ZOE_VIN} + + +@pytest.mark.usefixtures("patch_renault_account", "fixtures_with_data") +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +@pytest.mark.parametrize( + "side_effect", + [ + pytest.param( + exceptions.QuotaLimitException( + "err.func.wired.overloaded", "You have reached your quota limit" + ), + id="quota_limit", + ), + pytest.param( + exceptions.KamereonResponseException( + "err.func.unknown", "Something went wrong" + ), + id="kamereon_error", + ), + ], +) +async def test_vehicle_list_error( + hass: HomeAssistant, + config_entry: ConfigEntry, + device_registry: dr.DeviceRegistry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, + side_effect: Exception, +) -> None: + """Test an error during the vehicle list update keeps the vehicles.""" + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + mock_get_vehicles.side_effect = side_effect + await _async_poll_vehicle_list(hass, freezer) + + assert mock_get_vehicles.await_count == 2 + assert _device_vins(device_registry, config_entry) == {ZOE_VIN} + + +@pytest.mark.usefixtures("patch_renault_account", "fixtures_with_data") +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +async def test_vehicle_list_authentication_expired( + hass: HomeAssistant, + config_entry: ConfigEntry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, +) -> None: + """Test an expired login during the vehicle list update starts a reauth flow.""" + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + mock_get_vehicles.side_effect = NotAuthenticatedException("Not logged in") + await _async_poll_vehicle_list(hass, freezer) + + flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN) + assert len(flows) == 1 + assert flows[0]["context"]["source"] == SOURCE_REAUTH + + +@pytest.mark.usefixtures("patch_renault_account", "fixtures_with_data") +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +async def test_vehicle_details_authentication_expired( + hass: HomeAssistant, + config_entry: ConfigEntry, + device_registry: dr.DeviceRegistry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, + mock_get_vehicle_details: AsyncMock, +) -> None: + """Test an expired login while requesting new vehicle details starts a reauth flow.""" + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + mock_get_vehicles.return_value = _get_vehicles(ZOE_VIN, MISSING_DETAILS_VIN) + mock_get_vehicle_details.side_effect = NotAuthenticatedException("Not logged in") + await _async_poll_vehicle_list(hass, freezer) + + assert _device_vins(device_registry, config_entry) == {ZOE_VIN} + flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN) + assert len(flows) == 1 + assert flows[0]["context"]["source"] == SOURCE_REAUTH + + +@pytest.mark.usefixtures("patch_renault_account", "fixtures_with_data") +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +@pytest.mark.parametrize( + "side_effect", + [ + pytest.param(aiohttp.ClientConnectionError, id="client_error"), + pytest.param(TimeoutError, id="timeout"), + pytest.param(GigyaException, id="gigya_error"), + ], +) +async def test_vehicle_details_connection_error( + hass: HomeAssistant, + config_entry: ConfigEntry, + device_registry: dr.DeviceRegistry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, + mock_get_vehicle_details: AsyncMock, + side_effect: type[Exception], +) -> None: + """Test a connection error while requesting new vehicle details is retried.""" + mock_get_vehicles.return_value = _get_vehicles(ZOE_VIN, MISSING_DETAILS_VIN) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + mock_get_vehicle_details.side_effect = side_effect + await _async_poll_vehicle_list(hass, freezer) + await _async_poll_vehicle_list(hass, freezer) + + assert mock_get_vehicle_details.await_count == 3 + assert _device_vins(device_registry, config_entry) == {ZOE_VIN} + assert not hass.config_entries.flow.async_progress_by_handler(DOMAIN) + + +@pytest.mark.usefixtures("patch_renault_account", "sensor_platform") +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +async def test_vehicle_list_throttled( + hass: HomeAssistant, + config_entry: ConfigEntry, + device_registry: dr.DeviceRegistry, + freezer: FrozenDateTimeFactory, + mock_get_vehicles: AsyncMock, + mock_get_vehicle_details: AsyncMock, + fixtures_with_data: dict[str, AsyncMock], +) -> None: + """Test the Renault servers are not called while the hub is throttled.""" + mock_get_vehicles.return_value = _get_vehicles(ZOE_VIN, MISSING_DETAILS_VIN) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + # The vehicle updates just before the vehicle list update start the cooldown. + for get_data_mock in fixtures_with_data.values(): + get_data_mock.side_effect = exceptions.QuotaLimitException( + "err.func.wired.overloaded", "You have reached your quota limit" + ) + freezer.tick(VEHICLE_LIST_SCAN_INTERVAL - timedelta(minutes=1)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + freezer.tick(timedelta(minutes=1)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert mock_get_vehicles.await_count == 1 + assert mock_get_vehicle_details.await_count == 1 + assert _device_vins(device_registry, config_entry) == {ZOE_VIN} diff --git a/tests/components/renault/test_sensor.py b/tests/components/renault/test_sensor.py index 832364f00031..2f4fef30f46c 100644 --- a/tests/components/renault/test_sensor.py +++ b/tests/components/renault/test_sensor.py @@ -225,16 +225,17 @@ async def test_sensor_authentication_expired( assert flows[0]["context"]["entry_id"] == config_entry.entry_id -# scan interval in seconds = (3600 * num_calls) / MAX_CALLS_PER_HOURS -# MAX_CALLS_PER_HOURS being a constant, for now 60 calls per hour +# scan interval in seconds = (3600 * num_calls) / (MAX_CALLS_PER_HOURS - 1) +# MAX_CALLS_PER_HOURS being a constant, for now 60 calls per hour, with one +# call per hour kept for the vehicle list # num_calls = num_coordinator_car_0 + num_coordinator_car_1 + ... # + num_coordinator_car_n @pytest.mark.parametrize( ("vehicle_type", "vehicle_count", "scan_interval"), [ - ("zoe_50", 1, 420), # 7 coordinators => 7 minutes interval - ("captur_fuel", 1, 180), # 3 coordinators => 3 minutes interval - ("multi", 2, 540), # 9 coordinators => 9 minutes interval + ("zoe_50", 1, 427), # 7 coordinators => 7 minutes 7 seconds interval + ("captur_fuel", 1, 183), # 3 coordinators => 3 minutes 3 seconds interval + ("multi", 2, 549), # 9 coordinators => 9 minutes 9 seconds interval ], indirect=["vehicle_type"], ) @@ -265,16 +266,17 @@ async def test_dynamic_scan_interval( assert fixtures_with_data["cockpit"].call_count == vehicle_count * 2 -# scan interval in seconds = (3600 * num_calls) / MAX_CALLS_PER_HOURS -# MAX_CALLS_PER_HOURS being a constant, for now 60 calls per hour +# scan interval in seconds = (3600 * num_calls) / (MAX_CALLS_PER_HOURS - 1) +# MAX_CALLS_PER_HOURS being a constant, for now 60 calls per hour, with one +# call per hour kept for the vehicle list # num_calls = num_coordinator_car_0 + num_coordinator_car_1 + ... # + num_coordinator_car_n @pytest.mark.parametrize( ("vehicle_type", "vehicle_count", "scan_interval"), [ - ("zoe_50", 1, 360), # (7-1) coordinators => 6 minutes interval - ("captur_fuel", 1, 180), # (4-1) coordinators => 3 minutes interval - ("multi", 2, 480), # (10-2) coordinators => 8 minutes interval + ("zoe_50", 1, 366), # (7-1) coordinators => 6 minutes 6 seconds interval + ("captur_fuel", 1, 183), # (4-1) coordinators => 3 minutes 3 seconds interval + ("multi", 2, 488), # (10-2) coordinators => 8 minutes 8 seconds interval ], indirect=["vehicle_type"], )