Merge pull request #26310 from edx/py-amnesty-student

Applied pylint-amnesty to student
This commit is contained in:
Jawayria
2021-02-03 18:07:24 +05:00
committed by GitHub
69 changed files with 338 additions and 337 deletions

View File

@@ -1,3 +1,3 @@
"""
""" # lint-amnesty, pylint: disable=django-not-configured
Student app helpers and settings
"""

View File

@@ -133,7 +133,7 @@ class CourseAccessRoleForm(forms.ModelForm):
fields = '__all__'
email = forms.EmailField(required=True)
COURSE_ACCESS_ROLES = [(role_name, role_name) for role_name in REGISTERED_ACCESS_ROLES.keys()]
COURSE_ACCESS_ROLES = [(role_name, role_name) for role_name in REGISTERED_ACCESS_ROLES.keys()] # lint-amnesty, pylint: disable=consider-iterating-dictionary
role = forms.ChoiceField(choices=COURSE_ACCESS_ROLES)
def clean_course_id(self):
@@ -167,7 +167,7 @@ class CourseAccessRoleForm(forms.ModelForm):
try:
user = User.objects.get(email=email)
except Exception:
raise forms.ValidationError(
raise forms.ValidationError( # lint-amnesty, pylint: disable=raise-missing-from
u"Email does not exist. Could not find {email}. Please re-enter email address".format(
email=email
)
@@ -179,7 +179,7 @@ class CourseAccessRoleForm(forms.ModelForm):
"""
Checking the course already exists in db.
"""
cleaned_data = super(CourseAccessRoleForm, self).clean()
cleaned_data = super(CourseAccessRoleForm, self).clean() # lint-amnesty, pylint: disable=super-with-arguments
if not self.errors:
if CourseAccessRole.objects.filter(
user=cleaned_data.get("email"),
@@ -192,7 +192,7 @@ class CourseAccessRoleForm(forms.ModelForm):
return cleaned_data
def __init__(self, *args, **kwargs):
super(CourseAccessRoleForm, self).__init__(*args, **kwargs)
super(CourseAccessRoleForm, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
if self.instance.user_id:
self.fields['email'].initial = self.instance.user.email
@@ -219,7 +219,7 @@ class CourseAccessRoleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.user = form.cleaned_data['email']
super(CourseAccessRoleAdmin, self).save_model(request, obj, form, change)
super(CourseAccessRoleAdmin, self).save_model(request, obj, form, change) # lint-amnesty, pylint: disable=super-with-arguments
@admin.register(LinkedInAddToProfileConfiguration)
@@ -240,10 +240,10 @@ class CourseEnrollmentForm(forms.ModelForm):
try:
args_copy['course'] = CourseKey.from_string(args_copy['course'])
except InvalidKeyError:
raise forms.ValidationError("Cannot make a valid CourseKey from id {}!".format(args_copy['course']))
raise forms.ValidationError("Cannot make a valid CourseKey from id {}!".format(args_copy['course'])) # lint-amnesty, pylint: disable=raise-missing-from
args = [args_copy]
super(CourseEnrollmentForm, self).__init__(*args, **kwargs)
super(CourseEnrollmentForm, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
if self.data.get('course'):
try:
@@ -254,20 +254,20 @@ class CourseEnrollmentForm(forms.ModelForm):
# However, the args copy above before the super() call handles this case.
pass
def clean_course_id(self):
def clean_course_id(self): # lint-amnesty, pylint: disable=missing-function-docstring
course_id = self.cleaned_data['course']
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError:
raise forms.ValidationError("Cannot make a valid CourseKey from id {}!".format(course_id))
raise forms.ValidationError("Cannot make a valid CourseKey from id {}!".format(course_id)) # lint-amnesty, pylint: disable=raise-missing-from
if not modulestore().has_course(course_key):
raise forms.ValidationError("Cannot find course with id {} in the modulestore".format(course_id))
return course_key
def save(self, *args, **kwargs):
course_enrollment = super(CourseEnrollmentForm, self).save(commit=False)
def save(self, *args, **kwargs): # lint-amnesty, pylint: disable=signature-differs, unused-argument
course_enrollment = super(CourseEnrollmentForm, self).save(commit=False) # lint-amnesty, pylint: disable=super-with-arguments
user = self.cleaned_data['user']
course_overview = self.cleaned_data['course']
enrollment = CourseEnrollment.get_or_create_enrollment(user, course_overview.id)
@@ -290,7 +290,7 @@ class CourseEnrollmentAdmin(DisableEnrollmentAdminMixin, admin.ModelAdmin):
form = CourseEnrollmentForm
def get_search_results(self, request, queryset, search_term):
qs, use_distinct = super(CourseEnrollmentAdmin, self).get_search_results(request, queryset, search_term)
qs, use_distinct = super(CourseEnrollmentAdmin, self).get_search_results(request, queryset, search_term) # lint-amnesty, pylint: disable=super-with-arguments
# annotate each enrollment with whether the username was an
# exact match for the search term
@@ -305,7 +305,7 @@ class CourseEnrollmentAdmin(DisableEnrollmentAdminMixin, admin.ModelAdmin):
return qs, use_distinct
def queryset(self, request):
return super(CourseEnrollmentAdmin, self).queryset(request).select_related('user')
return super(CourseEnrollmentAdmin, self).queryset(request).select_related('user') # lint-amnesty, pylint: disable=no-member, super-with-arguments
class UserProfileInline(admin.StackedInline):
@@ -331,7 +331,7 @@ class UserChangeForm(BaseUserChangeForm):
last_name = forms.CharField(max_length=30, required=False)
def __init__(self, *args, **kwargs):
super(UserChangeForm, self).__init__(*args, **kwargs)
super(UserChangeForm, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
if not settings.FEATURES.get('ENABLE_CHANGE_USER_PASSWORD_ADMIN'):
self.fields["password"] = ReadOnlyPasswordHashField(
@@ -351,9 +351,9 @@ class UserAdmin(BaseUserAdmin):
def get_readonly_fields(self, request, obj=None):
"""
Allows editing the users while skipping the username check, so we can have Unicode username with no problems.
The username is marked read-only when editing existing users regardless of `ENABLE_UNICODE_USERNAME`, to simplify the bokchoy tests.
The username is marked read-only when editing existing users regardless of `ENABLE_UNICODE_USERNAME`, to simplify the bokchoy tests. # lint-amnesty, pylint: disable=line-too-long
"""
django_readonly = super(UserAdmin, self).get_readonly_fields(request, obj)
django_readonly = super(UserAdmin, self).get_readonly_fields(request, obj) # lint-amnesty, pylint: disable=super-with-arguments
if obj:
return django_readonly + ('username',)
return django_readonly
@@ -395,35 +395,35 @@ class LoginFailuresAdmin(admin.ModelAdmin):
"""
Only enabled if feature is enabled.
"""
return super(LoginFailuresAdmin, self).has_module_permission(request)
return super(LoginFailuresAdmin, self).has_module_permission(request) # lint-amnesty, pylint: disable=super-with-arguments
@_Check.is_enabled(LoginFailures.is_feature_enabled)
def has_view_permission(self, request, obj=None):
"""
Only enabled if feature is enabled.
"""
return super(LoginFailuresAdmin, self).has_view_permission(request, obj)
return super(LoginFailuresAdmin, self).has_view_permission(request, obj) # lint-amnesty, pylint: disable=super-with-arguments
@_Check.is_enabled(LoginFailures.is_feature_enabled)
def has_delete_permission(self, request, obj=None):
"""
Only enabled if feature is enabled.
"""
return super(LoginFailuresAdmin, self).has_delete_permission(request, obj)
return super(LoginFailuresAdmin, self).has_delete_permission(request, obj) # lint-amnesty, pylint: disable=super-with-arguments
@_Check.is_enabled(LoginFailures.is_feature_enabled)
def has_change_permission(self, request, obj=None):
"""
Only enabled if feature is enabled.
"""
return super(LoginFailuresAdmin, self).has_change_permission(request, obj)
return super(LoginFailuresAdmin, self).has_change_permission(request, obj) # lint-amnesty, pylint: disable=super-with-arguments
@_Check.is_enabled(LoginFailures.is_feature_enabled)
def has_add_permission(self, request):
"""
Only enabled if feature is enabled.
"""
return super(LoginFailuresAdmin, self).has_add_permission(request)
return super(LoginFailuresAdmin, self).has_add_permission(request) # lint-amnesty, pylint: disable=super-with-arguments
def unlock_student_accounts(self, request, queryset):
"""
@@ -456,13 +456,13 @@ class LoginFailuresAdmin(admin.ModelAdmin):
self.unlock_student(request, object_id=object_id)
url = reverse('admin:student_loginfailures_changelist', current_app=self.admin_site.name)
return HttpResponseRedirect(url)
return super(LoginFailuresAdmin, self).change_view(request, object_id, form_url, extra_context)
return super(LoginFailuresAdmin, self).change_view(request, object_id, form_url, extra_context) # lint-amnesty, pylint: disable=super-with-arguments
def get_actions(self, request):
"""
Get actions for model admin and remove delete action.
"""
actions = super(LoginFailuresAdmin, self).get_actions(request)
actions = super(LoginFailuresAdmin, self).get_actions(request) # lint-amnesty, pylint: disable=super-with-arguments
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
@@ -492,14 +492,14 @@ class AllowedAuthUserForm(forms.ModelForm):
email_domain = email.split('@')[-1]
allowed_site_email_domain = self.cleaned_data['site'].configuration.get_value('THIRD_PARTY_AUTH_ONLY_DOMAIN')
if not allowed_site_email_domain:
if not allowed_site_email_domain: # lint-amnesty, pylint: disable=no-else-raise
raise forms.ValidationError(
_("Please add a key/value 'THIRD_PARTY_AUTH_ONLY_DOMAIN/{site_email_domain}' in SiteConfiguration "
"model's site_values field.")
)
elif email_domain != allowed_site_email_domain:
raise forms.ValidationError(
_("Email doesn't have {domain_name} domain name.".format(domain_name=allowed_site_email_domain))
_("Email doesn't have {domain_name} domain name.".format(domain_name=allowed_site_email_domain)) # lint-amnesty, pylint: disable=translation-of-non-string
)
elif not User.objects.filter(email=email).exists():
raise forms.ValidationError(_("User with this email doesn't exist in system."))

View File

@@ -38,7 +38,7 @@ def is_ccx_course(course_key):
Check whether the course locator maps to a CCX course; this is important
because we don't allow access to CCX courses in Studio.
"""
return isinstance(course_key, CCXLocator) or isinstance(course_key, CCXBlockUsageLocator)
return isinstance(course_key, CCXLocator) or isinstance(course_key, CCXBlockUsageLocator) # lint-amnesty, pylint: disable=consider-merging-isinstance
def user_has_role(user, role):
@@ -172,7 +172,7 @@ def _check_caller_authority(caller, role):
if GlobalStaff().has_user(caller):
return
if isinstance(role, (GlobalStaff, CourseCreatorRole)):
if isinstance(role, (GlobalStaff, CourseCreatorRole)): # lint-amnesty, pylint: disable=no-else-raise
raise PermissionDenied
elif isinstance(role, CourseRole): # instructors can change the roles w/in their course
if not user_has_role(caller, CourseInstructorRole(role.course_key)):

View File

@@ -3,16 +3,16 @@ Utility functions for validating forms
"""
import re
from importlib import import_module
import re # lint-amnesty, pylint: disable=unused-import
from importlib import import_module # lint-amnesty, pylint: disable=unused-import
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user, unused-import
from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import ValidationError
from django.core.exceptions import ValidationError # lint-amnesty, pylint: disable=unused-import
from django.urls import reverse
from django.utils.http import int_to_base36
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext_lazy as _ # lint-amnesty, pylint: disable=unused-import
from edx_ace import ace
from edx_ace.recipient import Recipient
@@ -20,12 +20,12 @@ from openedx.core.djangoapps.ace_common.template_context import get_base_templat
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from openedx.core.djangoapps.theming.helpers import get_current_site
from openedx.core.djangoapps.user_api import accounts as accounts_settings
from openedx.core.djangoapps.user_api.accounts.utils import is_secondary_email_feature_enabled
from openedx.core.djangoapps.user_api import accounts as accounts_settings # lint-amnesty, pylint: disable=unused-import
from openedx.core.djangoapps.user_api.accounts.utils import is_secondary_email_feature_enabled # lint-amnesty, pylint: disable=unused-import
from openedx.core.djangoapps.user_authn.utils import should_redirect_to_authn_microfrontend
from openedx.core.djangoapps.user_api.preferences.api import get_user_preference
from common.djangoapps.student.message_types import AccountRecovery as AccountRecoveryMessage
from common.djangoapps.student.models import CourseEnrollmentAllowed, email_exists_or_retired
from common.djangoapps.student.models import CourseEnrollmentAllowed, email_exists_or_retired # lint-amnesty, pylint: disable=unused-import
def send_account_recovery_email_for_user(user, request, email=None):

View File

@@ -14,7 +14,7 @@ from completion.exceptions import UnavailableCompletionData
from completion.utilities import get_key_to_last_completed_block
from django.conf import settings
from django.contrib.auth import load_backend
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.core.validators import ValidationError
from django.db import IntegrityError, transaction, ProgrammingError
@@ -423,7 +423,7 @@ class AccountValidationError(Exception):
Used in account creation views to raise exceptions with details about specific invalid fields
"""
def __init__(self, message, field):
super(AccountValidationError, self).__init__(message)
super(AccountValidationError, self).__init__(message) # lint-amnesty, pylint: disable=super-with-arguments
self.field = field
@@ -641,13 +641,13 @@ def do_create_account(form, custom_form=None):
# AccountValidationError and a consistent user message returned (i.e. both should
# return "It looks like {username} belongs to an existing account. Try again with a
# different username.")
if username_exists_or_retired(user.username):
raise AccountValidationError(
if username_exists_or_retired(user.username): # lint-amnesty, pylint: disable=no-else-raise
raise AccountValidationError( # lint-amnesty, pylint: disable=raise-missing-from
USERNAME_EXISTS_MSG_FMT.format(username=proposed_username),
field="username"
)
elif email_exists_or_retired(user.email):
raise AccountValidationError(
raise AccountValidationError( # lint-amnesty, pylint: disable=raise-missing-from
_("An account with the Email '{email}' already exists.").format(email=user.email),
field="email"
)

View File

@@ -1,10 +1,10 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from django.contrib.auth.models import Group, User
from django.contrib.auth.models import Group, User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
def add_arguments(self, parser):
parser.add_argument('name_or_email',
help='Username or email address of the user to add or remove')
@@ -47,7 +47,7 @@ class Command(BaseCommand):
group = Group(name=group_name)
group.save()
else:
raise CommandError('Group {} does not exist'.format(group_name))
raise CommandError('Group {} does not exist'.format(group_name)) # lint-amnesty, pylint: disable=raise-missing-from
if options['remove']:
user.groups.remove(group)

View File

@@ -11,7 +11,7 @@ the following:
import csv
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.management.base import BaseCommand, CommandError
from opaque_keys.edx.keys import CourseKey
from six import text_type
@@ -60,4 +60,4 @@ class Command(BaseCommand):
anonymous_id_for_user(student, course_key)
))
except IOError:
raise CommandError("Error writing to file: %s" % output_filename)
raise CommandError("Error writing to file: %s" % output_filename) # lint-amnesty, pylint: disable=raise-missing-from

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import datetime
import json
@@ -6,7 +6,7 @@ import random
import sys
from textwrap import dedent
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.management.base import BaseCommand
from pytz import UTC
@@ -28,10 +28,10 @@ def group_from_value(groups, v):
curr_sum = curr_sum + p_value
if curr_sum > v:
return group
return group # For round-off errors
return group # For round-off errors # lint-amnesty, pylint: disable=undefined-loop-variable
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
help = dedent("""
Assign users to test groups. Takes a list of groups:
a:0.3,b:0.4,c:0.3 file.txt "Testing something"
@@ -54,7 +54,7 @@ class Command(BaseCommand):
print("Groups", groups)
# Confirm group probabilities add up to 1
total = sum(zip(*groups)[1])
total = sum(zip(*groups)[1]) # lint-amnesty, pylint: disable=unsubscriptable-object
print("Total:", total)
if abs(total - 1) > 0.01:
print("Total not 1")
@@ -74,7 +74,7 @@ class Command(BaseCommand):
for group in dict(groups):
utg = UserTestGroup()
utg.name = group
utg.description = json.dumps({"description": options['description']},
utg.description = json.dumps({"description": options['description']}, # lint-amnesty, pylint: disable=too-many-function-args
{"time": datetime.datetime.now(UTC).isoformat()})
group_objects[group] = utg
group_objects[group].save()

View File

@@ -68,7 +68,7 @@ class Command(BaseCommand):
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError:
raise CommandError('Course ID {} is invalid.'.format(course_id))
raise CommandError('Course ID {} is invalid.'.format(course_id)) # lint-amnesty, pylint: disable=raise-missing-from
if modulestore().get_course(course_key) is None:
raise CommandError('The given course {} does not exist.'.format(course_id))

View File

@@ -4,7 +4,7 @@ Un-enroll Bulk users course wide as well as specified in csv
import logging
import unicodecsv
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ObjectDoesNotExist # lint-amnesty, pylint: disable=unused-import
from django.core.management.base import BaseCommand
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey

View File

@@ -49,7 +49,7 @@ class Command(BaseCommand):
email_mappings = [
(current_email, new_email)
for (current_email, new_email)
for (current_email, new_email) # lint-amnesty, pylint: disable=unnecessary-comprehension
in csv_reader
]
@@ -72,5 +72,5 @@ class Command(BaseCommand):
len(failed_updates)
)
if (failed_updates):
exit(-1)
if (failed_updates): # lint-amnesty, pylint: disable=superfluous-parens
exit(-1) # lint-amnesty, pylint: disable=consider-using-sys-exit

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import csv
import os
@@ -8,7 +8,7 @@ from django.core.management.base import BaseCommand, CommandError
from common.djangoapps.student.models import UserProfile
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
help = """
Sets or gets certificate restrictions for users
from embargoed countries. (allow_certificate in

View File

@@ -21,10 +21,10 @@ class IncorrectDeadline(Exception):
"""
Exception raised explicitly to use default date when date given by user is prior to today.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
help = """
Changes the credit course eligibility deadline for a student in a particular course.

View File

@@ -19,10 +19,10 @@ class RollbackException(Exception):
"""
Exception raised explicitly to cause a database transaction rollback.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
help = """
Changes the enrollment status for students that meet
@@ -77,7 +77,7 @@ class Command(BaseCommand):
try:
course_key = CourseKey.from_string(options['course_id'])
except InvalidKeyError:
raise CommandError('Invalid or non-existant course id {}'.format(options['course_id']))
raise CommandError('Invalid or non-existant course id {}'.format(options['course_id'])) # lint-amnesty, pylint: disable=raise-missing-from
if not options['username'] and not options['email']:
raise CommandError('You must include usernames (-u) or emails (-e) to select users to update')
@@ -98,7 +98,7 @@ class Command(BaseCommand):
self.report(error_users, success_users)
def update_enrollments(self, identifier, enrollment_args, options, error_users, success_users, enrollment_attrs=None):
def update_enrollments(self, identifier, enrollment_args, options, error_users, success_users, enrollment_attrs=None): # lint-amnesty, pylint: disable=line-too-long
""" Update enrollments for a specific user identifier (email or username). """
users = options[identifier].split(",")

View File

@@ -6,7 +6,7 @@ Django management command for changing an enterprise user's username.
import logging
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.management import BaseCommand
from enterprise.models import EnterpriseCustomerUser

View File

@@ -20,7 +20,7 @@ def random_user_data_generator(num_users):
}
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
help = """Create N new users, with random parameters.
Usage: create_random_users.py N [course_id_to_enroll_in].

View File

