test: fix timezone_not_near_midnight not to use pytz (#4678)

This commit is contained in:
Jennifer Richards 2022-10-28 18:19:08 -03:00 committed by GitHub
parent b6b2902857
commit 9752fabf85
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 10 deletions

View file

@ -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()

View file

@ -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')