Skip to content

gh-128438: Use EnvironmentVarGuard for datetimetester.py to manage environment varibales #130002

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 27, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions Lib/test/datetimetester.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Test the datetime module."""
import bisect
import contextlib
import copy
import decimal
import io
Expand All @@ -20,7 +21,7 @@

from test import support
from test.support import is_resource_enabled, ALWAYS_EQ, LARGEST, SMALLEST
from test.support import script_helper, warnings_helper
from test.support import os_helper, script_helper, warnings_helper

import datetime as datetime_module
from datetime import MINYEAR, MAXYEAR
Expand Down Expand Up @@ -6691,6 +6692,17 @@ def test_gaps(self):
ldt = tz.fromutc(udt.replace(tzinfo=tz))
self.assertEqual(ldt.fold, 0)

@classmethod
@contextlib.contextmanager
def _change_tz(cls, new_tzinfo):
try:
with os_helper.EnvironmentVarGuard() as env:
env["TZ"] = new_tzinfo
_time.tzset()
yield
finally:
_time.tzset()

@unittest.skipUnless(
hasattr(_time, "tzset"), "time module has no attribute tzset"
)
Expand All @@ -6705,18 +6717,15 @@ def test_system_transitions(self):
self.zonename.startswith('right/')):
self.skipTest("Skipping %s" % self.zonename)
tz = self.tz
TZ = os.environ.get('TZ')
os.environ['TZ'] = self.zonename
try:
_time.tzset()
with self._change_tz(self.zonename):
for udt, shift in tz.transitions():
if udt.year >= 2037:
# System support for times around the end of 32-bit time_t
# and later is flaky on many systems.
break
s0 = (udt - datetime(1970, 1, 1)) // SEC
ss = shift // SEC # shift seconds
for x in [-40 * 3600, -20*3600, -1, 0,
for x in [-40 * 3600, -20 * 3600, -1, 0,
ss - 1, ss + 20 * 3600, ss + 40 * 3600]:
s = s0 + x
sdt = datetime.fromtimestamp(s)
Expand All @@ -6735,12 +6744,6 @@ def test_system_transitions(self):
utc0 = dt.astimezone(timezone.utc)
utc1 = dt.replace(fold=1).astimezone(timezone.utc)
self.assertEqual(utc0, utc1 + timedelta(0, ss))
finally:
if TZ is None:
del os.environ['TZ']
else:
os.environ['TZ'] = TZ
_time.tzset()


class ZoneInfoCompleteTest(unittest.TestSuite):
Expand Down
Loading