diff --git a/cms/djangoapps/contentstore/management/commands/export_all_courses.py b/cms/djangoapps/contentstore/management/commands/export_all_courses.py index 6f77ec7a99..b0514b0528 100644 --- a/cms/djangoapps/contentstore/management/commands/export_all_courses.py +++ b/cms/djangoapps/contentstore/management/commands/export_all_courses.py @@ -51,7 +51,7 @@ def export_courses_to_output_path(output_path): print("-" * 80) print("Exporting course id = {0} to {1}".format(course_id, output_path)) try: - course_dir = course_id.to_deprecated_string().replace('/', '...') + course_dir = text_type(course_id).replace('/', '...') export_course_to_xml(module_store, content_store, course_id, root_dir, course_dir) except Exception as err: # pylint: disable=broad-except failed_export_courses.append(text_type(course_id)) diff --git a/common/djangoapps/student/management/commands/anonymized_id_mapping.py b/common/djangoapps/student/management/commands/anonymized_id_mapping.py index 6315facc65..c306867c55 100644 --- a/common/djangoapps/student/management/commands/anonymized_id_mapping.py +++ b/common/djangoapps/student/management/commands/anonymized_id_mapping.py @@ -15,6 +15,7 @@ from django.core.management.base import BaseCommand, CommandError from student.models import anonymous_id_for_user from opaque_keys.edx.keys import CourseKey +from six import text_type class Command(BaseCommand): @@ -34,12 +35,12 @@ class Command(BaseCommand): # Generate the output filename from the course ID. # Change slashes to dashes first, and then append .csv extension. - output_filename = course_key.to_deprecated_string().replace('/', '-') + ".csv" + output_filename = text_type(course_key).replace('/', '-') + ".csv" # Figure out which students are enrolled in the course students = User.objects.filter(courseenrollment__course_id=course_key) if len(students) == 0: - self.stdout.write("No students enrolled in %s" % course_key.to_deprecated_string()) + self.stdout.write("No students enrolled in %s" % text_type(course_key)) return # Write mapping to output file in CSV format with a simple header diff --git a/common/lib/xmodule/xmodule/modulestore/mongo/base.py b/common/lib/xmodule/xmodule/modulestore/mongo/base.py index 44eb2a8fee..f70d761d73 100644 --- a/common/lib/xmodule/xmodule/modulestore/mongo/base.py +++ b/common/lib/xmodule/xmodule/modulestore/mongo/base.py @@ -8,7 +8,7 @@ structure: '_id': , 'metadata': 'definition': - 'definition.children': + 'definition.children': } """ diff --git a/common/lib/xmodule/xmodule/modulestore/mongo/draft.py b/common/lib/xmodule/xmodule/modulestore/mongo/draft.py index 9429f9d76b..993c3bccba 100644 --- a/common/lib/xmodule/xmodule/modulestore/mongo/draft.py +++ b/common/lib/xmodule/xmodule/modulestore/mongo/draft.py @@ -11,6 +11,7 @@ import logging from opaque_keys.edx.keys import UsageKey from opaque_keys.edx.locations import Location +from six import text_type from openedx.core.lib.cache_utils import memoize_in_request_cache from xmodule.exceptions import InvalidVersionError from xmodule.modulestore import ModuleStoreEnum @@ -263,7 +264,7 @@ class DraftModuleStore(MongoModuleStore): # create a query to find all items in the course that have the given location listed as a child query = self._course_key_to_son(location.course_key) - query['definition.children'] = location.to_deprecated_string() + query['definition.children'] = text_type(location) # find all the items that satisfy the query parents = self.collection.find(query, {'_id': True}, sort=[SORT_REVISION_FAVOR_DRAFT]) diff --git a/common/lib/xmodule/xmodule/modulestore/mongoengine_fields.py b/common/lib/xmodule/xmodule/modulestore/mongoengine_fields.py index 6c3f422e6c..68c9851399 100644 --- a/common/lib/xmodule/xmodule/modulestore/mongoengine_fields.py +++ b/common/lib/xmodule/xmodule/modulestore/mongoengine_fields.py @@ -5,6 +5,7 @@ import mongoengine from opaque_keys.edx.locations import Location from types import NoneType from opaque_keys.edx.keys import CourseKey, UsageKey +from six import text_type class CourseKeyField(mongoengine.StringField): @@ -22,7 +23,7 @@ class CourseKeyField(mongoengine.StringField): assert isinstance(course_key, (NoneType, CourseKey)) if course_key: # don't call super as base.BaseField.to_mongo calls to_python() for some odd reason - return course_key.to_deprecated_string() + return text_type(course_key) else: return None @@ -43,7 +44,7 @@ class CourseKeyField(mongoengine.StringField): def validate(self, value): assert isinstance(value, (NoneType, basestring, CourseKey)) if isinstance(value, CourseKey): - return super(CourseKeyField, self).validate(value.to_deprecated_string()) + return super(CourseKeyField, self).validate(text_type(value)) else: return super(CourseKeyField, self).validate(value) @@ -62,7 +63,7 @@ class UsageKeyField(mongoengine.StringField): assert isinstance(location, (NoneType, UsageKey)) if location is None: return None - return super(UsageKeyField, self).to_mongo(location.to_deprecated_string()) + return super(UsageKeyField, self).to_mongo(text_type(location)) def to_python(self, location): """ @@ -80,7 +81,7 @@ class UsageKeyField(mongoengine.StringField): def validate(self, value): assert isinstance(value, (NoneType, basestring, UsageKey)) if isinstance(value, UsageKey): - return super(UsageKeyField, self).validate(value.to_deprecated_string()) + return super(UsageKeyField, self).validate(text_type(value)) else: return super(UsageKeyField, self).validate(value) diff --git a/common/lib/xmodule/xmodule/modulestore/xml_exporter.py b/common/lib/xmodule/xmodule/modulestore/xml_exporter.py index fb6fefeec2..b529b115eb 100644 --- a/common/lib/xmodule/xmodule/modulestore/xml_exporter.py +++ b/common/lib/xmodule/xmodule/modulestore/xml_exporter.py @@ -58,12 +58,12 @@ def _export_drafts(modulestore, course_key, export_fs, xml_centric_course_key): # if module has no parent, set its parent_url to `None` parent_url = None if parent_loc is not None: - parent_url = parent_loc.to_deprecated_string() + parent_url = text_type(parent_loc) draft_node = draft_node_constructor( draft_module, location=draft_module.location, - url=draft_module.location.to_deprecated_string(), + url=text_type(draft_module.location), parent_location=parent_loc, parent_url=parent_url, ) diff --git a/common/lib/xmodule/xmodule/tests/__init__.py b/common/lib/xmodule/xmodule/tests/__init__.py index 4289a52bb9..897200b638 100644 --- a/common/lib/xmodule/xmodule/tests/__init__.py +++ b/common/lib/xmodule/xmodule/tests/__init__.py @@ -19,6 +19,7 @@ from contextlib import contextmanager, nested from functools import wraps from mock import Mock from path import Path as path +from six import text_type from opaque_keys.edx.keys import CourseKey from xblock.field_data import DictFieldData @@ -610,8 +611,8 @@ class CourseComparisonTest(BulkAssertionTest): expected_filename = expected_asset.pop('filename') actual_filename = actual_asset.pop('filename') - self.assertEqual(expected_key.to_deprecated_string(), expected_filename) - self.assertEqual(actual_key.to_deprecated_string(), actual_filename) + self.assertEqual(text_type(expected_key), expected_filename) + self.assertEqual(text_type(actual_key), actual_filename) self.assertEqual(expected_asset, actual_asset) def _assertAssetsEqual(self, expected_course_key, expected_assets, actual_course_key, actual_assets): # pylint: disable=invalid-name diff --git a/common/lib/xmodule/xmodule/tests/test_conditional.py b/common/lib/xmodule/xmodule/tests/test_conditional.py index 5704e439bf..2029c81efa 100644 --- a/common/lib/xmodule/xmodule/tests/test_conditional.py +++ b/common/lib/xmodule/xmodule/tests/test_conditional.py @@ -4,6 +4,7 @@ import unittest from fs.memoryfs import MemoryFS from lxml import etree from mock import Mock, patch +from six import text_type from xblock.field_data import DictFieldData from xblock.fields import ScopeIds @@ -273,7 +274,7 @@ class ConditionalModuleXmlTest(unittest.TestCase): 'conditional_ajax.html', { # Test ajax url is just usage-id / handler_name - 'ajax_url': '{}/xmodule_handler'.format(location.to_deprecated_string()), + 'ajax_url': '{}/xmodule_handler'.format(text_type(location)), 'element_id': u'i4x-HarvardX-ER22x-conditional-condone', 'depends': u'i4x-HarvardX-ER22x-problem-choiceprob' } diff --git a/common/lib/xmodule/xmodule/tests/test_export.py b/common/lib/xmodule/xmodule/tests/test_export.py index fa98a23f4c..46f5742881 100644 --- a/common/lib/xmodule/xmodule/tests/test_export.py +++ b/common/lib/xmodule/xmodule/tests/test_export.py @@ -12,6 +12,7 @@ import unittest from datetime import datetime, timedelta, tzinfo from fs.osfs import OSFS from path import Path as path +from six import text_type from tempfile import mkdtemp from textwrap import dedent @@ -30,7 +31,7 @@ def strip_filenames(descriptor): """ Recursively strips 'filename' from all children's definitions. """ - print "strip filename from {desc}".format(desc=descriptor.location.to_deprecated_string()) + print "strip filename from {desc}".format(desc=text_type(descriptor.location)) if descriptor._field_data.has(descriptor, 'filename'): descriptor._field_data.delete(descriptor, 'filename') @@ -171,10 +172,10 @@ class TestEdxJsonEncoder(unittest.TestCase): def test_encode_location(self): loc = Location('org', 'course', 'run', 'category', 'name', None) - self.assertEqual(loc.to_deprecated_string(), self.encoder.default(loc)) + self.assertEqual(text_type(loc), self.encoder.default(loc)) loc = Location('org', 'course', 'run', 'category', 'name', 'version') - self.assertEqual(loc.to_deprecated_string(), self.encoder.default(loc)) + self.assertEqual(text_type(loc), self.encoder.default(loc)) def test_encode_naive_datetime(self): self.assertEqual( diff --git a/common/lib/xmodule/xmodule/tests/test_import.py b/common/lib/xmodule/xmodule/tests/test_import.py index 9bed263d2d..56d32d62b6 100644 --- a/common/lib/xmodule/xmodule/tests/test_import.py +++ b/common/lib/xmodule/xmodule/tests/test_import.py @@ -9,6 +9,7 @@ from lxml import etree from mock import Mock, patch from pytz import UTC +from six import text_type from xmodule.xml_module import is_pointer_tag from opaque_keys.edx.locations import Location @@ -446,7 +447,7 @@ class ImportTestCase(BaseCourseTestCase): def check_for_key(key, node, value): "recursive check for presence of key" - print "Checking {0}".format(node.location.to_deprecated_string()) + print "Checking {0}".format(text_type(node.location)) self.assertEqual(getattr(node, key), value) for c in node.get_children(): check_for_key(key, c, value) diff --git a/common/lib/xmodule/xmodule/tests/test_lti_unit.py b/common/lib/xmodule/xmodule/tests/test_lti_unit.py index 0017519c2b..ba53770dd1 100644 --- a/common/lib/xmodule/xmodule/tests/test_lti_unit.py +++ b/common/lib/xmodule/xmodule/tests/test_lti_unit.py @@ -8,6 +8,7 @@ import textwrap from lxml import etree from webob.request import Request from copy import copy +from six import text_type import urllib from xmodule.fields import Timedelta @@ -276,7 +277,7 @@ class LTIModuleTest(LogicTest): self.assertEqual(self.xmodule.module_score, float(self.defaults['grade'])) def test_user_id(self): - expected_user_id = unicode(urllib.quote(self.xmodule.runtime.anonymous_student_id)) + expected_user_id = text_type(urllib.quote(self.xmodule.runtime.anonymous_student_id)) real_user_id = self.xmodule.get_user_id() self.assertEqual(real_user_id, expected_user_id) @@ -295,13 +296,13 @@ class LTIModuleTest(LogicTest): def test_resource_link_id(self): with patch('xmodule.lti_module.LTIModule.location', new_callable=PropertyMock): self.xmodule.location.html_id = lambda: 'i4x-2-3-lti-31de800015cf4afb973356dbe81496df' - expected_resource_link_id = unicode(urllib.quote(self.unquoted_resource_link_id)) + expected_resource_link_id = text_type(urllib.quote(self.unquoted_resource_link_id)) real_resource_link_id = self.xmodule.get_resource_link_id() self.assertEqual(real_resource_link_id, expected_resource_link_id) def test_lis_result_sourcedid(self): expected_sourced_id = u':'.join(urllib.quote(i) for i in ( - self.system.course_id.to_deprecated_string(), + text_type(self.system.course_id), self.xmodule.get_resource_link_id(), self.user_id )) @@ -520,4 +521,4 @@ class LTIModuleTest(LogicTest): """ Tests that LTI parameter context_id is equal to course_id. """ - self.assertEqual(self.system.course_id.to_deprecated_string(), self.xmodule.context_id) + self.assertEqual(text_type(self.system.course_id), self.xmodule.context_id) diff --git a/common/lib/xmodule/xmodule/tests/xml/__init__.py b/common/lib/xmodule/xmodule/tests/xml/__init__.py index 000d5e4606..23cbc0c65e 100644 --- a/common/lib/xmodule/xmodule/tests/xml/__init__.py +++ b/common/lib/xmodule/xmodule/tests/xml/__init__.py @@ -4,6 +4,7 @@ Xml parsing tests for XModules import pprint from lxml import etree from mock import Mock +from six import text_type from unittest import TestCase from xmodule.x_module import XMLParsingSystem, policy_key @@ -47,12 +48,12 @@ class InMemorySystem(XMLParsingSystem, MakoDescriptorSystem): # pylint: disable None, CourseLocationManager(self.course_id), ) - self._descriptors[descriptor.location.to_deprecated_string()] = descriptor + self._descriptors[text_type(descriptor.location)] = descriptor return descriptor def load_item(self, location, for_parent=None): # pylint: disable=method-hidden, unused-argument """Return the descriptor loaded for `location`""" - return self._descriptors[location.to_deprecated_string()] + return self._descriptors[text_type(location)] class XModuleXmlImportTest(TestCase): diff --git a/lms/djangoapps/bulk_email/tests/test_err_handling.py b/lms/djangoapps/bulk_email/tests/test_err_handling.py index c82d05c2b4..f5f5d0f6b1 100644 --- a/lms/djangoapps/bulk_email/tests/test_err_handling.py +++ b/lms/djangoapps/bulk_email/tests/test_err_handling.py @@ -15,6 +15,7 @@ from django.db import DatabaseError from mock import Mock, patch from nose.plugins.attrib import attr from opaque_keys.edx.locator import CourseLocator +from six import text_type from bulk_email.models import SEND_TO_MYSELF, BulkEmailFlag, CourseEmail from bulk_email.tasks import perform_delegate_email_batches, send_course_email @@ -56,10 +57,10 @@ class TestEmailErrors(ModuleStoreTestCase): # load initial content (since we don't run migrations as part of tests): call_command("loaddata", "course_email_template.json") - self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) - self.send_mail_url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()}) + self.url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) + self.send_mail_url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) self.success_content = { - 'course_id': self.course.id.to_deprecated_string(), + 'course_id': text_type(self.course.id), 'success': True, } diff --git a/lms/djangoapps/bulk_email/tests/test_forms.py b/lms/djangoapps/bulk_email/tests/test_forms.py index 2915b49602..7bf95f69ab 100644 --- a/lms/djangoapps/bulk_email/tests/test_forms.py +++ b/lms/djangoapps/bulk_email/tests/test_forms.py @@ -5,6 +5,7 @@ Unit tests for bulk-email-related forms. from nose.plugins.attrib import attr from opaque_keys.edx.locator import CourseLocator +from six import text_type from bulk_email.forms import CourseAuthorizationAdminForm, CourseEmailTemplateForm from bulk_email.models import BulkEmailFlag, CourseEmailTemplate @@ -30,7 +31,7 @@ class CourseAuthorizationFormTest(ModuleStoreTestCase): # Initially course shouldn't be authorized self.assertFalse(BulkEmailFlag.feature_enabled(self.course.id)) # Test authorizing the course, which should totally work - form_data = {'course_id': self.course.id.to_deprecated_string(), 'email_enabled': True} + form_data = {'course_id': text_type(self.course.id), 'email_enabled': True} form = CourseAuthorizationAdminForm(data=form_data) # Validation should work self.assertTrue(form.is_valid()) @@ -42,7 +43,7 @@ class CourseAuthorizationFormTest(ModuleStoreTestCase): # Initially course shouldn't be authorized self.assertFalse(BulkEmailFlag.feature_enabled(self.course.id)) # Test authorizing the course, which should totally work - form_data = {'course_id': self.course.id.to_deprecated_string(), 'email_enabled': True} + form_data = {'course_id': text_type(self.course.id), 'email_enabled': True} form = CourseAuthorizationAdminForm(data=form_data) # Validation should work self.assertTrue(form.is_valid()) @@ -51,7 +52,7 @@ class CourseAuthorizationFormTest(ModuleStoreTestCase): self.assertTrue(BulkEmailFlag.feature_enabled(self.course.id)) # Now make a new course authorization with the same course id that tries to turn email off - form_data = {'course_id': self.course.id.to_deprecated_string(), 'email_enabled': False} + form_data = {'course_id': text_type(self.course.id), 'email_enabled': False} form = CourseAuthorizationAdminForm(data=form_data) # Validation should not work because course_id field is unique self.assertFalse(form.is_valid()) @@ -72,13 +73,13 @@ class CourseAuthorizationFormTest(ModuleStoreTestCase): # Munge course id bad_id = CourseLocator(u'Broken{}'.format(self.course.id.org), 'hello', self.course.id.run + '_typo') - form_data = {'course_id': bad_id.to_deprecated_string(), 'email_enabled': True} + form_data = {'course_id': text_type(bad_id), 'email_enabled': True} form = CourseAuthorizationAdminForm(data=form_data) # Validation shouldn't work self.assertFalse(form.is_valid()) msg = u'COURSE NOT FOUND' - msg += u' --- Entered course id was: "{0}". '.format(bad_id.to_deprecated_string()) + msg += u' --- Entered course id was: "{0}". '.format(text_type(bad_id)) msg += 'Please recheck that you have supplied a valid course id.' self.assertEquals(msg, form._errors['course_id'][0]) # pylint: disable=protected-access diff --git a/lms/djangoapps/certificates/management/commands/gen_cert_report.py b/lms/djangoapps/certificates/management/commands/gen_cert_report.py index b658621464..70133fe3cb 100644 --- a/lms/djangoapps/certificates/management/commands/gen_cert_report.py +++ b/lms/djangoapps/certificates/management/commands/gen_cert_report.py @@ -8,6 +8,7 @@ from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from django.db.models import Count from opaque_keys.edx.keys import CourseKey +from six import text_type from certificates.models import GeneratedCertificate @@ -118,7 +119,7 @@ class Command(BaseCommand): print ' '.join(["{:>16}".format(heading) for heading in status_headings]) # print the report - print "{0:>26}".format(course_id.to_deprecated_string()), + print "{0:>26}".format(text_type(course_id)), for heading in status_headings: if heading in cert_data[course_id]: print "{:>16}".format(cert_data[course_id][heading]), diff --git a/lms/djangoapps/class_dashboard/tests/test_dashboard_data.py b/lms/djangoapps/class_dashboard/tests/test_dashboard_data.py index 5aa1e91d59..43e4bf6803 100644 --- a/lms/djangoapps/class_dashboard/tests/test_dashboard_data.py +++ b/lms/djangoapps/class_dashboard/tests/test_dashboard_data.py @@ -8,6 +8,7 @@ from django.core.urlresolvers import reverse from django.test.client import RequestFactory from mock import patch from nose.plugins.attrib import attr +from six import text_type from capa.tests.response_xml_factory import StringResponseXMLFactory from class_dashboard.dashboard_data import ( @@ -169,7 +170,7 @@ class TestGetProblemGradeDistribution(SharedModuleStoreTestCase): def test_get_students_problem_grades(self): - attributes = '?module_id=' + self.item.location.to_deprecated_string() + attributes = '?module_id=' + text_type(self.item.location) request = self.request_factory.get(reverse('get_students_problem_grades') + attributes) response = get_students_problem_grades(request) @@ -187,7 +188,7 @@ class TestGetProblemGradeDistribution(SharedModuleStoreTestCase): def test_get_students_problem_grades_max(self): with patch('class_dashboard.dashboard_data.MAX_SCREEN_LIST_LENGTH', 2): - attributes = '?module_id=' + self.item.location.to_deprecated_string() + attributes = '?module_id=' + text_type(self.item.location) request = self.request_factory.get(reverse('get_students_problem_grades') + attributes) response = get_students_problem_grades(request) @@ -201,7 +202,7 @@ class TestGetProblemGradeDistribution(SharedModuleStoreTestCase): def test_get_students_problem_grades_csv(self): tooltip = 'P1.2.1 Q1 - 3382 Students (100%: 1/1 questions)' - attributes = '?module_id=' + self.item.location.to_deprecated_string() + '&tooltip=' + tooltip + '&csv=true' + attributes = '?module_id=' + text_type(self.item.location) + '&tooltip=' + tooltip + '&csv=true' request = self.request_factory.get(reverse('get_students_problem_grades') + attributes) response = get_students_problem_grades(request) @@ -221,7 +222,7 @@ class TestGetProblemGradeDistribution(SharedModuleStoreTestCase): def test_get_students_opened_subsection(self): - attributes = '?module_id=' + self.item.location.to_deprecated_string() + attributes = '?module_id=' + text_type(self.item.location) request = self.request_factory.get(reverse('get_students_opened_subsection') + attributes) response = get_students_opened_subsection(request) @@ -234,7 +235,7 @@ class TestGetProblemGradeDistribution(SharedModuleStoreTestCase): with patch('class_dashboard.dashboard_data.MAX_SCREEN_LIST_LENGTH', 2): - attributes = '?module_id=' + self.item.location.to_deprecated_string() + attributes = '?module_id=' + text_type(self.item.location) request = self.request_factory.get(reverse('get_students_opened_subsection') + attributes) response = get_students_opened_subsection(request) @@ -248,7 +249,7 @@ class TestGetProblemGradeDistribution(SharedModuleStoreTestCase): def test_get_students_opened_subsection_csv(self): tooltip = '4162 students opened Subsection 5: Relational Algebra Exercises' - attributes = '?module_id=' + self.item.location.to_deprecated_string() + '&tooltip=' + tooltip + '&csv=true' + attributes = '?module_id=' + text_type(self.item.location) + '&tooltip=' + tooltip + '&csv=true' request = self.request_factory.get(reverse('get_students_opened_subsection') + attributes) response = get_students_opened_subsection(request) @@ -267,7 +268,7 @@ class TestGetProblemGradeDistribution(SharedModuleStoreTestCase): data = json.dumps({'sections': sections, 'tooltips': tooltips, - 'course_id': course_id.to_deprecated_string(), + 'course_id': text_type(course_id), 'data_type': data_type, }) @@ -303,7 +304,7 @@ class TestGetProblemGradeDistribution(SharedModuleStoreTestCase): data = json.dumps({'sections': sections, 'tooltips': tooltips, - 'course_id': course_id.to_deprecated_string(), + 'course_id': text_type(course_id), 'data_type': data_type, }) diff --git a/lms/djangoapps/class_dashboard/tests/test_views.py b/lms/djangoapps/class_dashboard/tests/test_views.py index 7976ec4a9d..bcc0cbde9a 100644 --- a/lms/djangoapps/class_dashboard/tests/test_views.py +++ b/lms/djangoapps/class_dashboard/tests/test_views.py @@ -6,6 +6,7 @@ import json from django.test.client import RequestFactory from mock import patch from nose.plugins.attrib import attr +from six import text_type from class_dashboard import views from student.tests.factories import AdminFactory @@ -93,11 +94,11 @@ class TestViews(ModuleStoreTestCase): instructor = AdminFactory.create() self.request.user = instructor - response = views.all_sequential_open_distrib(self.request, course.id.to_deprecated_string()) + response = views.all_sequential_open_distrib(self.request, text_type(course.id)) self.assertEqual('[]', response.content) - response = views.all_problem_grade_distribution(self.request, course.id.to_deprecated_string()) + response = views.all_problem_grade_distribution(self.request, text_type(course.id)) self.assertEqual('[]', response.content) - response = views.section_problem_grade_distrib(self.request, course.id.to_deprecated_string(), 'no section') + response = views.section_problem_grade_distrib(self.request, text_type(course.id), 'no section') self.assertEqual('{"error": "error"}', response.content) diff --git a/lms/djangoapps/course_wiki/tests/tests.py b/lms/djangoapps/course_wiki/tests/tests.py index d387ed3f8a..8328880c83 100644 --- a/lms/djangoapps/course_wiki/tests/tests.py +++ b/lms/djangoapps/course_wiki/tests/tests.py @@ -5,6 +5,7 @@ Tests for course wiki from django.core.urlresolvers import reverse from mock import patch from nose.plugins.attrib import attr +from six import text_type from courseware.tests.tests import LoginEnrollmentTestCase from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseTestConsentRequired @@ -49,7 +50,7 @@ class WikiRedirectTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCas self.enroll(self.toy) - referer = reverse("progress", kwargs={'course_id': self.toy.id.to_deprecated_string()}) + referer = reverse("progress", kwargs={'course_id': text_type(self.toy.id)}) destination = reverse("wiki:get", kwargs={'path': 'some/fake/wiki/page/'}) redirected_to = referer.replace("progress", "wiki/some/fake/wiki/page/") @@ -78,7 +79,7 @@ class WikiRedirectTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCas self.enroll(self.toy) - referer = reverse("progress", kwargs={'course_id': self.toy.id.to_deprecated_string()}) + referer = reverse("progress", kwargs={'course_id': text_type(self.toy.id)}) destination = reverse("wiki:get", kwargs={'path': 'some/fake/wiki/page/'}) resp = self.client.get(destination, HTTP_REFERER=referer) @@ -90,8 +91,8 @@ class WikiRedirectTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCas The user must be enrolled in the course to see the page. """ - course_wiki_home = reverse('course_wiki', kwargs={'course_id': course.id.to_deprecated_string()}) - referer = reverse("progress", kwargs={'course_id': course.id.to_deprecated_string()}) + course_wiki_home = reverse('course_wiki', kwargs={'course_id': text_type(course.id)}) + referer = reverse("progress", kwargs={'course_id': text_type(course.id)}) resp = self.client.get(course_wiki_home, follow=True, HTTP_REFERER=referer) @@ -123,7 +124,7 @@ class WikiRedirectTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCas self.create_course_page(self.toy) course_wiki_page = reverse('wiki:get', kwargs={'path': self.toy.wiki_slug + '/'}) - referer = reverse("courseware", kwargs={'course_id': self.toy.id.to_deprecated_string()}) + referer = reverse("courseware", kwargs={'course_id': text_type(self.toy.id)}) resp = self.client.get(course_wiki_page, follow=True, HTTP_REFERER=referer) @@ -143,7 +144,7 @@ class WikiRedirectTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCas self.login(self.student, self.password) course_wiki_page = reverse('wiki:get', kwargs={'path': self.toy.wiki_slug + '/'}) - referer = reverse("courseware", kwargs={'course_id': self.toy.id.to_deprecated_string()}) + referer = reverse("courseware", kwargs={'course_id': text_type(self.toy.id)}) # When not enrolled, we should get a 302 resp = self.client.get(course_wiki_page, follow=False, HTTP_REFERER=referer) @@ -153,7 +154,7 @@ class WikiRedirectTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCas resp = self.client.get(course_wiki_page, follow=True, HTTP_REFERER=referer) target_url, __ = resp.redirect_chain[-1] self.assertTrue( - target_url.endswith(reverse('about_course', args=[self.toy.id.to_deprecated_string()])) + target_url.endswith(reverse('about_course', args=[text_type(self.toy.id)])) ) @patch.dict("django.conf.settings.FEATURES", {'ALLOW_WIKI_ROOT_ACCESS': True}) @@ -198,7 +199,7 @@ class WikiRedirectTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCas self.create_course_page(course) course_wiki_page = reverse('wiki:get', kwargs={'path': course.wiki_slug + '/'}) - referer = reverse("courseware", kwargs={'course_id': course.id.to_deprecated_string()}) + referer = reverse("courseware", kwargs={'course_id': text_type(course.id)}) resp = self.client.get(course_wiki_page, follow=True, HTTP_REFERER=referer) self.assertEqual(resp.status_code, 200) diff --git a/lms/djangoapps/courseware/features/registration.py b/lms/djangoapps/courseware/features/registration.py index d1baaaf305..513d9f5f4f 100644 --- a/lms/djangoapps/courseware/features/registration.py +++ b/lms/djangoapps/courseware/features/registration.py @@ -4,11 +4,12 @@ import time from lettuce import step, world from lettuce.django import django_url +from six import text_type @step('I register for the course "([^"]*)"$') def i_register_for_the_course(_step, course): - url = django_url('courses/%s/about' % world.scenario_dict['COURSE'].id.to_deprecated_string()) + url = django_url('courses/%s/about' % text_type(world.scenario_dict['COURSE'].id)) world.browser.visit(url) world.css_click('.intro a.register') assert world.is_css_present('.dashboard') @@ -16,7 +17,7 @@ def i_register_for_the_course(_step, course): @step('I register to audit the course$') def i_register_to_audit_the_course(_step): - url = django_url('courses/%s/about' % world.scenario_dict['COURSE'].id.to_deprecated_string()) + url = django_url('courses/%s/about' % text_type(world.scenario_dict['COURSE'].id)) world.browser.visit(url) world.css_click('.intro a.register') # When the page first loads some animation needs to diff --git a/lms/djangoapps/courseware/tests/helpers.py b/lms/djangoapps/courseware/tests/helpers.py index 19117b46c0..6387faa28e 100644 --- a/lms/djangoapps/courseware/tests/helpers.py +++ b/lms/djangoapps/courseware/tests/helpers.py @@ -8,6 +8,7 @@ from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import Client, RequestFactory +from six import text_type from courseware.access import has_access from courseware.masquerade import handle_ajax, setup_masquerade @@ -253,7 +254,7 @@ class LoginEnrollmentTestCase(TestCase): """ resp = self.client.post(reverse('change_enrollment'), { 'enrollment_action': 'enroll', - 'course_id': course.id.to_deprecated_string(), + 'course_id': text_type(course.id), 'check_access': True, }) result = resp.status_code == 200 @@ -269,7 +270,7 @@ class LoginEnrollmentTestCase(TestCase): url = reverse('change_enrollment') request_data = { 'enrollment_action': 'unenroll', - 'course_id': course.id.to_deprecated_string(), + 'course_id': text_type(course.id), } self.assert_request_status_code(200, url, method="POST", data=request_data) diff --git a/lms/djangoapps/courseware/tests/test_about.py b/lms/djangoapps/courseware/tests/test_about.py index 95e3943e72..8246420e80 100644 --- a/lms/djangoapps/courseware/tests/test_about.py +++ b/lms/djangoapps/courseware/tests/test_about.py @@ -11,6 +11,7 @@ from django.test.utils import override_settings from milestones.tests.utils import MilestonesTestCaseMixin from mock import patch from nose.plugins.attrib import attr +from six import text_type from course_modes.models import CourseMode from lms.djangoapps.ccx.tests.factories import CcxFactory @@ -78,7 +79,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra """ This test asserts that a non-logged in user can visit the course about page """ - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) @@ -91,7 +92,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra This test asserts that a logged-in user can visit the course about page """ self.setup_user() - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) @@ -103,7 +104,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra """ self.setup_user() self.enroll(self.course, True) - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("You are enrolled in this course", resp.content) @@ -114,38 +115,38 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra """ Verify that the About Page honors the permission settings in the course module """ - url = reverse('about_course', args=[self.course_with_about.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course_with_about.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("WITH ABOUT", resp.content) - url = reverse('about_course', args=[self.course_without_about.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course_without_about.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 404) @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) def test_logged_in_marketing(self): self.setup_user() - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) # should be redirected self.assertEqual(resp.status_code, 302) # follow this time, and check we're redirected to the course info page resp = self.client.get(url, follow=True) target_url = resp.redirect_chain[-1][0] - info_url = reverse('info', args=[self.course.id.to_deprecated_string()]) + info_url = reverse('info', args=[text_type(self.course.id)]) self.assertTrue(target_url.endswith(info_url)) @patch.dict(settings.FEATURES, {'ENABLE_PREREQUISITE_COURSES': True}) def test_pre_requisite_course(self): pre_requisite_course = CourseFactory.create(org='edX', course='900', display_name='pre requisite course') - course = CourseFactory.create(pre_requisite_courses=[unicode(pre_requisite_course.id)]) + course = CourseFactory.create(pre_requisite_courses=[text_type(pre_requisite_course.id)]) self.setup_user() - url = reverse('about_course', args=[unicode(course.id)]) + url = reverse('about_course', args=[text_type(course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) pre_requisite_courses = get_prerequisite_courses_display(course) - pre_requisite_course_about_url = reverse('about_course', args=[unicode(pre_requisite_courses[0]['key'])]) + pre_requisite_course_about_url = reverse('about_course', args=[text_type(pre_requisite_courses[0]['key'])]) self.assertIn("{}" .format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']), resp.content.strip('\n')) @@ -158,7 +159,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra display_name='pre requisite course', ) - pre_requisite_courses = [unicode(pre_requisite_course.id)] + pre_requisite_courses = [text_type(pre_requisite_course.id)] # for this failure to occur, the enrollment window needs to be in the past course = CourseFactory.create( @@ -177,11 +178,11 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra self.enroll(self.course, True) self.enroll(pre_requisite_course, True) - url = reverse('about_course', args=[unicode(course.id)]) + url = reverse('about_course', args=[text_type(course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) pre_requisite_courses = get_prerequisite_courses_display(course) - pre_requisite_course_about_url = reverse('about_course', args=[unicode(pre_requisite_courses[0]['key'])]) + pre_requisite_course_about_url = reverse('about_course', args=[text_type(pre_requisite_courses[0]['key'])]) self.assertIn("{}" .format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']), resp.content.strip('\n')) @@ -226,14 +227,14 @@ class AboutTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase): @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_logged_in_xml(self): self.setup_user() - url = reverse('about_course', args=[self.xml_course_id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.xml_course_id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn(self.xml_data, resp.content) @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_anonymous_user_xml(self): - url = reverse('about_course', args=[self.xml_course_id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.xml_course_id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn(self.xml_data, resp.content) @@ -258,7 +259,7 @@ class AboutWithCappedEnrollmentsTestCase(LoginEnrollmentTestCase, SharedModuleSt This test will make sure that enrollment caps are enforced """ self.setup_user() - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn('', resp.content) @@ -305,7 +306,7 @@ class AboutWithInvitationOnly(SharedModuleStoreTestCase): Test for user not logged in, invitation only course. """ - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("Enrollment in this course is by invitation only", resp.content) @@ -323,7 +324,7 @@ class AboutWithInvitationOnly(SharedModuleStoreTestCase): CourseEnrollmentAllowedFactory(email=user.email, course_id=self.course.id) self.client.login(username=user.username, password='test') - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn(u"Enroll in {}".format(self.course.id.course), resp.content.decode('utf-8')) @@ -352,7 +353,7 @@ class AboutTestCaseShibCourse(LoginEnrollmentTestCase, SharedModuleStoreTestCase For shib courses, logged in users will see the enroll button, but get rejected once they click there """ self.setup_user() - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) @@ -364,7 +365,7 @@ class AboutTestCaseShibCourse(LoginEnrollmentTestCase, SharedModuleStoreTestCase """ For shib courses, anonymous users will also see the enroll button """ - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) @@ -399,7 +400,7 @@ class AboutWithClosedEnrollment(ModuleStoreTestCase): ) def test_closed_enrollmement(self): - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("Enrollment is Closed", resp.content) @@ -408,7 +409,7 @@ class AboutWithClosedEnrollment(ModuleStoreTestCase): self.assertNotIn(REG_STR, resp.content) def test_course_price_is_not_visble_in_sidebar(self): - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) # course price is not visible ihe course_about page when the course @@ -462,7 +463,7 @@ class AboutPurchaseCourseTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest """ Make sure an anonymous user sees the purchase button """ - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("Add buyme to Cart ($10 USD)", resp.content) @@ -472,7 +473,7 @@ class AboutPurchaseCourseTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest Make sure a logged in user sees the purchase button """ self.setup_user() - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("Add buyme to Cart ($10 USD)", resp.content) @@ -486,7 +487,7 @@ class AboutPurchaseCourseTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest cart = Order.get_cart_for_user(self.user) PaidCourseRegistration.add_to_order(cart, self.course.id) - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("This course is in your", resp.content) @@ -503,7 +504,7 @@ class AboutPurchaseCourseTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest # for paywalled courses CourseEnrollment.enroll(self.user, self.course.id) - url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) @@ -518,7 +519,7 @@ class AboutPurchaseCourseTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest """ self.setup_user() - url = reverse('about_course', args=[self.closed_course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.closed_course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("Enrollment is Closed", resp.content) @@ -537,7 +538,7 @@ class AboutPurchaseCourseTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest self._set_ecomm(course) self.setup_user() - url = reverse('about_course', args=[course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("Enrollment in this course is by invitation only", resp.content) @@ -556,7 +557,7 @@ class AboutPurchaseCourseTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest self._set_ecomm(course) self.setup_user() - url = reverse('about_course', args=[course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("Add buyme to Cart ($10 USD)", resp.content) @@ -588,7 +589,7 @@ class AboutPurchaseCourseTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest """ course = CourseFactory.create(org='MITx', number='free', display_name='Course For Free') self.setup_user() - url = reverse('about_course', args=[course.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) diff --git a/lms/djangoapps/courseware/tests/test_course_info.py b/lms/djangoapps/courseware/tests/test_course_info.py index ed734a58de..4b8c8a4426 100644 --- a/lms/djangoapps/courseware/tests/test_course_info.py +++ b/lms/djangoapps/courseware/tests/test_course_info.py @@ -15,6 +15,7 @@ from openedx.core.djangoapps.self_paced.models import SelfPacedConfiguration from openedx.core.djangoapps.waffle_utils.testutils import WAFFLE_TABLES from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseTestConsentRequired from pyquery import PyQuery as pq +from six import text_type from student.models import CourseEnrollment from student.tests.factories import AdminFactory from util.date_utils import strftime_localized @@ -50,7 +51,7 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, def test_logged_in_unenrolled(self): self.setup_user() - url = reverse('info', args=[self.course.id.to_deprecated_string()]) + url = reverse('info', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) @@ -58,7 +59,7 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, def test_logged_in_enrolled(self): self.enroll(self.course) - url = reverse('info', args=[self.course.id.to_deprecated_string()]) + url = reverse('info', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertNotIn("You are not currently enrolled in this course", resp.content) @@ -72,19 +73,19 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, self.setup_user() self.enroll(self.course) - url = reverse('info', args=[self.course.id.to_deprecated_string()]) + url = reverse('info', args=[text_type(self.course.id)]) self.verify_consent_required(self.client, url) def test_anonymous_user(self): - url = reverse('info', args=[self.course.id.to_deprecated_string()]) + url = reverse('info', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertNotIn("OOGIE BLOOGIE", resp.content) def test_logged_in_not_enrolled(self): self.setup_user() - url = reverse('info', args=[self.course.id.to_deprecated_string()]) + url = reverse('info', args=[text_type(self.course.id)]) self.client.get(url) # Check whether the user has been enrolled in the course. @@ -103,7 +104,7 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, """ self.setup_user() self.enroll(self.course) - url = reverse('info', args=[unicode(self.course.id)]) + url = reverse('info', args=[text_type(self.course.id)]) response = self.client.get(url) start_date = strftime_localized(self.course.start, 'SHORT_DATE') expected_params = QueryDict(mutable=True) @@ -125,7 +126,7 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, fake_unicode_start_time = u"üñîçø∂é_ßtå®t_tîµé" mock_strftime_localized.return_value = fake_unicode_start_time - url = reverse('info', args=[unicode(self.course.id)]) + url = reverse('info', args=[text_type(self.course.id)]) response = self.client.get(url) expected_params = QueryDict(mutable=True) expected_params['notlive'] = fake_unicode_start_time @@ -335,14 +336,14 @@ class CourseInfoTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase): @mock.patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_logged_in_xml(self): self.setup_user() - url = reverse('info', args=[self.xml_course_key.to_deprecated_string()]) + url = reverse('info', args=[text_type(self.xml_course_key)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn(self.xml_data, resp.content) @mock.patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_anonymous_user_xml(self): - url = reverse('info', args=[self.xml_course_key.to_deprecated_string()]) + url = reverse('info', args=[text_type(self.xml_course_key)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertNotIn(self.xml_data, resp.content) @@ -372,7 +373,7 @@ class SelfPacedCourseInfoTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest Fetch the given course's info page, asserting the number of SQL and Mongo queries. """ - url = reverse('info', args=[unicode(course.id)]) + url = reverse('info', args=[text_type(course.id)]) with self.assertNumQueries(sql_queries, table_blacklist=QUERY_COUNT_TABLE_BLACKLIST): with check_mongo_calls(mongo_queries): with mock.patch("openedx.core.djangoapps.theming.helpers.get_current_site", return_value=None): diff --git a/lms/djangoapps/courseware/tests/test_lti_integration.py b/lms/djangoapps/courseware/tests/test_lti_integration.py index 65e9e8ae16..b6be3737a8 100644 --- a/lms/djangoapps/courseware/tests/test_lti_integration.py +++ b/lms/djangoapps/courseware/tests/test_lti_integration.py @@ -14,6 +14,7 @@ from courseware.tests.helpers import BaseTestXmodule from courseware.views.views import get_course_lti_endpoints from nose.plugins.attrib import attr from openedx.core.lib.url_utils import quote_slashes +from six import text_type from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory from xmodule.x_module import STUDENT_VIEW @@ -41,10 +42,10 @@ class TestLTI(BaseTestXmodule): mocked_decoded_signature = u'my_signature=' # Note: this course_id is actually a course_key - context_id = self.item_descriptor.course_id.to_deprecated_string() - user_id = unicode(self.item_descriptor.xmodule_runtime.anonymous_student_id) + context_id = text_type(self.item_descriptor.course_id) + user_id = text_type(self.item_descriptor.xmodule_runtime.anonymous_student_id) hostname = self.item_descriptor.xmodule_runtime.hostname - resource_link_id = unicode(urllib.quote('{}-{}'.format(hostname, self.item_descriptor.location.html_id()))) + resource_link_id = text_type(urllib.quote('{}-{}'.format(hostname, self.item_descriptor.location.html_id()))) sourcedId = "{context}:{resource_link}:{user_id}".format( context=urllib.quote(context_id), @@ -175,8 +176,8 @@ class TestLTIModuleListing(SharedModuleStoreTestCase): return "https://{}{}".format(settings.SITE_NAME, reverse( 'xblock_handler_noauth', args=[ - self.course.id.to_deprecated_string(), - quote_slashes(unicode(self.lti_published.scope_ids.usage_id.to_deprecated_string()).encode('utf-8')), + text_type(self.course.id), + quote_slashes(text_type(self.lti_published.scope_ids.usage_id).encode('utf-8')), handler ] )) @@ -194,7 +195,7 @@ class TestLTIModuleListing(SharedModuleStoreTestCase): """tests that the draft lti module is part of the endpoint response""" request = mock.Mock() request.method = 'GET' - response = get_course_lti_endpoints(request, course_id=self.course.id.to_deprecated_string()) + response = get_course_lti_endpoints(request, course_id=text_type(self.course.id)) self.assertEqual(200, response.status_code) self.assertEqual('application/json', response['Content-Type']) @@ -213,5 +214,5 @@ class TestLTIModuleListing(SharedModuleStoreTestCase): for method in DISALLOWED_METHODS: request = mock.Mock() request.method = method - response = get_course_lti_endpoints(request, self.course.id.to_deprecated_string()) + response = get_course_lti_endpoints(request, text_type(self.course.id)) self.assertEqual(405, response.status_code) diff --git a/lms/djangoapps/courseware/tests/test_microsites.py b/lms/djangoapps/courseware/tests/test_microsites.py index d1017f6757..46d35e3c53 100644 --- a/lms/djangoapps/courseware/tests/test_microsites.py +++ b/lms/djangoapps/courseware/tests/test_microsites.py @@ -10,6 +10,7 @@ from django.core.urlresolvers import reverse from django.test.utils import override_settings from mock import patch from nose.plugins.attrib import attr +from six import text_type from course_modes.models import CourseMode from courseware.tests.helpers import LoginEnrollmentTestCase @@ -279,7 +280,7 @@ class TestSites(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.login(email, password) self.enroll(self.course, True) - resp = self.client.get(reverse('courseware', args=[unicode(self.course.id)]), + resp = self.client.get(reverse('courseware', args=[text_type(self.course.id)]), HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME) self.assertContains(resp, 'Test Site Tab:') @@ -289,11 +290,11 @@ class TestSites(SharedModuleStoreTestCase, LoginEnrollmentTestCase): Make sure the Site is honoring the visible_about_page permissions that is set in configuration """ - url = reverse('about_course', args=[self.course_with_visibility.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course_with_visibility.id)]) resp = self.client.get(url, HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME) self.assertEqual(resp.status_code, 200) - url = reverse('about_course', args=[self.course_hidden_visibility.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course_hidden_visibility.id)]) resp = self.client.get(url, HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME) self.assertEqual(resp.status_code, 404) @@ -313,14 +314,14 @@ class TestSites(SharedModuleStoreTestCase, LoginEnrollmentTestCase): # first try on the non site, which # should pick up the global configuration (where ENABLE_PAID_COURSE_REGISTRATIONS = False) - url = reverse('about_course', args=[self.course_with_visibility.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course_with_visibility.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("Enroll in {}".format(self.course_with_visibility.id.course), resp.content) self.assertNotIn("Add {} to Cart ($10)".format(self.course_with_visibility.id.course), resp.content) # now try on the site - url = reverse('about_course', args=[self.course_with_visibility.id.to_deprecated_string()]) + url = reverse('about_course', args=[text_type(self.course_with_visibility.id)]) resp = self.client.get(url, HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME) self.assertEqual(resp.status_code, 200) self.assertNotIn("Enroll in {}".format(self.course_with_visibility.id.course), resp.content) diff --git a/lms/djangoapps/courseware/tests/test_module_render.py b/lms/djangoapps/courseware/tests/test_module_render.py index d4f4798513..44cde95c8b 100644 --- a/lms/djangoapps/courseware/tests/test_module_render.py +++ b/lms/djangoapps/courseware/tests/test_module_render.py @@ -26,6 +26,7 @@ from mock import MagicMock, Mock, patch from nose.plugins.attrib import attr from opaque_keys.edx.keys import CourseKey, UsageKey from pyquery import PyQuery +from six import text_type from xblock.completable import CompletableXBlockMixin from xblock.core import XBlock, XBlockAside from xblock.field_data import FieldData @@ -195,7 +196,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.callback_url = reverse( 'xqueue_callback', kwargs=dict( - course_id=self.course_key.to_deprecated_string(), + course_id=text_type(self.course_key), userid=str(self.mock_user.id), mod_id=self.mock_module.id, dispatch=self.dispatch @@ -238,7 +239,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): # See if the url got rewritten to the target link # note if the URL mapping changes then this assertion will break - self.assertIn('/courses/' + self.course_key.to_deprecated_string() + '/jump_to_id/vertical_test', html) + self.assertIn('/courses/' + text_type(self.course_key) + '/jump_to_id/vertical_test', html) @pytest.mark.django111_expected_failure def test_xqueue_callback_success(self): @@ -302,8 +303,8 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): dispatch_url = reverse( 'xblock_handler', args=[ - self.course_key.to_deprecated_string(), - quote_slashes(self.course_key.make_usage_key('videosequence', 'Toy_Videos').to_deprecated_string()), + text_type(self.course_key), + quote_slashes(text_type(self.course_key.make_usage_key('videosequence', 'Toy_Videos'))), 'xmodule_handler', 'goto_position' ] @@ -319,8 +320,8 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): dispatch_url = reverse( 'xblock_handler', args=[ - self.course_key.to_deprecated_string(), - quote_slashes(self.course_key.make_usage_key('videosequence', 'Toy_Videos').to_deprecated_string()), + text_type(self.course_key), + quote_slashes(text_type(self.course_key.make_usage_key('videosequence', 'Toy_Videos'))), 'xmodule_handler', 'goto_position' ] @@ -471,7 +472,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas # Construct a 'standard' xqueue_callback url self.callback_url = reverse( 'xqueue_callback', kwargs={ - 'course_id': self.course_key.to_deprecated_string(), + 'course_id': text_type(self.course_key), 'userid': str(self.mock_user.id), 'mod_id': self.mock_module.id, 'dispatch': self.dispatch @@ -515,7 +516,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas with self.assertRaises(Http404): render.handle_xblock_callback( request, - self.course_key.to_deprecated_string(), + text_type(self.course_key), 'invalid Location', 'dummy_handler' 'dummy_dispatch' @@ -530,8 +531,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas self.assertEquals( render.handle_xblock_callback( request, - self.course_key.to_deprecated_string(), - quote_slashes(self.location.to_deprecated_string()), + text_type(self.course_key), + quote_slashes(text_type(self.location)), 'dummy_handler' ).content, json.dumps({ @@ -550,8 +551,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas self.assertEquals( render.handle_xblock_callback( request, - self.course_key.to_deprecated_string(), - quote_slashes(self.location.to_deprecated_string()), + text_type(self.course_key), + quote_slashes(text_type(self.location)), 'dummy_handler' ).content, json.dumps({ @@ -565,8 +566,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas request.user = self.mock_user response = render.handle_xblock_callback( request, - self.course_key.to_deprecated_string(), - quote_slashes(self.location.to_deprecated_string()), + text_type(self.course_key), + quote_slashes(text_type(self.location)), 'xmodule_handler', 'goto_position', ) @@ -579,7 +580,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas render.handle_xblock_callback( request, 'bad_course_id', - quote_slashes(self.location.to_deprecated_string()), + quote_slashes(text_type(self.location)), 'xmodule_handler', 'goto_position', ) @@ -590,8 +591,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas with self.assertRaises(Http404): render.handle_xblock_callback( request, - self.course_key.to_deprecated_string(), - quote_slashes(self.course_key.make_usage_key('chapter', 'bad_location').to_deprecated_string()), + text_type(self.course_key), + quote_slashes(text_type(self.course_key.make_usage_key('chapter', 'bad_location'))), 'xmodule_handler', 'goto_position', ) @@ -602,8 +603,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas with self.assertRaises(Http404): render.handle_xblock_callback( request, - self.course_key.to_deprecated_string(), - quote_slashes(self.location.to_deprecated_string()), + text_type(self.course_key), + quote_slashes(text_type(self.location)), 'xmodule_handler', 'bad_dispatch', ) @@ -614,8 +615,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas with self.assertRaises(Http404): render.handle_xblock_callback( request, - self.course_key.to_deprecated_string(), - quote_slashes(self.location.to_deprecated_string()), + text_type(self.course_key), + quote_slashes(text_type(self.location)), 'bad_handler', 'bad_dispatch', ) @@ -1432,7 +1433,7 @@ class TestHtmlModifiers(ModuleStoreTestCase): self.assertIn( '/courses/{course_id}/bar/content'.format( - course_id=self.course.id.to_deprecated_string() + course_id=text_type(self.course.id) ), result_fragment.content ) @@ -1907,8 +1908,8 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): render.handle_xblock_callback( self.request, - self.course.id.to_deprecated_string(), - quote_slashes(descriptor.location.to_deprecated_string()), + text_type(self.course.id), + quote_slashes(text_type(descriptor.location)), 'xmodule_handler', 'problem_check', ) diff --git a/lms/djangoapps/courseware/tests/test_navigation.py b/lms/djangoapps/courseware/tests/test_navigation.py index 9b87544c7d..d3abde6e82 100644 --- a/lms/djangoapps/courseware/tests/test_navigation.py +++ b/lms/djangoapps/courseware/tests/test_navigation.py @@ -8,6 +8,7 @@ from django.core.urlresolvers import reverse from django.test.utils import override_settings from mock import patch from nose.plugins.attrib import attr +from six import text_type from courseware.tests.factories import GlobalStaffFactory from courseware.tests.helpers import LoginEnrollmentTestCase @@ -118,7 +119,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): ) for (displayname, accordion, tabs) in test_data: response = self.client.get(reverse('courseware_section', kwargs={ - 'course_id': self.course.id.to_deprecated_string(), + 'course_id': text_type(self.course.id), 'chapter': 'Chrome', 'section': displayname, })) @@ -129,7 +130,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.assertTabActive('courseware', response) response = self.client.get(reverse('courseware_section', kwargs={ - 'course_id': self.course.id.to_deprecated_string(), + 'course_id': text_type(self.course.id), 'chapter': 'Chrome', 'section': 'progress_tab', })) @@ -169,9 +170,9 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.enroll(self.test_course, True) resp = self.client.get(reverse('courseware', - kwargs={'course_id': self.course.id.to_deprecated_string()})) + kwargs={'course_id': text_type(self.course.id)})) self.assertRedirects(resp, reverse( - 'courseware_section', kwargs={'course_id': self.course.id.to_deprecated_string(), + 'courseware_section', kwargs={'course_id': text_type(self.course.id), 'chapter': 'Overview', 'section': 'Welcome'})) @@ -188,14 +189,14 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): section_url = reverse( 'courseware_section', kwargs={ - 'course_id': self.course.id.to_deprecated_string(), + 'course_id': text_type(self.course.id), 'chapter': 'Overview', 'section': 'Welcome', }, ) self.client.get(section_url) resp = self.client.get( - reverse('courseware', kwargs={'course_id': self.course.id.to_deprecated_string()}), + reverse('courseware', kwargs={'course_id': text_type(self.course.id)}), ) self.assertRedirects(resp, section_url) @@ -212,7 +213,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): section_url = reverse( 'courseware_section', kwargs={ - 'course_id': self.course.id.to_deprecated_string(), + 'course_id': text_type(self.course.id), 'chapter': 'factory_chapter', 'section': 'factory_section', } @@ -222,7 +223,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): # And now hitting the courseware tab should redirect to 'factory_chapter' url = reverse( 'courseware', - kwargs={'course_id': self.course.id.to_deprecated_string()} + kwargs={'course_id': text_type(self.course.id)} ) resp = self.client.get(url) self.assertRedirects(resp, section_url) @@ -235,7 +236,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.login(email, password) self.enroll(self.test_course, True) - test_course_id = self.test_course.id.to_deprecated_string() + test_course_id = text_type(self.test_course.id) url = reverse( 'courseware', @@ -289,7 +290,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.login(email, password) self.enroll(self.test_course_proctored, True) - test_course_id = self.test_course_proctored.id.to_deprecated_string() + test_course_id = text_type(self.test_course_proctored.id) with patch.dict(settings.FEATURES, {'ENABLE_SPECIAL_EXAMS': False}): url = reverse( diff --git a/lms/djangoapps/courseware/tests/test_split_module.py b/lms/djangoapps/courseware/tests/test_split_module.py index 3413ddd3f9..d831abcf24 100644 --- a/lms/djangoapps/courseware/tests/test_split_module.py +++ b/lms/djangoapps/courseware/tests/test_split_module.py @@ -4,6 +4,7 @@ Test for split test XModule from django.core.urlresolvers import reverse from mock import MagicMock from nose.plugins.attrib import attr +from six import text_type from courseware.model_data import FieldDataCache from courseware.module_render import get_module_for_descriptor @@ -118,7 +119,7 @@ class SplitTestBase(SharedModuleStoreTestCase): resp = self.client.get(reverse( 'courseware_section', - kwargs={'course_id': self.course.id.to_deprecated_string(), + kwargs={'course_id': text_type(self.course.id), 'chapter': self.chapter.url_name, 'section': self.sequential.url_name} )) diff --git a/lms/djangoapps/courseware/tests/test_submitting_problems.py b/lms/djangoapps/courseware/tests/test_submitting_problems.py index e86788d28c..11614641c2 100644 --- a/lms/djangoapps/courseware/tests/test_submitting_problems.py +++ b/lms/djangoapps/courseware/tests/test_submitting_problems.py @@ -18,6 +18,7 @@ from django.test.client import RequestFactory from django.utils.timezone import now from mock import patch from nose.plugins.attrib import attr +from six import text_type from capa.tests.response_xml_factory import ( CodeResponseXMLFactory, @@ -69,8 +70,8 @@ class ProblemSubmissionTestMixin(TestCase): return reverse( 'xblock_handler', kwargs={ - 'course_id': self.course.id.to_deprecated_string(), - 'usage_id': quote_slashes(problem_location.to_deprecated_string()), + 'course_id': text_type(self.course.id), + 'usage_id': quote_slashes(text_type(problem_location)), 'handler': 'xmodule_handler', 'suffix': dispatch, } @@ -602,7 +603,7 @@ class TestCourseGrader(TestSubmittingProblems): with patch('submissions.api.get_scores') as mock_get_scores: mock_get_scores.return_value = { - self.problem_location('p3').to_deprecated_string(): { + text_type(self.problem_location('p3')): { 'points_earned': 1, 'points_possible': 1, 'created_at': now(), @@ -612,7 +613,7 @@ class TestCourseGrader(TestSubmittingProblems): # Verify that the submissions API was sent an anonymized student ID mock_get_scores.assert_called_with( - self.course.id.to_deprecated_string(), + text_type(self.course.id), anonymous_id_for_user(self.student_user, self.course.id) ) diff --git a/lms/djangoapps/courseware/tests/test_tabs.py b/lms/djangoapps/courseware/tests/test_tabs.py index 00825797b1..1bfbeb49b4 100644 --- a/lms/djangoapps/courseware/tests/test_tabs.py +++ b/lms/djangoapps/courseware/tests/test_tabs.py @@ -9,6 +9,7 @@ from django.http import Http404 from milestones.tests.utils import MilestonesTestCaseMixin from mock import MagicMock, Mock, patch from nose.plugins.attrib import attr +from six import text_type from courseware.courses import get_course_by_id from courseware.tabs import ( @@ -222,7 +223,7 @@ class TextbooksTestCase(TabTestCase): book_type, book_index = tab.tab_id.split("/", 1) expected_link = self.reverse( type_to_reverse_name[book_type], - args=[self.course.id.to_deprecated_string(), book_index] + args=[text_type(self.course.id), book_index] ) self.assertEqual(tab.link_func(self.course, self.reverse), expected_link) self.assertTrue(tab.name.startswith('Book{0}'.format(book_index))) @@ -249,13 +250,13 @@ class StaticTabDateTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase): def test_logged_in(self): self.setup_user() - url = reverse('static_tab', args=[self.course.id.to_deprecated_string(), 'new_tab']) + url = reverse('static_tab', args=[text_type(self.course.id), 'new_tab']) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) def test_anonymous_user(self): - url = reverse('static_tab', args=[self.course.id.to_deprecated_string(), 'new_tab']) + url = reverse('static_tab', args=[text_type(self.course.id), 'new_tab']) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) @@ -274,7 +275,7 @@ class StaticTabDateTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase): # Test render works okay tab_content = get_static_tab_fragment(request, course, tab).content - self.assertIn(self.course.id.to_deprecated_string(), tab_content) + self.assertIn(text_type(self.course.id), tab_content) self.assertIn('static_tab', tab_content) # Test when render raises an exception @@ -323,14 +324,14 @@ class StaticTabDateTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase): @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_logged_in_xml(self): self.setup_user() - url = reverse('static_tab', args=[self.xml_course_key.to_deprecated_string(), self.xml_url]) + url = reverse('static_tab', args=[text_type(self.xml_course_key), self.xml_url]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn(self.xml_data, resp.content) @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_anonymous_user_xml(self): - url = reverse('static_tab', args=[self.xml_course_key.to_deprecated_string(), self.xml_url]) + url = reverse('static_tab', args=[text_type(self.xml_course_key), self.xml_url]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn(self.xml_data, resp.content) @@ -490,7 +491,7 @@ class TextBookCourseViewsTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest book_type, book_index = tab.tab_id.split("/", 1) expected_link = reverse( type_to_reverse_name[book_type], - args=[self.course.id.to_deprecated_string(), book_index] + args=[text_type(self.course.id), book_index] ) tab_link = tab.link_func(self.course, reverse) self.assertEqual(tab_link, expected_link) @@ -733,7 +734,7 @@ class ProgressTestCase(TabTestCase): return self.check_tab( tab_class=ProgressTab, dict_tab={'type': ProgressTab.type, 'name': 'same'}, - expected_link=self.reverse('progress', args=[self.course.id.to_deprecated_string()]), + expected_link=self.reverse('progress', args=[text_type(self.course.id)]), expected_tab_id=ProgressTab.type, invalid_dict_tab=None, ) @@ -766,7 +767,7 @@ class StaticTabTestCase(TabTestCase): tab = self.check_tab( tab_class=xmodule_tabs.StaticTab, dict_tab={'type': xmodule_tabs.StaticTab.type, 'name': 'same', 'url_slug': url_slug}, - expected_link=self.reverse('static_tab', args=[self.course.id.to_deprecated_string(), url_slug]), + expected_link=self.reverse('static_tab', args=[text_type(self.course.id), url_slug]), expected_tab_id='static_tab_schmug', invalid_dict_tab=self.fake_dict_tab, ) diff --git a/lms/djangoapps/courseware/tests/test_view_authentication.py b/lms/djangoapps/courseware/tests/test_view_authentication.py index 1c2cc27469..e9ab065bb0 100644 --- a/lms/djangoapps/courseware/tests/test_view_authentication.py +++ b/lms/djangoapps/courseware/tests/test_view_authentication.py @@ -4,6 +4,7 @@ import pytz from django.core.urlresolvers import reverse from mock import patch from nose.plugins.attrib import attr +from six import text_type from courseware.access import has_access from courseware.tests.factories import ( @@ -43,7 +44,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro Returns a list URLs corresponding to section in the passed in course. """ - return [reverse(name, kwargs={'course_id': course.id.to_deprecated_string()}) + return [reverse(name, kwargs={'course_id': text_type(course.id)}) for name in names] def _check_non_staff_light(self, course): @@ -52,7 +53,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro `course` is an instance of CourseDescriptor. """ - urls = [reverse('about_course', kwargs={'course_id': course.id.to_deprecated_string()}), + urls = [reverse('about_course', kwargs={'course_id': text_type(course.id)}), reverse('courses')] for url in urls: self.assert_request_status_code(200, url) @@ -65,7 +66,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro names = ['courseware', 'progress'] urls = self._reverse_urls(names, course) urls.extend([ - reverse('book', kwargs={'course_id': course.id.to_deprecated_string(), + reverse('book', kwargs={'course_id': text_type(course.id), 'book_index': index}) for index, __ in enumerate(course.textbooks) ]) @@ -73,7 +74,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro self.assert_request_status_code(302, url) self.assert_request_status_code( - 404, reverse('instructor_dashboard', kwargs={'course_id': course.id.to_deprecated_string()}) + 404, reverse('instructor_dashboard', kwargs={'course_id': text_type(course.id)}) ) def _check_staff(self, course): @@ -83,7 +84,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro names = ['about_course', 'instructor_dashboard', 'progress'] urls = self._reverse_urls(names, course) urls.extend([ - reverse('book', kwargs={'course_id': course.id.to_deprecated_string(), + reverse('book', kwargs={'course_id': text_type(course.id), 'book_index': index}) for index in xrange(len(course.textbooks)) ]) @@ -99,7 +100,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro url = reverse( 'student_progress', kwargs={ - 'course_id': course.id.to_deprecated_string(), + 'course_id': text_type(course.id), 'student_id': self.enrolled_user.id, } ) @@ -170,12 +171,12 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro """ self.login(self.unenrolled_user) response = self.client.get(reverse('courseware', - kwargs={'course_id': self.course.id.to_deprecated_string()})) + kwargs={'course_id': text_type(self.course.id)})) self.assertRedirects( response, reverse( 'about_course', - args=[self.course.id.to_deprecated_string()] + args=[text_type(self.course.id)] ) ) @@ -189,7 +190,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro response = self.client.get( reverse( 'courseware', - kwargs={'course_id': self.course.id.to_deprecated_string()} + kwargs={'course_id': text_type(self.course.id)} ) ) @@ -197,7 +198,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro response, reverse( 'courseware_section', - kwargs={'course_id': self.course.id.to_deprecated_string(), + kwargs={'course_id': text_type(self.course.id), 'chapter': self.overview_chapter.url_name, 'section': self.welcome_section.url_name} ) @@ -212,7 +213,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro self.login(self.enrolled_user) url = reverse( 'courseware', - kwargs={'course_id': self.course.id.to_deprecated_string()} + kwargs={'course_id': text_type(self.course.id)} ) self.verify_consent_required(self.client, url, status_code=302) @@ -223,8 +224,8 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro """ self.login(self.enrolled_user) - urls = [reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}), - reverse('instructor_dashboard', kwargs={'course_id': self.test_course.id.to_deprecated_string()})] + urls = [reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}), + reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)})] # Shouldn't be able to get to the instructor pages for url in urls: @@ -238,10 +239,10 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro self.login(self.staff_user) # Now should be able to get to self.course, but not self.test_course - url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) self.assert_request_status_code(200, url) - url = reverse('instructor_dashboard', kwargs={'course_id': self.test_course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)}) self.assert_request_status_code(404, url) def test_instructor_course_access(self): @@ -252,10 +253,10 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro self.login(self.instructor_user) # Now should be able to get to self.course, but not self.test_course - url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) self.assert_request_status_code(200, url) - url = reverse('instructor_dashboard', kwargs={'course_id': self.test_course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)}) self.assert_request_status_code(404, url) def test_org_staff_access(self): @@ -264,13 +265,13 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro and student profile pages for course in their org. """ self.login(self.org_staff_user) - url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) self.assert_request_status_code(200, url) - url = reverse('instructor_dashboard', kwargs={'course_id': self.test_course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)}) self.assert_request_status_code(200, url) - url = reverse('instructor_dashboard', kwargs={'course_id': self.other_org_course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.other_org_course.id)}) self.assert_request_status_code(404, url) def test_org_instructor_access(self): @@ -279,13 +280,13 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro and student profile pages for course in their org. """ self.login(self.org_instructor_user) - url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) self.assert_request_status_code(200, url) - url = reverse('instructor_dashboard', kwargs={'course_id': self.test_course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)}) self.assert_request_status_code(200, url) - url = reverse('instructor_dashboard', kwargs={'course_id': self.other_org_course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.other_org_course.id)}) self.assert_request_status_code(404, url) def test_global_staff_access(self): @@ -295,8 +296,8 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro self.login(self.global_staff_user) # and now should be able to load both - urls = [reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}), - reverse('instructor_dashboard', kwargs={'course_id': self.test_course.id.to_deprecated_string()})] + urls = [reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}), + reverse('instructor_dashboard', kwargs={'course_id': text_type(self.test_course.id)})] for url in urls: self.assert_request_status_code(200, url) diff --git a/lms/djangoapps/courseware/tests/test_views.py b/lms/djangoapps/courseware/tests/test_views.py index 4075bebc79..0d8bda7795 100644 --- a/lms/djangoapps/courseware/tests/test_views.py +++ b/lms/djangoapps/courseware/tests/test_views.py @@ -25,6 +25,7 @@ from nose.plugins.attrib import attr from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locations import Location from pytz import UTC +from six import text_type from xblock.core import XBlock from xblock.fields import Scope, String from xblock.fragment import Fragment @@ -533,16 +534,16 @@ class ViewsTestCase(ModuleStoreTestCase): # test the course location self.assertEqual( u'/courses/{course_key}/courseware?{activate_block_id}'.format( - course_key=self.course_key.to_deprecated_string(), - activate_block_id=urlencode({'activate_block_id': self.course.location.to_deprecated_string()}) + course_key=text_type(self.course_key), + activate_block_id=urlencode({'activate_block_id': text_type(self.course.location)}) ), get_redirect_url(self.course_key, self.course.location), ) # test a section location self.assertEqual( u'/courses/{course_key}/courseware/Chapter_1/Sequential_1/?{activate_block_id}'.format( - course_key=self.course_key.to_deprecated_string(), - activate_block_id=urlencode({'activate_block_id': self.section.location.to_deprecated_string()}) + course_key=text_type(self.course_key), + activate_block_id=urlencode({'activate_block_id': text_type(self.section.location)}) ), get_redirect_url(self.course_key, self.section.location), ) diff --git a/lms/djangoapps/courseware/tests/tests.py b/lms/djangoapps/courseware/tests/tests.py index 9489ba60f8..92dde53e45 100644 --- a/lms/djangoapps/courseware/tests/tests.py +++ b/lms/djangoapps/courseware/tests/tests.py @@ -8,6 +8,7 @@ import mock from django.core.urlresolvers import reverse from nose.plugins.attrib import attr from opaque_keys.edx.keys import CourseKey +from six import text_type from courseware.tests.helpers import LoginEnrollmentTestCase from lms.djangoapps.lms_xblock.field_data import LmsFieldData @@ -75,22 +76,22 @@ class PageLoaderTestCase(LoginEnrollmentTestCase): if descriptor.location.category == 'about': self._assert_loads('about_course', - {'course_id': course_key.to_deprecated_string()}, + {'course_id': text_type(course_key)}, descriptor) elif descriptor.location.category == 'static_tab': - kwargs = {'course_id': course_key.to_deprecated_string(), + kwargs = {'course_id': text_type(course_key), 'tab_slug': descriptor.location.name} self._assert_loads('static_tab', kwargs, descriptor) elif descriptor.location.category == 'course_info': - self._assert_loads('info', {'course_id': course_key.to_deprecated_string()}, + self._assert_loads('info', {'course_id': text_type(course_key)}, descriptor) else: - kwargs = {'course_id': course_key.to_deprecated_string(), - 'location': descriptor.location.to_deprecated_string()} + kwargs = {'course_id': text_type(course_key), + 'location': text_type(descriptor.location)} self._assert_loads('jump_to', kwargs, descriptor, expect_redirect=True, diff --git a/lms/djangoapps/courseware/views/views.py b/lms/djangoapps/courseware/views/views.py index a681347261..72414bba7b 100644 --- a/lms/djangoapps/courseware/views/views.py +++ b/lms/djangoapps/courseware/views/views.py @@ -33,6 +33,7 @@ from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey from pytz import UTC from rest_framework import status +from six import text_type from web_fragments.fragment import Fragment import shoppingcart @@ -246,10 +247,10 @@ def jump_to_id(request, course_id, module_id): module_id, course_id, request.META.get("HTTP_REFERER", ""), - items[0].location.to_deprecated_string() + text_type(items[0].location) ) - return jump_to(request, course_id, items[0].location.to_deprecated_string()) + return jump_to(request, course_id, text_type(items[0].location)) @ensure_csrf_cookie @@ -303,7 +304,7 @@ def course_info(request, course_id): section_module = get_current_child(chapter_module) if section_module is not None: url = reverse('courseware_section', kwargs={ - 'course_id': unicode(course.id), + 'course_id': text_type(course.id), 'chapter': chapter_module.url_name, 'section': section_module.url_name }) @@ -337,7 +338,7 @@ def course_info(request, course_id): # If the user needs to take an entrance exam to access this course, then we'll need # to send them to that specific course module before allowing them into other areas if not user_can_skip_entrance_exam(user, course): - return redirect(reverse('courseware', args=[unicode(course.id)])) + return redirect(reverse('courseware', args=[text_type(course.id)])) # TODO: LEARNER-611: Remove deprecated course.bypass_home. # If the user is coming from the dashboard and bypass_home setting is set, @@ -367,7 +368,7 @@ def course_info(request, course_id): context = { 'request': request, 'masquerade_user': user, - 'course_id': course_key.to_deprecated_string(), + 'course_id': text_type(course_key), 'url_to_enroll': CourseTabView.url_to_enroll(course_key), 'cache': None, 'course': course, @@ -476,7 +477,7 @@ class CourseTabView(EdxFragmentView): """ Returns the URL to use to enroll in the specified course. """ - url_to_enroll = reverse('about_course', args=[unicode(course_key)]) + url_to_enroll = reverse('about_course', args=[text_type(course_key)]) if settings.FEATURES.get('ENABLE_MKTG_SITE'): url_to_enroll = marketing_link('COURSES') return url_to_enroll @@ -536,7 +537,7 @@ class CourseTabView(EdxFragmentView): request.path, getattr(user, 'real_user', user), user, - unicode(course.id), + text_type(course.id), ) try: return render_to_response( @@ -703,7 +704,7 @@ class EnrollStaffView(View): return redirect(_next) # In any other case redirect to the course about page. - return redirect(reverse('about_course', args=[unicode(course_key)])) + return redirect(reverse('about_course', args=[text_type(course_key)])) @ensure_csrf_cookie @@ -727,7 +728,7 @@ def course_about(request, course_id): modes = CourseMode.modes_for_course_dict(course_key) if configuration_helpers.get_value('ENABLE_MKTG_SITE', settings.FEATURES.get('ENABLE_MKTG_SITE', False)): - return redirect(reverse(course_home_url_name(course.id), args=[unicode(course.id)])) + return redirect(reverse(course_home_url_name(course.id), args=[text_type(course.id)])) registered = registered_for_course(course, request.user) @@ -735,9 +736,9 @@ def course_about(request, course_id): studio_url = get_studio_url(course, 'settings/details') if has_access(request.user, 'load', course): - course_target = reverse(course_home_url_name(course.id), args=[course.id.to_deprecated_string()]) + course_target = reverse(course_home_url_name(course.id), args=[text_type(course.id)]) else: - course_target = reverse('about_course', args=[course.id.to_deprecated_string()]) + course_target = reverse('about_course', args=[text_type(course.id)]) show_courseware_link = bool( ( @@ -1160,7 +1161,7 @@ def submission_history(request, course_id, student_username, location): 'scores': scores, 'username': student_username, 'location': location, - 'course_id': course_key.to_deprecated_string() + 'course_id': text_type(course_key) } return render_to_response('courseware/submission_history.html', context) @@ -1391,7 +1392,7 @@ def _track_successful_certificate_generation(user_id, course_id): # pylint: dis event_name, { 'category': 'certificates', - 'label': unicode(course_id) + 'label': text_type(course_id) }, context={ 'ip': tracking_context.get('ip'), @@ -1427,7 +1428,7 @@ def render_xblock(request, usage_key_string, check_if_enrolled=True): # get the block, which verifies whether the user has access to the block. block, _ = get_module_by_usage_id( - request, unicode(course_key), unicode(usage_key), disable_staff_debug_info=True, course=course + request, text_type(course_key), text_type(usage_key), disable_staff_debug_info=True, course=course ) student_view_context = request.GET.dict() @@ -1575,7 +1576,7 @@ def financial_assistance_form(request): 'email': user.email, 'username': user.username, 'name': user.profile.name, - 'country': unicode(user.profile.country.name), + 'country': text_type(user.profile.country.name), }, 'submit_url': reverse('submit_financial_assistance_request'), 'fields': [ @@ -1675,7 +1676,7 @@ def get_financial_aid_courses(user): financial_aid_courses.append( { 'name': enrollment.course_overview.display_name, - 'value': unicode(enrollment.course_id) + 'value': text_type(enrollment.course_id) } ) diff --git a/lms/djangoapps/dashboard/tests/test_sysadmin.py b/lms/djangoapps/dashboard/tests/test_sysadmin.py index 655d55ca8d..2b03fb289e 100644 --- a/lms/djangoapps/dashboard/tests/test_sysadmin.py +++ b/lms/djangoapps/dashboard/tests/test_sysadmin.py @@ -17,6 +17,7 @@ from django.test.utils import override_settings from pytz import UTC from nose.plugins.attrib import attr from opaque_keys.edx.keys import CourseKey +from six import text_type from dashboard.git_import import GitImportErrorNoDir from dashboard.models import CourseImportLog @@ -84,7 +85,7 @@ class SysadminBaseTestCase(SharedModuleStoreTestCase): response = self.client.post( reverse('sysadmin_courses'), { - 'course_id': course.id.to_deprecated_string(), + 'course_id': text_type(course.id), 'action': 'del_course', } ) diff --git a/lms/djangoapps/debug/management/commands/dump_xml_courses.py b/lms/djangoapps/debug/management/commands/dump_xml_courses.py index 9f4d3e388e..aebca647c2 100644 --- a/lms/djangoapps/debug/management/commands/dump_xml_courses.py +++ b/lms/djangoapps/debug/management/commands/dump_xml_courses.py @@ -14,6 +14,7 @@ import json from django.conf import settings from django.core.management.base import BaseCommand, CommandError from path import Path as path +from six import text_type from xmodule.modulestore.xml import XMLModuleStore @@ -42,7 +43,7 @@ class Command(BaseCommand): for course_id, course_modules in xml_module_store.modules.iteritems(): course_path = course_id.replace('/', '_') for location, descriptor in course_modules.iteritems(): - location_path = location.to_deprecated_string().replace('/', '_') + location_path = text_type(location).replace('/', '_') data = {} for field_name, field in descriptor.fields.iteritems(): try: diff --git a/lms/djangoapps/discussion/tests/test_views.py b/lms/djangoapps/discussion/tests/test_views.py index d89b43b8bf..02cb53c5ad 100644 --- a/lms/djangoapps/discussion/tests/test_views.py +++ b/lms/djangoapps/discussion/tests/test_views.py @@ -10,6 +10,7 @@ from django.test.utils import override_settings from django.utils import translation from mock import ANY, Mock, call, patch from nose.tools import assert_true +from six import text_type from course_modes.models import CourseMode from course_modes.tests.factories import CourseModeFactory @@ -113,7 +114,7 @@ class ViewsExceptionTestCase(UrlResetMixin, ModuleStoreTestCase): mock_from_django_user.return_value = Mock() url = reverse('user_profile', - kwargs={'course_id': self.course.id.to_deprecated_string(), 'user_id': '12345'}) # There is no user 12345 + kwargs={'course_id': text_type(self.course.id), 'user_id': '12345'}) # There is no user 12345 self.response = self.client.get(url) self.assertEqual(self.response.status_code, 404) @@ -130,7 +131,7 @@ class ViewsExceptionTestCase(UrlResetMixin, ModuleStoreTestCase): mock_from_django_user.return_value = Mock() url = reverse('followed_threads', - kwargs={'course_id': self.course.id.to_deprecated_string(), 'user_id': '12345'}) # There is no user 12345 + kwargs={'course_id': text_type(self.course.id), 'user_id': '12345'}) # There is no user 12345 self.response = self.client.get(url) self.assertEqual(self.response.status_code, 404) @@ -295,7 +296,7 @@ class SingleThreadTestCase(ForumsEnableMixin, ModuleStoreTestCase): request.user = self.student response = views.single_thread( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), "dummy_discussion_id", "test_thread_id" ) @@ -332,7 +333,7 @@ class SingleThreadTestCase(ForumsEnableMixin, ModuleStoreTestCase): request.user = self.student response = views.single_thread( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), "dummy_discussion_id", "test_thread_id" ) @@ -363,7 +364,7 @@ class SingleThreadTestCase(ForumsEnableMixin, ModuleStoreTestCase): request = RequestFactory().post("dummy_url") response = views.single_thread( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), "dummy_discussion_id", "dummy_thread_id" ) @@ -378,7 +379,7 @@ class SingleThreadTestCase(ForumsEnableMixin, ModuleStoreTestCase): Http404, views.single_thread, request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), "test_discussion_id", "test_thread_id" ) @@ -451,7 +452,7 @@ class SingleThreadQueryCountTestCase(ForumsEnableMixin, ModuleStoreTestCase): with patch.dict("django.conf.settings.FEATURES", dict(ENABLE_ENTERPRISE_INTEGRATION=enterprise_enabled)): response = views.single_thread( request, - course.id.to_deprecated_string(), + text_type(course.id), "dummy_discussion_id", test_thread_id ) @@ -491,7 +492,7 @@ class SingleCohortedThreadTestCase(CohortedTestCase): request.user = self.student response = views.single_thread( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), "cohorted_topic", self.mock_thread_id ) @@ -551,7 +552,7 @@ class SingleThreadAccessTestCase(CohortedTestCase): request.user = user return views.single_thread( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), commentable_id, thread_id ) @@ -847,7 +848,7 @@ class InlineDiscussionGroupIdTestCase( request.user = user return views.inline_discussion( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), commentable_id ) @@ -1091,7 +1092,7 @@ class FollowedThreadsDiscussionGroupIdTestCase(CohortedTestCase, CohortedTopicGr request.user = user return views.followed_threads( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), user.id ) @@ -1135,7 +1136,7 @@ class InlineDiscussionTestCase(ForumsEnableMixin, ModuleStoreTestCase): course=self.course, text="dummy content", commentable_id=self.discussion1.discussion_id ) return views.inline_discussion( - request, self.course.id.to_deprecated_string(), self.discussion1.discussion_id + request, text_type(self.course.id), self.discussion1.discussion_id ) def verify_response(self, response): @@ -1198,7 +1199,7 @@ class UserProfileTestCase(ForumsEnableMixin, UrlResetMixin, ModuleStoreTestCase) StringEndsWithMatcher('/users/{}/active_threads'.format(self.profiled_user.id)), data=None, params=PartialDictMatcher({ - "course_id": self.course.id.to_deprecated_string(), + "course_id": text_type(self.course.id), "page": params.get("page", 1), "per_page": views.THREADS_PER_PAGE }), @@ -1254,7 +1255,7 @@ class UserProfileTestCase(ForumsEnableMixin, UrlResetMixin, ModuleStoreTestCase) with self.assertRaises(Http404): views.user_profile( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), unenrolled_user.id ) @@ -1264,7 +1265,7 @@ class UserProfileTestCase(ForumsEnableMixin, UrlResetMixin, ModuleStoreTestCase) with self.assertRaises(Http404): views.user_profile( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), -999 ) @@ -1286,7 +1287,7 @@ class UserProfileTestCase(ForumsEnableMixin, UrlResetMixin, ModuleStoreTestCase) request.user = self.student response = views.user_profile( request, - self.course.id.to_deprecated_string(), + text_type(self.course.id), self.profiled_user.id ) self.assertEqual(response.status_code, 405) @@ -1337,7 +1338,7 @@ class CommentsServiceRequestHeadersTestCase(ForumsEnableMixin, UrlResetMixin, Mo reverse( "single_thread", kwargs={ - "course_id": self.course.id.to_deprecated_string(), + "course_id": text_type(self.course.id), "discussion_id": "dummy_discussion_id", "thread_id": thread_id, } @@ -1353,7 +1354,7 @@ class CommentsServiceRequestHeadersTestCase(ForumsEnableMixin, UrlResetMixin, Mo self.client.get( reverse( "forum_form_discussion", - kwargs={"course_id": self.course.id.to_deprecated_string()} + kwargs={"course_id": text_type(self.course.id)} ), ) self.assert_all_calls_have_header(mock_request, "X-Edx-Api-Key", "test_api_key") @@ -1384,7 +1385,7 @@ class InlineDiscussionUnicodeTestCase(ForumsEnableMixin, SharedModuleStoreTestCa request.user = self.student response = views.inline_discussion( - request, self.course.id.to_deprecated_string(), self.course.discussion_topics['General']['id'] + request, text_type(self.course.id), self.course.discussion_topics['General']['id'] ) self.assertEqual(response.status_code, 200) response_data = json.loads(response.content) @@ -1416,7 +1417,7 @@ class ForumFormDiscussionUnicodeTestCase(ForumsEnableMixin, SharedModuleStoreTes request.user = self.student request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" # so request.is_ajax() == True - response = views.forum_form_discussion(request, self.course.id.to_deprecated_string()) + response = views.forum_form_discussion(request, text_type(self.course.id)) self.assertEqual(response.status_code, 200) response_data = json.loads(response.content) self.assertEqual(response_data["discussion_data"][0]["title"], text) @@ -1503,7 +1504,7 @@ class ForumDiscussionSearchUnicodeTestCase(ForumsEnableMixin, SharedModuleStoreT request.user = self.student request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" # so request.is_ajax() == True - response = views.forum_form_discussion(request, self.course.id.to_deprecated_string()) + response = views.forum_form_discussion(request, text_type(self.course.id)) self.assertEqual(response.status_code, 200) response_data = json.loads(response.content) self.assertEqual(response_data["discussion_data"][0]["title"], text) @@ -1536,7 +1537,7 @@ class SingleThreadUnicodeTestCase(ForumsEnableMixin, SharedModuleStoreTestCase, request.user = self.student request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" # so request.is_ajax() == True - response = views.single_thread(request, self.course.id.to_deprecated_string(), "dummy_discussion_id", thread_id) + response = views.single_thread(request, text_type(self.course.id), "dummy_discussion_id", thread_id) self.assertEqual(response.status_code, 200) response_data = json.loads(response.content) self.assertEqual(response_data["content"]["title"], text) @@ -1568,7 +1569,7 @@ class UserProfileUnicodeTestCase(ForumsEnableMixin, SharedModuleStoreTestCase, U request.user = self.student request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" # so request.is_ajax() == True - response = views.user_profile(request, self.course.id.to_deprecated_string(), str(self.student.id)) + response = views.user_profile(request, text_type(self.course.id), str(self.student.id)) self.assertEqual(response.status_code, 200) response_data = json.loads(response.content) self.assertEqual(response_data["discussion_data"][0]["title"], text) @@ -1600,7 +1601,7 @@ class FollowedThreadsUnicodeTestCase(ForumsEnableMixin, SharedModuleStoreTestCas request.user = self.student request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" # so request.is_ajax() == True - response = views.followed_threads(request, self.course.id.to_deprecated_string(), str(self.student.id)) + response = views.followed_threads(request, text_type(self.course.id), str(self.student.id)) self.assertEqual(response.status_code, 200) response_data = json.loads(response.content) self.assertEqual(response_data["discussion_data"][0]["title"], text) @@ -1626,7 +1627,7 @@ class EnrollmentTestCase(ForumsEnableMixin, ModuleStoreTestCase): request = RequestFactory().get('dummy_url') request.user = self.student with self.assertRaises(CourseAccessRedirect): - views.forum_form_discussion(request, course_id=self.course.id.to_deprecated_string()) + views.forum_form_discussion(request, course_id=text_type(self.course.id)) @patch('requests.request', autospec=True) diff --git a/lms/djangoapps/django_comment_client/base/tests.py b/lms/djangoapps/django_comment_client/base/tests.py index 90f625d969..64c482239e 100644 --- a/lms/djangoapps/django_comment_client/base/tests.py +++ b/lms/djangoapps/django_comment_client/base/tests.py @@ -16,6 +16,7 @@ from mock import ANY, Mock, patch from nose.plugins.attrib import attr from nose.tools import assert_equal, assert_true from opaque_keys.edx.keys import CourseKey +from six import text_type from common.test.utils import MockSignalHandlerMixin, disable_signal from course_modes.models import CourseMode @@ -1970,7 +1971,7 @@ class UsersEndpointTestCase(ForumsEnableMixin, SharedModuleStoreTestCase, MockRe request = getattr(RequestFactory(), method)("dummy_url", kwargs) request.user = self.student request.view_name = "users" - return views.users(request, course_id=course_id.to_deprecated_string()) + return views.users(request, course_id=text_type(course_id)) @patch('lms.lib.comment_client.utils.requests.request', autospec=True) def test_finds_exact_match(self, mock_request): diff --git a/lms/djangoapps/django_comment_client/base/views.py b/lms/djangoapps/django_comment_client/base/views.py index f646d3d40e..9234096f7e 100644 --- a/lms/djangoapps/django_comment_client/base/views.py +++ b/lms/djangoapps/django_comment_client/base/views.py @@ -13,6 +13,7 @@ from django.utils.translation import ugettext as _ from django.views.decorators import csrf from django.views.decorators.http import require_GET, require_POST from opaque_keys.edx.keys import CourseKey +from six import text_type import django_comment_client.settings as cc_settings import lms.lib.comment_client as cc @@ -256,7 +257,7 @@ def create_thread(request, course_id, commentable_id): 'anonymous': anonymous, 'anonymous_to_peers': anonymous_to_peers, 'commentable_id': commentable_id, - 'course_id': course_key.to_deprecated_string(), + 'course_id': text_type(course_key), 'user_id': user.id, 'thread_type': post["thread_type"], 'body': post["body"], @@ -374,7 +375,7 @@ def _create_comment(request, course_key, thread_id=None, parent_id=None): anonymous=anonymous, anonymous_to_peers=anonymous_to_peers, user_id=user.id, - course_id=course_key.to_deprecated_string(), + course_id=text_type(course_key), thread_id=thread_id, parent_id=parent_id, body=post["body"] diff --git a/lms/djangoapps/django_comment_client/tests/test_utils.py b/lms/djangoapps/django_comment_client/tests/test_utils.py index 4070545df9..5bf1d56e08 100644 --- a/lms/djangoapps/django_comment_client/tests/test_utils.py +++ b/lms/djangoapps/django_comment_client/tests/test_utils.py @@ -11,6 +11,7 @@ from django.test import RequestFactory, TestCase from mock import Mock, patch from nose.plugins.attrib import attr from pytz import UTC +from six import text_type import django_comment_client.utils as utils from course_modes.models import CourseMode @@ -180,8 +181,8 @@ class CoursewareContextTestCase(ModuleStoreTestCase): reverse( "jump_to", kwargs={ - "course_id": self.course.id.to_deprecated_string(), - "location": discussion.location.to_deprecated_string() + "course_id": text_type(self.course.id), + "location": text_type(discussion.location) } ) ) diff --git a/lms/djangoapps/grades/config/forms.py b/lms/djangoapps/grades/config/forms.py index d1561c46d0..4c72b57995 100644 --- a/lms/djangoapps/grades/config/forms.py +++ b/lms/djangoapps/grades/config/forms.py @@ -6,6 +6,7 @@ import logging from django import forms from opaque_keys import InvalidKeyError from opaque_keys.edx.locator import CourseLocator +from six import text_type from lms.djangoapps.grades.config.models import CoursePersistentGradesFlag from xmodule.modulestore.django import modulestore @@ -30,7 +31,7 @@ class CoursePersistentGradesAdminForm(forms.ModelForm): raise forms.ValidationError(msg) if not modulestore().has_course(course_key): - msg = u'Course not found. Entered course id was: "{0}". '.format(course_key.to_deprecated_string()) + msg = u'Course not found. Entered course id was: "{0}". '.format(text_type(course_key)) raise forms.ValidationError(msg) return course_key diff --git a/lms/djangoapps/grades/config/models.py b/lms/djangoapps/grades/config/models.py index 647ce30388..4bf868a6fd 100644 --- a/lms/djangoapps/grades/config/models.py +++ b/lms/djangoapps/grades/config/models.py @@ -5,6 +5,7 @@ controlling persistent grades. from config_models.models import ConfigurationModel from django.conf import settings from django.db.models import BooleanField, IntegerField, TextField +from six import text_type from openedx.core.djangoapps.xmodule_django.models import CourseKeyField from request_cache.middleware import request_cached @@ -71,7 +72,7 @@ class CoursePersistentGradesFlag(ConfigurationModel): if self.enabled: not_en = "" # pylint: disable=no-member - return u"Course '{}': Persistent Grades {}Enabled".format(self.course_id.to_deprecated_string(), not_en) + return u"Course '{}': Persistent Grades {}Enabled".format(text_type(self.course_id), not_en) class ComputeGradesSetting(ConfigurationModel): diff --git a/lms/djangoapps/instructor/tests/test_api_email_localization.py b/lms/djangoapps/instructor/tests/test_api_email_localization.py index 7ab9ab5e08..c48f843f49 100644 --- a/lms/djangoapps/instructor/tests/test_api_email_localization.py +++ b/lms/djangoapps/instructor/tests/test_api_email_localization.py @@ -7,6 +7,7 @@ from django.core import mail from django.core.urlresolvers import reverse from django.test.utils import override_settings from nose.plugins.attrib import attr +from six import text_type from courseware.tests.factories import InstructorFactory from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY @@ -45,7 +46,7 @@ class TestInstructorAPIEnrollmentEmailLocalization(SharedModuleStoreTestCase): """ Update the current student enrollment status. """ - url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()}) + url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) args = {'identifiers': student_email, 'email_students': 'true', 'action': action, 'reason': 'testing'} response = self.client.post(url, args) return response @@ -81,7 +82,7 @@ class TestInstructorAPIEnrollmentEmailLocalization(SharedModuleStoreTestCase): self.check_outbox_is_french() def test_set_beta_role(self): - url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) + url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) self.client.post(url, {'identifiers': self.student.email, 'action': 'add', 'email_students': 'true'}) self.check_outbox_is_french() diff --git a/lms/djangoapps/instructor/tests/test_ecommerce.py b/lms/djangoapps/instructor/tests/test_ecommerce.py index 86c28c38f5..2bc2f6b19c 100644 --- a/lms/djangoapps/instructor/tests/test_ecommerce.py +++ b/lms/djangoapps/instructor/tests/test_ecommerce.py @@ -7,6 +7,7 @@ import datetime import pytz from django.core.urlresolvers import reverse from nose.plugins.attrib import attr +from six import text_type from course_modes.models import CourseMode from openedx.core.djangoapps.site_configuration.tests.mixins import SiteMixin @@ -28,7 +29,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): cls.course = CourseFactory.create() # URL for instructor dash - cls.url = reverse('instructor_dashboard', kwargs={'course_id': cls.course.id.to_deprecated_string()}) + cls.url = reverse('instructor_dashboard', kwargs={'course_id': text_type(cls.course.id)}) cls.ecommerce_link = '' def setUp(self): @@ -38,7 +39,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): self.instructor = AdminFactory.create() self.client.login(username=self.instructor.username, password="test") mode = CourseMode( - course_id=self.course.id.to_deprecated_string(), mode_slug='honor', + course_id=text_type(self.course.id), mode_slug='honor', mode_display_name='honor', min_price=10, currency='usd' ) mode.save() @@ -85,7 +86,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): CourseFinanceAdminRole(self.course.id).remove_users(self.instructor) # Order/Invoice sales csv button text should not be visible in e-commerce page if the user is not finance admin - url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url) self.assertNotIn('Download All Invoices', response.content) @@ -108,7 +109,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): CourseFinanceAdminRole(self.course.id).remove_users(self.instructor) # total amount should not be visible in e-commerce page if the user is not finance admin - url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) response = self.client.get(url) self.assertNotIn('+ Set Price', response.content) @@ -117,20 +118,20 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): # course B course2 = CourseFactory.create(org='EDX', display_name='test_course', number='100') mode = CourseMode( - course_id=course2.id.to_deprecated_string(), mode_slug='honor', + course_id=text_type(course2.id), mode_slug='honor', mode_display_name='honor', min_price=30, currency='usd' ) mode.save() # course A update CourseMode.objects.filter(course_id=self.course.id).update(min_price=price) - set_course_price_url = reverse('set_course_mode_price', kwargs={'course_id': self.course.id.to_deprecated_string()}) + set_course_price_url = reverse('set_course_mode_price', kwargs={'course_id': text_type(self.course.id)}) data = {'course_price': price, 'currency': 'usd'} response = self.client.post(set_course_price_url, data) self.assertIn('CourseMode price updated successfully', response.content) # Course A updated total amount should be visible in e-commerce page if the user is finance admin - url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) + url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) response = self.client.get(url) self.assertIn('Course price per seat: $' + str(price) + '', response.content) @@ -140,7 +141,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): test to set the course price related functionality. test al the scenarios for setting a new course price """ - set_course_price_url = reverse('set_course_mode_price', kwargs={'course_id': self.course.id.to_deprecated_string()}) + set_course_price_url = reverse('set_course_mode_price', kwargs={'course_id': text_type(self.course.id)}) data = {'course_price': '12%', 'currency': 'usd'} # Value Error course price should be a numeric value @@ -166,11 +167,11 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): Test Add Coupon Scenarios. Handle all the HttpResponses return by add_coupon view """ # URL for add_coupon - add_coupon_url = reverse('add_coupon', kwargs={'course_id': self.course.id.to_deprecated_string()}) + add_coupon_url = reverse('add_coupon', kwargs={'course_id': text_type(self.course.id)}) expiration_date = datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=2) data = { - 'code': 'A2314', 'course_id': self.course.id.to_deprecated_string(), + 'code': 'A2314', 'course_id': text_type(self.course.id), 'description': 'ADSADASDSAD', 'created_by': self.instructor, 'discount': 5, 'expiration_date': '{month}/{day}/{year}'.format( month=expiration_date.month, day=expiration_date.day, year=expiration_date.year @@ -185,7 +186,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): #now add the coupon with the wrong value in the expiration_date # server will through the ValueError Exception in the expiration_date field data = { - 'code': '213454', 'course_id': self.course.id.to_deprecated_string(), + 'code': '213454', 'course_id': text_type(self.course.id), 'description': 'ADSADASDSAD', 'created_by': self.instructor, 'discount': 5, 'expiration_date': expiration_date.strftime('"%d/%m/%Y') } @@ -193,7 +194,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): self.assertIn("Please enter the date in this format i-e month/day/year", response.content) data = { - 'code': 'A2314', 'course_id': self.course.id.to_deprecated_string(), + 'code': 'A2314', 'course_id': text_type(self.course.id), 'description': 'asdsasda', 'created_by': self.instructor, 'discount': 99 } response = self.client.post(add_coupon_url, data) @@ -205,7 +206,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): self.assertNotIn('111', response.content) data = { - 'code': 'A2345314', 'course_id': self.course.id.to_deprecated_string(), + 'code': 'A2345314', 'course_id': text_type(self.course.id), 'description': 'asdsasda', 'created_by': self.instructor, 'discount': 199 } response = self.client.post(add_coupon_url, data) @@ -216,7 +217,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): self.assertIn('Please Enter the Integer Value for Coupon Discount', response.content) course_registration = CourseRegistrationCode( - code='Vs23Ws4j', course_id=unicode(self.course.id), created_by=self.instructor, + code='Vs23Ws4j', course_id=text_type(self.course.id), created_by=self.instructor, mode_slug='honor' ) course_registration.save() @@ -231,7 +232,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): Test Delete Coupon Scenarios. Handle all the HttpResponses return by remove_coupon view """ coupon = Coupon( - code='AS452', description='asdsadsa', course_id=self.course.id.to_deprecated_string(), + code='AS452', description='asdsadsa', course_id=text_type(self.course.id), percentage_discount=10, created_by=self.instructor ) @@ -241,7 +242,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): self.assertIn('AS452', response.content) # URL for remove_coupon - delete_coupon_url = reverse('remove_coupon', kwargs={'course_id': self.course.id.to_deprecated_string()}) + delete_coupon_url = reverse('remove_coupon', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(delete_coupon_url, {'id': coupon.id}) self.assertIn( 'coupon with the coupon id ({coupon_id}) updated successfully'.format(coupon_id=coupon.id), @@ -271,13 +272,13 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): Test Edit Coupon Info Scenarios. Handle all the HttpResponses return by edit_coupon_info view """ coupon = Coupon( - code='AS452', description='asdsadsa', course_id=self.course.id.to_deprecated_string(), + code='AS452', description='asdsadsa', course_id=text_type(self.course.id), percentage_discount=10, created_by=self.instructor, expiration_date=datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=2) ) coupon.save() # URL for edit_coupon_info - edit_url = reverse('get_coupon_info', kwargs={'course_id': self.course.id.to_deprecated_string()}) + edit_url = reverse('get_coupon_info', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(edit_url, {'id': coupon.id}) self.assertIn( 'coupon with the coupon id ({coupon_id}) updated successfully'.format(coupon_id=coupon.id), @@ -308,7 +309,7 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): Test Update Coupon Info Scenarios. Handle all the HttpResponses return by update_coupon view """ coupon = Coupon( - code='AS452', description='asdsadsa', course_id=self.course.id.to_deprecated_string(), + code='AS452', description='asdsadsa', course_id=text_type(self.course.id), percentage_discount=10, created_by=self.instructor ) coupon.save() @@ -316,10 +317,10 @@ class TestECommerceDashboardViews(SiteMixin, SharedModuleStoreTestCase): self.assertIn('AS452', response.content) data = { 'coupon_id': coupon.id, 'code': 'AS452', 'discount': '10', 'description': 'updated_description', - 'course_id': coupon.course_id.to_deprecated_string() + 'course_id': text_type(coupon.course_id) } # URL for update_coupon - update_coupon_url = reverse('update_coupon', kwargs={'course_id': self.course.id.to_deprecated_string()}) + update_coupon_url = reverse('update_coupon', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(update_coupon_url, data=data) self.assertIn( 'coupon with the coupon id ({coupon_id}) updated Successfully'.format(coupon_id=coupon.id), diff --git a/lms/djangoapps/instructor/tests/test_email.py b/lms/djangoapps/instructor/tests/test_email.py index 4a0b89ffd4..a889f62b6c 100644 --- a/lms/djangoapps/instructor/tests/test_email.py +++ b/lms/djangoapps/instructor/tests/test_email.py @@ -8,6 +8,7 @@ that the view is conditionally available when Course Auth is turned on. from django.core.urlresolvers import reverse from nose.plugins.attrib import attr from opaque_keys.edx.keys import CourseKey +from six import text_type from bulk_email.models import BulkEmailFlag, CourseAuthorization from student.tests.factories import AdminFactory @@ -27,7 +28,7 @@ class TestNewInstructorDashboardEmailViewMongoBacked(SharedModuleStoreTestCase): cls.course = CourseFactory.create() # URL for instructor dash - cls.url = reverse('instructor_dashboard', kwargs={'course_id': cls.course.id.to_deprecated_string()}) + cls.url = reverse('instructor_dashboard', kwargs={'course_id': text_type(cls.course.id)}) # URL for email view cls.email_link = '' @@ -122,7 +123,7 @@ class TestNewInstructorDashboardEmailViewXMLBacked(SharedModuleStoreTestCase): cls.course_key = CourseKey.from_string('edX/toy/2012_Fall') # URL for instructor dash - cls.url = reverse('instructor_dashboard', kwargs={'course_id': unicode(cls.course_key)}) + cls.url = reverse('instructor_dashboard', kwargs={'course_id': text_type(cls.course_key)}) # URL for email view cls.email_link = '' @@ -134,7 +135,7 @@ class TestNewInstructorDashboardEmailViewXMLBacked(SharedModuleStoreTestCase): self.client.login(username=instructor.username, password="test") # URL for instructor dash - self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course_key.to_deprecated_string()}) + self.url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course_key)}) # URL for email view self.email_link = '' diff --git a/lms/djangoapps/instructor/tests/test_enrollment.py b/lms/djangoapps/instructor/tests/test_enrollment.py index 14f63a6027..0271e34bff 100644 --- a/lms/djangoapps/instructor/tests/test_enrollment.py +++ b/lms/djangoapps/instructor/tests/test_enrollment.py @@ -14,6 +14,7 @@ from django.utils.translation import get_language from mock import patch from nose.plugins.attrib import attr from opaque_keys.edx.locator import CourseLocator +from six import text_type from capa.tests.response_xml_factory import MultipleChoiceResponseXMLFactory from courseware.models import StudentModule @@ -417,8 +418,8 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): # Create a submission and score for the student using the submissions API student_item = { 'student_id': anonymous_id_for_user(user, self.course_key), - 'course_id': self.course_key.to_deprecated_string(), - 'item_id': problem_location.to_deprecated_string(), + 'course_id': text_type(self.course_key), + 'item_id': text_type(problem_location), 'item_type': 'openassessment' } submission = sub_api.create_submission(student_item, 'test answer') @@ -727,7 +728,7 @@ class TestGetEmailParams(SharedModuleStoreTestCase): site = settings.SITE_NAME cls.course_url = u'https://{}/courses/{}/'.format( site, - cls.course.id.to_deprecated_string() + text_type(cls.course.id) ) cls.course_about_url = cls.course_url + 'about' cls.registration_url = u'https://{}/register'.format(site) diff --git a/lms/djangoapps/instructor/tests/test_proctoring.py b/lms/djangoapps/instructor/tests/test_proctoring.py index 6dc03d187b..ef1506cec2 100644 --- a/lms/djangoapps/instructor/tests/test_proctoring.py +++ b/lms/djangoapps/instructor/tests/test_proctoring.py @@ -7,6 +7,7 @@ from django.conf import settings from django.core.urlresolvers import reverse from mock import patch from nose.plugins.attrib import attr +from six import text_type from student.roles import CourseStaffRole, CourseInstructorRole from student.tests.factories import AdminFactory @@ -38,7 +39,7 @@ class TestProctoringDashboardViews(SharedModuleStoreTestCase): """ Create URL for instructor dashboard """ - self.url = reverse('instructor_dashboard', kwargs={'course_id': course.id.to_deprecated_string()}) + self.url = reverse('instructor_dashboard', kwargs={'course_id': text_type(course.id)}) def setup_course(self, enable_proctored_exams, enable_timed_exams): """ diff --git a/lms/djangoapps/instructor/tests/test_registration_codes.py b/lms/djangoapps/instructor/tests/test_registration_codes.py index 64f52cc38e..9c7e7bde73 100644 --- a/lms/djangoapps/instructor/tests/test_registration_codes.py +++ b/lms/djangoapps/instructor/tests/test_registration_codes.py @@ -7,6 +7,7 @@ from django.core.urlresolvers import reverse from django.test.utils import override_settings from django.utils.translation import ugettext as _ from nose.plugins.attrib import attr +from six import text_type from course_modes.models import CourseMode from course_modes.tests.factories import CourseModeFactory @@ -57,13 +58,13 @@ class TestCourseRegistrationCodeStatus(SharedModuleStoreTestCase): course_id=self.course.id ) self.lookup_code_url = reverse('look_up_registration_code', - kwargs={'course_id': unicode(self.course.id)}) + kwargs={'course_id': text_type(self.course.id)}) self.registration_code_detail_url = reverse('registration_code_details', - kwargs={'course_id': unicode(self.course.id)}) + kwargs={'course_id': text_type(self.course.id)}) url = reverse('generate_registration_codes', - kwargs={'course_id': self.course.id.to_deprecated_string()}) + kwargs={'course_id': text_type(self.course.id)}) data = { 'total_registration_codes': 12, @@ -251,7 +252,7 @@ class TestCourseRegistrationCodeStatus(SharedModuleStoreTestCase): for i in range(2): CourseRegistrationCode.objects.create( code='reg_code{}'.format(i), - course_id=self.course.id.to_deprecated_string(), + course_id=text_type(self.course.id), created_by=self.instructor, invoice=self.sale_invoice, invoice_item=self.invoice_item, @@ -282,7 +283,7 @@ class TestCourseRegistrationCodeStatus(SharedModuleStoreTestCase): for i in range(2): CourseRegistrationCode.objects.create( code='reg_code{}'.format(i), - course_id=self.course.id.to_deprecated_string(), + course_id=text_type(self.course.id), created_by=self.instructor, invoice=self.sale_invoice, invoice_item=self.invoice_item, diff --git a/lms/djangoapps/instructor/tests/test_spoc_gradebook.py b/lms/djangoapps/instructor/tests/test_spoc_gradebook.py index a0a50a44c8..ec16a13dc3 100644 --- a/lms/djangoapps/instructor/tests/test_spoc_gradebook.py +++ b/lms/djangoapps/instructor/tests/test_spoc_gradebook.py @@ -4,6 +4,7 @@ Tests of the instructor dashboard spoc gradebook from django.core.urlresolvers import reverse from nose.plugins.attrib import attr +from six import text_type from capa.tests.response_xml_factory import StringResponseXMLFactory from courseware.tests.factories import StudentModuleFactory @@ -74,11 +75,11 @@ class TestGradebook(SharedModuleStoreTestCase): course_id=self.course.id, module_state_key=item.location ) - compute_all_grades_for_course.apply_async(kwargs={'course_key': unicode(self.course.id)}) + compute_all_grades_for_course.apply_async(kwargs={'course_key': text_type(self.course.id)}) self.response = self.client.get(reverse( 'spoc_gradebook', - args=(self.course.id.to_deprecated_string(),) + args=(text_type(self.course.id),) )) self.assertEquals(self.response.status_code, 200) @@ -92,7 +93,7 @@ class TestDefaultGradingPolicy(TestGradebook): """ def test_all_users_listed(self): for user in self.users: - self.assertIn(user.username, unicode(self.response.content, 'utf-8')) + self.assertIn(user.username, text_type(self.response.content, 'utf-8')) def test_default_policy(self): # Default >= 50% passes, so Users 5-10 should be passing for Homework 1 [6] diff --git a/lms/djangoapps/instructor/tests/test_tools.py b/lms/djangoapps/instructor/tests/test_tools.py index 0754dd2036..7d05da99dd 100644 --- a/lms/djangoapps/instructor/tests/test_tools.py +++ b/lms/djangoapps/instructor/tests/test_tools.py @@ -7,11 +7,13 @@ import json import unittest import mock +import six from django.test import TestCase from django.test.utils import override_settings from pytz import UTC from nose.plugins.attrib import attr from opaque_keys.edx.keys import CourseKey +from six import text_type from courseware.field_overrides import OverrideFieldData from lms.djangoapps.ccx.tests.test_overrides import inject_field_overrides @@ -120,7 +122,7 @@ class TestFindUnit(SharedModuleStoreTestCase): """ Test finding a nested unit. """ - url = self.homework.location.to_deprecated_string() + url = text_type(self.homework.location) found_unit = tools.find_unit(self.course, url) self.assertEqual(found_unit.location, self.homework.location) @@ -161,8 +163,10 @@ class TestGetUnitsWithDueDate(ModuleStoreTestCase): def test_it(self): def urls(seq): - "URLs for sequence of nodes." - return sorted(i.location.to_deprecated_string() for i in seq) + """ + URLs for sequence of nodes. + """ + return sorted(text_type(i.location) for i in seq) self.assertEquals( urls(tools.get_units_with_due_date(self.course)), @@ -179,9 +183,18 @@ class TestTitleOrUrl(unittest.TestCase): self.assertEquals(tools.title_or_url(unit), 'hello') def test_url(self): + def mock_location_text(self): + """ + Mock implementation of __unicode__ or __str__ for the unit's location. + """ + return u'test:hello' + unit = mock.Mock(display_name=None) - unit.location.to_deprecated_string.return_value = 'test:hello' - self.assertEquals(tools.title_or_url(unit), 'test:hello') + if six.PY2: + unit.location.__unicode__ = mock_location_text + else: + unit.location.__str__ = mock_location_text + self.assertEquals(tools.title_or_url(unit), u'test:hello') @attr(shard=1) diff --git a/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py b/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py index 1c970e11dd..b073b8019f 100644 --- a/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py +++ b/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py @@ -11,6 +11,7 @@ from django.test.utils import override_settings from mock import patch from nose.plugins.attrib import attr from pytz import UTC +from six import text_type from common.test.utils import XssTestMixin from course_modes.models import CourseMode @@ -71,21 +72,21 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT self.client.login(username=self.instructor.username, password="test") # URL for instructor dash - self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) + self.url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)}) def get_dashboard_enrollment_message(self): """ Returns expected dashboard enrollment message with link to Insights. """ return 'Enrollment data is now available in Example.'.format(unicode(self.course.id)) + 'target="_blank">Example.'.format(text_type(self.course.id)) def get_dashboard_analytics_message(self): """ Returns expected dashboard demographic message with link to Insights. """ return 'For analytics about your course, go to Example.'.format(unicode(self.course.id)) + 'target="_blank">Example.'.format(text_type(self.course.id)) def test_instructor_tab(self): """ diff --git a/lms/djangoapps/instructor/views/api.py b/lms/djangoapps/instructor/views/api.py index 196e16ea62..d1e47e730b 100644 --- a/lms/djangoapps/instructor/views/api.py +++ b/lms/djangoapps/instructor/views/api.py @@ -32,6 +32,7 @@ from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.http import require_http_methods, require_POST from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey +from six import text_type import instructor_analytics.basic import instructor_analytics.csvs @@ -952,7 +953,7 @@ def list_course_role_members(request, course_id): } response_payload = { - 'course_id': course_id.to_deprecated_string(), + 'course_id': text_type(course_id), rolename: map(extract_user_info, list_with_level( course, rolename )), @@ -1014,7 +1015,7 @@ def get_grading_config(request, course_id): grading_config_summary = instructor_analytics.basic.dump_grading_context(course) response_payload = { - 'course_id': course_id.to_deprecated_string(), + 'course_id': text_type(course_id), 'grading_config_summary': grading_config_summary, } return JsonResponse(response_payload) @@ -1041,7 +1042,7 @@ def get_sale_records(request, course_id, csv=False): # pylint: disable=unused-a item['created_by'] = item['created_by'].username response_payload = { - 'course_id': course_id.to_deprecated_string(), + 'course_id': text_type(course_id), 'sale': sale_data, 'queried_features': query_features } @@ -1669,7 +1670,7 @@ def generate_registration_codes(request, course_id): discount = (float(quantity * course_price) - float(sale_price)) course_url = '{base_url}{course_about}'.format( base_url=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), - course_about=reverse('about_course', kwargs={'course_id': course_id.to_deprecated_string()}) + course_about=reverse('about_course', kwargs={'course_id': text_type(course_id)}) ) dashboard_url = '{base_url}{dashboard}'.format( base_url=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), @@ -1821,14 +1822,14 @@ def get_anon_ids(request, course_id): # pylint: disable=unused-argument def csv_response(filename, header, rows): """Returns a CSV http response for the given header and rows (excel/utf-8).""" response = HttpResponse(content_type='text/csv') - response['Content-Disposition'] = 'attachment; filename={0}'.format(unicode(filename).encode('utf-8')) + response['Content-Disposition'] = 'attachment; filename={0}'.format(text_type(filename).encode('utf-8')) writer = csv.writer(response, dialect='excel', quotechar='"', quoting=csv.QUOTE_ALL) # In practice, there should not be non-ascii data in this query, # but trying to do the right thing anyway. - encoded = [unicode(s).encode('utf-8') for s in header] + encoded = [text_type(s).encode('utf-8') for s in header] writer.writerow(encoded) for row in rows: - encoded = [unicode(s).encode('utf-8') for s in row] + encoded = [text_type(s).encode('utf-8') for s in row] writer.writerow(encoded) return response @@ -1837,7 +1838,7 @@ def get_anon_ids(request, course_id): # pylint: disable=unused-argument ).order_by('id') header = ['User ID', 'Anonymized User ID', 'Course Specific Anonymized User ID'] rows = [[s.id, unique_id_for_user(s, save=False), anonymous_id_for_user(s, course_id, save=False)] for s in students] - return csv_response(course_id.to_deprecated_string().replace('/', '-') + '-anon-ids.csv', header, rows) + return csv_response(text_type(course_id).replace('/', '-') + '-anon-ids.csv', header, rows) @require_POST @@ -1861,10 +1862,10 @@ def get_student_progress_url(request, course_id): course_id = CourseKey.from_string(course_id) user = get_student_from_identifier(request.POST.get('unique_student_identifier')) - progress_url = reverse('student_progress', kwargs={'course_id': course_id.to_deprecated_string(), 'student_id': user.id}) + progress_url = reverse('student_progress', kwargs={'course_id': text_type(course_id), 'student_id': user.id}) response_payload = { - 'course_id': course_id.to_deprecated_string(), + 'course_id': text_type(course_id), 'progress_url': progress_url, } return JsonResponse(response_payload) @@ -2513,7 +2514,7 @@ def list_forum_members(request, course_id): } response_payload = { - 'course_id': course_id.to_deprecated_string(), + 'course_id': text_type(course_id), rolename: map(extract_user_info, users), 'division_scheme': course_discussion_settings.division_scheme, } @@ -2590,7 +2591,7 @@ def send_email(request, course_id): lms.djangoapps.instructor_task.api.submit_bulk_course_email(request, course_id, email.id) response_payload = { - 'course_id': course_id.to_deprecated_string(), + 'course_id': text_type(course_id), 'success': True, } @@ -2657,7 +2658,7 @@ def update_forum_role_membership(request, course_id): return HttpResponseBadRequest("Role does not exist.") response_payload = { - 'course_id': course_id.to_deprecated_string(), + 'course_id': text_type(course_id), 'action': action, } return JsonResponse(response_payload) @@ -2684,9 +2685,9 @@ def _display_unit(unit): """ name = getattr(unit, 'display_name', None) if name: - return u'{0} ({1})'.format(name, unit.location.to_deprecated_string()) + return u'{0} ({1})'.format(name, text_type(unit.location)) else: - return unit.location.to_deprecated_string() + return text_type(unit.location) @handle_dashboard_error diff --git a/lms/djangoapps/instructor/views/coupons.py b/lms/djangoapps/instructor/views/coupons.py index bf17c234c6..cd49e33c40 100644 --- a/lms/djangoapps/instructor/views/coupons.py +++ b/lms/djangoapps/instructor/views/coupons.py @@ -10,6 +10,7 @@ from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ from django.views.decorators.http import require_POST from opaque_keys.edx.locator import CourseKey +from six import text_type from shoppingcart.models import Coupon, CourseRegistrationCode from util.json_request import JsonResponse @@ -161,7 +162,7 @@ def get_coupon_info(request, course_id): # pylint: disable=unused-argument return JsonResponse({ 'coupon_code': coupon.code, 'coupon_description': coupon.description, - 'coupon_course_id': coupon.course_id.to_deprecated_string(), + 'coupon_course_id': text_type(coupon.course_id), 'coupon_discount': coupon.percentage_discount, 'expiry_date': expiry_date, 'message': _('coupon with the coupon id ({coupon_id}) updated successfully').format(coupon_id=coupon_id) diff --git a/lms/djangoapps/instructor/views/tools.py b/lms/djangoapps/instructor/views/tools.py index 25f843e007..7484279d10 100644 --- a/lms/djangoapps/instructor/views/tools.py +++ b/lms/djangoapps/instructor/views/tools.py @@ -9,6 +9,7 @@ from django.http import HttpResponseBadRequest from pytz import UTC from django.utils.translation import ugettext as _ from opaque_keys.edx.keys import UsageKey +from six import text_type from courseware.field_overrides import disable_overrides from courseware.models import StudentFieldOverride @@ -106,7 +107,7 @@ def find_unit(course, url): """ Find node in course tree for url. """ - if node.location.to_deprecated_string() == url: + if text_type(node.location) == url: return node for child in node.get_children(): found = find(child, url) @@ -150,7 +151,7 @@ def title_or_url(node): """ title = getattr(node, 'display_name', None) if not title: - title = node.location.to_deprecated_string() + title = text_type(node.location) return title diff --git a/lms/djangoapps/instructor_analytics/tests/test_basic.py b/lms/djangoapps/instructor_analytics/tests/test_basic.py index 719d1e33a6..45cecd69af 100644 --- a/lms/djangoapps/instructor_analytics/tests/test_basic.py +++ b/lms/djangoapps/instructor_analytics/tests/test_basic.py @@ -13,6 +13,7 @@ from edx_proctoring.models import ProctoredExamStudentAttempt from mock import MagicMock, Mock, patch from nose.plugins.attrib import attr from opaque_keys.edx.locator import UsageKey +from six import text_type from course_modes.models import CourseMode from course_modes.tests.factories import CourseModeFactory @@ -312,7 +313,7 @@ class TestCourseSaleRecordsAnalyticsBasic(ModuleStoreTestCase): ) for i in range(5): course_code = CourseRegistrationCode( - code="test_code{}".format(i), course_id=self.course.id.to_deprecated_string(), + code="test_code{}".format(i), course_id=text_type(self.course.id), created_by=self.instructor, invoice=sale_invoice, invoice_item=invoice_item, mode_slug='honor' ) course_code.save() @@ -541,7 +542,7 @@ class TestCourseRegistrationCodeAnalyticsBasic(ModuleStoreTestCase): mode.save() url = reverse('generate_registration_codes', - kwargs={'course_id': self.course.id.to_deprecated_string()}) + kwargs={'course_id': text_type(self.course.id)}) data = { 'total_registration_codes': 12, 'company_name': 'Test Group', 'unit_price': 122.45, @@ -574,7 +575,7 @@ class TestCourseRegistrationCodeAnalyticsBasic(ModuleStoreTestCase): self.assertIn(course_registration['code'], [registration_code.code for registration_code in registration_codes]) self.assertIn( course_registration['course_id'], - [registration_code.course_id.to_deprecated_string() for registration_code in registration_codes] + [text_type(registration_code.course_id) for registration_code in registration_codes] ) self.assertIn( course_registration['company_name'], @@ -630,5 +631,5 @@ class TestCourseRegistrationCodeAnalyticsBasic(ModuleStoreTestCase): self.assertIn(active_coupon['expiration_date'], [coupon.display_expiry_date for coupon in active_coupons]) self.assertIn( active_coupon['course_id'], - [coupon.course_id.to_deprecated_string() for coupon in active_coupons] + [text_type(coupon.course_id) for coupon in active_coupons] ) diff --git a/lms/djangoapps/instructor_task/tests/test_base.py b/lms/djangoapps/instructor_task/tests/test_base.py index 9bfce46389..0b35797d51 100644 --- a/lms/djangoapps/instructor_task/tests/test_base.py +++ b/lms/djangoapps/instructor_task/tests/test_base.py @@ -16,6 +16,7 @@ from django.core.urlresolvers import reverse from mock import Mock, patch from opaque_keys.edx.locations import Location from opaque_keys.edx.keys import CourseKey +from six import text_type from capa.tests.response_xml_factory import OptionResponseXMLFactory from courseware.model_data import StudentModule @@ -283,9 +284,9 @@ class InstructorTaskModuleTestCase(InstructorTaskCourseTestCase): self.login_username(username) # make ajax call: modx_url = reverse('xblock_handler', kwargs={ - 'course_id': self.course.id.to_deprecated_string(), + 'course_id': text_type(self.course.id), 'usage_id': quote_slashes( - InstructorTaskModuleTestCase.problem_location(problem_url_name, self.course.id).to_deprecated_string() + text_type(InstructorTaskModuleTestCase.problem_location(problem_url_name, self.course.id)) ), 'handler': 'xmodule_handler', 'suffix': 'problem_check', diff --git a/lms/djangoapps/instructor_task/tests/test_integration.py b/lms/djangoapps/instructor_task/tests/test_integration.py index afd57eb3f3..092f0107b5 100644 --- a/lms/djangoapps/instructor_task/tests/test_integration.py +++ b/lms/djangoapps/instructor_task/tests/test_integration.py @@ -16,6 +16,7 @@ from django.contrib.auth.models import User from django.core.urlresolvers import reverse from mock import patch from nose.plugins.attrib import attr +from six import text_type from capa.responsetypes import StudentInputError from capa.tests.response_xml_factory import CodeResponseXMLFactory, CustomResponseXMLFactory @@ -56,7 +57,7 @@ class TestIntegrationTask(InstructorTaskModuleTestCase): self.assertEqual(instructor_task.task_type, task_type) task_input = json.loads(instructor_task.task_input) self.assertNotIn('student', task_input) - self.assertEqual(task_input['problem_url'], InstructorTaskModuleTestCase.problem_location(problem_url_name).to_deprecated_string()) + self.assertEqual(task_input['problem_url'], text_type(InstructorTaskModuleTestCase.problem_location(problem_url_name))) status = json.loads(instructor_task.task_output) self.assertEqual(status['exception'], 'ZeroDivisionError') self.assertEqual(status['message'], expected_message) @@ -98,8 +99,8 @@ class TestRescoringTask(TestIntegrationTask): self.login_username(username) # make ajax call: modx_url = reverse('xblock_handler', kwargs={ - 'course_id': self.course.id.to_deprecated_string(), - 'usage_id': quote_slashes(InstructorTaskModuleTestCase.problem_location(problem_url_name).to_deprecated_string()), + 'course_id': text_type(self.course.id), + 'usage_id': quote_slashes(text_type(InstructorTaskModuleTestCase.problem_location(problem_url_name))), 'handler': 'xmodule_handler', 'suffix': 'problem_get', }) @@ -300,7 +301,7 @@ class TestRescoringTask(TestIntegrationTask): self.assertEqual(instructor_task.task_type, 'rescore_problem') task_input = json.loads(instructor_task.task_input) self.assertNotIn('student', task_input) - self.assertEqual(task_input['problem_url'], InstructorTaskModuleTestCase.problem_location(problem_url_name).to_deprecated_string()) + self.assertEqual(task_input['problem_url'], text_type(InstructorTaskModuleTestCase.problem_location(problem_url_name))) status = json.loads(instructor_task.task_output) self.assertEqual(status['attempted'], 1) self.assertEqual(status['succeeded'], 0) diff --git a/lms/djangoapps/instructor_task/tests/test_tasks_helper.py b/lms/djangoapps/instructor_task/tests/test_tasks_helper.py index 1c92e54a50..1891263800 100644 --- a/lms/djangoapps/instructor_task/tests/test_tasks_helper.py +++ b/lms/djangoapps/instructor_task/tests/test_tasks_helper.py @@ -23,6 +23,7 @@ from freezegun import freeze_time from mock import MagicMock, Mock, patch from nose.plugins.attrib import attr from pytz import UTC +from six import text_type import openedx.core.djangoapps.user_api.course_tag.api as course_tag_api from capa.tests.response_xml_factory import MultipleChoiceResponseXMLFactory @@ -611,7 +612,7 @@ class TestInstructorDetailedEnrollmentReport(TestReportMixin, InstructorTaskCour course_registration_code = CourseRegistrationCode( code='abcde', - course_id=self.course.id.to_deprecated_string(), + course_id=text_type(self.course.id), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, @@ -652,7 +653,7 @@ class TestInstructorDetailedEnrollmentReport(TestReportMixin, InstructorTaskCour invoice_transaction.save() course_registration_code = CourseRegistrationCode( code='abcde', - course_id=self.course.id.to_deprecated_string(), + course_id=text_type(self.course.id), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, @@ -2557,7 +2558,7 @@ class TestInstructorOra2Report(SharedModuleStoreTestCase): # pylint: disable=maybe-no-member timestamp_str = datetime.now(UTC).strftime('%Y-%m-%d-%H%M') - course_id_string = urllib.quote(self.course.id.to_deprecated_string().replace('/', '_')) + course_id_string = urllib.quote(text_type(self.course.id).replace('/', '_')) filename = u'{}_ORA_data_{}.csv'.format(course_id_string, timestamp_str) self.assertEqual(return_val, UPDATE_STATUS_SUCCEEDED) diff --git a/lms/djangoapps/shoppingcart/tests/test_reports.py b/lms/djangoapps/shoppingcart/tests/test_reports.py index 307bdb074d..91f6895e6d 100644 --- a/lms/djangoapps/shoppingcart/tests/test_reports.py +++ b/lms/djangoapps/shoppingcart/tests/test_reports.py @@ -10,6 +10,7 @@ from textwrap import dedent import pytz from django.conf import settings from mock import patch +from six import text_type from course_modes.models import CourseMode from shoppingcart.models import ( @@ -51,7 +52,7 @@ class ReportTypeTests(ModuleStoreTestCase): self.cost = 40 self.course = CourseFactory.create(org='MITx', number='999', display_name=u'Robot Super Course') self.course_key = self.course.id - settings.COURSE_LISTINGS['default'] = [self.course_key.to_deprecated_string()] + settings.COURSE_LISTINGS['default'] = [text_type(self.course_key)] course_mode = CourseMode(course_id=self.course_key, mode_slug="honor", mode_display_name="honor cert", @@ -245,10 +246,10 @@ class ItemizedPurchaseReportTest(ModuleStoreTestCase): """ Fill in gap in test coverage. __unicode__ method of PaidCourseRegistrationAnnotation """ - self.assertEqual(unicode(self.annotation), u'{} : {}'.format(self.course_key.to_deprecated_string(), self.TEST_ANNOTATION)) + self.assertEqual(text_type(self.annotation), u'{} : {}'.format(text_type(self.course_key), self.TEST_ANNOTATION)) def test_courseregcodeitemannotationannotation_unicode(self): """ Fill in gap in test coverage. __unicode__ method of CourseRegCodeItemAnnotation """ - self.assertEqual(unicode(self.course_reg_code_annotation), u'{} : {}'.format(self.course_key.to_deprecated_string(), self.TEST_ANNOTATION)) + self.assertEqual(text_type(self.course_reg_code_annotation), u'{} : {}'.format(text_type(self.course_key), self.TEST_ANNOTATION)) diff --git a/lms/djangoapps/shoppingcart/tests/test_views.py b/lms/djangoapps/shoppingcart/tests/test_views.py index 2d46cf7f4b..cc44487943 100644 --- a/lms/djangoapps/shoppingcart/tests/test_views.py +++ b/lms/djangoapps/shoppingcart/tests/test_views.py @@ -23,6 +23,7 @@ from freezegun import freeze_time from mock import Mock, patch from nose.plugins.attrib import attr from pytz import UTC +from six import text_type from common.test.utils import XssTestMixin from course_modes.models import CourseMode @@ -198,7 +199,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.client.login(username=self.user.username, password="password") def test_add_course_to_cart_anon(self): - resp = self.client.post(reverse('add_course_to_cart', args=[self.course_key.to_deprecated_string()])) + resp = self.client.post(reverse('add_course_to_cart', args=[text_type(self.course_key)])) self.assertEqual(resp.status_code, 403) @patch('shoppingcart.views.render_to_response', render_mock) @@ -260,7 +261,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.login_user() # add first course to user cart resp = self.client.post( - reverse('add_course_to_cart', args=[self.course_key.to_deprecated_string()]) + reverse('add_course_to_cart', args=[text_type(self.course_key)]) ) self.assertEqual(resp.status_code, 200) # add and apply the coupon code to course in the cart @@ -273,7 +274,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): #now add the second course to cart, the coupon code should be # applied when adding the second course to the cart resp = self.client.post( - reverse('add_course_to_cart', args=[self.testing_course.id.to_deprecated_string()]) + reverse('add_course_to_cart', args=[text_type(self.testing_course.id)]) ) self.assertEqual(resp.status_code, 200) #now check the user cart and see that the discount has been applied on both the courses @@ -286,9 +287,9 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): def test_add_course_to_cart_already_in_cart(self): PaidCourseRegistration.add_to_order(self.cart, self.course_key) self.login_user() - resp = self.client.post(reverse('add_course_to_cart', args=[self.course_key.to_deprecated_string()])) + 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(self.course_key.to_deprecated_string()), resp.content) + self.assertIn('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) @@ -428,7 +429,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.assertIn("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 = self.course_key.to_deprecated_string() + 'testing' + course_key = text_type(self.course_key) + 'testing' self.add_coupon(course_key, True, self.coupon_code) self.add_course_to_user_cart(self.course_key) @@ -441,7 +442,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): test to redeem inactive registration code and it returns an error. """ - course_key = self.course_key.to_deprecated_string() + course_key = text_type(self.course_key) self.add_reg_code(course_key, is_valid=False) self.add_course_to_user_cart(self.course_key) @@ -454,7 +455,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): enrollment_code=self.reg_code), resp.content) def test_course_does_not_exist_in_cart_against_valid_reg_code(self): - course_key = self.course_key.to_deprecated_string() + 'testing' + course_key = text_type(self.course_key) + 'testing' self.add_reg_code(course_key) self.add_course_to_user_cart(self.course_key) @@ -463,7 +464,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): self.assertIn("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 = self.course_key.to_deprecated_string() + course_key = text_type(self.course_key) self.add_reg_code(course_key) item = self.add_course_to_user_cart(self.course_key) resp = self.client.post(reverse('shoppingcart.views.update_user_cart'), {'ItemId': item.id, 'qty': 4}) @@ -477,7 +478,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): @ddt.data(True, False) def test_reg_code_uses_associated_mode(self, expired_mode): """Tests the use of reg codes on verified courses, expired or active. """ - course_key = self.course_key.to_deprecated_string() + course_key = text_type(self.course_key) expiration_date = self.yesterday if expired_mode else self.tomorrow self._add_course_mode(mode_slug='verified', expiration_date=expiration_date) self.add_reg_code(course_key, mode_slug='verified') @@ -489,7 +490,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): @ddt.data(True, False) def test_reg_code_uses_unknown_mode(self, expired_mode): """Tests the use of reg codes on verified courses, expired or active. """ - course_key = self.course_key.to_deprecated_string() + course_key = text_type(self.course_key) expiration_date = self.yesterday if expired_mode else self.tomorrow self._add_course_mode(mode_slug='verified', expiration_date=expiration_date) self.add_reg_code(course_key, mode_slug='bananas') @@ -618,7 +619,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): def test_upgrade_from_valid_reg_code(self): """Use a valid registration code to upgrade from honor to verified mode. """ # Ensure the course has a verified mode - course_key = self.course_key.to_deprecated_string() + course_key = text_type(self.course_key) self._add_course_mode(mode_slug='verified') self.add_reg_code(course_key, mode_slug='verified') @@ -769,9 +770,9 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): def test_add_course_to_cart_already_registered(self): CourseEnrollment.enroll(self.user, self.course_key) self.login_user() - resp = self.client.post(reverse('add_course_to_cart', args=[self.course_key.to_deprecated_string()])) + 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(self.course_key.to_deprecated_string()), resp.content) + self.assertIn('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() @@ -781,8 +782,8 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): def test_add_course_to_cart_success(self): self.login_user() - reverse('add_course_to_cart', args=[self.course_key.to_deprecated_string()]) - resp = self.client.post(reverse('add_course_to_cart', args=[self.course_key.to_deprecated_string()])) + reverse('add_course_to_cart', args=[text_type(self.course_key)]) + resp = self.client.post(reverse('add_course_to_cart', args=[text_type(self.course_key)])) self.assertEqual(resp.status_code, 200) self.assertTrue(PaidCourseRegistration.contained_in_order(self.cart, self.course_key)) @@ -1435,7 +1436,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): 'edx.course.enrollment.upgrade.succeeded', { 'user_id': self.user.id, - 'course_id': self.verified_course_key.to_deprecated_string(), + 'course_id': text_type(self.verified_course_key), 'mode': 'verified' } ) @@ -1446,7 +1447,7 @@ class ShoppingCartViewsTests(SharedModuleStoreTestCase, XssTestMixin): """ CourseEnrollment.enroll(self.user, self.course_key) self.add_course_to_user_cart(self.testing_course.id) - resp = self.client.get(reverse('courseware', kwargs={'course_id': unicode(self.course.id)})) + resp = self.client.get(reverse('courseware', kwargs={'course_id': text_type(self.course.id)})) self.assertEqual(resp.status_code, 200) self.assertIn(' <% @@ -22,10 +23,10 @@ from django.utils.translation import ugettext as _ % if allows_login: % if restrict_enroll_for_course: % else: % if allow_public_account_creation: