async def test_event_update(u: UpdatedTime): m = MagicMock() u.set(pd_now(UTC)) list = HABApp.core.EventBusListener( 'test', HABApp.core.WrappedFunction(m, name='MockFunc')) HABApp.core.EventBus.add_listener(list) u.set(pd_now(UTC)) await asyncio.sleep(1) m.assert_not_called() await asyncio.sleep(0.1) m.assert_called_once() c = m.call_args[0][0] assert isinstance(c, HABApp.core.events.ItemNoUpdateEvent) assert c.name == 'test' assert c.seconds == 1 await asyncio.sleep(2) assert m.call_count == 2 c = m.call_args[0][0] assert isinstance(c, HABApp.core.events.ItemNoUpdateEvent) assert c.name == 'test' assert c.seconds == 3 list.cancel()
def test_time_change(self): i = Item('test') i.set_value('test') i._last_change.set(pd_now(UTC) - timedelta(seconds=5)) i._last_update.set(pd_now(UTC) - timedelta(seconds=5)) i.set_value('test1') self.assertGreater(i._last_update.dt, pd_now(UTC) - timedelta(milliseconds=100)) self.assertGreater(i._last_change.dt, pd_now(UTC) - timedelta(milliseconds=100))
def test_time_value_change(self): i = self.CLS('test') for value in self.TEST_VALUES: i._last_change.set(pd_now(UTC) - timedelta(seconds=5), events=False) i._last_update.set(pd_now(UTC) - timedelta(seconds=5), events=False) i.set_value(value) assert i._last_update.dt > pd_now(UTC) - timedelta( milliseconds=100) assert i._last_change.dt > pd_now(UTC) - timedelta( milliseconds=100)
async def test_cancel_running(u: UpdatedTime): u.set(pd_now(UTC)) w1 = u.tasks[0] w2 = u.tasks[1] await asyncio.sleep(1.1) assert w1.fut.task.done() assert not w2.fut.task.done() assert w2 in u.tasks w2.cancel() await asyncio.sleep(0.05) u.set(pd_now(UTC)) await asyncio.sleep(0.05) assert w2 not in u.tasks
def __init__(self, name: str): super().__init__() assert isinstance(name, str), type(name) self._name: str = name _now = pd_now(UTC) self._last_change: ChangedTime = ChangedTime(self._name, _now) self._last_update: UpdatedTime = UpdatedTime(self._name, _now)
def c(): a = ChangedTime('test', pd_now(UTC)) w1 = a.add_watch(1) w2 = a.add_watch(3) yield a # cancel the rest of the running tasks w1.cancel() w2.cancel()
def set_value(self, new_value) -> bool: """Set a new value without creating events on the event bus :param new_value: new value of the item :return: True if state has changed """ state_changed = self.value != new_value _now = pd_now(UTC) if state_changed: self._last_change.set(_now) self._last_update.set(_now) self.value = new_value return state_changed
def test_sec_timedelta(): a = UpdatedTime('test', pd_now(UTC)) w1 = a.add_watch(1) # We return the same object because it is the same time assert w1 is a.add_watch(timedelta(seconds=1)) w2 = a.add_watch(timedelta(seconds=3)) assert w2.fut.secs == 3 w3 = a.add_watch(timedelta(minutes=3)) assert w3.fut.secs == 3 * 60 w1.cancel() w2.cancel() w3.cancel()
def __update_timestamps(self, changed: bool): _now = pd_now(UTC) self._last_update.set(_now) if changed: self._last_change.set(_now) return None