Merge pull request #26893 from edx/BOM-2375-student-1

BOM-2375-student-part1
This commit is contained in:
Awais Qureshi
2021-03-09 17:52:30 +05:00
committed by GitHub
29 changed files with 105 additions and 111 deletions

View File

@@ -34,6 +34,6 @@ def create_users(
allow_access(course, user, 'staff', send_email=False)
if course_key and course_staff:
print('Created user {} as course staff'.format(user.username))
print(f'Created user {user.username} as course staff')
else:
print('Created user {}'.format(user.username))
print(f'Created user {user.username}')

View File

@@ -25,7 +25,7 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
def print_groups(self):
print('Groups available:')
for group in Group.objects.all().distinct():
print(' {}'.format(group.name))
print(f' {group.name}')
def handle(self, *args, **options):
if options['list']:
@@ -47,7 +47,7 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
group = Group(name=group_name)
group.save()
else:
raise CommandError('Group {} does not exist'.format(group_name)) # lint-amnesty, pylint: disable=raise-missing-from
raise CommandError(f'Group {group_name} does not exist') # lint-amnesty, pylint: disable=raise-missing-from
if options['remove']:
user.groups.remove(group)

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""Dump username, per-student anonymous id, and per-course anonymous id triples as CSV.
Give instructors easy access to the mapping from anonymized IDs to user IDs
@@ -36,12 +35,12 @@ class Command(BaseCommand):
# Generate the output filename from the course ID.
# Change slashes to dashes first, and then append .csv extension.
output_filename = text_type(course_key).replace('/', '-') + ".csv"
output_filename = str(course_key).replace('/', '-') + ".csv"
# Figure out which students are enrolled in the course
students = User.objects.filter(courseenrollment__course_id=course_key)
if len(students) == 0:
self.stdout.write("No students enrolled in %s" % text_type(course_key))
self.stdout.write("No students enrolled in %s" % str(course_key))
return
# Write mapping to output file in CSV format with a simple header
@@ -59,5 +58,5 @@ class Command(BaseCommand):
anonymous_id_for_user(student, None),
anonymous_id_for_user(student, course_key)
))
except IOError:
except OSError:
raise CommandError("Error writing to file: %s" % output_filename) # lint-amnesty, pylint: disable=raise-missing-from

View File