@@ -13,7 +13,7 @@ from django.db import transaction
from django.utils.translation import gettext as _
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
help = 'Creates the specified group, if it does not exist, and sets its permissions.'
def add_arguments(self, parser):
@@ -21,7 +21,7 @@ class Command(BaseCommand):
parser.add_argument('--remove', dest='is_remove', action='store_true')
parser.add_argument('-p', '--permissions', nargs='*', default=[])
def _handle_remove(self, group_name):
def _handle_remove(self, group_name): # lint-amnesty, pylint: disable=missing-function-docstring
try:
Group.objects.get(name=group_name).delete()
@@ -30,7 +30,7 @@ class Command(BaseCommand):
self.stderr.write(_('Did not find a group with name "{}" - skipping.').format(group_name))
@transaction.atomic
def handle(self, group_name, is_remove, permissions=None, *args, **options):
def handle(self, group_name, is_remove, permissions=None, *args, **options): # lint-amnesty, pylint: disable=arguments-differ, keyword-arg-before-vararg
if is_remove:
self._handle_remove(group_name)
@@ -47,7 +47,7 @@ class Command(BaseCommand):
group.full_clean()
except ValidationError as exc:
# give a more helpful error
raise CommandError(
raise CommandError( # lint-amnesty, pylint: disable=raise-missing-from
_(
'Invalid group name: "{group_name}". {messages}'
).format(
@@ -86,14 +86,14 @@ class Command(BaseCommand):
group.save()
def _resolve_permissions(self, permissions):
def _resolve_permissions(self, permissions): # lint-amnesty, pylint: disable=missing-function-docstring
new_permissions = set()
for permission in permissions:
try:
app_label, model_name, codename = permission.split(':')
except ValueError:
# give a more helpful error
raise CommandError(_(
raise CommandError(_( # lint-amnesty, pylint: disable=raise-missing-from
'Invalid permission option: "{}". Please specify permissions '
'using the format: app_label:model_name:permission_codename.'
).format(permission))
@@ -101,7 +101,7 @@ class Command(BaseCommand):
try:
model_class = apps.get_model(app_label, model_name)
except LookupError as exc:
raise CommandError(str(exc))
raise CommandError(str(exc)) # lint-amnesty, pylint: disable=raise-missing-from
content_type = ContentType.objects.get_for_model(model_class)
try:
@@ -111,7 +111,7 @@ class Command(BaseCommand):
)
except Permission.DoesNotExist:
# give a more helpful error
raise CommandError(
raise CommandError( # lint-amnesty, pylint: disable=raise-missing-from
_(
'Invalid permission codename: "{codename}". No such permission exists '
'for the model {module}.{model_name}.'

View File

@@ -29,7 +29,7 @@ def is_valid_django_hash(encoded):
return True
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
help = 'Creates the specified user, if it does not exist, and sets its groups.'
def add_arguments(self, parser):
@@ -74,7 +74,7 @@ class Command(BaseCommand):
).format(user.username)
)
def _handle_remove(self, username, email):
def _handle_remove(self, username, email): # lint-amnesty, pylint: disable=missing-function-docstring
try:
user = get_user_model().objects.get(username=username)
except get_user_model().DoesNotExist:
@@ -85,7 +85,7 @@ class Command(BaseCommand):
user.delete()
@transaction.atomic
def handle(self, username, email, is_remove, is_staff, is_superuser, groups,
def handle(self, username, email, is_remove, is_staff, is_superuser, groups, # lint-amnesty, pylint: disable=arguments-differ
unusable_password, initial_password_hash, *args, **options):
if is_remove:

View File

@@ -4,7 +4,7 @@ Command to back-populate domain of the site the user account was created on.
import six
from django.contrib.auth.models import User
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.base import BaseCommand, CommandError

View File

@@ -1,13 +1,13 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import re
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.management.base import BaseCommand
from six import text_type
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
help = """
This command will set is_staff to true for one or more users.

View File

@@ -1,7 +1,7 @@
"""Management command to grant or revoke superuser access for one or more users"""
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.management.base import BaseCommand
from six import text_type

View File

@@ -5,7 +5,7 @@ Transfer Student Management Command
from textwrap import dedent
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.db import transaction
from opaque_keys.edx.keys import CourseKey
from six import text_type
@@ -18,7 +18,7 @@ class TransferStudentError(Exception):
"""
Generic Error when handling student transfers.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class Command(TrackedCommand):

View File

@@ -20,7 +20,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
"""Tests for the bulk_change_enrollment command."""
def setUp(self):
super(BulkChangeEnrollmentTests, self).setUp()
super(BulkChangeEnrollmentTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.org = 'testX'
self.course = CourseFactory.create(org=self.org)
self.users = UserFactory.create_batch(5)

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import unittest
from tempfile import NamedTemporaryFile
@@ -27,7 +27,7 @@ class BulkChangeEnrollmentCSVTests(SharedModuleStoreTestCase):
Tests bulk_change_enrollmetn_csv command
"""
def setUp(self):
super(BulkChangeEnrollmentCSVTests, self).setUp()
super(BulkChangeEnrollmentCSVTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.courses = []
self.user_info = [

View File

@@ -19,7 +19,7 @@ LOGGER_NAME = 'common.djangoapps.student.management.commands.bulk_unenroll'
class BulkUnenrollTests(SharedModuleStoreTestCase):
"""Test Bulk un-enroll command works fine for all test cases."""
def setUp(self):
super(BulkUnenrollTests, self).setUp()
super(BulkUnenrollTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course = CourseFactory.create()
self.audit_mode = CourseModeFactory.create(
course_id=self.course.id,

View File

@@ -24,7 +24,7 @@ class ChangeEligibilityDeadlineTests(SharedModuleStoreTestCase):
def setUp(self):
""" Initial set up for tests """
super(ChangeEligibilityDeadlineTests, self).setUp()
super(ChangeEligibilityDeadlineTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course = CourseFactory.create()
self.enrolled_user = UserFactory.create(username='amy', email='amy@pond.com', password='password')

View File

@@ -17,7 +17,7 @@ from xmodule.modulestore.tests.factories import CourseFactory
class ChangeEnrollmentTests(SharedModuleStoreTestCase):
""" Test the enrollment change functionality of the change_enrollment script."""
def setUp(self):
super(ChangeEnrollmentTests, self).setUp()
super(ChangeEnrollmentTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course = CourseFactory.create()
self.audit_mode = CourseModeFactory.create(
course_id=self.course.id,

View File

@@ -5,7 +5,7 @@ Tests for the django management command `change_enterprise_user_username`.
import mock
from django.contrib.auth.models import User
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 call_command
from django.db.models.signals import post_save

View File

@@ -19,7 +19,7 @@ class CreateRandomUserTests(SharedModuleStoreTestCase):
Test creating random users via command line, with various options
"""
def setUp(self):
super(CreateRandomUserTests, self).setUp()
super(CreateRandomUserTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course = CourseFactory.create()
self.user_model = get_user_model()
self.num_users_start = len(self.user_model.objects.all())

View File

@@ -7,7 +7,7 @@ import itertools
import ddt
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Group, User
from django.contrib.auth.models import Group, User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.management import CommandError, call_command
from django.test import TestCase

View File

@@ -5,7 +5,7 @@ Unittests for populate_created_on_site_user_attribute management command.
import ddt
import mock
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.management import CommandError, call_command
from django.test import TestCase
from six.moves import range
@@ -24,7 +24,7 @@ class TestPopulateUserAttribute(SiteMixin, TestCase):
"""
def setUp(self):
super(TestPopulateUserAttribute, self).setUp()
super(TestPopulateUserAttribute, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self._create_sample_data()
self.users = User.objects.all()

View File

@@ -27,7 +27,7 @@ class RecoverAccountTests(TestCase):
request_factory = RequestFactory()
def setUp(self):
super(RecoverAccountTests, self).setUp()
super(RecoverAccountTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(username='amy', email='amy@edx.com', password='password')
def _write_test_csv(self, csv, lines):

View File

@@ -35,11 +35,11 @@ class TestTransferStudents(ModuleStoreTestCase):
PASSWORD = 'test'
signal_fired = False
def setUp(self, **kwargs):
def setUp(self, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
Connect a stub receiver, and analytics event tracking.
"""
super(TestTransferStudents, self).setUp()
super(TestTransferStudents, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
UNENROLL_DONE.connect(self.assert_unenroll_signal)
patcher = patch('common.djangoapps.student.models.tracker')
@@ -141,7 +141,7 @@ class TestTransferStudents(ModuleStoreTestCase):
run=course_location.run
)
def _create_and_purchase_verified(self, student, course_id):
def _create_and_purchase_verified(self, student, course_id): # lint-amnesty, pylint: disable=unused-argument
"""
Creates a verified mode for the course and purchases it for the student.
"""

View File

@@ -18,7 +18,7 @@ class UserStandingMiddleware(MiddlewareMixin):
Checks a user's standing on request. Returns a 403 if the user's
status is 'disabled'.
"""
def process_request(self, request):
def process_request(self, request): # lint-amnesty, pylint: disable=missing-function-docstring
user = request.user
try:
user_account = UserStanding.objects.get(user=user.id)

View File

@@ -26,7 +26,7 @@ import six
from config_models.models import ConfigurationModel
from django.apps import apps
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.contrib.sites.models import Site
from django.core.cache import cache
@@ -806,7 +806,7 @@ def user_profile_pre_save_callback(sender, **kwargs):
# Cache "old" field values on the model instance so that they can be
# retrieved in the post_save callback when we emit an event with new and
# old field values.
user_profile._changed_fields = get_changed_fields_dict(user_profile, sender)
user_profile._changed_fields = get_changed_fields_dict(user_profile, sender) # lint-amnesty, pylint: disable=protected-access
@receiver(post_save, sender=UserProfile)
@@ -830,7 +830,7 @@ def user_pre_save_callback(sender, **kwargs):
private field on the current model for use in the post_save callback.
"""
user = kwargs['instance']
user._changed_fields = get_changed_fields_dict(user, sender)
user._changed_fields = get_changed_fields_dict(user, sender) # lint-amnesty, pylint: disable=protected-access
@receiver(post_save, sender=User)
@@ -844,7 +844,7 @@ def user_post_save_callback(sender, **kwargs):
"""
user = kwargs['instance']
changed_fields = user._changed_fields
changed_fields = user._changed_fields # lint-amnesty, pylint: disable=protected-access
if 'is_active' in changed_fields or 'email' in changed_fields:
if user.is_active:
@@ -1147,7 +1147,7 @@ class CourseEnrollmentManager(models.Manager):
"""
max_enrollments = settings.FEATURES.get("MAX_ENROLLMENT_INSTR_BUTTONS")
enrollment_number = super(CourseEnrollmentManager, self).get_queryset().filter(
enrollment_number = super(CourseEnrollmentManager, self).get_queryset().filter( # lint-amnesty, pylint: disable=super-with-arguments
course_id=course_id,
is_active=1
)[:max_enrollments + 1].count()
@@ -1176,7 +1176,7 @@ class CourseEnrollmentManager(models.Manager):
admins = CourseInstructorRole(course_locator).users_with_role()
coaches = CourseCcxCoachRole(course_locator).users_with_role()
return super(CourseEnrollmentManager, self).get_queryset().filter(
return super(CourseEnrollmentManager, self).get_queryset().filter( # lint-amnesty, pylint: disable=super-with-arguments
course_id=course_id,
is_active=1,
).exclude(user__in=staff).exclude(user__in=admins).exclude(user__in=coaches).count()
@@ -1220,7 +1220,7 @@ class CourseEnrollmentManager(models.Manager):
"""
# Unfortunately, Django's "group by"-style queries look super-awkward
query = use_read_replica_if_available(
super(CourseEnrollmentManager, self).get_queryset().filter(course_id=course_id, is_active=True).values(
super(CourseEnrollmentManager, self).get_queryset().filter(course_id=course_id, is_active=True).values( # lint-amnesty, pylint: disable=super-with-arguments
'mode').order_by().annotate(Count('mode')))
total = 0
enroll_dict = defaultdict(int)
@@ -1303,7 +1303,7 @@ class CourseEnrollment(models.Model):
ordering = ('user', 'course')
def __init__(self, *args, **kwargs):
super(CourseEnrollment, self).__init__(*args, **kwargs)
super(CourseEnrollment, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
# Private variable for storing course_overview to minimize calls to the database.
# When the property .course_overview is accessed for the first time, this variable will be set.
@@ -1315,7 +1315,7 @@ class CourseEnrollment(models.Model):
).format(self.user, self.course_id, self.created, self.is_active)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
super(CourseEnrollment, self).save(force_insert=force_insert, force_update=force_update, using=using,
super(CourseEnrollment, self).save(force_insert=force_insert, force_update=force_update, using=using, # lint-amnesty, pylint: disable=super-with-arguments
update_fields=update_fields)
# Delete the cached status hash, forcing the value to be recalculated the next time it is needed.
@@ -1583,7 +1583,7 @@ class CourseEnrollment(models.Model):
# announced before the start of content creation.
if check_access:
log.warning(u"User %s failed to enroll in non-existent course %s", user.username, text_type(course_key))
raise NonExistentCourseError
raise NonExistentCourseError # lint-amnesty, pylint: disable=raise-missing-from
if check_access:
if cls.is_enrollment_closed(user, course) and not can_upgrade:
@@ -2075,9 +2075,9 @@ class CourseEnrollment(models.Model):
log.debug(
'Schedules: Pulling upgrade deadline for CourseEnrollment %d from Schedule %d.',
self.id, self.schedule.id
self.id, self.schedule.id # lint-amnesty, pylint: disable=no-member
)
return self.schedule.upgrade_deadline
return self.schedule.upgrade_deadline # lint-amnesty, pylint: disable=no-member
except ObjectDoesNotExist:
# NOTE: Schedule has a one-to-one mapping with CourseEnrollment. If no schedule is associated
# with this enrollment, Django will raise an exception rather than return None.
@@ -2180,7 +2180,7 @@ class CourseEnrollment(models.Model):
RequestCache(cls.MODE_CACHE_NAMESPACE).clear()
records = cls.objects.filter(user__in=users, course_id=course_key).select_related('user')
cache = cls._get_mode_active_request_cache()
cache = cls._get_mode_active_request_cache() # lint-amnesty, pylint: disable=redefined-outer-name
for record in records:
enrollment_state = CourseEnrollmentState(record.mode, record.is_active)
cls._update_enrollment(cache, record.user.id, course_key, enrollment_state)
@@ -2209,7 +2209,7 @@ class CourseEnrollment(models.Model):
cls._update_enrollment(cls._get_mode_active_request_cache(), user.id, course_key, enrollment_state)
@classmethod
def _update_enrollment(cls, cache, user_id, course_key, enrollment_state):
def _update_enrollment(cls, cache, user_id, course_key, enrollment_state): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Updates the cached value for the user's enrollment in the
given cache.
@@ -2430,7 +2430,7 @@ class CourseAccessRole(models.Model):
Overriding eq b/c the django impl relies on the primary key which requires fetch. sometimes we
just want to compare roles w/o doing another fetch.
"""
return type(self) == type(other) and self._key == other._key # pylint: disable=protected-access
return type(self) == type(other) and self._key == other._key # lint-amnesty, pylint: disable=protected-access, unidiomatic-typecheck
def __hash__(self):
return hash(self._key)
@@ -2442,7 +2442,7 @@ class CourseAccessRole(models.Model):
return self._key < other._key
def __str__(self):
return "[CourseAccessRole] user: {} role: {} org: {} course: {}".format(self.user.username, self.role, self.org, self.course_id)
return "[CourseAccessRole] user: {} role: {} org: {} course: {}".format(self.user.username, self.role, self.org, self.course_id) # lint-amnesty, pylint: disable=line-too-long
#### Helper methods for use from python manage.py shell and other classes.
@@ -2484,7 +2484,7 @@ def get_user(email):
return user, u_prof
def user_info(email):
def user_info(email): # lint-amnesty, pylint: disable=missing-function-docstring
user, u_prof = get_user(email)
print("User id", user.id)
print("Username", user.username)
@@ -2543,7 +2543,7 @@ DEFAULT_GROUPS = {
}
def add_user_to_default_group(user, group):
def add_user_to_default_group(user, group): # lint-amnesty, pylint: disable=missing-function-docstring
try:
utg = UserTestGroup.objects.get(name=group)
except UserTestGroup.DoesNotExist:
@@ -2555,7 +2555,7 @@ def add_user_to_default_group(user, group):
utg.save()
def create_comments_service_user(user):
def create_comments_service_user(user): # lint-amnesty, pylint: disable=missing-function-docstring
if not settings.FEATURES['ENABLE_DISCUSSION_SERVICE']:
# Don't try--it won't work, and it will fill the logs with lots of errors
return
@@ -2576,7 +2576,7 @@ def create_comments_service_user(user):
@receiver(user_logged_in)
def log_successful_login(sender, request, user, **kwargs):
def log_successful_login(sender, request, user, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""Handler to log when logins have occurred successfully."""
if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
AUDIT_LOG.info(u"Login success - user.id: {0}".format(user.id))
@@ -2585,7 +2585,7 @@ def log_successful_login(sender, request, user, **kwargs):
@receiver(user_logged_out)
def log_successful_logout(sender, request, user, **kwargs):
def log_successful_logout(sender, request, user, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""Handler to log when logouts have occurred successfully."""
if hasattr(request, 'user'):
if settings.FEATURES['SQUELCH_PII_IN_LOGS']:
@@ -2798,7 +2798,7 @@ class LanguageField(models.CharField):
'help_text',
_("The ISO 639-1 language code for this language."),
)
super(LanguageField, self).__init__(
super(LanguageField, self).__init__( # lint-amnesty, pylint: disable=super-with-arguments
max_length=16,
choices=settings.ALL_LANGUAGES,
help_text=help_text,
@@ -2984,7 +2984,7 @@ class RegistrationCookieConfiguration(ConfigurationModel):
)
class BulkUnenrollConfiguration(ConfigurationModel):
class BulkUnenrollConfiguration(ConfigurationModel): # lint-amnesty, pylint: disable=empty-docstring
"""
"""
@@ -3068,13 +3068,13 @@ class AccountRecoveryManager(models.Manager):
AccountRecovery: AccountRecovery object with is_active=true
"""
filters['is_active'] = True
return super(AccountRecoveryManager, self).get_queryset().get(**filters)
return super(AccountRecoveryManager, self).get_queryset().get(**filters) # lint-amnesty, pylint: disable=super-with-arguments
def activate(self):
"""
Set is_active flag to True.
"""
super(AccountRecoveryManager, self).get_queryset().update(is_active=True)
super(AccountRecoveryManager, self).get_queryset().update(is_active=True) # lint-amnesty, pylint: disable=super-with-arguments
class AccountRecovery(models.Model):

View File

@@ -30,7 +30,7 @@ DEFAULT_TRANSITION_STATE = _DEFAULT_TRANSITION_STATE
log = logging.getLogger(__name__)
def create_manual_enrollment_audit(
def create_manual_enrollment_audit( # lint-amnesty, pylint: disable=missing-function-docstring
enrolled_by,
user_email,
state_transition,

View File

@@ -9,7 +9,7 @@ from abc import ABCMeta, abstractmethod
from collections import defaultdict
import six
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from opaque_keys.edx.django.models import CourseKeyField
from openedx.core.lib.cache_utils import get_cache
@@ -37,12 +37,12 @@ def register_access_role(cls):
return cls
class BulkRoleCache(object):
class BulkRoleCache(object): # lint-amnesty, pylint: disable=missing-class-docstring
CACHE_NAMESPACE = u"student.roles.BulkRoleCache"
CACHE_KEY = u'roles_by_user'
@classmethod
def prefetch(cls, users):
def prefetch(cls, users): # lint-amnesty, pylint: disable=missing-function-docstring
roles_by_user = defaultdict(set)
get_cache(cls.CACHE_NAMESPACE)[cls.CACHE_KEY] = roles_by_user
@@ -99,14 +99,14 @@ class AccessRole(six.with_metaclass(ABCMeta, object)):
"""
Add the role to the supplied django users.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def remove_users(self, *users):
"""
Remove the role from the supplied django users.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def users_with_role(self):
@@ -150,7 +150,7 @@ class RoleBase(AccessRole):
an org. Provide org and course if constrained to a course. Although, you should use the subclasses
for all of these.
"""
super(RoleBase, self).__init__()
super(RoleBase, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self.org = org
self.course_key = course_key
@@ -185,7 +185,7 @@ class RoleBase(AccessRole):
"""
# silently ignores anonymous and inactive users so that any that are
# legit get updated.
from common.djangoapps.student.models import CourseAccessRole
from common.djangoapps.student.models import CourseAccessRole # lint-amnesty, pylint: disable=redefined-outer-name, reimported
for user in users:
if user.is_authenticated and user.is_active and not self.has_user(user):
entry = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org)
@@ -229,10 +229,10 @@ class CourseRole(RoleBase):
Args:
course_key (CourseKey)
"""
super(CourseRole, self).__init__(role, course_key.org, course_key)
super(CourseRole, self).__init__(role, course_key.org, course_key) # lint-amnesty, pylint: disable=super-with-arguments
@classmethod
def course_group_already_exists(self, course_key):
def course_group_already_exists(self, course_key): # lint-amnesty, pylint: disable=bad-classmethod-argument
return CourseAccessRole.objects.filter(org=course_key.org, course_id=course_key).exists()
def __repr__(self):
@@ -253,7 +253,7 @@ class CourseStaffRole(CourseRole):
ROLE = 'staff'
def __init__(self, *args, **kwargs):
super(CourseStaffRole, self).__init__(self.ROLE, *args, **kwargs)
super(CourseStaffRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
@register_access_role
@@ -262,7 +262,7 @@ class CourseInstructorRole(CourseRole):
ROLE = 'instructor'
def __init__(self, *args, **kwargs):
super(CourseInstructorRole, self).__init__(self.ROLE, *args, **kwargs)
super(CourseInstructorRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
@register_access_role
@@ -271,7 +271,7 @@ class CourseFinanceAdminRole(CourseRole):
ROLE = 'finance_admin'
def __init__(self, *args, **kwargs):
super(CourseFinanceAdminRole, self).__init__(self.ROLE, *args, **kwargs)
super(CourseFinanceAdminRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
@register_access_role
@@ -280,7 +280,7 @@ class CourseSalesAdminRole(CourseRole):
ROLE = 'sales_admin'
def __init__(self, *args, **kwargs):
super(CourseSalesAdminRole, self).__init__(self.ROLE, *args, **kwargs)
super(CourseSalesAdminRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
@register_access_role
@@ -289,7 +289,7 @@ class CourseBetaTesterRole(CourseRole):
ROLE = 'beta_testers'
def __init__(self, *args, **kwargs):
super(CourseBetaTesterRole, self).__init__(self.ROLE, *args, **kwargs)
super(CourseBetaTesterRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
@register_access_role
@@ -301,7 +301,7 @@ class LibraryUserRole(CourseRole):
ROLE = 'library_user'
def __init__(self, *args, **kwargs):
super(LibraryUserRole, self).__init__(self.ROLE, *args, **kwargs)
super(LibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
class CourseCcxCoachRole(CourseRole):
@@ -309,7 +309,7 @@ class CourseCcxCoachRole(CourseRole):
ROLE = 'ccx_coach'
def __init__(self, *args, **kwargs):
super(CourseCcxCoachRole, self).__init__(self.ROLE, *args, **kwargs)
super(CourseCcxCoachRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
@register_access_role
@@ -318,19 +318,19 @@ class CourseDataResearcherRole(CourseRole):
ROLE = 'data_researcher'
def __init__(self, *args, **kwargs):
super(CourseDataResearcherRole, self).__init__(self.ROLE, *args, **kwargs)
super(CourseDataResearcherRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
class OrgStaffRole(OrgRole):
"""An organization staff member"""
def __init__(self, *args, **kwargs):
super(OrgStaffRole, self).__init__('staff', *args, **kwargs)
super(OrgStaffRole, self).__init__('staff', *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
class OrgInstructorRole(OrgRole):
"""An organization instructor"""
def __init__(self, *args, **kwargs):
super(OrgInstructorRole, self).__init__('instructor', *args, **kwargs)
super(OrgInstructorRole, self).__init__('instructor', *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
class OrgLibraryUserRole(OrgRole):
@@ -341,7 +341,7 @@ class OrgLibraryUserRole(OrgRole):
ROLE = LibraryUserRole.ROLE
def __init__(self, *args, **kwargs):
super(OrgLibraryUserRole, self).__init__(self.ROLE, *args, **kwargs)
super(OrgLibraryUserRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
class OrgDataResearcherRole(OrgRole):
@@ -349,7 +349,7 @@ class OrgDataResearcherRole(OrgRole):
ROLE = 'data_researcher'
def __init__(self, *args, **kwargs):
super(OrgDataResearcherRole, self).__init__(self.ROLE, *args, **kwargs)
super(OrgDataResearcherRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
@register_access_role
@@ -361,7 +361,7 @@ class CourseCreatorRole(RoleBase):
ROLE = "course_creator_group"
def __init__(self, *args, **kwargs):
super(CourseCreatorRole, self).__init__(self.ROLE, *args, **kwargs)
super(CourseCreatorRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
@register_access_role
@@ -372,7 +372,7 @@ class SupportStaffRole(RoleBase):
ROLE = "support"
def __init__(self, *args, **kwargs):
super(SupportStaffRole, self).__init__(self.ROLE, *args, **kwargs)
super(SupportStaffRole, self).__init__(self.ROLE, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
class UserBasedRole(object):

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from common.djangoapps.student.signals.signals import (
ENROLL_STATUS_CHANGE,

View File

@@ -12,7 +12,7 @@ from django.dispatch import receiver
from lms.djangoapps.courseware.toggles import courseware_mfe_first_section_celebration_is_active
from common.djangoapps.student.helpers import EMAIL_EXISTS_MSG_FMT, USERNAME_EXISTS_MSG_FMT, AccountValidationError
from common.djangoapps.student.models import CourseEnrollment, CourseEnrollmentCelebration, is_email_retired, is_username_retired
from common.djangoapps.student.models import CourseEnrollment, CourseEnrollmentCelebration, is_email_retired, is_username_retired # lint-amnesty, pylint: disable=line-too-long
@receiver(pre_save, sender=get_user_model())

View File

@@ -8,7 +8,7 @@ import logging
from celery.exceptions import MaxRetriesExceededError
from celery import shared_task
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.contrib.sites.models import Site
from edx_ace import ace
from edx_ace.errors import RecoverableChannelDeliveryError
@@ -70,7 +70,7 @@ def _send_activation_email(self, msg_string, from_address=None):
from_address,
dest_addr,
)
raise Exception
raise Exception # lint-amnesty, pylint: disable=raise-missing-from
_OLD_TASK_NAME = 'student.send_activation_email'

View File

@@ -32,7 +32,7 @@ from common.djangoapps.student.models import (
TEST_PASSWORD = 'test'
class GroupFactory(DjangoModelFactory):
class GroupFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = Group
django_get_or_create = ('name', )
@@ -40,7 +40,7 @@ class GroupFactory(DjangoModelFactory):
name = factory.Sequence(u'group{0}'.format)
class UserStandingFactory(DjangoModelFactory):
class UserStandingFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = UserStanding
@@ -49,7 +49,7 @@ class UserStandingFactory(DjangoModelFactory):
changed_by = None
class UserProfileFactory(DjangoModelFactory):
class UserProfileFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = UserProfile
django_get_or_create = ('user', )
@@ -63,7 +63,7 @@ class UserProfileFactory(DjangoModelFactory):
allow_certificate = True
class RegistrationFactory(DjangoModelFactory):
class RegistrationFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = Registration
@@ -71,7 +71,7 @@ class RegistrationFactory(DjangoModelFactory):
activation_key = six.text_type(uuid4().hex)
class UserFactory(DjangoModelFactory):
class UserFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = User
django_get_or_create = ('email', 'username')
@@ -100,7 +100,7 @@ class UserFactory(DjangoModelFactory):
return None
@factory.post_generation
def groups(self, create, extracted, **kwargs):
def groups(self, create, extracted, **kwargs): # lint-amnesty, pylint: disable=missing-function-docstring, unused-argument
if extracted is None:
return
@@ -108,7 +108,7 @@ class UserFactory(DjangoModelFactory):
extracted = [extracted]
for group_name in extracted:
self.groups.add(GroupFactory.simple_generate(create, name=group_name))
self.groups.add(GroupFactory.simple_generate(create, name=group_name)) # lint-amnesty, pylint: disable=no-member
class AnonymousUserFactory(factory.Factory):
@@ -124,7 +124,7 @@ class SuperuserFactory(UserFactory):
is_superuser = True
class CourseEnrollmentFactory(DjangoModelFactory):
class CourseEnrollmentFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = CourseEnrollment
@@ -173,7 +173,7 @@ class CourseEnrollmentCelebrationFactory(DjangoModelFactory):
enrollment = factory.SubFactory(CourseEnrollmentFactory)
class CourseAccessRoleFactory(DjangoModelFactory):
class CourseAccessRoleFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = CourseAccessRole
@@ -182,7 +182,7 @@ class CourseAccessRoleFactory(DjangoModelFactory):
role = 'TestRole'
class CourseEnrollmentAllowedFactory(DjangoModelFactory):
class CourseEnrollmentAllowedFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = CourseEnrollmentAllowed
@@ -212,7 +212,7 @@ class ContentTypeFactory(DjangoModelFactory):
app_label = factory.Faker('app_name')
class PermissionFactory(DjangoModelFactory):
class PermissionFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = Permission
@@ -220,7 +220,7 @@ class PermissionFactory(DjangoModelFactory):
content_type = factory.SubFactory(ContentTypeFactory)
class AccountRecoveryFactory(DjangoModelFactory):
class AccountRecoveryFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring
class Meta(object):
model = AccountRecovery
django_get_or_create = ('user',)

View File

@@ -5,7 +5,7 @@ import unittest
from uuid import uuid4
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.test import TestCase, override_settings
from django.urls import reverse
from mock import patch
@@ -24,7 +24,7 @@ class TestActivateAccount(TestCase):
"""Tests for account creation"""
def setUp(self):
super(TestActivateAccount, self).setUp()
super(TestActivateAccount, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.username = "jack"
self.email = "jack@fake.edx.org"
self.password = "test-password"

View File

@@ -8,9 +8,9 @@ import datetime
import ddt
import six
from django.conf import settings
from django.conf import settings # lint-amnesty, pylint: disable=unused-import
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.forms import ValidationError
from django.test import TestCase, override_settings
from django.urls import reverse
@@ -19,7 +19,7 @@ from edx_toggles.toggles.testutils import override_waffle_switch
from mock import Mock
from pytz import UTC
from common.djangoapps.student.admin import AllowedAuthUserForm, COURSE_ENROLLMENT_ADMIN_SWITCH, UserAdmin, CourseEnrollmentForm
from common.djangoapps.student.admin import AllowedAuthUserForm, COURSE_ENROLLMENT_ADMIN_SWITCH, UserAdmin, CourseEnrollmentForm # lint-amnesty, pylint: disable=line-too-long
from common.djangoapps.student.models import AllowedAuthUser, CourseEnrollment, LoginFailures
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
@@ -38,7 +38,7 @@ class AdminCourseRolesPageTest(SharedModuleStoreTestCase):
cls.course = CourseFactory.create(org='edx')
def setUp(self):
super(AdminCourseRolesPageTest, self).setUp()
super(AdminCourseRolesPageTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(is_staff=True, is_superuser=True)
self.user.save()
@@ -178,7 +178,7 @@ class AdminUserPageTest(TestCase):
Unit tests for the UserAdmin view.
"""
def setUp(self):
super(AdminUserPageTest, self).setUp()
super(AdminUserPageTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.admin = UserAdmin(User, AdminSite())
def test_username_is_writable_for_user_creation(self):
@@ -221,7 +221,7 @@ class CourseEnrollmentAdminTest(SharedModuleStoreTestCase):
)
def setUp(self):
super(CourseEnrollmentAdminTest, self).setUp()
super(CourseEnrollmentAdminTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(is_staff=True, is_superuser=True)
self.course = CourseFactory()
self.course_enrollment = CourseEnrollmentFactory(
@@ -327,7 +327,7 @@ class LoginFailuresAdminTest(TestCase):
def setUp(self):
"""Setup."""
super(LoginFailuresAdminTest, self).setUp()
super(LoginFailuresAdminTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.client.login(username=self.user.username, password='test')
self.user2 = UserFactory.create(username=u'Zażółć gęślą jaźń')
self.user_lockout_until = datetime.datetime.now(UTC)
@@ -336,7 +336,7 @@ class LoginFailuresAdminTest(TestCase):
def tearDown(self):
"""Tear Down."""
super(LoginFailuresAdminTest, self).tearDown()
super(LoginFailuresAdminTest, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments
LoginFailures.objects.all().delete()
def test_unicode_username(self):
@@ -406,7 +406,7 @@ class CourseEnrollmentAdminFormTest(SharedModuleStoreTestCase):
cls.course = CourseOverviewFactory(start=now())
def setUp(self):
super(CourseEnrollmentAdminFormTest, self).setUp()
super(CourseEnrollmentAdminFormTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create()
def test_admin_model_form_create(self):

View File

@@ -5,12 +5,12 @@ Tests authz.py
import mock
from ccx_keys.locator import CCXLocator
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.models import AnonymousUser, User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from opaque_keys.edx.locator import CourseLocator
from common.djangoapps.student.auth import add_users, has_studio_read_access, has_studio_write_access, remove_users, user_has_role
from common.djangoapps.student.auth import add_users, has_studio_read_access, has_studio_write_access, remove_users, user_has_role # lint-amnesty, pylint: disable=line-too-long
from common.djangoapps.student.roles import CourseCreatorRole, CourseInstructorRole, CourseStaffRole
from common.djangoapps.student.tests.factories import AdminFactory
@@ -22,7 +22,7 @@ class CreatorGroupTest(TestCase):
def setUp(self):
""" Test case setup """
super(CreatorGroupTest, self).setUp()
super(CreatorGroupTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = User.objects.create_user('testuser', 'test+courses@edx.org', 'foo')
self.admin = User.objects.create_user('Mark', 'admin+courses@edx.org', 'foo')
self.admin.is_staff = True
@@ -150,7 +150,7 @@ class CCXCourseGroupTest(TestCase):
"""
Set up test variables
"""
super(CCXCourseGroupTest, self).setUp()
super(CCXCourseGroupTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.global_admin = AdminFactory()
self.staff = User.objects.create_user('teststaff', 'teststaff+courses@edx.org', 'foo')
self.ccx_course_key = CCXLocator.from_string('ccx-v1:edX+DemoX+Demo_Course+ccx@1')
@@ -188,7 +188,7 @@ class CourseGroupTest(TestCase):
def setUp(self):
""" Test case setup """
super(CourseGroupTest, self).setUp()
super(CourseGroupTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.global_admin = AdminFactory()
self.creator = User.objects.create_user('testcreator', 'testcreator+courses@edx.org', 'foo')
self.staff = User.objects.create_user('teststaff', 'teststaff+courses@edx.org', 'foo')

View File

@@ -31,7 +31,7 @@ class TestStudentDashboardEmailView(SharedModuleStoreTestCase):
cls.course = CourseFactory.create()
def setUp(self):
super(TestStudentDashboardEmailView, self).setUp()
super(TestStudentDashboardEmailView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
# Create student account
student = UserFactory.create()
@@ -51,7 +51,7 @@ class TestStudentDashboardEmailView(SharedModuleStoreTestCase):
)
def tearDown(self):
super(TestStudentDashboardEmailView, self).tearDown()
super(TestStudentDashboardEmailView, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments
BulkEmailFlag.objects.all().delete()
def test_email_flag_true(self):

View File

@@ -45,7 +45,7 @@ class CertificateDisplayTestBase(SharedModuleStoreTestCase):
cls.store.update_item(cls.course, cls.USERNAME)
def setUp(self):
super(CertificateDisplayTestBase, self).setUp()
super(CertificateDisplayTestBase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(username=self.USERNAME, password=self.PASSWORD)
result = self.client.login(username=self.USERNAME, password=self.PASSWORD)
self.assertTrue(result, msg="Could not log in")
@@ -120,7 +120,7 @@ class CertificateDashboardMessageDisplayTest(CertificateDisplayTestBase):
cls.course.save()
cls.store.update_item(cls.course, cls.USERNAME)
def _check_message(self, certificate_available_date):
def _check_message(self, certificate_available_date): # lint-amnesty, pylint: disable=missing-function-docstring
response = self.client.get(reverse('dashboard'))
if certificate_available_date is None:

View File

@@ -6,7 +6,7 @@ Test for user creation from sites with configuration overrides.
import json
import mock
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.test import TestCase
from django.urls import reverse
@@ -53,7 +53,7 @@ def fake_get_value(name, default=None):
class TestSite(TestCase):
"""Test for Account Creation from white labeled Sites"""
def setUp(self):
super(TestSite, self).setUp()
super(TestSite, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.username = "test_user"
self.url = reverse("create_account")
self.params = {

View File

@@ -13,7 +13,7 @@ from django.test.client import Client
from milestones.tests.utils import MilestonesTestCaseMixin
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from common.djangoapps.student.models import CourseEnrollment, DashboardConfiguration
from common.djangoapps.student.models import CourseEnrollment, DashboardConfiguration # lint-amnesty, pylint: disable=unused-import
from common.djangoapps.student.roles import GlobalStaff
from common.djangoapps.student.tests.factories import UserFactory
from common.djangoapps.student.views import get_course_enrollments
@@ -35,7 +35,7 @@ class TestCourseListing(ModuleStoreTestCase, MilestonesTestCaseMixin):
"""
Add a student & teacher
"""
super(TestCourseListing, self).setUp()
super(TestCourseListing, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.student = UserFactory()
self.teacher = UserFactory()
@@ -65,7 +65,7 @@ class TestCourseListing(ModuleStoreTestCase, MilestonesTestCaseMixin):
Reverse the setup
"""
self.client.logout()
super(TestCourseListing, self).tearDown()
super(TestCourseListing, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
def test_get_course_list(self):
@@ -125,7 +125,7 @@ class TestCourseListing(ModuleStoreTestCase, MilestonesTestCaseMixin):
Create good courses, courses that won't load, and deleted courses which still have
roles. Test course listing.
"""
mongo_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.mongo)
mongo_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.mongo) # lint-amnesty, pylint: disable=protected-access
good_location = mongo_store.make_course_key('testOrg', 'testCourse', 'RunBabyRun')
self._create_course_with_access_groups(good_location, default_store=ModuleStoreEnum.Type.mongo)

View File

@@ -43,7 +43,7 @@ class CreditCourseDashboardTest(ModuleStoreTestCase):
def setUp(self):
"""Create a course and an enrollment. """
super(CreditCourseDashboardTest, self).setUp()
super(CreditCourseDashboardTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
# Create a user and log in
self.user = UserFactory.create(username=self.USERNAME, password=self.PASSWORD)

View File

@@ -1,4 +1,4 @@
# coding=utf-8
# coding=utf-8 # lint-amnesty, pylint: disable=missing-module-docstring
import json
@@ -8,7 +8,7 @@ from string import capwords
import ddt
import six
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core import mail
from django.db import transaction
from django.http import HttpResponse
@@ -48,7 +48,7 @@ class TestException(Exception):
"""
Exception used for testing that nothing will catch explicitly
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def mock_render_to_string(template_name, context):
@@ -294,7 +294,7 @@ class EmailChangeRequestTests(EventTestMixin, EmailTemplateTagMixin, CacheIsolat
"""
def setUp(self, tracker='common.djangoapps.student.views.management.tracker'):
super(EmailChangeRequestTests, self).setUp(tracker)
super(EmailChangeRequestTests, self).setUp(tracker) # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create()
self.new_email = 'new.email@edx.org'
self.req_factory = RequestFactory()
@@ -329,7 +329,7 @@ class EmailChangeRequestTests(EventTestMixin, EmailTemplateTagMixin, CacheIsolat
self.assertEqual(expected_error, response_data['error'])
self.assertFalse(self.user.email_user.called)
@patch('common.djangoapps.student.views.management.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))
@patch('common.djangoapps.student.views.management.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True)) # lint-amnesty, pylint: disable=line-too-long
def test_duplicate_activation_key(self):
"""
Assert that if two users change Email address simultaneously, no error is thrown
@@ -418,14 +418,14 @@ class EmailChangeRequestTests(EventTestMixin, EmailTemplateTagMixin, CacheIsolat
@ddt.ddt
@patch('common.djangoapps.student.views.management.render_to_response', Mock(side_effect=mock_render_to_response, autospec=True))
@patch('common.djangoapps.student.views.management.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))
@patch('common.djangoapps.student.views.management.render_to_response', Mock(side_effect=mock_render_to_response, autospec=True)) # lint-amnesty, pylint: disable=line-too-long
@patch('common.djangoapps.student.views.management.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True)) # lint-amnesty, pylint: disable=line-too-long
class EmailChangeConfirmationTests(EmailTestMixin, EmailTemplateTagMixin, CacheIsolationMixin, TransactionTestCase):
"""
Test that confirmation of email change requests function even in the face of exceptions thrown while sending email
"""
def setUp(self):
super(EmailChangeConfirmationTests, self).setUp()
super(EmailChangeConfirmationTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.clear_caches()
self.addCleanup(self.clear_caches)
self.user = UserFactory.create()
@@ -602,7 +602,7 @@ class SecondaryEmailChangeRequestTests(EventTestMixin, EmailTemplateTagMixin, Ca
"""
def setUp(self, tracker='common.djangoapps.student.views.management.tracker'):
super(SecondaryEmailChangeRequestTests, self).setUp(tracker)
super(SecondaryEmailChangeRequestTests, self).setUp(tracker) # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create()
self.new_secondary_email = 'new.secondary.email@edx.org'
self.req_factory = RequestFactory()

View File

@@ -53,7 +53,7 @@ class EnrollmentTest(UrlResetMixin, SharedModuleStoreTestCase):
@patch.dict(settings.FEATURES, {'EMBARGO': True})
def setUp(self):
""" Create a course and user, then log in. """
super(EnrollmentTest, self).setUp()
super(EnrollmentTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(username=self.USERNAME, email=self.EMAIL, password=self.PASSWORD)
self.client.login(username=self.USERNAME, password=self.PASSWORD)
self.course_limited.max_student_enrollments_allowed = 1

View File

@@ -19,7 +19,7 @@ class TestUserProfileEvents(UserSettingsEventTestMixin, TestCase):
Test that we emit field change events when UserProfile models are changed.
"""
def setUp(self):
super(TestUserProfileEvents, self).setUp()
super(TestUserProfileEvents, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.table = 'auth_userprofile'
self.user = UserFactory.create()
self.profile = self.user.profile
@@ -93,7 +93,7 @@ class TestUserEvents(UserSettingsEventTestMixin, TestCase):
Test that we emit field change events when User models are changed.
"""
def setUp(self):
super(TestUserEvents, self).setUp()
super(TestUserEvents, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create()
self.reset_tracker()
self.table = 'auth_user'
@@ -161,7 +161,7 @@ class TestUserEvents(UserSettingsEventTestMixin, TestCase):
"""
Test that when a user's email changes, the user is enrolled in pending courses.
"""
pending_enrollment = CourseEnrollmentAllowedFactory(auto_enroll=True)
pending_enrollment = CourseEnrollmentAllowedFactory(auto_enroll=True) # lint-amnesty, pylint: disable=unused-variable
# the e-mail will change to test@edx.org (from something else)
self.assertNotEqual(self.user.email, 'test@edx.org')

View File

@@ -25,7 +25,7 @@ class TestLoginHelper(TestCase):
static_url = settings.STATIC_URL
def setUp(self):
super(TestLoginHelper, self).setUp()
super(TestLoginHelper, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.request = RequestFactory()
@staticmethod

View File

@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- # lint-amnesty, pylint: disable=missing-module-docstring
import json
@@ -9,10 +9,10 @@ from django.urls import reverse
from openedx.core.djangoapps.user_api.accounts import USERNAME_BAD_LENGTH_MSG
class TestLongUsernameEmail(TestCase):
class TestLongUsernameEmail(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def setUp(self):
super(TestLongUsernameEmail, self).setUp()
super(TestLongUsernameEmail, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.url = reverse('create_account')
self.url_params = {
'username': 'username',
@@ -44,7 +44,7 @@ class TestLongUsernameEmail(TestCase):
"""
Test name cannot contain html.
"""
self.url_params['name'] = '<p style="font-size:300px; color:green;"></br>Name<input type="text"></br>Content spoof'
self.url_params['name'] = '<p style="font-size:300px; color:green;"></br>Name<input type="text"></br>Content spoof' # lint-amnesty, pylint: disable=line-too-long
response = self.client.post(self.url, self.url_params)
self.assertEqual(response.status_code, 400)

View File

@@ -1,10 +1,11 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import datetime
import hashlib
import ddt
import factory
import pytz
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.models import AnonymousUser, User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.cache import cache
from django.db.models import signals
from django.db.models.functions import Lower
@@ -33,14 +34,14 @@ from xmodule.modulestore.tests.factories import CourseFactory
@ddt.ddt
class CourseEnrollmentTests(SharedModuleStoreTestCase):
class CourseEnrollmentTests(SharedModuleStoreTestCase): # lint-amnesty, pylint: disable=missing-class-docstring
@classmethod
def setUpClass(cls):
super(CourseEnrollmentTests, cls).setUpClass()
cls.course = CourseFactory()
def setUp(self):
super(CourseEnrollmentTests, self).setUp()
super(CourseEnrollmentTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory()
self.user_2 = UserFactory()
@@ -59,7 +60,7 @@ class CourseEnrollmentTests(SharedModuleStoreTestCase):
self.assertIsNone(CourseEnrollment.generate_enrollment_status_hash(AnonymousUser()))
# No enrollments
expected = hashlib.md5(self.user.username.encode('utf-8')).hexdigest()
expected = hashlib.md5(self.user.username.encode('utf-8')).hexdigest() # lint-amnesty, pylint: disable=no-member
self.assertEqual(CourseEnrollment.generate_enrollment_status_hash(self.user), expected)
self.assert_enrollment_status_hash_cached(self.user, expected)
@@ -108,20 +109,20 @@ class CourseEnrollmentTests(SharedModuleStoreTestCase):
def test_users_enrolled_in_active_only(self):
"""CourseEnrollment.users_enrolled_in should return only Users with active enrollments when
`include_inactive` has its default value (False)."""
CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id, is_active=True)
CourseEnrollmentFactory.create(user=self.user_2, course_id=self.course.id, is_active=False)
CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id, is_active=True) # lint-amnesty, pylint: disable=no-member
CourseEnrollmentFactory.create(user=self.user_2, course_id=self.course.id, is_active=False) # lint-amnesty, pylint: disable=no-member
active_enrolled_users = list(CourseEnrollment.objects.users_enrolled_in(self.course.id))
active_enrolled_users = list(CourseEnrollment.objects.users_enrolled_in(self.course.id)) # lint-amnesty, pylint: disable=no-member
self.assertEqual([self.user], active_enrolled_users)
def test_users_enrolled_in_all(self):
"""CourseEnrollment.users_enrolled_in should return active and inactive users when
`include_inactive` is True."""
CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id, is_active=True)
CourseEnrollmentFactory.create(user=self.user_2, course_id=self.course.id, is_active=False)
CourseEnrollmentFactory.create(user=self.user, course_id=self.course.id, is_active=True) # lint-amnesty, pylint: disable=no-member
CourseEnrollmentFactory.create(user=self.user_2, course_id=self.course.id, is_active=False) # lint-amnesty, pylint: disable=no-member
all_enrolled_users = list(
CourseEnrollment.objects.users_enrolled_in(self.course.id, include_inactive=True)
CourseEnrollment.objects.users_enrolled_in(self.course.id, include_inactive=True) # lint-amnesty, pylint: disable=no-member
)
self.assertListEqual([self.user, self.user_2], all_enrolled_users)
@@ -169,7 +170,7 @@ class CourseEnrollmentTests(SharedModuleStoreTestCase):
@ddt.data(*(set(CourseMode.ALL_MODES) - set(CourseMode.AUDIT_MODES)))
def test_upgrade_deadline_for_non_upgradeable_enrollment(self, mode):
""" The property should return None if an upgrade cannot be upgraded. """
enrollment = CourseEnrollmentFactory(course_id=self.course.id, mode=mode)
enrollment = CourseEnrollmentFactory(course_id=self.course.id, mode=mode) # lint-amnesty, pylint: disable=no-member
self.assertIsNone(enrollment.upgrade_deadline)
@skip_unless_lms
@@ -253,7 +254,7 @@ class PendingNameChangeTests(SharedModuleStoreTestCase):
cls.user = UserFactory()
cls.user2 = UserFactory()
def setUp(self):
def setUp(self): # lint-amnesty, pylint: disable=super-method-not-called
self.name_change, _ = PendingNameChange.objects.get_or_create(
user=self.user,
new_name='New Name PII',
@@ -282,7 +283,7 @@ class PendingEmailChangeTests(SharedModuleStoreTestCase):
cls.user = UserFactory()
cls.user2 = UserFactory()
def setUp(self):
def setUp(self): # lint-amnesty, pylint: disable=super-method-not-called
self.email_change, _ = PendingEmailChange.objects.get_or_create(
user=self.user,
new_email='new@example.com',
@@ -300,10 +301,10 @@ class PendingEmailChangeTests(SharedModuleStoreTestCase):
self.assertEqual(1, len(PendingEmailChange.objects.all()))
class TestCourseEnrollmentAllowed(TestCase):
class TestCourseEnrollmentAllowed(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def setUp(self):
super(TestCourseEnrollmentAllowed, self).setUp()
super(TestCourseEnrollmentAllowed, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.email = 'learner@example.com'
self.course_key = CourseKey.from_string("course-v1:edX+DemoX+Demo_Course")
self.user = UserFactory.create()
@@ -354,8 +355,8 @@ class TestManualEnrollmentAudit(SharedModuleStoreTestCase):
the enrolled_email and reason columns of each row associated with that
enrollment.
"""
enrollment = CourseEnrollment.enroll(self.user, self.course.id)
other_enrollment = CourseEnrollment.enroll(self.user, self.other_course.id)
enrollment = CourseEnrollment.enroll(self.user, self.course.id) # lint-amnesty, pylint: disable=no-member
other_enrollment = CourseEnrollment.enroll(self.user, self.other_course.id) # lint-amnesty, pylint: disable=no-member
ManualEnrollmentAudit.create_manual_enrollment_audit(
self.instructor, self.user.email, ALLOWEDTOENROLL_TO_ENROLLED,
'manually enrolling unenrolled user', enrollment
@@ -413,7 +414,7 @@ class TestUserPostSaveCallback(SharedModuleStoreTestCase):
changing any existing course mode states.
"""
def setUp(self):
super(TestUserPostSaveCallback, self).setUp()
super(TestUserPostSaveCallback, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course = CourseFactory.create()
@ddt.data(*(set(CourseMode.ALL_MODES) - set(CourseMode.AUDIT_MODES)))

View File

@@ -17,7 +17,7 @@ class ProfileParentalControlsTest(TestCase):
password = "test"
def setUp(self):
super(ProfileParentalControlsTest, self).setUp()
super(ProfileParentalControlsTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(password=self.password)
self.profile = UserProfile.objects.get(id=self.user.id)

View File

@@ -6,14 +6,14 @@ This test file will verify proper password policy enforcement, which is an optio
import json
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import AnonymousUser # lint-amnesty, pylint: disable=unused-import
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from django.urls import reverse
from mock import patch
from mock import patch # lint-amnesty, pylint: disable=unused-import
from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory
from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory # lint-amnesty, pylint: disable=unused-import
from common.djangoapps.util.password_policy_validators import create_validator_config
@@ -22,7 +22,7 @@ class TestPasswordPolicy(TestCase):
Go through some password policy tests to make sure things are properly working
"""
def setUp(self):
super(TestPasswordPolicy, self).setUp()
super(TestPasswordPolicy, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.url = reverse('create_account')
self.request_factory = RequestFactory()
self.url_params = {
@@ -34,7 +34,7 @@ class TestPasswordPolicy(TestCase):
}
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 6})
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 6}) # lint-amnesty, pylint: disable=line-too-long
])
def test_password_length_too_short(self):
self.url_params['password'] = 'aaa'
@@ -47,7 +47,7 @@ class TestPasswordPolicy(TestCase):
)
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 6})
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 6}) # lint-amnesty, pylint: disable=line-too-long
])
def test_password_length_long_enough(self):
self.url_params['password'] = 'ThisIsALongerPassword'
@@ -57,7 +57,7 @@ class TestPasswordPolicy(TestCase):
self.assertTrue(obj['success'])
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.MaximumLengthValidator', {'max_length': 12})
create_validator_config('common.djangoapps.util.password_policy_validators.MaximumLengthValidator', {'max_length': 12}) # lint-amnesty, pylint: disable=line-too-long
])
def test_password_length_too_long(self):
self.url_params['password'] = 'ThisPasswordIsWayTooLong'
@@ -70,7 +70,7 @@ class TestPasswordPolicy(TestCase):
)
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.UppercaseValidator', {'min_upper': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.UppercaseValidator', {'min_upper': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_password_not_enough_uppercase(self):
self.url_params['password'] = 'thisshouldfail'
@@ -83,7 +83,7 @@ class TestPasswordPolicy(TestCase):
)
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.UppercaseValidator', {'min_upper': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.UppercaseValidator', {'min_upper': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_password_enough_uppercase(self):
self.url_params['password'] = 'ThisShouldPass'
@@ -93,7 +93,7 @@ class TestPasswordPolicy(TestCase):
self.assertTrue(obj['success'])
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.LowercaseValidator', {'min_lower': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.LowercaseValidator', {'min_lower': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_password_not_enough_lowercase(self):
self.url_params['password'] = 'THISSHOULDFAIL'
@@ -106,7 +106,7 @@ class TestPasswordPolicy(TestCase):
)
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.LowercaseValidator', {'min_lower': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.LowercaseValidator', {'min_lower': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_password_enough_lowercase(self):
self.url_params['password'] = 'ThisShouldPass'
@@ -116,7 +116,7 @@ class TestPasswordPolicy(TestCase):
self.assertTrue(obj['success'])
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.PunctuationValidator', {'min_punctuation': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.PunctuationValidator', {'min_punctuation': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_not_enough_punctuations(self):
self.url_params['password'] = 'thisshouldfail'
@@ -129,7 +129,7 @@ class TestPasswordPolicy(TestCase):
)
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.PunctuationValidator', {'min_punctuation': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.PunctuationValidator', {'min_punctuation': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_enough_punctuations(self):
self.url_params['password'] = 'Th!sSh.uldPa$*'
@@ -139,7 +139,7 @@ class TestPasswordPolicy(TestCase):
self.assertTrue(obj['success'])
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.NumericValidator', {'min_numeric': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.NumericValidator', {'min_numeric': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_not_enough_numeric_characters(self):
# The unicode ២ is the number 2 in Khmer and the ٧ is the Arabic-Indic number 7
@@ -153,7 +153,7 @@ class TestPasswordPolicy(TestCase):
)
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.NumericValidator', {'min_numeric': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.NumericValidator', {'min_numeric': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_enough_numeric_characters(self):
# The unicode ២ is the number 2 in Khmer
@@ -164,7 +164,7 @@ class TestPasswordPolicy(TestCase):
self.assertTrue(obj['success'])
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.AlphabeticValidator', {'min_alphabetic': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.AlphabeticValidator', {'min_alphabetic': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_not_enough_alphabetic_characters(self):
self.url_params['password'] = '123456ab'
@@ -177,7 +177,7 @@ class TestPasswordPolicy(TestCase):
)
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.AlphabeticValidator', {'min_alphabetic': 3})
create_validator_config('common.djangoapps.util.password_policy_validators.AlphabeticValidator', {'min_alphabetic': 3}) # lint-amnesty, pylint: disable=line-too-long
])
def test_enough_alphabetic_characters(self):
self.url_params['password'] = u'𝒯𝓗Ï𝓼𝒫å𝓼𝓼𝔼𝓼'
@@ -187,10 +187,10 @@ class TestPasswordPolicy(TestCase):
self.assertTrue(obj['success'])
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 3}),
create_validator_config('common.djangoapps.util.password_policy_validators.UppercaseValidator', {'min_upper': 3}),
create_validator_config('common.djangoapps.util.password_policy_validators.NumericValidator', {'min_numeric': 3}),
create_validator_config('common.djangoapps.util.password_policy_validators.PunctuationValidator', {'min_punctuation': 3}),
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 3}), # lint-amnesty, pylint: disable=line-too-long
create_validator_config('common.djangoapps.util.password_policy_validators.UppercaseValidator', {'min_upper': 3}), # lint-amnesty, pylint: disable=line-too-long
create_validator_config('common.djangoapps.util.password_policy_validators.NumericValidator', {'min_numeric': 3}), # lint-amnesty, pylint: disable=line-too-long
create_validator_config('common.djangoapps.util.password_policy_validators.PunctuationValidator', {'min_punctuation': 3}), # lint-amnesty, pylint: disable=line-too-long
])
def test_multiple_errors_fail(self):
self.url_params['password'] = 'thisshouldfail'
@@ -206,11 +206,11 @@ class TestPasswordPolicy(TestCase):
self.assertEqual(obj['password'][i]['user_message'], error_strings[i])
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 3}),
create_validator_config('common.djangoapps.util.password_policy_validators.UppercaseValidator', {'min_upper': 3}),
create_validator_config('common.djangoapps.util.password_policy_validators.LowercaseValidator', {'min_lower': 3}),
create_validator_config('common.djangoapps.util.password_policy_validators.NumericValidator', {'min_numeric': 3}),
create_validator_config('common.djangoapps.util.password_policy_validators.PunctuationValidator', {'min_punctuation': 3}),
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 3}), # lint-amnesty, pylint: disable=line-too-long
create_validator_config('common.djangoapps.util.password_policy_validators.UppercaseValidator', {'min_upper': 3}), # lint-amnesty, pylint: disable=line-too-long
create_validator_config('common.djangoapps.util.password_policy_validators.LowercaseValidator', {'min_lower': 3}), # lint-amnesty, pylint: disable=line-too-long
create_validator_config('common.djangoapps.util.password_policy_validators.NumericValidator', {'min_numeric': 3}), # lint-amnesty, pylint: disable=line-too-long
create_validator_config('common.djangoapps.util.password_policy_validators.PunctuationValidator', {'min_punctuation': 3}), # lint-amnesty, pylint: disable=line-too-long
])
def test_multiple_errors_pass(self):
self.url_params['password'] = u'tH1s Sh0u!d P3#$!'
@@ -243,8 +243,8 @@ class TestPasswordPolicy(TestCase):
self.assertTrue(obj['success'])
@override_settings(AUTH_PASSWORD_VALIDATORS=[
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 6}),
create_validator_config('common.djangoapps.util.password_policy_validators.MaximumLengthValidator', {'max_length': 75}),
create_validator_config('common.djangoapps.util.password_policy_validators.MinimumLengthValidator', {'min_length': 6}), # lint-amnesty, pylint: disable=line-too-long
create_validator_config('common.djangoapps.util.password_policy_validators.MaximumLengthValidator', {'max_length': 75}), # lint-amnesty, pylint: disable=line-too-long
])
def test_with_unicode(self):
self.url_params['password'] = u'四節比分和七年前'
@@ -259,7 +259,7 @@ class TestUsernamePasswordNonmatch(TestCase):
Test that registration username and password fields differ
"""
def setUp(self):
super(TestUsernamePasswordNonmatch, self).setUp()
super(TestUsernamePasswordNonmatch, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.url = reverse('create_account')
self.url_params = {

View File

@@ -15,8 +15,8 @@ from pytz import UTC
from six.moves import range, zip
from common.test.utils import XssTestMixin
from common.djangoapps.course_modes.tests.factories import CourseModeFactory
from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration_context
from common.djangoapps.course_modes.tests.factories import CourseModeFactory # lint-amnesty, pylint: disable=unused-import
from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration_context # lint-amnesty, pylint: disable=unused-import
from common.djangoapps.student.models import CourseEnrollment, DashboardConfiguration
from common.djangoapps.student.tests.factories import UserFactory
from common.djangoapps.student.views import get_course_enrollments
@@ -37,7 +37,7 @@ class TestRecentEnrollments(ModuleStoreTestCase, XssTestMixin):
"""
Add a student
"""
super(TestRecentEnrollments, self).setUp()
super(TestRecentEnrollments, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.student = UserFactory()
self.student.set_password(self.PASSWORD)
self.student.save()
@@ -159,7 +159,7 @@ class TestRecentEnrollments(ModuleStoreTestCase, XssTestMixin):
'Course2',
'Run2'
)
course, _ = self._create_course_and_enrollment(course_location)
course, _ = self._create_course_and_enrollment(course_location) # lint-amnesty, pylint: disable=unused-variable
self.client.login(username=self.student.username, password=self.PASSWORD)
response = self.client.get(reverse("dashboard"))

View File

@@ -51,7 +51,7 @@ class RefundableTest(SharedModuleStoreTestCase):
def setUp(self):
""" Setup components used by each refund test."""
super(RefundableTest, self).setUp()
super(RefundableTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(password=self.USER_PASSWORD)
self.verified_mode = CourseModeFactory.create(
course_id=self.course.id,

View File

@@ -9,7 +9,7 @@ import ddt
import pytest
from django.apps import apps
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.test import TestCase
from django.urls import reverse
@@ -61,7 +61,7 @@ def retirement_status(retirement_user): # pylint: disable=redefined-outer-name
@pytest.fixture
def two_users_same_username_different_case(retirement_status):
def two_users_same_username_different_case(retirement_status): # lint-amnesty, pylint: disable=missing-function-docstring, redefined-outer-name, unused-argument
user1 = UserFactory.create(username='TestUser')
user2 = UserFactory.create(username='testuser')
UserRetirementStatus = apps.get_model('user_api', 'UserRetirementStatus')
@@ -88,7 +88,7 @@ def check_email_against_fmt(hashed_email):
assert hashed_email.endswith(settings.RETIRED_EMAIL_DOMAIN)
def test_get_retired_username(retirement_user):
def test_get_retired_username(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Basic testing of getting retired usernames. The hasher is opaque
to us, we just care that it's succeeding and using our format.
@@ -107,7 +107,7 @@ def test_get_retired_username_status_exists(retirement_user, retirement_status):
assert retirement_status.retired_username == hashed_username
def test_get_all_retired_usernames_by_username(retirement_user):
def test_get_all_retired_usernames_by_username(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Check that all salts are used for this method and return expected
formats.
@@ -122,7 +122,7 @@ def test_get_all_retired_usernames_by_username(retirement_user):
assert len(hashed_usernames) == len(set(hashed_usernames))
def test_is_username_retired_is_retired(retirement_user):
def test_is_username_retired_is_retired(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Check functionality of is_username_retired when username is retired
"""
@@ -136,14 +136,14 @@ def test_is_username_retired_is_retired(retirement_user):
assert is_username_retired(original_username)
def test_is_username_retired_not_retired(retirement_user):
def test_is_username_retired_not_retired(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Check functionality of is_username_retired when username is not retired
"""
assert not is_username_retired(retirement_user.username)
def test_is_email_retired_is_retired(retirement_user):
def test_is_email_retired_is_retired(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Check functionality of is_email_retired when email is retired
"""
@@ -157,14 +157,14 @@ def test_is_email_retired_is_retired(retirement_user):
assert is_email_retired(original_email)
def test_is_email_retired_not_retired(retirement_user):
def test_is_email_retired_not_retired(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Check functionality of is_email_retired when email is not retired
"""
assert not is_email_retired(retirement_user.email)
def test_get_retired_email(retirement_user):
def test_get_retired_email(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Basic testing of retired emails.
"""
@@ -182,7 +182,7 @@ def test_get_retired_email_status_exists(retirement_user, retirement_status): #
assert retirement_status.retired_email == hashed_email
def test_get_all_retired_email_by_email(retirement_user):
def test_get_all_retired_email_by_email(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Check that all salts are used for this method and return expected
formats.
@@ -197,27 +197,27 @@ def test_get_all_retired_email_by_email(retirement_user):
assert len(hashed_emails) == len(set(hashed_emails))
def test_get_correct_user_varying_by_case_only(two_users_same_username_different_case):
def test_get_correct_user_varying_by_case_only(two_users_same_username_different_case): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Check that two users - one retired, one active - with the same username except for case can be found.
"""
retired_status, retired_user, active_user = two_users_same_username_different_case
retired_status, retired_user, active_user = two_users_same_username_different_case # lint-amnesty, pylint: disable=unused-variable
first_user = get_potentially_retired_user_by_username(retired_status.original_username)
second_user = get_potentially_retired_user_by_username(active_user.username)
assert first_user.username != second_user.username
assert second_user.username == active_user.username
def test_get_potentially_retired_user_username_match(retirement_user):
def test_get_potentially_retired_user_username_match(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Check that we can pass in an un-retired username and get the
user-to-be-retired back.
"""
hashed_username = get_retired_username_by_username(retirement_user.username)
assert get_potentially_retired_user_by_username_and_hash(retirement_user.username, hashed_username) == retirement_user
assert get_potentially_retired_user_by_username_and_hash(retirement_user.username, hashed_username) == retirement_user # lint-amnesty, pylint: disable=line-too-long
def test_get_potentially_retired_user_hashed_match(retirement_user):
def test_get_potentially_retired_user_hashed_match(retirement_user): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Check that we can pass in a hashed username and get the
user-to-be-retired back.
@@ -270,7 +270,7 @@ class TestRegisterRetiredUsername(TestCase):
INVALID_ERR_MSG = ('It looks like', 'belongs to an existing account. Try again with a different username.')
def setUp(self):
super(TestRegisterRetiredUsername, self).setUp()
super(TestRegisterRetiredUsername, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.url = reverse('user_api_registration')
self.url_params = {
'username': 'username',
@@ -281,7 +281,7 @@ class TestRegisterRetiredUsername(TestCase):
'honor_code': 'true',
}
def _validate_exiting_username_response(self, orig_username, response, start_msg=INVALID_ACCT_ERR_MSG[0], end_msg=INVALID_ACCT_ERR_MSG[1]):
def _validate_exiting_username_response(self, orig_username, response, start_msg=INVALID_ACCT_ERR_MSG[0], end_msg=INVALID_ACCT_ERR_MSG[1]): # lint-amnesty, pylint: disable=line-too-long
"""
Validates a response stating that a username already exists -or- is invalid.
"""
@@ -307,7 +307,7 @@ class TestRegisterRetiredUsername(TestCase):
# Attempt to create another account with the same username that's been retired.
self.url_params['username'] = orig_username
response = self.client.post(self.url, self.url_params)
self._validate_exiting_username_response(orig_username, response, self.INVALID_ERR_MSG[0], self.INVALID_ERR_MSG[1])
self._validate_exiting_username_response(orig_username, response, self.INVALID_ERR_MSG[0], self.INVALID_ERR_MSG[1]) # lint-amnesty, pylint: disable=line-too-long
def test_username_close_to_retired_format_active(self):
"""

View File

@@ -28,7 +28,7 @@ class RolesTestCase(TestCase):
"""
def setUp(self):
super(RolesTestCase, self).setUp()
super(RolesTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course_key = CourseKey.from_string('edX/toy/2012_Fall')
self.course_loc = self.course_key.make_usage_key('course', '2012_Fall')
self.anonymous_user = AnonymousUserFactory()
@@ -166,7 +166,7 @@ class RolesTestCase(TestCase):
@ddt.ddt
class RoleCacheTestCase(TestCase):
class RoleCacheTestCase(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
IN_KEY = CourseKey.from_string('edX/toy/2012_Fall')
NOT_IN_KEY = CourseKey.from_string('edX/toy/2013_Fall')
@@ -180,7 +180,7 @@ class RoleCacheTestCase(TestCase):
)
def setUp(self):
super(RoleCacheTestCase, self).setUp()
super(RoleCacheTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory()
@ddt.data(*ROLES)
@@ -198,6 +198,6 @@ class RoleCacheTestCase(TestCase):
@ddt.data(*ROLES)
@ddt.unpack
def test_empty_cache(self, role, target):
def test_empty_cache(self, role, target): # lint-amnesty, pylint: disable=unused-argument
cache = RoleCache(self.user)
self.assertFalse(cache.has_role(*target))

View File

@@ -21,7 +21,7 @@ class SendActivationEmailTestCase(TestCase):
"""
def setUp(self):
""" Setup components used by each test."""
super(SendActivationEmailTestCase, self).setUp()
super(SendActivationEmailTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.student = UserFactory()
registration = Registration()
@@ -45,7 +45,7 @@ class SendActivationEmailTestCase(TestCase):
@mock.patch('time.sleep', mock.Mock(return_value=None))
@mock.patch('common.djangoapps.student.tasks.log')
@mock.patch('common.djangoapps.student.tasks.ace.send', mock.Mock(side_effect=RecoverableChannelDeliveryError(None, None)))
@mock.patch('common.djangoapps.student.tasks.ace.send', mock.Mock(side_effect=RecoverableChannelDeliveryError(None, None))) # lint-amnesty, pylint: disable=line-too-long
def test_RetrySendUntilFail(self, mock_log):
"""
Tests retries when the activation email doesn't send

View File

@@ -21,7 +21,7 @@ class UserProfilePropertiesTest(CacheIsolationTestCase):
ENABLED_CACHES = ['default']
def setUp(self):
super(UserProfilePropertiesTest, self).setUp()
super(UserProfilePropertiesTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create(password=self.password)
self.profile = self.user.profile

View File

@@ -18,7 +18,7 @@ class UserStandingTest(TestCase):
"""test suite for user standing view for enabling and disabling accounts"""
def setUp(self):
super(UserStandingTest, self).setUp()
super(UserStandingTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
# create users
self.bad_user = UserFactory.create(
username='bad_user',
@@ -72,7 +72,7 @@ class UserStandingTest(TestCase):
self.assertEqual(
UserStanding.objects.filter(user=self.good_user).count(), 0
)
response = self.admin_client.post(reverse('disable_account_ajax'), {
response = self.admin_client.post(reverse('disable_account_ajax'), { # lint-amnesty, pylint: disable=unused-variable
'username': self.good_user.username,
'account_action': 'disable',
})
@@ -87,7 +87,7 @@ class UserStandingTest(TestCase):
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
def test_reenable_account(self):
response = self.admin_client.post(reverse('disable_account_ajax'), {
response = self.admin_client.post(reverse('disable_account_ajax'), { # lint-amnesty, pylint: disable=unused-variable
'username': self.bad_user.username,
'account_action': 'reenable'
})

View File

@@ -48,7 +48,7 @@ class TestCourseVerificationStatus(UrlResetMixin, ModuleStoreTestCase):
def setUp(self):
# Invoke UrlResetMixin
super(TestCourseVerificationStatus, self).setUp()
super(TestCourseVerificationStatus, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory(password="edx")
self.course = CourseFactory.create()

View File

@@ -7,7 +7,7 @@ import itertools
import json
import re
import unittest
from datetime import datetime, timedelta
from datetime import datetime, timedelta # lint-amnesty, pylint: disable=unused-import
import ddt
import six
@@ -40,7 +40,7 @@ from common.djangoapps.student.helpers import DISABLE_UNENROLL_CERT_STATES
from common.djangoapps.student.models import CourseEnrollment, UserProfile
from common.djangoapps.student.signals import REFUND_ORDER
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
from common.djangoapps.util.milestones_helpers import get_course_milestones, remove_prerequisite_course, set_prerequisite_courses
from common.djangoapps.util.milestones_helpers import get_course_milestones, remove_prerequisite_course, set_prerequisite_courses # lint-amnesty, pylint: disable=line-too-long
from common.djangoapps.util.testing import UrlResetMixin
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
@@ -64,7 +64,7 @@ class TestStudentDashboardUnenrollments(SharedModuleStoreTestCase):
def setUp(self):
""" Create a course and user, then log in. """
super(TestStudentDashboardUnenrollments, self).setUp()
super(TestStudentDashboardUnenrollments, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory()
self.enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user)
self.cert_status = 'processing'
@@ -196,7 +196,7 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
"""
Create a course and user, then log in.
"""
super(StudentDashboardTests, self).setUp()
super(StudentDashboardTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory()
self.client.login(username=self.user.username, password=PASSWORD)
self.path = reverse('dashboard')
@@ -227,11 +227,11 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
Verify that learners are not able to see their final grade before the end
of course in the learner dashboard
"""
self.course_key = CourseKey.from_string('course-v1:edX+DemoX+Demo_Course')
self.course = CourseOverviewFactory.create(id=self.course_key, end_date=self.TOMORROW,
self.course_key = CourseKey.from_string('course-v1:edX+DemoX+Demo_Course') # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.course = CourseOverviewFactory.create(id=self.course_key, end_date=self.TOMORROW, # lint-amnesty, pylint: disable=attribute-defined-outside-init
certificate_available_date=self.THREE_YEARS_AGO,
lowest_passing_grade=0.3)
self.course_enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user)
self.course_enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user) # lint-amnesty, pylint: disable=attribute-defined-outside-init
GeneratedCertificateFactory(status='notpassing', course_id=self.course.id, user=self.user, grade=0.45)
response = self.client.get(reverse('dashboard'))
@@ -244,11 +244,11 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
Verify that learners are able to see their final grade of the course in
the learner dashboard after the course had ended
"""
self.course_key = CourseKey.from_string('course-v1:edX+DemoX+Demo_Course')
self.course = CourseOverviewFactory.create(id=self.course_key, end_date=self.THREE_YEARS_AGO,
self.course_key = CourseKey.from_string('course-v1:edX+DemoX+Demo_Course') # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.course = CourseOverviewFactory.create(id=self.course_key, end_date=self.THREE_YEARS_AGO, # lint-amnesty, pylint: disable=attribute-defined-outside-init
certificate_available_date=self.TOMORROW,
lowest_passing_grade=0.3)
self.course_enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user)
self.course_enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user) # lint-amnesty, pylint: disable=attribute-defined-outside-init
GeneratedCertificateFactory(status='notpassing', course_id=self.course.id, user=self.user, grade=0.45)
response = self.client.get(reverse('dashboard'))
@@ -269,8 +269,8 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
Verify that the course sharing icons show up if course is starting in future and
any of marketing or social sharing urls are set.
"""
self.course = CourseFactory.create(start=self.TOMORROW, emit_signals=True, default_store=modulestore_type)
self.course_enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user)
self.course = CourseFactory.create(start=self.TOMORROW, emit_signals=True, default_store=modulestore_type) # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.course_enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user) # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.set_course_sharing_urls(set_marketing, set_social_sharing)
# Assert course sharing icons
@@ -285,14 +285,14 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
If we remove the prerequisite and access the dashboard again, the prerequisite
should not appear.
"""
self.pre_requisite_course = CourseFactory.create(org='edx', number='999', display_name='Pre requisite Course')
self.course = CourseFactory.create(
self.pre_requisite_course = CourseFactory.create(org='edx', number='999', display_name='Pre requisite Course') # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.course = CourseFactory.create( # lint-amnesty, pylint: disable=attribute-defined-outside-init
org='edx',
number='998',
display_name='Test Course',
pre_requisite_courses=[six.text_type(self.pre_requisite_course.id)]
)
self.course_enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user)
self.course_enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user) # lint-amnesty, pylint: disable=attribute-defined-outside-init
set_prerequisite_courses(self.course.id, [six.text_type(self.pre_requisite_course.id)])
response = self.client.get(reverse('dashboard'))
@@ -506,7 +506,7 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
start=self.TOMORROW, self_paced=True, enrollment_end=self.TOMORROW
)
mock_course_overview.return_value = mocked_course_overview
course_enrollment = CourseEnrollmentFactory(user=self.user, course_id=six.text_type(mocked_course_overview.id), created=self.THREE_YEARS_AGO)
course_enrollment = CourseEnrollmentFactory(user=self.user, course_id=six.text_type(mocked_course_overview.id), created=self.THREE_YEARS_AGO) # lint-amnesty, pylint: disable=line-too-long
mock_course_runs.return_value = [
{
'key': str(mocked_course_overview.id),
@@ -516,7 +516,7 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
'status': 'published'
}
]
entitlement = CourseEntitlementFactory(user=self.user, enrollment_course_run=course_enrollment, created=self.THREE_YEARS_AGO)
entitlement = CourseEntitlementFactory(user=self.user, enrollment_course_run=course_enrollment, created=self.THREE_YEARS_AGO) # lint-amnesty, pylint: disable=line-too-long
program = ProgramFactory()
program['courses'][0]['course_runs'] = [{'key': six.text_type(mocked_course_overview.id)}]
program['courses'][0]['uuid'] = entitlement.course_uuid
@@ -619,7 +619,7 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
return ''.join(response.content.decode('utf-8').split())
@staticmethod
def _pull_course_run_from_course_key(course_key_string):
def _pull_course_run_from_course_key(course_key_string): # lint-amnesty, pylint: disable=missing-function-docstring
search_results = re.search(r'Run_[0-9]+$', course_key_string)
assert search_results
course_run_string = search_results.group(0).replace('_', ' ')

View File

@@ -13,7 +13,7 @@ import ddt
import pytz
from config_models.models import cache
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.models import AnonymousUser, User # lint-amnesty, pylint: disable=imported-auth-user
from django.test import TestCase, override_settings
from django.test.client import Client
from django.urls import reverse
@@ -301,7 +301,7 @@ class DashboardTest(ModuleStoreTestCase, TestVerificationBase):
ENABLED_SIGNALS = ['course_published']
def setUp(self):
super(DashboardTest, self).setUp()
super(DashboardTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course = CourseFactory.create()
self.user = UserFactory.create(username="jack", email="jack@fake.edx.org", password='test')
self.client = Client()
@@ -569,7 +569,7 @@ class DashboardTestsWithSiteOverrides(SiteMixin, ModuleStoreTestCase):
"""
def setUp(self):
super(DashboardTestsWithSiteOverrides, self).setUp()
super(DashboardTestsWithSiteOverrides, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.org = 'fakeX'
self.course = CourseFactory.create(org=self.org)
self.user = UserFactory.create(username='jack', email='jack@fake.edx.org', password='test')
@@ -624,8 +624,8 @@ class UserSettingsEventTestMixin(EventTestMixin):
"""
Mixin for verifying that user setting events were emitted during a test.
"""
def setUp(self):
super(UserSettingsEventTestMixin, self).setUp('common.djangoapps.util.model_utils.tracker')
def setUp(self): # lint-amnesty, pylint: disable=arguments-differ
super(UserSettingsEventTestMixin, self).setUp('common.djangoapps.util.model_utils.tracker') # lint-amnesty, pylint: disable=super-with-arguments
def assert_user_setting_event_emitted(self, **kwargs):
"""
@@ -651,8 +651,8 @@ class UserSettingsEventTestMixin(EventTestMixin):
class EnrollmentEventTestMixin(EventTestMixin):
""" Mixin with assertions for validating enrollment events. """
def setUp(self):
super(EnrollmentEventTestMixin, self).setUp('common.djangoapps.student.models.tracker')
def setUp(self): # lint-amnesty, pylint: disable=arguments-differ
super(EnrollmentEventTestMixin, self).setUp('common.djangoapps.student.models.tracker') # lint-amnesty, pylint: disable=super-with-arguments
def assert_enrollment_mode_change_event_was_emitted(self, user, course_key, mode):
"""Ensures an enrollment mode change event was emitted"""
@@ -880,7 +880,7 @@ class ChangeEnrollmentViewTest(ModuleStoreTestCase):
"""Tests the student.views.change_enrollment view"""
def setUp(self):
super(ChangeEnrollmentViewTest, self).setUp()
super(ChangeEnrollmentViewTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course = CourseFactory.create()
self.user = UserFactory.create(password='secret')
self.client.login(username=self.user.username, password='secret')
@@ -962,7 +962,7 @@ class AnonymousLookupTable(ModuleStoreTestCase):
Tests for anonymous_id_functions
"""
def setUp(self):
super(AnonymousLookupTable, self).setUp()
super(AnonymousLookupTable, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course = CourseFactory.create()
self.user = UserFactory.create()
CourseModeFactory.create(
@@ -1051,7 +1051,7 @@ class RelatedProgramsTests(ProgramsApiConfigMixin, SharedModuleStoreTestCase):
cls.enrollment = CourseEnrollmentFactory(user=cls.user, course_id=cls.course.id) # pylint: disable=no-member
def setUp(self):
super(RelatedProgramsTests, self).setUp()
super(RelatedProgramsTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.url = reverse('dashboard')
@@ -1116,7 +1116,7 @@ class UserAttributeTests(TestCase):
"""Tests for the UserAttribute model."""
def setUp(self):
super(UserAttributeTests, self).setUp()
super(UserAttributeTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory()
self.name = 'test'
self.value = 'test-value'

View File

@@ -110,7 +110,7 @@ def _get_recently_enrolled_courses(course_enrollments):
]
def _create_recent_enrollment_message(course_enrollments, course_modes):
def _create_recent_enrollment_message(course_enrollments, course_modes): # lint-amnesty, pylint: disable=unused-argument
"""
Builds a recent course enrollment message.
@@ -476,7 +476,7 @@ def get_dashboard_course_limit():
@login_required
@ensure_csrf_cookie
@add_maintenance_banner
def student_dashboard(request):
def student_dashboard(request): # lint-amnesty, pylint: disable=too-many-statements
"""
Provides the LMS dashboard view
@@ -583,10 +583,10 @@ def student_dashboard(request):
recovery_email_message = recovery_email_activation_message = None
if is_secondary_email_feature_enabled():
try:
pending_email = PendingSecondaryEmailChange.objects.get(user=user)
pending_email = PendingSecondaryEmailChange.objects.get(user=user) # lint-amnesty, pylint: disable=unused-variable
except PendingSecondaryEmailChange.DoesNotExist:
try:
account_recovery_obj = AccountRecovery.objects.get(user=user)
account_recovery_obj = AccountRecovery.objects.get(user=user) # lint-amnesty, pylint: disable=unused-variable
except AccountRecovery.DoesNotExist:
recovery_email_message = Text(
_(

View File

@@ -1,4 +1,4 @@
"""
""" # lint-amnesty, pylint: disable=cyclic-import
Student Views
"""
@@ -12,19 +12,19 @@ import six
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.models import AnonymousUser, User # lint-amnesty, pylint: disable=imported-auth-user
from django.contrib.sites.models import Site
from django.core.validators import ValidationError, validate_email
from django.db import transaction
from django.db.models.signals import post_save
from django.dispatch import Signal, receiver
from django.dispatch import Signal, receiver # lint-amnesty, pylint: disable=unused-import
from django.http import Http404, HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from django.shortcuts import redirect
from django.template.context_processors import csrf
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
from django.views.decorators.http import require_GET, require_http_methods, require_POST
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie # lint-amnesty, pylint: disable=unused-import
from django.views.decorators.http import require_GET, require_http_methods, require_POST # lint-amnesty, pylint: disable=unused-import
from edx_ace import ace
from edx_ace.recipient import Recipient
from edx_django_utils import monitoring as monitoring_utils
@@ -40,7 +40,7 @@ from common.djangoapps.track import views as track_views
from lms.djangoapps.bulk_email.models import Optout
from common.djangoapps.course_modes.models import CourseMode
from lms.djangoapps.courseware.courses import get_courses, sort_by_announcement, sort_by_start_date
from common.djangoapps.edxmako.shortcuts import marketing_link, render_to_response, render_to_string
from common.djangoapps.edxmako.shortcuts import marketing_link, render_to_response, render_to_string # lint-amnesty, pylint: disable=unused-import
from common.djangoapps.entitlements.models import CourseEntitlement
from openedx.core.djangoapps.ace_common.template_context import get_base_template_context
from openedx.core.djangoapps.catalog.utils import get_programs_with_type
@@ -54,8 +54,8 @@ from openedx.core.djangoapps.user_authn.utils import should_redirect_to_authn_mi
from openedx.core.djangolib.markup import HTML, Text
from common.djangoapps.student.email_helpers import generate_activation_email_context
from common.djangoapps.student.helpers import DISABLE_UNENROLL_CERT_STATES, cert_info
from common.djangoapps.student.message_types import AccountActivation, EmailChange, EmailChangeConfirmation, RecoveryEmailCreate
from common.djangoapps.student.models import (
from common.djangoapps.student.message_types import AccountActivation, EmailChange, EmailChangeConfirmation, RecoveryEmailCreate # lint-amnesty, pylint: disable=line-too-long
from common.djangoapps.student.models import ( # lint-amnesty, pylint: disable=unused-import
AccountRecovery,
CourseEnrollment,
PendingEmailChange,
@@ -591,7 +591,7 @@ def validate_new_email(user, new_email):
try:
validate_email(new_email)
except ValidationError:
raise ValueError(_('Valid e-mail address required.'))
raise ValueError(_('Valid e-mail address required.')) # lint-amnesty, pylint: disable=raise-missing-from
if new_email == user.email:
raise ValueError(_('Old email is the same as the new email.'))
@@ -684,7 +684,7 @@ def do_email_change_request(user, new_email, activation_key=None, secondary_emai
except Exception:
from_address = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL)
log.error(u'Unable to send email activation link to user from "%s"', from_address, exc_info=True)
raise ValueError(_('Unable to send email activation link. Please try again later.'))
raise ValueError(_('Unable to send email activation link. Please try again later.')) # lint-amnesty, pylint: disable=raise-missing-from
if not secondary_email_change_request:
# When the email address change is complete, a "edx.user.settings.changed" event will be emitted.