From c8902bed58a072e774ae532d1982aee4fec2f9b9 Mon Sep 17 00:00:00 2001 From: "M. Zulqarnain" Date: Tue, 16 Mar 2021 14:15:01 +0500 Subject: [PATCH] refactor: pyupgrade in heartbeat, lang_pref, models (#26916) --- .../djangoapps/heartbeat/default_checks.py | 23 +++++++++---------- .../core/djangoapps/heartbeat/runchecks.py | 4 ++-- .../heartbeat/tests/test_heartbeat.py | 4 ++-- openedx/core/djangoapps/heartbeat/views.py | 5 ++-- openedx/core/djangoapps/lang_pref/api.py | 1 - .../core/djangoapps/lang_pref/middleware.py | 2 +- .../djangoapps/lang_pref/tests/test_api.py | 14 +++++------ .../lang_pref/tests/test_middleware.py | 7 +++--- .../djangoapps/lang_pref/tests/test_views.py | 2 +- openedx/core/djangoapps/lang_pref/views.py | 4 +--- .../core/djangoapps/models/config/waffle.py | 2 +- .../core/djangoapps/models/course_details.py | 8 +++---- .../models/tests/test_course_details.py | 4 ++-- 13 files changed, 36 insertions(+), 44 deletions(-) diff --git a/openedx/core/djangoapps/heartbeat/default_checks.py b/openedx/core/djangoapps/heartbeat/default_checks.py index d07ca41d31..e976231fdb 100644 --- a/openedx/core/djangoapps/heartbeat/default_checks.py +++ b/openedx/core/djangoapps/heartbeat/default_checks.py @@ -8,7 +8,6 @@ Other checks should be included in their respective modules/djangoapps from datetime import datetime, timedelta from time import sleep, time -import six from django.conf import settings from django.core.cache import cache from django.db import connection @@ -39,9 +38,9 @@ def check_modulestore(): try: #@TODO Do we want to parse the output for split and mongo detail and return it? modulestore().heartbeat() - return 'modulestore', True, u'OK' + return 'modulestore', True, 'OK' except HeartbeatFailure as fail: - return 'modulestore', False, six.text_type(fail) + return 'modulestore', False, str(fail) def check_database(): @@ -56,9 +55,9 @@ def check_database(): try: cursor.execute("SELECT 1") cursor.fetchone() - return 'sql', True, u'OK' + return 'sql', True, 'OK' except DatabaseError as fail: - return 'sql', False, six.text_type(fail) + return 'sql', False, str(fail) # Caching @@ -76,9 +75,9 @@ def check_cache_set(): """ try: cache.set(CACHE_KEY, CACHE_VALUE, 30) - return 'cache_set', True, u'OK' + return 'cache_set', True, 'OK' except Exception as fail: # lint-amnesty, pylint: disable=broad-except - return 'cache_set', False, six.text_type(fail) + return 'cache_set', False, str(fail) def check_cache_get(): @@ -92,11 +91,11 @@ def check_cache_get(): try: data = cache.get(CACHE_KEY) if data == CACHE_VALUE: - return 'cache_get', True, u'OK' + return 'cache_get', True, 'OK' else: - return 'cache_get', False, u'value check failed' + return 'cache_get', False, 'value check failed' except Exception as fail: # lint-amnesty, pylint: disable=broad-except - return 'cache_get', False, six.text_type(fail) + return 'cache_get', False, str(fail) # Celery @@ -117,8 +116,8 @@ def check_celery(): while expires > datetime.now(): if task.ready() and task.result: finished = str(time() - now) - return 'celery', True, six.text_type({'time': finished}) + return 'celery', True, str({'time': finished}) sleep(0.25) return 'celery', False, "expired" except Exception as fail: # lint-amnesty, pylint: disable=broad-except - return 'celery', False, six.text_type(fail) + return 'celery', False, str(fail) diff --git a/openedx/core/djangoapps/heartbeat/runchecks.py b/openedx/core/djangoapps/heartbeat/runchecks.py index f0a0406735..0bf0c2563b 100644 --- a/openedx/core/djangoapps/heartbeat/runchecks.py +++ b/openedx/core/djangoapps/heartbeat/runchecks.py @@ -35,7 +35,7 @@ def runchecks(include_extended=False): 'message': message } except ImportError as e: - raise ImproperlyConfigured(u'Error importing module %s: "%s"' % (module, e)) # lint-amnesty, pylint: disable=raise-missing-from + raise ImproperlyConfigured(f'Error importing module {module}: "{e}"') # lint-amnesty, pylint: disable=raise-missing-from except AttributeError: - raise ImproperlyConfigured(u'Module "%s" does not define a "%s" callable' % (module, attr)) # lint-amnesty, pylint: disable=raise-missing-from + raise ImproperlyConfigured(f'Module "{module}" does not define a "{attr}" callable') # lint-amnesty, pylint: disable=raise-missing-from return response_dict diff --git a/openedx/core/djangoapps/heartbeat/tests/test_heartbeat.py b/openedx/core/djangoapps/heartbeat/tests/test_heartbeat.py index 90e20bd17b..b83cd1e629 100644 --- a/openedx/core/djangoapps/heartbeat/tests/test_heartbeat.py +++ b/openedx/core/djangoapps/heartbeat/tests/test_heartbeat.py @@ -4,11 +4,11 @@ Test the heartbeat import json +from unittest.mock import patch from django.db.utils import DatabaseError from django.test.client import Client from django.urls import reverse -from mock import patch from xmodule.exceptions import HeartbeatFailure from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase @@ -22,7 +22,7 @@ class HeartbeatTestCase(ModuleStoreTestCase): def setUp(self): self.client = Client() self.heartbeat_url = reverse('heartbeat') - return super(HeartbeatTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + return super().setUp() def test_success(self): response = self.client.get(self.heartbeat_url + '?extended') diff --git a/openedx/core/djangoapps/heartbeat/views.py b/openedx/core/djangoapps/heartbeat/views.py index 23fd38df3e..a3615a269e 100644 --- a/openedx/core/djangoapps/heartbeat/views.py +++ b/openedx/core/djangoapps/heartbeat/views.py @@ -4,7 +4,6 @@ Views for verifying the health (heartbeat) of the app. import logging -import six from common.djangoapps.util.json_request import JsonResponse @@ -30,9 +29,9 @@ def heartbeat(request): status_code = 503 # 503 on any failure except Exception as e: # lint-amnesty, pylint: disable=broad-except status_code = 503 - check_results = {'error': six.text_type(e)} + check_results = {'error': str(e)} if status_code == 503: - log.error(u'Heartbeat check failed (%s): %s', status_code, check_results) + log.error('Heartbeat check failed (%s): %s', status_code, check_results) return JsonResponse(check_results, status=status_code) diff --git a/openedx/core/djangoapps/lang_pref/api.py b/openedx/core/djangoapps/lang_pref/api.py index 8f8f10234d..2874f02c2e 100644 --- a/openedx/core/djangoapps/lang_pref/api.py +++ b/openedx/core/djangoapps/lang_pref/api.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Python API for language and translation management. """ diff --git a/openedx/core/djangoapps/lang_pref/middleware.py b/openedx/core/djangoapps/lang_pref/middleware.py index b0f88f0166..e00dca0e0d 100644 --- a/openedx/core/djangoapps/lang_pref/middleware.py +++ b/openedx/core/djangoapps/lang_pref/middleware.py @@ -40,7 +40,7 @@ class LanguagePreferenceMiddleware(MiddlewareMixin): # Promote the cookie_lang over any language currently in the accept header current_langs = [(lang, qvalue) for (lang, qvalue) in current_langs if lang != cookie_lang] current_langs.insert(0, (cookie_lang, 1)) - accept_header = ",".join("{};q={}".format(lang, qvalue) for (lang, qvalue) in current_langs) + accept_header = ",".join(f"{lang};q={qvalue}" for (lang, qvalue) in current_langs) else: accept_header = cookie_lang request.META[LANGUAGE_HEADER] = accept_header diff --git a/openedx/core/djangoapps/lang_pref/tests/test_api.py b/openedx/core/djangoapps/lang_pref/tests/test_api.py index 3bd51346b0..a91a424b9b 100644 --- a/openedx/core/djangoapps/lang_pref/tests/test_api.py +++ b/openedx/core/djangoapps/lang_pref/tests/test_api.py @@ -1,20 +1,18 @@ -# -*- coding: utf-8 -*- """ Tests for the language API. """ - +from unittest.mock import patch import ddt from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.test.utils import override_settings from django.utils import translation -from mock import patch from openedx.core.djangoapps.dark_lang.models import DarkLangConfig from openedx.core.djangoapps.lang_pref import api as language_api from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration_context from openedx.core.djangolib.testing.utils import CacheIsolationTestCase EN = language_api.Language('en', 'English') -ES_419 = language_api.Language('es-419', u'Español (Latinoamérica)') -LT_LT = language_api.Language('lt-lt', u'Lietuvių (Lietuva)') +ES_419 = language_api.Language('es-419', 'Español (Latinoamérica)') +LT_LT = language_api.Language('lt-lt', 'Lietuvių (Lietuva)') @ddt.ddt @@ -85,7 +83,7 @@ class LanguageApiTest(CacheIsolationTestCase): released_languages = language_api.released_languages() assert released_languages == expected_languages - @override_settings(ALL_LANGUAGES=[[u"cs", u"Czech"], [u"nl", u"Dutch"]]) + @override_settings(ALL_LANGUAGES=[["cs", "Czech"], ["nl", "Dutch"]]) def test_all_languages(self): """ Tests for the list of all languages. @@ -97,8 +95,8 @@ class LanguageApiTest(CacheIsolationTestCase): assert all_languages[0][1] < all_languages[1][1] assert 'nl' == all_languages[0][0] assert 'cs' == all_languages[1][0] - assert u'Hollandais' == all_languages[0][1] - assert u'Tchèque' == all_languages[1][1] + assert 'Hollandais' == all_languages[0][1] + assert 'Tchèque' == all_languages[1][1] def test_beta_languages(self): """ diff --git a/openedx/core/djangoapps/lang_pref/tests/test_middleware.py b/openedx/core/djangoapps/lang_pref/tests/test_middleware.py index f89dc98575..b53dda1983 100644 --- a/openedx/core/djangoapps/lang_pref/tests/test_middleware.py +++ b/openedx/core/djangoapps/lang_pref/tests/test_middleware.py @@ -4,10 +4,9 @@ Tests for lang_pref middleware. import itertools +from unittest import mock import ddt -import mock -import six from django.conf import settings from django.contrib.sessions.middleware import SessionMiddleware from django.http import HttpResponse @@ -33,7 +32,7 @@ class TestUserPreferenceMiddleware(CacheIsolationTestCase): """ def setUp(self): - super(TestUserPreferenceMiddleware, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.middleware = LanguagePreferenceMiddleware() self.session_middleware = SessionMiddleware() self.user = UserFactory.create() @@ -151,7 +150,7 @@ class TestUserPreferenceMiddleware(CacheIsolationTestCase): accept_lang_out = parse_accept_lang_header(accept_lang_out) if accept_lang_out and accept_lang_result: - six.assertCountEqual(self, accept_lang_result, accept_lang_out) + self.assertCountEqual(accept_lang_result, accept_lang_out) else: assert accept_lang_result == accept_lang_out diff --git a/openedx/core/djangoapps/lang_pref/tests/test_views.py b/openedx/core/djangoapps/lang_pref/tests/test_views.py index 529965e453..7f3005a093 100644 --- a/openedx/core/djangoapps/lang_pref/tests/test_views.py +++ b/openedx/core/djangoapps/lang_pref/tests/test_views.py @@ -19,7 +19,7 @@ class TestLangPrefView(TestCase): """ def setUp(self): - super(TestLangPrefView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.session_middleware = SessionMiddleware() self.user = UserFactory.create() self.request = RequestFactory().get('/somewhere') diff --git a/openedx/core/djangoapps/lang_pref/views.py b/openedx/core/djangoapps/lang_pref/views.py index 747a3e43e1..fbbe93cc7a 100644 --- a/openedx/core/djangoapps/lang_pref/views.py +++ b/openedx/core/djangoapps/lang_pref/views.py @@ -5,8 +5,6 @@ Language Preference Views import json -import six - from django.conf import settings from django.http import HttpResponse from django.utils.translation import LANGUAGE_SESSION_KEY @@ -26,7 +24,7 @@ def update_session_language(request): data = json.loads(request.body.decode('utf8')) language = data.get(LANGUAGE_KEY, settings.LANGUAGE_CODE) if request.session.get(LANGUAGE_SESSION_KEY, None) != language: - request.session[LANGUAGE_SESSION_KEY] = six.text_type(language) + request.session[LANGUAGE_SESSION_KEY] = str(language) response.set_cookie( settings.LANGUAGE_COOKIE, language, diff --git a/openedx/core/djangoapps/models/config/waffle.py b/openedx/core/djangoapps/models/config/waffle.py index 834bb24706..e0d798456a 100644 --- a/openedx/core/djangoapps/models/config/waffle.py +++ b/openedx/core/djangoapps/models/config/waffle.py @@ -12,7 +12,7 @@ COURSE_DETAIL_WAFFLE_FLAG_NAMESPACE = LegacyWaffleFlagNamespace(name=COURSE_DETA WAFFLE_SWITCHES = LegacyWaffleSwitchNamespace(name=COURSE_DETAIL_WAFFLE_NAMESPACE) # Course Override Flag -COURSE_DETAIL_UPDATE_CERTIFICATE_DATE = u'course_detail_update_certificate_date' +COURSE_DETAIL_UPDATE_CERTIFICATE_DATE = 'course_detail_update_certificate_date' def waffle_flags(): diff --git a/openedx/core/djangoapps/models/course_details.py b/openedx/core/djangoapps/models/course_details.py index 0d6fd3d543..748e90b591 100644 --- a/openedx/core/djangoapps/models/course_details.py +++ b/openedx/core/djangoapps/models/course_details.py @@ -33,7 +33,7 @@ ABOUT_ATTRIBUTES = [ ] -class CourseDetails(object): +class CourseDetails: """ An interface for extracting course information from the modulestore. """ @@ -82,7 +82,7 @@ class CourseDetails(object): Retrieve an attribute from a course's "about" info """ if attribute not in ABOUT_ATTRIBUTES + ['video']: - raise ValueError(u"'{0}' is not a valid course about attribute.".format(attribute)) + raise ValueError(f"'{attribute}' is not a valid course about attribute.") usage_key = course_key.make_usage_key('about', attribute) try: @@ -151,7 +151,7 @@ class CourseDetails(object): """ video_id = cls.fetch_youtube_video_id(course_key) if video_id: - return "http://www.youtube.com/watch?v={0}".format(video_id) + return f"http://www.youtube.com/watch?v={video_id}" @classmethod def update_about_item(cls, course, about_key, data, user_id, store=None): @@ -334,7 +334,7 @@ class CourseDetails(object): result = None if video_key: result = ( - HTML(u'').format(video_key) ) return result diff --git a/openedx/core/djangoapps/models/tests/test_course_details.py b/openedx/core/djangoapps/models/tests/test_course_details.py index e321dc9f51..fcd3f27ed5 100644 --- a/openedx/core/djangoapps/models/tests/test_course_details.py +++ b/openedx/core/djangoapps/models/tests/test_course_details.py @@ -21,7 +21,7 @@ class CourseDetailsTestCase(ModuleStoreTestCase): """ def setUp(self): - super(CourseDetailsTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course = CourseFactory.create() def test_virgin_fetch(self): @@ -141,4 +141,4 @@ class CourseDetailsTestCase(ModuleStoreTestCase): CourseDetails.update_about_video(self.course, video_value, self.user.id) assert CourseDetails.fetch_youtube_video_id(self.course.id) == video_value video_url = CourseDetails.fetch_video_url(self.course.id) - self.assertRegex(video_url, r'http://.*{}'.format(video_value)) + self.assertRegex(video_url, fr'http://.*{video_value}')