Simplify time zone setting in tests (#68330)

* Simplify timezone setting in tests

* Fix typo

* Adjust caldav tests

* Adjust input_datetime tests

* Adjust time_date tests

* Adjust tod tests

* Adjust helper tests

* Adjust recorder tests

* Adjust risco tests

* Adjust aemet tests

* Adjust flux tests

* Adjust forecast_solar tests

* Revert unnecessary change in forecast_solar test

* Adjust climacell tests

* Adjust google tests

* Adjust sensor tests

* Adjust sonarr tests

* Adjust template tests

* Adjust zodiac tests

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Erik Montnemery 2022-03-20 10:25:15 +01:00 committed by GitHub
parent dbeec1f7da
commit cf4033b1bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 256 additions and 320 deletions

View File

@ -282,7 +282,7 @@ async def async_test_home_assistant(loop, load_registries=True):
hass.config.latitude = 32.87336 hass.config.latitude = 32.87336
hass.config.longitude = -117.22743 hass.config.longitude = -117.22743
hass.config.elevation = 0 hass.config.elevation = 0
hass.config.time_zone = "US/Pacific" hass.config.set_time_zone("US/Pacific")
hass.config.units = METRIC_SYSTEM hass.config.units = METRIC_SYSTEM
hass.config.media_dirs = {"local": get_test_config_dir("media")} hass.config.media_dirs = {"local": get_test_config_dir("media")}
hass.config.skip_pip = True hass.config.skip_pip = True

View File

@ -15,6 +15,7 @@ from .util import async_init_integration
async def test_aemet_forecast_create_sensors(hass): async def test_aemet_forecast_create_sensors(hass):
"""Test creation of forecast sensors.""" """Test creation of forecast sensors."""
hass.config.set_time_zone("UTC")
now = dt_util.parse_datetime("2021-01-09 12:00:00+00:00") now = dt_util.parse_datetime("2021-01-09 12:00:00+00:00")
with patch("homeassistant.util.dt.now", return_value=now), patch( with patch("homeassistant.util.dt.now", return_value=now), patch(
"homeassistant.util.dt.utcnow", return_value=now "homeassistant.util.dt.utcnow", return_value=now

View File

@ -30,6 +30,7 @@ from .util import async_init_integration
async def test_aemet_weather(hass): async def test_aemet_weather(hass):
"""Test states of the weather.""" """Test states of the weather."""
hass.config.set_time_zone("UTC")
now = dt_util.parse_datetime("2021-01-09 12:00:00+00:00") now = dt_util.parse_datetime("2021-01-09 12:00:00+00:00")
with patch("homeassistant.util.dt.now", return_value=now), patch( with patch("homeassistant.util.dt.now", return_value=now), patch(
"homeassistant.util.dt.utcnow", return_value=now "homeassistant.util.dt.utcnow", return_value=now

View File

@ -222,15 +222,6 @@ CALDAV_CONFIG = {
"custom_calendars": [], "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 @pytest.fixture
def set_tz(request): def set_tz(request):
@ -239,21 +230,21 @@ def set_tz(request):
@pytest.fixture @pytest.fixture
def utc(): def utc(hass):
"""Set the default TZ to UTC.""" """Set the default TZ to UTC."""
dt.set_default_time_zone(dt.get_time_zone("UTC")) hass.config.set_time_zone("UTC")
@pytest.fixture @pytest.fixture
def new_york(): def new_york(hass):
"""Set the default TZ to America/New_York.""" """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 @pytest.fixture
def baghdad(): def baghdad(hass):
"""Set the default TZ to Asia/Baghdad.""" """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) @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" assert state.name == "HomeOffice"
@pytest.mark.parametrize("set_tz", ["utc"], indirect=True)
@patch("homeassistant.util.dt.now", return_value=_local_datetime(17, 45)) @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.""" """Test that the ongoing event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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)) @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.""" """Test that the next ongoing event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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)) @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.""" """Test that the ongoing event with another timezone is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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)) @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.""" """Test that floating events without timezones work."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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)) @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.""" """Test that the offset is taken into account."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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)) @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.""" """Test that the matching event is returned."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ 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)) @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.""" """Test that the event matching the regexp is returned."""
config = dict(CALDAV_CONFIG) config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [ 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)) @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.""" """Test that the future recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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)) @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.""" """Test that the current recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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)) @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.""" """Test that the future recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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)) @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.""" """Test that the ongoing recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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)) @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.""" """Test that the endless recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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( @patch(
"homeassistant.util.dt.now", "homeassistant.util.dt.now",
return_value=dt.as_local(datetime.datetime(2015, 11, 27, 0, 15)), 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.""" """Test that the endless recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() 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( @patch(
"homeassistant.util.dt.now", "homeassistant.util.dt.now",
return_value=dt.as_local(datetime.datetime(2015, 11, 27, 11, 15)), 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.""" """Test that the endless recurring event is returned."""
assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG}) assert await async_setup_component(hass, "calendar", {"calendar": CALDAV_CONFIG})
await hass.async_block_till_done() await hass.async_block_till_done()

View File

@ -91,7 +91,7 @@ async def test_v3_weather(
assert weather_state.attributes[ATTR_FORECAST] == [ assert weather_state.attributes[ATTR_FORECAST] == [
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_SUNNY, 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: 0,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0,
ATTR_FORECAST_TEMP: 7, ATTR_FORECAST_TEMP: 7,
@ -99,7 +99,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0,
ATTR_FORECAST_TEMP: 10, ATTR_FORECAST_TEMP: 10,
@ -107,7 +107,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0,
ATTR_FORECAST_TEMP: 19, ATTR_FORECAST_TEMP: 19,
@ -115,7 +115,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0,
ATTR_FORECAST_TEMP: 18, ATTR_FORECAST_TEMP: 18,
@ -123,7 +123,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 5, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 5,
ATTR_FORECAST_TEMP: 20, ATTR_FORECAST_TEMP: 20,
@ -131,7 +131,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0.0457,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 25, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 25,
ATTR_FORECAST_TEMP: 20, ATTR_FORECAST_TEMP: 20,
@ -139,7 +139,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 25, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 25,
ATTR_FORECAST_TEMP: 16, ATTR_FORECAST_TEMP: 16,
@ -147,7 +147,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_RAINY, 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: 1.0744,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 75, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 75,
ATTR_FORECAST_TEMP: 6, ATTR_FORECAST_TEMP: 6,
@ -155,7 +155,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_SNOWY, 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: 7.3050,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 95, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 95,
ATTR_FORECAST_TEMP: 1, ATTR_FORECAST_TEMP: 1,
@ -163,7 +163,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0.0051,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 5, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 5,
ATTR_FORECAST_TEMP: 6, ATTR_FORECAST_TEMP: 6,
@ -171,7 +171,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 0,
ATTR_FORECAST_TEMP: 11, ATTR_FORECAST_TEMP: 11,
@ -179,7 +179,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 5, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 5,
ATTR_FORECAST_TEMP: 12, ATTR_FORECAST_TEMP: 12,
@ -187,7 +187,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0.1778,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 45, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 45,
ATTR_FORECAST_TEMP: 9, ATTR_FORECAST_TEMP: 9,
@ -195,7 +195,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_RAINY, 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: 1.2319,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 55, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 55,
ATTR_FORECAST_TEMP: 5, ATTR_FORECAST_TEMP: 5,
@ -203,7 +203,7 @@ async def test_v3_weather(
}, },
{ {
ATTR_FORECAST_CONDITION: ATTR_CONDITION_CLOUDY, 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: 0.0432,
ATTR_FORECAST_PRECIPITATION_PROBABILITY: 20, ATTR_FORECAST_PRECIPITATION_PROBABILITY: 20,
ATTR_FORECAST_TEMP: 7, ATTR_FORECAST_TEMP: 7,

View File

@ -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.const import CONF_UNIT_SYSTEM, CONF_UNIT_SYSTEM_IMPERIAL
from homeassistant.util import dt as dt_util, location from homeassistant.util import dt as dt_util, location
ORIG_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE
@pytest.fixture @pytest.fixture
async def client(hass, hass_ws_client): async def client(hass, hass_ws_client):

View File

@ -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): async def test_valid_config(hass):
"""Test configuration.""" """Test configuration."""
assert await async_setup_component( assert await async_setup_component(

View File

@ -43,8 +43,11 @@ def mock_config_entry() -> MockConfigEntry:
@pytest.fixture @pytest.fixture
def mock_forecast_solar() -> Generator[None, MagicMock, None]: def mock_forecast_solar(hass) -> Generator[None, MagicMock, None]:
"""Return a mocked Forecast.Solar client.""" """Return a mocked Forecast.Solar client.
hass fixture included because it sets the time zone.
"""
with patch( with patch(
"homeassistant.components.forecast_solar.ForecastSolar", autospec=True "homeassistant.components.forecast_solar.ForecastSolar", autospec=True
) as forecast_solar_mock: ) as forecast_solar_mock:

View File

@ -68,7 +68,7 @@ async def test_sensors(
assert entry assert entry
assert state assert state
assert entry.unique_id == f"{entry_id}_power_highest_peak_time_today" 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_FRIENDLY_NAME) == "Highest Power Peak Time - Today"
assert state.attributes.get(ATTR_STATE_CLASS) is None assert state.attributes.get(ATTR_STATE_CLASS) is None
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.TIMESTAMP assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.TIMESTAMP
@ -80,7 +80,7 @@ async def test_sensors(
assert entry assert entry
assert state assert state
assert entry.unique_id == f"{entry_id}_power_highest_peak_time_tomorrow" 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 ( assert (
state.attributes.get(ATTR_FRIENDLY_NAME) == "Highest Power Peak Time - Tomorrow" state.attributes.get(ATTR_FRIENDLY_NAME) == "Highest Power Peak Time - Tomorrow"
) )

View File

@ -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.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE
ApiResult = Callable[[dict[str, Any]], None] ApiResult = Callable[[dict[str, Any]], None]
ComponentSetup = Callable[[], Awaitable[bool]] ComponentSetup = Callable[[], Awaitable[bool]]
_T = TypeVar("_T") _T = TypeVar("_T")
@ -252,10 +249,7 @@ def set_time_zone(hass):
"""Set the time zone for the tests.""" """Set the time zone for the tests."""
# Set our timezone to CST/Regina so we can check calculations # Set our timezone to CST/Regina so we can check calculations
# This keeps UTC-6 all year round # This keeps UTC-6 all year round
hass.config.time_zone = "CST" hass.config.set_time_zone("America/Regina")
dt_util.set_default_time_zone(dt_util.get_time_zone("America/Regina"))
yield
dt_util.set_default_time_zone(ORIG_TIMEZONE)
@pytest.fixture @pytest.fixture

View File

@ -417,11 +417,11 @@ async def test_add_event_date_time(
"description": "Description", "description": "Description",
"start": { "start": {
"dateTime": start_datetime.isoformat(timespec="seconds"), "dateTime": start_datetime.isoformat(timespec="seconds"),
"timeZone": "CST", "timeZone": "America/Regina",
}, },
"end": { "end": {
"dateTime": end_datetime.isoformat(timespec="seconds"), "dateTime": end_datetime.isoformat(timespec="seconds"),
"timeZone": "CST", "timeZone": "America/Regina",
}, },
}, },
) )

View File

@ -38,8 +38,6 @@ INITIAL_DATE = "2020-01-10"
INITIAL_TIME = "23:45:56" INITIAL_TIME = "23:45:56"
INITIAL_DATETIME = f"{INITIAL_DATE} {INITIAL_TIME}" INITIAL_DATETIME = f"{INITIAL_DATE} {INITIAL_TIME}"
ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE
@pytest.fixture @pytest.fixture
def storage_setup(hass, hass_storage): def storage_setup(hass, hass_storage):
@ -131,7 +129,9 @@ async def test_set_datetime(hass):
entity_id = "input_datetime.test_datetime" 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) 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" 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) 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" 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()) await async_set_timestamp(hass, entity_id, dt_util.as_utc(dt_obj).timestamp())
@ -649,8 +653,7 @@ async def test_setup_no_config(hass, hass_admin_user):
async def test_timestamp(hass): async def test_timestamp(hass):
"""Test timestamp.""" """Test timestamp."""
try: hass.config.set_time_zone("America/Los_Angeles")
dt_util.set_default_time_zone(dt_util.get_time_zone("America/Los_Angeles"))
assert await async_setup_component( assert await async_setup_component(
hass, hass,
@ -742,9 +745,6 @@ async def test_timestamp(hass):
== state_without_tz.attributes[ATTR_TIMESTAMP] == state_without_tz.attributes[ATTR_TIMESTAMP]
) )
finally:
dt_util.set_default_time_zone(ORIG_TIMEZONE)
@pytest.mark.parametrize( @pytest.mark.parametrize(
"config, error", "config, error",

View File

@ -13,13 +13,6 @@ HDATE_DEFAULT_ALTITUDE = 754
NYC_LATLNG = _LatLng(40.7128, -74.0060) NYC_LATLNG = _LatLng(40.7128, -74.0060)
JERUSALEM_LATLNG = _LatLng(31.778, 35.235) 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): def make_nyc_test_params(dtime, results, havdalah_offset=0):
"""Make test params for NYC.""" """Make test params for NYC."""

View File

@ -181,7 +181,7 @@ async def test_issur_melacha_sensor(
time_zone = dt_util.get_time_zone(tzname) time_zone = dt_util.get_time_zone(tzname)
test_time = now.replace(tzinfo=time_zone) test_time = now.replace(tzinfo=time_zone)
hass.config.time_zone = tzname hass.config.set_time_zone(tzname)
hass.config.latitude = latitude hass.config.latitude = latitude
hass.config.longitude = longitude hass.config.longitude = longitude
@ -272,7 +272,7 @@ async def test_issur_melacha_sensor_update(
time_zone = dt_util.get_time_zone(tzname) time_zone = dt_util.get_time_zone(tzname)
test_time = now.replace(tzinfo=time_zone) test_time = now.replace(tzinfo=time_zone)
hass.config.time_zone = tzname hass.config.set_time_zone(tzname)
hass.config.latitude = latitude hass.config.latitude = latitude
hass.config.longitude = longitude hass.config.longitude = longitude

View File

@ -165,7 +165,7 @@ async def test_jewish_calendar_sensor(
time_zone = dt_util.get_time_zone(tzname) time_zone = dt_util.get_time_zone(tzname)
test_time = now.replace(tzinfo=time_zone) test_time = now.replace(tzinfo=time_zone)
hass.config.time_zone = tzname hass.config.set_time_zone(tzname)
hass.config.latitude = latitude hass.config.latitude = latitude
hass.config.longitude = longitude hass.config.longitude = longitude
@ -510,7 +510,7 @@ async def test_shabbat_times_sensor(
time_zone = dt_util.get_time_zone(tzname) time_zone = dt_util.get_time_zone(tzname)
test_time = now.replace(tzinfo=time_zone) test_time = now.replace(tzinfo=time_zone)
hass.config.time_zone = tzname hass.config.set_time_zone(tzname)
hass.config.latitude = latitude hass.config.latitude = latitude
hass.config.longitude = longitude hass.config.longitude = longitude

View File

@ -12,7 +12,6 @@ from homeassistant.components.pvpc_hourly_pricing import (
) )
from homeassistant.const import CONF_NAME from homeassistant.const import CONF_NAME
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from .conftest import check_valid_state from .conftest import check_valid_state
@ -32,7 +31,7 @@ async def test_config_flow(
- Check removal and add again to check state restoration - Check removal and add again to check state restoration
- Configure options to change power and tariff to "2.0TD" - 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 = { tst_config = {
CONF_NAME: "test", CONF_NAME: "test",
ATTR_TARIFF: TARIFFS[1], ATTR_TARIFF: TARIFFS[1],

View File

@ -11,7 +11,6 @@ from homeassistant.components.pvpc_hourly_pricing import (
TARIFFS, TARIFFS,
) )
from homeassistant.const import CONF_NAME from homeassistant.const import CONF_NAME
from homeassistant.util import dt as dt_util
from .conftest import check_valid_state 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.""" """Test tariff migration when there are >1 old sensors."""
entity_reg = mock_registry(hass) 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_1 = "discrimination"
uid_2 = "normal" uid_2 = "normal"
old_conf_1 = {CONF_NAME: "test_pvpc_1", ATTR_TARIFF: uid_1} old_conf_1 = {CONF_NAME: "test_pvpc_1", ATTR_TARIFF: uid_1}

View File

@ -37,6 +37,8 @@ import homeassistant.util.dt as dt_util
from tests.common import get_test_home_assistant, mock_registry from tests.common import get_test_home_assistant, mock_registry
from tests.components.recorder.common import wait_recording_done from tests.components.recorder.common import wait_recording_done
ORIG_TZ = dt_util.DEFAULT_TIME_ZONE
def test_compile_hourly_statistics(hass_recorder): def test_compile_hourly_statistics(hass_recorder):
"""Test compiling hourly statistics.""" """Test compiling hourly statistics."""
@ -841,6 +843,7 @@ def test_delete_duplicates(caplog, tmpdir):
session.add(recorder.models.Statistics.from_stats(3, stat)) session.add(recorder.models.Statistics.from_stats(3, stat))
hass.stop() hass.stop()
dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
# Test that the duplicates are removed during migration from schema 23 # Test that the duplicates are removed during migration from schema 23
hass = get_test_home_assistant() hass = get_test_home_assistant()
@ -849,6 +852,7 @@ def test_delete_duplicates(caplog, tmpdir):
wait_recording_done(hass) wait_recording_done(hass)
wait_recording_done(hass) wait_recording_done(hass)
hass.stop() hass.stop()
dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
assert "Deleted 2 duplicated statistics rows" in caplog.text assert "Deleted 2 duplicated statistics rows" in caplog.text
assert "Found non identical" not 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)) session.add(recorder.models.Statistics.from_stats(3, stat))
hass.stop() hass.stop()
dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
# Test that the duplicates are removed during migration from schema 23 # Test that the duplicates are removed during migration from schema 23
hass = get_test_home_assistant() hass = get_test_home_assistant()
@ -1022,6 +1027,7 @@ def test_delete_duplicates_many(caplog, tmpdir):
wait_recording_done(hass) wait_recording_done(hass)
wait_recording_done(hass) wait_recording_done(hass)
hass.stop() hass.stop()
dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
assert "Deleted 3002 duplicated statistics rows" in caplog.text assert "Deleted 3002 duplicated statistics rows" in caplog.text
assert "Found non identical" not 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)) session.add(recorder.models.Statistics.from_stats(2, stat))
hass.stop() hass.stop()
dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
# Test that the duplicates are removed during migration from schema 23 # Test that the duplicates are removed during migration from schema 23
hass = get_test_home_assistant() 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)
wait_recording_done(hass) wait_recording_done(hass)
hass.stop() hass.stop()
dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
assert "Deleted 2 duplicated statistics rows" in caplog.text assert "Deleted 2 duplicated statistics rows" in caplog.text
assert "Deleted 1 non identical" 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() hass.stop()
dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
# Test that the duplicates are removed during migration from schema 23 # Test that the duplicates are removed during migration from schema 23
hass = get_test_home_assistant() 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)
wait_recording_done(hass) wait_recording_done(hass)
hass.stop() hass.stop()
dt_util.DEFAULT_TIME_ZONE = ORIG_TZ
assert "duplicated statistics rows" not in caplog.text assert "duplicated statistics rows" not in caplog.text
assert "Found non identical" not in caplog.text assert "Found non identical" not in caplog.text

