Esempio n. 1
0
    def test_if_action_after(self):
        """Test for if action after."""
        assert _setup_component(
            self.hass, automation.DOMAIN, {
                automation.DOMAIN: {
                    'trigger': {
                        'platform': 'event',
                        'event_type': 'test_event'
                    },
                    'condition': {
                        'platform': 'time',
                        'after': '10:00',
                    },
                    'action': {
                        'service': 'test.automation'
                    }
                }
            })

        before_10 = dt_util.now().replace(hour=8)
        after_10 = dt_util.now().replace(hour=14)

        with patch('blumate.helpers.condition.dt_util.now',
                   return_value=before_10):
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()

        self.assertEqual(0, len(self.calls))

        with patch('blumate.helpers.condition.dt_util.now',
                   return_value=after_10):
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()

        self.assertEqual(1, len(self.calls))
Esempio n. 2
0
    def test_if_action_after(self):
        """Test for if action after."""
        assert _setup_component(self.hass, automation.DOMAIN, {
            automation.DOMAIN: {
                'trigger': {
                    'platform': 'event',
                    'event_type': 'test_event'
                },
                'condition': {
                    'platform': 'time',
                    'after': '10:00',
                },
                'action': {
                    'service': 'test.automation'
                }
            }
        })

        before_10 = dt_util.now().replace(hour=8)
        after_10 = dt_util.now().replace(hour=14)

        with patch('blumate.helpers.condition.dt_util.now',
                   return_value=before_10):
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()

        self.assertEqual(0, len(self.calls))

        with patch('blumate.helpers.condition.dt_util.now',
                   return_value=after_10):
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()

        self.assertEqual(1, len(self.calls))
Esempio n. 3
0
    def test_if_action_one_weekday(self):
        """Test for if action with one weekday."""
        assert _setup_component(self.hass, automation.DOMAIN, {
            automation.DOMAIN: {
                'trigger': {
                    'platform': 'event',
                    'event_type': 'test_event'
                },
                'condition': {
                    'platform': 'time',
                    'weekday': 'mon',
                },
                'action': {
                    'service': 'test.automation'
                }
            }
        })

        days_past_monday = dt_util.now().weekday()
        monday = dt_util.now() - timedelta(days=days_past_monday)
        tuesday = monday + timedelta(days=1)

        with patch('blumate.helpers.condition.dt_util.now',
                   return_value=monday):
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()

        self.assertEqual(1, len(self.calls))

        with patch('blumate.helpers.condition.dt_util.now',
                   return_value=tuesday):
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()

        self.assertEqual(1, len(self.calls))
Esempio n. 4
0
    def test_get_age(self):
        """Test get_age."""
        diff = dt_util.now() - timedelta(seconds=0)
        self.assertEqual(dt_util.get_age(diff), "0 second")

        diff = dt_util.now() - timedelta(seconds=30)
        self.assertEqual(dt_util.get_age(diff), "30 seconds")

        diff = dt_util.now() - timedelta(minutes=5)
        self.assertEqual(dt_util.get_age(diff), "5 minutes")

        diff = dt_util.now() - timedelta(minutes=1)
        self.assertEqual(dt_util.get_age(diff), "1 minute")

        diff = dt_util.now() - timedelta(minutes=300)
        self.assertEqual(dt_util.get_age(diff), "5 hours")

        diff = dt_util.now() - timedelta(minutes=320)
        self.assertEqual(dt_util.get_age(diff), "5 hours")

        diff = dt_util.now() - timedelta(minutes=2*60*24)
        self.assertEqual(dt_util.get_age(diff), "2 days")

        diff = dt_util.now() - timedelta(minutes=32*60*24)
        self.assertEqual(dt_util.get_age(diff), "1 month")

        diff = dt_util.now() - timedelta(minutes=365*60*24)
        self.assertEqual(dt_util.get_age(diff), "1 year")
Esempio n. 5
0
def time(before=None, after=None, weekday=None):
    """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 after is None:
        after = dt_util.dt.time(0)
    if before is None:
        before = dt_util.dt.time(23, 59, 59, 999999)

    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()]

        if isinstance(weekday, str) and weekday != now_weekday or \
           now_weekday not in weekday:
            return False

    return True
Esempio n. 6
0
    def test_notify_file(self, mock_utcnow):
        """Test the notify file output."""
        mock_utcnow.return_value = dt_util.as_utc(dt_util.now())

        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.utcnow().isoformat(), '-' * 80)

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

            result = open(filename).read()
            self.assertEqual(result, "{}{}\n".format(title, message))
Esempio n. 7
0
    def test_notify_file(self, mock_utcnow):
        """Test the notify file output."""
        mock_utcnow.return_value = dt_util.as_utc(dt_util.now())

        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.utcnow().isoformat(),
                '-' * 80)

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

            result = open(filename).read()
            self.assertEqual(result, "{}{}\n".format(title, message))
    def check_light_on_dev_state_change(hass, entity, old_state, new_state):
        """Handle tracked device state changes."""
        # pylint: disable=unused-variable
        lights_are_on = group.is_on(hass, light_group)

        light_needed = not (lights_are_on or sun.is_on(hass))

        # These variables are needed for the elif check
        now = dt_util.now()
        start_point = calc_time_for_light_when_sunset()

        # Do we need lights?
        if light_needed:
            logger.info("Home coming event for %s. Turning lights on", entity)
            light.turn_on(hass, light_ids, profile=light_profile)

        # Are we in the time span were we would turn on the lights
        # if someone would be home?
        # Check this by seeing if current time is later then the point
        # in time when we would start putting the lights on.
        elif (start_point and
              start_point < now < sun.next_setting(hass)):

            # Check for every light if it would be on if someone was home
            # when the fading in started and turn it on if so
            for index, light_id in enumerate(light_ids):
                if now > start_point + index * LIGHT_TRANSITION_TIME:
                    light.turn_on(hass, light_id)

                else:
                    # If this light didn't happen to be turned on yet so
                    # will all the following then, break.
                    break
Esempio n. 9
0
def time(before=None, after=None, weekday=None):
    """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 after is None:
        after = dt_util.dt.time(0)
    if before is None:
        before = dt_util.dt.time(23, 59, 59, 999999)

    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()]

        if isinstance(weekday, str) and weekday != now_weekday or \
           now_weekday not in weekday:
            return False

    return True
Esempio n. 10
0
    def check_light_on_dev_state_change(hass, entity, old_state, new_state):
        """Handle tracked device state changes."""
        # pylint: disable=unused-variable
        lights_are_on = group.is_on(hass, light_group)

        light_needed = not (lights_are_on or sun.is_on(hass))

        # These variables are needed for the elif check
        now = dt_util.now()
        start_point = calc_time_for_light_when_sunset()

        # Do we need lights?
        if light_needed:
            logger.info("Home coming event for %s. Turning lights on", entity)
            light.turn_on(hass, light_ids, profile=light_profile)

        # Are we in the time span were we would turn on the lights
        # if someone would be home?
        # Check this by seeing if current time is later then the point
        # in time when we would start putting the lights on.
        elif (start_point and start_point < now < sun.next_setting(hass)):

            # Check for every light if it would be on if someone was home
            # when the fading in started and turn it on if so
            for index, light_id in enumerate(light_ids):
                if now > start_point + index * LIGHT_TRANSITION_TIME:
                    light.turn_on(hass, light_id)

                else:
                    # If this light didn't happen to be turned on yet so
                    # will all the following then, break.
                    break
Esempio n. 11
0
    def test_set_default_time_zone(self):
        """Test setting default time zone."""
        time_zone = dt_util.get_time_zone(TEST_TIME_ZONE)

        dt_util.set_default_time_zone(time_zone)

        # We cannot compare the timezones directly because of DST
        self.assertEqual(time_zone.zone, dt_util.now().tzinfo.zone)
Esempio n. 12
0
    def _update_info(self):
        """Scan the network for devices.

        Returns boolean if scanning successful.
        """
        _LOGGER.info("Scanning")

        from nmap import PortScanner, PortScannerError
        scanner = PortScanner()

        options = "-F --host-timeout 5s"

        if self.home_interval:
            boundary = dt_util.now() - self.home_interval
            last_results = [
                device for device in self.last_results
                if device.last_update > boundary
            ]
            if last_results:
                # Pylint is confused here.
                # pylint: disable=no-member
                options += " --exclude {}".format(",".join(
                    device.ip for device in last_results))
        else:
            last_results = []

        try:
            result = scanner.scan(hosts=self.hosts, arguments=options)
        except PortScannerError:
            return False

        now = dt_util.now()
        for ipv4, info in result['scan'].items():
            if info['status']['state'] != 'up':
                continue
            name = info['hostnames'][0]['name'] if info['hostnames'] else ipv4
            # Mac address only returned if nmap ran as root
            mac = info['addresses'].get('mac') or _arp(ipv4)
            if mac is None:
                continue
            last_results.append(Device(mac.upper(), name, ipv4, now))

        self.last_results = last_results

        _LOGGER.info("nmap scan successful")
        return True
Esempio n. 13
0
    def test_as_utc_with_local_object(self):
        """Test the UTC time with local object."""
        dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE))
        localnow = dt_util.now()
        utcnow = dt_util.as_utc(localnow)

        self.assertEqual(localnow, utcnow)
        self.assertNotEqual(localnow.tzinfo, utcnow.tzinfo)
Esempio n. 14
0
    def test_now(self):
        """Test the now method."""
        dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE))

        self.assertAlmostEqual(
            dt_util.as_utc(dt_util.now()).replace(tzinfo=None),
            datetime.utcnow(),
            delta=timedelta(seconds=1))
Esempio n. 15
0
    def test_if_action_list_weekday(self):
        """Test for action with a list of weekdays."""
        assert _setup_component(
            self.hass, automation.DOMAIN, {
                automation.DOMAIN: {
                    'trigger': {
                        'platform': 'event',
                        'event_type': 'test_event'
                    },
                    'condition': {
                        'platform': 'time',
                        'weekday': ['mon', 'tue'],
                    },
                    'action': {
                        'service': 'test.automation'
                    }
                }
            })

        days_past_monday = dt_util.now().weekday()
        monday = dt_util.now() - timedelta(days=days_past_monday)
        tuesday = monday + timedelta(days=1)
        wednesday = tuesday + timedelta(days=1)

        with patch('blumate.helpers.condition.dt_util.now',
                   return_value=monday):
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()

        self.assertEqual(1, len(self.calls))

        with patch('blumate.helpers.condition.dt_util.now',
                   return_value=tuesday):
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()

        self.assertEqual(2, len(self.calls))

        with patch('blumate.helpers.condition.dt_util.now',
                   return_value=wednesday):
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()

        self.assertEqual(2, len(self.calls))
Esempio n. 16
0
    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('blumate.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('blumate.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('blumate.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('blumate.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)
Esempio n. 17
0
    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('blumate.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('blumate.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('blumate.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('blumate.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)
Esempio n. 18
0
    def test_flux_with_custom_colortemps(self):
        """Test the flux with custom start and stop colortemps."""
        platform = loader.get_component('light.test')
        platform.init()
        self.assertTrue(
            light.setup(self.hass, {light.DOMAIN: {CONF_PLATFORM: 'test'}}))

        dev1 = platform.DEVICES[0]

        # Verify initial state of light
        state = self.hass.states.get(dev1.entity_id)
        self.assertEqual(STATE_ON, state.state)
        self.assertIsNone(state.attributes.get('xy_color'))
        self.assertIsNone(state.attributes.get('brightness'))

        test_time = dt_util.now().replace(hour=17, minute=30, second=0)
        sunset_time = test_time.replace(hour=17, minute=0, second=0)
        sunrise_time = test_time.replace(hour=5,
                                         minute=0,
                                         second=0) + timedelta(days=1)

        with patch('blumate.util.dt.now', return_value=test_time):
            with patch('blumate.components.sun.next_rising',
                       return_value=sunrise_time):
                with patch('blumate.components.sun.next_setting',
                           return_value=sunset_time):
                    assert setup_component(self.hass, switch.DOMAIN, {
                        switch.DOMAIN: {
                            'platform': 'flux',
                            'name': 'flux',
                            'lights': [dev1.entity_id],
                            'start_colortemp': '1000',
                            'stop_colortemp': '6000'
                        }
                    })
                    turn_on_calls = mock_service(
                        self.hass, light.DOMAIN, SERVICE_TURN_ON)
                    switch.turn_on(self.hass, 'switch.flux')
                    self.hass.pool.block_till_done()
                    fire_time_changed(self.hass, test_time)
                    self.hass.pool.block_till_done()
        call = turn_on_calls[-1]
        self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 167)
        self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.461, 0.389])
