From ce6921d73ccba927e409e63674eb9bc8620538a6 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Fri, 3 Sep 2021 22:35:59 +0200 Subject: [PATCH] Use EntityDescription - picnic (#55682) * Use EntityDescription - picnic * Change _attr_extra_state_attributes to be static * Fix tests --- homeassistant/components/picnic/const.py | 214 +++++++++++++--------- homeassistant/components/picnic/sensor.py | 66 +++---- tests/components/picnic/test_sensor.py | 4 +- 3 files changed, 150 insertions(+), 134 deletions(-) diff --git a/homeassistant/components/picnic/const.py b/homeassistant/components/picnic/const.py index 18a62589732..e37f85cb28b 100644 --- a/homeassistant/components/picnic/const.py +++ b/homeassistant/components/picnic/const.py @@ -1,5 +1,12 @@ """Constants for the Picnic integration.""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Callable, Literal + +from homeassistant.components.sensor import SensorEntityDescription from homeassistant.const import CURRENCY_EURO, DEVICE_CLASS_TIMESTAMP +from homeassistant.helpers.typing import StateType DOMAIN = "picnic" @@ -28,91 +35,122 @@ SENSOR_LAST_ORDER_ETA_END = "last_order_eta_end" SENSOR_LAST_ORDER_DELIVERY_TIME = "last_order_delivery_time" SENSOR_LAST_ORDER_TOTAL_PRICE = "last_order_total_price" -SENSOR_TYPES = { - SENSOR_CART_ITEMS_COUNT: { - "icon": "mdi:format-list-numbered", - "data_type": CART_DATA, - "state": lambda cart: cart.get("total_count", 0), - }, - SENSOR_CART_TOTAL_PRICE: { - "unit": CURRENCY_EURO, - "icon": "mdi:currency-eur", - "default_enabled": True, - "data_type": CART_DATA, - "state": lambda cart: cart.get("total_price", 0) / 100, - }, - SENSOR_SELECTED_SLOT_START: { - "class": DEVICE_CLASS_TIMESTAMP, - "icon": "mdi:calendar-start", - "default_enabled": True, - "data_type": SLOT_DATA, - "state": lambda slot: slot.get("window_start"), - }, - SENSOR_SELECTED_SLOT_END: { - "class": DEVICE_CLASS_TIMESTAMP, - "icon": "mdi:calendar-end", - "default_enabled": True, - "data_type": SLOT_DATA, - "state": lambda slot: slot.get("window_end"), - }, - SENSOR_SELECTED_SLOT_MAX_ORDER_TIME: { - "class": DEVICE_CLASS_TIMESTAMP, - "icon": "mdi:clock-alert-outline", - "default_enabled": True, - "data_type": SLOT_DATA, - "state": lambda slot: slot.get("cut_off_time"), - }, - SENSOR_SELECTED_SLOT_MIN_ORDER_VALUE: { - "unit": CURRENCY_EURO, - "icon": "mdi:currency-eur", - "default_enabled": True, - "data_type": SLOT_DATA, - "state": lambda slot: slot["minimum_order_value"] / 100 - if slot.get("minimum_order_value") - else None, - }, - SENSOR_LAST_ORDER_SLOT_START: { - "class": DEVICE_CLASS_TIMESTAMP, - "icon": "mdi:calendar-start", - "data_type": LAST_ORDER_DATA, - "state": lambda last_order: last_order.get("slot", {}).get("window_start"), - }, - SENSOR_LAST_ORDER_SLOT_END: { - "class": DEVICE_CLASS_TIMESTAMP, - "icon": "mdi:calendar-end", - "data_type": LAST_ORDER_DATA, - "state": lambda last_order: last_order.get("slot", {}).get("window_end"), - }, - SENSOR_LAST_ORDER_STATUS: { - "icon": "mdi:list-status", - "data_type": LAST_ORDER_DATA, - "state": lambda last_order: last_order.get("status"), - }, - SENSOR_LAST_ORDER_ETA_START: { - "class": DEVICE_CLASS_TIMESTAMP, - "icon": "mdi:clock-start", - "default_enabled": True, - "data_type": LAST_ORDER_DATA, - "state": lambda last_order: last_order.get("eta", {}).get("start"), - }, - SENSOR_LAST_ORDER_ETA_END: { - "class": DEVICE_CLASS_TIMESTAMP, - "icon": "mdi:clock-end", - "default_enabled": True, - "data_type": LAST_ORDER_DATA, - "state": lambda last_order: last_order.get("eta", {}).get("end"), - }, - SENSOR_LAST_ORDER_DELIVERY_TIME: { - "class": DEVICE_CLASS_TIMESTAMP, - "icon": "mdi:timeline-clock", - "default_enabled": True, - "data_type": LAST_ORDER_DATA, - "state": lambda last_order: last_order.get("delivery_time", {}).get("start"), - }, - SENSOR_LAST_ORDER_TOTAL_PRICE: { - "unit": CURRENCY_EURO, - "icon": "mdi:cash-marker", - "data_type": LAST_ORDER_DATA, - "state": lambda last_order: last_order.get("total_price", 0) / 100, - }, -} + +@dataclass +class PicnicRequiredKeysMixin: + """Mixin for required keys.""" + + data_type: Literal["cart_data", "slot_data", "last_order_data"] + state: Callable[[Any], StateType] + + +@dataclass +class PicnicSensorEntityDescription(SensorEntityDescription, PicnicRequiredKeysMixin): + """Describes Picnic sensor entity.""" + + entity_registry_enabled_default: bool = False + + +SENSOR_TYPES: tuple[PicnicSensorEntityDescription, ...] = ( + PicnicSensorEntityDescription( + key=SENSOR_CART_ITEMS_COUNT, + icon="mdi:format-list-numbered", + data_type="cart_data", + state=lambda cart: cart.get("total_count", 0), + ), + PicnicSensorEntityDescription( + key=SENSOR_CART_TOTAL_PRICE, + native_unit_of_measurement=CURRENCY_EURO, + icon="mdi:currency-eur", + entity_registry_enabled_default=True, + data_type="cart_data", + state=lambda cart: cart.get("total_price", 0) / 100, + ), + PicnicSensorEntityDescription( + key=SENSOR_SELECTED_SLOT_START, + device_class=DEVICE_CLASS_TIMESTAMP, + icon="mdi:calendar-start", + entity_registry_enabled_default=True, + data_type="slot_data", + state=lambda slot: slot.get("window_start"), + ), + PicnicSensorEntityDescription( + key=SENSOR_SELECTED_SLOT_END, + device_class=DEVICE_CLASS_TIMESTAMP, + icon="mdi:calendar-end", + entity_registry_enabled_default=True, + data_type="slot_data", + state=lambda slot: slot.get("window_end"), + ), + PicnicSensorEntityDescription( + key=SENSOR_SELECTED_SLOT_MAX_ORDER_TIME, + device_class=DEVICE_CLASS_TIMESTAMP, + icon="mdi:clock-alert-outline", + entity_registry_enabled_default=True, + data_type="slot_data", + state=lambda slot: slot.get("cut_off_time"), + ), + PicnicSensorEntityDescription( + key=SENSOR_SELECTED_SLOT_MIN_ORDER_VALUE, + native_unit_of_measurement=CURRENCY_EURO, + icon="mdi:currency-eur", + entity_registry_enabled_default=True, + data_type="slot_data", + state=lambda slot: ( + slot["minimum_order_value"] / 100 + if slot.get("minimum_order_value") + else None + ), + ), + PicnicSensorEntityDescription( + key=SENSOR_LAST_ORDER_SLOT_START, + device_class=DEVICE_CLASS_TIMESTAMP, + icon="mdi:calendar-start", + data_type="last_order_data", + state=lambda last_order: last_order.get("slot", {}).get("window_start"), + ), + PicnicSensorEntityDescription( + key=SENSOR_LAST_ORDER_SLOT_END, + device_class=DEVICE_CLASS_TIMESTAMP, + icon="mdi:calendar-end", + data_type="last_order_data", + state=lambda last_order: last_order.get("slot", {}).get("window_end"), + ), + PicnicSensorEntityDescription( + key=SENSOR_LAST_ORDER_STATUS, + icon="mdi:list-status", + data_type="last_order_data", + state=lambda last_order: last_order.get("status"), + ), + PicnicSensorEntityDescription( + key=SENSOR_LAST_ORDER_ETA_START, + device_class=DEVICE_CLASS_TIMESTAMP, + icon="mdi:clock-start", + entity_registry_enabled_default=True, + data_type="last_order_data", + state=lambda last_order: last_order.get("eta", {}).get("start"), + ), + PicnicSensorEntityDescription( + key=SENSOR_LAST_ORDER_ETA_END, + device_class=DEVICE_CLASS_TIMESTAMP, + icon="mdi:clock-end", + entity_registry_enabled_default=True, + data_type="last_order_data", + state=lambda last_order: last_order.get("eta", {}).get("end"), + ), + PicnicSensorEntityDescription( + key=SENSOR_LAST_ORDER_DELIVERY_TIME, + device_class=DEVICE_CLASS_TIMESTAMP, + icon="mdi:timeline-clock", + entity_registry_enabled_default=True, + data_type="last_order_data", + state=lambda last_order: last_order.get("delivery_time", {}).get("start"), + ), + PicnicSensorEntityDescription( + key=SENSOR_LAST_ORDER_TOTAL_PRICE, + native_unit_of_measurement=CURRENCY_EURO, + icon="mdi:cash-marker", + data_type="last_order_data", + state=lambda last_order: last_order.get("total_price", 0) / 100, + ), +) diff --git a/homeassistant/components/picnic/sensor.py b/homeassistant/components/picnic/sensor.py index 57f24180c03..34ad2943d8e 100644 --- a/homeassistant/components/picnic/sensor.py +++ b/homeassistant/components/picnic/sensor.py @@ -13,7 +13,14 @@ from homeassistant.helpers.update_coordinator import ( DataUpdateCoordinator, ) -from .const import ADDRESS, ATTRIBUTION, CONF_COORDINATOR, DOMAIN, SENSOR_TYPES +from .const import ( + ADDRESS, + ATTRIBUTION, + CONF_COORDINATOR, + DOMAIN, + SENSOR_TYPES, + PicnicSensorEntityDescription, +) async def async_setup_entry( @@ -24,8 +31,8 @@ async def async_setup_entry( # Add an entity for each sensor type async_add_entities( - PicnicSensor(picnic_coordinator, config_entry, sensor_type, props) - for sensor_type, props in SENSOR_TYPES.items() + PicnicSensor(picnic_coordinator, config_entry, description) + for description in SENSOR_TYPES ) return True @@ -34,71 +41,40 @@ async def async_setup_entry( class PicnicSensor(SensorEntity, CoordinatorEntity): """The CoordinatorEntity subclass representing Picnic sensors.""" + entity_description: PicnicSensorEntityDescription + _attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION} + def __init__( self, coordinator: DataUpdateCoordinator[Any], config_entry: ConfigEntry, - sensor_type, - properties, - ): + description: PicnicSensorEntityDescription, + ) -> None: """Init a Picnic sensor.""" super().__init__(coordinator) + self.entity_description = description - self.sensor_type = sensor_type - self.properties = properties - self.entity_id = f"sensor.picnic_{sensor_type}" + self.entity_id = f"sensor.picnic_{description.key}" self._service_unique_id = config_entry.unique_id - @property - def native_unit_of_measurement(self) -> str | None: - """Return the unit this state is expressed in.""" - return self.properties.get("unit") - - @property - def unique_id(self) -> str | None: - """Return a unique ID.""" - return f"{self._service_unique_id}.{self.sensor_type}" - - @property - def name(self) -> str | None: - """Return the name of the entity.""" - return self._to_capitalized_name(self.sensor_type) + self._attr_name = self._to_capitalized_name(description.key) + self._attr_unique_id = f"{config_entry.unique_id}.{description.key}" @property def native_value(self) -> StateType: """Return the state of the entity.""" data_set = ( - self.coordinator.data.get(self.properties["data_type"], {}) + self.coordinator.data.get(self.entity_description.data_type, {}) if self.coordinator.data is not None else {} ) - return self.properties["state"](data_set) - - @property - def device_class(self) -> str | None: - """Return the class of this device, from component DEVICE_CLASSES.""" - return self.properties.get("class") - - @property - def icon(self) -> str | None: - """Return the icon to use in the frontend, if any.""" - return self.properties["icon"] + return self.entity_description.state(data_set) @property def available(self) -> bool: """Return True if entity is available.""" return self.coordinator.last_update_success and self.state is not None - @property - def entity_registry_enabled_default(self) -> bool: - """Return if the entity should be enabled when first added to the entity registry.""" - return self.properties.get("default_enabled", False) - - @property - def extra_state_attributes(self): - """Return the sensor specific state attributes.""" - return {ATTR_ATTRIBUTION: ATTRIBUTION} - @property def device_info(self): """Return device info.""" diff --git a/tests/components/picnic/test_sensor.py b/tests/components/picnic/test_sensor.py index 098d86785ab..36aa06443df 100644 --- a/tests/components/picnic/test_sensor.py +++ b/tests/components/picnic/test_sensor.py @@ -85,6 +85,8 @@ DEFAULT_DELIVERY_RESPONSE = { ], } +SENSOR_KEYS = [desc.key for desc in SENSOR_TYPES] + @pytest.mark.usefixtures("hass_storage") class TestPicnicSensor(unittest.IsolatedAsyncioTestCase): @@ -161,7 +163,7 @@ class TestPicnicSensor(unittest.IsolatedAsyncioTestCase): async def _enable_all_sensors(self): """Enable all sensors of the Picnic integration.""" # Enable the sensors - for sensor_type in SENSOR_TYPES.keys(): + for sensor_type in SENSOR_KEYS: updated_entry = self.entity_registry.async_update_entity( f"sensor.picnic_{sensor_type}", disabled_by=None )