diff --git a/homeassistant/helpers/condition.py b/homeassistant/helpers/condition.py index 4785612f114..e4335e2f2e4 100644 --- a/homeassistant/helpers/condition.py +++ b/homeassistant/helpers/condition.py @@ -225,15 +225,27 @@ def template_from_config(config, config_validation=True): def time(before=None, after=None, weekday=None): - """Test if local time condition matches.""" + """Test if local time condition matches. + + Handle the fact that time is continuous and we may be testing for + a period that crosses midnight. In that case it is easier to test + for the opposite. "(23:59 <= now < 00:01)" would be the same as + "not (00:01 <= now < 23:59)". + """ now = dt_util.now() now_time = now.time() - if before is not None and now_time > before: - return False + if after is None: + after = dt_util.dt.time(0) + if before is None: + before = dt_util.dt.time(23, 59, 59, 999999) - if after is not None and now_time < after: - return False + if after < before: + if not after <= now_time < before: + return False + else: + if before <= now_time < after: + return False if weekday is not None: now_weekday = WEEKDAYS[now.weekday()] diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index 8eaee797e73..e1813f6ba1c 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -1,5 +1,8 @@ """Test the condition helper.""" +from unittest.mock import patch + from homeassistant.helpers import condition +from homeassistant.util import dt from tests.common import get_test_home_assistant @@ -66,3 +69,28 @@ class TestConditionHelper: self.hass.states.set('sensor.temperature', 100) assert test(self.hass) + + def test_time_window(self): + """Test time condition windows.""" + sixam = dt.parse_time("06:00:00") + sixpm = dt.parse_time("18:00:00") + + with patch('homeassistant.helpers.condition.dt_util.now', + return_value=dt.now().replace(hour=3)): + assert not condition.time(after=sixam, before=sixpm) + assert condition.time(after=sixpm, before=sixam) + + with patch('homeassistant.helpers.condition.dt_util.now', + return_value=dt.now().replace(hour=9)): + assert condition.time(after=sixam, before=sixpm) + assert not condition.time(after=sixpm, before=sixam) + + with patch('homeassistant.helpers.condition.dt_util.now', + return_value=dt.now().replace(hour=15)): + assert condition.time(after=sixam, before=sixpm) + assert not condition.time(after=sixpm, before=sixam) + + with patch('homeassistant.helpers.condition.dt_util.now', + return_value=dt.now().replace(hour=21)): + assert not condition.time(after=sixam, before=sixpm) + assert condition.time(after=sixpm, before=sixam)