Fix history stats device class when type is not time (#77855)

This commit is contained in:
J. Nick Koston 2022-09-05 13:56:27 -05:00 committed by GitHub
parent 6867029062
commit 6644f62ad2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 2 deletions

View File

@ -143,7 +143,6 @@ class HistoryStatsSensorBase(
class HistoryStatsSensor(HistoryStatsSensorBase):
"""A HistoryStats sensor."""
_attr_device_class = SensorDeviceClass.DURATION
_attr_state_class = SensorStateClass.MEASUREMENT
def __init__(
@ -157,6 +156,8 @@ class HistoryStatsSensor(HistoryStatsSensorBase):
self._attr_native_unit_of_measurement = UNITS[sensor_type]
self._type = sensor_type
self._process_update()
if self._type == CONF_TYPE_TIME:
self._attr_device_class = SensorDeviceClass.DURATION
@callback
def _process_update(self) -> None:

View File

@ -9,7 +9,7 @@ import pytest
from homeassistant import config as hass_config
from homeassistant.components.history_stats import DOMAIN
from homeassistant.const import SERVICE_RELOAD, STATE_UNKNOWN
from homeassistant.const import ATTR_DEVICE_CLASS, SERVICE_RELOAD, STATE_UNKNOWN
import homeassistant.core as ha
from homeassistant.helpers.entity_component import async_update_entity
from homeassistant.setup import async_setup_component, setup_component
@ -1496,3 +1496,46 @@ async def test_end_time_with_microseconds_zeroed(time_zone, hass, recorder_mock)
async_fire_time_changed(hass, rolled_to_next_day_plus_18)
await hass.async_block_till_done()
assert hass.states.get("sensor.heatpump_compressor_today").state == "16.0"
async def test_device_classes(hass, recorder_mock):
"""Test the device classes."""
await async_setup_component(
hass,
"sensor",
{
"sensor": [
{
"platform": "history_stats",
"entity_id": "binary_sensor.test_id",
"name": "time",
"state": "on",
"start": "{{ as_timestamp(now()) - 3600 }}",
"end": "{{ as_timestamp(now()) + 3600 }}",
"type": "time",
},
{
"platform": "history_stats",
"entity_id": "binary_sensor.test_id",
"name": "count",
"state": "on",
"start": "{{ as_timestamp(now()) - 3600 }}",
"end": "{{ as_timestamp(now()) + 3600 }}",
"type": "count",
},
{
"platform": "history_stats",
"entity_id": "binary_sensor.test_id",
"name": "ratio",
"state": "on",
"start": "{{ as_timestamp(now()) - 3600 }}",
"end": "{{ as_timestamp(now()) + 3600 }}",
"type": "ratio",
},
]
},
)
await hass.async_block_till_done()
assert hass.states.get("sensor.time").attributes[ATTR_DEVICE_CLASS] == "duration"
assert ATTR_DEVICE_CLASS not in hass.states.get("sensor.ratio").attributes
assert ATTR_DEVICE_CLASS not in hass.states.get("sensor.count").attributes