Exemplo n.º 1
0
def set_time_zone():
    """Set the time zone for the tests."""
    # 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"))
    yield
    dt_util.set_default_time_zone(dt_util.get_time_zone("UTC"))
Exemplo n.º 2
0
async def test_timezone_intervals(opp):
    """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(opp, "date")
    now = dt_util.utc_from_timestamp(50000)
    with patch("openpeerpower.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(opp, "date")
    with patch("openpeerpower.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("openpeerpower.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("openpeerpower.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("openpeerpower.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("openpeerpower.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")
Exemplo n.º 3
0
def test_now():
    """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)
Exemplo n.º 4
0
def test_set_default_time_zone():
    """Test setting default time zone."""
    time_zone = dt_util.get_time_zone(TEST_TIME_ZONE)

    dt_util.set_default_time_zone(time_zone)

    assert dt_util.now().tzinfo is time_zone
Exemplo n.º 5
0
async def test_states_non_default_timezone(opp):
    """Test states of sensors in a timezone other than 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)

    now = dt_util.utc_from_timestamp(1495068856)
    device = time_date.TimeDateSensor(opp, "time")
    device._update_internal_state(now)
    assert device.state == "20:54"

    device = time_date.TimeDateSensor(opp, "date")
    device._update_internal_state(now)
    assert device.state == "2017-05-17"

    device = time_date.TimeDateSensor(opp, "time_utc")
    device._update_internal_state(now)
    assert device.state == "00:54"

    device = time_date.TimeDateSensor(opp, "date_time")
    device._update_internal_state(now)
    assert device.state == "2017-05-17, 20:54"

    device = time_date.TimeDateSensor(opp, "date_time_utc")
    device._update_internal_state(now)
    assert device.state == "2017-05-18, 00:54"

    device = time_date.TimeDateSensor(opp, "beat")
    device._update_internal_state(now)
    assert device.state == "@079"

    device = time_date.TimeDateSensor(opp, "date_time_iso")
    device._update_internal_state(now)
    assert device.state == "2017-05-17T20:54:00"
Exemplo n.º 6
0
def test_auto_purge_disabled(opp_recorder):
    """Test periodic db cleanup still run when auto purge is disabled."""
    opp = opp_recorder({CONF_AUTO_PURGE: False})

    original_tz = dt_util.DEFAULT_TIME_ZONE

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

    # Purging is scheduled to happen at 4:12am every day. We want
    # to verify that when auto purge is disabled perodic db cleanups
    # are still scheduled
    #
    # The clock is started at 4:15am then advanced forward below
    now = dt_util.utcnow()
    test_time = datetime(now.year + 2, 1, 1, 4, 15, 0, tzinfo=tz)
    run_tasks_at_time(opp, test_time)

    with patch("openpeerpower.components.recorder.purge.purge_old_data",
               return_value=True) as purge_old_data, patch(
                   "openpeerpower.components.recorder.perodic_db_cleanups"
               ) as perodic_db_cleanups:
        # Advance one day, and the purge task should run
        test_time = test_time + timedelta(days=1)
        run_tasks_at_time(opp, test_time)
        assert len(purge_old_data.mock_calls) == 0
        assert len(perodic_db_cleanups.mock_calls) == 1

        purge_old_data.reset_mock()
        perodic_db_cleanups.reset_mock()

    dt_util.set_default_time_zone(original_tz)
Exemplo n.º 7
0
 def _naive_time_to_utc_datetime(self, naive_time):
     """Convert naive time from config to utc_datetime with current day."""
     # get the current local date from utc time
     current_local_date = (dt_util.utcnow().astimezone(
         dt_util.get_time_zone(self.opp.config.time_zone)).date())
     # calculate utc datetime corresponding to local time
     return dt_util.as_utc(datetime.combine(current_local_date, naive_time))
Exemplo n.º 8
0
def time_zone(value: str) -> str:
    """Validate timezone."""
    if dt_util.get_time_zone(value) is not None:
        return value
    raise vol.Invalid(
        "Invalid time zone passed in. Valid options can be found here: "
        "http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
Exemplo n.º 9
0
def test_as_utc_with_local_object():
    """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
Exemplo n.º 10
0
async def test_timezone_intervals_empty_parameter(opp):
    """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(opp, "date")
    next_time = device.get_next_interval()
    assert next_time.timestamp() == dt_util.as_timestamp("2017-11-14 00:00:00-07:00")
Exemplo n.º 11
0
def test_as_local_with_utc_object():
    """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
Exemplo n.º 12
0
 def extra_state_attributes(self):
     """Return the state attributes of the sensor."""
     time_zone = dt_util.get_time_zone(self.opp.config.time_zone)
     return {
         ATTR_AFTER: self._time_after.astimezone(time_zone).isoformat(),
         ATTR_BEFORE: self._time_before.astimezone(time_zone).isoformat(),
         ATTR_NEXT_UPDATE:
         self._next_update.astimezone(time_zone).isoformat(),
     }
Exemplo n.º 13
0
    def set_time_zone(self, time_zone_str: str) -> None:
        """Help to set the time zone."""
        time_zone = dt_util.get_time_zone(time_zone_str)

        if time_zone:
            self.time_zone = time_zone
            dt_util.set_default_time_zone(time_zone)
        else:
            raise ValueError(f"Received invalid time zone {time_zone_str}")
Exemplo n.º 14
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):
        """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 datetime(2021, 3, 15, 2, 30, 0, tzinfo=tz) == find(
        datetime(2021, 3, 14, 1, 50, 0, tzinfo=tz), 2, 30, 0)

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

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

    assert 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 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 datetime(2021, 11, 7, 2, 30, 0, tzinfo=tz) == find(
        datetime(2021, 11, 7, 2, 5, 0, tzinfo=tz), 2, 30, 0)

    assert 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 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 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 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 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 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 datetime(2021, 11, 8, 2, 30, 0, tzinfo=tz) == find(
        datetime(2021, 11, 7, 2, 55, 0, tzinfo=tz, fold=0), 2, 30, 0)
Exemplo n.º 15
0
def test_auto_purge(opp_recorder):
    """Test periodic purge scheduling."""
    opp = opp_recorder()

    original_tz = dt_util.DEFAULT_TIME_ZONE

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

    # Purging is scheduled to happen at 4:12am every day. Exercise this behavior by
    # firing time changed events and advancing the clock around this time. Pick an
    # arbitrary year in the future to avoid boundary conditions relative to the current
    # date.
    #
    # The clock is started at 4:15am then advanced forward below
    now = dt_util.utcnow()
    test_time = datetime(now.year + 2, 1, 1, 4, 15, 0, tzinfo=tz)
    run_tasks_at_time(opp, test_time)

    with patch("openpeerpower.components.recorder.purge.purge_old_data",
               return_value=True) as purge_old_data, patch(
                   "openpeerpower.components.recorder.perodic_db_cleanups"
               ) as perodic_db_cleanups:
        # Advance one day, and the purge task should run
        test_time = test_time + timedelta(days=1)
        run_tasks_at_time(opp, test_time)
        assert len(purge_old_data.mock_calls) == 1
        assert len(perodic_db_cleanups.mock_calls) == 1

        purge_old_data.reset_mock()
        perodic_db_cleanups.reset_mock()

        # Advance one day, and the purge task should run again
        test_time = test_time + timedelta(days=1)
        run_tasks_at_time(opp, test_time)
        assert len(purge_old_data.mock_calls) == 1
        assert len(perodic_db_cleanups.mock_calls) == 1

        purge_old_data.reset_mock()
        perodic_db_cleanups.reset_mock()

        # Advance less than one full day.  The alarm should not yet fire.
        test_time = test_time + timedelta(hours=23)
        run_tasks_at_time(opp, test_time)
        assert len(purge_old_data.mock_calls) == 0
        assert len(perodic_db_cleanups.mock_calls) == 0

        # Advance to the next day and fire the alarm again
        test_time = test_time + timedelta(hours=1)
        run_tasks_at_time(opp, test_time)
        assert len(purge_old_data.mock_calls) == 1
        assert len(perodic_db_cleanups.mock_calls) == 1

    dt_util.set_default_time_zone(original_tz)
Exemplo n.º 16
0
async def test_if_action_after_sunset_no_offset_kotzebue(opp, 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)
    opp.config.latitude = 66.5
    opp.config.longitude = 162.4
    await async_setup_component(
        opp,
        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("openpeerpower.util.dt.utcnow", return_value=now):
        opp.bus.async_fire("test_event")
        await opp.async_block_till_done()
        assert 1 == len(calls)

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

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

    # now = local midnight - 1s -> 'after sunset' true
    now = datetime(2015, 7, 24, 7, 59, 59, tzinfo=dt_util.UTC)
    with patch("openpeerpower.util.dt.utcnow", return_value=now):
        opp.bus.async_fire("test_event")
        await opp.async_block_till_done()
        assert 2 == len(calls)
Exemplo n.º 17
0
async def test_process_timestamp():
    """Test processing time stamp to UTC."""
    datetime_with_tzinfo = datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC)
    datetime_without_tzinfo = datetime(2016, 7, 9, 11, 0, 0)
    est = dt_util.get_time_zone("US/Eastern")
    datetime_est_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=est)
    nst = dt_util.get_time_zone("Canada/Newfoundland")
    datetime_nst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=nst)
    hst = dt_util.get_time_zone("US/Hawaii")
    datetime_hst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=hst)

    assert process_timestamp(datetime_with_tzinfo) == datetime(2016,
                                                               7,
                                                               9,
                                                               11,
                                                               0,
                                                               0,
                                                               tzinfo=dt.UTC)
    assert process_timestamp(datetime_without_tzinfo) == datetime(
        2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC)
    assert process_timestamp(datetime_est_timezone) == datetime(2016,
                                                                7,
                                                                9,
                                                                15,
                                                                0,
                                                                tzinfo=dt.UTC)
    assert process_timestamp(datetime_nst_timezone) == datetime(2016,
                                                                7,
                                                                9,
                                                                13,
                                                                30,
                                                                tzinfo=dt.UTC)
    assert process_timestamp(datetime_hst_timezone) == datetime(2016,
                                                                7,
                                                                9,
                                                                21,
                                                                0,
                                                                tzinfo=dt.UTC)
    assert process_timestamp(None) is None
Exemplo n.º 18
0
async def test_process_timestamp_to_utc_isoformat():
    """Test processing time stamp to UTC isoformat."""
    datetime_with_tzinfo = datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC)
    datetime_without_tzinfo = datetime(2016, 7, 9, 11, 0, 0)
    est = dt_util.get_time_zone("US/Eastern")
    datetime_est_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=est)
    est = dt_util.get_time_zone("US/Eastern")
    datetime_est_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=est)
    nst = dt_util.get_time_zone("Canada/Newfoundland")
    datetime_nst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=nst)
    hst = dt_util.get_time_zone("US/Hawaii")
    datetime_hst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=hst)

    assert (process_timestamp_to_utc_isoformat(datetime_with_tzinfo) ==
            "2016-07-09T11:00:00+00:00")
    assert (process_timestamp_to_utc_isoformat(datetime_without_tzinfo) ==
            "2016-07-09T11:00:00+00:00")
    assert (process_timestamp_to_utc_isoformat(datetime_est_timezone) ==
            "2016-07-09T15:00:00+00:00")
    assert (process_timestamp_to_utc_isoformat(datetime_nst_timezone) ==
            "2016-07-09T13:30:00+00:00")
    assert (process_timestamp_to_utc_isoformat(datetime_hst_timezone) ==
            "2016-07-09T21:00:00+00:00")
    assert process_timestamp_to_utc_isoformat(None) is None
Exemplo n.º 19
0
def test_auto_statistics(opp_recorder):
    """Test periodic statistics scheduling."""
    opp = opp_recorder()

    original_tz = dt_util.DEFAULT_TIME_ZONE

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

    # Statistics is scheduled to happen at *:12am every hour. Exercise this behavior by
    # firing time changed events and advancing the clock around this time. Pick an
    # arbitrary year in the future to avoid boundary conditions relative to the current
    # date.
    #
    # The clock is started at 4:15am then advanced forward below
    now = dt_util.utcnow()
    test_time = datetime(now.year + 2, 1, 1, 4, 15, 0, tzinfo=tz)
    run_tasks_at_time(opp, test_time)

    with patch(
            "openpeerpower.components.recorder.statistics.compile_statistics",
            return_value=True,
    ) as compile_statistics:
        # Advance one hour, and the statistics task should run
        test_time = test_time + timedelta(hours=1)
        run_tasks_at_time(opp, test_time)
        assert len(compile_statistics.mock_calls) == 1

        compile_statistics.reset_mock()

        # Advance one hour, and the statistics task should run again
        test_time = test_time + timedelta(hours=1)
        run_tasks_at_time(opp, test_time)
        assert len(compile_statistics.mock_calls) == 1

        compile_statistics.reset_mock()

        # Advance less than one full hour. The task should not run.
        test_time = test_time + timedelta(minutes=50)
        run_tasks_at_time(opp, test_time)
        assert len(compile_statistics.mock_calls) == 0

        # Advance to the next hour, and the statistics task should run again
        test_time = test_time + timedelta(hours=1)
        run_tasks_at_time(opp, test_time)
        assert len(compile_statistics.mock_calls) == 1

    dt_util.set_default_time_zone(original_tz)
Exemplo n.º 20
0
async def async_setup_platform(opp,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the World clock sensor."""
    name = config.get(CONF_NAME)
    time_zone = dt_util.get_time_zone(config.get(CONF_TIME_ZONE))

    async_add_entities(
        [WorldClockSensor(
            time_zone,
            name,
            config.get(CONF_TIME_FORMAT),
        )],
        True,
    )
