From 2814ed5003da1aa9e82bfa4ca0d5fb77ed87a223 Mon Sep 17 00:00:00 2001 From: Ron Weikamp <15732230+ronweikamp@users.noreply.github.com> Date: Thu, 30 May 2024 17:42:34 +0200 Subject: [PATCH] Add allow_negative configuration option to DurationSelector (#116134) * Add configuration option positive to DurationSelector * Rename to allow_negative in conjunction with a deprecation notice Co-authored-by: Erik Montnemery --------- Co-authored-by: Erik Montnemery --- homeassistant/helpers/selector.py | 8 +++++++- tests/helpers/test_selector.py | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/homeassistant/helpers/selector.py b/homeassistant/helpers/selector.py index c103999bd33..1db4dd9f80b 100644 --- a/homeassistant/helpers/selector.py +++ b/homeassistant/helpers/selector.py @@ -718,6 +718,7 @@ class DurationSelectorConfig(TypedDict, total=False): """Class to represent a duration selector config.""" enable_day: bool + allow_negative: bool @SELECTORS.register("duration") @@ -731,6 +732,8 @@ class DurationSelector(Selector[DurationSelectorConfig]): # Enable day field in frontend. A selection with `days` set is allowed # even if `enable_day` is not set vol.Optional("enable_day"): cv.boolean, + # Allow negative durations. Will default to False in HA Core 2025.6.0. + vol.Optional("allow_negative"): cv.boolean, } ) @@ -740,7 +743,10 @@ class DurationSelector(Selector[DurationSelectorConfig]): def __call__(self, data: Any) -> dict[str, float]: """Validate the passed selection.""" - cv.time_period_dict(data) + if self.config.get("allow_negative", True): + cv.time_period_dict(data) + else: + cv.positive_time_period_dict(data) return cast(dict[str, float], data) diff --git a/tests/helpers/test_selector.py b/tests/helpers/test_selector.py index 5e6209f2c6c..6db313baa24 100644 --- a/tests/helpers/test_selector.py +++ b/tests/helpers/test_selector.py @@ -745,6 +745,11 @@ def test_attribute_selector_schema( ({"seconds": 10}, {"days": 10}), (None, {}), ), + ( + {"allow_negative": False}, + ({"seconds": 10}, {"days": 10}), + (None, {}, {"seconds": -1}), + ), ], ) def test_duration_selector_schema(schema, valid_selections, invalid_selections) -> None: