refactor: ran pyupgrade on openedx/core/djangoapps (#26956)

Ran pyupgrade on openedx/core/djangoapps/{system_wide_roles, theming}
This commit is contained in:
Usama Sadiq
2021-04-01 19:27:38 +05:00
committed by GitHub
parent b8afc30079
commit 24272e5caa
29 changed files with 75 additions and 94 deletions

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Django admin integration for system wide roles application.
"""
@@ -18,5 +17,5 @@ class SystemWideRoleAssignmentAdmin(UserRoleAssignmentAdmin):
form = SystemWideRoleAssignmentForm
class Meta(object):
class Meta:
model = SystemWideRoleAssignment

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-07-02 09:33

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-07-11 11:26

View File

@@ -13,7 +13,7 @@ class SystemWideRoleTests(TestCase):
""" Tests for SystemWideRole in system_wide_roles app """
def setUp(self):
super(SystemWideRoleTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.role = SystemWideRole.objects.create(name='TestRole')
def test_str(self):
@@ -27,7 +27,7 @@ class SystemWideRoleAssignmentTests(TestCase):
""" Tests for SystemWideRoleAssignment in system_wide_roles app """
def setUp(self):
super(SystemWideRoleAssignmentTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.user = UserFactory.create()
self.role = SystemWideRole.objects.create(name='TestRole')

View File

@@ -13,7 +13,7 @@ class SiteThemeAdmin(admin.ModelAdmin):
list_display = ('site', 'theme_dir_name')
search_fields = ('site__domain', 'theme_dir_name')
class Meta(object):
class Meta:
"""
Meta class for SiteTheme admin model
"""

View File

@@ -5,7 +5,7 @@ from edx_django_utils.plugins import PluginURLs
from openedx.core.djangoapps.plugins.constants import ProjectType
plugin_urls_config = {PluginURLs.NAMESPACE: u'theming', PluginURLs.REGEX: r'^theming/'}
plugin_urls_config = {PluginURLs.NAMESPACE: 'theming', PluginURLs.REGEX: r'^theming/'}
class ThemingConfig(AppConfig): # lint-amnesty, pylint: disable=missing-class-docstring

View File

@@ -5,7 +5,6 @@ Settings validations for the theming app
import os
import six
from django.conf import settings
from django.core.checks import Error, Tags, register
from edx_toggles.toggles import SettingToggle
@@ -55,7 +54,7 @@ def check_comprehensive_theme_settings(app_configs, **kwargs): # lint-amnesty,
id='openedx.core.djangoapps.theming.E004',
)
)
if not all(isinstance(theme_dir, six.string_types) for theme_dir in theme_dirs):
if not all(isinstance(theme_dir, str) for theme_dir in theme_dirs):
errors.append(
Error(
"COMPREHENSIVE_THEME_DIRS must contain only strings.",

View File

@@ -24,7 +24,6 @@ from collections import OrderedDict
from django.contrib.staticfiles import utils
from django.contrib.staticfiles.finders import BaseFinder
from django.utils import six
from openedx.core.djangoapps.theming.helpers import get_themes
from openedx.core.djangoapps.theming.storage import ThemeStorage
@@ -55,13 +54,13 @@ class ThemeFilesFinder(BaseFinder): # lint-amnesty, pylint: disable=abstract-me
if theme.theme_dir_name not in self.themes:
self.themes.append(theme.theme_dir_name)
super(ThemeFilesFinder, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
super().__init__(*args, **kwargs)
def list(self, ignore_patterns):
"""
List all files in all app storages.
"""
for storage in six.itervalues(self.storages):
for storage in self.storages.values():
if storage.exists(''): # check if storage location exists
for path in utils.get_files(storage, ignore_patterns):
yield path, storage

View File

@@ -206,7 +206,7 @@ def get_current_theme():
)
except ValueError as error:
# Log exception message and return None, so that open source theme is used instead
logger.exception(u'Theme not found in any of the themes dirs. [%s]', error)
logger.exception('Theme not found in any of the themes dirs. [%s]', error)
return None
@@ -240,7 +240,7 @@ def get_theme_base_dir(theme_dir_name, suppress_error=False):
return None
raise ValueError(
u"Theme '{theme}' not found in any of the following themes dirs, \nTheme dirs: \n{dir}".format(
"Theme '{theme}' not found in any of the following themes dirs, \nTheme dirs: \n{dir}".format(
theme=theme_dir_name,
dir=get_theme_base_dirs(),
))

View File

@@ -6,7 +6,6 @@ as the discovery happens during the initial setup of Django settings.
import os
from django.utils.encoding import python_2_unicode_compatible
from path import Path
@@ -106,8 +105,7 @@ def get_project_root_name_from_settings(project_root):
return root.name
@python_2_unicode_compatible
class Theme(object):
class Theme:
"""
class to encapsulate theme related information.
"""
@@ -146,7 +144,7 @@ class Theme(object):
def __str__(self):
# pylint: disable=line-too-long
return u"<Theme: {name} at '{path}'>".format(name=self.name, path=self.path) # xss-lint: disable=python-wrap-html
return f"<Theme: {self.name} at '{self.path}'>" # xss-lint: disable=python-wrap-html
def __repr__(self):
return self.__str__()

View File

@@ -3,7 +3,6 @@ Management command for compiling sass.
"""
import six
from django.core.management import BaseCommand, CommandError
from paver.easy import call_task
@@ -111,7 +110,7 @@ class Command(BaseCommand):
)
if "all" in given_themes:
themes = list(six.itervalues(available_themes))
themes = list(available_themes.values())
elif "no" in given_themes:
themes = []
else:

View File

@@ -72,7 +72,7 @@ class Command(BaseCommand):
"""
client_id = "{service_name}-key{site_name}".format(
service_name=service_name,
site_name="" if site_name == "edx" else "-{}".format(site_name)
site_name="" if site_name == "edx" else f"-{site_name}"
)
app, _ = Application.objects.update_or_create(
client_id=client_id,
@@ -87,7 +87,7 @@ class Command(BaseCommand):
),
"client_type": Application.CLIENT_CONFIDENTIAL,
"authorization_grant_type": Application.GRANT_AUTHORIZATION_CODE,
"redirect_uris": "{url}complete/edx-oauth2/".format(url=url),
"redirect_uris": f"{url}complete/edx-oauth2/",
"skip_authorization": True,
}
)
@@ -109,17 +109,17 @@ class Command(BaseCommand):
defaults={"name": theme_dir_name}
)
if created:
LOG.info(u"Creating '{site_name}' SiteTheme".format(site_name=site_domain))
LOG.info(f"Creating '{site_domain}' SiteTheme")
SiteTheme.objects.create(site=site, theme_dir_name=theme_dir_name)
LOG.info(u"Creating '{site_name}' SiteConfiguration".format(site_name=site_domain))
LOG.info(f"Creating '{site_domain}' SiteConfiguration")
SiteConfiguration.objects.create(
site=site,
site_values=site_configuration,
enabled=True
)
else:
LOG.info(u"'{site_domain}' site already exists".format(site_domain=site_domain))
LOG.info(f"'{site_domain}' site already exists")
def find(self, pattern, path):
"""
@@ -172,7 +172,7 @@ class Command(BaseCommand):
"""
site_data = {}
for config_file in self.find(self.configuration_filename, self.theme_path):
LOG.info(u"Reading file from {file}".format(file=config_file))
LOG.info(f"Reading file from {config_file}")
configuration_data = json.loads(
json.dumps(
json.load(
@@ -232,7 +232,7 @@ class Command(BaseCommand):
)
self.ecommerce_base_url_fmt = "https://ecommerce-{site_domain}/"
self.configuration_filename = '{}_configuration.json'.format(configuration_prefix)
self.configuration_filename = f'{configuration_prefix}_configuration.json'
self.discovery_user = self.get_or_create_service_user("lms_catalog_service_user")
self.ecommerce_user = self.get_or_create_service_user("ecommerce_worker")
@@ -246,13 +246,13 @@ class Command(BaseCommand):
discovery_url = self.discovery_base_url_fmt.format(site_domain=site_domain)
ecommerce_url = self.ecommerce_base_url_fmt.format(site_domain=site_domain)
LOG.info(u"Creating '{site_name}' Site".format(site_name=site_name))
LOG.info(f"Creating '{site_name}' Site")
self._create_sites(site_domain, site_data['theme_dir_name'], site_data['configuration'])
LOG.info(u"Creating discovery oauth2 client for '{site_name}' site".format(site_name=site_name))
LOG.info(f"Creating discovery oauth2 client for '{site_name}' site")
self._create_oauth2_client(discovery_url, site_name, 'discovery', self.discovery_user)
LOG.info(u"Creating ecommerce oauth2 client for '{site_name}' site".format(site_name=site_name))
LOG.info(f"Creating ecommerce oauth2 client for '{site_name}' site")
self._create_oauth2_client(ecommerce_url, site_name, 'ecommerce', self.ecommerce_user)
self._enable_commerce_configuration()

View File

@@ -2,8 +2,8 @@
Test cases for create_sites_and_configurations command.
"""
from unittest import mock
import pytest
import mock
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.contrib.sites.models import Site
from django.core.management import CommandError, call_command
@@ -27,7 +27,7 @@ def _generate_site_config(dns_name, site_domain, devstack=False):
return {
"lms_url": lms_url_fmt.format(domain=site_domain, dns_name=dns_name),
"platform_name": "{domain}-{dns_name}".format(domain=site_domain, dns_name=dns_name)
"platform_name": f"{site_domain}-{dns_name}"
}
@@ -43,7 +43,7 @@ def _get_sites(dns_name, devstack=False):
for site in SITES:
sites.update({
site: {
"theme_dir_name": "{}_dir_name".format(site),
"theme_dir_name": f"{site}_dir_name",
"configuration": _generate_site_config(dns_name, site),
"site_domain": site_domain_fmt.format(site=site, dns_name=dns_name)
}
@@ -54,7 +54,7 @@ def _get_sites(dns_name, devstack=False):
class TestCreateSiteAndConfiguration(TestCase):
""" Test the create_site_and_configuration command """
def setUp(self):
super(TestCreateSiteAndConfiguration, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.dns_name = "dummy_dns"
self.theme_path = "/dummyA/dummyB/"
@@ -69,7 +69,7 @@ class TestCreateSiteAndConfiguration(TestCase):
if site.name in SITES:
site_theme = SiteTheme.objects.get(site=site)
assert site_theme.theme_dir_name == '{}_dir_name'.format(site.name)
assert site_theme.theme_dir_name == f'{site.name}_dir_name'
self.assertDictEqual(
dict(site.configuration.values),
@@ -98,9 +98,9 @@ class TestCreateSiteAndConfiguration(TestCase):
assert len(clients) == len(SITES)
if devstack:
ecommerce_url_fmt = u"http://ecommerce-{site_name}-{dns_name}.e2e.devstack:18130/"
ecommerce_url_fmt = "http://ecommerce-{site_name}-{dns_name}.e2e.devstack:18130/"
else:
ecommerce_url_fmt = u"https://ecommerce-{site_name}-{dns_name}.sandbox.edx.org/"
ecommerce_url_fmt = "https://ecommerce-{site_name}-{dns_name}.sandbox.edx.org/"
for client in clients:
assert client.user.username == service_user[0].username
@@ -109,8 +109,8 @@ class TestCreateSiteAndConfiguration(TestCase):
site_name=site_name,
dns_name=self.dns_name
)
assert client.redirect_uris == '{ecommerce_url}complete/edx-oauth2/'.format(ecommerce_url=ecommerce_url)
assert client.client_id == 'ecommerce-key-{site_name}'.format(site_name=site_name)
assert client.redirect_uris == f'{ecommerce_url}complete/edx-oauth2/'
assert client.client_id == f'ecommerce-key-{site_name}'
access = ApplicationAccess.objects.filter(application_id=client.id).first()
assert access.scopes == ['user_id']
@@ -125,9 +125,9 @@ class TestCreateSiteAndConfiguration(TestCase):
assert len(clients) == len(SITES)
if devstack:
discovery_url_fmt = u"http://discovery-{site_name}-{dns_name}.e2e.devstack:18381/"
discovery_url_fmt = "http://discovery-{site_name}-{dns_name}.e2e.devstack:18381/"
else:
discovery_url_fmt = u"https://discovery-{site_name}-{dns_name}.sandbox.edx.org/"
discovery_url_fmt = "https://discovery-{site_name}-{dns_name}.sandbox.edx.org/"
for client in clients:
assert client.user.username == service_user[0].username
@@ -137,8 +137,8 @@ class TestCreateSiteAndConfiguration(TestCase):
dns_name=self.dns_name
)
assert client.redirect_uris == '{discovery_url}complete/edx-oauth2/'.format(discovery_url=discovery_url)
assert client.client_id == 'discovery-key-{site_name}'.format(site_name=site_name)
assert client.redirect_uris == f'{discovery_url}complete/edx-oauth2/'
assert client.client_id == f'discovery-key-{site_name}'
access = ApplicationAccess.objects.filter(application_id=client.id).first()
assert access.scopes == ['user_id']

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations, models

View File

@@ -30,8 +30,8 @@ def get_theme_paths(themes, theme_dirs):
theme_base_dirs = get_theme_base_dirs(theme, theme_dirs)
if not theme_base_dirs:
print((
u"\033[91m\nSkipping '{theme}': \n"
u"Theme ({theme}) not found in any of the theme dirs ({theme_dirs}). \033[00m".format(
"\033[91m\nSkipping '{theme}': \n"
"Theme ({theme}) not found in any of the theme dirs ({theme_dirs}). \033[00m".format(
theme=theme,
theme_dirs=", ".join(theme_dirs)
),

View File

@@ -8,15 +8,11 @@ import os.path
import posixpath
import re
from urllib.parse import unquote, urldefrag, urlsplit # pylint: disable=import-error
from django.conf import settings
from django.contrib.staticfiles.finders import find
from django.contrib.staticfiles.storage import ManifestFilesMixin, StaticFilesStorage
from django.utils._os import safe_join
from django.utils.six.moves.urllib.parse import ( # pylint: disable=no-name-in-module, import-error
unquote,
urldefrag,
urlsplit
)
from pipeline.storage import PipelineMixin
from openedx.core.djangoapps.theming.helpers import (
@@ -28,7 +24,7 @@ from openedx.core.djangoapps.theming.helpers import (
)
class ThemeMixin(object):
class ThemeMixin:
"""
Comprehensive theme aware Static files storage.
"""
@@ -41,7 +37,7 @@ class ThemeMixin(object):
def __init__(self, **kwargs):
self.prefix = kwargs.pop('prefix', None)
super(ThemeMixin, self).__init__(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments
super().__init__(**kwargs)
def url(self, name):
"""
@@ -70,7 +66,7 @@ class ThemeMixin(object):
if prefix and self.themed(name, prefix):
name = os.path.join(prefix, name)
return super(ThemeMixin, self).url(name) # lint-amnesty, pylint: disable=super-with-arguments
return super().url(name)
def themed(self, name, theme):
"""
@@ -287,10 +283,9 @@ class ThemePipelineMixin(PipelineMixin):
paths[output_file] = (self, output_file)
yield output_file, output_file, True
super_class = super(ThemePipelineMixin, self) # lint-amnesty, pylint: disable=super-with-arguments
super_class = super()
if hasattr(super_class, 'post_process'):
for name, hashed_name, processed in super_class.post_process(paths.copy(), dry_run, **options):
yield name, hashed_name, processed
yield from super_class.post_process(paths.copy(), dry_run, **options)
@staticmethod
def get_themed_packages(prefix, packages):

View File

@@ -33,7 +33,7 @@ class ThemeFilesystemLoader(FilesystemLoader):
theme_dirs = self.get_theme_template_sources()
if isinstance(theme_dirs, list):
self.dirs = theme_dirs + self.dirs
super(ThemeFilesystemLoader, self).__init__(engine, self.dirs) # lint-amnesty, pylint: disable=super-with-arguments
super().__init__(engine, self.dirs)
@staticmethod
def get_theme_template_sources():

View File

@@ -22,7 +22,7 @@ register = Library()
class OptionalIncludeNode(IncludeNode):
def render(self, context):
try:
return super(OptionalIncludeNode, self).render(context)
return super().render(context)
except TemplateDoesNotExist:
return ''

View File

@@ -57,7 +57,7 @@ def stylesheet(parser, token): # pylint: disable=unused-argument
_, name = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError( # lint-amnesty, pylint: disable=raise-missing-from
u'%r requires exactly one argument: the name of a group in the PIPELINE["STYLESHEETS"] setting' %
'%r requires exactly one argument: the name of a group in the PIPELINE["STYLESHEETS"] setting' %
token.split_contents()[0]
)
return ThemeStylesheetNode(name)
@@ -72,7 +72,7 @@ def javascript(parser, token): # pylint: disable=unused-argument
_, name = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError( # lint-amnesty, pylint: disable=raise-missing-from
u'%r requires exactly one argument: the name of a group in the PIPELINE["JAVASCRIPT"] setting' %
'%r requires exactly one argument: the name of a group in the PIPELINE["JAVASCRIPT"] setting' %
token.split_contents()[0]
)
return ThemeJavascriptNode(name)

View File

@@ -3,7 +3,6 @@ Tests for Management commands of comprehensive theming.
"""
import pytest
import six
from django.core.management import CommandError, call_command
from django.test import TestCase
@@ -16,7 +15,7 @@ class TestUpdateAssets(TestCase):
Test comprehensive theming helper functions.
"""
def setUp(self):
super(TestUpdateAssets, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.themes = get_themes()
def test_errors_for_invalid_arguments(self):
@@ -45,16 +44,15 @@ class TestUpdateAssets(TestCase):
"""
# make sure compile_sass picks all themes when called with 'themes=all' option
parsed_args = Command.parse_arguments(themes=["all"])
six.assertCountEqual(self, parsed_args[2], get_themes())
self.assertCountEqual(parsed_args[2], get_themes())
# make sure compile_sass picks no themes when called with 'themes=no' option
parsed_args = Command.parse_arguments(themes=["no"])
six.assertCountEqual(self, parsed_args[2], [])
self.assertCountEqual(parsed_args[2], [])
# make sure compile_sass picks only specified themes
parsed_args = Command.parse_arguments(themes=["test-theme"])
six.assertCountEqual(
self,
self.assertCountEqual(
parsed_args[2],
[theme for theme in get_themes() if theme.theme_dir_name == "test-theme"]
)

View File

@@ -17,7 +17,7 @@ class TestThemeFinders(TestCase):
"""
def setUp(self):
super(TestThemeFinders, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.finder = ThemeFilesFinder()
def test_find_first_themed_asset(self):

View File

@@ -3,11 +3,10 @@ Test helpers for Comprehensive Theming.
"""
import six
from unittest.mock import Mock, patch
from django.conf import settings
from django.test import TestCase, override_settings
from edx_django_utils.cache import RequestCache # lint-amnesty, pylint: disable=unused-import
from mock import Mock, patch
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from openedx.core.djangoapps.theming import helpers as theming_helpers
@@ -39,7 +38,7 @@ class TestHelpers(TestCase):
Theme('test-theme', 'test-theme', get_theme_base_dir('test-theme'), settings.PROJECT_ROOT),
]
actual_themes = get_themes()
six.assertCountEqual(self, expected_themes, actual_themes)
self.assertCountEqual(expected_themes, actual_themes)
@override_settings(COMPREHENSIVE_THEME_DIRS=[settings.TEST_THEME.dirname()])
def test_get_themes_2(self):
@@ -50,7 +49,7 @@ class TestHelpers(TestCase):
Theme('test-theme', 'test-theme', get_theme_base_dir('test-theme'), settings.PROJECT_ROOT),
]
actual_themes = get_themes()
six.assertCountEqual(self, expected_themes, actual_themes)
self.assertCountEqual(expected_themes, actual_themes)
def test_get_value_returns_override(self):
"""

View File

@@ -24,7 +24,7 @@ class TestCurrentSiteThemeMiddleware(TestCase):
"""
Initialize middleware and related objects
"""
super(TestCurrentSiteThemeMiddleware, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.site_theme_middleware = CurrentSiteThemeMiddleware()
self.user = UserFactory.create()
@@ -34,7 +34,7 @@ class TestCurrentSiteThemeMiddleware(TestCase):
Returns a mock GET request.
"""
if qs_theme:
test_url = "{}?site_theme={}".format(TEST_URL, qs_theme)
test_url = f"{TEST_URL}?site_theme={qs_theme}"
else:
test_url = TEST_URL

View File

@@ -4,11 +4,11 @@ Tests for comprehensive theme static files storage classes.
import re
from unittest.mock import patch
import ddt
from django.conf import settings
from django.test import TestCase, override_settings
from mock import patch
from openedx.core.djangoapps.theming.helpers import Theme, get_theme_base_dir, get_theme_base_dirs
from openedx.core.djangoapps.theming.storage import ThemeStorage
@@ -23,7 +23,7 @@ class TestStorageLMS(TestCase):
"""
def setUp(self):
super(TestStorageLMS, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.themes_dir = get_theme_base_dirs()[0]
self.enabled_theme = "red-theme"
self.system_dir = settings.REPO_ROOT / "lms"

View File

@@ -26,4 +26,4 @@ class TestComprehensiveThemeLocale(TestCase):
"""
test comprehensive theming directory path exist.
"""
assert os.path.exists((settings.REPO_ROOT / 'themes/conf/locale'))
assert os.path.exists(settings.REPO_ROOT / 'themes/conf/locale')

View File

@@ -23,7 +23,7 @@ class TestComprehensiveThemeLMS(TestCase):
"""
Clear static file finders cache and register cleanup methods.
"""
super(TestComprehensiveThemeLMS, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.user = UserFactory()
# Clear the internal staticfiles caches, to get test isolation.
@@ -152,7 +152,7 @@ class TestComprehensiveThemeDisabledLMS(TestCase):
"""
Clear static file finders cache.
"""
super(TestComprehensiveThemeDisabledLMS, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
# Clear the internal staticfiles caches, to get test isolation.
staticfiles.finders.get_finder.cache_clear()
@@ -177,7 +177,7 @@ class TestStanfordTheme(TestCase):
"""
Clear static file finders cache and register cleanup methods.
"""
super(TestStanfordTheme, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
# Clear the internal staticfiles caches, to get test isolation.
staticfiles.finders.get_finder.cache_clear()

View File

@@ -8,10 +8,10 @@ import os
import os.path
import re
from functools import wraps
from unittest.mock import patch
from django.conf import settings
from django.contrib.sites.models import Site
from mock import patch
from common.djangoapps import edxmako
from openedx.core.djangoapps.theming.models import SiteTheme
@@ -65,16 +65,16 @@ def with_comprehensive_theme_context(theme=None):
def dump_theming_info():
"""Dump a bunch of theming information, for debugging."""
for namespace, lookup in edxmako.LOOKUP.items():
print(u"--- %s: %s" % (namespace, lookup.template_args['module_directory']))
print("--- {}: {}".format(namespace, lookup.template_args['module_directory']))
for directory in lookup.directories:
print(u" %s" % (directory,))
print(f" {directory}")
print("=" * 80)
for dirname, __, filenames in os.walk(settings.MAKO_MODULE_DIR):
print(u"%s ----------------" % (dir,))
print(f"{dir} ----------------")
for filename in sorted(filenames):
if filename.endswith(".pyc"):
continue
with open(os.path.join(dirname, filename)) as f:
content = len(f.read())
print(u" %s: %d" % (filename, content))
print(" %s: %d" % (filename, content))

View File

@@ -25,7 +25,7 @@ class TestThemingViews(TestCase):
"""
Initialize middleware and related objects
"""
super(TestThemingViews, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.site_theme_middleware = CurrentSiteThemeMiddleware()
self.user = UserFactory.create()
@@ -89,7 +89,7 @@ class TestThemingViews(TestCase):
assert response.status_code == 200
self.assertContains(
response,
u'<option value="{theme_name}" selected=selected>'.format(theme_name=TEST_THEME_NAME)
f'<option value="{TEST_THEME_NAME}" selected=selected>'
)
# Request to reset the theme
@@ -106,5 +106,5 @@ class TestThemingViews(TestCase):
assert response.status_code == 200
self.assertContains(
response,
u'<option value="{theme_name}">'.format(theme_name=TEST_THEME_NAME)
f'<option value="{TEST_THEME_NAME}">'
)

View File

@@ -74,12 +74,12 @@ def set_user_preview_site_theme(request, preview_site_theme):
set_user_preference(request.user, PREVIEW_SITE_THEME_PREFERENCE_KEY, preview_site_theme_name)
PageLevelMessages.register_success_message(
request,
_(u'Site theme changed to {site_theme}').format(site_theme=preview_site_theme_name)
_('Site theme changed to {site_theme}').format(site_theme=preview_site_theme_name)
)
else:
PageLevelMessages.register_error_message(
request,
_(u'Theme {site_theme} does not exist').format(site_theme=preview_site_theme_name)
_('Theme {site_theme} does not exist').format(site_theme=preview_site_theme_name)
)
else:
delete_user_preference(request.user, PREVIEW_SITE_THEME_PREFERENCE_KEY)
@@ -105,7 +105,7 @@ class ThemingAdministrationFragmentView(EdxFragmentView):
"""
if not user_can_preview_themes(request.user):
raise Http404
return super(ThemingAdministrationFragmentView, self).get(request, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
return super().get(request, *args, **kwargs)
@method_decorator(login_required)
def post(self, request, **kwargs): # lint-amnesty, pylint: disable=unused-argument