def setUp(self):
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()

        # Set our timezone to CST/Regina so we can check calculations
        # This keeps UTC-6 all year round
        dt_util.set_default_time_zone(dt_util.get_time_zone('America/Regina'))
Example #2
0
    def test_periodic_task_leaving_dst(self):
        """Test periodic task behavior when leaving dst."""
        tz = dt_util.get_time_zone('Europe/Vienna')
        dt_util.set_default_time_zone(tz)
        specific_runs = []

        unsub = track_time_change(
            self.hass, lambda x: specific_runs.append(1), hour=2, minute=30,
            second=0)

        self._send_time_changed(
            tz.localize(datetime(2018, 10, 28, 2, 5, 0), is_dst=False))
        self.hass.block_till_done()
        assert 0 == len(specific_runs)

        self._send_time_changed(
            tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=False))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(
            tz.localize(datetime(2018, 10, 28, 2, 5, 0), is_dst=True))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(
            tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=True))
        self.hass.block_till_done()
        assert 2 == len(specific_runs)

        unsub()
Example #3
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
        assert time_zone.zone == dt_util.now().tzinfo.zone
Example #4
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)

        assert localnow == utcnow
        assert localnow.tzinfo != utcnow.tzinfo
Example #5
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))
Example #6
0
    def test_as_local_with_utc_object(self):
        dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE))

        utcnow = dt_util.utcnow()
        localnow = dt_util.as_local(utcnow)

        self.assertEqual(localnow, utcnow)
        self.assertNotEqual(localnow.tzinfo, utcnow.tzinfo)
 def test_timezone_intervals_empty_parameter(self, _):
     """Test get_interval() without parameters."""
     new_tz = dt_util.get_time_zone('America/Edmonton')
     assert new_tz is not None
     dt_util.set_default_time_zone(new_tz)
     device = time_date.TimeDateSensor(self.hass, 'date')
     next_time = device.get_next_interval()
     assert (next_time.timestamp() ==
             dt_util.as_timestamp('2017-11-14 00:00:00-07:00'))
Example #8
0
    def test_now(self):
        """Test the now method."""
        dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE))

        assert abs(
            dt_util.as_utc(dt_util.now()).replace(
                tzinfo=None
            ) - datetime.utcnow()
        ) < timedelta(seconds=1)
Example #9
0
    def test_as_local_with_utc_object(self):
        """Test local time with UTC object."""
        dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE))

        utcnow = dt_util.utcnow()
        localnow = dt_util.as_local(utcnow)

        assert localnow == utcnow
        assert localnow.tzinfo != utcnow.tzinfo
Example #10
0
    def set_time_zone(time_zone_str: Optional[str]) -> None:
        """Help to set the time zone."""
        if time_zone_str is None:
            return

        time_zone = date_util.get_time_zone(time_zone_str)

        if time_zone:
            hac.time_zone = time_zone
            date_util.set_default_time_zone(time_zone)
        else:
            _LOGGER.error("Received invalid time zone %s", time_zone_str)
Example #11
0
    def test_timezone_intervals(self):
        """Test date sensor behavior in a timezone besides UTC."""
        new_tz = dt_util.get_time_zone('America/New_York')
        assert new_tz is not None
        dt_util.set_default_time_zone(new_tz)

        device = time_date.TimeDateSensor(self.hass, 'date')
        now = dt_util.utc_from_timestamp(50000)
        next_time = device.get_next_interval(now)
        # start of local day in EST was 18000.0
        # so the second day was 18000 + 86400
        assert next_time.timestamp() == 104400
Example #12
0
    def set_time_zone(time_zone_str):
        """ Helper method to set time zone in HA. """
        if time_zone_str is None:
            return

        time_zone = date_util.get_time_zone(time_zone_str)

        if time_zone:
            hac.time_zone = time_zone
            date_util.set_default_time_zone(time_zone)
        else:
            _LOGGER.error("Received invalid time zone %s", time_zone_str)
 def test_jewish_calendar_sensor(self, time, tzname, latitude, longitude,
                                 language, sensor, diaspora, result):
     """Test Jewish calendar sensor output."""
     tz = get_time_zone(tzname)
     set_default_time_zone(tz)
     test_time = tz.localize(time)
     self.hass.config.latitude = latitude
     self.hass.config.longitude = longitude
     sensor = JewishCalSensor(
         name='test', language=language, sensor_type=sensor,
         latitude=latitude, longitude=longitude,
         timezone=tz, diaspora=diaspora)
     sensor.hass = self.hass
     with patch('homeassistant.util.dt.now', return_value=test_time):
         run_coroutine_threadsafe(
             sensor.async_update(),
             self.hass.loop).result()
         assert sensor.state == result
Example #14
0
    def test_find_next_time_expression_time_dst(self):
        """Test daylight saving time for find_next_time_expression_time."""
        tz = dt_util.get_time_zone('Europe/Vienna')
        dt_util.set_default_time_zone(tz)

        def find(dt, hour, minute, second):
            """Call test_find_next_time_expression_time."""
            seconds = dt_util.parse_time_expression(second, 0, 59)
            minutes = dt_util.parse_time_expression(minute, 0, 59)
            hours = dt_util.parse_time_expression(hour, 0, 23)

            return dt_util.find_next_time_expression_time(
                dt, seconds, minutes, hours)

        # Entering DST, clocks are rolled forward
        assert tz.localize(datetime(2018, 3, 26, 2, 30, 0)) == \
            find(tz.localize(datetime(2018, 3, 25, 1, 50, 0)), 2, 30, 0)

        assert tz.localize(datetime(2018, 3, 26, 2, 30, 0)) == \
            find(tz.localize(datetime(2018, 3, 25, 3, 50, 0)), 2, 30, 0)

        assert tz.localize(datetime(2018, 3, 26, 2, 30, 0)) == \
            find(tz.localize(datetime(2018, 3, 26, 1, 50, 0)), 2, 30, 0)

        # Leaving DST, clocks are rolled back
        assert tz.localize(datetime(2018, 10, 28, 2, 30, 0), is_dst=False) == \
            find(tz.localize(datetime(2018, 10, 28, 2, 5, 0), is_dst=False),
                 2, 30, 0)

        assert tz.localize(datetime(2018, 10, 28, 2, 30, 0), is_dst=False) == \
            find(tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=True),
                 2, 30, 0)

        assert tz.localize(datetime(2018, 10, 28, 4, 30, 0), is_dst=False) == \
            find(tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=True),
                 4, 30, 0)

        assert tz.localize(datetime(2018, 10, 28, 2, 30, 0), is_dst=True) == \
            find(tz.localize(datetime(2018, 10, 28, 2, 5, 0), is_dst=True),
                 2, 30, 0)

        assert tz.localize(datetime(2018, 10, 29, 2, 30, 0)) == \
            find(tz.localize(datetime(2018, 10, 28, 2, 55, 0), is_dst=False),
                 2, 30, 0)
Example #15
0
 def test_issur_melacha_sensor(self, now, candle_lighting, havdalah,
                               diaspora, tzname, latitude, longitude,
                               result):
     """Test Issur Melacha sensor output."""
     time_zone = get_time_zone(tzname)
     set_default_time_zone(time_zone)
     test_time = time_zone.localize(now)
     self.hass.config.latitude = latitude
     self.hass.config.longitude = longitude
     sensor = JewishCalSensor(
         name='test', language='english',
         sensor_type='issur_melacha_in_effect',
         latitude=latitude, longitude=longitude,
         timezone=time_zone, diaspora=diaspora, havdalah_offset=havdalah,
         candle_lighting_offset=candle_lighting)
     sensor.hass = self.hass
     with patch('homeassistant.util.dt.now', return_value=test_time):
         run_coroutine_threadsafe(
             sensor.async_update(),
             self.hass.loop).result()
         assert sensor.state == result
Example #16
0
    def test_shabbat_times_sensor(self, now, candle_lighting, havdalah,
                                  diaspora, tzname, latitude, longitude,
                                  result):
        """Test sensor output for upcoming shabbat/yomtov times."""
        time_zone = get_time_zone(tzname)
        set_default_time_zone(time_zone)
        test_time = time_zone.localize(now)
        for sensor_type, value in result.items():
            if isinstance(value, dt):
                result[sensor_type] = time_zone.localize(value)
        self.hass.config.latitude = latitude
        self.hass.config.longitude = longitude

        if ('upcoming_shabbat_candle_lighting' in result
                and 'upcoming_candle_lighting' not in result):
            result['upcoming_candle_lighting'] = \
                result['upcoming_shabbat_candle_lighting']
        if ('upcoming_shabbat_havdalah' in result
                and 'upcoming_havdalah' not in result):
            result['upcoming_havdalah'] = result['upcoming_shabbat_havdalah']

        for sensor_type, result_value in result.items():
            language = 'english'
            if sensor_type.startswith('hebrew_'):
                language = 'hebrew'
                sensor_type = sensor_type.replace('hebrew_', '')
            sensor = JewishCalSensor(
                name='test', language=language, sensor_type=sensor_type,
                latitude=latitude, longitude=longitude,
                timezone=time_zone, diaspora=diaspora,
                havdalah_offset=havdalah,
                candle_lighting_offset=candle_lighting)
            sensor.hass = self.hass
            with patch('homeassistant.util.dt.now', return_value=test_time):
                run_coroutine_threadsafe(
                    sensor.async_update(),
                    self.hass.loop).result()
                assert sensor.state == result_value, "Value for {}".format(
                    sensor_type)
def test_find_next_time_expression_time_leave_dst_chicago_into_the_fold_same_time():
    """Test leaving daylight saving time for find_next_time_expression_time."""
    tz = dt_util.get_time_zone("America/Chicago")
    dt_util.set_default_time_zone(tz)

    # Leaving DST, clocks are rolled back

    # Find the same time inside the fold
    hour_minute_second = (1, 30, 1)
    test_time = datetime(2021, 11, 7, *hour_minute_second, tzinfo=tz, fold=0)
    matching_hours, matching_minutes, matching_seconds = _get_matches(
        *hour_minute_second
    )

    next_time = dt_util.find_next_time_expression_time(
        test_time, matching_seconds, matching_minutes, matching_hours
    )
    assert next_time == datetime(2021, 11, 7, *hour_minute_second, tzinfo=tz, fold=1)
    assert next_time.fold == 0
    assert dt_util.as_utc(next_time) == datetime(
        2021, 11, 7, 6, 30, 1, tzinfo=dt_util.UTC
    )
Example #18
0
async def test_websocket_core_update(hass, client):
    """Test core config update websocket command."""
    assert hass.config.latitude != 60
    assert hass.config.longitude != 50
    assert hass.config.elevation != 25
    assert hass.config.location_name != "Huis"
    assert hass.config.units.name != CONF_UNIT_SYSTEM_IMPERIAL
    assert hass.config.time_zone.zone != "America/New_York"
    assert hass.config.external_url != "https://www.example.com"
    assert hass.config.internal_url != "http://example.com"

    await client.send_json({
        "id": 5,
        "type": "config/core/update",
        "latitude": 60,
        "longitude": 50,
        "elevation": 25,
        "location_name": "Huis",
        CONF_UNIT_SYSTEM: CONF_UNIT_SYSTEM_IMPERIAL,
        "time_zone": "America/New_York",
        "external_url": "https://www.example.com",
        "internal_url": "http://example.local",
    })

    msg = await client.receive_json()

    assert msg["id"] == 5
    assert msg["type"] == TYPE_RESULT
    assert msg["success"]
    assert hass.config.latitude == 60
    assert hass.config.longitude == 50
    assert hass.config.elevation == 25
    assert hass.config.location_name == "Huis"
    assert hass.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL
    assert hass.config.time_zone.zone == "America/New_York"
    assert hass.config.external_url == "https://www.example.com"
    assert hass.config.internal_url == "http://example.local"

    dt_util.set_default_time_zone(ORIG_TIME_ZONE)
Example #19
0
    def test_timezone_intervals(self):
        """Test date sensor behavior in a timezone besides UTC."""
        new_tz = dt_util.get_time_zone("America/New_York")
        assert new_tz is not None
        dt_util.set_default_time_zone(new_tz)

        device = time_date.TimeDateSensor(self.hass, "date")
        now = dt_util.utc_from_timestamp(50000)
        next_time = device.get_next_interval(now)
        # start of local day in EST was 18000.0
        # so the second day was 18000 + 86400
        assert next_time.timestamp() == 104400

        new_tz = dt_util.get_time_zone("America/Edmonton")
        assert new_tz is not None
        dt_util.set_default_time_zone(new_tz)
        now = dt_util.parse_datetime("2017-11-13 19:47:19-07:00")
        device = time_date.TimeDateSensor(self.hass, "date")
        next_time = device.get_next_interval(now)
        assert next_time.timestamp() == dt_util.as_timestamp(
            "2017-11-14 00:00:00-07:00"
        )
Example #20
0
def test_auto_purge(hass_recorder):
    """Test saving and restoring a state."""
    hass = hass_recorder()

    original_tz = dt_util.DEFAULT_TIME_ZONE

    tz = dt_util.get_time_zone("Europe/Copenhagen")
    dt_util.set_default_time_zone(tz)

    test_time = tz.localize(datetime(2020, 1, 1, 4, 12, 0))

    with patch("homeassistant.components.recorder.purge.purge_old_data"
               ) as purge_old_data:
        for delta in (-1, 0, 1):
            hass.bus.fire(EVENT_TIME_CHANGED,
                          {ATTR_NOW: test_time + timedelta(seconds=delta)})
            hass.block_till_done()
            hass.data[DATA_INSTANCE].block_till_done()

        assert len(purge_old_data.mock_calls) == 1

    dt_util.set_default_time_zone(original_tz)
Example #21
0
 def test_jewish_calendar_sensor(self, cur_time, tzname, latitude,
                                 longitude, language, sensor, diaspora,
                                 result):
     """Test Jewish calendar sensor output."""
     time_zone = get_time_zone(tzname)
     set_default_time_zone(time_zone)
     test_time = time_zone.localize(cur_time)
     self.hass.config.latitude = latitude
     self.hass.config.longitude = longitude
     sensor = JewishCalSensor(
         name="test",
         language=language,
         sensor_type=sensor,
         latitude=latitude,
         longitude=longitude,
         timezone=time_zone,
         diaspora=diaspora,
     )
     sensor.hass = self.hass
     with patch("homeassistant.util.dt.now", return_value=test_time):
         run_coroutine_threadsafe(sensor.async_update(),
                                  self.hass.loop).result()
         assert sensor.state == result
Example #22
0
 def test_issur_melacha_sensor(self, now, candle_lighting, havdalah,
                               diaspora, tzname, latitude, longitude,
                               result):
     """Test Issur Melacha sensor output."""
     time_zone = get_time_zone(tzname)
     set_default_time_zone(time_zone)
     test_time = time_zone.localize(now)
     self.hass.config.latitude = latitude
     self.hass.config.longitude = longitude
     sensor = JewishCalSensor(name='test',
                              language='english',
                              sensor_type='issur_melacha_in_effect',
                              latitude=latitude,
                              longitude=longitude,
                              timezone=time_zone,
                              diaspora=diaspora,
                              havdalah_offset=havdalah,
                              candle_lighting_offset=candle_lighting)
     sensor.hass = self.hass
     with patch('homeassistant.util.dt.now', return_value=test_time):
         run_coroutine_threadsafe(sensor.async_update(),
                                  self.hass.loop).result()
         assert sensor.state == result
Example #23
0
def test_auto_purge(hass_recorder):
    """Test saving and restoring a state."""
    hass = hass_recorder()

    original_tz = dt_util.DEFAULT_TIME_ZONE

    tz = dt_util.get_time_zone("Europe/Copenhagen")
    dt_util.set_default_time_zone(tz)

    now = dt_util.utcnow()
    test_time = tz.localize(datetime(now.year + 1, 1, 1, 4, 12, 0))
    async_fire_time_changed(hass, test_time)

    with patch("homeassistant.components.recorder.purge.purge_old_data",
               return_value=True) as purge_old_data:
        for delta in (-1, 0, 1):
            async_fire_time_changed(hass, test_time + timedelta(seconds=delta))
            hass.block_till_done()
            hass.data[DATA_INSTANCE].block_till_done()

        assert len(purge_old_data.mock_calls) == 1

    dt_util.set_default_time_zone(original_tz)
Example #24
0
async def test_dst(hass, freezer, hass_tz_info):
    """Test sun event with offset."""
    hass.config.time_zone = "CET"
    dt_util.set_default_time_zone(dt_util.get_time_zone("CET"))
    test_time = datetime(2019, 3, 30, 3, 0, 0, tzinfo=hass_tz_info)
    config = {
        "binary_sensor": [
            {"platform": "tod", "name": "Day", "after": "2:30", "before": "2:40"}
        ]
    }
    # Test DST:
    # after 2019-03-30 03:00 CET the next update should ge scheduled
    # at 3:30 not 2:30 local time
    entity_id = "binary_sensor.day"
    freezer.move_to(test_time)
    await async_setup_component(hass, "binary_sensor", config)
    await hass.async_block_till_done()

    await hass.async_block_till_done()
    state = hass.states.get(entity_id)
    assert state.attributes["after"] == "2019-03-31T03:30:00+02:00"
    assert state.attributes["before"] == "2019-03-31T03:40:00+02:00"
    assert state.attributes["next_update"] == "2019-03-31T03:30:00+02:00"
    assert state.state == STATE_OFF
Example #25
0
def test_find_next_time_expression_time_leave_dst_chicago_past_the_fold_ahead_2_hour_10_min():
    """Test leaving daylight saving time for find_next_time_expression_time."""
    tz = dt_util.get_time_zone("America/Chicago")
    dt_util.set_default_time_zone(tz)

    # Leaving DST, clocks are rolled back

    # Find 1h 10m after into the fold
    # Start at 01:30:01 fold=0
    # Reach to 02:20:01 past the fold
    hour_minute_second = (2, 20, 1)
    test_time = datetime(2021, 11, 7, 1, 30, 1, tzinfo=tz, fold=0)
    matching_hours, matching_minutes, matching_seconds = _get_matches(
        *hour_minute_second
    )

    next_time = dt_util.find_next_time_expression_time(
        test_time, matching_seconds, matching_minutes, matching_hours
    )
    assert next_time == datetime(2021, 11, 7, *hour_minute_second, tzinfo=tz, fold=1)
    assert next_time.fold == 0  # Time is no longer ambiguous
    assert dt_util.as_utc(next_time) == datetime(
        2021, 11, 7, 8, 20, 1, tzinfo=dt_util.UTC
    )
Example #26
0
def test_find_next_time_expression_time_leave_dst_chicago_inside_the_fold_ahead_10_min():
    """Test leaving daylight saving time for find_next_time_expression_time."""
    tz = dt_util.get_time_zone("America/Chicago")
    dt_util.set_default_time_zone(tz)

    # Leaving DST, clocks are rolled back

    # Find 10m later while we are in the fold
    # Start at 01:30:01 fold=0
    # Reach to 01:40:01 fold=1
    hour_minute_second = (1, 40, 1)
    test_time = datetime(2021, 11, 7, 1, 30, 1, tzinfo=tz, fold=1)
    matching_hours, matching_minutes, matching_seconds = _get_matches(
        *hour_minute_second
    )

    next_time = dt_util.find_next_time_expression_time(
        test_time, matching_seconds, matching_minutes, matching_hours
    )
    assert next_time == datetime(2021, 11, 7, *hour_minute_second, tzinfo=tz, fold=1)
    assert next_time.fold == 1  # time is ambiguous
    assert dt_util.as_utc(next_time) == datetime(
        2021, 11, 7, 7, 40, 1, tzinfo=dt_util.UTC
    )
Example #27
0
    def forecast(self, src=None):
        """Return the forecast array."""
        src = src or self._forecast
        forecast = []
        now = int(time.time())
        dt_util.set_default_time_zone(self._timezone)
        for i in src:
            fc_time = i.get(ATTR_FORECAST_TIME)
            if fc_time is None:
                continue

            data = {
                ATTR_FORECAST_TIME: dt_util.as_local(
                    datetime.utcfromtimestamp(fc_time)
                ).isoformat(),
                ATTR_FORECAST_CONDITION: self.condition(i),
                ATTR_FORECAST_TEMP: self.temperature(i),
                ATTR_FORECAST_PRESSURE: self.pressure_hpa(i),
                ATTR_FORECAST_HUMIDITY: self.humidity(i),
                ATTR_FORECAST_WIND_SPEED: self.wind_speed_kmh(i),
                ATTR_FORECAST_WIND_BEARING: self.wind_bearing(i),
                ATTR_FORECAST_PRECIPITATION: self.precipitation_amount(i),
            }

            if (
                self._mode == FORECAST_MODE_DAILY
                and i.get(ATTR_FORECAST_TEMP_LOW) is not None
            ):
                data[ATTR_FORECAST_TEMP_LOW] = i.get(ATTR_FORECAST_TEMP_LOW)

            if fc_time < now:
                forecast = [data]
            else:
                forecast.append(data)

        return forecast
async def test_timezone_intervals(hass):
    """Test date sensor behavior in a timezone besides UTC."""
    new_tz = dt_util.get_time_zone("America/New_York")
    assert new_tz is not None
    dt_util.set_default_time_zone(new_tz)

    device = time_date.TimeDateSensor(hass, "date")
    now = dt_util.utc_from_timestamp(50000)
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        next_time = device.get_next_interval()
    # start of local day in EST was 18000.0
    # so the second day was 18000 + 86400
    assert next_time.timestamp() == 104400

    new_tz = dt_util.get_time_zone("America/Edmonton")
    assert new_tz is not None
    dt_util.set_default_time_zone(new_tz)
    now = dt_util.parse_datetime("2017-11-13 19:47:19-07:00")
    device = time_date.TimeDateSensor(hass, "date")
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        next_time = device.get_next_interval()
    assert next_time.timestamp() == dt_util.as_timestamp(
        "2017-11-14 00:00:00-07:00")

    # Entering DST
    new_tz = dt_util.get_time_zone("Europe/Prague")
    assert new_tz is not None
    dt_util.set_default_time_zone(new_tz)

    now = dt_util.parse_datetime("2020-03-29 00:00+01:00")
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        next_time = device.get_next_interval()
    assert next_time.timestamp() == dt_util.as_timestamp(
        "2020-03-30 00:00+02:00")

    now = dt_util.parse_datetime("2020-03-29 03:00+02:00")
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        next_time = device.get_next_interval()
    assert next_time.timestamp() == dt_util.as_timestamp(
        "2020-03-30 00:00+02:00")

    # Leaving DST
    now = dt_util.parse_datetime("2020-10-25 00:00+02:00")
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        next_time = device.get_next_interval()
    assert next_time.timestamp() == dt_util.as_timestamp(
        "2020-10-26 00:00:00+01:00")

    now = dt_util.parse_datetime("2020-10-25 23:59+01:00")
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        next_time = device.get_next_interval()
    assert next_time.timestamp() == dt_util.as_timestamp(
        "2020-10-26 00:00:00+01:00")
def baghdad():
    """Set the default TZ to Asia/Baghdad."""
    dt.set_default_time_zone(dt.get_time_zone("Asia/Baghdad"))
Example #30
0
 def tearDown(self):
     """Stop everything that was started."""
     dt_util.set_default_time_zone(self.orig_default_time_zone)
Example #31
0
def teardown():
    """Restore."""
    yield

    dt_util.set_default_time_zone(ORIG_TIME_ZONE)
Example #32
0
def teardown():
    """Stop everything that was started."""
    dt_util.set_default_time_zone(DEFAULT_TIME_ZONE)
Example #33
0
def restore_timezone(hass):
    """Make sure we change timezone."""
    yield
    dt_util.set_default_time_zone(ORIG_TIMEZONE)
 def teardown_method(self, method):
     """Stop everything that was started."""
     self.hass.stop()
     # Reset the default timezone, so we don't affect other tests
     set_default_time_zone(get_time_zone('UTC'))
Example #35
0
async def test_periodic_task_leaving_dst(hass):
    """Test periodic task behavior when leaving dst."""
    timezone = dt_util.get_time_zone("Europe/Vienna")
    dt_util.set_default_time_zone(timezone)
    specific_runs = []

    now = dt_util.utcnow()

    time_that_will_not_match_right_away = timezone.localize(datetime(
        now.year + 1, 10, 28, 2, 28, 0),
                                                            is_dst=True)

    with patch("homeassistant.util.dt.utcnow",
               return_value=time_that_will_not_match_right_away):
        unsub = async_track_time_change(
            hass,
            callback(lambda x: specific_runs.append(x)),
            hour=2,
            minute=30,
            second=0,
        )

    async_fire_time_changed(
        hass,
        timezone.localize(datetime(now.year + 1, 10, 28, 2, 5, 0, 999999),
                          is_dst=False),
    )
    await hass.async_block_till_done()
    assert len(specific_runs) == 0

    async_fire_time_changed(
        hass,
        timezone.localize(datetime(now.year + 1, 10, 28, 2, 55, 0, 999999),
                          is_dst=False),
    )
    await hass.async_block_till_done()
    assert len(specific_runs) == 1

    async_fire_time_changed(
        hass,
        timezone.localize(datetime(now.year + 2, 10, 28, 2, 45, 0, 999999),
                          is_dst=True),
    )
    await hass.async_block_till_done()
    assert len(specific_runs) == 2

    async_fire_time_changed(
        hass,
        timezone.localize(datetime(now.year + 2, 10, 28, 2, 55, 0, 999999),
                          is_dst=True),
    )
    await hass.async_block_till_done()
    assert len(specific_runs) == 2

    async_fire_time_changed(
        hass,
        timezone.localize(datetime(now.year + 2, 10, 28, 2, 55, 0, 999999),
                          is_dst=True),
    )
    await hass.async_block_till_done()
    assert len(specific_runs) == 2

    unsub()
    def tearDown(self):
        """Stop everything that was started."""
        dt_util.set_default_time_zone(dt_util.get_time_zone('UTC'))

        self.hass.stop()
Example #37
0
async def test_timestamp(hass):
    """Test timestamp."""
    try:
        dt_util.set_default_time_zone(
            dt_util.get_time_zone("America/Los_Angeles"))

        assert await async_setup_component(
            hass,
            DOMAIN,
            {
                DOMAIN: {
                    "test_datetime_initial_with_tz": {
                        "has_time": True,
                        "has_date": True,
                        "initial": "2020-12-13 10:00:00+01:00",
                    },
                    "test_datetime_initial_without_tz": {
                        "has_time": True,
                        "has_date": True,
                        "initial": "2020-12-13 10:00:00",
                    },
                    "test_time_initial": {
                        "has_time": True,
                        "has_date": False,
                        "initial": "10:00:00",
                    },
                }
            },
        )

        # initial has been converted to the set timezone
        state_with_tz = hass.states.get(
            "input_datetime.test_datetime_initial_with_tz")
        assert state_with_tz is not None
        assert state_with_tz.state == "2020-12-13 01:00:00"
        assert (dt_util.as_local(
            dt_util.utc_from_timestamp(
                state_with_tz.attributes[ATTR_TIMESTAMP])).strftime(
                    FMT_DATETIME) == "2020-12-13 01:00:00")

        # initial has been interpreted as being part of set timezone
        state_without_tz = hass.states.get(
            "input_datetime.test_datetime_initial_without_tz")
        assert state_without_tz is not None
        assert state_without_tz.state == "2020-12-13 10:00:00"
        assert (dt_util.as_local(
            dt_util.utc_from_timestamp(
                state_without_tz.attributes[ATTR_TIMESTAMP])).strftime(
                    FMT_DATETIME) == "2020-12-13 10:00:00")
        # Use datetime.datetime.fromtimestamp
        assert (dt_util.as_local(
            datetime.datetime.fromtimestamp(
                state_without_tz.attributes[ATTR_TIMESTAMP])).strftime(
                    FMT_DATETIME) == "2020-12-13 10:00:00")

        # Test initial time sets timestamp correctly.
        state_time = hass.states.get("input_datetime.test_time_initial")
        assert state_time is not None
        assert state_time.state == "10:00:00"
        assert state_time.attributes[ATTR_TIMESTAMP] == 10 * 60 * 60

        # Test that setting the timestamp of an entity works.
        await hass.services.async_call(
            DOMAIN,
            "set_datetime",
            {
                ATTR_ENTITY_ID: "input_datetime.test_datetime_initial_with_tz",
                ATTR_TIMESTAMP: state_without_tz.attributes[ATTR_TIMESTAMP],
            },
            blocking=True,
        )
        state_with_tz_updated = hass.states.get(
            "input_datetime.test_datetime_initial_with_tz")
        assert state_with_tz_updated.state == "2020-12-13 10:00:00"
        assert (state_with_tz_updated.attributes[ATTR_TIMESTAMP] ==
                state_without_tz.attributes[ATTR_TIMESTAMP])

    finally:
        dt_util.set_default_time_zone(ORIG_TIMEZONE)
Example #38
0
 def teardown_method(self, method):
     """Stop everything that was started."""
     self.hass.stop()
     # Reset the default timezone, so we don't affect other tests
     set_default_time_zone(get_time_zone('UTC'))
def test_monthly_statistics(hass_recorder, caplog, timezone):
    """Test inserting external statistics."""
    dt_util.set_default_time_zone(dt_util.get_time_zone(timezone))

    hass = hass_recorder()
    wait_recording_done(hass)
    assert "Compiling statistics for" not in caplog.text
    assert "Statistics already compiled" not in caplog.text

    zero = dt_util.utcnow()
    period1 = dt_util.as_utc(dt_util.parse_datetime("2021-09-01 00:00:00"))
    period2 = dt_util.as_utc(dt_util.parse_datetime("2021-09-30 23:00:00"))
    period3 = dt_util.as_utc(dt_util.parse_datetime("2021-10-01 00:00:00"))
    period4 = dt_util.as_utc(dt_util.parse_datetime("2021-10-31 23:00:00"))

    external_statistics = (
        {
            "start": period1,
            "last_reset": None,
            "state": 0,
            "sum": 2,
        },
        {
            "start": period2,
            "last_reset": None,
            "state": 1,
            "sum": 3,
        },
        {
            "start": period3,
            "last_reset": None,
            "state": 2,
            "sum": 4,
        },
        {
            "start": period4,
            "last_reset": None,
            "state": 3,
            "sum": 5,
        },
    )
    external_metadata = {
        "has_mean": False,
        "has_sum": True,
        "name": "Total imported energy",
        "source": "test",
        "statistic_id": "test:total_energy_import",
        "unit_of_measurement": "kWh",
    }

    async_add_external_statistics(hass, external_metadata, external_statistics)
    wait_recording_done(hass)
    stats = statistics_during_period(hass, zero, period="month")
    sep_start = dt_util.as_utc(dt_util.parse_datetime("2021-09-01 00:00:00"))
    sep_end = dt_util.as_utc(dt_util.parse_datetime("2021-10-01 00:00:00"))
    oct_start = dt_util.as_utc(dt_util.parse_datetime("2021-10-01 00:00:00"))
    oct_end = dt_util.as_utc(dt_util.parse_datetime("2021-11-01 00:00:00"))
    assert stats == {
        "test:total_energy_import": [
            {
                "statistic_id": "test:total_energy_import",
                "start": sep_start.isoformat(),
                "end": sep_end.isoformat(),
                "max": None,
                "mean": None,
                "min": None,
                "last_reset": None,
                "state": approx(1.0),
                "sum": approx(3.0),
            },
            {
                "statistic_id": "test:total_energy_import",
                "start": oct_start.isoformat(),
                "end": oct_end.isoformat(),
                "max": None,
                "mean": None,
                "min": None,
                "last_reset": None,
                "state": approx(3.0),
                "sum": approx(5.0),
            },
        ]
    }

    dt_util.set_default_time_zone(dt_util.get_time_zone("UTC"))
