mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 11:33:11 -04:00
Add DVLA Vehicle Enquiry Service integration (#176149)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
This commit is contained in:
co-authored by
Copilot Autofix powered by AI
Joost Lekkerkerker
parent
23e129ad4b
commit
fcfe0cb610
Generated
+2
@@ -480,6 +480,8 @@ AGENTS.md @home-assistant/core
|
||||
/tests/components/duco/ @ronaldvdmeer
|
||||
/homeassistant/components/duotecno/ @cereal2nd
|
||||
/tests/components/duotecno/ @cereal2nd
|
||||
/homeassistant/components/dvla/ @jampez77
|
||||
/tests/components/dvla/ @jampez77
|
||||
/homeassistant/components/dwd_weather_warnings/ @runningman84 @stephan192
|
||||
/tests/components/dwd_weather_warnings/ @runningman84 @stephan192
|
||||
/homeassistant/components/dynalite/ @ziv1234
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""The DVLA integration."""
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
|
||||
from .coordinator import DVLACoordinator
|
||||
|
||||
type DVLAConfigEntry = ConfigEntry[DVLACoordinator]
|
||||
|
||||
PLATFORMS: list[Platform] = [Platform.SENSOR]
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: DVLAConfigEntry) -> None:
|
||||
"""Set up platform from a config entry."""
|
||||
|
||||
session = async_get_clientsession(hass)
|
||||
|
||||
coordinator = DVLACoordinator(
|
||||
hass,
|
||||
entry,
|
||||
session,
|
||||
)
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
|
||||
entry.runtime_data = coordinator
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: DVLAConfigEntry) -> None:
|
||||
"""Unload a config entry."""
|
||||
await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Config flow for DVLA integration."""
|
||||
|
||||
import logging
|
||||
from typing import Any, override
|
||||
|
||||
from aio_dvla_vehicle_enquiry import (
|
||||
DVLAAuthError,
|
||||
DVLAClient,
|
||||
DVLAError,
|
||||
DVLAInvalidRegistrationError,
|
||||
DVLARateLimitError,
|
||||
)
|
||||
import probatio
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
|
||||
from .const import API_KEY, CONF_REG_NUMBER, DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
STEP_USER_DATA_SCHEMA = probatio.Schema(
|
||||
{
|
||||
probatio.Required(CONF_REG_NUMBER): str,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class DVLAConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for DVLA."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
@override
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle the initial step."""
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
if user_input is not None:
|
||||
reg_number = "".join(user_input[CONF_REG_NUMBER].split())
|
||||
if not reg_number.isascii() or not reg_number.isalnum():
|
||||
errors[CONF_REG_NUMBER] = "invalid_registration"
|
||||
else:
|
||||
reg_number = reg_number.upper()
|
||||
await self.async_set_unique_id(reg_number)
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
session = async_get_clientsession(self.hass)
|
||||
client = DVLAClient(session, API_KEY)
|
||||
|
||||
try:
|
||||
await client.async_get_vehicle(reg_number)
|
||||
except DVLAInvalidRegistrationError:
|
||||
errors["base"] = "invalid_registration"
|
||||
except DVLAAuthError:
|
||||
errors["base"] = "auth_failed"
|
||||
except DVLARateLimitError:
|
||||
errors["base"] = "rate_limited"
|
||||
except DVLAError:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected error requesting DVLA vehicle data")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
return self.async_create_entry(
|
||||
title=reg_number,
|
||||
data={CONF_REG_NUMBER: reg_number},
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=self.add_suggested_values_to_schema(
|
||||
STEP_USER_DATA_SCHEMA,
|
||||
user_input or {},
|
||||
),
|
||||
errors=errors,
|
||||
)
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Constants for the DVLA integration."""
|
||||
|
||||
DOMAIN = "dvla"
|
||||
CONF_REG_NUMBER = "reg_number"
|
||||
|
||||
API_KEY = "cIKMsF5zS59gaSttDldv91M3F063H5gk7A2inSyx"
|
||||
@@ -0,0 +1,82 @@
|
||||
"""DVLA Coordinator."""
|
||||
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any, override
|
||||
|
||||
from aio_dvla_vehicle_enquiry import (
|
||||
DVLAAuthError,
|
||||
DVLAClient,
|
||||
DVLAError,
|
||||
DVLAInvalidRegistrationError,
|
||||
DVLARateLimitError,
|
||||
)
|
||||
from aiohttp import ClientSession
|
||||
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryError
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
|
||||
from .const import API_KEY, CONF_REG_NUMBER, DOMAIN
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from . import DVLAConfigEntry
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_RETRY_AFTER = 3600
|
||||
|
||||
|
||||
class DVLACoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
"""Data coordinator."""
|
||||
|
||||
config_entry: DVLAConfigEntry
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
config_entry: DVLAConfigEntry,
|
||||
session: ClientSession,
|
||||
) -> None:
|
||||
"""Initialize coordinator."""
|
||||
|
||||
super().__init__(
|
||||
hass,
|
||||
_LOGGER,
|
||||
config_entry=config_entry,
|
||||
name=config_entry.title,
|
||||
update_interval=timedelta(weeks=1),
|
||||
)
|
||||
self.client = DVLAClient(session, API_KEY)
|
||||
self.reg_number = config_entry.data[CONF_REG_NUMBER]
|
||||
|
||||
@override
|
||||
async def _async_update_data(self) -> dict[str, Any]:
|
||||
"""Fetch vehicle data from the DVLA API."""
|
||||
try:
|
||||
return await self.client.async_get_vehicle(self.reg_number)
|
||||
except DVLAInvalidRegistrationError:
|
||||
raise ConfigEntryError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="vehicle_not_found",
|
||||
translation_placeholders={"reg_number": self.reg_number},
|
||||
) from None
|
||||
except DVLAAuthError:
|
||||
raise ConfigEntryError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="auth_failed",
|
||||
) from None
|
||||
except DVLARateLimitError:
|
||||
raise UpdateFailed(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="rate_limited",
|
||||
retry_after=_RETRY_AFTER,
|
||||
) from None
|
||||
except DVLAError:
|
||||
raise UpdateFailed(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="update_failed",
|
||||
retry_after=_RETRY_AFTER
|
||||
if self.config_entry.state is ConfigEntryState.LOADED
|
||||
else None,
|
||||
) from None
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"additional_rate_of_tax_end_date": {
|
||||
"default": "mdi:calendar-end"
|
||||
},
|
||||
"co2_emissions": {
|
||||
"default": "mdi:molecule-co2"
|
||||
},
|
||||
"color": {
|
||||
"default": "mdi:spray"
|
||||
},
|
||||
"date_of_last_v5c_issued": {
|
||||
"default": "mdi:calendar"
|
||||
},
|
||||
"engine_capacity": {
|
||||
"default": "mdi:engine"
|
||||
},
|
||||
"euro_status": {
|
||||
"default": "mdi:molecule"
|
||||
},
|
||||
"fuel_type": {
|
||||
"default": "mdi:gas-station"
|
||||
},
|
||||
"month_of_first_registration": {
|
||||
"default": "mdi:calendar-month"
|
||||
},
|
||||
"mot_expiry_date": {
|
||||
"default": "mdi:calendar-check"
|
||||
},
|
||||
"mot_status": {
|
||||
"default": "mdi:car-wrench"
|
||||
},
|
||||
"revenue_weight": {
|
||||
"default": "mdi:weight-kilogram"
|
||||
},
|
||||
"tax_due_date": {
|
||||
"default": "mdi:calendar-clock"
|
||||
},
|
||||
"tax_status": {
|
||||
"default": "mdi:cash-clock"
|
||||
},
|
||||
"type_approval": {
|
||||
"default": "mdi:car"
|
||||
},
|
||||
"wheelplan": {
|
||||
"default": "mdi:tire"
|
||||
},
|
||||
"year_of_manufacture": {
|
||||
"default": "mdi:calendar"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"domain": "dvla",
|
||||
"name": "DVLA Vehicle Enquiry Service",
|
||||
"categories": ["vehicles_transport.cars_evs"],
|
||||
"codeowners": ["@jampez77"],
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/dvla",
|
||||
"integration_type": "service",
|
||||
"iot_class": "cloud_polling",
|
||||
"quality_scale": "bronze",
|
||||
"requirements": ["aio-dvla-vehicle-enquiry==0.1.4"]
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
rules:
|
||||
# Bronze
|
||||
action-setup:
|
||||
status: exempt
|
||||
comment: Integration registers no custom services/actions.
|
||||
appropriate-polling: done
|
||||
brands: done
|
||||
common-modules: done
|
||||
config-flow: done
|
||||
config-flow-test-coverage: done
|
||||
dependency-transparency: done
|
||||
docs-actions:
|
||||
status: exempt
|
||||
comment: Integration provides no custom actions.
|
||||
docs-conditions:
|
||||
status: exempt
|
||||
comment: This integration does not provide conditions.
|
||||
docs-high-level-description: done
|
||||
docs-installation-instructions: done
|
||||
docs-removal-instructions: done
|
||||
docs-triggers:
|
||||
status: exempt
|
||||
comment: This integration does not provide triggers.
|
||||
entity-event-setup:
|
||||
status: exempt
|
||||
comment: This integration does not subscribe to external entity events.
|
||||
entity-unique-id: done
|
||||
has-entity-name: done
|
||||
runtime-data: done
|
||||
test-before-configure: done
|
||||
test-before-setup: done
|
||||
unique-config-entry: done
|
||||
|
||||
# Silver
|
||||
action-exceptions:
|
||||
status: exempt
|
||||
comment: Integration registers no custom actions.
|
||||
config-entry-unloading: done
|
||||
docs-configuration-parameters: todo
|
||||
docs-installation-parameters: todo
|
||||
entity-unavailable: todo
|
||||
integration-owner: done
|
||||
log-when-unavailable: todo
|
||||
parallel-updates: todo
|
||||
reauthentication-flow:
|
||||
status: exempt
|
||||
comment: The DVLA Vehicle Enquiry Service uses an application API key and has no user reauthentication flow.
|
||||
test-coverage: todo
|
||||
|
||||
# Gold
|
||||
devices: done
|
||||
diagnostics: todo
|
||||
discovery:
|
||||
status: exempt
|
||||
comment: Vehicles are added manually by registration number and cannot be discovered.
|
||||
discovery-update-info:
|
||||
status: exempt
|
||||
comment: This integration does not use discovery.
|
||||
docs-data-update: todo
|
||||
docs-examples: todo
|
||||
docs-known-limitations: todo
|
||||
docs-supported-devices: todo
|
||||
docs-supported-functions: todo
|
||||
docs-troubleshooting: todo
|
||||
docs-use-cases: todo
|
||||
dynamic-devices:
|
||||
status: exempt
|
||||
comment: Vehicles are statically configured by config entries.
|
||||
entity-category: todo
|
||||
entity-device-class: done
|
||||
entity-disabled-by-default: todo
|
||||
entity-translations: done
|
||||
exception-translations: todo
|
||||
icon-translations: done
|
||||
reconfiguration-flow: todo
|
||||
repair-issues: todo
|
||||
stale-devices:
|
||||
status: exempt
|
||||
comment: Vehicles are removed by removing their config entry.
|
||||
|
||||
# Platinum
|
||||
async-dependency: done
|
||||
inject-websession: done
|
||||
strict-typing: todo
|
||||
@@ -0,0 +1,229 @@
|
||||
"""DVLA sensor platform."""
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from typing import Any, cast, override
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
SensorDeviceClass,
|
||||
SensorEntity,
|
||||
SensorEntityDescription,
|
||||
)
|
||||
from homeassistant.const import UnitOfMass, UnitOfVolume
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from homeassistant.helpers.typing import StateType
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from . import DVLAConfigEntry
|
||||
from .const import DOMAIN
|
||||
from .coordinator import DVLACoordinator
|
||||
|
||||
TAX_STATUS_OPTIONS = {
|
||||
"Not Taxed for on Road Use": "not_taxed_for_on_road_use",
|
||||
"SORN": "sorn",
|
||||
"Taxed": "taxed",
|
||||
"Untaxed": "untaxed",
|
||||
}
|
||||
|
||||
MOT_STATUS_OPTIONS = {
|
||||
"No details held by DVLA": "no_details_held_by_dvla",
|
||||
"No results returned": "no_results_returned",
|
||||
"Not valid": "not_valid",
|
||||
"Valid": "valid",
|
||||
}
|
||||
|
||||
|
||||
def raw_value(value: Any) -> StateType:
|
||||
"""Return a raw DVLA value."""
|
||||
return cast(StateType, value)
|
||||
|
||||
|
||||
def enum_value_fn(options: Mapping[str, str]) -> Callable[[Any], StateType]:
|
||||
"""Return a value function for a DVLA enum field."""
|
||||
|
||||
def _value_fn(value: Any) -> StateType:
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
return options.get(str(value))
|
||||
|
||||
return _value_fn
|
||||
|
||||
|
||||
def int_value(value: Any) -> StateType:
|
||||
"""Return an integer DVLA value."""
|
||||
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return int(value)
|
||||
except TypeError, ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def date_value(value: Any) -> StateType | date:
|
||||
"""Return a date DVLA value."""
|
||||
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
|
||||
try:
|
||||
return date.fromisoformat(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class DVLASensorEntityDescription(SensorEntityDescription):
|
||||
"""Describe a DVLA sensor."""
|
||||
|
||||
exists_fn: Callable[[Mapping[str, Any]], bool] = lambda _: True
|
||||
value_fn: Callable[[Any], StateType | date] = raw_value
|
||||
|
||||
|
||||
SENSOR_DESCRIPTIONS: tuple[DVLASensorEntityDescription, ...] = (
|
||||
DVLASensorEntityDescription(
|
||||
key="taxStatus",
|
||||
translation_key="tax_status",
|
||||
device_class=SensorDeviceClass.ENUM,
|
||||
options=list(TAX_STATUS_OPTIONS.values()),
|
||||
value_fn=enum_value_fn(TAX_STATUS_OPTIONS),
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="taxDueDate",
|
||||
translation_key="tax_due_date",
|
||||
device_class=SensorDeviceClass.DATE,
|
||||
value_fn=date_value,
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="artEndDate",
|
||||
translation_key="additional_rate_of_tax_end_date",
|
||||
device_class=SensorDeviceClass.DATE,
|
||||
value_fn=date_value,
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="motStatus",
|
||||
translation_key="mot_status",
|
||||
device_class=SensorDeviceClass.ENUM,
|
||||
options=list(MOT_STATUS_OPTIONS.values()),
|
||||
value_fn=enum_value_fn(MOT_STATUS_OPTIONS),
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="engineCapacity",
|
||||
translation_key="engine_capacity",
|
||||
device_class=SensorDeviceClass.VOLUME,
|
||||
native_unit_of_measurement=UnitOfVolume.MILLILITERS,
|
||||
exists_fn=lambda data: (
|
||||
"engineCapacity" in data or data.get("fuelType") != "ELECTRICITY"
|
||||
),
|
||||
value_fn=int_value,
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="yearOfManufacture",
|
||||
translation_key="year_of_manufacture",
|
||||
value_fn=int_value,
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="co2Emissions",
|
||||
translation_key="co2_emissions",
|
||||
native_unit_of_measurement="g/km",
|
||||
value_fn=int_value,
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="fuelType",
|
||||
translation_key="fuel_type",
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="colour",
|
||||
translation_key="color",
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="typeApproval",
|
||||
translation_key="type_approval",
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="revenueWeight",
|
||||
translation_key="revenue_weight",
|
||||
device_class=SensorDeviceClass.WEIGHT,
|
||||
native_unit_of_measurement=UnitOfMass.KILOGRAMS,
|
||||
value_fn=int_value,
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="dateOfLastV5CIssued",
|
||||
translation_key="date_of_last_v5c_issued",
|
||||
device_class=SensorDeviceClass.DATE,
|
||||
value_fn=date_value,
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="motExpiryDate",
|
||||
translation_key="mot_expiry_date",
|
||||
device_class=SensorDeviceClass.DATE,
|
||||
value_fn=date_value,
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="wheelplan",
|
||||
translation_key="wheelplan",
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="monthOfFirstRegistration",
|
||||
translation_key="month_of_first_registration",
|
||||
),
|
||||
DVLASensorEntityDescription(
|
||||
key="euroStatus",
|
||||
translation_key="euro_status",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: DVLAConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up sensors from a config entry created in the integrations UI."""
|
||||
coordinator = entry.runtime_data
|
||||
reg_number = coordinator.reg_number
|
||||
|
||||
async_add_entities(
|
||||
DVLASensor(coordinator, reg_number, description)
|
||||
for description in SENSOR_DESCRIPTIONS
|
||||
if description.exists_fn(coordinator.data)
|
||||
)
|
||||
|
||||
|
||||
class DVLASensor(CoordinatorEntity[DVLACoordinator], SensorEntity):
|
||||
"""Define a DVLA sensor."""
|
||||
|
||||
entity_description: DVLASensorEntityDescription
|
||||
|
||||
_attr_has_entity_name = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
coordinator: DVLACoordinator,
|
||||
reg_number: str,
|
||||
description: DVLASensorEntityDescription,
|
||||
) -> None:
|
||||
"""Initialize."""
|
||||
super().__init__(coordinator)
|
||||
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, reg_number)},
|
||||
manufacturer=coordinator.data.get("make"),
|
||||
name=reg_number,
|
||||
entry_type=DeviceEntryType.SERVICE,
|
||||
)
|
||||
self._attr_unique_id = f"{reg_number}-{description.key}"
|
||||
self.entity_description = description
|
||||
|
||||
@property
|
||||
@override
|
||||
def native_value(self) -> StateType | date:
|
||||
"""Native value."""
|
||||
return self.entity_description.value_fn(
|
||||
self.coordinator.data.get(self.entity_description.key)
|
||||
)
|
||||
@@ -0,0 +1,102 @@
|
||||
{
|
||||
"config": {
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
|
||||
},
|
||||
"error": {
|
||||
"auth_failed": "The DVLA service rejected the integration's API key",
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"invalid_registration": "Invalid or unknown vehicle registration number",
|
||||
"rate_limited": "The DVLA service is receiving too many requests. Try again later",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"step": {
|
||||
"user": {
|
||||
"data": {
|
||||
"reg_number": "Registration number"
|
||||
},
|
||||
"data_description": {
|
||||
"reg_number": "The vehicle registration number to look up, for example AB12CDE."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"additional_rate_of_tax_end_date": {
|
||||
"name": "Additional rate of tax end date"
|
||||
},
|
||||
"co2_emissions": {
|
||||
"name": "CO2 emissions"
|
||||
},
|
||||
"color": {
|
||||
"name": "Color"
|
||||
},
|
||||
"date_of_last_v5c_issued": {
|
||||
"name": "Date of last V5C issued"
|
||||
},
|
||||
"engine_capacity": {
|
||||
"name": "Engine capacity"
|
||||
},
|
||||
"euro_status": {
|
||||
"name": "Euro status"
|
||||
},
|
||||
"fuel_type": {
|
||||
"name": "Fuel type"
|
||||
},
|
||||
"month_of_first_registration": {
|
||||
"name": "First registration month"
|
||||
},
|
||||
"mot_expiry_date": {
|
||||
"name": "MOT expiry date"
|
||||
},
|
||||
"mot_status": {
|
||||
"name": "MOT status",
|
||||
"state": {
|
||||
"no_details_held_by_dvla": "No details held by DVLA",
|
||||
"no_results_returned": "No results returned",
|
||||
"not_valid": "Not valid",
|
||||
"valid": "Valid"
|
||||
}
|
||||
},
|
||||
"revenue_weight": {
|
||||
"name": "Revenue weight"
|
||||
},
|
||||
"tax_due_date": {
|
||||
"name": "Tax due date"
|
||||
},
|
||||
"tax_status": {
|
||||
"name": "Tax status",
|
||||
"state": {
|
||||
"not_taxed_for_on_road_use": "Not taxed for on-road use",
|
||||
"sorn": "SORN",
|
||||
"taxed": "Taxed",
|
||||
"untaxed": "Untaxed"
|
||||
}
|
||||
},
|
||||
"type_approval": {
|
||||
"name": "Type approval"
|
||||
},
|
||||
"wheelplan": {
|
||||
"name": "Wheelplan"
|
||||
},
|
||||
"year_of_manufacture": {
|
||||
"name": "Year of manufacture"
|
||||
}
|
||||
}
|
||||
},
|
||||
"exceptions": {
|
||||
"auth_failed": {
|
||||
"message": "[%key:component::dvla::config::error::auth_failed%]"
|
||||
},
|
||||
"rate_limited": {
|
||||
"message": "[%key:component::dvla::config::error::rate_limited%]"
|
||||
},
|
||||
"update_failed": {
|
||||
"message": "Unable to update vehicle information from the DVLA service"
|
||||
},
|
||||
"vehicle_not_found": {
|
||||
"message": "The DVLA service could not find a vehicle with registration {reg_number}"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+1
@@ -197,6 +197,7 @@ FLOWS = {
|
||||
"duco",
|
||||
"dunehd",
|
||||
"duotecno",
|
||||
"dvla",
|
||||
"dwd_weather_warnings",
|
||||
"dynalite",
|
||||
"dyson_infrared",
|
||||
|
||||
@@ -3418,6 +3418,15 @@
|
||||
],
|
||||
"supported_by": "opower"
|
||||
},
|
||||
"dvla": {
|
||||
"name": "DVLA Vehicle Enquiry Service",
|
||||
"integration_type": "service",
|
||||
"categories": [
|
||||
"vehicles_transport.cars_evs"
|
||||
],
|
||||
"config_flow": true,
|
||||
"iot_class": "cloud_polling"
|
||||
},
|
||||
"dwd_weather_warnings": {
|
||||
"name": "Deutscher Wetterdienst (DWD) Weather Warnings",
|
||||
"integration_type": "service",
|
||||
|
||||
Generated
+3
@@ -153,6 +153,9 @@ afsapi==1.0.2
|
||||
# homeassistant.components.agent_dvr
|
||||
agent-py==0.0.25
|
||||
|
||||
# homeassistant.components.dvla
|
||||
aio-dvla-vehicle-enquiry==0.1.4
|
||||
|
||||
# homeassistant.components.geo_json_events
|
||||
aio-geojson-generic-client==0.5
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Tests for the DVLA integration."""
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Fixtures for the DVLA integration tests."""
|
||||
|
||||
from collections.abc import Awaitable, Callable, Generator
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry, async_load_json_object_fixture
|
||||
|
||||
from homeassistant.components.dvla.const import CONF_REG_NUMBER, DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.util.json import JsonObjectType
|
||||
|
||||
MOCK_REG_NUMBER = "AB12CDE"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def vehicle_data(hass: HomeAssistant) -> JsonObjectType:
|
||||
"""Load synthetic vehicle data based on DVLA's published test responses."""
|
||||
return await async_load_json_object_fixture(hass, "vehicle.json", DOMAIN)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config_entry() -> MockConfigEntry:
|
||||
"""Return a mock DVLA config entry."""
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title=MOCK_REG_NUMBER,
|
||||
unique_id=MOCK_REG_NUMBER,
|
||||
data={CONF_REG_NUMBER: MOCK_REG_NUMBER},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_dvla_client(vehicle_data: JsonObjectType) -> Generator[AsyncMock]:
|
||||
"""Mock the DVLA client vehicle lookup."""
|
||||
with patch(
|
||||
"homeassistant.components.dvla.coordinator.DVLAClient.async_get_vehicle",
|
||||
return_value=vehicle_data,
|
||||
) as mock_get_vehicle:
|
||||
yield mock_get_vehicle
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup_dvla_entry(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_dvla_client: AsyncMock,
|
||||
) -> Callable[[dict[str, Any] | None], Awaitable[MockConfigEntry]]:
|
||||
"""Return a helper to set up the DVLA integration."""
|
||||
|
||||
async def _setup(vehicle_data: dict[str, Any] | None = None) -> MockConfigEntry:
|
||||
if vehicle_data is not None:
|
||||
mock_dvla_client.return_value = vehicle_data
|
||||
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
return mock_config_entry
|
||||
|
||||
return _setup
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"registrationNumber": "AB12CDE",
|
||||
"co2Emissions": 150,
|
||||
"engineCapacity": 1998,
|
||||
"euroStatus": "EURO6",
|
||||
"markedForExport": false,
|
||||
"fuelType": "PETROL",
|
||||
"motStatus": "Valid",
|
||||
"revenueWeight": 1500,
|
||||
"colour": "SILVER",
|
||||
"make": "FORD",
|
||||
"typeApproval": "M1",
|
||||
"yearOfManufacture": 2020,
|
||||
"taxDueDate": "2026-03-01",
|
||||
"taxStatus": "Taxed",
|
||||
"dateOfLastV5CIssued": "2024-05-18",
|
||||
"motExpiryDate": "2026-11-30",
|
||||
"wheelplan": "2 AXLE RIGID BODY",
|
||||
"monthOfFirstRegistration": "2024-05"
|
||||
}
|
||||
@@ -0,0 +1,844 @@
|
||||
# serializer version: 1
|
||||
# name: test_sensor_platform[sensor.ab12cde_additional_rate_of_tax_end_date-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_additional_rate_of_tax_end_date',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Additional rate of tax end date',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.DATE: 'date'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Additional rate of tax end date',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'additional_rate_of_tax_end_date',
|
||||
'unique_id': 'AB12CDE-artEndDate',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_additional_rate_of_tax_end_date-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'date',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Additional rate of tax end date',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_additional_rate_of_tax_end_date',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'unknown',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_co2_emissions-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_co2_emissions',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'CO2 emissions',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'CO2 emissions',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'co2_emissions',
|
||||
'unique_id': 'AB12CDE-co2Emissions',
|
||||
'unit_of_measurement': 'g/km',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_co2_emissions-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE CO2 emissions',
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: 'g/km',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_co2_emissions',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '150',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_color-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_color',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Color',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'Color',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'color',
|
||||
'unique_id': 'AB12CDE-colour',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_color-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Color',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_color',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'SILVER',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_date_of_last_v5c_issued-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_date_of_last_v5c_issued',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Date of last V5C issued',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.DATE: 'date'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Date of last V5C issued',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'date_of_last_v5c_issued',
|
||||
'unique_id': 'AB12CDE-dateOfLastV5CIssued',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_date_of_last_v5c_issued-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'date',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Date of last V5C issued',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_date_of_last_v5c_issued',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '2024-05-18',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_engine_capacity-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_engine_capacity',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Engine capacity',
|
||||
'options': dict({
|
||||
'sensor': dict({
|
||||
'suggested_display_precision': 0,
|
||||
}),
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.VOLUME: 'volume'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Engine capacity',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'engine_capacity',
|
||||
'unique_id': 'AB12CDE-engineCapacity',
|
||||
'unit_of_measurement': <UnitOfVolume.MILLILITERS: 'mL'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_engine_capacity-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'volume',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Engine capacity',
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: <UnitOfVolume.MILLILITERS: 'mL'>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_engine_capacity',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '1998',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_euro_status-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_euro_status',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Euro status',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'Euro status',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'euro_status',
|
||||
'unique_id': 'AB12CDE-euroStatus',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_euro_status-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Euro status',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_euro_status',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'EURO6',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_first_registration_month-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_first_registration_month',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'First registration month',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'First registration month',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'month_of_first_registration',
|
||||
'unique_id': 'AB12CDE-monthOfFirstRegistration',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_first_registration_month-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE First registration month',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_first_registration_month',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '2024-05',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_fuel_type-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_fuel_type',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Fuel type',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'Fuel type',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'fuel_type',
|
||||
'unique_id': 'AB12CDE-fuelType',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_fuel_type-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Fuel type',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_fuel_type',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'PETROL',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_mot_expiry_date-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_mot_expiry_date',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'MOT expiry date',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.DATE: 'date'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'MOT expiry date',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'mot_expiry_date',
|
||||
'unique_id': 'AB12CDE-motExpiryDate',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_mot_expiry_date-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'date',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE MOT expiry date',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_mot_expiry_date',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '2026-11-30',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_mot_status-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'no_details_held_by_dvla',
|
||||
'no_results_returned',
|
||||
'not_valid',
|
||||
'valid',
|
||||
]),
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_mot_status',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'MOT status',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.ENUM: 'enum'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'MOT status',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'mot_status',
|
||||
'unique_id': 'AB12CDE-motStatus',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_mot_status-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'enum',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE MOT status',
|
||||
<SensorEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'no_details_held_by_dvla',
|
||||
'no_results_returned',
|
||||
'not_valid',
|
||||
'valid',
|
||||
]),
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_mot_status',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'valid',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_revenue_weight-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_revenue_weight',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Revenue weight',
|
||||
'options': dict({
|
||||
'sensor': dict({
|
||||
'suggested_display_precision': 2,
|
||||
}),
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.WEIGHT: 'weight'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Revenue weight',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'revenue_weight',
|
||||
'unique_id': 'AB12CDE-revenueWeight',
|
||||
'unit_of_measurement': <UnitOfMass.KILOGRAMS: 'kg'>,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_revenue_weight-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'weight',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Revenue weight',
|
||||
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: <UnitOfMass.KILOGRAMS: 'kg'>,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_revenue_weight',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '1500',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_tax_due_date-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_tax_due_date',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Tax due date',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.DATE: 'date'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Tax due date',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'tax_due_date',
|
||||
'unique_id': 'AB12CDE-taxDueDate',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_tax_due_date-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'date',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Tax due date',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_tax_due_date',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '2026-03-01',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_tax_status-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<SensorEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'not_taxed_for_on_road_use',
|
||||
'sorn',
|
||||
'taxed',
|
||||
'untaxed',
|
||||
]),
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_tax_status',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Tax status',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.ENUM: 'enum'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Tax status',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'tax_status',
|
||||
'unique_id': 'AB12CDE-taxStatus',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_tax_status-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'enum',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Tax status',
|
||||
<SensorEntityCapabilityAttribute.OPTIONS: 'options'>: list([
|
||||
'not_taxed_for_on_road_use',
|
||||
'sorn',
|
||||
'taxed',
|
||||
'untaxed',
|
||||
]),
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_tax_status',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'taxed',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_type_approval-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_type_approval',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Type approval',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'Type approval',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'type_approval',
|
||||
'unique_id': 'AB12CDE-typeApproval',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_type_approval-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Type approval',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_type_approval',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'M1',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_wheelplan-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_wheelplan',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Wheelplan',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'Wheelplan',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'wheelplan',
|
||||
'unique_id': 'AB12CDE-wheelplan',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_wheelplan-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Wheelplan',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_wheelplan',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '2 AXLE RIGID BODY',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_year_of_manufacture-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('dvla', 'AB12CDE')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.ab12cde_year_of_manufacture',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Year of manufacture',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'Year of manufacture',
|
||||
'platform': 'dvla',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'year_of_manufacture',
|
||||
'unique_id': 'AB12CDE-yearOfManufacture',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensor_platform[sensor.ab12cde_year_of_manufacture-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'AB12CDE Year of manufacture',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.ab12cde_year_of_manufacture',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '2020',
|
||||
})
|
||||
# ---
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Tests for the DVLA config flow."""
|
||||
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from aio_dvla_vehicle_enquiry import (
|
||||
DVLAAuthError,
|
||||
DVLAError,
|
||||
DVLAInvalidRegistrationError,
|
||||
DVLARateLimitError,
|
||||
)
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.dvla.const import CONF_REG_NUMBER, DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
|
||||
async def test_form(hass: HomeAssistant) -> None:
|
||||
"""Test that the form is served."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
|
||||
|
||||
async def test_already_configured(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test that an already configured vehicle aborts."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_REG_NUMBER: "ab12 cde"},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_dvla_client")
|
||||
async def test_form_success(hass: HomeAssistant) -> None:
|
||||
"""Test successful config flow."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_REG_NUMBER: " ab12\tcde\n"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "AB12CDE"
|
||||
assert result["data"] == {CONF_REG_NUMBER: "AB12CDE"}
|
||||
assert result["result"].unique_id == "AB12CDE"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reg_number",
|
||||
[
|
||||
pytest.param("", id="empty"),
|
||||
pytest.param(" \t\n", id="whitespace"),
|
||||
pytest.param("AB12-CDE", id="punctuation"),
|
||||
pytest.param("AB12ß", id="non_ascii"),
|
||||
],
|
||||
)
|
||||
async def test_form_rejects_malformed_registration(
|
||||
hass: HomeAssistant,
|
||||
mock_dvla_client: AsyncMock,
|
||||
reg_number: str,
|
||||
) -> None:
|
||||
"""Test malformed input never reaches DVLA or sets a unique ID."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_REG_NUMBER: reg_number},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {CONF_REG_NUMBER: "invalid_registration"}
|
||||
flow = hass.config_entries.flow.async_get(result["flow_id"])
|
||||
assert flow["context"].get("unique_id") is None
|
||||
mock_dvla_client.assert_not_called()
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_REG_NUMBER: "AB12CDE"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["result"].unique_id == "AB12CDE"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "error_key"),
|
||||
[
|
||||
pytest.param(
|
||||
DVLAInvalidRegistrationError("Invalid registration number"),
|
||||
"invalid_registration",
|
||||
id="invalid_registration",
|
||||
),
|
||||
pytest.param(
|
||||
DVLAInvalidRegistrationError("Vehicle not found"),
|
||||
"invalid_registration",
|
||||
id="vehicle_not_found",
|
||||
),
|
||||
pytest.param(DVLAAuthError("Invalid key"), "auth_failed", id="auth"),
|
||||
pytest.param(
|
||||
DVLARateLimitError("Too many requests"), "rate_limited", id="rate"
|
||||
),
|
||||
pytest.param(DVLAError("DVLA unavailable"), "cannot_connect", id="connection"),
|
||||
pytest.param(Exception("Unexpected error"), "unknown", id="unexpected"),
|
||||
],
|
||||
)
|
||||
async def test_form_error_recovers(
|
||||
hass: HomeAssistant,
|
||||
mock_dvla_client: AsyncMock,
|
||||
error: Exception,
|
||||
error_key: str,
|
||||
) -> None:
|
||||
"""Test a config flow error can recover with a valid registration."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": config_entries.SOURCE_USER},
|
||||
)
|
||||
|
||||
mock_dvla_client.side_effect = error
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_REG_NUMBER: "UNKNOWN"},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["errors"] == {"base": error_key}
|
||||
|
||||
mock_dvla_client.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_REG_NUMBER: "AB12CDE"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "AB12CDE"
|
||||
assert result["data"] == {CONF_REG_NUMBER: "AB12CDE"}
|
||||
assert result["result"].unique_id == "AB12CDE"
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Tests for the DVLA data update coordinator."""
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from aio_dvla_vehicle_enquiry import (
|
||||
DVLAAuthError,
|
||||
DVLAError,
|
||||
DVLAInvalidRegistrationError,
|
||||
DVLARateLimitError,
|
||||
)
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import STATE_UNAVAILABLE
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "retry_delay"),
|
||||
[
|
||||
pytest.param(
|
||||
DVLAError("Connection failed"), timedelta(hours=1), id="connection"
|
||||
),
|
||||
pytest.param(
|
||||
DVLARateLimitError("Too many requests"), timedelta(hours=1), id="rate_limit"
|
||||
),
|
||||
pytest.param(DVLAAuthError("Invalid key"), timedelta(weeks=1), id="auth"),
|
||||
pytest.param(
|
||||
DVLAInvalidRegistrationError("Vehicle not found"),
|
||||
timedelta(weeks=1),
|
||||
id="registration",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_refresh_failure_and_recovery(
|
||||
hass: HomeAssistant,
|
||||
setup_dvla_entry: Callable[[dict[str, Any] | None], Awaitable[MockConfigEntry]],
|
||||
mock_dvla_client: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
error: DVLAError,
|
||||
retry_delay: timedelta,
|
||||
) -> None:
|
||||
"""Test scheduled refresh failures retry at the appropriate cadence."""
|
||||
entry = await setup_dvla_entry()
|
||||
entity_id = "sensor.ab12cde_tax_status"
|
||||
|
||||
mock_dvla_client.side_effect = error
|
||||
freezer.tick(timedelta(weeks=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
assert not hass.config_entries.flow.async_progress()
|
||||
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
|
||||
assert mock_dvla_client.await_count == 2
|
||||
|
||||
mock_dvla_client.side_effect = None
|
||||
freezer.tick(retry_delay - timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert mock_dvla_client.await_count == 2
|
||||
|
||||
freezer.tick(timedelta(minutes=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert hass.states.get(entity_id).state == "taxed"
|
||||
assert mock_dvla_client.await_count == 3
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Test the DVLA integration setup."""
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from aio_dvla_vehicle_enquiry import (
|
||||
DVLAAuthError,
|
||||
DVLAError,
|
||||
DVLAInvalidRegistrationError,
|
||||
DVLARateLimitError,
|
||||
)
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
from homeassistant.components.dvla.const import DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
|
||||
async def test_setup_entry(
|
||||
setup_dvla_entry: Callable[[dict[str, Any] | None], Awaitable[MockConfigEntry]],
|
||||
mock_dvla_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test setting up a config entry."""
|
||||
entry = await setup_dvla_entry()
|
||||
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
assert entry.runtime_data is not None
|
||||
assert entry.runtime_data.reg_number == "AB12CDE"
|
||||
mock_dvla_client.assert_awaited_once_with("AB12CDE")
|
||||
|
||||
|
||||
async def test_unload_entry(
|
||||
hass: HomeAssistant,
|
||||
setup_dvla_entry: Callable[
|
||||
[dict[str, Any] | None],
|
||||
Awaitable[MockConfigEntry],
|
||||
],
|
||||
) -> None:
|
||||
"""Test unloading a config entry."""
|
||||
entry = await setup_dvla_entry()
|
||||
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
assert await hass.config_entries.async_unload(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert entry.state is ConfigEntryState.NOT_LOADED
|
||||
|
||||
|
||||
async def test_setup_entry_retries_on_dvla_error(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_dvla_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test setup retries when DVLA update fails."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
mock_dvla_client.side_effect = DVLAError("DVLA unavailable")
|
||||
|
||||
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
assert mock_config_entry.error_reason_translation_domain == DOMAIN
|
||||
assert mock_config_entry.error_reason_translation_key == "update_failed"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "translation_key", "placeholders"),
|
||||
[
|
||||
pytest.param(
|
||||
DVLAAuthError("Raw DVLA response"), "auth_failed", None, id="auth"
|
||||
),
|
||||
pytest.param(
|
||||
DVLAInvalidRegistrationError("Raw DVLA response"),
|
||||
"vehicle_not_found",
|
||||
{"reg_number": "AB12CDE"},
|
||||
id="registration",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_setup_entry_fails_without_retry_or_reauth(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_dvla_client: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
error: DVLAError,
|
||||
translation_key: str,
|
||||
placeholders: dict[str, str] | None,
|
||||
) -> None:
|
||||
"""Test a rejected key or registration stops setup with a translated error."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
mock_dvla_client.side_effect = error
|
||||
|
||||
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
|
||||
assert mock_config_entry.error_reason_translation_domain == DOMAIN
|
||||
assert mock_config_entry.error_reason_translation_key == translation_key
|
||||
assert mock_config_entry.error_reason_translation_placeholders == placeholders
|
||||
assert not hass.config_entries.flow.async_progress()
|
||||
assert "Raw DVLA response" not in caplog.text
|
||||
|
||||
freezer.tick(timedelta(hours=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
mock_dvla_client.assert_awaited_once_with("AB12CDE")
|
||||
|
||||
|
||||
async def test_setup_entry_rate_limit_waits_before_retrying(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_dvla_client: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test setup does not immediately retry a rate-limited shared key."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
mock_dvla_client.side_effect = DVLARateLimitError("Too many requests")
|
||||
|
||||
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
assert mock_config_entry.error_reason_translation_key == "rate_limited"
|
||||
|
||||
mock_dvla_client.side_effect = None
|
||||
freezer.tick(timedelta(minutes=59))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
mock_dvla_client.assert_awaited_once_with("AB12CDE")
|
||||
|
||||
freezer.tick(timedelta(minutes=1, seconds=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
assert mock_dvla_client.await_count == 2
|
||||
@@ -0,0 +1,209 @@
|
||||
"""Tests for the DVLA sensor platform."""
|
||||
|
||||
from collections.abc import Awaitable, Callable
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from pytest_homeassistant.common import (
|
||||
MockConfigEntry,
|
||||
async_fire_time_changed,
|
||||
snapshot_platform,
|
||||
)
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.dvla.const import DOMAIN
|
||||
from homeassistant.components.sensor import SensorDeviceClass
|
||||
from homeassistant.const import STATE_UNKNOWN, UnitOfVolume
|
||||
from homeassistant.core import HomeAssistant, State
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.device_registry import DeviceEntryType
|
||||
from homeassistant.util.json import JsonObjectType
|
||||
|
||||
|
||||
def get_entity_id(entity_registry: er.EntityRegistry, key: str) -> str:
|
||||
"""Get entity ID by DVLA sensor key."""
|
||||
entity_id = entity_registry.async_get_entity_id(
|
||||
"sensor",
|
||||
DOMAIN,
|
||||
f"AB12CDE-{key}",
|
||||
)
|
||||
|
||||
assert entity_id is not None
|
||||
return entity_id
|
||||
|
||||
|
||||
def get_state(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
key: str,
|
||||
) -> State:
|
||||
"""Get state by DVLA sensor key."""
|
||||
state = hass.states.get(get_entity_id(entity_registry, key))
|
||||
|
||||
assert state is not None
|
||||
return state
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("key", "data"),
|
||||
[
|
||||
pytest.param("taxStatus", {"taxStatus": "Unexpected"}, id="invalid-tax-status"),
|
||||
pytest.param(
|
||||
"revenueWeight", {"revenueWeight": "not-a-number"}, id="invalid-weight"
|
||||
),
|
||||
pytest.param("taxDueDate", {"taxDueDate": "not-a-date"}, id="invalid-date"),
|
||||
pytest.param("taxDueDate", {"taxDueDate": 123}, id="non-string-date"),
|
||||
pytest.param(
|
||||
"monthOfFirstRegistration",
|
||||
{"monthOfFirstDvlaRegistration": "2024-05"},
|
||||
id="dvla-registration-month-is-not-a-substitute",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_unknown_sensor_value(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
setup_dvla_entry: Callable[[dict[str, Any] | None], Awaitable[MockConfigEntry]],
|
||||
key: str,
|
||||
data: dict[str, int | str],
|
||||
) -> None:
|
||||
"""Test absent or invalid values are exposed as unknown."""
|
||||
await setup_dvla_entry({"registrationNumber": "AB12CDE", "make": "FORD", **data})
|
||||
|
||||
assert get_state(hass, entity_registry, key).state == STATE_UNKNOWN
|
||||
|
||||
|
||||
async def test_sensor_platform(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
snapshot: SnapshotAssertion,
|
||||
setup_dvla_entry: Callable[
|
||||
[dict[str, Any] | None],
|
||||
Awaitable[MockConfigEntry],
|
||||
],
|
||||
) -> None:
|
||||
"""Test sensor platform setup."""
|
||||
entry = await setup_dvla_entry()
|
||||
|
||||
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
|
||||
|
||||
|
||||
async def test_no_engine_capacity_for_electric_vehicle(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
setup_dvla_entry: Callable[[dict[str, Any] | None], Awaitable[MockConfigEntry]],
|
||||
) -> None:
|
||||
"""Test an electric vehicle without engine capacity does not get that sensor."""
|
||||
await setup_dvla_entry(
|
||||
{"registrationNumber": "AB12CDE", "make": "FORD", "fuelType": "ELECTRICITY"}
|
||||
)
|
||||
|
||||
assert (
|
||||
entity_registry.async_get_entity_id(
|
||||
"sensor",
|
||||
DOMAIN,
|
||||
"AB12CDE-engineCapacity",
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert get_state(hass, entity_registry, "fuelType").state == "ELECTRICITY"
|
||||
|
||||
|
||||
async def test_engine_capacity_unit_conversion(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
setup_dvla_entry: Callable[[dict[str, Any] | None], Awaitable[MockConfigEntry]],
|
||||
) -> None:
|
||||
"""Test engine capacity can be displayed in litres."""
|
||||
await setup_dvla_entry()
|
||||
|
||||
entity_registry.async_update_entity_options(
|
||||
get_entity_id(entity_registry, "engineCapacity"),
|
||||
"sensor",
|
||||
{"unit_of_measurement": UnitOfVolume.LITERS},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = get_state(hass, entity_registry, "engineCapacity")
|
||||
assert float(state.state) == pytest.approx(1.998)
|
||||
assert state.attributes["unit_of_measurement"] == UnitOfVolume.LITERS
|
||||
|
||||
|
||||
async def test_revenue_weight_sensor_is_numeric(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
setup_dvla_entry: Callable[[dict[str, Any] | None], Awaitable[MockConfigEntry]],
|
||||
) -> None:
|
||||
"""Test revenue weight is exposed as a numeric weight sensor."""
|
||||
await setup_dvla_entry(
|
||||
{
|
||||
"registrationNumber": "AB12CDE",
|
||||
"make": "FORD",
|
||||
"revenueWeight": "3500",
|
||||
},
|
||||
)
|
||||
|
||||
state = get_state(hass, entity_registry, "revenueWeight")
|
||||
|
||||
assert state.state == "3500"
|
||||
assert state.attributes["unit_of_measurement"] == "kg"
|
||||
assert state.attributes["device_class"] == SensorDeviceClass.WEIGHT
|
||||
|
||||
|
||||
async def test_sensor_updates_after_weekly_refresh(
|
||||
hass: HomeAssistant,
|
||||
entity_registry: er.EntityRegistry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
mock_dvla_client: AsyncMock,
|
||||
setup_dvla_entry: Callable[[dict[str, Any] | None], Awaitable[MockConfigEntry]],
|
||||
vehicle_data: JsonObjectType,
|
||||
) -> None:
|
||||
"""Test weekly polling updates sensors, including newly returned values."""
|
||||
initial_data = vehicle_data.copy()
|
||||
initial_data.pop("motExpiryDate")
|
||||
mock_dvla_client.side_effect = [
|
||||
initial_data,
|
||||
{**vehicle_data, "taxStatus": "Untaxed"},
|
||||
]
|
||||
await setup_dvla_entry()
|
||||
|
||||
assert get_state(hass, entity_registry, "taxStatus").state == "taxed"
|
||||
assert get_state(hass, entity_registry, "motExpiryDate").state == STATE_UNKNOWN
|
||||
|
||||
freezer.tick(timedelta(days=6))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
mock_dvla_client.assert_awaited_once()
|
||||
|
||||
freezer.tick(timedelta(days=1))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_dvla_client.await_count == 2
|
||||
assert get_state(hass, entity_registry, "taxStatus").state == "untaxed"
|
||||
assert (
|
||||
get_state(hass, entity_registry, "motExpiryDate").state
|
||||
== vehicle_data["motExpiryDate"]
|
||||
)
|
||||
|
||||
|
||||
async def test_device_entry_type(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
setup_dvla_entry: Callable[[dict[str, Any] | None], Awaitable[MockConfigEntry]],
|
||||
) -> None:
|
||||
"""Test DVLA device is marked as a service."""
|
||||
entry = await setup_dvla_entry()
|
||||
|
||||
device = device_registry.async_get_device_by_identifier(
|
||||
(DOMAIN, "AB12CDE"),
|
||||
entry.entry_id,
|
||||
)
|
||||
|
||||
assert device is not None
|
||||
assert device.entry_type is DeviceEntryType.SERVICE
|
||||
assert device.manufacturer == "FORD"
|
||||
assert device.model is None
|
||||
Reference in New Issue
Block a user