diff --git a/lms/djangoapps/instructor/access.py b/lms/djangoapps/instructor/access.py index f20a89ae20..eb38818e96 100644 --- a/lms/djangoapps/instructor/access.py +++ b/lms/djangoapps/instructor/access.py @@ -67,7 +67,7 @@ def _change_access(course, user, level, action, send_email=True): try: role = ROLES[level](course.id) except KeyError: - raise ValueError("unrecognized level '{}'".format(level)) + raise ValueError(u"unrecognized level '{}'".format(level)) if action == 'allow': if level == 'ccx_coach': @@ -83,7 +83,7 @@ def _change_access(course, user, level, action, send_email=True): elif action == 'revoke': role.remove_users(user) else: - raise ValueError("unrecognized action '{}'".format(action)) + raise ValueError(u"unrecognized action '{}'".format(action)) def update_forum_role(course_id, user, rolename, action): @@ -103,4 +103,4 @@ def update_forum_role(course_id, user, rolename, action): elif action == 'revoke': role.users.remove(user) else: - raise ValueError("unrecognized action '{}'".format(action)) + raise ValueError(u"unrecognized action '{}'".format(action)) diff --git a/lms/djangoapps/instructor/enrollment.py b/lms/djangoapps/instructor/enrollment.py index ed599886c5..4a62821c06 100644 --- a/lms/djangoapps/instructor/enrollment.py +++ b/lms/djangoapps/instructor/enrollment.py @@ -44,6 +44,7 @@ from student.models import ( anonymous_id_for_user, is_email_retired, ) +from openedx.core.djangolib.markup import Text from submissions import api as sub_api # installed from the edx-submissions repository from submissions.models import score_set from track.event_transaction_utils import ( @@ -223,7 +224,7 @@ def send_beta_role_email(action, user, email_params): email_params['email_address'] = user.email email_params['full_name'] = user.profile.name else: - raise ValueError("Unexpected action received '{}' - expected 'add' or 'remove'".format(action)) + raise ValueError(u"Unexpected action received '{}' - expected 'add' or 'remove'".format(action)) trying_to_add_inactive_user = not user.is_active and action == 'add' if not trying_to_add_inactive_user: send_mail_to_student(user.email, email_params, language=get_user_email_language(user)) @@ -274,7 +275,7 @@ def reset_student_attempts(course_id, student, module_state_key, requesting_user submission_cleared = True except ItemNotFoundError: block = None - log.warning("Could not find %s in modulestore when attempting to reset attempts.", module_state_key) + log.warning(u"Could not find %s in modulestore when attempting to reset attempts.", module_state_key) # Reset the student's score in the submissions API, if xblock.clear_student_state has not done so already. # We need to do this before retrieving the `StudentModule` model, because a score may exist with no student module. @@ -375,7 +376,7 @@ def get_email_params(course, auto_enroll, secure=True, course_key=None, display_ protocol = 'https' if secure else 'http' course_key = course_key or text_type(course.id) - display_name = display_name or course.display_name_with_default_escaped + display_name = display_name or Text(course.display_name_with_default) stripped_site_name = configuration_helpers.get_value( 'SITE_NAME', @@ -449,7 +450,7 @@ def send_mail_to_student(student, param_dict, language=None): if 'display_name' in param_dict: param_dict['course_name'] = param_dict['display_name'] elif 'course' in param_dict: - param_dict['course_name'] = param_dict['course'].display_name_with_default + param_dict['course_name'] = Text(param_dict['course'].display_name_with_default) param_dict['site_name'] = configuration_helpers.get_value( 'SITE_NAME', diff --git a/lms/djangoapps/instructor/paidcourse_enrollment_report.py b/lms/djangoapps/instructor/paidcourse_enrollment_report.py index d9fae3ce15..189946f218 100644 --- a/lms/djangoapps/instructor/paidcourse_enrollment_report.py +++ b/lms/djangoapps/instructor/paidcourse_enrollment_report.py @@ -37,7 +37,7 @@ class PaidCourseEnrollmentReportProvider(BaseAbstractEnrollmentReportProvider): # check the user enrollment role if user.is_staff: platform_name = configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME) - enrollment_role = _('{platform_name} Staff').format(platform_name=platform_name) + enrollment_role = _(u'{platform_name} Staff').format(platform_name=platform_name) elif is_course_staff: enrollment_role = _('Course Staff') else: @@ -67,14 +67,14 @@ class PaidCourseEnrollmentReportProvider(BaseAbstractEnrollmentReportProvider): manual_enrollment = ManualEnrollmentAudit.get_manual_enrollment(course_enrollment) if manual_enrollment is not None: enrollment_source = _( - 'manually enrolled by username: {username}' + u'manually enrolled by username: {username}' ).format(username=manual_enrollment.enrolled_by.username) manual_enrollment_reason = manual_enrollment.reason else: enrollment_source = _('Manually Enrolled') - enrollment_date = course_enrollment.created.strftime("%B %d, %Y") + enrollment_date = course_enrollment.created.strftime(u"%B %d, %Y") currently_enrolled = course_enrollment.is_active course_enrollment_data = collections.OrderedDict() diff --git a/lms/djangoapps/instructor/services.py b/lms/djangoapps/instructor/services.py index 8947cef23a..b0b7384173 100644 --- a/lms/djangoapps/instructor/services.py +++ b/lms/djangoapps/instructor/services.py @@ -44,7 +44,7 @@ class InstructorService(object): except ObjectDoesNotExist: err_msg = ( 'Error occurred while attempting to reset student attempts for user ' - '{student_identifier} for content_id {content_id}. ' + u'{student_identifier} for content_id {content_id}. ' 'User does not exist!'.format( student_identifier=student_identifier, content_id=content_id @@ -57,7 +57,7 @@ class InstructorService(object): module_state_key = UsageKey.from_string(content_id) except InvalidKeyError: err_msg = ( - 'Invalid content_id {content_id}!'.format(content_id=content_id) + u'Invalid content_id {content_id}!'.format(content_id=content_id) ) log.error(err_msg) return @@ -74,7 +74,7 @@ class InstructorService(object): except (StudentModule.DoesNotExist, enrollment.sub_api.SubmissionError): err_msg = ( 'Error occurred while attempting to reset student attempts for user ' - '{student_identifier} for content_id {content_id}.'.format( + u'{student_identifier} for content_id {content_id}.'.format( student_identifier=student_identifier, content_id=content_id ) @@ -106,8 +106,8 @@ class InstructorService(object): subject = _(u"Proctored Exam Review: {review_status}").format(review_status=review_status) body = _( u"A proctored exam attempt for {exam_name} in {course_name} by username: {student_username} " - "was reviewed as {review_status} by the proctored exam review provider.\n" - "Review link: {review_url}" + u"was reviewed as {review_status} by the proctored exam review provider.\n" + u"Review link: {review_url}" ).format( exam_name=exam_name, course_name=course.display_name, diff --git a/lms/djangoapps/instructor/tests/test_api.py b/lms/djangoapps/instructor/tests/test_api.py index d43a3ca5fb..e875c7e662 100644 --- a/lms/djangoapps/instructor/tests/test_api.py +++ b/lms/djangoapps/instructor/tests/test_api.py @@ -234,7 +234,7 @@ def reverse(endpoint, args=None, kwargs=None, is_dashboard_endpoint=True): if is_dashboard_endpoint and is_endpoint_declared is False: # Verify that all endpoints are declared so we can ensure they are # properly validated elsewhere. - raise ValueError("The endpoint {} must be declared in ENDPOINTS before use.".format(endpoint)) + raise ValueError(u"The endpoint {} must be declared in ENDPOINTS before use.".format(endpoint)) return django_reverse(endpoint, args=args, kwargs=kwargs) @@ -359,7 +359,7 @@ class TestEndpointHttpMethods(SharedModuleStoreTestCase, LoginEnrollmentTestCase self.assertEqual( response.status_code, 405, - "Endpoint {} returned status code {} instead of a 405. It should not allow GET.".format( + u"Endpoint {} returned status code {} instead of a 405. It should not allow GET.".format( data, response.status_code ) ) @@ -374,7 +374,7 @@ class TestEndpointHttpMethods(SharedModuleStoreTestCase, LoginEnrollmentTestCase self.assertNotEqual( response.status_code, 405, - "Endpoint {} returned status code 405 where it shouldn't, since it should allow GET.".format( + u"Endpoint {} returned status code 405 where it shouldn't, since it should allow GET.".format( data ) ) @@ -690,7 +690,7 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) # test the log for email that's send to new created user. - info_log.assert_called_with('email sent to new created user at %s', 'test_student@example.com') + info_log.assert_called_with(u'email sent to new created user at %s', 'test_student@example.com') @patch('lms.djangoapps.instructor.views.api.log.info') def test_account_creation_and_enrollment_with_csv_with_blank_lines(self, info_log): @@ -711,7 +711,7 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) # test the log for email that's send to new created user. - info_log.assert_called_with('email sent to new created user at %s', 'test_student@example.com') + info_log.assert_called_with(u'email sent to new created user at %s', 'test_student@example.com') @patch('lms.djangoapps.instructor.views.api.log.info') def test_email_and_username_already_exist(self, info_log): @@ -798,7 +798,7 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas self.assertNotEquals(len(data['row_errors']), 0) self.assertEquals(len(data['warnings']), 0) self.assertEquals(len(data['general_errors']), 0) - self.assertEquals(data['row_errors'][0]['response'], 'Invalid email {0}.'.format('test_student.example.com')) + self.assertEquals(data['row_errors'][0]['response'], u'Invalid email {0}.'.format('test_student.example.com')) manual_enrollments = ManualEnrollmentAudit.objects.all() self.assertEqual(manual_enrollments.count(), 0) @@ -835,8 +835,8 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas response = self.client.post(self.url, {'students_list': uploaded_file}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) - warning_message = 'An account with email {email} exists but the provided username {username} ' \ - 'is different. Enrolling anyway with {email}.'.format(email='test_student@example.com', username='test_student_2') + warning_message = u'An account with email {email} exists but the provided username {username} ' \ + u'is different. Enrolling anyway with {email}.'.format(email='test_student@example.com', username='test_student_2') self.assertNotEquals(len(data['warnings']), 0) self.assertEquals(data['warnings'][0]['response'], warning_message) user = User.objects.get(email='test_student@example.com') @@ -872,7 +872,7 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas self.assertNotEquals(len(data['row_errors']), 0) self.assertEquals( data['row_errors'][0]['response'], - 'Invalid email {email}.'.format(email=conflicting_email) + u'Invalid email {email}.'.format(email=conflicting_email) ) self.assertFalse(User.objects.filter(email=conflicting_email).exists()) @@ -890,7 +890,7 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertNotEquals(len(data['row_errors']), 0) - self.assertEquals(data['row_errors'][0]['response'], 'Username {user} already exists.'.format(user='test_student_1')) + self.assertEquals(data['row_errors'][0]['response'], u'Username {user} already exists.'.format(user='test_student_1')) def test_csv_file_not_attached(self): """ @@ -960,11 +960,11 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas self.assertNotEquals(len(data['row_errors']), 0) self.assertEquals( data['row_errors'][0]['response'], - 'Username {user} already exists.'.format(user='test_student_1') + u'Username {user} already exists.'.format(user='test_student_1') ) self.assertEquals( data['row_errors'][1]['response'], - 'Invalid email {email}.'.format(email='test_student4@example.com') + u'Invalid email {email}.'.format(email='test_student4@example.com') ) self.assertTrue(User.objects.filter(username='test_student_1', email='test_student1@example.com').exists()) self.assertTrue(User.objects.filter(username='test_student_2', email='test_student2@example.com').exists()) @@ -1221,7 +1221,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'enroll', 'email_students': False}) - print("type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))) + print(u"type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))) self.assertEqual(response.status_code, 200) # test that the user is now enrolled @@ -1267,7 +1267,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) - print("type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))) + print(u"type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))) self.assertEqual(response.status_code, 200) # test that the user is now enrolled @@ -1313,7 +1313,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest assert text_body.startswith('Dear NotEnrolled Student\n\n') for body in [text_body, html_body]: - self.assertIn('You have been enrolled in {course_name} at edx.org by a member of the course staff.'.format( + self.assertIn(u'You have been enrolled in {course_name} at edx.org by a member of the course staff.'.format( course_name=self.course.display_name, ), body) @@ -1350,14 +1350,14 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest register_url = '{proto}://{site}/register'.format(proto=protocol, site=self.site_name) assert text_body.startswith('Dear student,') - assert 'To finish your registration, please visit {register_url}'.format( + assert u'To finish your registration, please visit {register_url}'.format( register_url=register_url, ) in text_body assert 'Please finish your registration and fill out' in html_body assert register_url in html_body for body in [text_body, html_body]: - assert 'You have been invited to join {course} at edx.org by a member of the course staff.'.format( + assert u'You have been invited to join {course} at edx.org by a member of the course staff.'.format( course=self.course.display_name ) in body @@ -1395,7 +1395,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest assert 'Please finish your registration and fill' in html_body for body in [text_body, html_body]: - assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( + assert u'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( display_name=self.course.display_name ) in body @@ -1407,7 +1407,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest assert ('fill out the registration form making sure to use ' 'robot-not-an-email-yet@robot.org in the Email field') in body - assert 'You can then enroll in {display_name}.'.format( + assert u'You can then enroll in {display_name}.'.format( display_name=self.course.display_name ) in body @@ -1420,7 +1420,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest 'auto_enroll': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) - print("type(self.notregistered_email): {}".format(type(self.notregistered_email))) + print(u"type(self.notregistered_email): {}".format(type(self.notregistered_email))) self.assertEqual(response.status_code, 200) # Check the outbox @@ -1441,7 +1441,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest ) assert text_body.startswith('Dear student,') - assert 'To finish your registration, please visit {register_url}'.format( + assert u'To finish your registration, please visit {register_url}'.format( register_url=register_url, ) in text_body assert 'Please finish your registration and fill out the registration' in html_body @@ -1449,7 +1449,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest assert register_url in html_body for body in [text_body, html_body]: - assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( + assert u'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( display_name=self.course.display_name ) in body @@ -1457,8 +1457,8 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest 'out the registration form making sure to use robot-not-an-email-yet@robot.org ' 'in the Email field') in body - assert ('Once you have registered and activated your account, ' - 'you will see {display_name} listed on your dashboard.').format( + assert (u'Once you have registered and activated your account, ' + u'you will see {display_name} listed on your dashboard.').format( display_name=self.course.display_name ) in body @@ -1468,7 +1468,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': False}) - print("type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))) + print(u"type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))) self.assertEqual(response.status_code, 200) # test that the user is now unenrolled @@ -1511,7 +1511,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': True}) - print("type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))) + print(u"type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))) self.assertEqual(response.status_code, 200) # test that the user is now unenrolled @@ -1551,7 +1551,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, - 'You have been unenrolled from {display_name}'.format(display_name=self.course.display_name,) + u'You have been unenrolled from {display_name}'.format(display_name=self.course.display_name,) ) text_body = mail.outbox[0].body @@ -1560,7 +1560,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest assert text_body.startswith('Dear Enrolled Student') for body in [text_body, html_body]: - assert 'You have been unenrolled from {display_name} at edx.org by a member of the course staff.'.format( + assert u'You have been unenrolled from {display_name} at edx.org by a member of the course staff.'.format( display_name=self.course.display_name, ) in body @@ -1572,7 +1572,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.allowed_email, 'action': 'unenroll', 'email_students': True}) - print("type(self.allowed_email): {}".format(type(self.allowed_email))) + print(u"type(self.allowed_email): {}".format(type(self.allowed_email))) self.assertEqual(response.status_code, 200) # test the response data @@ -1608,7 +1608,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, - 'You have been unenrolled from {display_name}'.format(display_name=self.course.display_name,) + u'You have been unenrolled from {display_name}'.format(display_name=self.course.display_name,) ) text_body = mail.outbox[0].body @@ -1616,7 +1616,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest assert text_body.startswith('Dear Student,') for body in [text_body, html_body]: - assert 'You have been unenrolled from the course {display_name} by a member of the course staff.'.format( + assert u'You have been unenrolled from the course {display_name} by a member of the course staff.'.format( display_name=self.course.display_name, ) in body @@ -1638,7 +1638,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, - 'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,) + u'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,) ) text_body = mail.outbox[0].body @@ -1649,14 +1649,14 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest about_path=self.about_path, ) assert text_body.startswith('Dear student,') - assert 'To access this course visit {course_url} and register for this course.'.format( + assert u'To access this course visit {course_url} and register for this course.'.format( course_url=course_url, ) in text_body assert 'To access this course visit it and register:' in html_body assert course_url in html_body for body in [text_body, html_body]: - assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( + assert u'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( display_name=self.course.display_name, ) in body @@ -1681,7 +1681,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest assert text_body.startswith('Dear student,') for body in [text_body, html_body]: - assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( + assert u'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( display_name=self.course.display_name, ) in body @@ -1697,14 +1697,14 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest 'auto_enroll': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) - print("type(self.notregistered_email): {}".format(type(self.notregistered_email))) + print(u"type(self.notregistered_email): {}".format(type(self.notregistered_email))) self.assertEqual(response.status_code, 200) # Check the outbox self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, - 'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,) + u'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,) ) text_body = mail.outbox[0].body @@ -1715,11 +1715,11 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest assert text_body.startswith('Dear student,') assert course_url in html_body - assert 'To access this course visit {course_url} and login.'.format(course_url=course_url) in text_body + assert u'To access this course visit {course_url} and login.'.format(course_url=course_url) in text_body assert 'To access this course click on the button below and login:' in html_body for body in [text_body, html_body]: - assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( + assert u'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( display_name=self.course.display_name, ) in body @@ -2113,17 +2113,17 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, - 'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name,) + u'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name,) ) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] student_name = self.notenrolled_student.profile.name - assert text_body.startswith('Dear {student_name}'.format(student_name=student_name)) - assert 'Visit {display_name}'.format(display_name=self.course.display_name) in html_body + assert text_body.startswith(u'Dear {student_name}'.format(student_name=student_name)) + assert u'Visit {display_name}'.format(display_name=self.course.display_name) in html_body for body in [text_body, html_body]: - assert 'You have been invited to be a beta tester for {display_name} at edx.org'.format( + assert u'You have been invited to be a beta tester for {display_name} at edx.org'.format( display_name=self.course.display_name, ) in body @@ -2136,7 +2136,7 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll about_path=self.about_path, ) in body - assert 'This email was automatically sent from edx.org to {student_email}'.format( + assert u'This email was automatically sent from edx.org to {student_email}'.format( student_email=self.notenrolled_student.email, ) in body @@ -2169,16 +2169,16 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll self.assertEqual(len(mail.outbox), 1) self.assertEqual( mail.outbox[0].subject, - 'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name) + u'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name) ) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] student_name = self.notenrolled_student.profile.name - assert text_body.startswith('Dear {student_name}'.format(student_name=student_name)) + assert text_body.startswith(u'Dear {student_name}'.format(student_name=student_name)) for body in [text_body, html_body]: - assert 'You have been invited to be a beta tester for {display_name} at edx.org'.format( + assert u'You have been invited to be a beta tester for {display_name} at edx.org'.format( display_name=self.course.display_name, ) in body @@ -2191,7 +2191,7 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll course_path=self.course_path ) - assert 'This email was automatically sent from edx.org to {student_email}'.format( + assert u'This email was automatically sent from edx.org to {student_email}'.format( student_email=self.notenrolled_student.email, ) in body @@ -2206,17 +2206,17 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] student_name = self.notenrolled_student.profile.name - assert text_body.startswith('Dear {student_name}'.format(student_name=student_name)) + assert text_body.startswith(u'Dear {student_name}'.format(student_name=student_name)) for body in [text_body, html_body]: - assert 'You have been invited to be a beta tester for {display_name} at edx.org'.format( + assert u'You have been invited to be a beta tester for {display_name} at edx.org'.format( display_name=self.course.display_name, ) in body assert 'by a member of the course staff.' in body assert 'Visit edx.org' in body assert 'enroll in this course and begin the beta test' in body - assert 'This email was automatically sent from edx.org to {student_email}'.format( + assert u'This email was automatically sent from edx.org to {student_email}'.format( student_email=self.notenrolled_student.email, ) in body @@ -2312,10 +2312,10 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] - assert text_body.startswith('Dear {name}'.format(name=self.beta_tester.profile.name)) + assert text_body.startswith(u'Dear {name}'.format(name=self.beta_tester.profile.name)) for body in [text_body, html_body]: - assert 'You have been removed as a beta tester for {display_name} at edx.org'.format( + assert u'You have been removed as a beta tester for {display_name} at edx.org'.format( display_name=self.course.display_name, ) in body @@ -2324,7 +2324,7 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll assert 'Your other courses have not been affected.' in body - assert 'This email was automatically sent from edx.org to {email_address}'.format( + assert u'This email was automatically sent from edx.org to {email_address}'.format( email_address=self.beta_tester.email, ) in body @@ -2681,7 +2681,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment # submitting invalid invoice number data['invoice_number'] = 'testing' response = self.assert_request_status_code(400, url, method="POST", data=data) - self.assertIn("invoice_number must be an integer, {value} provided".format(value=data['invoice_number']), response.content) + self.assertIn(u"invoice_number must be an integer, {value} provided".format(value=data['invoice_number']), response.content) def test_get_sale_order_records_features_csv(self): """ @@ -2981,7 +2981,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment correctly in the response to get_students_features. """ for student in self.students: - student.profile.city = "Mos Eisley {}".format(student.id) + student.profile.city = u"Mos Eisley {}".format(student.id) student.profile.save() url = reverse('get_students_features', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {}) @@ -3335,7 +3335,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment kwargs = {'course_id': unicode(self.course.id)} kwargs.update(extra_instructor_api_kwargs) url = reverse(instructor_api_endpoint, kwargs=kwargs) - success_status = "The {report_type} report is being created.".format(report_type=report_type) + success_status = u"The {report_type} report is being created.".format(report_type=report_type) with patch(task_api_endpoint) as patched_task_api_endpoint: patched_task_api_endpoint.return_value.task_id = "12345667-9abc-deff-ffed-cba987654321" @@ -3364,7 +3364,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment CourseFinanceAdminRole(self.course.id).add_users(self.instructor) with patch(task_api_endpoint): response = self.client.post(url, {}) - success_status = "The {report_type} report is being created." \ + success_status = u"The {report_type} report is being created." \ " To view the status of the report, see Pending" \ " Tasks below".format(report_type=report_type) self.assertIn(success_status, response.content) @@ -3877,7 +3877,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE }) self.assertEqual(response.status_code, 200) # check response - message = _('This student (%s) will skip the entrance exam.') % self.student.email + message = _(u'This student (%s) will skip the entrance exam.') % self.student.email self.assertContains(response, message) # post again with same student @@ -3886,7 +3886,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE }) # This time response message should be different - message = _('This student (%s) is already allowed to skip the entrance exam.') % self.student.email + message = _(u'This student (%s) is already allowed to skip the entrance exam.') % self.student.email self.assertContains(response, message) @@ -4768,10 +4768,10 @@ class TestCourseIssuedCertificatesData(SharedModuleStoreTestCase): for __ in xrange(certificate_count): self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) - current_date = datetime.date.today().strftime("%B %d, %Y") + current_date = datetime.date.today().strftime(u"%B %d, %Y") response = self.client.get(url, {'csv': 'true'}) self.assertEqual(response['Content-Type'], 'text/csv') - self.assertEqual(response['Content-Disposition'], 'attachment; filename={0}'.format('issued_certificates.csv')) + self.assertEqual(response['Content-Disposition'], u'attachment; filename={0}'.format('issued_certificates.csv')) self.assertEqual( response.content.strip(), '"CourseID","Certificate Type","Total Certificates Issued","Date Report Run"\r\n"' diff --git a/lms/djangoapps/instructor/tests/test_certificates.py b/lms/djangoapps/instructor/tests/test_certificates.py index a508103525..0f2322fabc 100644 --- a/lms/djangoapps/instructor/tests/test_certificates.py +++ b/lms/djangoapps/instructor/tests/test_certificates.py @@ -186,7 +186,7 @@ class CertificatesInstructorDashTest(SharedModuleStoreTestCase): response = self.client.get(self.url) if expected_status == 'started': - expected = 'Generating example {name} certificate'.format(name=cert_name) + expected = u'Generating example {name} certificate'.format(name=cert_name) self.assertContains(response, expected) elif expected_status == 'error': expected = self.ERROR_REASON @@ -195,7 +195,7 @@ class CertificatesInstructorDashTest(SharedModuleStoreTestCase): expected = self.DOWNLOAD_URL self.assertContains(response, expected) else: - self.fail("Invalid certificate status: {status}".format(status=expected_status)) + self.fail(u"Invalid certificate status: {status}".format(status=expected_status)) def _assert_enable_certs_button_is_disabled(self): """Check that the "enable student-generated certificates" button is disabled. """ @@ -685,7 +685,7 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): # Assert Error Message self.assertEqual( res_json['message'], - "{user} is not enrolled in this course. Please check your spelling and retry.".format( + u"{user} is not enrolled in this course. Please check your spelling and retry.".format( user=self.certificate_exception['user_name'] ) ) diff --git a/lms/djangoapps/instructor/tests/test_ecommerce.py b/lms/djangoapps/instructor/tests/test_ecommerce.py index 25ad7e6d22..239b448a20 100644 --- a/lms/djangoapps/instructor/tests/test_ecommerce.py +++ b/lms/djangoapps/instructor/tests/test_ecommerce.py @@ -158,7 +158,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): # Course Mode not exist with mode slug honor response = self.client.post(set_course_price_url, data) self.assertIn( - "CourseMode with the mode slug({mode_slug}) DoesNotExist".format(mode_slug='honor'), + u"CourseMode with the mode slug({mode_slug}) DoesNotExist".format(mode_slug='honor'), response.content ) @@ -179,7 +179,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): } response = self.client.post(add_coupon_url, data) self.assertIn( - "coupon with the coupon code ({code}) added successfully".format(code=data['code']), + u"coupon with the coupon code ({code}) added successfully".format(code=data['code']), response.content ) @@ -198,7 +198,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): 'description': 'asdsasda', 'created_by': self.instructor, 'discount': 99 } response = self.client.post(add_coupon_url, data) - self.assertIn("coupon with the coupon code ({code}) already exist".format(code='A2314'), response.content) + self.assertIn(u"coupon with the coupon code ({code}) already exist".format(code='A2314'), response.content) response = self.client.post(self.url) self.assertIn('
%s' % msg.replace('<', '<') + msg = HTML('
{}').format(Text(msg))
return msg
diff --git a/lms/djangoapps/instructor_analytics/csvs.py b/lms/djangoapps/instructor_analytics/csvs.py
index 77fda1d07c..f66e748bf6 100644
--- a/lms/djangoapps/instructor_analytics/csvs.py
+++ b/lms/djangoapps/instructor_analytics/csvs.py
@@ -21,7 +21,7 @@ def create_csv_response(filename, header, datarows):
"""
response = HttpResponse(content_type='text/csv')
- response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
+ response['Content-Disposition'] = u'attachment; filename={0}'.format(filename)
csvwriter = csv.writer(
response,
dialect='excel',
diff --git a/lms/djangoapps/instructor_analytics/distributions.py b/lms/djangoapps/instructor_analytics/distributions.py
index fe2394625a..93d1c9bcb2 100644
--- a/lms/djangoapps/instructor_analytics/distributions.py
+++ b/lms/djangoapps/instructor_analytics/distributions.py
@@ -1,4 +1,4 @@
-"""
+u"""
Profile Distributions
Aggregate sums for values of fields in students profiles.
@@ -95,7 +95,7 @@ def profile_distribution(course_id, feature):
if feature not in AVAILABLE_PROFILE_FEATURES:
raise ValueError(
- "unsupported feature requested for distribution '{}'".format(
+ u"unsupported feature requested for distribution u'{}'".format(
feature)
)
diff --git a/lms/djangoapps/instructor_analytics/tests/test_basic.py b/lms/djangoapps/instructor_analytics/tests/test_basic.py
index cffbeed0e0..c59ea00d4c 100644
--- a/lms/djangoapps/instructor_analytics/tests/test_basic.py
+++ b/lms/djangoapps/instructor_analytics/tests/test_basic.py
@@ -62,8 +62,8 @@ class TestAnalyticsBasic(ModuleStoreTestCase):
self.instructor = InstructorFactory(course_key=self.course_key)
for user in self.users:
user.profile.meta = json.dumps({
- "position": "edX expert {}".format(user.id),
- "company": "Open edX Inc {}".format(user.id),
+ "position": u"edX expert {}".format(user.id),
+ "company": u"Open edX Inc {}".format(user.id),
})
user.profile.save()
self.students_who_may_enroll = list(self.users) + [UserFactory() for _ in range(5)]
@@ -125,8 +125,8 @@ class TestAnalyticsBasic(ModuleStoreTestCase):
def test_enrolled_students_features_keys(self):
query_features = ('username', 'name', 'email', 'city', 'country',)
for user in self.users:
- user.profile.city = "Mos Eisley {}".format(user.id)
- user.profile.country = "Tatooine {}".format(user.id)
+ user.profile.city = u"Mos Eisley {}".format(user.id)
+ user.profile.country = u"Tatooine {}".format(user.id)
user.profile.save()
for feature in query_features:
self.assertIn(feature, AVAILABLE_FEATURES)
@@ -163,8 +163,8 @@ class TestAnalyticsBasic(ModuleStoreTestCase):
self.assertEqual(len(userreports), len(self.users))
for userreport in userreports:
self.assertEqual(set(userreport.keys()), set(query_features))
- self.assertIn(userreport['meta.position'], ["edX expert {}".format(user.id) for user in self.users])
- self.assertIn(userreport['meta.company'], ["Open edX Inc {}".format(user.id) for user in self.users])
+ self.assertIn(userreport['meta.position'], [u"edX expert {}".format(user.id) for user in self.users])
+ self.assertIn(userreport['meta.company'], [u"Open edX Inc {}".format(user.id) for user in self.users])
def test_enrolled_students_enrollment_verification(self):
"""
diff --git a/lms/djangoapps/instructor_analytics/tests/test_csvs.py b/lms/djangoapps/instructor_analytics/tests/test_csvs.py
index 8a82bb0bab..e7983a5fe9 100644
--- a/lms/djangoapps/instructor_analytics/tests/test_csvs.py
+++ b/lms/djangoapps/instructor_analytics/tests/test_csvs.py
@@ -16,7 +16,7 @@ class TestAnalyticsCSVS(TestCase):
res = create_csv_response('robot.csv', header, datarows)
self.assertEqual(res['Content-Type'], 'text/csv')
- self.assertEqual(res['Content-Disposition'], 'attachment; filename={0}'.format('robot.csv'))
+ self.assertEqual(res['Content-Disposition'], u'attachment; filename={0}'.format('robot.csv'))
self.assertEqual(res.content.strip(), '"Name","Email"')
def test_create_csv_response(self):
@@ -25,7 +25,7 @@ class TestAnalyticsCSVS(TestCase):
res = create_csv_response('robot.csv', header, datarows)
self.assertEqual(res['Content-Type'], 'text/csv')
- self.assertEqual(res['Content-Disposition'], 'attachment; filename={0}'.format('robot.csv'))
+ self.assertEqual(res['Content-Disposition'], u'attachment; filename={0}'.format('robot.csv'))
self.assertEqual(res.content.strip(), '"Name","Email"\r\n"Jim","jim@edy.org"\r\n"Jake","jake@edy.org"\r\n"Jeeves","jeeves@edy.org"')
def test_create_csv_response_empty(self):
@@ -34,7 +34,7 @@ class TestAnalyticsCSVS(TestCase):
res = create_csv_response('robot.csv', header, datarows)
self.assertEqual(res['Content-Type'], 'text/csv')
- self.assertEqual(res['Content-Disposition'], 'attachment; filename={0}'.format('robot.csv'))
+ self.assertEqual(res['Content-Disposition'], u'attachment; filename={0}'.format('robot.csv'))
self.assertEqual(res.content.strip(), '')
@@ -79,7 +79,7 @@ class TestAnalyticsFormatDictlist(TestCase):
res = create_csv_response('robot.csv', header, datarows)
self.assertEqual(res['Content-Type'], 'text/csv')
- self.assertEqual(res['Content-Disposition'], 'attachment; filename={0}'.format('robot.csv'))
+ self.assertEqual(res['Content-Disposition'], u'attachment; filename={0}'.format('robot.csv'))
self.assertEqual(res.content.strip(), '"Name","Email"\r\n"Jim","jim@edy.org"\r\n"Jake","jake@edy.org"\r\n"Jeeves","jeeves@edy.org"')
diff --git a/lms/djangoapps/instructor_task/api.py b/lms/djangoapps/instructor_task/api.py
index 9cd38750d2..dda5be3c65 100644
--- a/lms/djangoapps/instructor_task/api.py
+++ b/lms/djangoapps/instructor_task/api.py
@@ -308,7 +308,7 @@ def submit_bulk_course_email(request, course_key, email_id):
targets = Counter([target.target_type for target in email_obj.targets.all()])
targets = [
target if count <= 1 else
- "{} {}".format(count, target)
+ u"{} {}".format(count, target)
for target, count in targets.iteritems()
]
diff --git a/lms/djangoapps/instructor_task/api_helper.py b/lms/djangoapps/instructor_task/api_helper.py
index 1504ef747d..ddd53ddc06 100644
--- a/lms/djangoapps/instructor_task/api_helper.py
+++ b/lms/djangoapps/instructor_task/api_helper.py
@@ -75,7 +75,7 @@ def _reserve_task(course_id, task_type, task_key, task_input, requester):
"""
if _task_is_running(course_id, task_type, task_key):
- log.warning("Duplicate task found for task_type %s and task_key %s", task_type, task_key)
+ log.warning(u"Duplicate task found for task_type %s and task_key %s", task_type, task_key)
error_message = generate_already_running_error_message(task_type)
raise AlreadyRunningError(error_message)
@@ -85,7 +85,7 @@ def _reserve_task(course_id, task_type, task_key, task_input, requester):
most_recent_id = "None found"
finally:
log.warning(
- "No duplicate tasks found: task_type %s, task_key %s, and most recent task_id = %s",
+ u"No duplicate tasks found: task_type %s, task_key %s, and most recent task_id = %s",
task_type,
task_key,
most_recent_id
@@ -118,7 +118,7 @@ def generate_already_running_error_message(task_type):
if report_types.get(task_type):
message = _(
- "The {report_type} report is being created. "
+ u"The {report_type} report is being created. "
"To view the status of the report, see Pending Tasks below. "
"You will be able to download the report when it is complete."
).format(report_type=report_types.get(task_type))
@@ -213,20 +213,20 @@ def _update_instructor_task(instructor_task, task_result):
elif result_state in [PROGRESS, SUCCESS]:
# construct a status message directly from the task result's result:
# it needs to go back with the entry passed in.
- log.info("background task (%s), state %s: result: %s", task_id, result_state, returned_result)
+ log.info(u"background task (%s), state %s: result: %s", task_id, result_state, returned_result)
task_output = InstructorTask.create_output_for_success(returned_result)
elif result_state == FAILURE:
# on failure, the result's result contains the exception that caused the failure
exception = returned_result
traceback = result_traceback if result_traceback is not None else ''
- log.warning("background task (%s) failed: %s %s", task_id, returned_result, traceback)
+ log.warning(u"background task (%s) failed: %s %s", task_id, returned_result, traceback)
task_output = InstructorTask.create_output_for_failure(exception, result_traceback)
elif result_state == REVOKED:
# on revocation, the result's result doesn't contain anything
# but we cannot rely on the worker thread to set this status,
# so we set it here.
entry_needs_saving = True
- log.warning("background task (%s) revoked.", task_id)
+ log.warning(u"background task (%s) revoked.", task_id)
task_output = InstructorTask.create_output_for_revoked()
# save progress and state into the entry, even if it's not being saved:
@@ -256,7 +256,7 @@ def _handle_instructor_task_failure(instructor_task, error):
"""
Do required operations if task creation was not complete.
"""
- log.info("instructor task (%s) failed, result: %s", instructor_task.task_id, text_type(error))
+ log.info(u"instructor task (%s) failed, result: %s", instructor_task.task_id, text_type(error))
_update_instructor_task_state(instructor_task, FAILURE, text_type(error))
raise QueueConnectionError()
@@ -273,7 +273,7 @@ def get_updated_instructor_task(task_id):
try:
instructor_task = InstructorTask.objects.get(task_id=task_id)
except InstructorTask.DoesNotExist:
- log.warning("query for InstructorTask status failed: task_id=(%s) not found", task_id)
+ log.warning(u"query for InstructorTask status failed: task_id=(%s) not found", task_id)
return None
# if the task is not already known to be done, then we need to query
diff --git a/lms/djangoapps/instructor_task/models.py b/lms/djangoapps/instructor_task/models.py
index 2938e8d561..612f07f075 100644
--- a/lms/djangoapps/instructor_task/models.py
+++ b/lms/djangoapps/instructor_task/models.py
@@ -99,7 +99,7 @@ class InstructorTask(models.Model):
# check length of task_input, and return an exception if it's too long:
if len(json_task_input) > 265:
- fmt = 'Task input longer than 265: "{input}" for "{task}" of "{course}"'
+ fmt = u'Task input longer than 265: "{input}" for "{task}" of "{course}"'
msg = fmt.format(input=json_task_input, task=task_type, course=course_id)
raise ValueError(msg)
@@ -135,7 +135,7 @@ class InstructorTask(models.Model):
# will fit in the column. In the meantime, just return an exception.
json_output = json.dumps(returned_result)
if len(json_output) > 1023:
- raise ValueError("Length of task output is too long: {0}".format(json_output))
+ raise ValueError(u"Length of task output is too long: {0}".format(json_output))
return json_output
@staticmethod
diff --git a/lms/djangoapps/instructor_task/subtasks.py b/lms/djangoapps/instructor_task/subtasks.py
index fc209625ab..206ea6ecd7 100644
--- a/lms/djangoapps/instructor_task/subtasks.py
+++ b/lms/djangoapps/instructor_task/subtasks.py
@@ -113,7 +113,7 @@ def _generate_items_for_subtask(
# more items than items_per_task allows. We expect this to be a small enough
# number as to be negligible.
if num_items_queued != total_num_items:
- TASK_LOG.info("Number of items generated by chunking %s not equal to original total %s", num_items_queued, total_num_items)
+ TASK_LOG.info(u"Number of items generated by chunking %s not equal to original total %s", num_items_queued, total_num_items)
class SubtaskStatus(object):
@@ -302,7 +302,7 @@ def queue_subtasks_for_query(
# Update the InstructorTask with information about the subtasks we've defined.
TASK_LOG.info(
- "Task %s: updating InstructorTask %s with subtask info for %s subtasks to process %s items.",
+ u"Task %s: updating InstructorTask %s with subtask info for %s subtasks to process %s items.",
task_id,
entry.id,
total_num_subtasks,
@@ -325,7 +325,7 @@ def queue_subtasks_for_query(
# Now create the subtasks, and start them running.
TASK_LOG.info(
- "Task %s: creating %s subtasks to process %s items.",
+ u"Task %s: creating %s subtasks to process %s items.",
task_id,
total_num_subtasks,
total_num_items,
@@ -359,7 +359,7 @@ def _acquire_subtask_lock(task_id):
key = "subtask-{}".format(task_id)
succeeded = cache.add(key, 'true', SUBTASK_LOCK_EXPIRE)
if not succeeded:
- TASK_LOG.warning("task_id '%s': already locked. Contains value '%s'", task_id, cache.get(key))
+ TASK_LOG.warning(u"task_id '%s': already locked. Contains value '%s'", task_id, cache.get(key))
return succeeded
@@ -401,7 +401,7 @@ def check_subtask_is_valid(entry_id, current_task_id, new_subtask_status):
# Confirm that the InstructorTask actually defines subtasks.
entry = InstructorTask.objects.get(pk=entry_id)
if len(entry.subtasks) == 0:
- format_str = "Unexpected task_id '{}': unable to find subtasks of instructor task '{}': rejecting task {}"
+ format_str = u"Unexpected task_id '{}': unable to find subtasks of instructor task '{}': rejecting task {}"
msg = format_str.format(current_task_id, entry, new_subtask_status)
TASK_LOG.warning(msg)
raise DuplicateTaskException(msg)
@@ -410,7 +410,7 @@ def check_subtask_is_valid(entry_id, current_task_id, new_subtask_status):
subtask_dict = json.loads(entry.subtasks)
subtask_status_info = subtask_dict['status']
if current_task_id not in subtask_status_info:
- format_str = "Unexpected task_id '{}': unable to find status for subtask of instructor task '{}': rejecting task {}"
+ format_str = u"Unexpected task_id '{}': unable to find status for subtask of instructor task '{}': rejecting task {}"
msg = format_str.format(current_task_id, entry, new_subtask_status)
TASK_LOG.warning(msg)
raise DuplicateTaskException(msg)
@@ -420,7 +420,7 @@ def check_subtask_is_valid(entry_id, current_task_id, new_subtask_status):
subtask_status = SubtaskStatus.from_dict(subtask_status_info[current_task_id])
subtask_state = subtask_status.state
if subtask_state in READY_STATES:
- format_str = "Unexpected task_id '{}': already completed - status {} for subtask of instructor task '{}': rejecting task {}"
+ format_str = u"Unexpected task_id '{}': already completed - status {} for subtask of instructor task '{}': rejecting task {}"
msg = format_str.format(current_task_id, subtask_status, entry, new_subtask_status)
TASK_LOG.warning(msg)
raise DuplicateTaskException(msg)
@@ -433,7 +433,7 @@ def check_subtask_is_valid(entry_id, current_task_id, new_subtask_status):
new_retry_count = new_subtask_status.get_retry_count()
current_retry_count = subtask_status.get_retry_count()
if new_retry_count < current_retry_count:
- format_str = "Unexpected task_id '{}': already retried - status {} for subtask of instructor task '{}': rejecting task {}"
+ format_str = u"Unexpected task_id '{}': already retried - status {} for subtask of instructor task '{}': rejecting task {}"
msg = format_str.format(current_task_id, subtask_status, entry, new_subtask_status)
TASK_LOG.warning(msg)
raise DuplicateTaskException(msg)
@@ -442,7 +442,7 @@ def check_subtask_is_valid(entry_id, current_task_id, new_subtask_status):
# If it fails, then it means that another worker is already in the
# middle of working on this.
if not _acquire_subtask_lock(current_task_id):
- format_str = "Unexpected task_id '{}': already being executed - for subtask of instructor task '{}'"
+ format_str = u"Unexpected task_id '{}': already being executed - for subtask of instructor task '{}'"
msg = format_str.format(current_task_id, entry)
TASK_LOG.warning(msg)
raise DuplicateTaskException(msg)
@@ -466,11 +466,11 @@ def update_subtask_status(entry_id, current_task_id, new_subtask_status, retry_c
# If we fail, try again recursively.
retry_count += 1
if retry_count < MAX_DATABASE_LOCK_RETRIES:
- TASK_LOG.info("Retrying to update status for subtask %s of instructor task %d with status %s: retry %d",
+ TASK_LOG.info(u"Retrying to update status for subtask %s of instructor task %d with status %s: retry %d",
current_task_id, entry_id, new_subtask_status, retry_count)
update_subtask_status(entry_id, current_task_id, new_subtask_status, retry_count)
else:
- TASK_LOG.info("Failed to update status after %d retries for subtask %s of instructor task %d with status %s",
+ TASK_LOG.info(u"Failed to update status after %d retries for subtask %s of instructor task %d with status %s",
retry_count, current_task_id, entry_id, new_subtask_status)
raise
finally:
@@ -508,7 +508,7 @@ def _update_subtask_status(entry_id, current_task_id, new_subtask_status):
is the value of the SubtaskStatus.to_dict(), but could be expanded in future to store information
about failure messages, progress made, etc.
"""
- TASK_LOG.info("Preparing to update status for subtask %s for instructor task %d with status %s",
+ TASK_LOG.info(u"Preparing to update status for subtask %s for instructor task %d with status %s",
current_task_id, entry_id, new_subtask_status)
try:
@@ -517,7 +517,7 @@ def _update_subtask_status(entry_id, current_task_id, new_subtask_status):
subtask_status_info = subtask_dict['status']
if current_task_id not in subtask_status_info:
# unexpected error -- raise an exception
- format_str = "Unexpected task_id '{}': unable to update status for subtask of instructor task '{}'"
+ format_str = u"Unexpected task_id '{}': unable to update status for subtask of instructor task '{}'"
msg = format_str.format(current_task_id, entry_id)
TASK_LOG.warning(msg)
raise ValueError(msg)
@@ -564,7 +564,7 @@ def _update_subtask_status(entry_id, current_task_id, new_subtask_status):
TASK_LOG.debug("about to save....")
entry.save()
- TASK_LOG.info("Task output updated to %s for subtask %s of instructor task %d",
+ TASK_LOG.info(u"Task output updated to %s for subtask %s of instructor task %d",
entry.task_output, current_task_id, entry_id)
except Exception:
TASK_LOG.exception("Unexpected error while updating InstructorTask.")
diff --git a/lms/djangoapps/instructor_task/tasks_base.py b/lms/djangoapps/instructor_task/tasks_base.py
index 1b7419feaa..c650b80912 100644
--- a/lms/djangoapps/instructor_task/tasks_base.py
+++ b/lms/djangoapps/instructor_task/tasks_base.py
@@ -49,7 +49,7 @@ class BaseInstructorTask(Task):
This is JSON-serialized and stored in the task_output column of the InstructorTask entry.
"""
- TASK_LOG.debug('Task %s: success returned with progress: %s', task_id, task_progress)
+ TASK_LOG.debug(u'Task %s: success returned with progress: %s', task_id, task_progress)
# We should be able to find the InstructorTask object to update
# based on the task_id here, without having to dig into the
# original args to the task. On the other hand, the entry_id
diff --git a/lms/djangoapps/instructor_task/tasks_helper/module_state.py b/lms/djangoapps/instructor_task/tasks_helper/module_state.py
index 6508ff63e7..5d20274720 100644
--- a/lms/djangoapps/instructor_task/tasks_helper/module_state.py
+++ b/lms/djangoapps/instructor_task/tasks_helper/module_state.py
@@ -101,7 +101,7 @@ def perform_module_state_update(update_fcn, filter_fcn, _entry_id, course_id, ta
elif update_status == UPDATE_STATUS_SKIPPED:
task_progress.skipped += 1
else:
- raise UpdateProblemModuleStateError("Unexpected update_status returned: {}".format(update_status))
+ raise UpdateProblemModuleStateError(u"Unexpected update_status returned: {}".format(update_status))
return task_progress.update_task_state()
@@ -141,7 +141,7 @@ def rescore_problem_module_state(xmodule_instance_args, module_descriptor, stude
if instance is None:
# Either permissions just changed, or someone is trying to be clever
# and load something they shouldn't have access to.
- msg = "No module {location} for student {student}--access denied?".format(
+ msg = u"No module {location} for student {student}--access denied?".format(
location=usage_key,
student=student
)
@@ -151,7 +151,7 @@ def rescore_problem_module_state(xmodule_instance_args, module_descriptor, stude
if not hasattr(instance, 'rescore'):
# This should not happen, since it should be already checked in the
# caller, but check here to be sure.
- msg = "Specified module {0} of type {1} does not support rescoring.".format(usage_key, instance.__class__)
+ msg = u"Specified module {0} of type {1} does not support rescoring.".format(usage_key, instance.__class__)
raise UpdateProblemModuleStateError(msg)
# We check here to see if the problem has any submissions. If it does not, we don't want to rescore it
@@ -226,7 +226,7 @@ def override_score_module_state(xmodule_instance_args, module_descriptor, studen
if instance is None:
# Either permissions just changed, or someone is trying to be clever
# and load something they shouldn't have access to.
- msg = "No module {location} for student {student}--access denied?".format(
+ msg = u"No module {location} for student {student}--access denied?".format(
location=usage_key,
student=student
)
diff --git a/lms/djangoapps/instructor_task/tests/test_base.py b/lms/djangoapps/instructor_task/tests/test_base.py
index 80bad8b4c5..ad48703176 100644
--- a/lms/djangoapps/instructor_task/tests/test_base.py
+++ b/lms/djangoapps/instructor_task/tests/test_base.py
@@ -219,7 +219,7 @@ class InstructorTaskModuleTestCase(InstructorTaskCourseTestCase):
Returns the factory args for the option problem type.
"""
return {
- 'question_text': 'The correct answer is {0}'.format(correct_answer),
+ 'question_text': u'The correct answer is {0}'.format(correct_answer),
'options': [OPTION_1, OPTION_2],
'correct_option': correct_answer,
'num_responses': num_responses,
diff --git a/lms/djangoapps/instructor_task/tests/test_integration.py b/lms/djangoapps/instructor_task/tests/test_integration.py
index 770e25ffc2..6cd1e550b3 100644
--- a/lms/djangoapps/instructor_task/tests/test_integration.py
+++ b/lms/djangoapps/instructor_task/tests/test_integration.py
@@ -354,7 +354,7 @@ class TestRescoringTask(TestIntegrationTask):
to not-equals).
"""
factory = CustomResponseXMLFactory()
- script = textwrap.dedent("""
+ script = textwrap.dedent(u"""
def check_func(expect, answer_given):
expected = str(random.randint(0, 100))
return {'ok': answer_given %s expected, 'msg': expected}
@@ -400,7 +400,7 @@ class TestRescoringTask(TestIntegrationTask):
module = self.get_student_module(user.username, descriptor)
state = json.loads(module.state)
correct_map = state['correct_map']
- log.info("Correct Map: %s", correct_map)
+ log.info(u"Correct Map: %s", correct_map)
# only one response, so pull it out:
answer = correct_map.values()[0]['msg']
self.submit_student_answer(user.username, problem_url_name, [answer, answer])
@@ -596,7 +596,7 @@ class TestGradeReportConditionalContent(TestReportMixin, TestConditionalContent,
def user_partition_group(user):
"""Return a dict having single key with value equals to students group in partition"""
- group_config_hdr_tpl = 'Experiment Group ({})'
+ group_config_hdr_tpl = u'Experiment Group ({})'
return {
group_config_hdr_tpl.format(self.partition.name): self.partition.scheme.get_group_for_user(
self.course.id, user, self.partition
diff --git a/lms/djangoapps/instructor_task/tests/test_tasks.py b/lms/djangoapps/instructor_task/tests/test_tasks.py
index 87a618870e..471a1e811a 100644
--- a/lms/djangoapps/instructor_task/tests/test_tasks.py
+++ b/lms/djangoapps/instructor_task/tests/test_tasks.py
@@ -433,7 +433,7 @@ class TestRescoreInstructorTask(TestInstructorTasks):
entry = InstructorTask.objects.get(id=task_entry.id)
output = json.loads(entry.task_output)
self.assertEquals(output['exception'], "UpdateProblemModuleStateError")
- self.assertEquals(output['message'], "Specified module {0} of type {1} does not support rescoring.".format(
+ self.assertEquals(output['message'], u"Specified module {0} of type {1} does not support rescoring.".format(
self.location,
mock_instance.__class__,
))
diff --git a/lms/djangoapps/instructor_task/tests/test_tasks_helper.py b/lms/djangoapps/instructor_task/tests/test_tasks_helper.py
index 858ed24245..cf2b660f23 100644
--- a/lms/djangoapps/instructor_task/tests/test_tasks_helper.py
+++ b/lms/djangoapps/instructor_task/tests/test_tasks_helper.py
@@ -1079,10 +1079,10 @@ class TestProblemReportSplitTestContent(TestReportMixin, TestConditionalContent,
self.course = CourseFactory.create(
grading_policy={
"GRADER": [{
- "type": "Homework %d" % i,
+ "type": u"Homework %d" % i,
"min_count": 1,
"drop_count": 0,
- "short_label": "HW %d" % i,
+ "short_label": u"HW %d" % i,
"weight": 1.0
} for i in xrange(1, grader_num)]
}
@@ -1097,10 +1097,10 @@ class TestProblemReportSplitTestContent(TestReportMixin, TestConditionalContent,
problem_vertical_list = []
for i in xrange(1, grader_num):
- chapter_name = 'Chapter %d' % i
- problem_section_name = 'Problem section %d' % i
- problem_section_format = 'Homework %d' % i
- problem_vertical_name = 'Problem Unit %d' % i
+ chapter_name = u'Chapter %d' % i
+ problem_section_name = u'Problem section %d' % i
+ problem_section_format = u'Homework %d' % i
+ problem_vertical_name = u'Problem Unit %d' % i
chapter = ItemFactory.create(parent_location=self.course.location,
display_name=chapter_name)
@@ -1124,7 +1124,7 @@ class TestProblemReportSplitTestContent(TestReportMixin, TestConditionalContent,
for i in xrange(1, grader_num):
problem_url = 'test_problem_%d' % i
self.define_option_problem(problem_url, parent=problem_vertical_list[i - 1])
- title = 'Homework %d 1: Problem section %d - %s' % (i, i, problem_url)
+ title = u'Homework %d 1: Problem section %d - %s' % (i, i, problem_url)
problem_names.append(title)
header_row = [u'Student ID', u'Email', u'Username', u'Enrollment Status', u'Grade']
diff --git a/lms/djangoapps/instructor_task/tests/test_views.py b/lms/djangoapps/instructor_task/tests/test_views.py
index c1fa1ece19..137a705f9b 100644
--- a/lms/djangoapps/instructor_task/tests/test_views.py
+++ b/lms/djangoapps/instructor_task/tests/test_views.py
@@ -366,7 +366,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase):
def test_get_info_for_broken_output(self):
# check for non-JSON task_output
instructor_task = self._create_success_entry()
- instructor_task.task_output = "{ bad"
+ instructor_task.task_output = u"{ bad"
succeeded, message = get_task_completion_info(instructor_task)
self.assertFalse(succeeded)
self.assertEquals(message, "No parsable status information available")
@@ -382,7 +382,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase):
def test_get_info_for_broken_input(self):
# check for non-JSON task_input, but then just ignore it
instructor_task = self._create_success_entry()
- instructor_task.task_input = "{ bad"
+ instructor_task.task_input = u"{ bad"
succeeded, message = get_task_completion_info(instructor_task)
self.assertFalse(succeeded)
self.assertEquals(message, "Status: rescored 2 of 3 (out of 5)")
diff --git a/lms/djangoapps/instructor_task/views.py b/lms/djangoapps/instructor_task/views.py
index f272651f65..36e10d4618 100644
--- a/lms/djangoapps/instructor_task/views.py
+++ b/lms/djangoapps/instructor_task/views.py
@@ -106,13 +106,13 @@ def get_task_completion_info(instructor_task):
# we're more surprised if there is no output for a completed task, but just warn:
if instructor_task.task_output is None:
- log.warning(_("No task_output information found for instructor_task {0}").format(instructor_task.task_id))
+ log.warning(_(u"No task_output information found for instructor_task {0}").format(instructor_task.task_id))
return (succeeded, _("No status information available"))
try:
task_output = json.loads(instructor_task.task_output)
except ValueError:
- fmt = _("No parsable task_output information found for instructor_task {0}: {1}")
+ fmt = _(u"No parsable task_output information found for instructor_task {0}: {1}")
log.warning(fmt.format(instructor_task.task_id, instructor_task.task_output))
return (succeeded, _("No parsable status information available"))
@@ -120,7 +120,7 @@ def get_task_completion_info(instructor_task):
return (succeeded, task_output.get('message', _('No message provided')))
if any([key not in task_output for key in ['action_name', 'attempted', 'total']]):
- fmt = _("Invalid task_output information found for instructor_task {0}: {1}")
+ fmt = _(u"Invalid task_output information found for instructor_task {0}: {1}")
log.warning(fmt.format(instructor_task.task_id, instructor_task.task_output))
return (succeeded, _("No progress status information available"))
@@ -141,7 +141,7 @@ def get_task_completion_info(instructor_task):
try:
task_input = json.loads(instructor_task.task_input)
except ValueError:
- fmt = _("No parsable task_input information found for instructor_task {0}: {1}")
+ fmt = _(u"No parsable task_input information found for instructor_task {0}: {1}")
log.warning(fmt.format(instructor_task.task_id, instructor_task.task_input))
else:
student = task_input.get('student')
@@ -152,72 +152,72 @@ def get_task_completion_info(instructor_task):
if instructor_task.task_state == PROGRESS:
# special message for providing progress updates:
# Translators: {action} is a past-tense verb that is localized separately. {attempted} and {succeeded} are counts.
- msg_format = _("Progress: {action} {succeeded} of {attempted} so far")
+ msg_format = _(u"Progress: {action} {succeeded} of {attempted} so far")
elif student is not None and problem_url is not None:
# this reports on actions on problems for a particular student:
if num_attempted == 0:
# Translators: {action} is a past-tense verb that is localized separately. {student} is a student identifier.
- msg_format = _("Unable to find submission to be {action} for student '{student}'")
+ msg_format = _(u"Unable to find submission to be {action} for student '{student}'")
elif num_succeeded == 0:
# Translators: {action} is a past-tense verb that is localized separately. {student} is a student identifier.
- msg_format = _("Problem failed to be {action} for student '{student}'")
+ msg_format = _(u"Problem failed to be {action} for student '{student}'")
else:
succeeded = True
# Translators: {action} is a past-tense verb that is localized separately. {student} is a student identifier.
- msg_format = _("Problem successfully {action} for student '{student}'")
+ msg_format = _(u"Problem successfully {action} for student '{student}'")
elif student is not None and entrance_exam_url is not None:
# this reports on actions on entrance exam for a particular student:
if num_attempted == 0:
# Translators: {action} is a past-tense verb that is localized separately.
# {student} is a student identifier.
- msg_format = _("Unable to find entrance exam submission to be {action} for student '{student}'")
+ msg_format = _(u"Unable to find entrance exam submission to be {action} for student '{student}'")
else:
succeeded = True
# Translators: {action} is a past-tense verb that is localized separately.
# {student} is a student identifier.
- msg_format = _("Entrance exam successfully {action} for student '{student}'")
+ msg_format = _(u"Entrance exam successfully {action} for student '{student}'")
elif student is None and problem_url is not None:
# this reports on actions on problems for all students:
if num_attempted == 0:
# Translators: {action} is a past-tense verb that is localized separately.
- msg_format = _("Unable to find any students with submissions to be {action}")
+ msg_format = _(u"Unable to find any students with submissions to be {action}")
elif num_succeeded == 0:
# Translators: {action} is a past-tense verb that is localized separately. {attempted} is a count.
- msg_format = _("Problem failed to be {action} for any of {attempted} students")
+ msg_format = _(u"Problem failed to be {action} for any of {attempted} students")
elif num_succeeded == num_attempted:
succeeded = True
# Translators: {action} is a past-tense verb that is localized separately. {attempted} is a count.
- msg_format = _("Problem successfully {action} for {attempted} students")
+ msg_format = _(u"Problem successfully {action} for {attempted} students")
else: # num_succeeded < num_attempted
# Translators: {action} is a past-tense verb that is localized separately. {succeeded} and {attempted} are counts.
- msg_format = _("Problem {action} for {succeeded} of {attempted} students")
+ msg_format = _(u"Problem {action} for {succeeded} of {attempted} students")
elif email_id is not None:
# this reports on actions on bulk emails
if num_attempted == 0:
# Translators: {action} is a past-tense verb that is localized separately.
- msg_format = _("Unable to find any recipients to be {action}")
+ msg_format = _(u"Unable to find any recipients to be {action}")
elif num_succeeded == 0:
# Translators: {action} is a past-tense verb that is localized separately. {attempted} is a count.
- msg_format = _("Message failed to be {action} for any of {attempted} recipients ")
+ msg_format = _(u"Message failed to be {action} for any of {attempted} recipients ")
elif num_succeeded == num_attempted:
succeeded = True
# Translators: {action} is a past-tense verb that is localized separately. {attempted} is a count.
- msg_format = _("Message successfully {action} for {attempted} recipients")
+ msg_format = _(u"Message successfully {action} for {attempted} recipients")
else: # num_succeeded < num_attempted
# Translators: {action} is a past-tense verb that is localized separately. {succeeded} and {attempted} are counts.
- msg_format = _("Message {action} for {succeeded} of {attempted} recipients")
+ msg_format = _(u"Message {action} for {succeeded} of {attempted} recipients")
else:
# provide a default:
# Translators: {action} is a past-tense verb that is localized separately. {succeeded} and {attempted} are counts.
- msg_format = _("Status: {action} {succeeded} of {attempted}")
+ msg_format = _(u"Status: {action} {succeeded} of {attempted}")
if num_skipped > 0:
# Translators: {skipped} is a count. This message is appended to task progress status messages.
- msg_format += _(" (skipping {skipped})")
+ msg_format += _(u" (skipping {skipped})")
if student is None and num_attempted != num_total:
# Translators: {total} is a count. This message is appended to task progress status messages.
- msg_format += _(" (out of {total})")
+ msg_format += _(u" (out of {total})")
# Update status in task result object itself:
message = msg_format.format(
diff --git a/lms/djangoapps/learner_dashboard/tests/test_programs.py b/lms/djangoapps/learner_dashboard/tests/test_programs.py
index 634b5cbaeb..78c741e863 100644
--- a/lms/djangoapps/learner_dashboard/tests/test_programs.py
+++ b/lms/djangoapps/learner_dashboard/tests/test_programs.py
@@ -36,7 +36,7 @@ def load_serialized_data(response, key):
"""
Extract and deserialize serialized data from the response.
"""
- pattern = re.compile(r'{key}: (?P\[.*\])'.format(key=key))
+ pattern = re.compile(ur'{key}: (?P\[.*\])'.format(key=key))
match = pattern.search(response.content)
serialized = match.group('data')
@@ -215,7 +215,7 @@ class TestProgramDetails(ProgramsApiConfigMixin, CatalogIntegrationMixin, Shared
self.assertContains(response, 'programData')
self.assertContains(response, 'urls')
self.assertContains(response,
- '"program_record_url": "{}/records/programs/'.format(CREDENTIALS_PUBLIC_SERVICE_URL))
+ u'"program_record_url": "{}/records/programs/'.format(CREDENTIALS_PUBLIC_SERVICE_URL))
self.assertContains(response, 'program_listing_url')
self.assertContains(response, self.program_data['title'])
self.assert_programs_tab_present(response)
diff --git a/lms/djangoapps/lms_xblock/mixin.py b/lms/djangoapps/lms_xblock/mixin.py
index 9eb4942376..4c415eab0d 100644
--- a/lms/djangoapps/lms_xblock/mixin.py
+++ b/lms/djangoapps/lms_xblock/mixin.py
@@ -155,7 +155,7 @@ class LmsBlockMixin(XBlockMixin):
if user_partition.id == user_partition_id:
return user_partition
- raise NoSuchUserPartitionError("could not find a UserPartition with ID [{}]".format(user_partition_id))
+ raise NoSuchUserPartitionError(u"could not find a UserPartition with ID [{}]".format(user_partition_id))
def _has_nonsensical_access_settings(self):
"""
diff --git a/lms/djangoapps/lms_xblock/runtime.py b/lms/djangoapps/lms_xblock/runtime.py
index d25516995b..8cb9f240d3 100644
--- a/lms/djangoapps/lms_xblock/runtime.py
+++ b/lms/djangoapps/lms_xblock/runtime.py
@@ -35,7 +35,7 @@ def handler_url(block, handler_name, suffix='', query='', thirdparty=False):
# to ask for handler URLs without a student context.
func = getattr(block.__class__, handler_name, None)
if not func:
- raise ValueError("{!r} is not a function name".format(handler_name))
+ raise ValueError(u"{!r} is not a function name".format(handler_name))
# Is the following necessary? ProxyAttribute causes an UndefinedContext error
# if trying this without the module system.
@@ -104,7 +104,7 @@ class UserTagsService(object):
key: the key for the value we want
"""
if scope != user_course_tag_api.COURSE_SCOPE:
- raise ValueError("unexpected scope {0}".format(scope))
+ raise ValueError(u"unexpected scope {0}".format(scope))
return user_course_tag_api.get_course_tag(
self._get_current_user(),
@@ -120,7 +120,7 @@ class UserTagsService(object):
value: the value to set
"""
if scope != user_course_tag_api.COURSE_SCOPE:
- raise ValueError("unexpected scope {0}".format(scope))
+ raise ValueError(u"unexpected scope {0}".format(scope))
return user_course_tag_api.set_course_tag(
self._get_current_user(),
diff --git a/lms/djangoapps/lti_provider/outcomes.py b/lms/djangoapps/lti_provider/outcomes.py
index a69fede350..892dac39a6 100644
--- a/lms/djangoapps/lti_provider/outcomes.py
+++ b/lms/djangoapps/lti_provider/outcomes.py
@@ -37,9 +37,9 @@ def store_outcome_parameters(request_params, user, lti_consumer):
# to figure out the result service URL. As it stands, though, this
# is a badly-formed LTI request
log.warn(
- "Outcome Service: lis_outcome_service_url parameter missing "
- "from scored assignment; we will be unable to return a score. "
- "Request parameters: %s",
+ u"Outcome Service: lis_outcome_service_url parameter missing "
+ u"from scored assignment; we will be unable to return a score. "
+ u"Request parameters: %s",
request_params
)
return
@@ -140,8 +140,8 @@ def send_score_update(assignment, score):
# necessary.
if not (response and check_replace_result_response(response)):
log.error(
- "Outcome Service: Failed to update score on LTI consumer. "
- "User: %s, course: %s, usage: %s, score: %s, status: %s, body: %s",
+ u"Outcome Service: Failed to update score on LTI consumer. "
+ u"User: %s, course: %s, usage: %s, score: %s, status: %s, body: %s",
assignment.user,
assignment.course_key,
assignment.usage_key,
@@ -190,7 +190,7 @@ def check_replace_result_response(response):
# Pylint doesn't recognize members in the LXML module
if response.status_code != 200:
log.error(
- "Outcome service response: Unexpected status code %s",
+ u"Outcome service response: Unexpected status code %s",
response.status_code
)
return False
@@ -199,7 +199,7 @@ def check_replace_result_response(response):
xml = response.content
root = etree.fromstring(xml)
except etree.ParseError as ex:
- log.error("Outcome service response: Failed to parse XML: %s\n %s", ex, xml)
+ log.error(u"Outcome service response: Failed to parse XML: %s\n %s", ex, xml)
return False
major_codes = root.xpath(
@@ -207,14 +207,14 @@ def check_replace_result_response(response):
namespaces={'ns': 'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0'})
if len(major_codes) != 1:
log.error(
- "Outcome service response: Expected exactly one imsx_codeMajor field in response. Received %s",
+ u"Outcome service response: Expected exactly one imsx_codeMajor field in response. Received %s",
major_codes
)
return False
if major_codes[0].text != 'success':
log.error(
- "Outcome service response: Unexpected major code: %s.",
+ u"Outcome service response: Unexpected major code: %s.",
major_codes[0].text
)
return False
diff --git a/lms/djangoapps/lti_provider/signals.py b/lms/djangoapps/lti_provider/signals.py
index ff7eaceb19..f6975fb589 100644
--- a/lms/djangoapps/lti_provider/signals.py
+++ b/lms/djangoapps/lti_provider/signals.py
@@ -62,7 +62,7 @@ def score_changed_handler(sender, **kwargs): # pylint: disable=unused-argument
)
else:
log.error(
- "Outcome Service: Required signal parameter is None. "
+ u"Outcome Service: Required signal parameter is None. "
"points_possible: %s, points_earned: %s, user_id: %s, "
"course_id: %s, usage_id: %s",
points_possible, points_earned, user_id, course_id, usage_id
diff --git a/lms/djangoapps/lti_provider/tasks.py b/lms/djangoapps/lti_provider/tasks.py
index 6839ef154f..d0a4ef61bc 100644
--- a/lms/djangoapps/lti_provider/tasks.py
+++ b/lms/djangoapps/lti_provider/tasks.py
@@ -45,7 +45,7 @@ def send_composite_outcome(user_id, course_id, assignment_id, version):
assignment = GradedAssignment.objects.get(id=assignment_id)
if version != assignment.version_number:
log.info(
- "Score passback for GradedAssignment %s skipped. More recent score available.",
+ u"Score passback for GradedAssignment %s skipped. More recent score available.",
assignment.id
)
return
diff --git a/lms/djangoapps/lti_provider/tests/test_outcomes.py b/lms/djangoapps/lti_provider/tests/test_outcomes.py
index 88dae5d598..0d8b998038 100644
--- a/lms/djangoapps/lti_provider/tests/test_outcomes.py
+++ b/lms/djangoapps/lti_provider/tests/test_outcomes.py
@@ -187,7 +187,7 @@ class XmlHandlingTest(TestCase):
"""
shard = 4
- response_xml = """
+ response_xml = u"""
{msg}
'.format(msg=msg) + return HTML(u'{msg}
').format(msg=msg) CARDTYPE_MAP = defaultdict(lambda: "UNKNOWN") @@ -664,7 +665,7 @@ REASONCODE_MAP.update( """)), '233': _('General decline by the processor. Possible action: retry with another form of payment.'), '234': _( - "There is a problem with the information in your CyberSource account. Please let us know at {0}" + u"There is a problem with the information in your CyberSource account. Please let us know at {0}" ).format(settings.PAYMENT_SUPPORT_EMAIL), '235': _('The requested capture amount exceeds the originally authorized amount.'), '236': _('Processor Failure. Possible action: retry the payment'), diff --git a/lms/djangoapps/shoppingcart/processors/tests/test_CyberSource2.py b/lms/djangoapps/shoppingcart/processors/tests/test_CyberSource2.py index 5f07ebddfd..c3b7738036 100644 --- a/lms/djangoapps/shoppingcart/processors/tests/test_CyberSource2.py +++ b/lms/djangoapps/shoppingcart/processors/tests/test_CyberSource2.py @@ -80,7 +80,7 @@ class CyberSource2Test(TestCase): # Parameters determined by the order model self.assertEqual(params['amount'], '10.00') self.assertEqual(params['currency'], 'usd') - self.assertEqual(params['orderNumber'], 'OrderId: {order_id}'.format(order_id=self.order.id)) + self.assertEqual(params['orderNumber'], u'OrderId: {order_id}'.format(order_id=self.order.id)) self.assertEqual(params['reference_number'], self.order.id) # Parameters determined by the Django (test) settings @@ -149,7 +149,7 @@ class CyberSource2Test(TestCase): # Expect that we processed the payment successfully self.assertTrue( result['success'], - msg="Payment was not successful: {error}".format(error=result.get('error_html')) + msg=u"Payment was not successful: {error}".format(error=result.get('error_html')) ) self.assertEqual(result['error_html'], '') @@ -232,7 +232,7 @@ class CyberSource2Test(TestCase): # Expect that we processed the payment successfully self.assertTrue( result['success'], - msg="Payment was not successful: {error}".format(error=result.get('error_html')) + msg=u"Payment was not successful: {error}".format(error=result.get('error_html')) ) self.assertEqual(result['error_html'], '') self.assert_dump_recorded(result['order']) diff --git a/lms/djangoapps/shoppingcart/tests/test_pdf.py b/lms/djangoapps/shoppingcart/tests/test_pdf.py index fb03bcf619..4f044d1236 100644 --- a/lms/djangoapps/shoppingcart/tests/test_pdf.py +++ b/lms/djangoapps/shoppingcart/tests/test_pdf.py @@ -59,7 +59,7 @@ class TestPdfFile(unittest.TestCase): return the dictionary with the dummy data """ return { - 'item_description': 'Course %s Description' % index, + 'item_description': u'Course %s Description' % index, 'quantity': index, 'list_price': 10, 'discount': discount, diff --git a/lms/djangoapps/shoppingcart/tests/test_reports.py b/lms/djangoapps/shoppingcart/tests/test_reports.py index a53150b284..995e39ef4f 100644 --- a/lms/djangoapps/shoppingcart/tests/test_reports.py +++ b/lms/djangoapps/shoppingcart/tests/test_reports.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - """ Tests for the Shopping Cart Models """ @@ -242,7 +241,7 @@ class ItemizedPurchaseReportTest(ModuleStoreTestCase): """ # delete the matching annotation self.annotation.delete() - self.assertEqual(u"", self.reg.csv_report_comments) + self.assertEqual("", self.reg.csv_report_comments) def test_paidcourseregistrationannotation_unicode(self): """ diff --git a/lms/djangoapps/shoppingcart/tests/test_views.py b/lms/djangoapps/shoppingcart/tests/test_views.py index 7d478eddde..23b480b0c1 100644 --- a/lms/djangoapps/shoppingcart/tests/test_views.py +++ b/lms/djangoapps/shoppingcart/tests/test_views.py @@ -288,7 +288,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.login_user() resp = self.client.post(reverse('add_course_to_cart', args=[text_type(self.course_key)])) self.assertEqual(resp.status_code, 400) - self.assertIn('The course {0} is already in your cart.'.format(text_type(self.course_key)), resp.content) + self.assertIn(u'The course {0} is already in your cart.'.format(text_type(self.course_key)), resp.content) def test_course_discount_invalid_coupon(self): self.add_coupon(self.course_key, True, self.coupon_code) @@ -296,7 +296,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): non_existing_code = "non_existing_code" resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': non_existing_code}) self.assertEqual(resp.status_code, 404) - self.assertIn("Discount does not exist against code '{0}'.".format(non_existing_code), resp.content) + self.assertIn(u"Discount does not exist against code '{0}'.".format(non_existing_code), resp.content) def test_valid_qty_greater_then_one_and_purchase_type_should_business(self): qty = 2 @@ -418,14 +418,14 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): non_existing_code = "non_existing_code" resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': non_existing_code}) self.assertEqual(resp.status_code, 404) - self.assertIn("Discount does not exist against code '{0}'.".format(non_existing_code), resp.content) + self.assertIn(u"Discount does not exist against code '{0}'.".format(non_existing_code), resp.content) def test_course_discount_inactive_coupon(self): self.add_coupon(self.course_key, False, self.coupon_code) self.add_course_to_user_cart(self.course_key) resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.coupon_code}) self.assertEqual(resp.status_code, 404) - self.assertIn("Discount does not exist against code '{0}'.".format(self.coupon_code), resp.content) + self.assertIn(u"Discount does not exist against code '{0}'.".format(self.coupon_code), resp.content) def test_course_does_not_exist_in_cart_against_valid_coupon(self): course_key = text_type(self.course_key) + 'testing' @@ -434,7 +434,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.coupon_code}) self.assertEqual(resp.status_code, 404) - self.assertIn("Discount does not exist against code '{0}'.".format(self.coupon_code), resp.content) + self.assertIn(u"Discount does not exist against code '{0}'.".format(self.coupon_code), resp.content) def test_inactive_registration_code_returns_error(self): """ @@ -450,7 +450,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.reg_code}) self.assertEqual(resp.status_code, 400) self.assertIn( - "This enrollment code ({enrollment_code}) is no longer valid.".format( + u"This enrollment code ({enrollment_code}) is no longer valid.".format( enrollment_code=self.reg_code), resp.content) def test_course_does_not_exist_in_cart_against_valid_reg_code(self): @@ -460,7 +460,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.reg_code}) self.assertEqual(resp.status_code, 404) - self.assertIn("Code '{0}' is not valid for any course in the shopping cart.".format(self.reg_code), resp.content) + self.assertIn(u"Code '{0}' is not valid for any course in the shopping cart.".format(self.reg_code), resp.content) def test_cart_item_qty_greater_than_1_against_valid_reg_code(self): course_key = text_type(self.course_key) @@ -611,7 +611,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): # the item has been removed when using the registration code for the first time resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.reg_code}) self.assertEqual(resp.status_code, 400) - self.assertIn("This enrollment code ({enrollment_code}) is not valid.".format( + self.assertIn(u"This enrollment code ({enrollment_code}) is not valid.".format( enrollment_code=self.reg_code ), resp.content) @@ -649,7 +649,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): resp = self.client.post(reverse('shoppingcart.views.remove_item', args=[]), {'id': reg_item.id}) debug_log.assert_called_with( - 'Code redemption does not exist for order item id=%s.', + u'Code redemption does not exist for order item id=%s.', str(reg_item.id) ) @@ -671,7 +671,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.assertEqual(resp.status_code, 200) self.assertEquals(self.cart.orderitem_set.count(), 0) info_log.assert_called_with( - 'Coupon "%s" redemption entry removed for user "%s" for order item "%s"', + u'Coupon "%s" redemption entry removed for user "%s" for order item "%s"', self.coupon_code, self.user, str(reg_item.id) @@ -690,7 +690,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.assertEqual(resp.status_code, 200) info_log.assert_called_with( - 'Coupon redemption entry removed for user %s for order %s', + u'Coupon redemption entry removed for user %s for order %s', self.user, reg_item.id ) @@ -724,7 +724,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.assertEqual(resp.status_code, 200) self.assertEquals(self.cart.orderitem_set.count(), 1) info_log.assert_called_with( - 'Coupon "%s" redemption entry removed for user "%s" for order item "%s"', + 'Coupon "%s" redemption entry removed for user "%s" for order item "%s"', # pylint: disable=unicode-format-string,line-too-long self.coupon_code, self.user, str(reg_item.id) @@ -743,7 +743,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.assertEqual(resp.status_code, 200) self.assertEquals(self.cart.orderitem_set.count(), 1) - info_log.assert_called_with("order item %s removed for user %s", str(cert_item.id), self.user) + info_log.assert_called_with(u"order item %s removed for user %s", str(cert_item.id), self.user) @patch('shoppingcart.views.log.info') def test_remove_coupon_redemption_on_clear_cart(self, info_log): @@ -761,7 +761,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.assertEquals(self.cart.orderitem_set.count(), 0) info_log.assert_called_with( - 'Coupon redemption entry removed for user %s for order %s', + u'Coupon redemption entry removed for user %s for order %s', self.user, reg_item.id ) @@ -771,7 +771,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.login_user() resp = self.client.post(reverse('add_course_to_cart', args=[text_type(self.course_key)])) self.assertEqual(resp.status_code, 400) - self.assertIn('You are already registered in course {0}.'.format(text_type(self.course_key)), resp.content) + self.assertIn(u'You are already registered in course {0}.'.format(text_type(self.course_key)), resp.content) def test_add_nonexistent_course_to_cart(self): self.login_user() @@ -864,7 +864,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): {'id': cert_item.id}) self.assertEqual(resp2.status_code, 200) exception_log.assert_called_with( - 'Cannot remove cart OrderItem id=%s. DoesNotExist or item is already purchased', str(cert_item.id) + u'Cannot remove cart OrderItem id=%s. DoesNotExist or item is already purchased', str(cert_item.id) ) resp3 = self.client.post( @@ -873,7 +873,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): ) self.assertEqual(resp3.status_code, 200) exception_log.assert_called_with( - 'Cannot remove cart OrderItem id=%s. DoesNotExist or item is already purchased', + u'Cannot remove cart OrderItem id=%s. DoesNotExist or item is already purchased', '-1' ) @@ -936,7 +936,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): 'unit_cost': 40, 'quantity': 1, 'line_cost': 40, - 'line_desc': '{} for course Test Course'.format(self.verified_course_mode.mode_display_name), + 'line_desc': u'{} for course Test Course'.format(self.verified_course_mode.mode_display_name), 'course_key': unicode(self.verified_course_key) }) @@ -1004,7 +1004,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): 'unit_cost': 40, 'quantity': 1, 'line_cost': 40, - 'line_desc': '{} for course Test Course'.format(self.verified_course_mode.mode_display_name), + 'line_desc': u'{} for course Test Course'.format(self.verified_course_mode.mode_display_name), 'course_key': unicode(self.verified_course_key) }) @@ -1266,14 +1266,17 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.assertFalse(context['reg_code_info_list'][0]['is_redeemed']) self.assertFalse(context['reg_code_info_list'][1]['is_redeemed']) - self.assertIn(self.cart.purchase_time.strftime("%B %d, %Y"), resp.content) + self.assertIn(self.cart.purchase_time.strftime(u"%B %d, %Y"), resp.content) self.assertIn(self.cart.company_name, resp.content) self.assertIn(self.cart.company_contact_name, resp.content) self.assertIn(self.cart.company_contact_email, resp.content) self.assertIn(self.cart.recipient_email, resp.content) - self.assertIn("Invoice #{order_id}".format(order_id=self.cart.id), resp.content) - self.assertIn('You have successfully purchased {total_registration_codes} course registration codes' - .format(total_registration_codes=context['total_registration_codes']), resp.content) + self.assertIn(u"Invoice #{order_id}".format(order_id=self.cart.id), resp.content.decode(resp.charset)) + codes_string = u'You have successfully purchased {total_registration_codes} course registration codes' + self.assertIn(codes_string.format( + total_registration_codes=context['total_registration_codes']), + resp.content.decode(resp.charset) + ) # now redeem one of registration code from the previous order redeem_url = reverse('register_code_redemption', args=[context['reg_code_info_list'][0]['code']]) @@ -1638,7 +1641,9 @@ class ShoppingcartViewsClosedEnrollment(ModuleStoreTestCase): # coupon redemption entry should also be deleted when the item is expired. resp = self.client.get(reverse('shoppingcart.views.show_cart', args=[])) self.assertEqual(resp.status_code, 200) - self.assertIn("{course_name} has been removed because the enrollment period has closed.".format(course_name=self.testing_course.display_name), resp.content) + self.assertIn(u"{course_name} has been removed because the enrollment period has closed.".format( + course_name=self.testing_course.display_name), resp.content.decode(resp.charset) + ) # now the redemption entry should be deleted from the table. coupon_redemption = CouponRedemption.objects.filter(coupon__course_id=expired_course_item.course_id, @@ -1678,7 +1683,12 @@ class ShoppingcartViewsClosedEnrollment(ModuleStoreTestCase): resp = self.client.get(reverse('shoppingcart.views.show_cart', args=[])) self.assertEqual(resp.status_code, 200) - self.assertIn("{course_name} has been removed because the enrollment period has closed.".format(course_name=self.testing_course.display_name), resp.content) + self.assertIn( + u"{course_name} has been removed because the enrollment period has closed.".format( + course_name=self.testing_course.display_name + ), + resp.content.decode(resp.charset) + ) self.assertIn('40.00', resp.content) def test_is_enrollment_closed_when_order_type_is_business(self): @@ -1701,7 +1711,12 @@ class ShoppingcartViewsClosedEnrollment(ModuleStoreTestCase): # so we delete that item from the cart and display the message in the cart resp = self.client.get(reverse('shoppingcart.views.show_cart', args=[])) self.assertEqual(resp.status_code, 200) - self.assertIn("{course_name} has been removed because the enrollment period has closed.".format(course_name=self.testing_course.display_name), resp.content) + self.assertIn( + u"{course_name} has been removed because the enrollment period has closed.".format( + course_name=self.testing_course.display_name + ), + resp.content.decode(resp.charset) + ) self.assertIn('40.00', resp.content) diff --git a/lms/djangoapps/shoppingcart/views.py b/lms/djangoapps/shoppingcart/views.py index 5f22048649..afeaff1d2c 100644 --- a/lms/djangoapps/shoppingcart/views.py +++ b/lms/djangoapps/shoppingcart/views.py @@ -117,10 +117,10 @@ def add_course_to_cart(request, course_id): except CourseDoesNotExistException: return HttpResponseNotFound(_('The course you requested does not exist.')) except ItemAlreadyInCartException: - return HttpResponseBadRequest(_('The course {course_id} is already in your cart.').format(course_id=course_id)) + return HttpResponseBadRequest(_(u'The course {course_id} is already in your cart.').format(course_id=course_id)) except AlreadyEnrolledInCourseException: return HttpResponseBadRequest( - _('You are already registered in course {course_id}.').format(course_id=course_id)) + _(u'You are already registered in course {course_id}.').format(course_id=course_id)) else: # in case a coupon redemption code has been applied, new items should also get a discount if applicable. order = paid_course_item.order @@ -293,7 +293,7 @@ def use_code(request): try: course_reg = CourseRegistrationCode.objects.get(code=code) except CourseRegistrationCode.DoesNotExist: - return HttpResponseNotFound(_("Discount does not exist against code '{code}'.").format(code=code)) + return HttpResponseNotFound(_(u"Discount does not exist against code '{code}'.").format(code=code)) return use_registration_code(course_reg, request.user) @@ -318,7 +318,7 @@ def get_reg_code_validity(registration_code, request, limiter): reg_code_already_redeemed = RegistrationCodeRedemption.is_registration_code_redeemed(registration_code) if not reg_code_is_valid: # tick the rate limiter counter - AUDIT_LOG.info("Redemption of a invalid RegistrationCode %s", registration_code) + AUDIT_LOG.info(u"Redemption of a invalid RegistrationCode %s", registration_code) limiter.tick_bad_request_counter(request) raise Http404() @@ -465,7 +465,7 @@ def use_registration_code(course_reg, user): if not course_reg.is_valid: log.warning(u"The enrollment code (%s) is no longer valid.", course_reg.code) return HttpResponseBadRequest( - _("This enrollment code ({enrollment_code}) is no longer valid.").format( + _(u"This enrollment code ({enrollment_code}) is no longer valid.").format( enrollment_code=course_reg.code ) ) @@ -473,7 +473,7 @@ def use_registration_code(course_reg, user): if RegistrationCodeRedemption.is_registration_code_redeemed(course_reg.code): log.warning(u"This enrollment code ({%s}) has already been used.", course_reg.code) return HttpResponseBadRequest( - _("This enrollment code ({enrollment_code}) is not valid.").format( + _(u"This enrollment code ({enrollment_code}) is not valid.").format( enrollment_code=course_reg.code ) ) @@ -483,7 +483,7 @@ def use_registration_code(course_reg, user): except ItemNotFoundInCartException: log.warning(u"Course item does not exist against registration code '%s'", course_reg.code) return HttpResponseNotFound( - _("Code '{registration_code}' is not valid for any course in the shopping cart.").format( + _(u"Code '{registration_code}' is not valid for any course in the shopping cart.").format( registration_code=course_reg.code ) ) @@ -521,7 +521,7 @@ def use_coupon_code(coupons, user): if not is_redemption_applied: log.warning(u"Discount does not exist against code '%s'.", coupons[0].code) - return HttpResponseNotFound(_("Discount does not exist against code '{code}'.").format(code=coupons[0].code)) + return HttpResponseNotFound(_(u"Discount does not exist against code '{code}'.").format(code=coupons[0].code)) return HttpResponse( json.dumps({'response': 'success', 'coupon_code_applied': True}), @@ -950,7 +950,7 @@ def _show_receipt_html(request, order): 'currency': settings.PAID_COURSE_REGISTRATION_CURRENCY[0], 'total_registration_codes': total_registration_codes, 'reg_code_info_list': reg_code_info_list, - 'order_purchase_date': order.purchase_time.strftime("%B %d, %Y"), + 'order_purchase_date': order.purchase_time.strftime(u"%B %d, %Y"), } # We want to have the ability to override the default receipt page when @@ -1022,8 +1022,8 @@ def csv_report(request): items = report.rows() response = HttpResponse(content_type='text/csv') - filename = "purchases_report_{}.csv".format(datetime.datetime.now(pytz.UTC).strftime("%Y-%m-%d-%H-%M-%S")) - response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) + filename = u"purchases_report_{}.csv".format(datetime.datetime.now(pytz.UTC).strftime(u"%Y-%m-%d-%H-%M-%S")) + response['Content-Disposition'] = u'attachment; filename="{}"'.format(filename) report.write_csv(response) return response diff --git a/lms/djangoapps/static_template_view/tests/test_views.py b/lms/djangoapps/static_template_view/tests/test_views.py index ed8f00e488..f4c998a79d 100644 --- a/lms/djangoapps/static_template_view/tests/test_views.py +++ b/lms/djangoapps/static_template_view/tests/test_views.py @@ -119,7 +119,7 @@ class MarketingSiteViewTests(TestCase): resp = self.client.get(url, HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME) self.assertContains( resp, - 'There has been a 500 error on the {platform_name} servers'.format( + u'There has been a 500 error on the {platform_name} servers'.format( platform_name=settings.MICROSITE_CONFIGURATION['test_site']['platform_name'] ), status_code=500 diff --git a/lms/djangoapps/staticbook/views.py b/lms/djangoapps/staticbook/views.py index 0ffa909563..2137a30678 100644 --- a/lms/djangoapps/staticbook/views.py +++ b/lms/djangoapps/staticbook/views.py @@ -24,7 +24,7 @@ def index(request, course_id, book_index, page=None): book_index = int(book_index) if book_index < 0 or book_index >= len(course.textbooks): - raise Http404("Invalid book index value: {0}".format(book_index)) + raise Http404(u"Invalid book index value: {0}".format(book_index)) textbook = course.textbooks[book_index] table_of_contents = textbook.table_of_contents @@ -82,7 +82,7 @@ def pdf_index(request, course_id, book_index, chapter=None, page=None): book_index = int(book_index) if book_index < 0 or book_index >= len(course.pdf_textbooks): - raise Http404("Invalid book index value: {0}".format(book_index)) + raise Http404(u"Invalid book index value: {0}".format(book_index)) textbook = course.pdf_textbooks[book_index] viewer_params = '&file=' @@ -150,7 +150,7 @@ def html_index(request, course_id, book_index, chapter=None): book_index = int(book_index) if book_index < 0 or book_index >= len(course.html_textbooks): - raise Http404("Invalid book index value: {0}".format(book_index)) + raise Http404(u"Invalid book index value: {0}".format(book_index)) textbook = course.html_textbooks[book_index] if 'url' in textbook: diff --git a/lms/djangoapps/support/tests/test_refund.py b/lms/djangoapps/support/tests/test_refund.py index 5446d3b6a9..8f47cab648 100644 --- a/lms/djangoapps/support/tests/test_refund.py +++ b/lms/djangoapps/support/tests/test_refund.py @@ -107,7 +107,7 @@ class RefundTests(ModuleStoreTestCase): def test_no_order(self): self._enroll(purchase=False) response = self.client.post('/support/refund/', self.form_pars) - self.assertContains(response, 'No order found for %s' % self.student.username) + self.assertContains(response, u'No order found for %s' % self.student.username) def test_valid_order(self): self._enroll() @@ -124,7 +124,7 @@ class RefundTests(ModuleStoreTestCase): self.assertTrue(response.status_code, 302) response = self.client.get(response.get('location')) - self.assertContains(response, "Unenrolled %s from" % self.student) + self.assertContains(response, u"Unenrolled %s from" % self.student) self.assertContains(response, "Refunded 1.00 for order id") self.assertFalse(CourseEnrollment.is_enrolled(self.student, self.course_id)) diff --git a/lms/djangoapps/support/views/refund.py b/lms/djangoapps/support/views/refund.py index 1c13e0cd31..2617c1b6bc 100644 --- a/lms/djangoapps/support/views/refund.py +++ b/lms/djangoapps/support/views/refund.py @@ -60,7 +60,7 @@ class RefundForm(forms.Form): if user and course_id: self.cleaned_data['enrollment'] = enrollment = CourseEnrollment.get_or_create_enrollment(user, course_id) if enrollment.refundable(): - msg = _("Course {course_id} not past the refund window.").format(course_id=course_id) + msg = _(u"Course {course_id} not past the refund window.").format(course_id=course_id) raise forms.ValidationError(msg) try: self.cleaned_data['cert'] = enrollment.certificateitem_set.filter( @@ -68,7 +68,7 @@ class RefundForm(forms.Form): status='purchased' )[0] except IndexError: - msg = _("No order found for {user} in course {course_id}").format(user=user, course_id=course_id) + msg = _(u"No order found for {user} in course {course_id}").format(user=user, course_id=course_id) raise forms.ValidationError(msg) return self.cleaned_data @@ -125,14 +125,14 @@ class RefundSupportView(FormView): log.info(u"%s manually refunded %s %s", self.request.user, user, course_id) messages.success( self.request, - _("Unenrolled {user} from {course_id}").format( + _(u"Unenrolled {user} from {course_id}").format( user=user, course_id=course_id ) ) messages.success( self.request, - _("Refunded {cost} for order id {order_id}").format( + _(u"Refunded {cost} for order id {order_id}").format( cost=cert.unit_cost, order_id=cert.order.id ) diff --git a/lms/djangoapps/survey/models.py b/lms/djangoapps/survey/models.py index a8fa845bdd..e7500c7878 100644 --- a/lms/djangoapps/survey/models.py +++ b/lms/djangoapps/survey/models.py @@ -11,6 +11,7 @@ from lxml import etree from model_utils.models import TimeStampedModel from opaque_keys.edx.django.models import CourseKeyField +from openedx.core.djangolib.markup import HTML from student.models import User from survey.exceptions import SurveyFormNameAlreadyExists, SurveyFormNotFound @@ -52,8 +53,8 @@ class SurveyForm(TimeStampedModel): try: fields = cls.get_field_names_from_html(html) except Exception as ex: - log.exception("Cannot parse SurveyForm html: {}".format(ex)) - raise ValidationError("Cannot parse SurveyForm as HTML: {}".format(ex)) + log.exception(u"Cannot parse SurveyForm html: {}".format(ex)) + raise ValidationError(u"Cannot parse SurveyForm as HTML: {}".format(ex)) if not len(fields): raise ValidationError("SurveyForms must contain at least one form input field") @@ -146,7 +147,7 @@ class SurveyForm(TimeStampedModel): # make sure the form is wrap in some outer single element # otherwise lxml can't parse it # NOTE: This wrapping doesn't change the ability to query it - tree = etree.fromstring(u'