Esempio n. 19
0
    def _update_info(self):
        """Ensure the information from the router is up to date.

        Return boolean if scanning successful.
        """
        _LOGGER.info("Scanning")
        if not self.success_init:
            return False

        with self.lock:
            now = dt_util.now()
            actiontec_data = self.get_actiontec_data()
            if not actiontec_data:
                return False
            self.last_results = [Device(data['mac'], name, now)
                                 for name, data in actiontec_data.items()
                                 if data['timevalid'] > -60]
            _LOGGER.info("actiontec scan successful")
            return True
Esempio n. 20
0
    def __init__(self, hass, purge_days):
        """Initialize the recorder."""
        threading.Thread.__init__(self)

        self.hass = hass
        self.purge_days = purge_days
        self.conn = None
        self.queue = queue.Queue()
        self.quit_object = object()
        self.lock = threading.Lock()
        self.recording_start = dt_util.utcnow()
        self.utc_offset = dt_util.now().utcoffset().total_seconds()
        self.db_path = self.hass.config.path(DB_FILE)

        def start_recording(event):
            """Start recording."""
            self.start()

        hass.bus.listen_once(EVENT_BLUMATE_START, start_recording)
        hass.bus.listen_once(EVENT_BLUMATE_STOP, self.shutdown)
        hass.bus.listen(MATCH_ALL, self.event_listener)
Esempio n. 21
0
    def __init__(self, hass, purge_days):
        """Initialize the recorder."""
        threading.Thread.__init__(self)

        self.hass = hass
        self.purge_days = purge_days
        self.conn = None
        self.queue = queue.Queue()
        self.quit_object = object()
        self.lock = threading.Lock()
        self.recording_start = dt_util.utcnow()
        self.utc_offset = dt_util.now().utcoffset().total_seconds()
        self.db_path = self.hass.config.path(DB_FILE)

        def start_recording(event):
            """Start recording."""
            self.start()

        hass.bus.listen_once(EVENT_BLUMATE_START, start_recording)
        hass.bus.listen_once(EVENT_BLUMATE_STOP, self.shutdown)
        hass.bus.listen(MATCH_ALL, self.event_listener)
Esempio n. 22
0
    def test_state_changed_event_sends_message(self, mock_utcnow, mock_pub):
        """"Test the sending of a new message if event changed."""
        now = dt_util.as_utc(dt_util.now())
        e_id = 'fake.entity'
        pub_topic = 'bar'
        mock_utcnow.return_value = now

        # Add the eventstream component for publishing events
        self.assertTrue(self.add_eventstream(pub_topic=pub_topic))
        self.hass.pool.block_till_done()

        # Reset the mock because it will have already gotten calls for the
        # mqtt_eventstream state change on initialization, etc.
        mock_pub.reset_mock()

        # Set a state of an entity
        mock_state_change_event(self.hass, State(e_id, 'on'))
        self.hass.pool.block_till_done()

        # The order of the JSON is indeterminate,
        # so first just check that publish was called
        mock_pub.assert_called_with(self.hass, pub_topic, ANY)
        self.assertTrue(mock_pub.called)

        # Get the actual call to publish and make sure it was the one
        # we were looking for
        msg = mock_pub.call_args[0][2]
        event = {}
        event['event_type'] = EVENT_STATE_CHANGED
        new_state = {
            "last_updated": now.isoformat(),
            "state": "on",
            "entity_id": e_id,
            "attributes": {},
            "last_changed": now.isoformat()
        }
        event['event_data'] = {"new_state": new_state, "entity_id": e_id}

        # Verify that the message received was that expected
        self.assertEqual(json.loads(msg), event)
