From c69bd39502f33c4124863761e078b07e5020b3dd Mon Sep 17 00:00:00 2001 From: Adam Johnson Date: Tue, 19 Sep 2023 11:19:05 +0100 Subject: [PATCH] Tidy tests to use change_local_timezone() Added in #306. --- tests/test_time_machine.py | 42 +++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/tests/test_time_machine.py b/tests/test_time_machine.py index f1bf612..fe98fb7 100644 --- a/tests/test_time_machine.py +++ b/tests/test_time_machine.py @@ -1,13 +1,13 @@ from __future__ import annotations import asyncio -import contextlib import datetime as dt import os import sys import time import typing import uuid +from contextlib import contextmanager from importlib.util import module_from_spec from importlib.util import spec_from_file_location from unittest import mock @@ -38,6 +38,21 @@ ) +@contextmanager +def change_local_timezone(local_tz: str | None) -> typing.Iterator[None]: + orig_tz = os.environ["TZ"] + if local_tz: + os.environ["TZ"] = local_tz + else: + del os.environ["TZ"] + time.tzset() + try: + yield + finally: + os.environ["TZ"] = orig_tz + time.tzset() + + @pytest.mark.skipif( not hasattr(time, "CLOCK_REALTIME"), reason="No time.CLOCK_REALTIME" ) @@ -403,22 +418,15 @@ def test_destination_datetime_tzinfo_zoneinfo_nested(): def test_destination_datetime_tzinfo_zoneinfo_no_orig_tz(): - orig_tz = os.environ["TZ"] - del os.environ["TZ"] - time.tzset() - orig_tzname = time.tzname - - try: + with change_local_timezone(None): + orig_tzname = time.tzname dest = LIBRARY_EPOCH_DATETIME.replace(tzinfo=ZoneInfo("Africa/Addis_Ababa")) + with time_machine.travel(dest): assert time.tzname == ("EAT", "EAT") assert time.tzname == orig_tzname - finally: - os.environ["TZ"] = orig_tz - time.tzset() - def test_destination_datetime_tzinfo_zoneinfo_windows(): orig_timezone = time.timezone @@ -469,18 +477,6 @@ def test_destination_string(): assert time.time() == EPOCH + 60.0 -@contextlib.contextmanager -def change_local_timezone(local_tz: str) -> typing.Iterator[None]: - orig_tz = os.environ["TZ"] - os.environ["TZ"] = local_tz - time.tzset() - try: - yield - finally: - os.environ["TZ"] = orig_tz - time.tzset() - - @pytest.mark.parametrize( ["local_tz", "expected_offset"], [