View File

@ -168,6 +168,7 @@ def _check_state(hass, category, entity_id):
async def test_setup(hass, two_zone_alarm): # noqa: F811 async def test_setup(hass, two_zone_alarm): # noqa: F811
"""Test entity setup.""" """Test entity setup."""
hass.config.set_time_zone("UTC")
registry = er.async_get(hass) registry = er.async_get(hass)
for id in ENTITY_IDS.values(): for id in ENTITY_IDS.values():

View File

@ -2176,6 +2176,8 @@ def test_compile_statistics_hourly_daily_monthly_summary(
"homeassistant.components.recorder.models.dt_util.utcnow", return_value=zero "homeassistant.components.recorder.models.dt_util.utcnow", return_value=zero
): ):
hass = hass_recorder() 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 = hass.data[DATA_INSTANCE]
recorder._db_supports_row_number = db_supports_row_number recorder._db_supports_row_number = db_supports_row_number
setup_component(hass, "sensor", {}) setup_component(hass, "sensor", {})

View File

@ -96,10 +96,10 @@ async def test_sensors(
assert state assert state
assert state.attributes.get(ATTR_ICON) == "mdi:television" assert state.attributes.get(ATTR_ICON) == "mdi:television"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "Episodes" 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 ( assert (
state.attributes.get("The Andy Griffith Show S01E01") 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" assert state.state == "2"

View File

@ -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.common import async_fire_time_changed, async_mock_service, mock_component
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401 from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401
ORIG_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE
@pytest.fixture @pytest.fixture
def calls(hass): def calls(hass):
@ -33,20 +31,11 @@ def calls(hass):
def setup_comp(hass): def setup_comp(hass):
"""Initialize components.""" """Initialize components."""
mock_component(hass, "group") mock_component(hass, "group")
hass.config.set_time_zone(hass.config.time_zone)
hass.loop.run_until_complete( hass.loop.run_until_complete(
async_setup_component(hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) 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): async def test_sunset_trigger(hass, calls, legacy_patchable_time):
"""Test the sunset trigger.""" """Test the sunset trigger."""
now = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC) now = datetime(2015, 9, 15, 23, tzinfo=dt_util.UTC)

View File

@ -1124,7 +1124,8 @@ async def test_trigger_entity_device_class_parsing_works(hass):
await hass.async_block_till_done() 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): with patch("homeassistant.util.dt.now", return_value=now):
hass.bus.async_fire("test_event") 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): async def test_entity_device_class_parsing_works(hass):
"""Test entity device class parsing works.""" """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): with patch("homeassistant.util.dt.now", return_value=now):
assert await async_setup_component( assert await async_setup_component(

View File

@ -1,20 +1,9 @@
"""The tests for time_date sensor platform.""" """The tests for time_date sensor platform."""
from unittest.mock import patch from unittest.mock import patch
import pytest
import homeassistant.components.time_date.sensor as time_date import homeassistant.components.time_date.sensor as time_date
import homeassistant.util.dt as dt_util 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 # pylint: disable=protected-access
async def test_intervals(hass): async def test_intervals(hass):
@ -45,6 +34,8 @@ async def test_intervals(hass):
async def test_states(hass): async def test_states(hass):
"""Test states of sensors.""" """Test states of sensors."""
hass.config.set_time_zone("UTC")
now = dt_util.utc_from_timestamp(1495068856) now = dt_util.utc_from_timestamp(1495068856)
device = time_date.TimeDateSensor(hass, "time") device = time_date.TimeDateSensor(hass, "time")
device._update_internal_state(now) device._update_internal_state(now)
@ -79,9 +70,7 @@ async def test_states(hass):
async def test_states_non_default_timezone(hass): async def test_states_non_default_timezone(hass):
"""Test states of sensors in a timezone other than UTC.""" """Test states of sensors in a timezone other than UTC."""
new_tz = dt_util.get_time_zone("America/New_York") hass.config.set_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) now = dt_util.utc_from_timestamp(1495068856)
device = time_date.TimeDateSensor(hass, "time") device = time_date.TimeDateSensor(hass, "time")
@ -116,9 +105,7 @@ async def test_states_non_default_timezone(hass):
# pylint: disable=no-member # pylint: disable=no-member
async def test_timezone_intervals(hass): async def test_timezone_intervals(hass):
"""Test date sensor behavior in a timezone besides UTC.""" """Test date sensor behavior in a timezone besides UTC."""
new_tz = dt_util.get_time_zone("America/New_York") hass.config.set_time_zone("America/New_York")
assert new_tz is not None
dt_util.set_default_time_zone(new_tz)
device = time_date.TimeDateSensor(hass, "date") device = time_date.TimeDateSensor(hass, "date")
now = dt_util.utc_from_timestamp(50000) now = dt_util.utc_from_timestamp(50000)
@ -128,9 +115,7 @@ async def test_timezone_intervals(hass):
# so the second day was 18000 + 86400 # so the second day was 18000 + 86400
assert next_time.timestamp() == 104400 assert next_time.timestamp() == 104400
new_tz = dt_util.get_time_zone("America/Edmonton") hass.config.set_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") now = dt_util.parse_datetime("2017-11-13 19:47:19-07:00")
device = time_date.TimeDateSensor(hass, "date") device = time_date.TimeDateSensor(hass, "date")
with patch("homeassistant.util.dt.utcnow", return_value=now): 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") assert next_time.timestamp() == dt_util.as_timestamp("2017-11-14 00:00:00-07:00")
# Entering DST # Entering DST
new_tz = dt_util.get_time_zone("Europe/Prague") hass.config.set_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") now = dt_util.parse_datetime("2020-03-29 00:00+01:00")
with patch("homeassistant.util.dt.utcnow", return_value=now): with patch("homeassistant.util.dt.utcnow", return_value=now):
@ -168,11 +151,9 @@ async def test_timezone_intervals(hass):
"homeassistant.util.dt.utcnow", "homeassistant.util.dt.utcnow",
return_value=dt_util.parse_datetime("2017-11-14 02:47:19-00:00"), 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.""" """Test get_interval() without parameters."""
new_tz = dt_util.get_time_zone("America/Edmonton") hass.config.set_time_zone("America/Edmonton")
assert new_tz is not None
dt_util.set_default_time_zone(new_tz)
device = time_date.TimeDateSensor(hass, "date") device = time_date.TimeDateSensor(hass, "date")
next_time = device.get_next_interval() next_time = device.get_next_interval()
assert next_time.timestamp() == dt_util.as_timestamp("2017-11-14 00:00:00-07:00") assert next_time.timestamp() == dt_util.as_timestamp("2017-11-14 00:00:00-07:00")

View File

@ -12,8 +12,6 @@ import homeassistant.util.dt as dt_util
from tests.common import assert_setup_component from tests.common import assert_setup_component
ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def mock_legacy_time(legacy_patchable_time): def mock_legacy_time(legacy_patchable_time):
@ -28,13 +26,6 @@ def setup_fixture(hass):
hass.config.longitude = 18.98583 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): async def test_setup(hass):
"""Test the setup.""" """Test the setup."""
config = { config = {
@ -69,7 +60,9 @@ async def test_setup_no_sensors(hass):
async def test_in_period_on_start(hass): async def test_in_period_on_start(hass):
"""Test simple setting.""" """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 = { config = {
"binary_sensor": [ "binary_sensor": [
{ {
@ -93,7 +86,9 @@ async def test_in_period_on_start(hass):
async def test_midnight_turnover_before_midnight_inside_period(hass): async def test_midnight_turnover_before_midnight_inside_period(hass):
"""Test midnight turnover setting before midnight inside period .""" """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 = { config = {
"binary_sensor": [ "binary_sensor": [
{"platform": "tod", "name": "Night", "after": "22:00", "before": "5:00"} {"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): async def test_midnight_turnover_after_midnight_inside_period(hass):
"""Test midnight turnover setting before midnight inside period .""" """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 = { config = {
"binary_sensor": [ "binary_sensor": [
{"platform": "tod", "name": "Night", "after": "22:00", "before": "5:00"} {"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): async def test_midnight_turnover_after_midnight_outside_period(hass):
"""Test midnight turnover setting before midnight inside period .""" """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 = { config = {
"binary_sensor": [ "binary_sensor": [
@ -201,7 +200,9 @@ async def test_midnight_turnover_after_midnight_outside_period(hass):
state = hass.states.get("binary_sensor.night") state = hass.states.get("binary_sensor.night")
assert state.state == STATE_OFF 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( with patch(
"homeassistant.components.tod.binary_sensor.dt_util.utcnow", "homeassistant.components.tod.binary_sensor.dt_util.utcnow",
return_value=switchover_time, return_value=switchover_time,
@ -420,13 +421,13 @@ async def test_from_sunset_to_sunrise(hass):
async def test_offset(hass): async def test_offset(hass):
"""Test offset.""" """Test offset."""
after = datetime(2019, 1, 10, 18, 0, 0, tzinfo=dt_util.UTC) + timedelta( after = datetime(
hours=1, minutes=34 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( before = datetime(
hours=1, minutes=45 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" entity_id = "binary_sensor.evening"
config = { config = {
@ -499,9 +500,9 @@ async def test_offset(hass):
async def test_offset_overnight(hass): async def test_offset_overnight(hass):
"""Test offset overnight.""" """Test offset overnight."""
after = datetime(2019, 1, 10, 18, 0, 0, tzinfo=dt_util.UTC) + timedelta( after = datetime(
hours=1, minutes=34 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" entity_id = "binary_sensor.evening"
config = { config = {
"binary_sensor": [ "binary_sensor": [
@ -890,8 +891,7 @@ async def test_sun_offset(hass):
async def test_dst(hass): async def test_dst(hass):
"""Test sun event with offset.""" """Test sun event with offset."""
hass.config.time_zone = "CET" hass.config.set_time_zone("CET")
dt_util.set_default_time_zone(dt_util.get_time_zone("CET"))
test_time = datetime(2019, 3, 30, 3, 0, 0, tzinfo=dt_util.UTC) test_time = datetime(2019, 3, 30, 3, 0, 0, tzinfo=dt_util.UTC)
config = { config = {
"binary_sensor": [ "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): async def test_simple_before_after_does_not_loop_utc_not_in_range(hass):
"""Test simple before after.""" """Test simple before after."""
hass.config.time_zone = "UTC" hass.config.set_time_zone("UTC")
dt_util.set_default_time_zone(dt_util.UTC)
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.UTC)
config = { config = {
"binary_sensor": [ "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): async def test_simple_before_after_does_not_loop_utc_in_range(hass):
"""Test simple before after.""" """Test simple before after."""
hass.config.time_zone = "UTC" hass.config.set_time_zone("UTC")
dt_util.set_default_time_zone(dt_util.UTC)
test_time = datetime(2019, 1, 10, 22, 43, 0, tzinfo=dt_util.UTC) test_time = datetime(2019, 1, 10, 22, 43, 0, tzinfo=dt_util.UTC)
config = { config = {
"binary_sensor": [ "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): async def test_simple_before_after_does_not_loop_utc_fire_at_before(hass):
"""Test simple before after.""" """Test simple before after."""
hass.config.time_zone = "UTC" hass.config.set_time_zone("UTC")
dt_util.set_default_time_zone(dt_util.UTC)
test_time = datetime(2019, 1, 11, 6, 0, 0, tzinfo=dt_util.UTC) test_time = datetime(2019, 1, 11, 6, 0, 0, tzinfo=dt_util.UTC)
config = { config = {
"binary_sensor": [ "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): async def test_simple_before_after_does_not_loop_utc_fire_at_after(hass):
"""Test simple before after.""" """Test simple before after."""
hass.config.time_zone = "UTC" hass.config.set_time_zone("UTC")
dt_util.set_default_time_zone(dt_util.UTC)
test_time = datetime(2019, 1, 10, 22, 0, 0, tzinfo=dt_util.UTC) test_time = datetime(2019, 1, 10, 22, 0, 0, tzinfo=dt_util.UTC)
config = { config = {
"binary_sensor": [ "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): async def test_simple_before_after_does_not_loop_utc_both_before_now(hass):
"""Test simple before after.""" """Test simple before after."""
hass.config.time_zone = "UTC" hass.config.set_time_zone("UTC")
dt_util.set_default_time_zone(dt_util.UTC)
test_time = datetime(2019, 1, 10, 22, 0, 0, tzinfo=dt_util.UTC) test_time = datetime(2019, 1, 10, 22, 0, 0, tzinfo=dt_util.UTC)
config = { config = {
"binary_sensor": [ "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): async def test_simple_before_after_does_not_loop_berlin_not_in_range(hass):
"""Test simple before after.""" """Test simple before after."""
hass.config.time_zone = "Europe/Berlin" hass.config.set_time_zone("Europe/Berlin")
dt_util.set_default_time_zone(dt_util.get_time_zone("Europe/Berlin"))
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.UTC)
config = { config = {
"binary_sensor": [ "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): async def test_simple_before_after_does_not_loop_berlin_in_range(hass):
"""Test simple before after.""" """Test simple before after."""
hass.config.time_zone = "Europe/Berlin" hass.config.set_time_zone("Europe/Berlin")
dt_util.set_default_time_zone(dt_util.get_time_zone("Europe/Berlin"))
test_time = datetime(2019, 1, 10, 23, 43, 0, tzinfo=dt_util.UTC) test_time = datetime(2019, 1, 10, 23, 43, 0, tzinfo=dt_util.UTC)
config = { config = {
"binary_sensor": [ "binary_sensor": [

View File

@ -12,44 +12,29 @@ from .conftest import patch_metrics
from tests.common import MockConfigEntry 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 @pytest.fixture
def set_tz(request): def set_tz(request):
"""Set the default TZ to the one requested.""" """Set the default TZ to the one requested."""
return request.getfixturevalue(request.param) request.getfixturevalue(request.param)
@pytest.fixture @pytest.fixture
def utc() -> tzinfo: def utc(hass: HomeAssistant) -> None:
"""Set the default TZ to UTC.""" """Set the default TZ to UTC."""
tz = dt.get_time_zone("UTC") hass.config.set_time_zone("UTC")
dt.set_default_time_zone(tz)
return tz
@pytest.fixture @pytest.fixture
def helsinki() -> tzinfo: def helsinki(hass: HomeAssistant) -> None:
"""Set the default TZ to Europe/Helsinki.""" """Set the default TZ to Europe/Helsinki."""
tz = dt.get_time_zone("Europe/Helsinki") hass.config.set_time_zone("Europe/Helsinki")
dt.set_default_time_zone(tz)
return tz
@pytest.fixture @pytest.fixture
def new_york() -> tzinfo: def new_york(hass: HomeAssistant) -> None:
"""Set the default TZ to America/New_York.""" """Set the default TZ to America/New_York."""
tz = dt.get_time_zone("America/New_York") hass.config.set_time_zone("America/New_York")
dt.set_default_time_zone(tz)
return tz
def _sensor_to_datetime(sensor): def _sensor_to_datetime(sensor):

View File

@ -35,6 +35,7 @@ DAY3 = datetime(2020, 4, 21, tzinfo=dt_util.UTC)
) )
async def test_zodiac_day(hass, now, sign, element, modality): async def test_zodiac_day(hass, now, sign, element, modality):
"""Test the zodiac sensor.""" """Test the zodiac sensor."""
hass.config.set_time_zone("UTC")
config = {DOMAIN: {}} config = {DOMAIN: {}}
with patch("homeassistant.components.zodiac.sensor.utcnow", return_value=now): with patch("homeassistant.components.zodiac.sensor.utcnow", return_value=now):

View File

@ -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.const import ATTR_NOW, EVENT_TIME_CHANGED, HASSIO_USER_NAME
from homeassistant.helpers import config_entry_oauth2_flow, event from homeassistant.helpers import config_entry_oauth2_flow, event
from homeassistant.setup import async_setup_component 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 from tests.ignore_uncaught_exceptions import IGNORE_UNCAUGHT_EXCEPTIONS
@ -249,6 +249,8 @@ def load_registries():
def hass(loop, load_registries, hass_storage, request): def hass(loop, load_registries, hass_storage, request):
"""Fixture to provide a test instance of Home Assistant.""" """Fixture to provide a test instance of Home Assistant."""
orig_tz = dt_util.DEFAULT_TIME_ZONE
def exc_handle(loop, context): def exc_handle(loop, context):
"""Handle exceptions by rethrowing them, which will fail the test.""" """Handle exceptions by rethrowing them, which will fail the test."""
# Most of these contexts will contain an exception, but not all. # 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 yield hass
loop.run_until_complete(hass.async_stop(force=True)) 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: for ex in exceptions:
if ( if (
request.module.__name__, request.module.__name__,

View File

@ -28,8 +28,6 @@ import homeassistant.util.dt as dt_util
from tests.common import async_mock_service from tests.common import async_mock_service
ORIG_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE
@pytest.fixture @pytest.fixture
def calls(hass): 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): def assert_element(trace_element, expected_element, path):
"""Assert a trace element is as expected. """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 at 7 AM and sunset at 3AM during summer
After sunrise is true from sunrise until midnight, local time. After sunrise is true from sunrise until midnight, local time.
""" """
tz = dt_util.get_time_zone("America/Anchorage") hass.config.set_time_zone("America/Anchorage")
dt_util.set_default_time_zone(tz)
hass.config.latitude = 66.5 hass.config.latitude = 66.5
hass.config.longitude = 162.4 hass.config.longitude = 162.4
await async_setup_component( 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 at 7 AM and sunset at 3AM during summer
Before sunrise is true from midnight until sunrise, local time. Before sunrise is true from midnight until sunrise, local time.
""" """
tz = dt_util.get_time_zone("America/Anchorage") hass.config.set_time_zone("America/Anchorage")
dt_util.set_default_time_zone(tz)
hass.config.latitude = 66.5 hass.config.latitude = 66.5
hass.config.longitude = 162.4 hass.config.longitude = 162.4
await async_setup_component( 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 at 7 AM and sunset at 3AM during summer
Before sunset is true from midnight until sunset, local time. Before sunset is true from midnight until sunset, local time.
""" """
tz = dt_util.get_time_zone("America/Anchorage") hass.config.set_time_zone("America/Anchorage")
dt_util.set_default_time_zone(tz)
hass.config.latitude = 66.5 hass.config.latitude = 66.5
hass.config.longitude = 162.4 hass.config.longitude = 162.4
await async_setup_component( 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 at 7 AM and sunset at 3AM during summer
After sunset is true from sunset until midnight, local time. After sunset is true from sunset until midnight, local time.
""" """
tz = dt_util.get_time_zone("America/Anchorage") hass.config.set_time_zone("America/Anchorage")
dt_util.set_default_time_zone(tz)
hass.config.latitude = 66.5 hass.config.latitude = 66.5
hass.config.longitude = 162.4 hass.config.longitude = 162.4
await async_setup_component( await async_setup_component(

View File

@ -46,14 +46,6 @@ from tests.common import async_fire_time_changed
DEFAULT_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE 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): async def test_track_point_in_time(hass):
"""Test track point in time.""" """Test track point in time."""
before_birthday = datetime(1985, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC) 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") @pytest.mark.freeze_time("2021-03-28 01:28:00+01:00")
async def test_periodic_task_entering_dst(hass, freezer): async def test_periodic_task_entering_dst(hass, freezer):
"""Test periodic task behavior when entering dst.""" """Test periodic task behavior when entering dst."""
timezone = dt_util.get_time_zone("Europe/Vienna") hass.config.set_time_zone("Europe/Vienna")
dt_util.set_default_time_zone(timezone)
specific_runs = [] specific_runs = []
today = date.today().isoformat() 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) This tests a task firing every second in the range 0..58 (not *:*:59)
""" """
timezone = dt_util.get_time_zone("Europe/Vienna") hass.config.set_time_zone("Europe/Vienna")
dt_util.set_default_time_zone(timezone)
specific_runs = [] specific_runs = []
today = date.today().isoformat() 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") @pytest.mark.freeze_time("2021-10-31 02:28:00+02:00")
async def test_periodic_task_leaving_dst(hass, freezer): async def test_periodic_task_leaving_dst(hass, freezer):
"""Test periodic task behavior when leaving dst.""" """Test periodic task behavior when leaving dst."""
timezone = dt_util.get_time_zone("Europe/Vienna") hass.config.set_time_zone("Europe/Vienna")
dt_util.set_default_time_zone(timezone)
specific_runs = [] specific_runs = []
today = date.today().isoformat() 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") @pytest.mark.freeze_time("2021-10-31 02:28:00+02:00")
async def test_periodic_task_leaving_dst_2(hass, freezer): async def test_periodic_task_leaving_dst_2(hass, freezer):
"""Test periodic task behavior when leaving dst.""" """Test periodic task behavior when leaving dst."""
timezone = dt_util.get_time_zone("Europe/Vienna") hass.config.set_time_zone("Europe/Vienna")
dt_util.set_default_time_zone(timezone)
specific_runs = [] specific_runs = []
today = date.today().isoformat() 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.""" """Test cancel of async track point in time."""
times = [] times = []
hass.config.set_time_zone("US/Hawaii")
hst_tz = dt_util.get_time_zone("US/Hawaii") hst_tz = dt_util.get_time_zone("US/Hawaii")
dt_util.set_default_time_zone(hst_tz)
@ha.callback @ha.callback
def run_callback(local_time): def run_callback(local_time):

View File

@ -674,6 +674,7 @@ def test_strptime(hass):
def test_timestamp_custom(hass): def test_timestamp_custom(hass):
"""Test the timestamps to custom filter.""" """Test the timestamps to custom filter."""
hass.config.set_time_zone("UTC")
now = dt_util.utcnow() now = dt_util.utcnow()
tests = [ tests = [
(None, None, None, None), (None, None, None, None),
@ -700,6 +701,7 @@ def test_timestamp_custom(hass):
def test_timestamp_local(hass): def test_timestamp_local(hass):
"""Test the timestamps to local filter.""" """Test the timestamps to local filter."""
hass.config.set_time_zone("UTC")
tests = {None: None, 1469119144: "2016-07-21T16:39:04+00:00"} tests = {None: None, 1469119144: "2016-07-21T16:39:04+00:00"}
for inp, out in tests.items(): 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 = freeze_time(now)
freezer.start() freezer.start()
original_tz = dt_util.DEFAULT_TIME_ZONE hass.config.set_time_zone(timezone_str)
timezone = dt_util.get_time_zone(timezone_str)
dt_util.set_default_time_zone(timezone)
result = template.Template( result = template.Template(
"{{ today_at('10:00').isoformat() }}", "{{ 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() template.Template("{{ today_at('bad') }}", hass).async_render()
freezer.stop() freezer.stop()
dt_util.set_default_time_zone(original_tz)
@patch( @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): def test_relative_time(mock_is_safe, hass):
"""Test relative_time method.""" """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") 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): with patch("homeassistant.util.dt.now", return_value=now):
result = template.Template( result = template.Template(

View File

@ -12,7 +12,6 @@ import homeassistant.config as config_util
from homeassistant.const import SIGNAL_BOOTSTRAP_INTEGRATONS from homeassistant.const import SIGNAL_BOOTSTRAP_INTEGRATONS
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
import homeassistant.util.dt as dt_util
from tests.common import ( from tests.common import (
MockModule, MockModule,
@ -23,7 +22,6 @@ from tests.common import (
mock_integration, mock_integration,
) )
ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE
VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE)

View File

@ -32,7 +32,6 @@ from homeassistant.helpers import config_validation as cv
import homeassistant.helpers.check_config as check_config import homeassistant.helpers.check_config as check_config
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.loader import async_get_integration from homeassistant.loader import async_get_integration
from homeassistant.util import dt as dt_util
from homeassistant.util.yaml import SECRET_YAML from homeassistant.util.yaml import SECRET_YAML
from tests.common import get_test_config_dir, patch_yaml_files 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) AUTOMATIONS_PATH = os.path.join(CONFIG_DIR, config_util.AUTOMATION_CONFIG_PATH)
SCRIPTS_PATH = os.path.join(CONFIG_DIR, config_util.SCRIPT_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) SCENES_PATH = os.path.join(CONFIG_DIR, config_util.SCENE_CONFIG_PATH)
ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE
def create_file(path): def create_file(path):
@ -58,8 +56,6 @@ def teardown():
"""Clean up.""" """Clean up."""
yield yield
dt_util.DEFAULT_TIME_ZONE = ORIG_TIMEZONE
if os.path.isfile(YAML_PATH): if os.path.isfile(YAML_PATH):
os.remove(YAML_PATH) os.remove(YAML_PATH)