Esempio n. 23
0
    def test_state_changed_event_sends_message(self, mock_utcnow, mock_pub):
        """"Test the sending of a new message if event changed."""
        now = dt_util.as_utc(dt_util.now())
        e_id = 'fake.entity'
        pub_topic = 'bar'
        mock_utcnow.return_value = now

        # Add the eventstream component for publishing events
        self.assertTrue(self.add_eventstream(pub_topic=pub_topic))
        self.hass.pool.block_till_done()

        # Reset the mock because it will have already gotten calls for the
        # mqtt_eventstream state change on initialization, etc.
        mock_pub.reset_mock()

        # Set a state of an entity
        mock_state_change_event(self.hass, State(e_id, 'on'))
        self.hass.pool.block_till_done()

        # The order of the JSON is indeterminate,
        # so first just check that publish was called
        mock_pub.assert_called_with(self.hass, pub_topic, ANY)
        self.assertTrue(mock_pub.called)

        # Get the actual call to publish and make sure it was the one
        # we were looking for
        msg = mock_pub.call_args[0][2]
        event = {}
        event['event_type'] = EVENT_STATE_CHANGED
        new_state = {
            "last_updated": now.isoformat(),
            "state": "on",
            "entity_id": e_id,
            "attributes": {},
            "last_changed": now.isoformat()
        }
        event['event_data'] = {"new_state": new_state, "entity_id": e_id}

        # Verify that the message received was that expected
        self.assertEqual(json.loads(msg), event)
Esempio n. 24
0
    def test_flux_when_switch_is_off(self):
        """Test the flux switch when it is off."""
        platform = loader.get_component('light.test')
        platform.init()
        self.assertTrue(
            light.setup(self.hass, {light.DOMAIN: {CONF_PLATFORM: 'test'}}))

        dev1 = platform.DEVICES[0]

        # Verify initial state of light
        state = self.hass.states.get(dev1.entity_id)
        self.assertEqual(STATE_ON, state.state)
        self.assertIsNone(state.attributes.get('xy_color'))
        self.assertIsNone(state.attributes.get('brightness'))

        test_time = dt_util.now().replace(hour=10, minute=30,
                                          second=0)
        sunset_time = test_time.replace(hour=17, minute=0,
                                        second=0)
        sunrise_time = test_time.replace(hour=5, minute=0,
                                         second=0) + timedelta(days=1)
        with patch('blumate.util.dt.now', return_value=test_time):
            with patch('blumate.components.sun.next_rising',
                       return_value=sunrise_time):
                with patch('blumate.components.sun.next_setting',
                           return_value=sunset_time):
                    assert setup_component(self.hass, switch.DOMAIN, {
                        switch.DOMAIN: {
                            'platform': 'flux',
                            'name': 'flux',
                            'lights': [dev1.entity_id]
                        }
                    })
                    turn_on_calls = mock_service(
                        self.hass, light.DOMAIN, SERVICE_TURN_ON)
                    fire_time_changed(self.hass, test_time)
                    self.hass.pool.block_till_done()
        self.assertEqual(0, len(turn_on_calls))
Esempio n. 25
0
def sun(hass, before=None, after=None, before_offset=None, after_offset=None):
    """Test if current time matches sun requirements."""
    now = dt_util.now().time()
    before_offset = before_offset or timedelta(0)
    after_offset = after_offset or timedelta(0)

    if before == SUN_EVENT_SUNRISE and now > (sun_cmp.next_rising(hass) +
                                              before_offset).time():
        return False

    elif before == SUN_EVENT_SUNSET and now > (sun_cmp.next_setting(hass) +
                                               before_offset).time():
        return False

    if after == SUN_EVENT_SUNRISE and now < (sun_cmp.next_rising(hass) +
                                             after_offset).time():
        return False

    elif after == SUN_EVENT_SUNSET and now < (sun_cmp.next_setting(hass) +
                                              after_offset).time():
        return False

    return True