Example #40
0
 def tearDown(self):
     """Stop everything that was started."""
     dt_util.set_default_time_zone(self.orig_default_time_zone)
Example #41
0
def test_find_next_time_expression_time_dst_chicago():
    """Test daylight saving time for find_next_time_expression_time."""
    tz = dt_util.get_time_zone("America/Chicago")
    dt_util.set_default_time_zone(tz)

    def find(dt, hour, minute, second) -> datetime:
        """Call test_find_next_time_expression_time."""
        seconds = dt_util.parse_time_expression(second, 0, 59)
        minutes = dt_util.parse_time_expression(minute, 0, 59)
        hours = dt_util.parse_time_expression(hour, 0, 23)

        local = dt_util.find_next_time_expression_time(dt, seconds, minutes,
                                                       hours)
        return dt_util.as_utc(local)

    # Entering DST, clocks are rolled forward
    assert dt_util.as_utc(datetime(2021, 3, 15, 2, 30, 0, tzinfo=tz)) == find(
        datetime(2021, 3, 14, 1, 50, 0, tzinfo=tz), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 3, 15, 2, 30, 0, tzinfo=tz)) == find(
        datetime(2021, 3, 14, 3, 50, 0, tzinfo=tz), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 3, 15, 2, 30, 0, tzinfo=tz)) == find(
        datetime(2021, 3, 14, 1, 50, 0, tzinfo=tz), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 3, 14, 3, 30, 0, tzinfo=tz)) == find(
        datetime(2021, 3, 14, 1, 50, 0, tzinfo=tz), 3, 30, 0)

    # Leaving DST, clocks are rolled back
    assert dt_util.as_utc(datetime(2021, 11, 7, 2, 30, 0, tzinfo=tz,
                                   fold=0)) == find(
                                       datetime(2021,
                                                11,
                                                7,
                                                2,
                                                5,
                                                0,
                                                tzinfo=tz,
                                                fold=0), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 11, 7, 2, 30, 0, tzinfo=tz)) == find(
        datetime(2021, 11, 7, 2, 5, 0, tzinfo=tz), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 11, 7, 2, 30, 0, tzinfo=tz,
                                   fold=0)) == find(
                                       datetime(2021,
                                                11,
                                                7,
                                                2,
                                                5,
                                                0,
                                                tzinfo=tz), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 11, 7, 2, 30, 0, tzinfo=tz,
                                   fold=1)) == find(
                                       datetime(2021,
                                                11,
                                                7,
                                                2,
                                                10,
                                                0,
                                                tzinfo=tz), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 11, 7, 2, 30, 0, tzinfo=tz,
                                   fold=1)) == find(
                                       datetime(2021,
                                                11,
                                                7,
                                                2,
                                                30,
                                                0,
                                                tzinfo=tz,
                                                fold=0), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 11, 8, 2, 30, 0, tzinfo=tz,
                                   fold=1)) == find(
                                       datetime(2021,
                                                11,
                                                7,
                                                2,
                                                55,
                                                0,
                                                tzinfo=tz,
                                                fold=0), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 11, 7, 4, 30, 0, tzinfo=tz,
                                   fold=0)) == find(
                                       datetime(2021,
                                                11,
                                                7,
                                                2,
                                                55,
                                                0,
                                                tzinfo=tz,
                                                fold=1), 4, 30, 0)

    assert dt_util.as_utc(datetime(2021, 11, 7, 2, 30, 0, tzinfo=tz,
                                   fold=1)) == find(
                                       datetime(2021,
                                                11,
                                                7,
                                                2,
                                                5,
                                                0,
                                                tzinfo=tz,
                                                fold=1), 2, 30, 0)

    assert dt_util.as_utc(datetime(2021, 11, 8, 2, 30, 0, tzinfo=tz)) == find(
        datetime(2021, 11, 7, 2, 55, 0, tzinfo=tz, fold=0), 2, 30, 0)
def new_york():
    """Set the default TZ to America/New_York."""
    dt.set_default_time_zone(dt.get_time_zone("America/New_York"))