@@ -89,7 +89,7 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
v = random.uniform(0, 1)
group = group_from_value(groups, v)
group_objects[group].users.add(user)
f.write(u"Assigned user {name} ({id}) to {group}\n".format(
f.write("Assigned user {name} ({id}) to {group}\n".format(
name=user.username,
id=user.id,
group=group

View File

@@ -68,16 +68,16 @@ class Command(BaseCommand):
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError:
raise CommandError('Course ID {} is invalid.'.format(course_id)) # lint-amnesty, pylint: disable=raise-missing-from
raise CommandError(f'Course ID {course_id} is invalid.') # 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))
raise CommandError(f'The given course {course_id} does not exist.')
course_keys.append(course_key)
else:
course_keys = [course.id for course in CourseOverview.get_all_courses(orgs=[org])]
if not course_keys:
raise CommandError('No courses exist for the org "{}".'.format(org))
raise CommandError(f'No courses exist for the org "{org}".')
for course_key in course_keys:
self.move_users_for_course(course_key, from_mode, to_mode, commit)
@@ -96,9 +96,9 @@ class Command(BaseCommand):
commit (bool): required to make the change to the database. Otherwise
just a count will be displayed.
"""
unicode_course_key = text_type(course_key)
unicode_course_key = str(course_key)
if CourseMode.mode_for_course(course_key, to_mode) is None:
logger.info('Mode ({}) does not exist for course ({}).'.format(to_mode, unicode_course_key))
logger.info(f'Mode ({to_mode}) does not exist for course ({unicode_course_key}).')
return
course_enrollments = CourseEnrollment.objects.filter(course_id=course_key, mode=from_mode)

View File

@@ -69,7 +69,7 @@ class Command(BaseCommand):
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError:
msg = 'Invalid course id {}, skipping un-enrollement.'.format(course_id)
msg = f'Invalid course id {course_id}, skipping un-enrollement.'
logger.warning(msg)
return
@@ -77,7 +77,7 @@ class Command(BaseCommand):
if username:
enrollments = enrollments.filter(user__username=username)
logger.info("Processing [{}] with [{}] enrollments.".format(course_id, enrollments.count()))
logger.info(f"Processing [{course_id}] with [{enrollments.count()}] enrollments.")
if self.commit:
for enrollment in enrollments:

View File

@@ -44,7 +44,7 @@ class Command(BaseCommand):
if not path.isfile(file_path):
raise CommandError('File not found.')
with open(file_path, 'r') as csv_file:
with open(file_path) as csv_file:
csv_reader = csv.reader(csv_file)
email_mappings = [

View File

@@ -56,7 +56,7 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
def handle(self, *args, **options):
if options['output']:
if os.path.exists(options['output']):
raise CommandError("File {0} already exists".format(options['output']))
raise CommandError("File {} already exists".format(options['output']))
disabled_users = UserProfile.objects.filter(allow_certificate=False)
with open(options['output'], 'w') as csvfile:
@@ -67,28 +67,28 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
elif options['import']:
if not os.path.exists(options['import']):
raise CommandError("File {0} does not exist".format(options['import']))
raise CommandError("File {} does not exist".format(options['import']))
print("Importing students from {0}".format(options['import']))
print("Importing students from {}".format(options['import']))
with open(options['import']) as csvfile:
student_list = csv.reader(csvfile, delimiter=',', quotechar='"')
students = [student[0] for student in student_list]
if not students:
raise CommandError("Unable to read student data from {0}".format(options['import']))
raise CommandError("Unable to read student data from {}".format(options['import']))
update_cnt = UserProfile.objects.filter(user__username__in=students).update(allow_certificate=False)
print('{} user(s) disabled out of {} in CSV file'.format(update_cnt, len(students)))
elif options['enable']:
print("Enabling {0} for certificate download".format(options['enable']))
print("Enabling {} for certificate download".format(options['enable']))
cert_allow = UserProfile.objects.get(user__username=options['enable'])
cert_allow.allow_certificate = True
cert_allow.save()
elif options['disable']:
print("Disabling {0} for certificate download".format(options['disable']))
print("Disabling {} for certificate download".format(options['disable']))
cert_allow = UserProfile.objects.get(user__username=options['disable'])
cert_allow.allow_certificate = False
cert_allow.save()

View File

@@ -65,14 +65,14 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
logger.exception('Invalid or non-existent username {}'.format(username))
logger.exception(f'Invalid or non-existent username {username}')
raise
try:
course_key = CourseKey.from_string(course_id)
CourseEnrollment.objects.get(user=user, course_id=course_key, mode=CourseMode.CREDIT_MODE)
except InvalidKeyError:
logger.exception('Invalid or non-existent course id {}'.format(course_id))
logger.exception(f'Invalid or non-existent course id {course_id}')
raise
except CourseEnrollment.DoesNotExist:
logger.exception('No enrollment found in database for {username} in course {course_id}'
@@ -89,7 +89,7 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
expected_date = datetime.utcnow() + timedelta(days=DEFAULT_DAYS)
self.update_credit_eligibility_deadline(username, course_key, expected_date)
logger.info("Successfully updated credit eligibility deadline for {}".format(username))
logger.info(f"Successfully updated credit eligibility deadline for {username}")
def update_credit_eligibility_deadline(self, username, course_key, new_deadline):
""" Update Credit Eligibility new_deadline for a specific user """

View File

@@ -155,4 +155,4 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
if len(error_users) > 0:
logger.info('The following %i user(s) not saved:', len(error_users))
for user, error in error_users:
logger.info('user: [%s] reason: [%s] %s', user, type(error).__name__, text_type(error))
logger.info('user: [%s] reason: [%s] %s', user, type(error).__name__, str(error))

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Django management command for changing an enterprise user's username.
"""
@@ -51,11 +50,11 @@ class Command(BaseCommand):
try:
EnterpriseCustomerUser.objects.get(user_id=user_id)
except EnterpriseCustomerUser.DoesNotExist:
LOGGER.info('User {} must be an Enterprise User.'.format(user_id))
LOGGER.info(f'User {user_id} must be an Enterprise User.')
return
user = User.objects.get(id=user_id)
user.username = new_username
user.save()
LOGGER.info('User {} has been updated with username {}.'.format(user_id, new_username))
LOGGER.info(f'User {user_id} has been updated with username {new_username}.')

View File

@@ -13,10 +13,10 @@ def random_user_data_generator(num_users):
for _ in range(num_users):
identification = uuid.uuid4().hex[:8]
yield {
'username': 'user_{id}'.format(id=identification),
'email': 'email_{id}@example.com'.format(id=identification),
'username': f'user_{identification}',
'email': f'email_{identification}@example.com',
'password': '12345',
'name': 'User {id}'.format(id=identification),
'name': f'User {identification}',
}

View File

@@ -10,7 +10,7 @@ def user_info_generator(usernames, password, domain):
for username in usernames:
yield {
'username': username,
'email': '{username}@{domain}'.format(username=username, domain=domain),
'email': f'{username}@{domain}',
'password': password,
'name': username,
}

View File

@@ -100,7 +100,7 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
if created:
if initial_password_hash:
if not (is_password_usable(initial_password_hash) and is_valid_django_hash(initial_password_hash)):
raise CommandError('The password hash provided for user {} is invalid.'.format(username))
raise CommandError(f'The password hash provided for user {username} is invalid.')
user.password = initial_password_hash
else:
# Set the password to a random, unknown, but usable password

View File

@@ -64,18 +64,18 @@ class Command(BaseCommand):
try:
user = User.objects.get(id=user_id)
if UserAttribute.get_user_attribute(user, CREATED_ON_SITE):
self.stdout.write("created_on_site attribute already exists for user id: {id}".format(id=user_id))
self.stdout.write(f"created_on_site attribute already exists for user id: {user_id}")
else:
UserAttribute.set_user_attribute(user, CREATED_ON_SITE, site_domain)
except User.DoesNotExist:
self.stdout.write("This user id [{id}] does not exist in the system.".format(id=user_id))
self.stdout.write(f"This user id [{user_id}] does not exist in the system.")
for key in activation_keys:
try:
user = Registration.objects.get(activation_key=key).user
if UserAttribute.get_user_attribute(user, CREATED_ON_SITE):
self.stdout.write("created_on_site attribute already exists for user id: {id}".format(id=user.id))
self.stdout.write(f"created_on_site attribute already exists for user id: {user.id}")
else:
UserAttribute.set_user_attribute(user, CREATED_ON_SITE, site_domain)
except Registration.DoesNotExist:
self.stdout.write("This activation key [{key}] does not exist in the system.".format(key=key))
self.stdout.write(f"This activation key [{key}] does not exist in the system.")

View File

@@ -39,10 +39,10 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst
v.is_staff = True
v.save()
print('Modified {} sucessfully.'.format(user))
print(f'Modified {user} sucessfully.')
except Exception as err: # pylint: disable=broad-except
print("Error modifying user with identifier {}: {}: {}".format(user, type(err).__name__,
text_type(err)))
str(err)))
print('Complete!')

View File

@@ -39,10 +39,10 @@ class Command(BaseCommand):
userobj.is_superuser = True
userobj.save()
print('Modified {} sucessfully.'.format(user))
print(f'Modified {user} sucessfully.')
except Exception as err: # pylint: disable=broad-except
print("Error modifying user with identifier {}: {}: {}".format(user, type(err).__name__,
text_type(err)))
str(err)))
print('Complete!')

View File

@@ -56,7 +56,7 @@ class Command(TrackedCommand):
for user in source_students:
with transaction.atomic():
print('Moving {}.'.format(user.username))
print(f'Moving {user.username}.')
# Find the old enrollment.
enrollment = CourseEnrollment.objects.get(
user=user,
@@ -67,14 +67,14 @@ class Command(TrackedCommand):
mode = enrollment.mode
old_is_active = enrollment.is_active
CourseEnrollment.unenroll(user, source_key, skip_refund=True)
print('Unenrolled {} from {}'.format(user.username, text_type(source_key)))
print('Unenrolled {} from {}'.format(user.username, str(source_key)))
for dest_key in dest_keys:
if CourseEnrollment.is_enrolled(user, dest_key):
# Un Enroll from source course but don't mess
# with the enrollment in the destination course.
msg = 'Skipping {}, already enrolled in destination course {}'
print(msg.format(user.username, text_type(dest_key)))
print(msg.format(user.username, str(dest_key)))
else:
new_enrollment = CourseEnrollment.enroll(user, dest_key, mode=mode)

View File

@@ -1,18 +1,17 @@
"""Tests for the bulk_change_enrollment command."""
from unittest.mock import call, patch
import ddt
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
from mock import call, patch
from six import text_type
from common.djangoapps.course_modes.tests.factories import CourseModeFactory
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from common.djangoapps.student.models import EVENT_NAME_ENROLLMENT_MODE_CHANGED, CourseEnrollment
from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
@@ -22,7 +21,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
"""Tests for the bulk_change_enrollment command."""
def setUp(self):
super(BulkChangeEnrollmentTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.org = 'testX'
self.course = CourseFactory.create(org=self.org)
self.users = UserFactory.create_batch(5)
@@ -40,7 +39,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
assert len(CourseEnrollment.objects.filter(mode=to_mode, course_id=self.course.id)) == 0
args = '--course {course} --from_mode {from_mode} --to_mode {to_mode} --commit'.format(
course=text_type(self.course.id),
course=str(self.course.id),
from_mode=from_mode,
to_mode=to_mode
)
@@ -101,13 +100,13 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
call_command(
'bulk_change_enrollment',
org=self.org,
course=text_type(self.course.id),
course=str(self.course.id),
from_mode='audit',
to_mode='no-id-professional',
commit=True,
)
assert 'Error: one of the arguments -c/--course -o/--org is required' == text_type(err.value)
assert 'Error: one of the arguments -c/--course -o/--org is required' == str(err.value)
@patch('common.djangoapps.student.models.tracker')
def test_with_org_and_invalid_to_mode(self, mock_tracker):
@@ -164,7 +163,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
'bulk_change_enrollment', *args.split(' ')
)
assert 'No courses exist for the org "fakeX".' == text_type(err.value)
assert 'No courses exist for the org "fakeX".' == str(err.value)
def test_without_commit(self):
"""Verify that nothing happens when the `commit` flag is not given."""
@@ -172,7 +171,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
CourseModeFactory(course_id=self.course.id, mode_slug='honor')
args = '--course {course} --from_mode {from_mode} --to_mode {to_mode}'.format(
course=text_type(self.course.id),
course=str(self.course.id),
from_mode='audit',
to_mode='honor'
)
@@ -201,7 +200,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
*args.split(' ')
)
assert 'Error: the following arguments are required: -t/--to_mode' == text_type(err.value)
assert 'Error: the following arguments are required: -t/--to_mode' == str(err.value)
@ddt.data('from_mode', 'to_mode', 'course')
def test_without_options(self, option):
@@ -209,7 +208,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
command_options = {
'from_mode': 'audit',
'to_mode': 'honor',
'course': text_type(self.course.id),
'course': str(self.course.id),
}
command_options.pop(option)
@@ -227,7 +226,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
with pytest.raises(CommandError) as err:
call_command('bulk_change_enrollment', *args.split(' '))
assert 'Course ID yolo is invalid.' == text_type(err.value)
assert 'Course ID yolo is invalid.' == str(err.value)
def test_nonexistent_course_id(self):
"""Verify that the command fails when the given course does not exist."""
@@ -242,7 +241,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
'bulk_change_enrollment',
*args.split(' ')
)
assert 'The given course course-v1:testX+test+2016 does not exist.' == text_type(err.value)
assert 'The given course course-v1:testX+test+2016 does not exist.' == str(err.value)
def _assert_mode_changed(self, mock_tracker, course, user, to_mode):
"""Confirm the analytics event was emitted."""
@@ -250,7 +249,7 @@ class BulkChangeEnrollmentTests(SharedModuleStoreTestCase):
[
call(
EVENT_NAME_ENROLLMENT_MODE_CHANGED,
{'course_id': text_type(course.id), 'user_id': user.id, 'mode': to_mode}
{'course_id': str(course.id), 'user_id': user.id, 'mode': to_mode}
),
]
)

