Skip to content

Commit

Permalink
chore: replace pytz with zoneinfo
Browse files Browse the repository at this point in the history
  • Loading branch information
mfarhan943 committed Sep 24, 2024
1 parent ad23992 commit 8f61efd
Show file tree
Hide file tree
Showing 279 changed files with 1,139 additions and 1,110 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import datetime
import ddt
import pytz
from zoneinfo import ZoneInfo
from django.test import RequestFactory

from common.djangoapps.student.roles import CourseInstructorRole, CourseStaffRole
Expand All @@ -22,7 +22,7 @@ class CourseRunSerializerTests(ModuleStoreTestCase): # lint-amnesty, pylint: di
def setUp(self):
super().setUp()

self.course_start = datetime.datetime.now(pytz.UTC)
self.course_start = datetime.datetime.now(ZoneInfo("UTC"))
self.course_end = self.course_start + datetime.timedelta(days=30)

self.request = RequestFactory().get('')
Expand Down
16 changes: 8 additions & 8 deletions cms/djangoapps/api/v1/tests/test_views/test_course_runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from unittest.mock import patch # lint-amnesty, pylint: disable=unused-import

import ddt
import pytz
from zoneinfo import ZoneInfo
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import RequestFactory, override_settings
from django.urls import reverse
Expand Down Expand Up @@ -117,7 +117,7 @@ def test_update(self):
assert CourseAccessRole.objects.filter(course_id=course_run.id).count() == 0

