Allow time condition windows to cross midnight. (#2158)

* Allow time condition windows to cross midnight.

* Address comments.

Fold _in_time_window back into the time() condition test.
Use specific time values to test the time window.
This commit is contained in:
Jan Harkes 2016-05-29 17:32:32 -04:00 committed by Paulus Schoutsen
parent 952436aa0b
commit afe84c2a8b
2 changed files with 45 additions and 5 deletions

View File

@ -225,14 +225,26 @@ 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:
if after < before:
if not after <= now_time < before:
return False
else:
if before <= now_time < after:
return False
if weekday is not None:

View File

@ -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)