View File

@@ -26,7 +26,7 @@ class BulkChangeEnrollmentCSVTests(SharedModuleStoreTestCase):
Tests bulk_change_enrollmetn_csv command
"""
def setUp(self):
super(BulkChangeEnrollmentCSVTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.courses = []
self.user_info = [
@@ -62,7 +62,7 @@ class BulkChangeEnrollmentCSVTests(SharedModuleStoreTestCase):
csv = self._write_test_csv(csv, lines=["course-v1:edX+DemoX+Demo_Course,user,audit\n"])
with LogCapture(LOGGER_NAME) as log:
call_command("bulk_change_enrollment_csv", "--csv_file_path={}".format(csv.name))
call_command("bulk_change_enrollment_csv", f"--csv_file_path={csv.name}")
log.check(
(
LOGGER_NAME,
@@ -78,7 +78,7 @@ class BulkChangeEnrollmentCSVTests(SharedModuleStoreTestCase):
csv = self._write_test_csv(csv, lines=["Demo_Course,river,audit\n"])
with LogCapture(LOGGER_NAME) as log:
call_command("bulk_change_enrollment_csv", "--csv_file_path={}".format(csv.name))
call_command("bulk_change_enrollment_csv", f"--csv_file_path={csv.name}")
log.check(
(
LOGGER_NAME,
@@ -94,7 +94,7 @@ class BulkChangeEnrollmentCSVTests(SharedModuleStoreTestCase):
csv = self._write_test_csv(csv, lines=[str(self.courses[0].id) + ",amy,audit\n"])
with LogCapture(LOGGER_NAME) as log:
call_command("bulk_change_enrollment_csv", "--csv_file_path={}".format(csv.name))
call_command("bulk_change_enrollment_csv", f"--csv_file_path={csv.name}")
log.check(
(
LOGGER_NAME,
@@ -117,7 +117,7 @@ class BulkChangeEnrollmentCSVTests(SharedModuleStoreTestCase):
with NamedTemporaryFile() as csv:
csv = self._write_test_csv(csv, lines=lines)
call_command("bulk_change_enrollment_csv", "--csv_file_path={}".format(csv.name))
call_command("bulk_change_enrollment_csv", f"--csv_file_path={csv.name}")
for enrollment in self.enrollments:
new_enrollment = CourseEnrollment.get_enrollment(user=enrollment.user, course_key=enrollment.course)

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() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.course = CourseFactory.create()
self.audit_mode = CourseModeFactory.create(
course_id=self.course.id,
@@ -58,7 +58,7 @@ class BulkUnenrollTests(SharedModuleStoreTestCase):
csv = self._write_test_csv(csv, lines=["amy,test_course\n"])
with LogCapture(LOGGER_NAME) as log:
call_command("bulk_unenroll", "--csv_path={}".format(csv.name), "--commit")
call_command("bulk_unenroll", f"--csv_path={csv.name}", "--commit")
expected_message = 'Invalid course id {}, skipping un-enrollement.'.\
format('test_course')
@@ -76,7 +76,7 @@ class BulkUnenrollTests(SharedModuleStoreTestCase):
with NamedTemporaryFile() as csv:
csv = self._write_test_csv(csv, lines=lines)
call_command("bulk_unenroll", "--csv_path={}".format(csv.name), "--commit")
call_command("bulk_unenroll", f"--csv_path={csv.name}", "--commit")
for enrollment in CourseEnrollment.objects.all():
assert enrollment.is_active is False
@@ -92,7 +92,7 @@ class BulkUnenrollTests(SharedModuleStoreTestCase):
with NamedTemporaryFile() as csv:
csv = self._write_test_csv(csv, lines=lines)
call_command("bulk_unenroll", "--csv_path={}".format(csv.name))
call_command("bulk_unenroll", f"--csv_path={csv.name}")
for enrollment in CourseEnrollment.objects.all():
assert enrollment.is_active is True
@@ -124,7 +124,7 @@ class BulkUnenrollTests(SharedModuleStoreTestCase):
(
LOGGER_NAME,
'INFO',
'Processing [{}] with [1] enrollments.'.format(course_id),
f'Processing [{course_id}] with [1] enrollments.',
),
(
LOGGER_NAME,

View File

@@ -25,7 +25,7 @@ class ChangeEligibilityDeadlineTests(SharedModuleStoreTestCase):
def setUp(self):
""" Initial set up for tests """
super(ChangeEligibilityDeadlineTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.course = CourseFactory.create()
self.enrolled_user = UserFactory.create(username='amy', email='amy@pond.com', password='password')
@@ -41,7 +41,7 @@ class ChangeEligibilityDeadlineTests(SharedModuleStoreTestCase):
def test_invalid_command_arguments(self):
""" Test command with invalid arguments """
course_id_str = text_type(self.course.id)
course_id_str = str(self.course.id)
username = self.enrolled_user.username
# Incorrect username
@@ -79,7 +79,7 @@ class ChangeEligibilityDeadlineTests(SharedModuleStoreTestCase):
default value which is one month from today. It then continues to run the code
to change eligibility deadline.
"""
course_key = text_type(self.course.id)
course_key = str(self.course.id)
username = self.enrolled_user.username
# Test Date set prior to today
@@ -90,12 +90,12 @@ class ChangeEligibilityDeadlineTests(SharedModuleStoreTestCase):
)
logger.check(
(LOGGER_NAME, 'WARNING', 'Invalid date or date not provided. Setting deadline to one month from now'),
(LOGGER_NAME, 'INFO', 'Successfully updated credit eligibility deadline for {}'.format(username))
(LOGGER_NAME, 'INFO', f'Successfully updated credit eligibility deadline for {username}')
)
def test_valid_command_arguments(self):
""" Test command with valid arguments """
course_key = text_type(self.course.id)
course_key = str(self.course.id)
username = self.enrolled_user.username
new_deadline = datetime.utcnow() + timedelta(days=30)

