8000 gh-128438: Use `EnvironmentVarGuard` for `datetimetester.py` to manag… · python/cpython@a096a41 · GitHub
[go: up one dir, main page]

Skip to content

Commit a096a41

Browse files
authored
gh-128438: Use EnvironmentVarGuard for datetimetester.py to manage environment varibales (#130002)
1 parent 9b83670 commit a096a41

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

Lib/test/datetimetester.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Test the datetime module."""
22
import bisect
3+
import contextlib
34
import copy
45
import decimal
56
import io
@@ -20,7 +21,7 @@
2021

2122
from test import support
2223
from test.support import is_resource_enabled, ALWAYS_EQ, LARGEST, SMALLE 8000 ST
23-
from test.support import script_helper, warnings_helper
24+
from test.support import os_helper, script_helper, warnings_helper
2425

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

6695+
@classmethod
6696+
@contextlib.contextmanager
6697+
def _change_tz(cls, new_tzinfo):
6698+
try:
6699+
with os_helper.EnvironmentVarGuard() as env:
6700+
env["TZ"] = new_tzinfo
6701+
_time.tzset()
6702+
yield
6703+
finally:
6704+
_time.tzset()
6705+
66946706
@unittest.skipUnless(
66956707
hasattr(_time, "tzset"), "time module has no attribute tzset"
66966708
)
@@ -6705,18 +6717,15 @@ def test_system_transitions(self):
67056717
self.zonename.startswith('right/')):
67066718
self.skipTest("Skipping %s" % self.zonename)
67076719
tz = self.tz
6708-
TZ = os.environ.get('TZ')
6709-
os.environ['TZ'] = self.zonename
6710-
try:
6711-
_time.tzset()
6720+
with self._change_tz(self.zonename):
67126721
for udt, shift in tz.transitions():
67136722
if udt.year >= 2037:
67146723
# System support for times around the end of 32-bit time_t
67156724
# and later is flaky on many systems.
67166725
break
67176726
s0 = (udt - datetime(1970, 1, 1)) // SEC
67186727
ss = shift // SEC # shift seconds
6719-
for x in [-40 * 3600, -20*3600, -1, 0,
6728+
for x in [-40 * 3600, -20 * 3600, -1, 0,
67206729
ss - 1, ss + 20 * 3600, ss + 40 * 3600]:
67216730
s = s0 + x
67226731
sdt = datetime.fromtimestamp(s)
@@ -6735,12 +6744,6 @@ def test_system_transitions(self):
67356744
utc0 = dt.astimezone(timezone.utc)
67366745
utc1 = dt.replace(fold=1).astimezone(timezone.utc)
67376746
self.assertEqual(utc0, utc1 + timedelta(0, ss))
6738-
finally:
6739-
if TZ is None:
6740-
del os.environ['TZ']
6741-
else:
6742-
os.environ['TZ'] = TZ
6743-
_time.tzset()
67446747

67456748

67466749
class ZoneInfoCompleteTest(unittest.TestSuite):

0 commit comments

Comments
 (0)
0