Exemplo n.º 21
0
def test_find_next_time_expression_time_dst():
    """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 datetime(2018, 3, 26, 2, 30, 0, tzinfo=tz) == find(
        datetime(2018, 3, 25, 1, 50, 0, tzinfo=tz), 2, 30, 0)

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

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

    # Leaving DST, clocks are rolled back
    assert datetime(2018, 10, 28, 2, 30, 0, tzinfo=tz, fold=0) == find(
        datetime(2018, 10, 28, 2, 5, 0, tzinfo=tz, fold=0), 2, 30, 0)

    assert datetime(2018, 10, 28, 2, 30, 0, tzinfo=tz,
                    fold=0) == find(datetime(2018, 10, 28, 2, 5, 0, tzinfo=tz),
                                    2, 30, 0)

    assert datetime(2018, 10, 28, 2, 30, 0, tzinfo=tz, fold=1) == find(
        datetime(2018, 10, 28, 2, 55, 0, tzinfo=tz), 2, 30, 0)

    assert datetime(2018, 10, 28, 2, 30, 0, tzinfo=tz, fold=1) == find(
        datetime(2018, 10, 28, 2, 55, 0, tzinfo=tz, fold=0), 2, 30, 0)

    assert datetime(2018, 10, 28, 4, 30, 0, tzinfo=tz, fold=0) == find(
        datetime(2018, 10, 28, 2, 55, 0, tzinfo=tz, fold=1), 4, 30, 0)

    assert datetime(2018, 10, 28, 2, 30, 0, tzinfo=tz, fold=1) == find(
        datetime(2018, 10, 28, 2, 5, 0, tzinfo=tz, fold=1), 2, 30, 0)

    assert datetime(2018, 10, 28, 2, 30, 0, tzinfo=tz, fold=1) == find(
        datetime(2018, 10, 28, 2, 55, 0, tzinfo=tz, fold=0), 2, 30, 0)
Exemplo n.º 22
0
async def test_websocket_core_update(opp, client):
    """Test core config update websocket command."""
    assert opp.config.latitude != 60
    assert opp.config.longitude != 50
    assert opp.config.elevation != 25
    assert opp.config.location_name != "Huis"
    assert opp.config.units.name != CONF_UNIT_SYSTEM_IMPERIAL
    assert opp.config.time_zone != "America/New_York"
    assert opp.config.external_url != "https://www.example.com"
    assert opp.config.internal_url != "http://example.com"

    with patch("openpeerpower.util.dt.set_default_time_zone") as mock_set_tz:
        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 opp.config.latitude == 60
    assert opp.config.longitude == 50
    assert opp.config.elevation == 25
    assert opp.config.location_name == "Huis"
    assert opp.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL
    assert opp.config.external_url == "https://www.example.com"
    assert opp.config.internal_url == "http://example.local"

    assert len(mock_set_tz.mock_calls) == 1
    assert mock_set_tz.mock_calls[0][1][0] == dt_util.get_time_zone("America/New_York")
Exemplo n.º 23
0
    def update(self):
        """Update the data for the sensor."""
        time_zone = dt_util.get_time_zone(self.opp.config.time_zone)
        start = get_date(time_zone)
        end = get_date(time_zone, self.days)
        try:
            res = requests.get(
                ENDPOINTS[self.type].format(
                    self.ssl, self.host, self.port, self.urlbase, start, end
                ),
                headers={"X-Api-Key": self.apikey},
                timeout=10,
            )
        except OSError:
            _LOGGER.warning("Host %s is not available", self.host)
            self._available = False
            self._state = None
            return

        if res.status_code == HTTP_OK:
            if self.type in ["upcoming", "movies", "commands"]:
                self.data = res.json()
                self._state = len(self.data)
            elif self.type == "diskspace":
                # If included paths are not provided, use all data
                if self.included == []:
                    self.data = res.json()
                else:
                    # Filter to only show lists that are included
                    self.data = list(
                        filter(lambda x: x["path"] in self.included, res.json())
                    )
                self._state = "{:.2f}".format(
                    to_unit(sum([data["freeSpace"] for data in self.data]), self._unit)
                )
            elif self.type == "status":
                self.data = res.json()
                self._state = self.data["version"]
            self._available = True
Exemplo n.º 24
0
def test_get_time_zone_retrieves_valid_time_zone():
    """Test getting a time zone."""
    assert dt_util.get_time_zone(TEST_TIME_ZONE) is not None
Exemplo n.º 25
0
    MATCH_ALL,
    __version__,
)
import openpeerpower.core as ha
from openpeerpower.exceptions import (
    InvalidEntityFormatError,
    InvalidStateError,
    MaxLengthExceeded,
    ServiceNotFound,
)
import openpeerpower.util.dt as dt_util
from openpeerpower.util.unit_system import METRIC_SYSTEM

from tests.common import async_capture_events, async_mock_service

PST = dt_util.get_time_zone("America/Los_Angeles")


def test_split_entity_id():
    """Test split_entity_id."""
    assert ha.split_entity_id("domain.object_id") == ["domain", "object_id"]


def test_async_add_opp_job_schedule_callback():
    """Test that we schedule coroutines and add jobs to the job pool."""
    opp = MagicMock()
    job = MagicMock()

    ha.OpenPeerPower.async_add_opp_job(opp, ha.OppJob(ha.callback(job)))
    assert len(opp.loop.call_soon.mock_calls) == 1
    assert len(opp.loop.create_task.mock_calls) == 0
Exemplo n.º 26
0
async def test_sensor_availability(opp, caplog, legacy_patchable_time,
                                   pvpc_aioclient_mock: AiohttpClientMocker):
    """Test sensor availability and handling of cloud access."""
    opp.config.time_zone = dt_util.get_time_zone("Europe/Madrid")
    config = {DOMAIN: [{CONF_NAME: "test_dst", ATTR_TARIFF: "discrimination"}]}
    mock_data = {
        "return_time": datetime(2019, 10, 27, 20, 0, 0, tzinfo=date_util.UTC)
    }

    def mock_now():
        return mock_data["return_time"]

    with patch("openpeerpower.util.dt.utcnow", new=mock_now):
        assert await async_setup_component(opp, DOMAIN, config)
        await opp.async_block_till_done()
        caplog.clear()
        assert pvpc_aioclient_mock.call_count == 2

        await _process_time_step(opp, mock_data, "price_21h", 0.13896)
        await _process_time_step(opp, mock_data, "price_22h", 0.06893)
        assert pvpc_aioclient_mock.call_count == 4
        await _process_time_step(opp, mock_data, "price_23h", 0.06935)
        assert pvpc_aioclient_mock.call_count == 5

        # sensor has no more prices, state is "unavailable" from now on
        await _process_time_step(opp, mock_data, value="unavailable")
        await _process_time_step(opp, mock_data, value="unavailable")
        num_errors = sum(1 for x in caplog.records
                         if x.levelno == logging.ERROR
                         and "unknown job listener" not in x.msg)
        num_warnings = sum(1 for x in caplog.records
                           if x.levelno == logging.WARNING)
        assert num_warnings == 1
        assert num_errors == 0
        assert pvpc_aioclient_mock.call_count == 9

        # check that it is silent until it becomes available again
        caplog.clear()
        with caplog.at_level(logging.WARNING):
            # silent mode
            for _ in range(21):
                await _process_time_step(opp, mock_data, value="unavailable")
            assert pvpc_aioclient_mock.call_count == 30
            assert len(caplog.messages) == 0

            # warning about data access recovered
            await _process_time_step(opp, mock_data, value="unavailable")
            assert pvpc_aioclient_mock.call_count == 31
            assert len(caplog.messages) == 1
            assert caplog.records[0].levelno == logging.WARNING

            # working ok again
            await _process_time_step(opp,
                                     mock_data,
                                     "price_00h",
                                     value=0.06821)
            assert pvpc_aioclient_mock.call_count == 32
            await _process_time_step(opp,
                                     mock_data,
                                     "price_01h",
                                     value=0.06627)
            assert pvpc_aioclient_mock.call_count == 33
            assert len(caplog.messages) == 1
            assert caplog.records[0].levelno == logging.WARNING
Exemplo n.º 27
0
def test_get_time_zone_returns_none_for_garbage_time_zone():
    """Test getting a non existing time zone."""
    assert dt_util.get_time_zone("Non existing time zone") is None
Exemplo n.º 28
0
def time_zone():
    """Fixture for time zone."""
    return dt_util.get_time_zone("America/New_York")
Exemplo n.º 29
0
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
MAX_LIST = 20
MAX_TIME_OFFSET = 360
ICON = "mdi:bus"

ATTR_DEPARTURE = "departure"
ATTR_LINE = "line"
ATTR_ORIGIN = "origin"
ATTR_DIRECTION = "direction"
ATTR_TYPE = "type"
ATTR_DELAY = "delay"
ATTR_NEXT = "next"

PARALLEL_UPDATES = 0
BERLIN_TIME_ZONE = get_time_zone("Europe/Berlin")

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(opp, config_entry, async_add_devices):
    """Set up the sensor platform."""
    hub = opp.data[DOMAIN][config_entry.entry_id]

    session = aiohttp_client.async_get_clientsession(opp)

    sensor = HVVDepartureSensor(opp, config_entry, session, hub)
    async_add_devices([sensor], True)


class HVVDepartureSensor(SensorEntity):
Exemplo n.º 30
0
async def test_timestamp(opp):
    """Test timestamp."""
    try:
        dt_util.set_default_time_zone(
            dt_util.get_time_zone("America/Los_Angeles"))

        assert await async_setup_component(
            opp,
            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 = opp.states.get(
            "input_datetime.test_datetime_initial_with_tz")
        assert state_with_tz is not None
        # Timezone LA is UTC-8 => timestamp carries +01:00 => delta is -9 => 10:00 - 09:00 => 01:00
        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 = opp.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"
        # Timezone LA is UTC-8 => timestamp has no zone (= assumed local) => delta to UTC is +8 => 10:00 + 08:00 => 18:00
        assert (dt_util.utc_from_timestamp(
            state_without_tz.attributes[ATTR_TIMESTAMP]).strftime(FMT_DATETIME)
                == "2020-12-13 18: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],
                datetime.timezone.utc)).strftime(FMT_DATETIME) ==
                "2020-12-13 10:00:00")

        # Test initial time sets timestamp correctly.
        state_time = opp.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 opp.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 = opp.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)