Add dynamic devices to Renault (#187301)

This commit is contained in:
epenet
2026-10-20 10:26:40 +00:00
committed by GitHub
parent c29bd6e64d
commit 1effa7bf66
12 changed files with 659 additions and 55 deletions
@@ -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](
+3 -2
View File
@@ -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):
@@ -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
@@ -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 []
@@ -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(
+3 -2
View File
@@ -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](
@@ -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
+133 -26
View File
@@ -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."""
+3 -2
View File
@@ -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](
+3 -2
View File
@@ -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](
+428 -4
View File
@@ -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}
+12 -10
View File
@@ -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"],
)