Skip to content

Commit

Permalink
# This is a combination of 2 commits.
Browse files Browse the repository at this point in the history
# This is the 1st commit message:

BOM-2442
pyupgrade in course-duration

# This is the commit message #2:

Pyupgrade in openedx/features.
  • Loading branch information
awais786 committed Mar 17, 2021
1 parent 7d4f192 commit a4983a3
Show file tree
Hide file tree
Showing 16 changed files with 80 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from django.urls import reverse
from django.utils import timezone
from mock import patch
from unittest.mock import patch

from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.student.models import CourseEnrollment
Expand Down
2 changes: 1 addition & 1 deletion openedx/features/course_experience/api/v1/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
# URL for retrieving course deadlines info
urlpatterns += [
re_path(
r'v1/course_deadlines_info/{}'.format(settings.COURSE_KEY_PATTERN),
fr'v1/course_deadlines_info/{settings.COURSE_KEY_PATTERN}',
CourseDeadlinesMobileView.as_view(),
name='course-experience-course-deadlines-mobile'
),
Expand Down
2 changes: 1 addition & 1 deletion openedx/features/course_experience/course_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class HttpMethod(Enum):
PUT = 'PUT'


class CourseTool(object):
class CourseTool:
"""
This is an optional base class for Course Tool plugins.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class TestCourseDatesFragmentView(ModuleStoreTestCase):
"""Tests for the course dates fragment view."""

def setUp(self):
super(TestCourseDatesFragmentView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
with self.store.default_store(ModuleStoreEnum.Type.split):
self.course = CourseFactory.create(
org='edX',
Expand All @@ -35,7 +35,7 @@ def setUp(self):
self.dates_fragment_url = reverse(
'openedx.course_experience.mobile_dates_fragment_view',
kwargs={
'course_id': six.text_type(self.course.id)
'course_id': str(self.course.id)
}
)

Expand Down
28 changes: 13 additions & 15 deletions openedx/features/course_experience/tests/views/test_course_home.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
# coding=utf-8
"""
Tests for the course home page.
"""


from datetime import datetime, timedelta
from unittest import mock

import ddt
import mock
import six
from django.conf import settings
from django.http import QueryDict
Expand All @@ -21,8 +20,9 @@

from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.course_modes.tests.factories import CourseModeFactory
from common.djangoapps.util.date_utils import strftime_localized_html
from lms.djangoapps.experiments.models import ExperimentData
from common.djangoapps.student.models import CourseEnrollment, FBEEnrollmentExclusion
from common.djangoapps.student.tests.factories import UserFactory
from common.djangoapps.util.date_utils import strftime_localized, strftime_localized_html
from lms.djangoapps.commerce.models import CommerceConfiguration
from lms.djangoapps.commerce.utils import EcommerceService
from lms.djangoapps.course_goals.api import add_course_goal, remove_course_goal
Expand All @@ -37,6 +37,7 @@
from lms.djangoapps.courseware.tests.helpers import get_expiration_banner_text
from lms.djangoapps.courseware.utils import verified_upgrade_deadline_link
from lms.djangoapps.discussion.django_comment_client.tests.factories import RoleFactory
from lms.djangoapps.experiments.models import ExperimentData
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.django_comment_common.models import (
FORUM_ROLE_ADMINISTRATOR,
Expand All @@ -56,9 +57,6 @@
from openedx.features.course_experience.tests import BaseCourseUpdatesTestCase
from openedx.features.discounts.applicability import get_discount_expiration_date
from openedx.features.discounts.utils import REV1008_EXPERIMENT_ID, format_strikeout_price
from common.djangoapps.student.models import CourseEnrollment, FBEEnrollmentExclusion
from common.djangoapps.student.tests.factories import UserFactory
from common.djangoapps.util.date_utils import strftime_localized
from xmodule.course_module import COURSE_VISIBILITY_PRIVATE, COURSE_VISIBILITY_PUBLIC, COURSE_VISIBILITY_PUBLIC_OUTLINE
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import CourseUserType, ModuleStoreTestCase
Expand Down Expand Up @@ -94,7 +92,7 @@ def course_home_url(course):
Arguments:
course (CourseBlock): The course being tested.
"""
return course_home_url_from_string(six.text_type(course.id))
return course_home_url_from_string(str(course.id))


def course_home_url_from_string(course_key_string):
Expand Down Expand Up @@ -412,7 +410,7 @@ def test_first_purchase_offer_banner_display(self,
can_receive_discount_mock.return_value = applicability
discount_percentage_mock.return_value = percentage
user = self.create_user_for_course(self.course, CourseUserType.ENROLLED)
now_time = datetime.now(tz=UTC).strftime(u"%Y-%m-%d %H:%M:%S%z")
now_time = datetime.now(tz=UTC).strftime("%Y-%m-%d %H:%M:%S%z")
ExperimentData.objects.create(
user=user, experiment_id=REV1008_EXPERIMENT_ID, key=str(self.course.id), value=now_time
)
Expand All @@ -421,7 +419,7 @@ def test_first_purchase_offer_banner_display(self,
response = self.client.get(url)
expiration_date = strftime_localized_html(get_discount_expiration_date(user, self.course), 'SHORT_DATE')
upgrade_link = verified_upgrade_deadline_link(user=user, course=self.course)
bannerText = u'''<div class="first-purchase-offer-banner" role="note">
bannerText = '''<div class="first-purchase-offer-banner" role="note">
<span class="first-purchase-offer-banner-bold"><b>
Upgrade by {discount_expiration_date} and save {percentage}% [{strikeout_price}]</b></span>
<br>Use code <b>EDXWELCOME</b> at checkout! <a id="welcome" href="{upgrade_link}">Upgrade Now</a>
Expand Down Expand Up @@ -551,7 +549,7 @@ def test_expired_course(self):
expiration_date = strftime_localized(course.start + timedelta(weeks=4) + timedelta(days=1), 'SHORT_DATE')
expected_params = QueryDict(mutable=True)
course_name = CourseOverview.get_from_id(course.id).display_name_with_default
expected_params['access_response_error'] = u'Access to {run} expired on {expiration_date}'.format(
expected_params['access_response_error'] = 'Access to {run} expired on {expiration_date}'.format(
run=course_name,
expiration_date=expiration_date
)
Expand Down Expand Up @@ -633,14 +631,14 @@ def test_non_live_course_other_language(self, mock_strftime_localized):
future_course = self.create_future_course()
self.create_user_for_course(future_course, CourseUserType.ENROLLED)

fake_unicode_start_time = u"üñîçø∂é_ßtå®t_tîµé"
fake_unicode_start_time = "üñîçø∂é_ßtå®t_tîµé"
mock_strftime_localized.return_value = fake_unicode_start_time

url = course_home_url(future_course)
response = self.client.get(url)
expected_params = QueryDict(mutable=True)
expected_params['notlive'] = fake_unicode_start_time
expected_url = u'{url}?{params}'.format(
expected_url = '{url}?{params}'.format(
url=reverse('dashboard'),
params=expected_params.urlencode()
)
Expand Down Expand Up @@ -859,7 +857,7 @@ class CourseHomeFragmentViewTests(ModuleStoreTestCase):
CREATE_USER = False

def setUp(self):
super(CourseHomeFragmentViewTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
CommerceConfiguration.objects.create(checkout_on_ecommerce_service=True)

end = now() + timedelta(days=30)
Expand Down Expand Up @@ -898,7 +896,7 @@ def assert_upgrade_message_displayed(self): # lint-amnesty, pylint: disable=mis
self.assertContains(response, url)
self.assertContains(
response,
u"Upgrade (<span class='price'>${price}</span>)".format(price=self.verified_mode.min_price),
f"Upgrade (<span class='price'>${self.verified_mode.min_price}</span>)",
)

def test_no_upgrade_message_if_logged_out(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@

import datetime
import re
from unittest.mock import Mock, patch

import ddt
import six
from completion.waffle import ENABLE_COMPLETION_TRACKING_SWITCH
from completion.models import BlockCompletion
from completion.test_utils import CompletionWaffleTestMixin
from completion.waffle import ENABLE_COMPLETION_TRACKING_SWITCH
from django.contrib.sites.models import Site
from django.test import RequestFactory, override_settings
from django.urls import reverse
from django.utils import timezone
from edx_toggles.toggles.testutils import override_waffle_switch
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import Mock, patch
from opaque_keys.edx.keys import CourseKey, UsageKey
from pyquery import PyQuery as pq
from pytz import UTC
Expand All @@ -26,11 +26,13 @@

from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.course_modes.tests.factories import CourseModeFactory
from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.student.tests.factories import UserFactory
from lms.djangoapps.course_api.blocks.transformers.milestones import MilestonesAndSpecialExamsTransformer
from lms.djangoapps.gating import api as lms_gating_api
from lms.djangoapps.courseware.tests.factories import StaffFactory
from lms.djangoapps.courseware.tests.helpers import MasqueradeMixin
from lms.djangoapps.experiments.testutils import override_experiment_waffle_flag
from lms.djangoapps.gating import api as lms_gating_api
from lms.urls import RESET_COURSE_DEADLINES_NAME
from openedx.core.djangoapps.course_date_signals.models import SelfPacedRelativeDatesConfig
from openedx.core.djangoapps.schedules.models import Schedule
Expand All @@ -42,8 +44,6 @@
DEFAULT_COMPLETION_TRACKING_START,
CourseOutlineFragmentView
)
from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.student.tests.factories import UserFactory
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
Expand Down Expand Up @@ -72,7 +72,7 @@ def setUpClass(cls): # lint-amnesty, pylint: disable=super-method-not-called

# setUpClassAndTestData() already calls setUpClass on SharedModuleStoreTestCase
# pylint: disable=super-method-not-called
with super(TestCourseOutlinePage, cls).setUpClassAndTestData():
with super().setUpClassAndTestData():
cls.courses = []
course = CourseFactory.create(self_paced=True)
with cls.store.bulk_operations(course.id):
Expand Down Expand Up @@ -135,7 +135,7 @@ def setUp(self):
"""
Set up for the tests.
"""
super(TestCourseOutlinePage, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.client.login(username=self.user.username, password=TEST_PASSWORD)

@override_experiment_waffle_flag(RELATIVE_DATES_FLAG, active=True)
Expand All @@ -161,7 +161,7 @@ def test_outline_details(self):
self.assertContains(response, sequential['display_name'])
if sequential['graded']:
print(sequential)
self.assertContains(response, sequential['due'].strftime(u'%Y-%m-%d %H:%M:%S'))
self.assertContains(response, sequential['due'].strftime('%Y-%m-%d %H:%M:%S'))
self.assertContains(response, sequential['format'])
assert sequential['children']

Expand Down Expand Up @@ -289,7 +289,7 @@ def setUpClass(cls):
cls.PREREQ_REQUIRED = '(Prerequisite required)'
cls.UNLOCKED = 'Unlocked'

with super(TestCourseOutlinePageWithPrerequisites, cls).setUpClassAndTestData():
with super().setUpClassAndTestData():
cls.course, cls.course_blocks = cls.create_test_course()

@classmethod
Expand Down Expand Up @@ -340,7 +340,7 @@ def setUp(self):
"""
Set up for the tests.
"""
super(TestCourseOutlinePageWithPrerequisites, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.client.login(username=self.user.username, password=TEST_PASSWORD)

def setup_gated_section(self, gated_block, gating_block):
Expand All @@ -351,7 +351,7 @@ def setup_gated_section(self, gated_block, gating_block):
gating_block: (The prerequisite) The block that must be completed to get access to the gated block
"""

gating_api.add_prerequisite(self.course.id, six.text_type(gating_block.location))
gating_api.add_prerequisite(self.course.id, str(gating_block.location))
gating_api.set_required_content(self.course.id, gated_block.location, gating_block.location, 100)

def test_content_locked(self):
Expand Down Expand Up @@ -438,7 +438,7 @@ def setUpClass(cls):
"""
# setUpClassAndTestData() already calls setUpClass on SharedModuleStoreTestCase
# pylint: disable=super-method-not-called
with super(TestCourseOutlineResumeCourse, cls).setUpClassAndTestData():
with super().setUpClassAndTestData():
cls.course = cls.create_test_course()

@classmethod
Expand Down Expand Up @@ -480,7 +480,7 @@ def setUp(self):
"""
Set up for the tests.
"""
super(TestCourseOutlineResumeCourse, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.client.login(username=self.user.username, password=TEST_PASSWORD)

def visit_sequential(self, course, chapter, sequential):
Expand All @@ -490,7 +490,7 @@ def visit_sequential(self, course, chapter, sequential):
last_accessed_url = reverse(
'courseware_section',
kwargs={
'course_id': text_type(course.id),
'course_id': str(course.id),
'chapter': chapter.url_name,
'section': sequential.url_name,
}
Expand All @@ -504,7 +504,7 @@ def complete_sequential(self, course, sequential):
"""
course_key = CourseKey.from_string(str(course.id))
# Fake a visit to sequence2/vertical2
block_key = UsageKey.from_string(six.text_type(sequential.location))
block_key = UsageKey.from_string(str(sequential.location))
if block_key.course_key.run is None:
# Old mongo keys must be annotated with course run info before calling submit_completion:
block_key = block_key.replace(course_key=course_key)
Expand Down Expand Up @@ -565,7 +565,7 @@ def test_start_course(self):
content = pq(response.content)

vertical = course.children[0].children[0].children[0]
assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical.url_name))
assert content('.action-resume-course').attr('href').endswith('/vertical/' + vertical.url_name)

@override_settings(LMS_BASE='test_url:9999')
def test_resume_course_with_completion_api(self):
Expand All @@ -585,15 +585,15 @@ def test_resume_course_with_completion_api(self):

# Test for 'resume' link URL - should be vertical 1
content = pq(response.content)
assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical1.url_name))
assert content('.action-resume-course').attr('href').endswith('/vertical/' + vertical1.url_name)

self.complete_sequential(self.course, vertical2)
# Test for 'resume' link
response = self.visit_course_home(course, resume_count=1)

# Test for 'resume' link URL - should be vertical 2
content = pq(response.content)
assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical2.url_name))
assert content('.action-resume-course').attr('href').endswith('/vertical/' + vertical2.url_name)

# visit sequential 1, make sure 'Resume Course' URL is robust against 'Last Visited'
# (even though I visited seq1/vert1, 'Resume Course' still points to seq2/vert2)
Expand All @@ -602,7 +602,7 @@ def test_resume_course_with_completion_api(self):
# Test for 'resume' link URL - should be vertical 2 (last completed block, NOT last visited)
response = self.visit_course_home(course, resume_count=1)
content = pq(response.content)
assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical2.url_name))
assert content('.action-resume-course').attr('href').endswith('/vertical/' + vertical2.url_name)

def test_resume_course_deleted_sequential(self):
"""
Expand All @@ -628,7 +628,7 @@ def test_resume_course_deleted_sequential(self):
response = self.visit_course_home(course, resume_count=1)

content = pq(response.content)
assert content('.action-resume-course').attr('href').endswith(('/sequential/' + sequential2.url_name))
assert content('.action-resume-course').attr('href').endswith('/sequential/' + sequential2.url_name)

def test_resume_course_deleted_sequentials(self):
"""
Expand Down Expand Up @@ -666,7 +666,7 @@ def test_course_home_for_global_staff(self):
response = self.visit_course_home(course, start_count=1, resume_count=0)
content = pq(response.content)
vertical = course.children[0].children[0].children[0]
assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical.url_name))
assert content('.action-resume-course').attr('href').endswith('/vertical/' + vertical.url_name)

@override_waffle_switch(ENABLE_COMPLETION_TRACKING_SWITCH, active=True)
def test_course_outline_auto_open(self):
Expand All @@ -688,10 +688,10 @@ def get_sequential_button(url, is_hidden):
chapter2 = course.children[1]

response_content = self.client.get(course_home_url(course)).content
stripped_response = text_type(re.sub(b"\\s+", b"", response_content), "utf-8")
stripped_response = str(re.sub(b"\\s+", b"", response_content), "utf-8")

assert get_sequential_button(text_type(chapter1.location), False) in stripped_response
assert get_sequential_button(text_type(chapter2.location), True) in stripped_response
assert get_sequential_button(str(chapter1.location), False) in stripped_response
assert get_sequential_button(str(chapter2.location), True) in stripped_response

content = pq(response_content)
button = content('#expand-collapse-outline-all-button')
Expand Down
Loading

0 comments on commit a4983a3

Please sign in to comment.