Esempio n. 26
0
def sun(hass, before=None, after=None, before_offset=None, after_offset=None):
    """Test if current time matches sun requirements."""
    now = dt_util.now().time()
    before_offset = before_offset or timedelta(0)
    after_offset = after_offset or timedelta(0)

    if before == SUN_EVENT_SUNRISE and now > (sun_cmp.next_rising(hass) +
                                              before_offset).time():
        return False

    elif before == SUN_EVENT_SUNSET and now > (sun_cmp.next_setting(hass) +
                                               before_offset).time():
        return False

    if after == SUN_EVENT_SUNRISE and now < (sun_cmp.next_rising(hass) +
                                             after_offset).time():
        return False

    elif after == SUN_EVENT_SUNSET and now < (sun_cmp.next_setting(hass) +
                                              after_offset).time():
        return False

    return True
Esempio n. 27
0
    def test_flux_with_multiple_lights(self):
        """Test the flux switch with multiple light entities."""
        platform = loader.get_component('light.test')
        platform.init()
        self.assertTrue(
            light.setup(self.hass, {light.DOMAIN: {CONF_PLATFORM: 'test'}}))

        dev1, dev2, dev3 = platform.DEVICES
        light.turn_on(self.hass, entity_id=dev2.entity_id)
        self.hass.pool.block_till_done()
        light.turn_on(self.hass, entity_id=dev3.entity_id)
        self.hass.pool.block_till_done()

        state = self.hass.states.get(dev1.entity_id)
        self.assertEqual(STATE_ON, state.state)
        self.assertIsNone(state.attributes.get('xy_color'))
        self.assertIsNone(state.attributes.get('brightness'))

        state = self.hass.states.get(dev2.entity_id)
        self.assertEqual(STATE_ON, state.state)
        self.assertIsNone(state.attributes.get('xy_color'))
        self.assertIsNone(state.attributes.get('brightness'))

        state = self.hass.states.get(dev3.entity_id)
        self.assertEqual(STATE_ON, state.state)
        self.assertIsNone(state.attributes.get('xy_color'))
        self.assertIsNone(state.attributes.get('brightness'))

        test_time = dt_util.now().replace(hour=12, minute=0, second=0)
        sunset_time = test_time.replace(hour=17, minute=0, second=0)
        sunrise_time = test_time.replace(hour=5,
                                         minute=0,
                                         second=0) + timedelta(days=1)

        with patch('blumate.util.dt.now', return_value=test_time):
            with patch('blumate.components.sun.next_rising',
                       return_value=sunrise_time):
                with patch('blumate.components.sun.next_setting',
                           return_value=sunset_time):
                    assert setup_component(self.hass, switch.DOMAIN, {
                        switch.DOMAIN: {
                            'platform': 'flux',
                            'name': 'flux',
                            'lights': [dev1.entity_id,
                                       dev2.entity_id,
                                       dev3.entity_id]
                        }
                    })
                    turn_on_calls = mock_service(
                        self.hass, light.DOMAIN, SERVICE_TURN_ON)
                    switch.turn_on(self.hass, 'switch.flux')
                    self.hass.pool.block_till_done()
                    fire_time_changed(self.hass, test_time)
                    self.hass.pool.block_till_done()
        call = turn_on_calls[-1]
        self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 171)
        self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.452, 0.386])
        call = turn_on_calls[-2]
        self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 171)
        self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.452, 0.386])
        call = turn_on_calls[-3]
        self.assertEqual(call.data[light.ATTR_BRIGHTNESS], 171)
        self.assertEqual(call.data[light.ATTR_XY_COLOR], [0.452, 0.386])
Esempio n. 28
0
 def update(self):
     """Get the time and updates the states."""
     self._state = dt_util.now(time_zone=self._time_zone).strftime(
         TIME_STR_FORMAT)
Esempio n. 29
0
 def update(call=None):
     """Update service for manual updates."""
     data.update(dt_util.now())
     for sensor in dev:
         sensor.update()
Esempio n. 30
0
 def update(self):
     """Get the time and updates the states."""
     self._state = dt_util.now(
         time_zone=self._time_zone).strftime(TIME_STR_FORMAT)
Esempio n. 31
0
 def test_as_local_with_local_object(self):
     """Test local with local object."""
     now = dt_util.now()
     self.assertEqual(now, now)
Esempio n. 32
0
 def test_as_local_with_naive_object(self):
     """Test local time with native object."""
     now = dt_util.now()
     self.assertAlmostEqual(
         now, dt_util.as_local(datetime.utcnow()),
         delta=timedelta(seconds=1))