def test_setting_rising(self):
        """ Test retrieving sun setting and rising. """
        # Compare it with the real data
        self.hass.config.latitude = '32.87336'
        self.hass.config.longitude = '117.22743'
        sun.setup(self.hass, None)

        observer = ephem.Observer()
        observer.lat = '32.87336'  # pylint: disable=assigning-non-slot
        observer.long = '117.22743'  # pylint: disable=assigning-non-slot

        utc_now = dt_util.utcnow()
        body_sun = ephem.Sun()  # pylint: disable=no-member
        next_rising_dt = observer.next_rising(
            body_sun, start=utc_now).datetime().replace(tzinfo=dt_util.UTC)
        next_setting_dt = observer.next_setting(
            body_sun, start=utc_now).datetime().replace(tzinfo=dt_util.UTC)

        # Home Assistant strips out microseconds
        # strip it out of the datetime objects
        next_rising_dt = dt_util.strip_microseconds(next_rising_dt)
        next_setting_dt = dt_util.strip_microseconds(next_setting_dt)

        self.assertEqual(next_rising_dt, sun.next_rising_utc(self.hass))
        self.assertEqual(next_setting_dt, sun.next_setting_utc(self.hass))

        # Point it at a state without the proper attributes
        self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON)
        self.assertIsNone(sun.next_rising(self.hass))
        self.assertIsNone(sun.next_setting(self.hass))

        # Point it at a non-existing state
        self.assertIsNone(sun.next_rising(self.hass, 'non.existing'))
        self.assertIsNone(sun.next_setting(self.hass, 'non.existing'))
Example #2
0
    def test_setting_rising(self):
        """ Test retrieving sun setting and rising. """
        # Compare it with the real data
        self.hass.config.latitude = '32.87336'
        self.hass.config.longitude = '117.22743'
        sun.setup(self.hass, None)

        observer = ephem.Observer()
        observer.lat = '32.87336'  # pylint: disable=assigning-non-slot
        observer.long = '117.22743'  # pylint: disable=assigning-non-slot

        utc_now = dt_util.utcnow()
        body_sun = ephem.Sun()  # pylint: disable=no-member
        next_rising_dt = observer.next_rising(
            body_sun, start=utc_now).datetime().replace(tzinfo=dt_util.UTC)
        next_setting_dt = observer.next_setting(
            body_sun, start=utc_now).datetime().replace(tzinfo=dt_util.UTC)

        # Home Assistant strips out microseconds
        # strip it out of the datetime objects
        next_rising_dt = dt_util.strip_microseconds(next_rising_dt)
        next_setting_dt = dt_util.strip_microseconds(next_setting_dt)

        self.assertEqual(next_rising_dt, sun.next_rising_utc(self.hass))
        self.assertEqual(next_setting_dt, sun.next_setting_utc(self.hass))

        # Point it at a state without the proper attributes
        self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON)
        self.assertIsNone(sun.next_rising(self.hass))
        self.assertIsNone(sun.next_setting(self.hass))

        # Point it at a non-existing state
        self.assertIsNone(sun.next_rising(self.hass, 'non.existing'))
        self.assertIsNone(sun.next_setting(self.hass, 'non.existing'))
Example #3
0
    def test_humanify_filter_sensor(self):
        """Test humanify filter too frequent sensor values."""
        entity_id = 'sensor.bla'

        pointA = dt_util.strip_microseconds(dt_util.utcnow().replace(minute=2))
        pointB = pointA.replace(minute=5)
        pointC = pointA + timedelta(minutes=logbook.GROUP_BY_MINUTES)

        eventA = self.create_state_changed_event(pointA, entity_id, 10)
        eventB = self.create_state_changed_event(pointB, entity_id, 20)
        eventC = self.create_state_changed_event(pointC, entity_id, 30)

        entries = list(logbook.humanify((eventA, eventB, eventC)))

        self.assertEqual(2, len(entries))
        self.assert_entry(entries[0],
                          pointB,
                          'bla',
                          domain='sensor',
                          entity_id=entity_id)

        self.assert_entry(entries[1],
                          pointC,
                          'bla',
                          domain='sensor',
                          entity_id=entity_id)
Example #4
0
    def __init__(self, entity_id, state, attributes=None, last_changed=None, last_updated=None):
        if not ENTITY_ID_PATTERN.match(entity_id):
            raise InvalidEntityFormatError(
                ("Invalid entity id encountered: {}. " "Format should be <domain>.<object_id>").format(entity_id)
            )

        self.entity_id = entity_id.lower()
        self.state = state
        self.attributes = attributes or {}
        self.last_updated = date_util.strip_microseconds(last_updated or date_util.utcnow())

        # Strip microsecond from last_changed else we cannot guarantee
        # state == State.from_dict(state.as_dict())
        # This behavior occurs because to_dict uses datetime_to_str
        # which does not preserve microseconds
        self.last_changed = date_util.strip_microseconds(last_changed or self.last_updated)
Example #5
0
 def __init__(self, event_type, data=None, origin=EventOrigin.local,
              time_fired=None):
     self.event_type = event_type
     self.data = data or {}
     self.origin = origin
     self.time_fired = dt_util.strip_microseconds(
         time_fired or dt_util.utcnow())
Example #6
0
def get_changed_since(states, utc_point_in_time):
    """
    Returns all states that have been changed since utc_point_in_time.
    """
    point_in_time = dt_util.strip_microseconds(utc_point_in_time)

    return [state for state in states if state.last_updated >= point_in_time]