url = reverse('api:v1:course_run-detail', kwargs={'pk': str(course_run.id)})
start = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
start = datetime.datetime.now(ZoneInfo("UTC")).replace(microsecond=0)
end = start + datetime.timedelta(days=30)
title = 'A New Testing Strategy'
user = UserFactory()
Expand Down Expand Up @@ -165,7 +165,7 @@ def test_update_with_pacing_type(self):
"""
Test that update run updates the pacing type
"""
start = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
start = datetime.datetime.now(ZoneInfo("UTC")).replace(microsecond=0)
course_run = CourseFactory(start=start, end=None, self_paced=False)
data = {
'pacing_type': 'self_paced',
Expand All @@ -183,7 +183,7 @@ def test_update_with_instructor_role(self):
Test that update creates a new instructor role only if it does not exist
"""
instructor_role = 'instructor'
start = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
start = datetime.datetime.now(ZoneInfo("UTC")).replace(microsecond=0)
new_user = UserFactory()
course_run = CourseFactory(start=start, end=None, self_paced=False)
assert CourseAccessRole.objects.filter(course_id=course_run.id).count() == 0
Expand Down Expand Up @@ -214,7 +214,7 @@ def test_update_with_multiple_roles(self):
"""
staff_role = 'staff'
instructor_role = 'instructor'
start = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
start = datetime.datetime.now(ZoneInfo("UTC")).replace(microsecond=0)
course_run = CourseFactory(start=start, end=None, self_paced=False)

existing_user = UserFactory()
Expand Down Expand Up @@ -255,7 +255,7 @@ def test_update_with_multiple_roles(self):
def test_create(self, pacing_type, expected_self_paced_value):
"""Tests successful course run creation"""
user = UserFactory()
start = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
start = datetime.datetime.now(ZoneInfo("UTC")).replace(microsecond=0)
end = start + datetime.timedelta(days=30)
role = 'staff'
data = self.get_course_run_data(user, start, end, pacing_type, role)
Expand All @@ -280,7 +280,7 @@ def test_create_with_invalid_course_team(self):
with expected validation message
"""
user = UserFactory()
start = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
start = datetime.datetime.now(ZoneInfo("UTC")).replace(microsecond=0)
end = start + datetime.timedelta(days=30)
data = self.get_course_run_data(user, start, end, 'self-paced')
data['team'] = [{'user': 'invalid-username'}]
Expand Down Expand Up @@ -334,7 +334,7 @@ def test_rerun(self, pacing_type, expected_self_paced_value, number):
'short_name': original_course_run.id.org, # lint-amnesty, pylint: disable=no-member
'description': 'Testing Organization Description',
})
start = datetime.datetime.now(pytz.UTC).replace(microsecond=0)
start = datetime.datetime.now(ZoneInfo("UTC")).replace(microsecond=0)
end = start + datetime.timedelta(days=30)
user = UserFactory()
role = 'instructor'
Expand Down
18 changes: 9 additions & 9 deletions cms/djangoapps/contentstore/api/views/course_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging

import dateutil
from pytz import UTC
from zoneinfo import ZoneInfo
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

Expand Down Expand Up @@ -255,34 +255,34 @@ def _get_open_responses(self, course, graded_only):

def _has_date_before_start(self, ora, start): # lint-amnesty, pylint: disable=missing-function-docstring
if ora.submission_start:
if dateutil.parser.parse(ora.submission_start).replace(tzinfo=UTC) < start:
if dateutil.parser.parse(ora.submission_start).replace(tzinfo=ZoneInfo("UTC")) < start:
return True
if ora.submission_due:
if dateutil.parser.parse(ora.submission_due).replace(tzinfo=UTC) < start:
if dateutil.parser.parse(ora.submission_due).replace(tzinfo=ZoneInfo("UTC")) < start:
return True
for assessment in ora.rubric_assessments:
if assessment['start']:
if dateutil.parser.parse(assessment['start']).replace(tzinfo=UTC) < start:
if dateutil.parser.parse(assessment['start']).replace(tzinfo=ZoneInfo("UTC")) < start:
return True
if assessment['due']:
if dateutil.parser.parse(assessment['due']).replace(tzinfo=UTC) < start:
if dateutil.parser.parse(assessment['due']).replace(tzinfo=ZoneInfo("UTC")) < start:
return True

return False

def _has_date_after_end(self, ora, end): # lint-amnesty, pylint: disable=missing-function-docstring
if ora.submission_start:
if dateutil.parser.parse(ora.submission_start).replace(tzinfo=UTC) > end:
if dateutil.parser.parse(ora.submission_start).replace(tzinfo=ZoneInfo("UTC")) > end:
return True
if ora.submission_due:
if dateutil.parser.parse(ora.submission_due).replace(tzinfo=UTC) > end:
if dateutil.parser.parse(ora.submission_due).replace(tzinfo=ZoneInfo("UTC")) > end:
return True
for assessment in ora.rubric_assessments:
if assessment['start']:
if dateutil.parser.parse(assessment['start']).replace(tzinfo=UTC) > end:
if dateutil.parser.parse(assessment['start']).replace(tzinfo=ZoneInfo("UTC")) > end:
return True
if assessment['due']:
if dateutil.parser.parse(assessment['due']).replace(tzinfo=UTC) > end:
if dateutil.parser.parse(assessment['due']).replace(tzinfo=ZoneInfo("UTC")) > end:
return True
return False

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from datetime import datetime, timedelta

from django.core.management import CommandError, call_command
import pytz
from zoneinfo import ZoneInfo

from cms.djangoapps.contentstore.models import CleanStaleCertificateAvailabilityDatesConfig
from openedx.core.lib.courses import get_course_by_id
Expand All @@ -26,7 +26,7 @@ def setUp(self):
self.instructor_paced_course1 = CourseFactory()

# set the self-paced courses to self-paced, create and insert an invalid certificate available date for them
self.certificate_available_date = datetime.now(pytz.UTC) + timedelta(days=30)
self.certificate_available_date = datetime.now(ZoneInfo("UTC")) + timedelta(days=30)
self.self_paced_course1.self_paced = True
self.self_paced_course1.certificate_available_date = self.certificate_available_date
self.self_paced_course2.self_paced = True
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from unittest.mock import patch

import ddt
import pytz
from zoneinfo import ZoneInfo
from django.conf import settings
from django.test import override_settings
from django.urls import reverse
Expand Down Expand Up @@ -43,7 +43,7 @@ def setUp(self):
display_name="Demo Course (Sample)",
id=archived_course_key,
org=archived_course_key.org,
end=(datetime.now() - timedelta(days=365)).replace(tzinfo=pytz.UTC),
end=(datetime.now() - timedelta(days=365)).replace(tzinfo=ZoneInfo("UTC")),
)

def test_home_page_response(self):
Expand Down
8 changes: 4 additions & 4 deletions cms/djangoapps/contentstore/signals/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from opaque_keys.edx.keys import CourseKey
from openedx_events.content_authoring.data import CourseCatalogData, CourseScheduleData
from openedx_events.content_authoring.signals import COURSE_CATALOG_INFO_CHANGED
from pytz import UTC
from zoneinfo import ZoneInfo

from cms.djangoapps.contentstore.courseware_index import (
CourseAboutSearchIndexer,
Expand Down Expand Up @@ -145,8 +145,8 @@ def listen_for_course_publish(sender, course_key, **kwargs): # pylint: disable=

# Kick off a courseware indexing action after the data is ready
if CoursewareSearchIndexer.indexing_is_enabled() and CourseAboutSearchIndexer.indexing_is_enabled():
transaction.on_commit(lambda: update_search_index.delay(course_key_str, datetime.now(UTC).isoformat()))

transaction.on_commit(lambda: update_search_index.delay(
course_key_str, datetime.now(ZoneInfo("UTC")).isoformat()))
update_discussions_settings_from_course_task.apply_async(
args=[course_key_str],
countdown=settings.DISCUSSION_SETTINGS['COURSE_PUBLISH_TASK_DELAY'],
Expand Down Expand Up @@ -175,7 +175,7 @@ def listen_for_library_update(sender, library_key, **kwargs): # pylint: disable
# import here, because signal is registered at startup, but items in tasks are not yet able to be loaded
from cms.djangoapps.contentstore.tasks import update_library_index

update_library_index.delay(str(library_key), datetime.now(UTC).isoformat())
update_library_index.delay(str(library_key), datetime.now(ZoneInfo("UTC")).isoformat())


@receiver(SignalHandler.item_deleted)
Expand Down
4 changes: 2 additions & 2 deletions cms/djangoapps/contentstore/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
from organizations.exceptions import InvalidOrganizationException
from organizations.models import Organization, OrganizationCourse
from path import Path as path
from pytz import UTC
from zoneinfo import ZoneInfo
from user_tasks.models import UserTaskArtifact, UserTaskStatus
from user_tasks.tasks import UserTask

Expand Down Expand Up @@ -197,7 +197,7 @@ def _parse_time(time_isoformat):
# remove the +00:00 from the end of the formats generated within the system
time_isoformat.split('+')[0],
"%Y-%m-%dT%H:%M:%S.%f"
).replace(tzinfo=UTC)
).replace(tzinfo=ZoneInfo("UTC"))


@shared_task
Expand Down
20 changes: 10 additions & 10 deletions cms/djangoapps/contentstore/tests/test_course_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from edx_toggles.toggles.testutils import override_waffle_flag
from milestones.models import MilestoneRelationshipType
from milestones.tests.utils import MilestonesTestCaseMixin
from pytz import UTC
from zoneinfo import ZoneInfo

from cms.djangoapps.contentstore.utils import reverse_course_url, reverse_usage_url
from cms.djangoapps.models.settings.course_grading import (
Expand Down Expand Up @@ -75,7 +75,7 @@ def test_pre_1900_date(self):
doesn't work for these dates.
"""
details = CourseDetails.fetch(self.course.id)
pre_1900 = datetime.datetime(1564, 4, 23, 1, 1, 1, tzinfo=UTC)
pre_1900 = datetime.datetime(1564, 4, 23, 1, 1, 1, tzinfo=ZoneInfo("UTC"))
details.enrollment_start = pre_1900
dumped_jsondetails = json.dumps(details, cls=CourseSettingsEncoder)
loaded_jsondetails = json.loads(dumped_jsondetails)
Expand All @@ -88,7 +88,7 @@ def test_ooc_encoder(self):
details = {
'number': 1,
'string': 'string',
'datetime': datetime.datetime.now(UTC)
'datetime': datetime.datetime.now(ZoneInfo("UTC"))
}
jsondetails = json.dumps(details, cls=CourseSettingsEncoder)
jsondetails = json.loads(jsondetails)
Expand Down Expand Up @@ -116,7 +116,6 @@ def setUp(self):

@override_settings(FEATURES={'DISABLE_MOBILE_COURSE_AVAILABLE': True})
def test_mobile_field_available(self):

"""
Test to check `Mobile Course Available` field is not viewable in Studio
when DISABLE_MOBILE_COURSE_AVAILABLE is true.
Expand Down Expand Up @@ -235,12 +234,13 @@ def test_update_and_fetch(self):
resp = self.client.get_json(url)
self.compare_details_with_encoding(json.loads(resp.content.decode('utf-8')), details.__dict__, "virgin get")

self.alter_field(url, details, 'start_date', datetime.datetime(2012, 11, 12, 1, 30, tzinfo=UTC))
self.alter_field(url, details, 'start_date', datetime.datetime(2012, 11, 1, 13, 30, tzinfo=UTC))
self.alter_field(url, details, 'end_date', datetime.datetime(2013, 2, 12, 1, 30, tzinfo=UTC))
self.alter_field(url, details, 'enrollment_start', datetime.datetime(2012, 10, 12, 1, 30, tzinfo=UTC))
self.alter_field(url, details, 'start_date', datetime.datetime(2012, 11, 12, 1, 30, tzinfo=ZoneInfo("UTC")))
self.alter_field(url, details, 'start_date', datetime.datetime(2012, 11, 1, 13, 30, tzinfo=ZoneInfo("UTC")))
self.alter_field(url, details, 'end_date', datetime.datetime(2013, 2, 12, 1, 30, tzinfo=ZoneInfo("UTC")))
self.alter_field(url, details, 'enrollment_start', datetime.datetime(
2012, 10, 12, 1, 30, tzinfo=ZoneInfo("UTC")))

self.alter_field(url, details, 'enrollment_end', datetime.datetime(2012, 11, 15, 1, 30, tzinfo=UTC))
self.alter_field(url, details, 'enrollment_end', datetime.datetime(2012, 11, 15, 1, 30, tzinfo=ZoneInfo("UTC")))
self.alter_field(url, details, 'short_description', "Short Description")
self.alter_field(url, details, 'about_sidebar_html', "About Sidebar HTML")
self.alter_field(url, details, 'overview', "Overview")
Expand Down Expand Up @@ -1470,7 +1470,7 @@ def test_validate_update_does_not_allow_proctoring_provider_changes_after_course
Only admin users may update the provider if the course has started.
"""
field_name = "proctoring_provider"
course = CourseFactory.create(start=datetime.datetime.now(UTC) - datetime.timedelta(days=1))
course = CourseFactory.create(start=datetime.datetime.now(ZoneInfo("UTC")) - datetime.timedelta(days=1))
user = UserFactory.create(is_staff=staff_user)

did_validate, errors, test_model = CourseMetadata.validate_and_update_from_json(
Expand Down
Loading

0 comments on commit 8f61efd

Please sign in to comment.