Example #43
0
async def test_if_action_after_sunset_no_offset_kotzebue(hass, calls):
    """
    Test if action was after sunrise.

    Local timezone: Alaska time
    Location: Kotzebue, which has a very skewed local timezone with sunrise
    at 7 AM and sunset at 3AM during summer
    After sunset is true from sunset until midnight, local time.
    """
    tz = dt_util.get_time_zone("America/Anchorage")
    dt_util.set_default_time_zone(tz)
    hass.config.latitude = 66.5
    hass.config.longitude = 162.4
    await async_setup_component(
        hass,
        automation.DOMAIN,
        {
            automation.DOMAIN: {
                "trigger": {
                    "platform": "event",
                    "event_type": "test_event"
                },
                "condition": {
                    "condition": "sun",
                    "after": SUN_EVENT_SUNSET
                },
                "action": {
                    "service": "test.automation"
                },
            }
        },
    )

    # sunrise: 2015-07-24 07:17:24 local, sunset: 2015-07-25 03:16:27 local
    # sunrise: 2015-07-24 15:17:24 UTC,   sunset: 2015-07-25 11:16:27 UTC
    # now = sunset -> 'after sunset' true
    now = datetime(2015, 7, 25, 11, 16, 27, tzinfo=dt_util.UTC)
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        hass.bus.async_fire("test_event")
        await hass.async_block_till_done()
        assert len(calls) == 1

    # now = sunset - 1s -> 'after sunset' not true
    now = datetime(2015, 7, 25, 11, 16, 26, tzinfo=dt_util.UTC)
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        hass.bus.async_fire("test_event")
        await hass.async_block_till_done()
        assert len(calls) == 1

    # now = local midnight -> 'after sunset' not true
    now = datetime(2015, 7, 24, 8, 0, 1, tzinfo=dt_util.UTC)
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        hass.bus.async_fire("test_event")
        await hass.async_block_till_done()
        assert len(calls) == 1

    # now = local midnight - 1s -> 'after sunset' true
    now = datetime(2015, 7, 24, 7, 59, 59, tzinfo=dt_util.UTC)
    with patch("homeassistant.util.dt.utcnow", return_value=now):
        hass.bus.async_fire("test_event")
        await hass.async_block_till_done()
        assert len(calls) == 2
def utc():
    """Set the default TZ to UTC."""
    dt.set_default_time_zone(dt.get_time_zone("UTC"))
import logging
from homeassistant.util import dt as dt_util
from datetime import timedelta
from csv import writer
import matplotlib.pyplot as plt

_LOGGER = logging.getLogger(__name__)

if __name__ == '__main__':
    from custom_components.circadian_white.sensor import CircadianWhiteSensor
    # When to simulate
    dt_util.set_default_time_zone(dt_util.get_time_zone('Australia/Melbourne'))

    now = dt_util.now()
    day_start = now.replace(hour=7, minute=1, second=42)
    day_middle = now.replace(hour=12, minute=19, second=32)
    day_end = now.replace(hour=17, minute=37, second=26)

    circ = CircadianWhiteSensor('test_math', 2500, 4500, 6500, 2, 3)

    for offset in range(24):
        print("Offset {}".format(offset))
        test_now = now.replace(hour=offset, minute=0, second=0)

        circ._calculate_day_events(test_now, day_start, day_middle, day_end)
        print(circ._day_start)
        print(day_start)
        print(circ._day_middle)
        print(day_middle)
        print(circ._day_end)
        print(day_end)
Example #46
0
def async_test_home_assistant(loop):
    """Return a Home Assistant object pointing at test config dir."""
    hass = ha.HomeAssistant(loop)
    hass.config.async_load = Mock()
    store = auth_store.AuthStore(hass)
    hass.auth = auth.AuthManager(hass, store, {}, {})
    ensure_auth_manager_loaded(hass.auth)
    INSTANCES.append(hass)

    orig_async_add_job = hass.async_add_job
    orig_async_add_executor_job = hass.async_add_executor_job
    orig_async_create_task = hass.async_create_task

    def async_add_job(target, *args):
        """Add job."""
        if isinstance(target, Mock):
            return mock_coro(target(*args))
        return orig_async_add_job(target, *args)

    def async_add_executor_job(target, *args):
        """Add executor job."""
        if isinstance(target, Mock):
            return mock_coro(target(*args))
        return orig_async_add_executor_job(target, *args)

    def async_create_task(coroutine):
        """Create task."""
        if isinstance(coroutine, Mock):
            return mock_coro()
        return orig_async_create_task(coroutine)

    hass.async_add_job = async_add_job
    hass.async_add_executor_job = async_add_executor_job
    hass.async_create_task = async_create_task

    hass.config.location_name = "test home"
    hass.config.latitude = 51.8391
    hass.config.longitude = 5.8739
    hass.config.elevation = 0
    hass.config.time_zone = date_util.get_time_zone("Europe/Amsterdam")
    hass.config.units = METRIC_SYSTEM
    hass.config.skip_pip = True

    date_util.set_default_time_zone(hass.config.time_zone)

    hass.config_entries = config_entries.ConfigEntries(hass, {})
    hass.config_entries._entries = []
    hass.config_entries._store._async_ensure_stop_listener = lambda: None

    hass.state = ha.CoreState.running

    # Mock async_start
    orig_start = hass.async_start

    @asyncio.coroutine
    def mock_async_start():
        """Start the mocking."""
        # We only mock time during tests and we want to track tasks
        with patch("homeassistant.core._async_create_timer"), patch.object(
                hass, "async_stop_track_tasks"):
            yield from orig_start()

    hass.async_start = mock_async_start

    @ha.callback
    def clear_instance(event):
        """Clear global instance."""
        INSTANCES.remove(hass)

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, clear_instance)

    return hass
 def tearDown(self):
     """Stop everything that was started."""
     dt_util.set_default_time_zone(self.DEFAULT_TIME_ZONE)
     self.hass.stop()
Example #48
0
 def tearDown(self):
     dt_util.set_default_time_zone(self.orig_default_time_zone)
    def tearDown(self):
        """Stop everything that was started."""
        dt_util.set_default_time_zone(dt_util.get_time_zone('UTC'))

        self.hass.stop()
Example #50
0
def teardown_module():
    """Reset time zone."""
    dt_util.set_default_time_zone(ORIG_TIME_ZONE)
Example #51
0
 def tearDown(self):
     """Stop everything that was started."""
     dt_util.set_default_time_zone(self.DEFAULT_TIME_ZONE)
     self.hass.stop()