Remove deprecated format for date(time) sensors (#65734)

This commit is contained in:
Franck Nijhof 2022-02-05 08:42:29 +01:00 committed by GitHub
parent fbe4d42729
commit e242796394
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 91 deletions

View File

@ -9,7 +9,6 @@ import inspect
import logging import logging
from typing import Any, Final, cast, final from typing import Any, Final, cast, final
import ciso8601
import voluptuous as vol import voluptuous as vol
from homeassistant.backports.enum import StrEnum from homeassistant.backports.enum import StrEnum
@ -371,44 +370,6 @@ class SensorEntity(Entity):
value = self.native_value value = self.native_value
device_class = self.device_class device_class = self.device_class
# We have an old non-datetime value, warn about it and convert it during
# the deprecation period.
if (
value is not None
and device_class in (DEVICE_CLASS_DATE, DEVICE_CLASS_TIMESTAMP)
and not isinstance(value, (date, datetime))
):
# Deprecation warning for date/timestamp device classes
if not self.__datetime_as_string_deprecation_logged:
report_issue = self._suggest_report_issue()
_LOGGER.warning(
"%s is providing a string for its state, while the device "
"class is '%s', this is not valid and will be unsupported "
"from Home Assistant 2022.2. Please %s",
self.entity_id,
device_class,
report_issue,
)
self.__datetime_as_string_deprecation_logged = True
# Anyways, lets validate the date at least..
try:
value = ciso8601.parse_datetime(str(value))
except (ValueError, IndexError) as error:
raise ValueError(
f"Invalid date/datetime: {self.entity_id} provide state '{value}', "
f"while it has device class '{device_class}'"
) from error
if value.tzinfo is not None and value.tzinfo != timezone.utc:
value = value.astimezone(timezone.utc)
# Convert the date object to a standardized state string.
if device_class == DEVICE_CLASS_DATE:
return value.date().isoformat()
return value.isoformat(timespec="seconds")
# Received a datetime # Received a datetime
if value is not None and device_class == DEVICE_CLASS_TIMESTAMP: if value is not None and device_class == DEVICE_CLASS_TIMESTAMP:
try: try:
@ -427,7 +388,7 @@ class SensorEntity(Entity):
return value.isoformat(timespec="seconds") return value.isoformat(timespec="seconds")
except (AttributeError, TypeError) as err: except (AttributeError, TypeError) as err:
raise ValueError( raise ValueError(
f"Invalid datetime: {self.entity_id} has a timestamp device class" f"Invalid datetime: {self.entity_id} has a timestamp device class "
f"but does not provide a datetime state but {type(value)}" f"but does not provide a datetime state but {type(value)}"
) from err ) from err
@ -437,7 +398,7 @@ class SensorEntity(Entity):
return value.isoformat() # type: ignore return value.isoformat() # type: ignore
except (AttributeError, TypeError) as err: except (AttributeError, TypeError) as err:
raise ValueError( raise ValueError(
f"Invalid date: {self.entity_id} has a date device class" f"Invalid date: {self.entity_id} has a date device class "
f"but does not provide a date state but {type(value)}" f"but does not provide a date state but {type(value)}"
) from err ) from err

View File

@ -165,71 +165,28 @@ async def test_datetime_conversion(hass, caplog, enable_custom_integrations):
@pytest.mark.parametrize( @pytest.mark.parametrize(
"device_class,native_value,state_value", "device_class,state_value,provides",
[ [
(SensorDeviceClass.DATE, "2021-11-09", "2021-11-09"), (SensorDeviceClass.DATE, "2021-01-09", "date"),
( (SensorDeviceClass.TIMESTAMP, "2021-01-09T12:00:00+00:00", "datetime"),
SensorDeviceClass.DATE,
"2021-01-09T12:00:00+00:00",
"2021-01-09",
),
(
SensorDeviceClass.DATE,
"2021-01-09T00:00:00+01:00",
"2021-01-08",
),
(
SensorDeviceClass.TIMESTAMP,
"2021-01-09T12:00:00+00:00",
"2021-01-09T12:00:00+00:00",
),
(
SensorDeviceClass.TIMESTAMP,
"2021-01-09 12:00:00+00:00",
"2021-01-09T12:00:00+00:00",
),
(
SensorDeviceClass.TIMESTAMP,
"2021-01-09T12:00:00+04:00",
"2021-01-09T08:00:00+00:00",
),
(
SensorDeviceClass.TIMESTAMP,
"2021-01-09 12:00:00+01:00",
"2021-01-09T11:00:00+00:00",
),
(
SensorDeviceClass.TIMESTAMP,
"2021-01-09 12:00:00",
"2021-01-09T12:00:00",
),
(
SensorDeviceClass.TIMESTAMP,
"2021-01-09T12:00:00",
"2021-01-09T12:00:00",
),
], ],
) )
async def test_deprecated_datetime_str( async def test_deprecated_datetime_str(
hass, caplog, enable_custom_integrations, device_class, native_value, state_value hass, caplog, enable_custom_integrations, device_class, state_value, provides
): ):
"""Test warning on deprecated str for a date(time) value.""" """Test warning on deprecated str for a date(time) value."""
platform = getattr(hass.components, "test.sensor") platform = getattr(hass.components, "test.sensor")
platform.init(empty=True) platform.init(empty=True)
platform.ENTITIES["0"] = platform.MockSensor( platform.ENTITIES["0"] = platform.MockSensor(
name="Test", native_value=native_value, device_class=device_class name="Test", native_value=state_value, device_class=device_class
) )
entity0 = platform.ENTITIES["0"]
assert await async_setup_component(hass, "sensor", {"sensor": {"platform": "test"}}) assert await async_setup_component(hass, "sensor", {"sensor": {"platform": "test"}})
await hass.async_block_till_done() await hass.async_block_till_done()
state = hass.states.get(entity0.entity_id)
assert state.state == state_value
assert ( assert (
"is providing a string for its state, while the device class is " f"Invalid {provides}: sensor.test has a {device_class} device class "
f"'{device_class}', this is not valid and will be unsupported " f"but does not provide a {provides} state but {type(state_value)}"
"from Home Assistant 2022.2."
) in caplog.text ) in caplog.text