diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_delete_course.py b/cms/djangoapps/contentstore/management/commands/tests/test_delete_course.py index 8d0388aa14..d5b915a7c8 100644 --- a/cms/djangoapps/contentstore/management/commands/tests/test_delete_course.py +++ b/cms/djangoapps/contentstore/management/commands/tests/test_delete_course.py @@ -40,7 +40,7 @@ class DeleteCourseTests(ModuleStoreTestCase): store = contentstore() asset_key = course_run.id.make_asset_key('asset', 'test.txt') - content = StaticContent(asset_key, 'test.txt', 'plain/text', 'test data') + content = StaticContent(asset_key, 'test.txt', 'plain/text', b'test data') store.save(content) __, asset_count = store.get_all_content_for_course(course_run.id) assert asset_count == 1 @@ -69,7 +69,7 @@ class DeleteCourseTests(ModuleStoreTestCase): store = contentstore() asset_key = course_run.id.make_asset_key('asset', 'test.txt') - content = StaticContent(asset_key, 'test.txt', 'plain/text', 'test data') + content = StaticContent(asset_key, 'test.txt', 'plain/text', b'test data') store.save(content) __, asset_count = store.get_all_content_for_course(course_run.id) assert asset_count == 1 diff --git a/common/djangoapps/student/tests/test_email.py b/common/djangoapps/student/tests/test_email.py index 25d6bc8265..76a9848b51 100644 --- a/common/djangoapps/student/tests/test_email.py +++ b/common/djangoapps/student/tests/test_email.py @@ -215,7 +215,7 @@ class ReactivationEmailTests(EmailTestMixin, CacheIsolationTestCase): Send the reactivation email to the specified user, and return the response as json data. """ - return json.loads(send_reactivation_email_for_user(user).content) + return json.loads(send_reactivation_email_for_user(user).content.decode('utf-8')) def assertReactivateEmailSent(self, email_user): """ @@ -480,7 +480,7 @@ class EmailChangeConfirmationTests(EmailTestMixin, EmailTemplateTagMixin, CacheI self.assertEqual(response.status_code, 200) self.assertEquals( mock_render_to_response(expected_template, expected_context).content, - response.content + response.content.decode('utf-8') ) def assertChangeEmailSent(self, test_body_type): diff --git a/common/djangoapps/student/tests/test_models.py b/common/djangoapps/student/tests/test_models.py index e6b7d482e8..e3d83784fd 100644 --- a/common/djangoapps/student/tests/test_models.py +++ b/common/djangoapps/student/tests/test_models.py @@ -63,7 +63,7 @@ class CourseEnrollmentTests(SharedModuleStoreTestCase): self.assertIsNone(CourseEnrollment.generate_enrollment_status_hash(AnonymousUser())) # No enrollments - expected = hashlib.md5(self.user.username).hexdigest() + expected = hashlib.md5(self.user.username.encode('utf-8')).hexdigest() self.assertEqual(CourseEnrollment.generate_enrollment_status_hash(self.user), expected) self.assert_enrollment_status_hash_cached(self.user, expected) diff --git a/common/djangoapps/student/tests/test_reset_password.py b/common/djangoapps/student/tests/test_reset_password.py index 0ca7b6f21c..76b0a4dbac 100644 --- a/common/djangoapps/student/tests/test_reset_password.py +++ b/common/djangoapps/student/tests/test_reset_password.py @@ -76,7 +76,7 @@ class ResetPasswordTests(EventTestMixin, CacheIsolationTestCase): bad_pwd_resp = password_reset(bad_pwd_req) # If they've got an unusable password, we return a successful response code self.assertEquals(bad_pwd_resp.status_code, 200) - obj = json.loads(bad_pwd_resp.content) + obj = json.loads(bad_pwd_resp.content.decode('utf-8')) self.assertEquals(obj, { 'success': True, 'value': "('registration/password_reset_done.html', [])", @@ -95,7 +95,7 @@ class ResetPasswordTests(EventTestMixin, CacheIsolationTestCase): # This prevents someone potentially trying to "brute-force" find out which # emails are and aren't registered with edX self.assertEquals(bad_email_resp.status_code, 200) - obj = json.loads(bad_email_resp.content) + obj = json.loads(bad_email_resp.content.decode('utf-8')) self.assertEquals(obj, { 'success': True, 'value': "('registration/password_reset_done.html', [])", @@ -145,7 +145,7 @@ class ResetPasswordTests(EventTestMixin, CacheIsolationTestCase): self.assertFalse(dop_models.RefreshToken.objects.filter(user=self.user).exists()) self.assertFalse(dot_models.AccessToken.objects.filter(user=self.user).exists()) self.assertFalse(dot_models.RefreshToken.objects.filter(user=self.user).exists()) - obj = json.loads(good_resp.content) + obj = json.loads(good_resp.content.decode('utf-8')) self.assertTrue(obj['success']) self.assertIn('e-mailed you instructions for setting your password', obj['value']) diff --git a/common/djangoapps/terrain/stubs/edxnotes.py b/common/djangoapps/terrain/stubs/edxnotes.py index 027fdd23ea..08c1d60d78 100644 --- a/common/djangoapps/terrain/stubs/edxnotes.py +++ b/common/djangoapps/terrain/stubs/edxnotes.py @@ -121,7 +121,7 @@ class StubEdxNotesServiceHandler(StubHttpRequestHandler): } if status_code < 400 and content: headers["Content-Type"] = "application/json" - content = json.dumps(content) + content = json.dumps(content).encode('utf-8') else: headers["Content-Type"] = "text/html" @@ -131,7 +131,7 @@ class StubEdxNotesServiceHandler(StubHttpRequestHandler): """ Create a note, assign id, annotator_schema_version, created and updated dates. """ - note = json.loads(self.request_content) + note = json.loads(self.request_content.decode('utf-8')) note.update({ "id": uuid4().hex, "annotator_schema_version": "v1.0", @@ -146,7 +146,7 @@ class StubEdxNotesServiceHandler(StubHttpRequestHandler): The same as self._create, but it works a list of notes. """ try: - notes = json.loads(self.request_content) + notes = json.loads(self.request_content.decode('utf-8')) except ValueError: self.respond(400, "Bad Request") return @@ -181,7 +181,7 @@ class StubEdxNotesServiceHandler(StubHttpRequestHandler): """ Update the note by note id. """ - note = self.server.update_note(note_id, json.loads(self.request_content)) + note = self.server.update_note(note_id, json.loads(self.request_content.decode('utf-8'))) if note: self.respond(content=note) else: diff --git a/common/djangoapps/terrain/stubs/http.py b/common/djangoapps/terrain/stubs/http.py index dfd2902ca5..1213a1ef22 100644 --- a/common/djangoapps/terrain/stubs/http.py +++ b/common/djangoapps/terrain/stubs/http.py @@ -92,7 +92,7 @@ class StubHttpRequestHandler(BaseHTTPRequestHandler, object): Retrieve the content of the request. """ try: - length = int(self.headers.getheader('content-length')) + length = int(self.headers.get('content-length')) except (TypeError, ValueError): return "" diff --git a/common/djangoapps/third_party_auth/pipeline.py b/common/djangoapps/third_party_auth/pipeline.py index 03a9691a3b..55008258b5 100644 --- a/common/djangoapps/third_party_auth/pipeline.py +++ b/common/djangoapps/third_party_auth/pipeline.py @@ -503,17 +503,17 @@ def redirect_to_custom_form(request, auth_entry, details, kwargs): if isinstance(secret_key, six.text_type): secret_key = secret_key.encode('utf-8') custom_form_url = form_info['url'] - data_str = json.dumps({ + data_bytes = json.dumps({ "auth_entry": auth_entry, "backend_name": backend_name, "provider_id": provider_id, "user_details": details, - }) - digest = hmac.new(secret_key, msg=data_str, digestmod=hashlib.sha256).digest() + }).encode('utf-8') + digest = hmac.new(secret_key, msg=data_bytes, digestmod=hashlib.sha256).digest() # Store the data in the session temporarily, then redirect to a page that will POST it to # the custom login/register page. request.session['tpa_custom_auth_entry_data'] = { - 'data': base64.b64encode(data_str), + 'data': base64.b64encode(data_bytes), 'hmac': base64.b64encode(digest), 'post_url': custom_form_url, } diff --git a/common/djangoapps/third_party_auth/tests/specs/base.py b/common/djangoapps/third_party_auth/tests/specs/base.py index a85eadcf36..c8c9d6bf86 100644 --- a/common/djangoapps/third_party_auth/tests/specs/base.py +++ b/common/djangoapps/third_party_auth/tests/specs/base.py @@ -935,7 +935,7 @@ class IntegrationTest(testutil.TestCase, test.TestCase, HelperMixin): strategy.request.POST['password'] = 'bad_' + password if success is False else password self.assert_pipeline_running(strategy.request) - payload = json.loads(login_user(strategy.request).content) + payload = json.loads(login_user(strategy.request).content.decode('utf-8')) if success is None: # Request malformed -- just one of email/password given. diff --git a/common/djangoapps/third_party_auth/tests/specs/test_google.py b/common/djangoapps/third_party_auth/tests/specs/test_google.py index db8661810e..fa6ab9beb1 100644 --- a/common/djangoapps/third_party_auth/tests/specs/test_google.py +++ b/common/djangoapps/third_party_auth/tests/specs/test_google.py @@ -78,8 +78,8 @@ class GoogleOauth2IntegrationTest(base.Oauth2IntegrationTest): response = self.client.get(response['Location']) self.assertEqual(response.status_code, 200) - self.assertIn('action="/misc/my-custom-registration-form" method="post"', response.content) - data_decoded = base64.b64decode(response.context['data']) + self.assertIn('action="/misc/my-custom-registration-form" method="post"', response.content.decode('utf-8')) + data_decoded = base64.b64decode(response.context['data']).decode('utf-8') data_parsed = json.loads(data_decoded) # The user's details get passed to the custom page as a base64 encoded query parameter: self.assertEqual(data_parsed, { @@ -96,7 +96,11 @@ class GoogleOauth2IntegrationTest(base.Oauth2IntegrationTest): }) # Check the hash that is used to confirm the user's data in the GET parameter is correct secret_key = settings.THIRD_PARTY_AUTH_CUSTOM_AUTH_FORMS['custom1']['secret_key'] - hmac_expected = hmac.new(secret_key, msg=data_decoded, digestmod=hashlib.sha256).digest() + hmac_expected = hmac.new( + secret_key.encode('utf-8'), + msg=data_decoded.encode('utf-8'), + digestmod=hashlib.sha256 + ).digest() self.assertEqual(base64.b64decode(response.context['hmac']), hmac_expected) # Now our custom registration form creates or logs in the user: diff --git a/common/djangoapps/third_party_auth/tests/test_admin.py b/common/djangoapps/third_party_auth/tests/test_admin.py index 719dc0d0e6..dd5985da44 100644 --- a/common/djangoapps/third_party_auth/tests/test_admin.py +++ b/common/djangoapps/third_party_auth/tests/test_admin.py @@ -50,7 +50,7 @@ class Oauth2ProviderConfigAdminTest(testutil.TestCase): provider1 = self.configure_dummy_provider( enabled=True, icon_class='', - icon_image=SimpleUploadedFile('icon.svg', ''), + icon_image=SimpleUploadedFile('icon.svg', b''), ) # Get the provider instance with active flag diff --git a/common/lib/xmodule/xmodule/lti_module.py b/common/lib/xmodule/xmodule/lti_module.py index 01753cb0d0..302c65413a 100644 --- a/common/lib/xmodule/xmodule/lti_module.py +++ b/common/lib/xmodule/xmodule/lti_module.py @@ -657,7 +657,7 @@ oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"'} # so '='' becomes '%3D'. # We send form via browser, so browser will encode it again, # So we need to decode signature back: - params[u'oauth_signature'] = six.moves.urllib.parse.unquote(params[u'oauth_signature']).decode('utf8') + params[u'oauth_signature'] = six.moves.urllib.parse.unquote(params[u'oauth_signature']).encode('utf-8').decode('utf8') # Add LTI parameters to OAuth parameters for sending in form. params.update(body) diff --git a/common/lib/xmodule/xmodule/modulestore/tests/test_xml_importer.py b/common/lib/xmodule/xmodule/modulestore/tests/test_xml_importer.py index 070e4163fc..0cdfb2bf52 100644 --- a/common/lib/xmodule/xmodule/modulestore/tests/test_xml_importer.py +++ b/common/lib/xmodule/xmodule/modulestore/tests/test_xml_importer.py @@ -9,6 +9,7 @@ import unittest from uuid import uuid4 import mock +import six from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator from path import Path as path @@ -22,6 +23,11 @@ from xmodule.modulestore.xml_importer import StaticContentImporter, _update_and_ from xmodule.tests import DATA_DIR from xmodule.x_module import XModuleMixin +if six.PY2: + OPEN_BUILTIN = '__builtin__.open' +else: + OPEN_BUILTIN = 'builtins.open' + class ModuleStoreNoSettings(unittest.TestCase): """ @@ -379,7 +385,7 @@ class StaticContentImporterTest(unittest.TestCase): base_dir = path('/path/to/dir') full_file_path = os.path.join(base_dir, 'static/some_file.txt') self.mocked_content_store.generate_thumbnail.return_value = (None, None) - with mock.patch("__builtin__.open", mock.mock_open(read_data="data")) as mock_file: + with mock.patch(OPEN_BUILTIN, mock.mock_open(read_data=b"data")) as mock_file: self.static_content_importer.import_static_file( full_file_path=full_file_path, base_dir=base_dir diff --git a/common/lib/xmodule/xmodule/tests/__init__.py b/common/lib/xmodule/xmodule/tests/__init__.py index 6aab74ede0..2113f76678 100644 --- a/common/lib/xmodule/xmodule/tests/__init__.py +++ b/common/lib/xmodule/xmodule/tests/__init__.py @@ -176,7 +176,7 @@ def mock_render_template(*args, **kwargs): Allows us to not depend on any actual template rendering mechanism, while still returning a unicode object """ - return pprint.pformat((args, kwargs)).decode() + return pprint.pformat((args, kwargs)).encode().decode() class ModelsTest(unittest.TestCase): diff --git a/common/test/acceptance/tests/discussion/test_cohort_management.py b/common/test/acceptance/tests/discussion/test_cohort_management.py index fd960695da..b8f4fb30ab 100644 --- a/common/test/acceptance/tests/discussion/test_cohort_management.py +++ b/common/test/acceptance/tests/discussion/test_cohort_management.py @@ -346,7 +346,7 @@ class CohortConfigurationTest(EventsTestMixin, UniqueCourseTest, CohortTestMixin Then the cohort has 1 user And appropriate events have been emitted """ - cohort_name = str(uuid.uuid4().get_hex()[0:20]) + cohort_name = str(uuid.uuid4().hex[0:20]) self._verify_cohort_settings(cohort_name=cohort_name, assignment_type=None) def test_add_new_cohort_with_manual_assignment_type(self): @@ -361,7 +361,7 @@ class CohortConfigurationTest(EventsTestMixin, UniqueCourseTest, CohortTestMixin Then the cohort has 1 user And appropriate events have been emitted """ - cohort_name = str(uuid.uuid4().get_hex()[0:20]) + cohort_name = str(uuid.uuid4().hex[0:20]) self._verify_cohort_settings(cohort_name=cohort_name, assignment_type='manual') def test_add_new_cohort_with_random_assignment_type(self): @@ -376,7 +376,7 @@ class CohortConfigurationTest(EventsTestMixin, UniqueCourseTest, CohortTestMixin Then the cohort has 1 user And appropriate events have been emitted """ - cohort_name = str(uuid.uuid4().get_hex()[0:20]) + cohort_name = str(uuid.uuid4().hex[0:20]) self._verify_cohort_settings(cohort_name=cohort_name, assignment_type='random') def test_update_existing_cohort_settings(self): @@ -396,7 +396,7 @@ class CohortConfigurationTest(EventsTestMixin, UniqueCourseTest, CohortTestMixin And cohort with new name is present in cohorts dropdown list And cohort assignment type should be "manual" """ - cohort_name = str(uuid.uuid4().get_hex()[0:20]) + cohort_name = str(uuid.uuid4().hex[0:20]) new_cohort_name = '{old}__NEW'.format(old=cohort_name) self._verify_cohort_settings( cohort_name=cohort_name, @@ -422,7 +422,7 @@ class CohortConfigurationTest(EventsTestMixin, UniqueCourseTest, CohortTestMixin And I click on Save button Then I should see an error message """ - cohort_name = str(uuid.uuid4().get_hex()[0:20]) + cohort_name = str(uuid.uuid4().hex[0:20]) new_cohort_name = '' self._verify_cohort_settings( cohort_name=cohort_name, diff --git a/common/test/acceptance/tests/lms/test_lms_course_discovery.py b/common/test/acceptance/tests/lms/test_lms_course_discovery.py index 903562a2f7..a1f52df4aa 100644 --- a/common/test/acceptance/tests/lms/test_lms_course_discovery.py +++ b/common/test/acceptance/tests/lms/test_lms_course_discovery.py @@ -41,7 +41,7 @@ class CourseDiscoveryTest(AcceptanceTest): for i in range(12): org = 'test_org' - number = "{}{}".format(str(i), str(uuid.uuid4().get_hex().upper()[0:6])) + number = "{}{}".format(str(i), str(uuid.uuid4().hex.upper()[0:6])) run = "test_run" name = "test course" if i < 10 else "grass is always greener" settings = {'enrollment_start': datetime.datetime(1970, 1, 1).isoformat()} diff --git a/common/test/acceptance/tests/studio/test_studio_course_create.py b/common/test/acceptance/tests/studio/test_studio_course_create.py index 7df2bd6f03..75b9577486 100644 --- a/common/test/acceptance/tests/studio/test_studio_course_create.py +++ b/common/test/acceptance/tests/studio/test_studio_course_create.py @@ -31,7 +31,7 @@ class CreateCourseTest(AcceptanceTest): self.dashboard_page = DashboardPage(self.browser) self.course_name = "New Course Name" self.course_org = "orgX" - self.course_number = str(uuid.uuid4().get_hex().upper()[0:6]) + self.course_number = str(uuid.uuid4().hex.upper()[0:6]) self.course_run = "2015_T2" def test_create_course_with_non_existing_org(self): diff --git a/lms/djangoapps/ccx/tests/test_views.py b/lms/djangoapps/ccx/tests/test_views.py index fb59095873..347fd89342 100644 --- a/lms/djangoapps/ccx/tests/test_views.py +++ b/lms/djangoapps/ccx/tests/test_views.py @@ -346,7 +346,7 @@ class TestCoachDashboard(CcxTestCase, LoginEnrollmentTestCase): self.assertEqual(response.status_code, 200) self.assertTrue(re.search( '