diff --git a/tests/common.py b/tests/common.py index bdebc7217a7..55878f76da7 100644 --- a/tests/common.py +++ b/tests/common.py @@ -282,7 +282,7 @@ async def async_test_home_assistant(loop, load_registries=True): hass.config.latitude = 32.87336 hass.config.longitude = -117.22743 hass.config.elevation = 0 - hass.config.time_zone = "US/Pacific" + hass.config.set_time_zone("US/Pacific") hass.config.units = METRIC_SYSTEM hass.config.media_dirs = {"local": get_test_config_dir("media")} hass.config.skip_pip = True diff --git a/tests/components/aemet/test_sensor.py b/tests/components/aemet/test_sensor.py index 7887139a386..b5e7679dbe6 100644 --- a/tests/components/aemet/test_sensor.py +++ b/tests/components/aemet/test_sensor.py @@ -15,6 +15,7 @@ from .util import async_init_integration async def test_aemet_forecast_create_sensors(hass): """Test creation of forecast sensors.""" + hass.config.set_time_zone("UTC") now = dt_util.parse_datetime("2021-01-09 12:00:00+00:00") with patch("homeassistant.util.dt.now", return_value=now), patch( "homeassistant.util.dt.utcnow", return_value=now diff --git a/tests/components/aemet/test_weather.py b/tests/components/aemet/test_weather.py index 43acf4c1c87..d1f1889c807 100644 --- a/tests/components/aemet/test_weather.py +++ b/tests/components/aemet/test_weather.py @@ -30,6 +30,7 @@ from .util import async_init_integration async def test_aemet_weather(hass): """Test states of the weather.""" + hass.config.set_time_zone("UTC") now = dt_util.parse_datetime("2021-01-09 12:00:00+00:00") with patch("homeassistant.util.dt.now", return_value=now), patch( "homeassistant.util.dt.utcnow", return_value=now diff --git a/tests/components/caldav/test_calendar.py b/tests/components/caldav/test_calendar.py index 6993aa97081..7bfb8b620f6 100644 --- a/tests/components/caldav/test_calendar.py +++ b/tests/components/caldav/test_calendar.py @@ -222,15 +222,6 @@ CALDAV_CONFIG = { "custom_calendars": [], } -ORIG_TZ = dt.DEFAULT_TIME_ZONE - - -@pytest.fixture(autouse=True) -def reset_tz(): - """Restore the default TZ after test runs.""" - yield - dt.DEFAULT_TIME_ZONE = ORIG_TZ - @pytest.fixture def set_tz(request): @@ -239,21 +230,21 @@ def set_tz(request): @pytest.fixture -def utc(): +def utc(hass): """Set the default TZ to UTC.""" - dt.set_default_time_zone(dt.get_time_zone("UTC")) + hass.config.set_time_zone("UTC") @pytest.fixture -def new_york(): +def new_york(hass): """Set the default TZ to America/New_York.""" - dt.set_default_time_zone(dt.get_time_zone("America/New_York")) + hass.config.set_time_zone("America/New_York") @pytest.fixture -def baghdad(): +def baghdad(hass): """Set the default TZ to Asia/Baghdad.""" - dt.set_default_time_zone(dt.get_time_zone("Asia/Baghdad")) + hass.config.set_time_zone("Asia/Baghdad") @pytest.fixture(autouse=True) @@ -364,8 +355,9 @@ async def test_setup_component_with_one_custom_calendar(hass, mock_dav_client): assert state.name == "HomeOffice" +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 45)) -async def test_ongoing_event(mock_now, hass, calendar): +async def test_ongoing_event(mock_now, hass, calendar, set_tz): """Test that the ongoing event is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -385,8 +377,9 @@ async def test_ongoing_event(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 30)) -async def test_just_ended_event(mock_now, hass, calendar): +async def test_just_ended_event(mock_now, hass, calendar, set_tz): """Test that the next ongoing event is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -406,8 +399,9 @@ async def test_just_ended_event(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 00)) -async def test_ongoing_event_different_tz(mock_now, hass, calendar): +async def test_ongoing_event_different_tz(mock_now, hass, calendar, set_tz): """Test that the ongoing event with another timezone is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -427,8 +421,9 @@ async def test_ongoing_event_different_tz(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(19, 10)) -async def test_ongoing_floating_event_returned(mock_now, hass, calendar): +async def test_ongoing_floating_event_returned(mock_now, hass, calendar, set_tz): """Test that floating events without timezones work.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -448,8 +443,9 @@ async def test_ongoing_floating_event_returned(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(8, 30)) -async def test_ongoing_event_with_offset(mock_now, hass, calendar): +async def test_ongoing_event_with_offset(mock_now, hass, calendar, set_tz): """Test that the offset is taken into account.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -469,8 +465,9 @@ async def test_ongoing_event_with_offset(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(12, 00)) -async def test_matching_filter(mock_now, hass, calendar): +async def test_matching_filter(mock_now, hass, calendar, set_tz): """Test that the matching event is returned.""" config = dict(CALDAV_CONFIG) config["custom_calendars"] = [ @@ -495,8 +492,9 @@ async def test_matching_filter(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(12, 00)) -async def test_matching_filter_real_regexp(mock_now, hass, calendar): +async def test_matching_filter_real_regexp(mock_now, hass, calendar, set_tz): """Test that the event matching the regexp is returned.""" config = dict(CALDAV_CONFIG) config["custom_calendars"] = [ @@ -625,8 +623,9 @@ async def test_all_day_event_returned_late(hass, calendar, set_tz): ) +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(21, 45)) -async def test_event_rrule(mock_now, hass, calendar): +async def test_event_rrule(mock_now, hass, calendar, set_tz): """Test that the future recurring event is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -646,8 +645,9 @@ async def test_event_rrule(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(22, 15)) -async def test_event_rrule_ongoing(mock_now, hass, calendar): +async def test_event_rrule_ongoing(mock_now, hass, calendar, set_tz): """Test that the current recurring event is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -667,8 +667,9 @@ async def test_event_rrule_ongoing(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(22, 45)) -async def test_event_rrule_duration(mock_now, hass, calendar): +async def test_event_rrule_duration(mock_now, hass, calendar, set_tz): """Test that the future recurring event is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -688,8 +689,9 @@ async def test_event_rrule_duration(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(23, 15)) -async def test_event_rrule_duration_ongoing(mock_now, hass, calendar): +async def test_event_rrule_duration_ongoing(mock_now, hass, calendar, set_tz): """Test that the ongoing recurring event is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -709,8 +711,9 @@ async def test_event_rrule_duration_ongoing(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch("homeassistant.util.dt.now", return_value=_local_datetime(23, 37)) -async def test_event_rrule_endless(mock_now, hass, calendar): +async def test_event_rrule_endless(mock_now, hass, calendar, set_tz): """Test that the endless recurring event is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -798,11 +801,12 @@ async def test_event_rrule_all_day_late(hass, calendar, set_tz): ) +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch( "homeassistant.util.dt.now", return_value=dt.as_local(datetime.datetime(2015, 11, 27, 0, 15)), ) -async def test_event_rrule_hourly_on_first(mock_now, hass, calendar): +async def test_event_rrule_hourly_on_first(mock_now, hass, calendar, set_tz): """Test that the endless recurring event is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() @@ -822,11 +826,12 @@ async def test_event_rrule_hourly_on_first(mock_now, hass, calendar): } +@pytest.mark.parametrize("set_tz", ["utc"], indirect=True) @patch( "homeassistant.util.dt.now", return_value=dt.as_local(datetime.datetime(2015, 11, 27, 11, 15)), ) -async def test_event_rrule_hourly_on_last(mock_now, hass, calendar): +async def test_event_rrule_hourly_on_last(mock_now, hass, calendar, set_tz): """Test that the endless recurring event is returned.""" assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) await hass.async_block_till_done() diff --git a/tests/components/climacell/test_weather.py b/tests/components/climacell/test_weather.py index 3bac69dcbc5..d5385b6cfd5 100644 --- a/tests/components/climacell/test_weather.py +++ b/tests/components/climacell/test_weather.py @@ -91,7 +91,7 @@ async def test_v3_weather( assert weather_state.attributes[ATTR_FORECAST] == [ { ATTR_FORECAST_CONDITION: ATTR_CONDITION_SUNNY, - ATTR_FORECAST_TIME: "2021-03-07T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-07T00:00:00-08:00", ATTR_FORECAST_PRECIPITATION: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_TEMP: 7, @@ -99,7 +99,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-08T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-08T00:00:00-08:00", ATTR_FORECAST_PRECIPITATION: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_TEMP: 10, @@ -107,7 +107,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-09T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-09T00:00:00-08:00", ATTR_FORECAST_PRECIPITATION: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_TEMP: 19, @@ -115,7 +115,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-10T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-10T00:00:00-08:00", ATTR_FORECAST_PRECIPITATION: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_TEMP: 18, @@ -123,7 +123,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-11T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-11T00:00:00-08:00", ATTR_FORECAST_PRECIPITATION: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 5, ATTR_FORECAST_TEMP: 20, @@ -131,7 +131,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-12T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-12T00:00:00-08:00", ATTR_FORECAST_PRECIPITATION: 0.0457, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 25, ATTR_FORECAST_TEMP: 20, @@ -139,7 +139,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-13T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-13T00:00:00-08:00", ATTR_FORECAST_PRECIPITATION: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 25, ATTR_FORECAST_TEMP: 16, @@ -147,7 +147,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_RAINY, - ATTR_FORECAST_TIME: "2021-03-14T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-14T00:00:00-08:00", ATTR_FORECAST_PRECIPITATION: 1.0744, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 75, ATTR_FORECAST_TEMP: 6, @@ -155,7 +155,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_SNOWY, - ATTR_FORECAST_TIME: "2021-03-15T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-15T00:00:00-07:00", # DST starts ATTR_FORECAST_PRECIPITATION: 7.3050, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 95, ATTR_FORECAST_TEMP: 1, @@ -163,7 +163,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-16T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-16T00:00:00-07:00", ATTR_FORECAST_PRECIPITATION: 0.0051, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 5, ATTR_FORECAST_TEMP: 6, @@ -171,7 +171,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-17T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-17T00:00:00-07:00", ATTR_FORECAST_PRECIPITATION: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_TEMP: 11, @@ -179,7 +179,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-18T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-18T00:00:00-07:00", ATTR_FORECAST_PRECIPITATION: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 5, ATTR_FORECAST_TEMP: 12, @@ -187,7 +187,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-19T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-19T00:00:00-07:00", ATTR_FORECAST_PRECIPITATION: 0.1778, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 45, ATTR_FORECAST_TEMP: 9, @@ -195,7 +195,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_RAINY, - ATTR_FORECAST_TIME: "2021-03-20T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-20T00:00:00-07:00", ATTR_FORECAST_PRECIPITATION: 1.2319, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 55, ATTR_FORECAST_TEMP: 5, @@ -203,7 +203,7 @@ async def test_v3_weather( }, { ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, - ATTR_FORECAST_TIME: "2021-03-21T00:00:00+00:00", + ATTR_FORECAST_TIME: "2021-03-21T00:00:00-07:00", ATTR_FORECAST_PRECIPITATION: 0.0432, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 20, ATTR_FORECAST_TEMP: 7, diff --git a/tests/components/config/test_core.py b/tests/components/config/test_core.py index b78ed50cdf2..33309f6b6c6 100644 --- a/tests/components/config/test_core.py +++ b/tests/components/config/test_core.py @@ -10,8 +10,6 @@ from homeassistant.components.websocket_api.const import TYPE_RESULT from homeassistant.const import CONF_UNIT_SYSTEM, CONF_UNIT_SYSTEM_IMPERIAL from homeassistant.util import dt as dt_util, location -ORIG_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE - @pytest.fixture async def client(hass, hass_ws_client): diff --git a/tests/components/flux/test_switch.py b/tests/components/flux/test_switch.py index 275c10c5592..19d5c064e82 100644 --- a/tests/components/flux/test_switch.py +++ b/tests/components/flux/test_switch.py @@ -23,6 +23,12 @@ from tests.common import ( ) +@pytest.fixture(autouse=True) +def set_utc(hass): + """Set timezone to UTC.""" + hass.config.set_time_zone("UTC") + + async def test_valid_config(hass): """Test configuration.""" assert await async_setup_component( diff --git a/tests/components/forecast_solar/conftest.py b/tests/components/forecast_solar/conftest.py index 6e1adc14b7f..408c5423861 100644 --- a/tests/components/forecast_solar/conftest.py +++ b/tests/components/forecast_solar/conftest.py @@ -43,8 +43,11 @@ def mock_config_entry() -> MockConfigEntry: @pytest.fixture -def mock_forecast_solar() -> Generator[None, MagicMock, None]: - """Return a mocked Forecast.Solar client.""" +def mock_forecast_solar(hass) -> Generator[None, MagicMock, None]: + """Return a mocked Forecast.Solar client. + + hass fixture included because it sets the time zone. + """ with patch( "homeassistant.components.forecast_solar.ForecastSolar", autospec=True ) as forecast_solar_mock: diff --git a/tests/components/forecast_solar/test_sensor.py b/tests/components/forecast_solar/test_sensor.py index ee8afe5794b..a05acb5bc16 100644 --- a/tests/components/forecast_solar/test_sensor.py +++ b/tests/components/forecast_solar/test_sensor.py @@ -68,7 +68,7 @@ async def test_sensors( assert entry assert state assert entry.unique_id == f"{entry_id}_power_highest_peak_time_today" - assert state.state == "2021-06-27T13:00:00+00:00" + assert state.state == "2021-06-27T20:00:00+00:00" # Timestamp sensor is UTC assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Highest Power Peak Time - Today" assert state.attributes.get(ATTR_STATE_CLASS) is None assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.TIMESTAMP @@ -80,7 +80,7 @@ async def test_sensors( assert entry assert state assert entry.unique_id == f"{entry_id}_power_highest_peak_time_tomorrow" - assert state.state == "2021-06-27T14:00:00+00:00" + assert state.state == "2021-06-27T21:00:00+00:00" # Timestamp sensor is UTC assert ( state.attributes.get(ATTR_FRIENDLY_NAME) == "Highest Power Peak Time - Tomorrow" ) diff --git a/tests/components/google/conftest.py b/tests/components/google/conftest.py index c3b8ae4e172..102b8a1ccc6 100644 --- a/tests/components/google/conftest.py +++ b/tests/components/google/conftest.py @@ -15,13 +15,10 @@ from homeassistant.components.google import CONF_TRACK_NEW, DOMAIN from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component -import homeassistant.util.dt as dt_util from homeassistant.util.dt import utcnow from tests.common import MockConfigEntry -ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE - ApiResult = Callable[[dict[str, Any]], None] ComponentSetup = Callable[[], Awaitable[bool]] _T = TypeVar("_T") @@ -252,10 +249,7 @@ def set_time_zone(hass): """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 - hass.config.time_zone = "CST" - dt_util.set_default_time_zone(dt_util.get_time_zone("America/Regina")) - yield - dt_util.set_default_time_zone(ORIG_TIMEZONE) + hass.config.set_time_zone("America/Regina") @pytest.fixture diff --git a/tests/components/google/test_init.py b/tests/components/google/test_init.py index 6fc575ba03d..49e10d137b6 100644 --- a/tests/components/google/test_init.py +++ b/tests/components/google/test_init.py @@ -417,11 +417,11 @@ async def test_add_event_date_time( "description": "Description", "start": { "dateTime": start_datetime.isoformat(timespec="seconds"), - "timeZone": "CST", + "timeZone": "America/Regina", }, "end": { "dateTime": end_datetime.isoformat(timespec="seconds"), - "timeZone": "CST", + "timeZone": "America/Regina", }, }, ) diff --git a/tests/components/input_datetime/test_init.py b/tests/components/input_datetime/test_init.py index 0a968caf67f..28ca2ab02bd 100644 --- a/tests/components/input_datetime/test_init.py +++ b/tests/components/input_datetime/test_init.py @@ -38,8 +38,6 @@ INITIAL_DATE = "2020-01-10" INITIAL_TIME = "23:45:56" INITIAL_DATETIME = f"{INITIAL_DATE} {INITIAL_TIME}" -ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE - @pytest.fixture def storage_setup(hass, hass_storage): @@ -131,7 +129,9 @@ async def test_set_datetime(hass): entity_id = "input_datetime.test_datetime" - dt_obj = datetime.datetime(2017, 9, 7, 19, 46, 30, tzinfo=datetime.timezone.utc) + dt_obj = datetime.datetime( + 2017, 9, 7, 19, 46, 30, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) await async_set_date_and_time(hass, entity_id, dt_obj) @@ -157,7 +157,9 @@ async def test_set_datetime_2(hass): entity_id = "input_datetime.test_datetime" - dt_obj = datetime.datetime(2017, 9, 7, 19, 46, 30, tzinfo=datetime.timezone.utc) + dt_obj = datetime.datetime( + 2017, 9, 7, 19, 46, 30, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) await async_set_datetime(hass, entity_id, dt_obj) @@ -183,7 +185,9 @@ async def test_set_datetime_3(hass): entity_id = "input_datetime.test_datetime" - dt_obj = datetime.datetime(2017, 9, 7, 19, 46, 30, tzinfo=datetime.timezone.utc) + dt_obj = datetime.datetime( + 2017, 9, 7, 19, 46, 30, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) await async_set_timestamp(hass, entity_id, dt_util.as_utc(dt_obj).timestamp()) @@ -649,101 +653,97 @@ async def test_setup_no_config(hass, hass_admin_user): async def test_timestamp(hass): """Test timestamp.""" - try: - dt_util.set_default_time_zone(dt_util.get_time_zone("America/Los_Angeles")) + hass.config.set_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", - }, - } - }, - ) + 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 - # 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 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 + # 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 = 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" - # 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" - ) + # 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" + # 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 = 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 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) + # 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] + ) @pytest.mark.parametrize( diff --git a/tests/components/jewish_calendar/__init__.py b/tests/components/jewish_calendar/__init__.py index b0279fd2748..fbcd6c5325f 100644 --- a/tests/components/jewish_calendar/__init__.py +++ b/tests/components/jewish_calendar/__init__.py @@ -13,13 +13,6 @@ HDATE_DEFAULT_ALTITUDE = 754 NYC_LATLNG = _LatLng(40.7128, -74.0060) JERUSALEM_LATLNG = _LatLng(31.778, 35.235) -ORIG_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE - - -def teardown_module(): - """Reset time zone.""" - dt_util.set_default_time_zone(ORIG_TIME_ZONE) - def make_nyc_test_params(dtime, results, havdalah_offset=0): """Make test params for NYC.""" diff --git a/tests/components/jewish_calendar/test_binary_sensor.py b/tests/components/jewish_calendar/test_binary_sensor.py index b34dfdb28e4..15052243baa 100644 --- a/tests/components/jewish_calendar/test_binary_sensor.py +++ b/tests/components/jewish_calendar/test_binary_sensor.py @@ -181,7 +181,7 @@ async def test_issur_melacha_sensor( time_zone = dt_util.get_time_zone(tzname) test_time = now.replace(tzinfo=time_zone) - hass.config.time_zone = tzname + hass.config.set_time_zone(tzname) hass.config.latitude = latitude hass.config.longitude = longitude @@ -272,7 +272,7 @@ async def test_issur_melacha_sensor_update( time_zone = dt_util.get_time_zone(tzname) test_time = now.replace(tzinfo=time_zone) - hass.config.time_zone = tzname + hass.config.set_time_zone(tzname) hass.config.latitude = latitude hass.config.longitude = longitude diff --git a/tests/components/jewish_calendar/test_sensor.py b/tests/components/jewish_calendar/test_sensor.py index 879b5edb120..e2d24bcef04 100644 --- a/tests/components/jewish_calendar/test_sensor.py +++ b/tests/components/jewish_calendar/test_sensor.py @@ -165,7 +165,7 @@ async def test_jewish_calendar_sensor( time_zone = dt_util.get_time_zone(tzname) test_time = now.replace(tzinfo=time_zone) - hass.config.time_zone = tzname + hass.config.set_time_zone(tzname) hass.config.latitude = latitude hass.config.longitude = longitude @@ -510,7 +510,7 @@ async def test_shabbat_times_sensor( time_zone = dt_util.get_time_zone(tzname) test_time = now.replace(tzinfo=time_zone) - hass.config.time_zone = tzname + hass.config.set_time_zone(tzname) hass.config.latitude = latitude hass.config.longitude = longitude diff --git a/tests/components/pvpc_hourly_pricing/test_config_flow.py b/tests/components/pvpc_hourly_pricing/test_config_flow.py index ba0dc802007..4a9530768a6 100644 --- a/tests/components/pvpc_hourly_pricing/test_config_flow.py +++ b/tests/components/pvpc_hourly_pricing/test_config_flow.py @@ -12,7 +12,6 @@ from homeassistant.components.pvpc_hourly_pricing import ( ) from homeassistant.const import CONF_NAME from homeassistant.helpers import entity_registry as er -from homeassistant.util import dt as dt_util from .conftest import check_valid_state @@ -32,7 +31,7 @@ async def test_config_flow( - Check removal and add again to check state restoration - Configure options to change power and tariff to "2.0TD" """ - hass.config.time_zone = dt_util.get_time_zone("Europe/Madrid") + hass.config.set_time_zone("Europe/Madrid") tst_config = { CONF_NAME: "test", ATTR_TARIFF: TARIFFS[1], diff --git a/tests/components/pvpc_hourly_pricing/test_sensor.py b/tests/components/pvpc_hourly_pricing/test_sensor.py index 727a144e75d..bbea27477cf 100644 --- a/tests/components/pvpc_hourly_pricing/test_sensor.py +++ b/tests/components/pvpc_hourly_pricing/test_sensor.py @@ -11,7 +11,6 @@ from homeassistant.components.pvpc_hourly_pricing import ( TARIFFS, ) from homeassistant.const import CONF_NAME -from homeassistant.util import dt as dt_util from .conftest import check_valid_state @@ -29,7 +28,7 @@ async def test_multi_sensor_migration( ): """Test tariff migration when there are >1 old sensors.""" entity_reg = mock_registry(hass) - hass.config.time_zone = dt_util.get_time_zone("Europe/Madrid") + hass.config.set_time_zone("Europe/Madrid") uid_1 = "discrimination" uid_2 = "normal" old_conf_1 = {CONF_NAME: "test_pvpc_1", ATTR_TARIFF: uid_1} diff --git a/tests/components/recorder/test_statistics.py b/tests/components/recorder/test_statistics.py index c96465a671f..fe05dbc25ab 100644 --- a/tests/components/recorder/test_statistics.py +++ b/tests/components/recorder/test_statistics.py @@ -37,6 +37,8 @@ import homeassistant.util.dt as dt_util from tests.common import get_test_home_assistant, mock_registry from tests.components.recorder.common import wait_recording_done +ORIG_TZ = dt_util.DEFAULT_TIME_ZONE + def test_compile_hourly_statistics(hass_recorder): """Test compiling hourly statistics.""" @@ -841,6 +843,7 @@ def test_delete_duplicates(caplog, tmpdir): session.add(recorder.models.Statistics.from_stats(3, stat)) hass.stop() + dt_util.DEFAULT_TIME_ZONE = ORIG_TZ # Test that the duplicates are removed during migration from schema 23 hass = get_test_home_assistant() @@ -849,6 +852,7 @@ def test_delete_duplicates(caplog, tmpdir): wait_recording_done(hass) wait_recording_done(hass) hass.stop() + dt_util.DEFAULT_TIME_ZONE = ORIG_TZ assert "Deleted 2 duplicated statistics rows" in caplog.text assert "Found non identical" not in caplog.text @@ -1014,6 +1018,7 @@ def test_delete_duplicates_many(caplog, tmpdir): session.add(recorder.models.Statistics.from_stats(3, stat)) hass.stop() + dt_util.DEFAULT_TIME_ZONE = ORIG_TZ # Test that the duplicates are removed during migration from schema 23 hass = get_test_home_assistant() @@ -1022,6 +1027,7 @@ def test_delete_duplicates_many(caplog, tmpdir): wait_recording_done(hass) wait_recording_done(hass) hass.stop() + dt_util.DEFAULT_TIME_ZONE = ORIG_TZ assert "Deleted 3002 duplicated statistics rows" in caplog.text assert "Found non identical" not in caplog.text @@ -1149,6 +1155,7 @@ def test_delete_duplicates_non_identical(caplog, tmpdir): session.add(recorder.models.Statistics.from_stats(2, stat)) hass.stop() + dt_util.DEFAULT_TIME_ZONE = ORIG_TZ # Test that the duplicates are removed during migration from schema 23 hass = get_test_home_assistant() @@ -1158,6 +1165,7 @@ def test_delete_duplicates_non_identical(caplog, tmpdir): wait_recording_done(hass) wait_recording_done(hass) hass.stop() + dt_util.DEFAULT_TIME_ZONE = ORIG_TZ assert "Deleted 2 duplicated statistics rows" in caplog.text assert "Deleted 1 non identical" in caplog.text @@ -1249,6 +1257,7 @@ def test_delete_duplicates_short_term(caplog, tmpdir): ) hass.stop() + dt_util.DEFAULT_TIME_ZONE = ORIG_TZ # Test that the duplicates are removed during migration from schema 23 hass = get_test_home_assistant() @@ -1258,6 +1267,7 @@ def test_delete_duplicates_short_term(caplog, tmpdir): wait_recording_done(hass) wait_recording_done(hass) hass.stop() + dt_util.DEFAULT_TIME_ZONE = ORIG_TZ assert "duplicated statistics rows" not in caplog.text assert "Found non identical" not in caplog.text diff --git a/tests/components/risco/test_sensor.py b/tests/components/risco/test_sensor.py index 4286a7d09c9..24efbabf087 100644 --- a/tests/components/risco/test_sensor.py +++ b/tests/components/risco/test_sensor.py @@ -168,6 +168,7 @@ def _check_state(hass, category, entity_id): async def test_setup(hass, two_zone_alarm): # noqa: F811 """Test entity setup.""" + hass.config.set_time_zone("UTC") registry = er.async_get(hass) for id in ENTITY_IDS.values(): diff --git a/tests/components/sensor/test_recorder.py b/tests/components/sensor/test_recorder.py index 155060222c8..af1494b381e 100644 --- a/tests/components/sensor/test_recorder.py +++ b/tests/components/sensor/test_recorder.py @@ -2176,6 +2176,8 @@ def test_compile_statistics_hourly_daily_monthly_summary( "homeassistant.components.recorder.models.dt_util.utcnow", return_value=zero ): hass = hass_recorder() + # Remove this after dropping the use of the hass_recorder fixture + hass.config.set_time_zone("America/Regina") recorder = hass.data[DATA_INSTANCE] recorder._db_supports_row_number = db_supports_row_number setup_component(hass, "sensor", {}) diff --git a/tests/components/sonarr/test_sensor.py b/tests/components/sonarr/test_sensor.py index c499dc0112f..1b17fc2726e 100644 --- a/tests/components/sonarr/test_sensor.py +++ b/tests/components/sonarr/test_sensor.py @@ -96,10 +96,10 @@ async def test_sensors( assert state assert state.attributes.get(ATTR_ICON) == "mdi:television" assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "Episodes" - assert state.attributes.get("Bob's Burgers S04E11") == "2014-01-27T01:30:00+00:00" + assert state.attributes.get("Bob's Burgers S04E11") == "2014-01-26T17:30:00-08:00" assert ( state.attributes.get("The Andy Griffith Show S01E01") - == "1960-10-03T01:00:00+00:00" + == "1960-10-02T17:00:00-08:00" ) assert state.state == "2" diff --git a/tests/components/sun/test_trigger.py b/tests/components/sun/test_trigger.py index 55c31da6c89..3b5f3af76ec 100644 --- a/tests/components/sun/test_trigger.py +++ b/tests/components/sun/test_trigger.py @@ -20,8 +20,6 @@ import homeassistant.util.dt as dt_util from tests.common import async_fire_time_changed, async_mock_service, mock_component from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401 -ORIG_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE - @pytest.fixture def calls(hass): @@ -33,20 +31,11 @@ def calls(hass): def setup_comp(hass): """Initialize components.""" mock_component(hass, "group") - hass.config.set_time_zone(hass.config.time_zone) hass.loop.run_until_complete( async_setup_component(hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) ) -@pytest.fixture(autouse=True) -def teardown(): - """Restore.""" - yield - - dt_util.set_default_time_zone(ORIG_TIME_ZONE) - - async def test_sunset_trigger(hass, calls, legacy_patchable_time): """Test the sunset trigger.""" now = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC) diff --git a/tests/components/template/test_sensor.py b/tests/components/template/test_sensor.py index 0352080bed8..b9b1a0cd93b 100644 --- a/tests/components/template/test_sensor.py +++ b/tests/components/template/test_sensor.py @@ -1124,7 +1124,8 @@ async def test_trigger_entity_device_class_parsing_works(hass): await hass.async_block_till_done() - now = dt_util.now() + # State of timestamp sensors are always in UTC + now = dt_util.utcnow() with patch("homeassistant.util.dt.now", return_value=now): hass.bus.async_fire("test_event") @@ -1184,7 +1185,8 @@ async def test_trigger_entity_device_class_errors_works(hass): async def test_entity_device_class_parsing_works(hass): """Test entity device class parsing works.""" - now = dt_util.now() + # State of timestamp sensors are always in UTC + now = dt_util.utcnow() with patch("homeassistant.util.dt.now", return_value=now): assert await async_setup_component( diff --git a/tests/components/time_date/test_sensor.py b/tests/components/time_date/test_sensor.py index a9b5ea83c05..56f58221529 100644 --- a/tests/components/time_date/test_sensor.py +++ b/tests/components/time_date/test_sensor.py @@ -1,20 +1,9 @@ """The tests for time_date sensor platform.""" from unittest.mock import patch -import pytest - import homeassistant.components.time_date.sensor as time_date import homeassistant.util.dt as dt_util -ORIG_TZ = dt_util.DEFAULT_TIME_ZONE - - -@pytest.fixture(autouse=True) -def restore_ts(): - """Restore default TZ.""" - yield - dt_util.DEFAULT_TIME_ZONE = ORIG_TZ - # pylint: disable=protected-access async def test_intervals(hass): @@ -45,6 +34,8 @@ async def test_intervals(hass): async def test_states(hass): """Test states of sensors.""" + hass.config.set_time_zone("UTC") + now = dt_util.utc_from_timestamp(1495068856) device = time_date.TimeDateSensor(hass, "time") device._update_internal_state(now) @@ -79,9 +70,7 @@ async def test_states(hass): async def test_states_non_default_timezone(hass): """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) + hass.config.set_time_zone("America/New_York") now = dt_util.utc_from_timestamp(1495068856) device = time_date.TimeDateSensor(hass, "time") @@ -116,9 +105,7 @@ async def test_states_non_default_timezone(hass): # pylint: disable=no-member 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) + hass.config.set_time_zone("America/New_York") device = time_date.TimeDateSensor(hass, "date") now = dt_util.utc_from_timestamp(50000) @@ -128,9 +115,7 @@ async def test_timezone_intervals(hass): # 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) + hass.config.set_time_zone("America/Edmonton") 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): @@ -138,9 +123,7 @@ async def test_timezone_intervals(hass): 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) + hass.config.set_time_zone("Europe/Prague") now = dt_util.parse_datetime("2020-03-29 00:00+01:00") with patch("homeassistant.util.dt.utcnow", return_value=now): @@ -168,11 +151,9 @@ async def test_timezone_intervals(hass): "homeassistant.util.dt.utcnow", return_value=dt_util.parse_datetime("2017-11-14 02:47:19-00:00"), ) -async def test_timezone_intervals_empty_parameter(hass): +async def test_timezone_intervals_empty_parameter(utcnow_mock, hass): """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) + hass.config.set_time_zone("America/Edmonton") device = time_date.TimeDateSensor(hass, "date") next_time = device.get_next_interval() assert next_time.timestamp() == dt_util.as_timestamp("2017-11-14 00:00:00-07:00") diff --git a/tests/components/tod/test_binary_sensor.py b/tests/components/tod/test_binary_sensor.py index 06f29436d6e..ecdabdb910d 100644 --- a/tests/components/tod/test_binary_sensor.py +++ b/tests/components/tod/test_binary_sensor.py @@ -12,8 +12,6 @@ import homeassistant.util.dt as dt_util from tests.common import assert_setup_component -ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE - @pytest.fixture(autouse=True) def mock_legacy_time(legacy_patchable_time): @@ -28,13 +26,6 @@ def setup_fixture(hass): hass.config.longitude = 18.98583 -@pytest.fixture(autouse=True) -def restore_timezone(hass): - """Make sure we change timezone.""" - yield - dt_util.set_default_time_zone(ORIG_TIMEZONE) - - async def test_setup(hass): """Test the setup.""" config = { @@ -69,7 +60,9 @@ async def test_setup_no_sensors(hass): async def test_in_period_on_start(hass): """Test simple setting.""" - test_time = datetime(2019, 1, 10, 18, 43, 0, tzinfo=dt_util.UTC) + test_time = datetime( + 2019, 1, 10, 18, 43, 0, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) config = { "binary_sensor": [ { @@ -93,7 +86,9 @@ async def test_in_period_on_start(hass): async def test_midnight_turnover_before_midnight_inside_period(hass): """Test midnight turnover setting before midnight inside period .""" - test_time = datetime(2019, 1, 10, 22, 30, 0, tzinfo=dt_util.UTC) + test_time = datetime( + 2019, 1, 10, 22, 30, 0, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) config = { "binary_sensor": [ {"platform": "tod", "name": "Night", "after": "22:00", "before": "5:00"} @@ -112,7 +107,9 @@ async def test_midnight_turnover_before_midnight_inside_period(hass): async def test_midnight_turnover_after_midnight_inside_period(hass): """Test midnight turnover setting before midnight inside period .""" - test_time = datetime(2019, 1, 10, 21, 0, 0, tzinfo=dt_util.UTC) + test_time = datetime( + 2019, 1, 10, 21, 0, 0, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) config = { "binary_sensor": [ {"platform": "tod", "name": "Night", "after": "22:00", "before": "5:00"} @@ -184,7 +181,9 @@ async def test_after_happens_tomorrow(hass): async def test_midnight_turnover_after_midnight_outside_period(hass): """Test midnight turnover setting before midnight inside period .""" - test_time = datetime(2019, 1, 10, 20, 0, 0, tzinfo=dt_util.UTC) + test_time = datetime( + 2019, 1, 10, 20, 0, 0, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) config = { "binary_sensor": [ @@ -201,7 +200,9 @@ async def test_midnight_turnover_after_midnight_outside_period(hass): state = hass.states.get("binary_sensor.night") assert state.state == STATE_OFF - switchover_time = datetime(2019, 1, 11, 4, 59, 0, tzinfo=dt_util.UTC) + switchover_time = datetime( + 2019, 1, 11, 4, 59, 0, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=switchover_time, @@ -420,13 +421,13 @@ async def test_from_sunset_to_sunrise(hass): async def test_offset(hass): """Test offset.""" - after = datetime(2019, 1, 10, 18, 0, 0, tzinfo=dt_util.UTC) + timedelta( - hours=1, minutes=34 - ) + after = datetime( + 2019, 1, 10, 18, 0, 0, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) + timedelta(hours=1, minutes=34) - before = datetime(2019, 1, 10, 22, 0, 0, tzinfo=dt_util.UTC) + timedelta( - hours=1, minutes=45 - ) + before = datetime( + 2019, 1, 10, 22, 0, 0, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) + timedelta(hours=1, minutes=45) entity_id = "binary_sensor.evening" config = { @@ -499,9 +500,9 @@ async def test_offset(hass): async def test_offset_overnight(hass): """Test offset overnight.""" - after = datetime(2019, 1, 10, 18, 0, 0, tzinfo=dt_util.UTC) + timedelta( - hours=1, minutes=34 - ) + after = datetime( + 2019, 1, 10, 18, 0, 0, tzinfo=dt_util.get_time_zone(hass.config.time_zone) + ) + timedelta(hours=1, minutes=34) entity_id = "binary_sensor.evening" config = { "binary_sensor": [ @@ -890,8 +891,7 @@ async def test_sun_offset(hass): async def test_dst(hass): """Test sun event with offset.""" - hass.config.time_zone = "CET" - dt_util.set_default_time_zone(dt_util.get_time_zone("CET")) + hass.config.set_time_zone("CET") test_time = datetime(2019, 3, 30, 3, 0, 0, tzinfo=dt_util.UTC) config = { "binary_sensor": [ @@ -919,8 +919,7 @@ async def test_dst(hass): async def test_simple_before_after_does_not_loop_utc_not_in_range(hass): """Test simple before after.""" - hass.config.time_zone = "UTC" - dt_util.set_default_time_zone(dt_util.UTC) + hass.config.set_time_zone("UTC") test_time = datetime(2019, 1, 10, 18, 43, 0, tzinfo=dt_util.UTC) config = { "binary_sensor": [ @@ -948,8 +947,7 @@ async def test_simple_before_after_does_not_loop_utc_not_in_range(hass): async def test_simple_before_after_does_not_loop_utc_in_range(hass): """Test simple before after.""" - hass.config.time_zone = "UTC" - dt_util.set_default_time_zone(dt_util.UTC) + hass.config.set_time_zone("UTC") test_time = datetime(2019, 1, 10, 22, 43, 0, tzinfo=dt_util.UTC) config = { "binary_sensor": [ @@ -977,8 +975,7 @@ async def test_simple_before_after_does_not_loop_utc_in_range(hass): async def test_simple_before_after_does_not_loop_utc_fire_at_before(hass): """Test simple before after.""" - hass.config.time_zone = "UTC" - dt_util.set_default_time_zone(dt_util.UTC) + hass.config.set_time_zone("UTC") test_time = datetime(2019, 1, 11, 6, 0, 0, tzinfo=dt_util.UTC) config = { "binary_sensor": [ @@ -1006,8 +1003,7 @@ async def test_simple_before_after_does_not_loop_utc_fire_at_before(hass): async def test_simple_before_after_does_not_loop_utc_fire_at_after(hass): """Test simple before after.""" - hass.config.time_zone = "UTC" - dt_util.set_default_time_zone(dt_util.UTC) + hass.config.set_time_zone("UTC") test_time = datetime(2019, 1, 10, 22, 0, 0, tzinfo=dt_util.UTC) config = { "binary_sensor": [ @@ -1035,8 +1031,7 @@ async def test_simple_before_after_does_not_loop_utc_fire_at_after(hass): async def test_simple_before_after_does_not_loop_utc_both_before_now(hass): """Test simple before after.""" - hass.config.time_zone = "UTC" - dt_util.set_default_time_zone(dt_util.UTC) + hass.config.set_time_zone("UTC") test_time = datetime(2019, 1, 10, 22, 0, 0, tzinfo=dt_util.UTC) config = { "binary_sensor": [ @@ -1064,8 +1059,7 @@ async def test_simple_before_after_does_not_loop_utc_both_before_now(hass): async def test_simple_before_after_does_not_loop_berlin_not_in_range(hass): """Test simple before after.""" - hass.config.time_zone = "Europe/Berlin" - dt_util.set_default_time_zone(dt_util.get_time_zone("Europe/Berlin")) + hass.config.set_time_zone("Europe/Berlin") test_time = datetime(2019, 1, 10, 18, 43, 0, tzinfo=dt_util.UTC) config = { "binary_sensor": [ @@ -1093,8 +1087,7 @@ async def test_simple_before_after_does_not_loop_berlin_not_in_range(hass): async def test_simple_before_after_does_not_loop_berlin_in_range(hass): """Test simple before after.""" - hass.config.time_zone = "Europe/Berlin" - dt_util.set_default_time_zone(dt_util.get_time_zone("Europe/Berlin")) + hass.config.set_time_zone("Europe/Berlin") test_time = datetime(2019, 1, 10, 23, 43, 0, tzinfo=dt_util.UTC) config = { "binary_sensor": [ diff --git a/tests/components/vallox/test_sensor.py b/tests/components/vallox/test_sensor.py index bd8ecbea905..7649799f56b 100644 --- a/tests/components/vallox/test_sensor.py +++ b/tests/components/vallox/test_sensor.py @@ -12,44 +12,29 @@ from .conftest import patch_metrics from tests.common import MockConfigEntry -ORIG_TZ = dt.DEFAULT_TIME_ZONE - - -@pytest.fixture(autouse=True) -def reset_tz(): - """Restore the default TZ after test runs.""" - yield - dt.DEFAULT_TIME_ZONE = ORIG_TZ - @pytest.fixture def set_tz(request): """Set the default TZ to the one requested.""" - return request.getfixturevalue(request.param) + request.getfixturevalue(request.param) @pytest.fixture -def utc() -> tzinfo: +def utc(hass: HomeAssistant) -> None: """Set the default TZ to UTC.""" - tz = dt.get_time_zone("UTC") - dt.set_default_time_zone(tz) - return tz + hass.config.set_time_zone("UTC") @pytest.fixture -def helsinki() -> tzinfo: +def helsinki(hass: HomeAssistant) -> None: """Set the default TZ to Europe/Helsinki.""" - tz = dt.get_time_zone("Europe/Helsinki") - dt.set_default_time_zone(tz) - return tz + hass.config.set_time_zone("Europe/Helsinki") @pytest.fixture -def new_york() -> tzinfo: +def new_york(hass: HomeAssistant) -> None: """Set the default TZ to America/New_York.""" - tz = dt.get_time_zone("America/New_York") - dt.set_default_time_zone(tz) - return tz + hass.config.set_time_zone("America/New_York") def _sensor_to_datetime(sensor): diff --git a/tests/components/zodiac/test_sensor.py b/tests/components/zodiac/test_sensor.py index 6c784d3998f..90b19e73b04 100644 --- a/tests/components/zodiac/test_sensor.py +++ b/tests/components/zodiac/test_sensor.py @@ -35,6 +35,7 @@ DAY3 = datetime(2020, 4, 21, tzinfo=dt_util.UTC) ) async def test_zodiac_day(hass, now, sign, element, modality): """Test the zodiac sensor.""" + hass.config.set_time_zone("UTC") config = {DOMAIN: {}} with patch("homeassistant.components.zodiac.sensor.utcnow", return_value=now): diff --git a/tests/conftest.py b/tests/conftest.py index 902fc55eac4..a7dcef31591 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -29,7 +29,7 @@ from homeassistant.components.websocket_api.http import URL from homeassistant.const import ATTR_NOW, EVENT_TIME_CHANGED, HASSIO_USER_NAME from homeassistant.helpers import config_entry_oauth2_flow, event from homeassistant.setup import async_setup_component -from homeassistant.util import location +from homeassistant.util import dt as dt_util, location from tests.ignore_uncaught_exceptions import IGNORE_UNCAUGHT_EXCEPTIONS @@ -249,6 +249,8 @@ def load_registries(): def hass(loop, load_registries, hass_storage, request): """Fixture to provide a test instance of Home Assistant.""" + orig_tz = dt_util.DEFAULT_TIME_ZONE + def exc_handle(loop, context): """Handle exceptions by rethrowing them, which will fail the test.""" # Most of these contexts will contain an exception, but not all. @@ -273,6 +275,10 @@ def hass(loop, load_registries, hass_storage, request): yield hass loop.run_until_complete(hass.async_stop(force=True)) + + # Restore timezone, it is set when creating the hass object + dt_util.DEFAULT_TIME_ZONE = orig_tz + for ex in exceptions: if ( request.module.__name__, diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index ffbc2130f3b..2b5c35f06ad 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -28,8 +28,6 @@ import homeassistant.util.dt as dt_util from tests.common import async_mock_service -ORIG_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE - @pytest.fixture def calls(hass): @@ -46,14 +44,6 @@ def setup_comp(hass): ) -@pytest.fixture(autouse=True) -def teardown(): - """Restore.""" - yield - - dt_util.set_default_time_zone(ORIG_TIME_ZONE) - - def assert_element(trace_element, expected_element, path): """Assert a trace element is as expected. @@ -2659,8 +2649,7 @@ async def test_if_action_before_sunrise_no_offset_kotzebue(hass, hass_ws_client, at 7 AM and sunset at 3AM during summer After sunrise is true from sunrise until midnight, local time. """ - tz = dt_util.get_time_zone("America/Anchorage") - dt_util.set_default_time_zone(tz) + hass.config.set_time_zone("America/Anchorage") hass.config.latitude = 66.5 hass.config.longitude = 162.4 await async_setup_component( @@ -2736,8 +2725,7 @@ async def test_if_action_after_sunrise_no_offset_kotzebue(hass, hass_ws_client, at 7 AM and sunset at 3AM during summer Before sunrise is true from midnight until sunrise, local time. """ - tz = dt_util.get_time_zone("America/Anchorage") - dt_util.set_default_time_zone(tz) + hass.config.set_time_zone("America/Anchorage") hass.config.latitude = 66.5 hass.config.longitude = 162.4 await async_setup_component( @@ -2813,8 +2801,7 @@ async def test_if_action_before_sunset_no_offset_kotzebue(hass, hass_ws_client, at 7 AM and sunset at 3AM during summer Before sunset is true from midnight until sunset, local time. """ - tz = dt_util.get_time_zone("America/Anchorage") - dt_util.set_default_time_zone(tz) + hass.config.set_time_zone("America/Anchorage") hass.config.latitude = 66.5 hass.config.longitude = 162.4 await async_setup_component( @@ -2890,8 +2877,7 @@ async def test_if_action_after_sunset_no_offset_kotzebue(hass, hass_ws_client, c 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.set_time_zone("America/Anchorage") hass.config.latitude = 66.5 hass.config.longitude = 162.4 await async_setup_component( diff --git a/tests/helpers/test_event.py b/tests/helpers/test_event.py index bd17aec92e6..67fc679bb8b 100644 --- a/tests/helpers/test_event.py +++ b/tests/helpers/test_event.py @@ -46,14 +46,6 @@ from tests.common import async_fire_time_changed DEFAULT_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE -@pytest.fixture(autouse=True) -def teardown(): - """Stop everything that was started.""" - yield - - dt_util.set_default_time_zone(DEFAULT_TIME_ZONE) - - async def test_track_point_in_time(hass): """Test track point in time.""" before_birthday = datetime(1985, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC) @@ -3751,8 +3743,7 @@ async def test_periodic_task_duplicate_time(hass): @pytest.mark.freeze_time("2021-03-28 01:28:00+01:00") async def test_periodic_task_entering_dst(hass, freezer): """Test periodic task behavior when entering dst.""" - timezone = dt_util.get_time_zone("Europe/Vienna") - dt_util.set_default_time_zone(timezone) + hass.config.set_time_zone("Europe/Vienna") specific_runs = [] today = date.today().isoformat() @@ -3801,8 +3792,7 @@ async def test_periodic_task_entering_dst_2(hass, freezer): This tests a task firing every second in the range 0..58 (not *:*:59) """ - timezone = dt_util.get_time_zone("Europe/Vienna") - dt_util.set_default_time_zone(timezone) + hass.config.set_time_zone("Europe/Vienna") specific_runs = [] today = date.today().isoformat() @@ -3850,8 +3840,7 @@ async def test_periodic_task_entering_dst_2(hass, freezer): @pytest.mark.freeze_time("2021-10-31 02:28:00+02:00") async def test_periodic_task_leaving_dst(hass, freezer): """Test periodic task behavior when leaving dst.""" - timezone = dt_util.get_time_zone("Europe/Vienna") - dt_util.set_default_time_zone(timezone) + hass.config.set_time_zone("Europe/Vienna") specific_runs = [] today = date.today().isoformat() @@ -3925,8 +3914,7 @@ async def test_periodic_task_leaving_dst(hass, freezer): @pytest.mark.freeze_time("2021-10-31 02:28:00+02:00") async def test_periodic_task_leaving_dst_2(hass, freezer): """Test periodic task behavior when leaving dst.""" - timezone = dt_util.get_time_zone("Europe/Vienna") - dt_util.set_default_time_zone(timezone) + hass.config.set_time_zone("Europe/Vienna") specific_runs = [] today = date.today().isoformat() @@ -4188,8 +4176,8 @@ async def test_async_track_point_in_time_cancel(hass): """Test cancel of async track point in time.""" times = [] + hass.config.set_time_zone("US/Hawaii") hst_tz = dt_util.get_time_zone("US/Hawaii") - dt_util.set_default_time_zone(hst_tz) @ha.callback def run_callback(local_time): diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index d70837bd088..bbb5e11be7f 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -674,6 +674,7 @@ def test_strptime(hass): def test_timestamp_custom(hass): """Test the timestamps to custom filter.""" + hass.config.set_time_zone("UTC") now = dt_util.utcnow() tests = [ (None, None, None, None), @@ -700,6 +701,7 @@ def test_timestamp_custom(hass): def test_timestamp_local(hass): """Test the timestamps to local filter.""" + hass.config.set_time_zone("UTC") tests = {None: None, 1469119144: "2016-07-21T16:39:04+00:00"} for inp, out in tests.items(): @@ -1290,10 +1292,7 @@ def test_today_at(mock_is_safe, hass, now, expected, expected_midnight, timezone freezer = freeze_time(now) freezer.start() - original_tz = dt_util.DEFAULT_TIME_ZONE - - timezone = dt_util.get_time_zone(timezone_str) - dt_util.set_default_time_zone(timezone) + hass.config.set_time_zone(timezone_str) result = template.Template( "{{ today_at('10:00').isoformat() }}", @@ -1323,7 +1322,6 @@ def test_today_at(mock_is_safe, hass, now, expected, expected_midnight, timezone template.Template("{{ today_at('bad') }}", hass).async_render() freezer.stop() - dt_util.set_default_time_zone(original_tz) @patch( @@ -1332,6 +1330,7 @@ def test_today_at(mock_is_safe, hass, now, expected, expected_midnight, timezone ) def test_relative_time(mock_is_safe, hass): """Test relative_time method.""" + hass.config.set_time_zone("UTC") now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") with patch("homeassistant.util.dt.now", return_value=now): result = template.Template( diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py index 87d93c1a1ac..c6c507a0f73 100644 --- a/tests/test_bootstrap.py +++ b/tests/test_bootstrap.py @@ -12,7 +12,6 @@ import homeassistant.config as config_util from homeassistant.const import SIGNAL_BOOTSTRAP_INTEGRATONS from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.dispatcher import async_dispatcher_connect -import homeassistant.util.dt as dt_util from tests.common import ( MockModule, @@ -23,7 +22,6 @@ from tests.common import ( mock_integration, ) -ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) diff --git a/tests/test_config.py b/tests/test_config.py index 4e761bc3f47..552139fa0ef 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -32,7 +32,6 @@ from homeassistant.helpers import config_validation as cv import homeassistant.helpers.check_config as check_config from homeassistant.helpers.entity import Entity from homeassistant.loader import async_get_integration -from homeassistant.util import dt as dt_util from homeassistant.util.yaml import SECRET_YAML from tests.common import get_test_config_dir, patch_yaml_files @@ -44,7 +43,6 @@ VERSION_PATH = os.path.join(CONFIG_DIR, config_util.VERSION_FILE) AUTOMATIONS_PATH = os.path.join(CONFIG_DIR, config_util.AUTOMATION_CONFIG_PATH) SCRIPTS_PATH = os.path.join(CONFIG_DIR, config_util.SCRIPT_CONFIG_PATH) SCENES_PATH = os.path.join(CONFIG_DIR, config_util.SCENE_CONFIG_PATH) -ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE def create_file(path): @@ -58,8 +56,6 @@ def teardown(): """Clean up.""" yield - dt_util.DEFAULT_TIME_ZONE = ORIG_TIMEZONE - if os.path.isfile(YAML_PATH): os.remove(YAML_PATH)