From 9752fabf85d6fa4f3de416954ed0b0406d563301 Mon Sep 17 00:00:00 2001 From: Jennifer Richards Date: Fri, 28 Oct 2022 18:19:08 -0300 Subject: [PATCH] test: fix timezone_not_near_midnight not to use pytz (#4678) --- ietf/utils/tests.py | 12 ++++++------ ietf/utils/timezone.py | 11 +++++++---- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/ietf/utils/tests.py b/ietf/utils/tests.py index 4814235f6..7051cdec6 100644 --- a/ietf/utils/tests.py +++ b/ietf/utils/tests.py @@ -491,13 +491,13 @@ class TimezoneTests(TestCase): def test_timezone_not_near_midnight(self, mock): # give it several choices that should be rejected and one that should be accepted with patch( - 'ietf.utils.timezone.pytz.common_timezones', - [ + 'ietf.utils.timezone.available_timezones', + return_value=set([ 'America/Chicago', # time is 23:15, should be rejected 'America/Lima', # time is 23:15, should be rejected 'America/New_York', # time is 00:15, should be rejected 'Europe/Riga', # time is 07:15, acceptable - ], + ]), ): # check a few times (will pass by chance < 0.1% of the time) self.assertEqual(timezone_not_near_midnight(), 'Europe/Riga') @@ -508,12 +508,12 @@ class TimezoneTests(TestCase): # now give it no valid choice with patch( - 'ietf.utils.timezone.pytz.common_timezones', - [ + 'ietf.utils.timezone.available_timezones', + return_value=set([ 'America/Chicago', # time is 23:15, should be rejected 'America/Lima', # time is 23:15, should be rejected 'America/New_York', # time is 00:15, should be rejected - ], + ]), ): with self.assertRaises(RuntimeError): timezone_not_near_midnight() diff --git a/ietf/utils/timezone.py b/ietf/utils/timezone.py index 3d074bc79..bd7826d59 100644 --- a/ietf/utils/timezone.py +++ b/ietf/utils/timezone.py @@ -1,8 +1,9 @@ import datetime import random +import zoneinfo from typing import Union -from zoneinfo import ZoneInfo +from zoneinfo import available_timezones, ZoneInfo from django.conf import settings from django.utils import timezone @@ -89,15 +90,17 @@ def timezone_not_near_midnight(): Avoids midnight +/- 1 hour. Raises RuntimeError if it is unable to find a time zone satisfying this constraint. """ - timezone_options = pytz.common_timezones + timezone_options = list( + available_timezones().difference(['Factory', 'localtime']) # these two are not known to pytz + ) tzname = random.choice(timezone_options) - right_now = timezone.now().astimezone(pytz.timezone(tzname)) + right_now = timezone.now().astimezone(ZoneInfo(tzname)) # Avoid the remote possibility of an infinite loop (might come up # if there is a problem with the time zone library) tries_left = 20 while right_now.hour < 1 or right_now.hour >= 23: tzname = random.choice(timezone_options) - right_now = right_now.astimezone(pytz.timezone(tzname)) + right_now = right_now.astimezone(ZoneInfo(tzname)) tries_left -= 1 if tries_left <= 0: raise RuntimeError('Unable to find a time zone not near midnight')