diff --git a/homeassistant/util/__init__.py b/homeassistant/util/__init__.py index 1ce18792acc9..6bb6d8458c31 100644 --- a/homeassistant/util/__init__.py +++ b/homeassistant/util/__init__.py @@ -148,9 +148,6 @@ class Throttle: def throttled_value() -> None: # type: ignore[misc] """Stand-in function for when real func is being throttled.""" - if self.limit_no_throttle is not None: - method = Throttle(self.limit_no_throttle)(method) - # Different methods that can be passed in: # - a function # - an unbound function on a class @@ -189,11 +186,17 @@ class Throttle: if not throttle[0].acquire(False): return throttled_value() - # Check if method is never called or no_throttle is given - force = kwargs.pop("no_throttle", False) or not throttle[1] + no_throttle = kwargs.pop("no_throttle", False) try: - if force or utcnow() - throttle[1] > self.min_time: + # limit_no_throttle always applies, min_time only without no_throttle + if not throttle[1] or ( + (no_throttle or utcnow() - throttle[1] > self.min_time) + and ( + self.limit_no_throttle is None + or utcnow() - throttle[1] > self.limit_no_throttle + ) + ): result = method(*args, **kwargs) throttle[1] = utcnow() return result # type: ignore[no-any-return] diff --git a/tests/util/test_init.py b/tests/util/test_init.py index 47e9981902cb..c1a42f1f60b5 100644 --- a/tests/util/test_init.py +++ b/tests/util/test_init.py @@ -146,6 +146,30 @@ def test_throttle() -> None: assert len(calls2) == 2 +def test_throttle_refused_no_throttle_call_keeps_cooldown() -> None: + """Test a no_throttle call refused by limit_no_throttle keeps the cooldown.""" + calls = [] + + @util.Throttle(timedelta(seconds=10), timedelta(seconds=5)) + def test_throttle(): + calls.append(1) + return True + + now = dt_util.utcnow() + + with patch("homeassistant.util.utcnow", return_value=now): + assert test_throttle() is True + + # Refused by limit_no_throttle, must not restart the min_time cooldown + with patch("homeassistant.util.utcnow", return_value=now + timedelta(seconds=2)): + assert test_throttle(no_throttle=True) is None + + with patch("homeassistant.util.utcnow", return_value=now + timedelta(seconds=11)): + assert test_throttle() is True + + assert len(calls) == 2 + + def test_throttle_per_instance() -> None: """Test that the throttle method is done per instance of a class."""