View File

@@ -1,10 +1,10 @@
""" Test the change_enrollment command line script."""
from unittest.mock import patch
import ddt
from django.core.management import call_command
from mock import patch
from six import text_type
from common.djangoapps.course_modes.tests.factories import CourseModeFactory
from common.djangoapps.student.models import CourseEnrollment
@@ -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() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.course = CourseFactory.create()
self.audit_mode = CourseModeFactory.create(
course_id=self.course.id,
@@ -63,7 +63,7 @@ class ChangeEnrollmentTests(SharedModuleStoreTestCase):
# Hack around call_command bugs dealing with required options see:
# https://stackoverflow.com/questions/32036562/call-command-argument-is-required
command_args = '--course {course} --to honor --from audit --{method} {user_str}{noop}'.format(
course=text_type(self.course.id),
course=str(self.course.id),
noop=noop,
method=method,
user_str=user_str
@@ -96,7 +96,7 @@ class ChangeEnrollmentTests(SharedModuleStoreTestCase):
assert len(CourseEnrollment.objects.filter(mode='honor', user_id__in=real_user_ids)) == 0
command_args = '--course {course} --to honor --from audit --{method} {user_str}'.format(
course=text_type(self.course.id),
course=str(self.course.id),
method=method,
user_str=user_str
)

View File

@@ -1,10 +1,9 @@
# -*- coding: utf-8 -*-
"""
Tests for the django management command `change_enterprise_user_username`.
"""
import mock
from unittest import mock
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.contrib.sites.models import Site
from django.core.management import call_command
@@ -34,7 +33,7 @@ class ChangeEnterpriseUserUsernameCommandTests(TestCase):
call_command(self.command, user_id=user.id, new_username=new_username)
logger_mock.info.assert_called_with('User {} must be an Enterprise User.'.format(user.id))
logger_mock.info.assert_called_with(f'User {user.id} must be an Enterprise User.')
post_save_handler.assert_not_called()
@mock.patch('common.djangoapps.student.management.commands.change_enterprise_user_username.LOGGER')
@@ -59,7 +58,7 @@ class ChangeEnterpriseUserUsernameCommandTests(TestCase):
call_command(self.command, user_id=user.id, new_username=new_username)
logger_mock.info.assert_called_with('User {} has been updated with username {}.'.format(user.id, new_username))
logger_mock.info.assert_called_with(f'User {user.id} has been updated with username {new_username}.')
post_save_handler.assert_called()
updated_user = User.objects.get(id=user.id)

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() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.course = CourseFactory.create()
self.user_model = get_user_model()
self.num_users_start = len(self.user_model.objects.all())
@@ -29,7 +29,7 @@ class CreateRandomUserTests(SharedModuleStoreTestCase):
The command should create users_to_create number of random users
"""
users_to_create = 5
call_command('create_random_users', text_type(users_to_create))
call_command('create_random_users', str(users_to_create))
# Verify correct number of users are now in the database
assert (self.num_users_start + users_to_create) == len(self.user_model.objects.all())
@@ -39,7 +39,7 @@ class CreateRandomUserTests(SharedModuleStoreTestCase):
The command should create users_to_create number of random users and add them to self.course
"""
users_to_create = 3
call_command('create_random_users', text_type(users_to_create), text_type(self.course.id))
call_command('create_random_users', str(users_to_create), str(self.course.id))
# Verify correct number of users are now in the database
assert (self.num_users_start + users_to_create) == len(self.user_model.objects.all())
@@ -54,7 +54,7 @@ class CreateRandomUserTests(SharedModuleStoreTestCase):
users_to_create = 3
with pytest.raises(InvalidKeyError):
call_command('create_random_users', text_type(users_to_create), u'invalid_course_id')
call_command('create_random_users', str(users_to_create), 'invalid_course_id')
# Verify correct number of users are now in the database
assert self.num_users_start == len(self.user_model.objects.all())

View File

@@ -26,7 +26,7 @@ class CreateTestUsersTestCase(SharedModuleStoreTestCase):
def setUp(self):
super().setUp()
self.course = CourseFactory.create()
self.course_id = text_type(self.course.id)
self.course_id = str(self.course.id)
self.user_model = get_user_model()
self.num_users_start = len(self.user_model.objects.all())
@@ -62,7 +62,7 @@ class CreateTestUsersTestCase(SharedModuleStoreTestCase):
assert len(users) == len(usernames)
for user in users:
assert user.is_active
assert user.email == '{}@example.com'.format(user.username)
assert user.email == f'{user.username}@example.com'
assert self.client.login(username=user.username, password='12345')
assert not CourseEnrollment.objects.filter(user__in=users).exists()
@@ -134,7 +134,7 @@ class CreateTestUsersTestCase(SharedModuleStoreTestCase):
self.call_command([username], domain=domain)
user = self.user_model.objects.get(username=username)
assert user.email == '{}@{}'.format(username, domain)
assert user.email == f'{username}@{domain}'
def test_create_user__email_taken(self):
"""

View File

@@ -3,18 +3,17 @@ Unittests for populate_created_on_site_user_attribute management command.
"""
import ddt
import mock
import pytest
from unittest import mock
import ddt
import pytest
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
from openedx.core.djangoapps.site_configuration.tests.mixins import SiteMixin
from common.djangoapps.student.models import Registration, UserAttribute
from common.djangoapps.student.tests.factories import UserFactory
from openedx.core.djangoapps.site_configuration.tests.mixins import SiteMixin
CREATED_ON_SITE = 'created_on_site'
@@ -26,7 +25,7 @@ class TestPopulateUserAttribute(SiteMixin, TestCase):
"""
def setUp(self):
super(TestPopulateUserAttribute, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self._create_sample_data()
self.users = User.objects.all()
@@ -106,7 +105,7 @@ class TestPopulateUserAttribute(SiteMixin, TestCase):
user = self.users[0]
call_command(
"populate_created_on_site_user_attribute",
"--users", '9{id}'.format(id=user.id), # invalid id
"--users", f'9{user.id}', # invalid id
"--site-domain", self.site.domain
)
assert UserAttribute.get_user_attribute(user, CREATED_ON_SITE) is None
@@ -114,7 +113,7 @@ class TestPopulateUserAttribute(SiteMixin, TestCase):
register_user = self.registered_users[0]
call_command(
"populate_created_on_site_user_attribute",
"--activation-keys", "invalid-{key}".format(key=register_user.activation_key), # invalid key
"--activation-keys", f"invalid-{register_user.activation_key}", # invalid key
"--site-domain", self.site.domain
)
assert UserAttribute.get_user_attribute(register_user.user, CREATED_ON_SITE) is None

View File

@@ -35,7 +35,7 @@ class RecoverAccountTests(TestCase):
request_factory = RequestFactory()
def setUp(self):
super(RecoverAccountTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.user = UserFactory.create(username='amy', email='amy@edx.com', password='password')
def _write_test_csv(self, csv, lines):
@@ -55,7 +55,7 @@ class RecoverAccountTests(TestCase):
with NamedTemporaryFile() as csv:
csv = self._write_test_csv(csv, lines=['amy,amy@edx.com,amy@newemail.com\n'])
call_command("recover_account", "--csv_file_path={}".format(csv.name))
call_command("recover_account", f"--csv_file_path={csv.name}")
assert len(mail.outbox) == 1
@@ -83,7 +83,7 @@ class RecoverAccountTests(TestCase):
with NamedTemporaryFile() as csv:
csv = self._write_test_csv(csv, lines=['amy,amy@edx.com,amy@newemail.com\n'])
call_command("recover_account", "--csv_file_path={}".format(csv.name))
call_command("recover_account", f"--csv_file_path={csv.name}")
assert len(mail.outbox) == 1
@@ -110,7 +110,7 @@ class RecoverAccountTests(TestCase):
'exception was User matching query does not exist.'
with LogCapture(LOGGER_NAME) as log:
call_command("recover_account", "--csv_file_path={}".format(csv.name))
call_command("recover_account", f"--csv_file_path={csv.name}")
log.check_present(
(LOGGER_NAME, 'ERROR', expected_message)
@@ -126,7 +126,7 @@ class RecoverAccountTests(TestCase):
expected_message = "Successfully updated ['amy@newemail.com'] accounts. Failed to update [] accounts"
with LogCapture(LOGGER_NAME) as log:
call_command("recover_account", "--csv_file_path={}".format(csv.name))
call_command("recover_account", f"--csv_file_path={csv.name}")
log.check_present(
(LOGGER_NAME, 'INFO', expected_message)

View File

@@ -4,13 +4,12 @@ Tests the transfer student management command
import unittest
from unittest.mock import call, patch
import ddt
from django.conf import settings
from django.core.management import call_command
from mock import call, patch
from opaque_keys.edx import locator
from six import text_type
from common.djangoapps.course_modes.models import CourseMode
from common.djangoapps.student.models import (
@@ -39,7 +38,7 @@ class TestTransferStudents(ModuleStoreTestCase):
"""
Connect a stub receiver, and analytics event tracking.
"""
super(TestTransferStudents, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
UNENROLL_DONE.connect(self.assert_unenroll_signal)
patcher = patch('common.djangoapps.student.models.tracker')
@@ -79,9 +78,9 @@ class TestTransferStudents(ModuleStoreTestCase):
# New Course 2
course_location_two = locator.CourseLocator('Org2', 'Course2', 'Run2')
new_course_two = self._create_course(course_location_two)
original_key = text_type(course.id)
new_key_one = text_type(new_course_one.id)
new_key_two = text_type(new_course_two.id)
original_key = str(course.id)
new_key_one = str(new_course_one.id)
new_key_two = str(new_course_two.id)
# Run the actual management command
call_command(