Simplify timezone setting in recorder test (#116220)

This commit is contained in:
Erik Montnemery 2024-04-26 15:14:23 +02:00 committed by GitHub
parent b582d51a8a
commit 10be8f9683
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 50 additions and 91 deletions

View file

@ -554,7 +554,7 @@ def test_saving_state_with_commit_interval_zero(
hass_recorder: Callable[..., HomeAssistant], hass_recorder: Callable[..., HomeAssistant],
) -> None: ) -> None:
"""Test saving a state with a commit interval of zero.""" """Test saving a state with a commit interval of zero."""
hass = hass_recorder({"commit_interval": 0}) hass = hass_recorder(config={"commit_interval": 0})
assert get_instance(hass).commit_interval == 0 assert get_instance(hass).commit_interval == 0
entity_id = "test.recorder" entity_id = "test.recorder"
@ -611,7 +611,7 @@ def test_saving_state_include_domains(
hass_recorder: Callable[..., HomeAssistant], hass_recorder: Callable[..., HomeAssistant],
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder({"include": {"domains": "test2"}}) hass = hass_recorder(config={"include": {"domains": "test2"}})
states = _add_entities(hass, ["test.recorder", "test2.recorder"]) states = _add_entities(hass, ["test.recorder", "test2.recorder"])
assert len(states) == 1 assert len(states) == 1
assert _state_with_context(hass, "test2.recorder").as_dict() == states[0].as_dict() assert _state_with_context(hass, "test2.recorder").as_dict() == states[0].as_dict()
@ -622,7 +622,7 @@ def test_saving_state_include_domains_globs(
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder( hass = hass_recorder(
{"include": {"domains": "test2", "entity_globs": "*.included_*"}} config={"include": {"domains": "test2", "entity_globs": "*.included_*"}}
) )
states = _add_entities( states = _add_entities(
hass, ["test.recorder", "test2.recorder", "test3.included_entity"] hass, ["test.recorder", "test2.recorder", "test3.included_entity"]
@ -644,7 +644,7 @@ def test_saving_state_incl_entities(
hass_recorder: Callable[..., HomeAssistant], hass_recorder: Callable[..., HomeAssistant],
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder({"include": {"entities": "test2.recorder"}}) hass = hass_recorder(config={"include": {"entities": "test2.recorder"}})
states = _add_entities(hass, ["test.recorder", "test2.recorder"]) states = _add_entities(hass, ["test.recorder", "test2.recorder"])
assert len(states) == 1 assert len(states) == 1
assert _state_with_context(hass, "test2.recorder").as_dict() == states[0].as_dict() assert _state_with_context(hass, "test2.recorder").as_dict() == states[0].as_dict()
@ -705,7 +705,7 @@ def test_saving_state_exclude_domains(
hass_recorder: Callable[..., HomeAssistant], hass_recorder: Callable[..., HomeAssistant],
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder({"exclude": {"domains": "test"}}) hass = hass_recorder(config={"exclude": {"domains": "test"}})
states = _add_entities(hass, ["test.recorder", "test2.recorder"]) states = _add_entities(hass, ["test.recorder", "test2.recorder"])
assert len(states) == 1 assert len(states) == 1
assert _state_with_context(hass, "test2.recorder").as_dict() == states[0].as_dict() assert _state_with_context(hass, "test2.recorder").as_dict() == states[0].as_dict()
@ -716,7 +716,7 @@ def test_saving_state_exclude_domains_globs(
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder( hass = hass_recorder(
{"exclude": {"domains": "test", "entity_globs": "*.excluded_*"}} config={"exclude": {"domains": "test", "entity_globs": "*.excluded_*"}}
) )
states = _add_entities( states = _add_entities(
hass, ["test.recorder", "test2.recorder", "test2.excluded_entity"] hass, ["test.recorder", "test2.recorder", "test2.excluded_entity"]
@ -729,7 +729,7 @@ def test_saving_state_exclude_entities(
hass_recorder: Callable[..., HomeAssistant], hass_recorder: Callable[..., HomeAssistant],
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder({"exclude": {"entities": "test.recorder"}}) hass = hass_recorder(config={"exclude": {"entities": "test.recorder"}})
states = _add_entities(hass, ["test.recorder", "test2.recorder"]) states = _add_entities(hass, ["test.recorder", "test2.recorder"])
assert len(states) == 1 assert len(states) == 1
assert _state_with_context(hass, "test2.recorder").as_dict() == states[0].as_dict() assert _state_with_context(hass, "test2.recorder").as_dict() == states[0].as_dict()
@ -740,7 +740,10 @@ def test_saving_state_exclude_domain_include_entity(
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder( hass = hass_recorder(
{"include": {"entities": "test.recorder"}, "exclude": {"domains": "test"}} config={
"include": {"entities": "test.recorder"},
"exclude": {"domains": "test"},
}
) )
states = _add_entities(hass, ["test.recorder", "test2.recorder"]) states = _add_entities(hass, ["test.recorder", "test2.recorder"])
assert len(states) == 2 assert len(states) == 2
@ -751,7 +754,7 @@ def test_saving_state_exclude_domain_glob_include_entity(
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder( hass = hass_recorder(
{ config={
"include": {"entities": ["test.recorder", "test.excluded_entity"]}, "include": {"entities": ["test.recorder", "test.excluded_entity"]},
"exclude": {"domains": "test", "entity_globs": "*._excluded_*"}, "exclude": {"domains": "test", "entity_globs": "*._excluded_*"},
} }
@ -767,7 +770,10 @@ def test_saving_state_include_domain_exclude_entity(
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder( hass = hass_recorder(
{"exclude": {"entities": "test.recorder"}, "include": {"domains": "test"}} config={
"exclude": {"entities": "test.recorder"},
"include": {"domains": "test"},
}
) )
states = _add_entities(hass, ["test.recorder", "test2.recorder", "test.ok"]) states = _add_entities(hass, ["test.recorder", "test2.recorder", "test.ok"])
assert len(states) == 1 assert len(states) == 1
@ -780,7 +786,7 @@ def test_saving_state_include_domain_glob_exclude_entity(
) -> None: ) -> None:
"""Test saving and restoring a state.""" """Test saving and restoring a state."""
hass = hass_recorder( hass = hass_recorder(
{ config={
"exclude": {"entities": ["test.recorder", "test2.included_entity"]}, "exclude": {"entities": ["test.recorder", "test2.included_entity"]},
"include": {"domains": "test", "entity_globs": "*._included_*"}, "include": {"domains": "test", "entity_globs": "*._included_*"},
} }
@ -985,12 +991,9 @@ def run_tasks_at_time(hass, test_time):
@pytest.mark.parametrize("enable_nightly_purge", [True]) @pytest.mark.parametrize("enable_nightly_purge", [True])
def test_auto_purge(hass_recorder: Callable[..., HomeAssistant]) -> None: def test_auto_purge(hass_recorder: Callable[..., HomeAssistant]) -> None:
"""Test periodic purge scheduling.""" """Test periodic purge scheduling."""
hass = hass_recorder() timezone = "Europe/Copenhagen"
hass = hass_recorder(timezone=timezone)
original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone(timezone)
tz = dt_util.get_time_zone("Europe/Copenhagen")
dt_util.set_default_time_zone(tz)
# Purging is scheduled to happen at 4:12am every day. Exercise this behavior by # Purging is scheduled to happen at 4:12am every day. Exercise this behavior by
# firing time changed events and advancing the clock around this time. Pick an # firing time changed events and advancing the clock around this time. Pick an
@ -1040,20 +1043,15 @@ def test_auto_purge(hass_recorder: Callable[..., HomeAssistant]) -> None:
assert len(purge_old_data.mock_calls) == 1 assert len(purge_old_data.mock_calls) == 1
assert len(periodic_db_cleanups.mock_calls) == 1 assert len(periodic_db_cleanups.mock_calls) == 1
dt_util.set_default_time_zone(original_tz)
@pytest.mark.parametrize("enable_nightly_purge", [True]) @pytest.mark.parametrize("enable_nightly_purge", [True])
def test_auto_purge_auto_repack_on_second_sunday( def test_auto_purge_auto_repack_on_second_sunday(
hass_recorder: Callable[..., HomeAssistant], hass_recorder: Callable[..., HomeAssistant],
) -> None: ) -> None:
"""Test periodic purge scheduling does a repack on the 2nd sunday.""" """Test periodic purge scheduling does a repack on the 2nd sunday."""
hass = hass_recorder() timezone = "Europe/Copenhagen"
hass = hass_recorder(timezone=timezone)
original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone(timezone)
tz = dt_util.get_time_zone("Europe/Copenhagen")
dt_util.set_default_time_zone(tz)
# Purging is scheduled to happen at 4:12am every day. Exercise this behavior by # Purging is scheduled to happen at 4:12am every day. Exercise this behavior by
# firing time changed events and advancing the clock around this time. Pick an # firing time changed events and advancing the clock around this time. Pick an
@ -1084,20 +1082,15 @@ def test_auto_purge_auto_repack_on_second_sunday(
assert args[2] is True # repack assert args[2] is True # repack
assert len(periodic_db_cleanups.mock_calls) == 1 assert len(periodic_db_cleanups.mock_calls) == 1
dt_util.set_default_time_zone(original_tz)
@pytest.mark.parametrize("enable_nightly_purge", [True]) @pytest.mark.parametrize("enable_nightly_purge", [True])
def test_auto_purge_auto_repack_disabled_on_second_sunday( def test_auto_purge_auto_repack_disabled_on_second_sunday(
hass_recorder: Callable[..., HomeAssistant], hass_recorder: Callable[..., HomeAssistant],
) -> None: ) -> None:
"""Test periodic purge scheduling does not auto repack on the 2nd sunday if disabled.""" """Test periodic purge scheduling does not auto repack on the 2nd sunday if disabled."""
hass = hass_recorder({CONF_AUTO_REPACK: False}) timezone = "Europe/Copenhagen"
hass = hass_recorder(config={CONF_AUTO_REPACK: False}, timezone=timezone)
original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone(timezone)
tz = dt_util.get_time_zone("Europe/Copenhagen")
dt_util.set_default_time_zone(tz)
# Purging is scheduled to happen at 4:12am every day. Exercise this behavior by # Purging is scheduled to happen at 4:12am every day. Exercise this behavior by
# firing time changed events and advancing the clock around this time. Pick an # firing time changed events and advancing the clock around this time. Pick an
@ -1128,20 +1121,15 @@ def test_auto_purge_auto_repack_disabled_on_second_sunday(
assert args[2] is False # repack assert args[2] is False # repack
assert len(periodic_db_cleanups.mock_calls) == 1 assert len(periodic_db_cleanups.mock_calls) == 1
dt_util.set_default_time_zone(original_tz)
@pytest.mark.parametrize("enable_nightly_purge", [True]) @pytest.mark.parametrize("enable_nightly_purge", [True])
def test_auto_purge_no_auto_repack_on_not_second_sunday( def test_auto_purge_no_auto_repack_on_not_second_sunday(
hass_recorder: Callable[..., HomeAssistant], hass_recorder: Callable[..., HomeAssistant],
) -> None: ) -> None:
"""Test periodic purge scheduling does not do a repack unless its the 2nd sunday.""" """Test periodic purge scheduling does not do a repack unless its the 2nd sunday."""
hass = hass_recorder() timezone = "Europe/Copenhagen"
hass = hass_recorder(timezone=timezone)
original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone(timezone)
tz = dt_util.get_time_zone("Europe/Copenhagen")
dt_util.set_default_time_zone(tz)
# Purging is scheduled to happen at 4:12am every day. Exercise this behavior by # Purging is scheduled to happen at 4:12am every day. Exercise this behavior by
# firing time changed events and advancing the clock around this time. Pick an # firing time changed events and advancing the clock around this time. Pick an
@ -1173,18 +1161,13 @@ def test_auto_purge_no_auto_repack_on_not_second_sunday(
assert args[2] is False # repack assert args[2] is False # repack
assert len(periodic_db_cleanups.mock_calls) == 1 assert len(periodic_db_cleanups.mock_calls) == 1
dt_util.set_default_time_zone(original_tz)
@pytest.mark.parametrize("enable_nightly_purge", [True]) @pytest.mark.parametrize("enable_nightly_purge", [True])
def test_auto_purge_disabled(hass_recorder: Callable[..., HomeAssistant]) -> None: def test_auto_purge_disabled(hass_recorder: Callable[..., HomeAssistant]) -> None:
"""Test periodic db cleanup still run when auto purge is disabled.""" """Test periodic db cleanup still run when auto purge is disabled."""
hass = hass_recorder({CONF_AUTO_PURGE: False}) timezone = "Europe/Copenhagen"
hass = hass_recorder(config={CONF_AUTO_PURGE: False}, timezone=timezone)
original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone(timezone)
tz = dt_util.get_time_zone("Europe/Copenhagen")
dt_util.set_default_time_zone(tz)
# Purging is scheduled to happen at 4:12am every day. We want # Purging is scheduled to happen at 4:12am every day. We want
# to verify that when auto purge is disabled periodic db cleanups # to verify that when auto purge is disabled periodic db cleanups
@ -1212,18 +1195,13 @@ def test_auto_purge_disabled(hass_recorder: Callable[..., HomeAssistant]) -> Non
purge_old_data.reset_mock() purge_old_data.reset_mock()
periodic_db_cleanups.reset_mock() periodic_db_cleanups.reset_mock()
dt_util.set_default_time_zone(original_tz)
@pytest.mark.parametrize("enable_statistics", [True]) @pytest.mark.parametrize("enable_statistics", [True])
def test_auto_statistics(hass_recorder: Callable[..., HomeAssistant], freezer) -> None: def test_auto_statistics(hass_recorder: Callable[..., HomeAssistant], freezer) -> None:
"""Test periodic statistics scheduling.""" """Test periodic statistics scheduling."""
hass = hass_recorder() timezone = "Europe/Copenhagen"
hass = hass_recorder(timezone=timezone)
original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone(timezone)
tz = dt_util.get_time_zone("Europe/Copenhagen")
dt_util.set_default_time_zone(tz)
stats_5min = [] stats_5min = []
stats_hourly = [] stats_hourly = []
@ -1302,8 +1280,6 @@ def test_auto_statistics(hass_recorder: Callable[..., HomeAssistant], freezer) -
assert len(stats_5min) == 3 assert len(stats_5min) == 3
assert len(stats_hourly) == 1 assert len(stats_hourly) == 1
dt_util.set_default_time_zone(original_tz)
def test_statistics_runs_initiated(hass_recorder: Callable[..., HomeAssistant]) -> None: def test_statistics_runs_initiated(hass_recorder: Callable[..., HomeAssistant]) -> None:
"""Test statistics_runs is initiated when DB is created.""" """Test statistics_runs is initiated when DB is created."""
@ -1719,7 +1695,10 @@ async def test_database_corruption_while_running(
def test_entity_id_filter(hass_recorder: Callable[..., HomeAssistant]) -> None: def test_entity_id_filter(hass_recorder: Callable[..., HomeAssistant]) -> None:
"""Test that entity ID filtering filters string and list.""" """Test that entity ID filtering filters string and list."""
hass = hass_recorder( hass = hass_recorder(
{"include": {"domains": "hello"}, "exclude": {"domains": "hidden_domain"}} config={
"include": {"domains": "hello"},
"exclude": {"domains": "hidden_domain"},
}
) )
event_types = ("hello",) event_types = ("hello",)

View file

@ -1119,9 +1119,7 @@ def test_daily_statistics_sum(
timezone, timezone,
) -> None: ) -> None:
"""Test daily statistics.""" """Test daily statistics."""
dt_util.set_default_time_zone(dt_util.get_time_zone(timezone)) hass = hass_recorder(timezone=timezone)
hass = hass_recorder()
wait_recording_done(hass) wait_recording_done(hass)
assert "Compiling statistics for" not in caplog.text assert "Compiling statistics for" not in caplog.text
assert "Statistics already compiled" not in caplog.text assert "Statistics already compiled" not in caplog.text
@ -1291,8 +1289,6 @@ def test_daily_statistics_sum(
) )
assert stats == {} assert stats == {}
dt_util.set_default_time_zone(dt_util.get_time_zone("UTC"))
@pytest.mark.parametrize("timezone", ["America/Regina", "Europe/Vienna", "UTC"]) @pytest.mark.parametrize("timezone", ["America/Regina", "Europe/Vienna", "UTC"])
@pytest.mark.freeze_time("2022-10-01 00:00:00+00:00") @pytest.mark.freeze_time("2022-10-01 00:00:00+00:00")
@ -1302,9 +1298,7 @@ def test_weekly_statistics_mean(
timezone, timezone,
) -> None: ) -> None:
"""Test weekly statistics.""" """Test weekly statistics."""
dt_util.set_default_time_zone(dt_util.get_time_zone(timezone)) hass = hass_recorder(timezone=timezone)
hass = hass_recorder()
wait_recording_done(hass) wait_recording_done(hass)
assert "Compiling statistics for" not in caplog.text assert "Compiling statistics for" not in caplog.text
assert "Statistics already compiled" not in caplog.text assert "Statistics already compiled" not in caplog.text
@ -1429,8 +1423,6 @@ def test_weekly_statistics_mean(
) )
assert stats == {} assert stats == {}
dt_util.set_default_time_zone(dt_util.get_time_zone("UTC"))
@pytest.mark.parametrize("timezone", ["America/Regina", "Europe/Vienna", "UTC"]) @pytest.mark.parametrize("timezone", ["America/Regina", "Europe/Vienna", "UTC"])
@pytest.mark.freeze_time("2022-10-01 00:00:00+00:00") @pytest.mark.freeze_time("2022-10-01 00:00:00+00:00")
@ -1440,9 +1432,7 @@ def test_weekly_statistics_sum(
timezone, timezone,
) -> None: ) -> None:
"""Test weekly statistics.""" """Test weekly statistics."""
dt_util.set_default_time_zone(dt_util.get_time_zone(timezone)) hass = hass_recorder(timezone=timezone)
hass = hass_recorder()
wait_recording_done(hass) wait_recording_done(hass)
assert "Compiling statistics for" not in caplog.text assert "Compiling statistics for" not in caplog.text
assert "Statistics already compiled" not in caplog.text assert "Statistics already compiled" not in caplog.text
@ -1612,8 +1602,6 @@ def test_weekly_statistics_sum(
) )
assert stats == {} assert stats == {}
dt_util.set_default_time_zone(dt_util.get_time_zone("UTC"))
@pytest.mark.parametrize("timezone", ["America/Regina", "Europe/Vienna", "UTC"]) @pytest.mark.parametrize("timezone", ["America/Regina", "Europe/Vienna", "UTC"])
@pytest.mark.freeze_time("2021-08-01 00:00:00+00:00") @pytest.mark.freeze_time("2021-08-01 00:00:00+00:00")
@ -1623,9 +1611,7 @@ def test_monthly_statistics_sum(
timezone, timezone,
) -> None: ) -> None:
"""Test monthly statistics.""" """Test monthly statistics."""
dt_util.set_default_time_zone(dt_util.get_time_zone(timezone)) hass = hass_recorder(timezone=timezone)
hass = hass_recorder()
wait_recording_done(hass) wait_recording_done(hass)
assert "Compiling statistics for" not in caplog.text assert "Compiling statistics for" not in caplog.text
assert "Statistics already compiled" not in caplog.text assert "Statistics already compiled" not in caplog.text
@ -1851,8 +1837,6 @@ def test_monthly_statistics_sum(
) )
assert stats == {} assert stats == {}
dt_util.set_default_time_zone(dt_util.get_time_zone("UTC"))
def test_cache_key_for_generate_statistics_during_period_stmt() -> None: def test_cache_key_for_generate_statistics_during_period_stmt() -> None:
"""Test cache key for _generate_statistics_during_period_stmt.""" """Test cache key for _generate_statistics_during_period_stmt."""
@ -1946,9 +1930,7 @@ def test_change(
timezone, timezone,
) -> None: ) -> None:
"""Test deriving change from sum statistic.""" """Test deriving change from sum statistic."""
dt_util.set_default_time_zone(dt_util.get_time_zone(timezone)) hass = hass_recorder(timezone=timezone)
hass = hass_recorder()
wait_recording_done(hass) wait_recording_done(hass)
assert "Compiling statistics for" not in caplog.text assert "Compiling statistics for" not in caplog.text
assert "Statistics already compiled" not in caplog.text assert "Statistics already compiled" not in caplog.text
@ -2273,8 +2255,6 @@ def test_change(
) )
assert stats == {} assert stats == {}
dt_util.set_default_time_zone(dt_util.get_time_zone("UTC"))
@pytest.mark.parametrize("timezone", ["America/Regina", "Europe/Vienna", "UTC"]) @pytest.mark.parametrize("timezone", ["America/Regina", "Europe/Vienna", "UTC"])
@pytest.mark.freeze_time("2022-10-01 00:00:00+00:00") @pytest.mark.freeze_time("2022-10-01 00:00:00+00:00")
@ -2288,9 +2268,7 @@ def test_change_with_none(
This tests the behavior when some record has None sum. The calculated change This tests the behavior when some record has None sum. The calculated change
is not expected to be correct, but we should not raise on this error. is not expected to be correct, but we should not raise on this error.
""" """
dt_util.set_default_time_zone(dt_util.get_time_zone(timezone)) hass = hass_recorder(timezone=timezone)
hass = hass_recorder()
wait_recording_done(hass) wait_recording_done(hass)
assert "Compiling statistics for" not in caplog.text assert "Compiling statistics for" not in caplog.text
assert "Statistics already compiled" not in caplog.text assert "Statistics already compiled" not in caplog.text
@ -2502,5 +2480,3 @@ def test_change_with_none(
types={"change"}, types={"change"},
) )
assert stats == {} assert stats == {}
dt_util.set_default_time_zone(dt_util.get_time_zone("UTC"))

View file

@ -1404,8 +1404,12 @@ def hass_recorder(
), ),
): ):
def setup_recorder(config: dict[str, Any] | None = None) -> HomeAssistant: def setup_recorder(
*, config: dict[str, Any] | None = None, timezone: str | None = None
) -> HomeAssistant:
"""Set up with params.""" """Set up with params."""
if timezone is not None:
hass.config.set_time_zone(timezone)
init_recorder_component(hass, config, recorder_db_url) init_recorder_component(hass, config, recorder_db_url)
hass.start() hass.start()
hass.block_till_done() hass.block_till_done()