Example #7
0
    def test_notify_file(self):
        """Test the notify file output."""
        with tempfile.TemporaryDirectory() as tempdirname:
            filename = os.path.join(tempdirname, 'notify.txt')
            message = 'one, two, testing, testing'
            self.assertTrue(
                notify.setup(
                    self.hass, {
                        'notify': {
                            'name': 'test',
                            'platform': 'file',
                            'filename': filename,
                            'timestamp': 0
                        }
                    }))
            title = '{} notifications (Log started: {})\n{}\n'.format(
                ATTR_TITLE_DEFAULT,
                dt_util.strip_microseconds(dt_util.utcnow()), '-' * 80)

            self.hass.services.call('notify',
                                    'test', {'message': message},
                                    blocking=True)

            result = open(filename).read()
            self.assertEqual(result, "{}{}\n".format(title, message))
Example #8
0
    def get_since(self, point_in_time):
        """
        Returns all states that have been changed since point_in_time.
        """
        point_in_time = date_util.strip_microseconds(point_in_time)

        with self._lock:
            return [state for state in self._states.values() if state.last_updated >= point_in_time]
Example #9
0
    def get_since(self, point_in_time):
        """
        Returns all states that have been changed since point_in_time.
        """
        point_in_time = date_util.strip_microseconds(point_in_time)

        with self._lock:
            return [state for state in self._states.values()
                    if state.last_updated >= point_in_time]
Example #10
0
    def __init__(self, entity_id, state, attributes=None, last_changed=None,
                 last_updated=None):
        if not ENTITY_ID_PATTERN.match(entity_id):
            raise InvalidEntityFormatError((
                "Invalid entity id encountered: {}. "
                "Format should be <domain>.<object_id>").format(entity_id))

        self.entity_id = entity_id.lower()
        self.state = state
        self.attributes = attributes or {}
        self.last_updated = dt_util.strip_microseconds(
            last_updated or dt_util.utcnow())

        # Strip microsecond from last_changed else we cannot guarantee
        # state == State.from_dict(state.as_dict())
        # This behavior occurs because to_dict uses datetime_to_str
        # which does not preserve microseconds
        self.last_changed = dt_util.strip_microseconds(
            last_changed or self.last_updated)
Example #11
0
    def __init__(self, entity_id, state, attributes=None, last_changed=None,
                 last_updated=None):
        """Initialize a new state."""
        if not valid_entity_id(entity_id):
            raise InvalidEntityFormatError((
                "Invalid entity id encountered: {}. "
                "Format should be <domain>.<object_id>").format(entity_id))

        self.entity_id = entity_id.lower()
        self.state = str(state)
        self.attributes = MappingProxyType(attributes or {})
        self.last_updated = dt_util.strip_microseconds(
            last_updated or dt_util.utcnow())

        # Strip microsecond from last_changed else we cannot guarantee
        # state == State.from_dict(state.as_dict())
        # This behavior occurs because to_dict uses datetime_to_str
        # which does not preserve microseconds
        self.last_changed = dt_util.strip_microseconds(
            last_changed or self.last_updated)
Example #12
0
    def send_message(self, message="", **kwargs):
        """Send a message to a file."""
        with open(self.filepath, 'a') as file:
            if os.stat(self.filepath).st_size == 0:
                title = '{} notifications (Log started: {})\n{}\n'.format(
                    kwargs.get(ATTR_TITLE),
                    dt_util.strip_microseconds(dt_util.utcnow()), '-' * 80)
                file.write(title)

            if self.add_timestamp == 1:
                text = '{} {}\n'.format(dt_util.utcnow(), message)
                file.write(text)
            else:
                text = '{}\n'.format(message)
                file.write(text)
Example #13
0
    def send_message(self, message="", **kwargs):
        """Send a message to a file."""
        with open(self.filepath, 'a') as file:
            if os.stat(self.filepath).st_size == 0:
                title = '{} notifications (Log started: {})\n{}\n'.format(
                    kwargs.get(ATTR_TITLE),
                    dt_util.strip_microseconds(dt_util.utcnow()),
                    '-'*80)
                file.write(title)

            if self.add_timestamp == 1:
                text = '{} {}\n'.format(dt_util.utcnow(), message)
                file.write(text)
            else:
                text = '{}\n'.format(message)
                file.write(text)
Example #14
0
    def test_humanify_filter_sensor(self):
        """ Test humanify filter too frequent sensor values. """
        entity_id = "sensor.bla"

        pointA = dt_util.strip_microseconds(dt_util.utcnow().replace(minute=2))
        pointB = pointA.replace(minute=5)
        pointC = pointA + timedelta(minutes=logbook.GROUP_BY_MINUTES)

        eventA = self.create_state_changed_event(pointA, entity_id, 10)
        eventB = self.create_state_changed_event(pointB, entity_id, 20)
        eventC = self.create_state_changed_event(pointC, entity_id, 30)

        entries = list(logbook.humanify((eventA, eventB, eventC)))

        self.assertEqual(2, len(entries))
        self.assert_entry(entries[0], pointB, "bla", domain="sensor", entity_id=entity_id)

        self.assert_entry(entries[1], pointC, "bla", domain="sensor", entity_id=entity_id)
Example #15
0
    def test_strip_microseconds(self):
        """Test the now method."""
        test_time = datetime(2015, 1, 1, microsecond=5000)

        self.assertNotEqual(0, test_time.microsecond)
        self.assertEqual(0, dt_util.strip_microseconds(test_time).microsecond)