Skip to content
Merged
Show file tree
Hide file tree
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
12 changes: 6 additions & 6 deletions ietf/utils/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -508,12 +508,12 @@ def test_timezone_not_near_midnight(self, mock):

# 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()
11 changes: 7 additions & 4 deletions ietf/utils/timezone.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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')
Expand Down