INCR-265 Run python-modernize on lms/djangoapps/courseware/management and lms/djangoapps/courseware/tests (#20716)

* updated files according to INCR-265

* fixed docstring and line-length problems from quality test

* Revert "fixed docstring and line-length problems from quality test"

This reverts commit d050f55a4ecfaa38f46b80ec4bb85ff399a79a8c.

* fixed errors reported in quality report

* had error, fixed it

* reversed change

* fixed over/under indentation, and added line to import.py that Ned had suggested

* tried disabling pylint for this line

* testing new email

* testing email in different window

* re-added symlink and docstring
This commit is contained in:
alangsto
2019-05-31 14:07:18 -04:00
committed by GitHub
parent 9e01a9e2aa
commit 4a1346b068
45 changed files with 428 additions and 300 deletions

View File

@@ -1,14 +1,19 @@
from __future__ import print_function
"""
Contains functions that handle XML course data
"""
from __future__ import absolute_import, print_function
import os
import sys
import traceback
import lxml.etree
from django.core.management.base import BaseCommand
from fs.osfs import OSFS
from path import Path as path
from six.moves import map
from xmodule.modulestore.xml import XMLModuleStore

View File

@@ -3,13 +3,13 @@ Dump the course_ids available to the lms.
Output is UTF-8 encoded by default.
"""
from __future__ import unicode_literals
from __future__ import absolute_import, unicode_literals
from textwrap import dedent
from django.core.management.base import BaseCommand
from six import text_type
from django.core.management.base import BaseCommand
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview

View File

@@ -16,13 +16,17 @@ The resulting JSON object has one entry for each module in the course:
"""
from __future__ import absolute_import
import json
from textwrap import dedent
import six
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from xblock.fields import Scope
from xblock_discussion import DiscussionXBlock
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.inheritance import compute_inherited_metadata, own_metadata
@@ -73,7 +77,7 @@ class Command(BaseCommand):
info = dump_module(course, inherited=options['inherited'], defaults=options['inherited_defaults'])
return json.dumps(info, indent=2, sort_keys=True, default=unicode)
return json.dumps(info, indent=2, sort_keys=True, default=six.text_type)
def dump_module(module, destination=None, inherited=False, defaults=False):
@@ -90,11 +94,11 @@ def dump_module(module, destination=None, inherited=False, defaults=False):
if isinstance(module, DiscussionXBlock) and 'discussion_id' not in items:
items['discussion_id'] = module.discussion_id
filtered_metadata = {k: v for k, v in items.iteritems() if k not in FILTER_LIST}
filtered_metadata = {k: v for k, v in six.iteritems(items) if k not in FILTER_LIST}
destination[unicode(module.location)] = {
destination[six.text_type(module.location)] = {
'category': module.location.block_type,
'children': [unicode(child) for child in getattr(module, 'children', [])],
'children': [six.text_type(child) for child in getattr(module, 'children', [])],
'metadata': filtered_metadata,
}
@@ -115,7 +119,7 @@ def dump_module(module, destination=None, inherited=False, defaults=False):
return field.values != field.default
inherited_metadata = {field.name: field.read_json(module) for field in module.fields.values() if is_inherited(field)}
destination[unicode(module.location)]['inherited_metadata'] = inherited_metadata
destination[six.text_type(module.location)]['inherited_metadata'] = inherited_metadata
for child in module.get_children():
dump_module(child, destination, inherited, defaults)

View File

@@ -4,14 +4,17 @@
Tests for Django management commands
"""
from __future__ import absolute_import
import json
from StringIO import StringIO
from six import text_type
import factory
import six
from django.conf import settings
from django.core.management import call_command
from six import text_type
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import (
@@ -101,7 +104,7 @@ class CommandsTestBase(SharedModuleStoreTestCase):
self.fail(exception)
dump = json.loads(output)
self.assertGreater(len(dump.values()), 0)
self.assertGreater(len(list(dump.values())), 0)
def test_dump_course_structure(self):
args = [text_type(self.test_course_key)]
@@ -112,7 +115,7 @@ class CommandsTestBase(SharedModuleStoreTestCase):
# check that all elements in the course structure have metadata,
# but not inherited metadata:
for element in dump.itervalues():
for element in six.itervalues(dump):
self.assertIn('metadata', element)
self.assertIn('children', element)
self.assertIn('category', element)
@@ -133,7 +136,7 @@ class CommandsTestBase(SharedModuleStoreTestCase):
course_metadata = dump[video_id]['metadata']
course_metadata.pop('edx_video_id', None)
self.assertItemsEqual(
course_metadata.keys(),
list(course_metadata.keys()),
['download_video', 'youtube_id_0_75', 'youtube_id_1_0', 'youtube_id_1_25', 'youtube_id_1_5']
)
self.assertIn('youtube_id_1_0', dump[video_id]['metadata'])
@@ -149,7 +152,7 @@ class CommandsTestBase(SharedModuleStoreTestCase):
dump = json.loads(output)
# check that all elements in the course structure have inherited metadata,
# and that it contains a particular value as well:
for element in dump.itervalues():
for element in six.itervalues(dump):
self.assertIn('metadata', element)
self.assertIn('children', element)
self.assertIn('category', element)
@@ -164,7 +167,7 @@ class CommandsTestBase(SharedModuleStoreTestCase):
dump = json.loads(output)
# check that all elements in the course structure have inherited metadata,
# and that it contains a particular value as well:
for element in dump.itervalues():
for element in six.itervalues(dump):
self.assertIn('metadata', element)
self.assertIn('children', element)
self.assertIn('category', element)

View File

@@ -1,5 +1,7 @@
# Factories are self documenting
# pylint: disable=missing-docstring
from __future__ import absolute_import
import json
from functools import partial
@@ -23,9 +25,9 @@ from student.roles import (
OrgInstructorRole,
OrgStaffRole
)
from student.tests.factories import UserProfileFactory as StudentUserProfileFactory
# Imported to re-export
from student.tests.factories import UserFactory # Imported to re-export
from student.tests.factories import UserProfileFactory as StudentUserProfileFactory
# TODO fix this (course_id and location are invalid names as constants, and course_id should really be COURSE_KEY)
# pylint: disable=invalid-name

View File

@@ -1,9 +1,12 @@
"""
Helpers for courseware tests.
"""
from datetime import timedelta
import json
from __future__ import absolute_import
import json
from datetime import timedelta
import six
from django.contrib import messages
from django.contrib.auth.models import User
from django.test import TestCase
@@ -11,6 +14,8 @@ from django.test.client import Client, RequestFactory
from django.urls import reverse
from django.utils.timezone import now
from six import text_type
from six.moves import range
from xblock.field_data import DictFieldData
from courseware.access import has_access
from courseware.masquerade import handle_ajax, setup_masquerade
@@ -20,10 +25,9 @@ from lms.djangoapps.lms_xblock.field_data import LmsFieldData
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.lib.url_utils import quote_slashes
from openedx.features.course_duration_limits.access import EXPIRATION_DATE_FORMAT_STR
from student.models import Registration, CourseEnrollment
from student.models import CourseEnrollment, Registration
from student.tests.factories import CourseEnrollmentFactory, UserFactory
from util.date_utils import strftime_localized
from xblock.field_data import DictFieldData
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import TEST_DATA_MONGO_MODULESTORE, ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
@@ -88,7 +92,7 @@ class BaseTestXmodule(ModuleStoreTestCase):
self.item_descriptor.xmodule_runtime = self.new_module_runtime()
self.item_url = unicode(self.item_descriptor.location)
self.item_url = six.text_type(self.item_descriptor.location)
def setup_course(self):
self.course = CourseFactory.create(data=self.COURSE_DATA)
@@ -134,7 +138,7 @@ class BaseTestXmodule(ModuleStoreTestCase):
"""Return item url with dispatch."""
return reverse(
'xblock_handler',
args=(unicode(self.course.id), quote_slashes(self.item_url), 'xmodule_handler', dispatch)
args=(six.text_type(self.course.id), quote_slashes(self.item_url), 'xmodule_handler', dispatch)
)
@@ -342,7 +346,7 @@ def masquerade_as_group_member(user, course, partition_id, group_id):
user,
data={"role": "student", "user_partition_id": partition_id, "group_id": group_id}
)
response = handle_ajax(request, unicode(course.id))
response = handle_ajax(request, six.text_type(course.id))
setup_masquerade(request, course.id, True)
return response.status_code

View File

@@ -1,14 +1,18 @@
"""
Test the about xblock
"""
from __future__ import absolute_import
import datetime
import ddt
import mock
import pytz
import six
from ccx_keys.locator import CCXLocator
from django.conf import settings
from django.urls import reverse
from django.test.utils import override_settings
from django.urls import reverse
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import patch
from six import text_type
@@ -17,9 +21,9 @@ from waffle.testutils import override_switch
from course_modes.models import CourseMode
from lms.djangoapps.ccx.tests.factories import CcxFactory
from openedx.core.djangoapps.waffle_utils.testutils import override_waffle_flag
from openedx.features.course_experience.waffle import WAFFLE_NAMESPACE as COURSE_EXPERIENCE_WAFFLE_NAMESPACE
from openedx.features.course_experience.waffle import ENABLE_COURSE_ABOUT_SIDEBAR_HTML
from openedx.features.course_experience import COURSE_ENABLE_UNENROLLED_ACCESS_FLAG
from openedx.features.course_experience.waffle import ENABLE_COURSE_ABOUT_SIDEBAR_HTML
from openedx.features.course_experience.waffle import WAFFLE_NAMESPACE as COURSE_EXPERIENCE_WAFFLE_NAMESPACE
from shoppingcart.models import Order, PaidCourseRegistration
from student.models import CourseEnrollment
from student.tests.factories import AdminFactory, CourseEnrollmentAllowedFactory, UserFactory
@@ -29,8 +33,8 @@ from xmodule.course_module import (
CATALOG_VISIBILITY_ABOUT,
CATALOG_VISIBILITY_NONE,
COURSE_VISIBILITY_PRIVATE,
COURSE_VISIBILITY_PUBLIC_OUTLINE,
COURSE_VISIBILITY_PUBLIC
COURSE_VISIBILITY_PUBLIC,
COURSE_VISIBILITY_PUBLIC_OUTLINE
)
from xmodule.modulestore.tests.django_utils import (
TEST_DATA_MIXED_MODULESTORE,
@@ -226,7 +230,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra
.format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']),
resp.content.decode(resp.charset).strip('\n'))
url = reverse('about_course', args=[unicode(pre_requisite_course.id)])
url = reverse('about_course', args=[six.text_type(pre_requisite_course.id)])
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
@@ -681,7 +685,7 @@ class CourseAboutTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase)
# create ccx
ccx = CcxFactory(course_id=self.course.id, coach=self.coach)
ccx_locator = CCXLocator.from_course_locator(self.course.id, unicode(ccx.id))
ccx_locator = CCXLocator.from_course_locator(self.course.id, six.text_type(ccx.id))
self.setup_user()
url = reverse('openedx.course_experience.course_home', args=[ccx_locator])

View File

@@ -2,16 +2,19 @@
"""
Test the access control framework
"""
from __future__ import absolute_import
import datetime
import itertools
import ddt
import pytz
import six
from ccx_keys.locator import CCXLocator
from django.contrib.auth.models import User
from django.urls import reverse
from django.test import TestCase
from django.test.client import RequestFactory
from django.urls import reverse
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import Mock, patch
from opaque_keys.edx.locator import CourseLocator
@@ -100,7 +103,7 @@ class CoachAccessTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase)
)
ccx.save()
ccx_locator = CCXLocator.from_course_locator(self.course.id, unicode(ccx.id))
ccx_locator = CCXLocator.from_course_locator(self.course.id, six.text_type(ccx.id))
role = CourseCcxCoachRole(ccx_locator)
role.add_users(self.coach)
CourseEnrollment.enroll(self.coach, ccx_locator)
@@ -147,12 +150,12 @@ class CoachAccessTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase)
CourseEnrollment.enroll(student, ccx_locator)
# Test for access of a coach
resp = self.client.get(reverse('student_progress', args=[unicode(ccx_locator), student.id]))
resp = self.client.get(reverse('student_progress', args=[six.text_type(ccx_locator), student.id]))
self.assertEqual(resp.status_code, 200)
# Assert access of a student
self.client.login(username=student.username, password='test')
resp = self.client.get(reverse('student_progress', args=[unicode(ccx_locator), self.coach.id]))
resp = self.client.get(reverse('student_progress', args=[six.text_type(ccx_locator), self.coach.id]))
self.assertEqual(resp.status_code, 404)
@@ -591,7 +594,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes
org='test_org', number='788', run='test_run'
)
pre_requisite_courses = [unicode(pre_requisite_course.id)]
pre_requisite_courses = [six.text_type(pre_requisite_course.id)]
course = CourseFactory.create(
org='test_org', number='786', run='test_run', pre_requisite_courses=pre_requisite_courses
)
@@ -640,7 +643,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes
run='test_run',
)
pre_requisite_courses = [unicode(pre_requisite_course.id)]
pre_requisite_courses = [six.text_type(pre_requisite_course.id)]
course = CourseFactory.create(
org='edX',
course='1000',
@@ -656,7 +659,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes
self.login(user.email, test_password)
CourseEnrollmentFactory(user=user, course_id=course.id)
url = reverse('courseware', args=[unicode(course.id)])
url = reverse('courseware', args=[six.text_type(course.id)])
response = self.client.get(url)
self.assertRedirects(
response,

View File

@@ -1,5 +1,7 @@
"""Tests of comprehensive theming."""
from __future__ import absolute_import
from django.conf import settings
from django.contrib import staticfiles
from django.test import TestCase

View File

@@ -1,6 +1,8 @@
"""
Unit tests for courseware context_processor
"""
from __future__ import absolute_import
from django.contrib.auth.models import AnonymousUser
from mock import Mock

View File

@@ -2,15 +2,21 @@
"""
Test the course_info xblock
"""
from __future__ import absolute_import
from datetime import datetime
import ddt
import mock
import six
from ccx_keys.locator import CCXLocator
from django.conf import settings
from django.urls import reverse
from django.http import QueryDict
from django.test.utils import override_settings
from django.urls import reverse
from pyquery import PyQuery as pq
from six import text_type
from ccx_keys.locator import CCXLocator
from lms.djangoapps.ccx.tests.factories import CcxFactory
from openedx.core.djangoapps.self_paced.models import SelfPacedConfiguration
from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration_context
@@ -18,8 +24,6 @@ from openedx.core.djangoapps.waffle_utils.testutils import WAFFLE_TABLES, overri
from openedx.features.content_type_gating.models import ContentTypeGatingConfig
from openedx.features.course_experience import UNIFIED_COURSE_TAB_FLAG
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
@@ -171,7 +175,7 @@ class CourseInfoLastAccessedTestCase(LoginEnrollmentTestCase, ModuleStoreTestCas
is no course content.
"""
SelfPacedConfiguration(enable_course_home_improvements=True).save()
url = reverse('info', args=(unicode(self.course.id),))
url = reverse('info', args=(six.text_type(self.course.id),))
response = self.client.get(url)
content = pq(response.content)
self.assertEqual(content('.page-header-secondary a').length, 0)
@@ -202,7 +206,7 @@ class CourseInfoLastAccessedTestCase(LoginEnrollmentTestCase, ModuleStoreTestCas
}
)
self.client.get(section_url)
info_url = reverse('info', args=(unicode(self.course.id),))
info_url = reverse('info', args=(six.text_type(self.course.id),))
# Assuring a non-authenticated user cannot see the resume course button.
resume_course_url = self.get_resume_course_url(info_url)
@@ -288,7 +292,7 @@ class CourseInfoTitleTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase):
Test the info page on a course with all the multiple display options
depeding on the current site configuration
"""
url = reverse('info', args=(unicode(self.course.id),))
url = reverse('info', args=(six.text_type(self.course.id),))
with with_site_configuration_context(configuration=site_config):
response = self.client.get(url)
@@ -339,7 +343,7 @@ class CourseInfoTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
"""
# create ccx
ccx = CcxFactory(course_id=self.course.id, coach=self.coach)
ccx_locator = CCXLocator.from_course_locator(self.course.id, unicode(ccx.id))
ccx_locator = CCXLocator.from_course_locator(self.course.id, six.text_type(ccx.id))
self.setup_user()
url = reverse('info', args=[ccx_locator])

View File

@@ -2,11 +2,15 @@
Python tests for the Survey workflows
"""
from __future__ import absolute_import
from collections import OrderedDict
from copy import deepcopy
import six
from django.contrib.auth.models import User
from django.urls import reverse
from six.moves import range
from common.test.utils import XssTestMixin
from courseware.tests.helpers import LoginEnrollmentTestCase
@@ -78,12 +82,12 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe
resp = self.client.get(
reverse(
view_name,
kwargs={'course_id': unicode(course.id)}
kwargs={'course_id': six.text_type(course.id)}
)
)
self.assertRedirects(
resp,
reverse('course_survey', kwargs={'course_id': unicode(course.id)})
reverse('course_survey', kwargs={'course_id': six.text_type(course.id)})
)
def _assert_no_redirect(self, course):
@@ -95,7 +99,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe
resp = self.client.get(
reverse(
view_name,
kwargs={'course_id': unicode(course.id)}
kwargs={'course_id': six.text_type(course.id)}
)
)
self.assertEquals(resp.status_code, 200)
@@ -122,7 +126,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe
resp = self.client.get(
reverse(
'openedx.course_experience.course_home',
kwargs={'course_id': unicode(self.course.id)}
kwargs={'course_id': six.text_type(self.course.id)}
)
)
self.assertEquals(resp.status_code, 200)
@@ -147,13 +151,13 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe
resp = self.client.get(
reverse(
'course_survey',
kwargs={'course_id': unicode(self.course.id)}
kwargs={'course_id': six.text_type(self.course.id)}
)
)
self.assertEqual(resp.status_code, 200)
expected = u'<input type="hidden" name="course_id" value="{course_id}" />'.format(
course_id=unicode(self.course.id)
course_id=six.text_type(self.course.id)
)
self.assertContains(resp, expected)
@@ -165,7 +169,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe
answers = deepcopy(self.student_answers)
answers.update({
'course_id': unicode(self.course.id)
'course_id': six.text_type(self.course.id)
})
resp = self.client.post(
@@ -199,13 +203,13 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe
resp = self.client.get(
reverse(
'course_survey',
kwargs={'course_id': unicode(self.course_with_bogus_survey.id)}
kwargs={'course_id': six.text_type(self.course_with_bogus_survey.id)}
)
)
course_home_path = 'openedx.course_experience.course_home'
self.assertRedirects(
resp,
reverse(course_home_path, kwargs={'course_id': unicode(self.course_with_bogus_survey.id)})
reverse(course_home_path, kwargs={'course_id': six.text_type(self.course_with_bogus_survey.id)})
)
def test_visiting_survey_with_no_course_survey(self):
@@ -216,13 +220,13 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe
resp = self.client.get(
reverse(
'course_survey',
kwargs={'course_id': unicode(self.course_without_survey.id)}
kwargs={'course_id': six.text_type(self.course_without_survey.id)}
)
)
course_home_path = 'openedx.course_experience.course_home'
self.assertRedirects(
resp,
reverse(course_home_path, kwargs={'course_id': unicode(self.course_without_survey.id)})
reverse(course_home_path, kwargs={'course_id': six.text_type(self.course_without_survey.id)})
)
def test_survey_xss(self):
@@ -230,7 +234,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe
response = self.client.get(
reverse(
'course_survey',
kwargs={'course_id': unicode(self.course.id)}
kwargs={'course_id': six.text_type(self.course.id)}
)
)
self.assert_no_xss(response, '<script>alert("XSS")</script>')

View File

@@ -2,12 +2,14 @@
Unit tests for course tools.
"""
import crum
from __future__ import absolute_import
import datetime
from mock import patch
import crum
import pytz
from django.test import RequestFactory
from mock import patch
from course_modes.models import CourseMode
from course_modes.tests.factories import CourseModeFactory

View File

@@ -2,19 +2,23 @@
"""
Tests for course access
"""
import itertools
from __future__ import absolute_import
import datetime
import itertools
import ddt
import mock
import pytz
import six
from crum import set_current_request
from django.conf import settings
from django.urls import reverse
from django.test.client import RequestFactory
from django.test.utils import override_settings
from django.urls import reverse
from opaque_keys.edx.keys import CourseKey
from six import text_type
from crum import set_current_request
from six.moves import range
from courseware.courses import (
course_open_for_self_enrollment,
@@ -27,7 +31,7 @@ from courseware.courses import (
get_course_overview_with_access,
get_course_with_access,
get_courses,
get_current_child,
get_current_child
)
from courseware.model_data import FieldDataCache
from courseware.module_render import get_module_for_descriptor
@@ -40,8 +44,8 @@ from xmodule.modulestore.django import _get_modulestore_branch_setting, modulest
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls
from xmodule.modulestore.xml_importer import import_course_from_xml
from xmodule.tests.xml import factories as xml
from xmodule.tests.xml import XModuleXmlImportTest
from xmodule.tests.xml import factories as xml
CMS_BASE_TEST = 'testcms'
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
@@ -67,9 +71,9 @@ class CoursesTest(ModuleStoreTestCase):
org='org', number='num', display_name='name'
)
cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, unicode(self.course.id))
cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, six.text_type(self.course.id))
self.assertEqual(cms_url, get_cms_course_link(self.course))
cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, unicode(self.course.location))
cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, six.text_type(self.course.location))
self.assertEqual(cms_url, get_cms_block_link(self.course, 'course'))
@ddt.data(GET_COURSE_WITH_ACCESS, GET_COURSE_OVERVIEW_WITH_ACCESS)
@@ -389,7 +393,7 @@ class CourseInstantiationTests(ModuleStoreTestCase):
self.factory = RequestFactory()
@ddt.data(*itertools.product(xrange(5), [ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split], [None, 0, 5]))
@ddt.data(*itertools.product(range(5), [ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split], [None, 0, 5]))
@ddt.unpack
def test_repeated_course_module_instantiation(self, loops, default_store, course_depth):
@@ -400,12 +404,12 @@ class CourseInstantiationTests(ModuleStoreTestCase):
__ = ItemFactory(parent=section, category='problem')
fake_request = self.factory.get(
reverse('progress', kwargs={'course_id': unicode(course.id)})
reverse('progress', kwargs={'course_id': six.text_type(course.id)})
)
course = modulestore().get_course(course.id, depth=course_depth)
for _ in xrange(loops):
for _ in range(loops):
field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
course.id, self.user, course, depth=course_depth
)
@@ -448,5 +452,5 @@ class TestGetCourseChapters(ModuleStoreTestCase):
self.assertEqual(len(course_chapter_ids), 2)
self.assertEqual(
course_chapter_ids,
[unicode(child) for child in course.children]
[six.text_type(child) for child in course.children]
)

View File

@@ -2,7 +2,10 @@
Tests for credit requirement display on the progress page.
"""
from __future__ import absolute_import
import ddt
import six
from django.conf import settings
from django.urls import reverse
from mock import patch
@@ -168,5 +171,5 @@ class ProgressPageCreditRequirementsTest(SharedModuleStoreTestCase):
def _get_progress_page(self):
"""Load the progress page for the course the user is enrolled in. """
url = reverse("progress", kwargs={"course_id": unicode(self.course.id)})
url = reverse("progress", kwargs={"course_id": six.text_type(self.course.id)})
return self.client.get(url)

View File

@@ -1,12 +1,14 @@
# -*- coding: utf-8 -*-
"""Tests for course home page date summary blocks."""
from __future__ import absolute_import
from datetime import datetime, timedelta
import ddt
import waffle
from django.contrib.messages.middleware import MessageMiddleware
from django.urls import reverse
from django.test import RequestFactory
from django.urls import reverse
from freezegun import freeze_time
from mock import patch
from pytz import utc

View File

@@ -6,12 +6,16 @@ tests for functionalities that require django API, and lms specific
functionalities.
"""
from __future__ import absolute_import
import json
import uuid
import ddt
import mock
import six
from django.urls import reverse
from six.moves import range
from web_fragments.fragment import Fragment
from xblock.field_data import DictFieldData
@@ -356,7 +360,7 @@ class TestXBlockInCourse(SharedModuleStoreTestCase):
Tests that course block api returns student_view_data for discussion xblock
"""
self.client.login(username=self.user.username, password='test')
url = reverse('blocks_in_block_tree', kwargs={'usage_key_string': unicode(self.course_usage_key)})
url = reverse('blocks_in_block_tree', kwargs={'usage_key_string': six.text_type(self.course_usage_key)})
query_params = {
'depth': 'all',
'username': self.user.username,
@@ -365,8 +369,8 @@ class TestXBlockInCourse(SharedModuleStoreTestCase):
}
response = self.client.get(url, query_params)
self.assertEquals(response.status_code, 200)
self.assertEquals(response.data['root'], unicode(self.course_usage_key))
for block_key_string, block_data in response.data['blocks'].iteritems():
self.assertEquals(response.data['root'], six.text_type(self.course_usage_key))
for block_key_string, block_data in six.iteritems(response.data['blocks']):
block_key = deserialize_usage_key(block_key_string, self.course_key)
self.assertEquals(block_data['id'], block_key_string)
self.assertEquals(block_data['type'], block_key.block_type)

View File

@@ -1,3 +1,9 @@
"""
Test the draft modulestore
"""
from __future__ import absolute_import
from django.test import TestCase
from opaque_keys.edx.keys import CourseKey

View File

@@ -1,9 +1,13 @@
"""
Tests use cases related to LMS Entrance Exam behavior, such as gated content access (TOC)
"""
from django.urls import reverse
from mock import Mock, patch
from __future__ import absolute_import
import six
from crum import set_current_request
from django.urls import reverse
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import Mock, patch
from capa.tests.response_xml_factory import MultipleChoiceResponseXMLFactory
from courseware.entrance_exams import (
@@ -14,9 +18,8 @@ from courseware.entrance_exams import (
)
from courseware.model_data import FieldDataCache
from courseware.module_render import get_module, handle_xblock_callback, toc_for_course
from courseware.tests.factories import InstructorFactory, StaffFactory, UserFactory, RequestFactoryNoCsrf
from courseware.tests.factories import InstructorFactory, RequestFactoryNoCsrf, StaffFactory, UserFactory
from courseware.tests.helpers import LoginEnrollmentTestCase
from milestones.tests.utils import MilestonesTestCaseMixin
from openedx.core.djangoapps.waffle_utils.testutils import override_waffle_flag
from openedx.core.djangolib.testing.utils import get_mock_request
from openedx.features.course_experience import COURSE_OUTLINE_PAGE_FLAG, UNIFIED_COURSE_TAB_FLAG
@@ -136,7 +139,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
self.course.entrance_exam_enabled = True
self.course.entrance_exam_minimum_score_pct = 0.50
self.course.entrance_exam_id = unicode(self.entrance_exam.scope_ids.usage_id)
self.course.entrance_exam_id = six.text_type(self.entrance_exam.scope_ids.usage_id)
self.anonymous_user = AnonymousUserFactory()
self.addCleanup(set_current_request, None)
@@ -229,10 +232,10 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
"""
Unit Test: if entrance exam is required. Should return a redirect.
"""
url = reverse('courseware', kwargs={'course_id': unicode(self.course.id)})
url = reverse('courseware', kwargs={'course_id': six.text_type(self.course.id)})
expected_url = reverse('courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.entrance_exam.location.block_id,
'section': self.exam_1.location.block_id
})
@@ -244,10 +247,10 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
"""
Unit Test: If entrance exam is not enabled then page should be redirected with chapter contents.
"""
url = reverse('courseware', kwargs={'course_id': unicode(self.course.id)})
url = reverse('courseware', kwargs={'course_id': six.text_type(self.course.id)})
expected_url = reverse('courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.chapter.location.block_id,
'section': self.welcome.location.block_id
})
@@ -261,10 +264,10 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
Unit Test: If entrance exam is enabled then its content e.g. problems should be loaded and redirection will
occur with entrance exam contents.
"""
url = reverse('courseware', kwargs={'course_id': unicode(self.course.id)})
url = reverse('courseware', kwargs={'course_id': six.text_type(self.course.id)})
expected_url = reverse('courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.entrance_exam.location.block_id,
'section': self.exam_1.location.block_id
})
@@ -295,7 +298,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.entrance_exam.location.block_id,
'section': self.exam_1.location.block_id,
}
@@ -319,7 +322,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.entrance_exam.location.block_id,
'section': self.exam_1.location.block_id
}
@@ -345,7 +348,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.chapter.location.block_id,
'section': self.chapter_subsection.location.block_id
}
@@ -365,7 +368,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.entrance_exam.location.block_id,
'section': self.exam_1.location.block_id
}
@@ -411,7 +414,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
# hit skip entrance exam api in instructor app
instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=instructor.username, password='test')
url = reverse('mark_student_can_skip_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
url = reverse('mark_student_can_skip_entrance_exam', kwargs={'course_id': six.text_type(self.course.id)})
response = self.client.post(url, {
'unique_student_identifier': self.request.user.email,
})
@@ -444,12 +447,12 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
"""
url = reverse(
'courseware_chapter',
kwargs={'course_id': unicode(self.course.id), 'chapter': self.chapter.url_name}
kwargs={'course_id': six.text_type(self.course.id), 'chapter': self.chapter.url_name}
)
response = self.client.get(url)
expected_url = reverse('courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.entrance_exam.location.block_id,
'section': self.exam_1.location.block_id
})
@@ -460,9 +463,9 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
"""
Test courseware access page without passing entrance exam
"""
url = reverse('info', args=[unicode(self.course.id)])
url = reverse('info', args=[six.text_type(self.course.id)])
response = self.client.get(url)
redirect_url = reverse('courseware', args=[unicode(self.course.id)])
redirect_url = reverse('courseware', args=[six.text_type(self.course.id)])
self.assertRedirects(response, redirect_url, status_code=302, target_status_code=302)
response = self.client.get(redirect_url)
exam_url = response.get('Location')
@@ -535,7 +538,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
Tests entrance exam xblock has `entrance_exam_passed` key in json response.
"""
request_factory = RequestFactoryNoCsrf()
data = {'input_{}_2_1'.format(unicode(self.problem_1.location.html_id())): 'choice_2'}
data = {'input_{}_2_1'.format(six.text_type(self.problem_1.location.html_id())): 'choice_2'}
request = request_factory.post(
'problem_check',
data=data
@@ -543,8 +546,8 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
request.user = self.user
response = handle_xblock_callback(
request,
unicode(self.course.id),
unicode(self.problem_1.location),
six.text_type(self.course.id),
six.text_type(self.problem_1.location),
'xmodule_handler',
'problem_check',
)
@@ -557,7 +560,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
"""
url = reverse(
'courseware_chapter',
kwargs={'course_id': unicode(course.id), 'chapter': chapter.url_name}
kwargs={'course_id': six.text_type(course.id), 'chapter': chapter.url_name}
)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
@@ -639,13 +642,13 @@ def add_entrance_exam_milestone(course, entrance_exam):
}
)
add_course_milestone(
unicode(course.id),
six.text_type(course.id),
milestone_relationship_types['REQUIRES'],
milestone
)
add_course_content_milestone(
unicode(course.id),
unicode(entrance_exam.location),
six.text_type(course.id),
six.text_type(entrance_exam.location),
milestone_relationship_types['FULFILLS'],
milestone
)

View File

@@ -1,3 +1,9 @@
"""
Tests of the courseware favicon
"""
from __future__ import absolute_import
from django.test import TestCase
from django.test.utils import override_settings

View File

@@ -2,6 +2,8 @@
Tests for `field_overrides` module.
"""
# pylint: disable=missing-docstring
from __future__ import absolute_import
import unittest
from django.test.utils import override_settings

View File

@@ -3,8 +3,11 @@ Tests related to the basic footer-switching based off SITE_NAME to ensure
edx.org uses an edx footer but other instances use an Open edX footer.
"""
from __future__ import absolute_import
import unittest
import six
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
@@ -65,7 +68,7 @@ class TestFooter(TestCase):
)
def test_edx_footer_social_links(self):
resp = self.client.get('/')
for name, url in self.SOCIAL_MEDIA_URLS.iteritems():
for name, url in six.iteritems(self.SOCIAL_MEDIA_URLS):
self.assertContains(resp, url)
self.assertContains(resp, settings.SOCIAL_MEDIA_FOOTER_DISPLAY[name]['title'])
self.assertContains(resp, settings.SOCIAL_MEDIA_FOOTER_DISPLAY[name]['icon'])

View File

@@ -3,6 +3,8 @@ This module defines tests for courseware.access that are specific to group
access control rules.
"""
from __future__ import absolute_import
import ddt
from stevedore.extension import Extension, ExtensionManager

View File

@@ -2,13 +2,15 @@
Tests i18n in courseware
"""
from __future__ import absolute_import
import json
import re
from django.conf import settings
from django.contrib.auth.models import User
from django.urls import reverse, reverse_lazy
from django.test.client import Client
from django.urls import reverse, reverse_lazy
from django.utils import translation
from openedx.core.djangoapps.dark_lang.models import DarkLangConfig

View File

@@ -1,18 +1,22 @@
"""LTI integration tests"""
from __future__ import absolute_import
import json
import urllib
from collections import OrderedDict
import mock
import oauthlib
import six.moves.urllib.error # pylint: disable=import-error
import six.moves.urllib.parse # pylint: disable=import-error
import six.moves.urllib.request # pylint: disable=import-error
from django.conf import settings
from django.urls import reverse
from six import text_type
import oauthlib
from courseware.tests.helpers import BaseTestXmodule
from courseware.views.views import get_course_lti_endpoints
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
@@ -42,10 +46,12 @@ class TestLTI(BaseTestXmodule):
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 = text_type(urllib.quote('{}-{}'.format(hostname, self.item_descriptor.location.html_id())))
resource_link_id = text_type(six.moves.urllib.parse.quote('{}-{}'.format(hostname,
self.item_descriptor.location.html_id()
)))
sourcedId = "{context}:{resource_link}:{user_id}".format(
context=urllib.quote(context_id),
context=six.moves.urllib.parse.quote(context_id),
resource_link=resource_link_id,
user_id=user_id
)

View File

@@ -2,16 +2,20 @@
"""
Unit tests for masquerade.
"""
from __future__ import absolute_import
import json
import pickle
from datetime import datetime
import ddt
import six
from django.conf import settings
from django.urls import reverse
from django.test import TestCase
from django.urls import reverse
from mock import patch
from pytz import UTC
from xblock.runtime import DictKeyValueStore
from capa.tests.response_xml_factory import OptionResponseXMLFactory
from courseware.masquerade import CourseMasquerade, MasqueradingKeyValueStore, get_masquerading_user_group
@@ -25,7 +29,6 @@ from openedx.core.djangoapps.waffle_utils.testutils import override_waffle_flag
from openedx.features.course_experience import UNIFIED_COURSE_TAB_FLAG
from student.models import CourseEnrollment
from student.tests.factories import UserFactory
from xblock.runtime import DictKeyValueStore
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
@@ -89,7 +92,7 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.chapter.location.block_id,
'section': self.sequential.location.block_id,
}
@@ -103,7 +106,7 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
url = reverse(
'info',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
}
)
return self.client.get(url)
@@ -115,7 +118,7 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
url = reverse(
'progress',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
}
)
return self.client.get(url)
@@ -135,8 +138,8 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase):
problem_url = reverse(
'xblock_handler',
kwargs={
'course_id': unicode(self.course.id),
'usage_id': unicode(self.problem.location),
'course_id': six.text_type(self.course.id),
'usage_id': six.text_type(self.problem.location),
'handler': 'xmodule_handler',
'suffix': 'problem_get'
}
@@ -207,7 +210,7 @@ class StaffMasqueradeTestCase(MasqueradeTestCase):
masquerade_url = reverse(
'masquerade_update',
kwargs={
'course_key_string': unicode(self.course.id),
'course_key_string': six.text_type(self.course.id),
}
)
response = self.client.post(

View File

@@ -2,13 +2,17 @@
Tests related to the Site Configuration feature
"""
from bs4 import BeautifulSoup
from __future__ import absolute_import
from contextlib import contextmanager
from bs4 import BeautifulSoup
from django.conf import settings
from django.urls import reverse
from django.test.utils import override_settings
from django.urls import reverse
from mock import patch
from six import text_type
from six.moves import range
from course_modes.models import CourseMode
from courseware.tests.helpers import LoginEnrollmentTestCase

View File

@@ -2,6 +2,8 @@
Tests for courseware middleware
"""
from __future__ import absolute_import
from django.http import Http404
from django.test.client import RequestFactory

View File

@@ -1,6 +1,8 @@
"""
Test for lms courseware app, module data (runtime data storage for XBlocks)
"""
from __future__ import absolute_import
import json
from functools import partial
@@ -18,14 +20,9 @@ from courseware.models import (
XModuleStudentPrefsField,
XModuleUserStateSummaryField
)
from courseware.tests.factories import StudentInfoFactory
from courseware.tests.factories import StudentModuleFactory as cmfStudentModuleFactory
from courseware.tests.factories import (
StudentInfoFactory,
StudentPrefsFactory,
UserStateSummaryFactory,
course_id,
location
)
from courseware.tests.factories import StudentPrefsFactory, UserStateSummaryFactory, course_id, location
from student.tests.factories import UserFactory

View File

@@ -2,6 +2,8 @@
"""
Test for lms courseware app, module render unit
"""
from __future__ import absolute_import
import itertools
import json
from datetime import datetime
@@ -9,20 +11,21 @@ from functools import partial
import ddt
import pytz
import six
from bson import ObjectId
from completion.models import BlockCompletion
from completion import waffle as completion_waffle
from completion.models import BlockCompletion
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.http import Http404, HttpResponse
from django.middleware.csrf import get_token
from django.test.client import RequestFactory
from django.urls import reverse
from django.http import Http404, HttpResponse
from django.test.utils import override_settings
from django.urls import reverse
from edx_oauth2_provider.tests.factories import AccessTokenFactory, ClientFactory
from edx_proctoring.api import create_exam, create_exam_attempt, update_attempt_status
from edx_proctoring.runtime import set_runtime_service
from edx_proctoring.tests.test_services import MockCreditService, MockGradesService, MockCertificateService
from edx_proctoring.tests.test_services import MockCertificateService, MockCreditService, MockGradesService
from freezegun import freeze_time
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import MagicMock, Mock, patch
@@ -30,39 +33,36 @@ from opaque_keys.edx.asides import AsideUsageKeyV2
from opaque_keys.edx.keys import CourseKey, UsageKey
from pyquery import PyQuery
from six import text_type
from six.moves import range
from web_fragments.fragment import Fragment
from xblock.completable import CompletableXBlockMixin
from xblock.core import XBlock, XBlockAside
from xblock.field_data import FieldData
from xblock.fields import ScopeIds
from xblock.runtime import (
DictKeyValueStore,
KvsFieldData,
Runtime
)
from xblock.runtime import DictKeyValueStore, KvsFieldData, Runtime
from xblock.test.tools import TestRuntime
from capa.tests.response_xml_factory import OptionResponseXMLFactory
from course_modes.models import CourseMode
from courseware import module_render as render
from courseware.courses import get_course_info_section, get_course_with_access
from courseware.access_response import AccessResponse
from courseware.courses import get_course_info_section, get_course_with_access
from courseware.masquerade import CourseMasquerade
from courseware.model_data import FieldDataCache
from courseware.models import StudentModule
from courseware.module_render import get_module_for_descriptor, hash_resource
from courseware.tests.factories import GlobalStaffFactory, StudentModuleFactory, UserFactory, RequestFactoryNoCsrf
from courseware.tests.factories import GlobalStaffFactory, RequestFactoryNoCsrf, StudentModuleFactory, UserFactory
from courseware.tests.test_submitting_problems import TestSubmittingProblems
from courseware.tests.tests import LoginEnrollmentTestCase
from lms.djangoapps.lms_xblock.field_data import LmsFieldData
from lms.djangoapps.courseware.field_overrides import OverrideFieldData
from lms.djangoapps.lms_xblock.field_data import LmsFieldData
from openedx.core.djangoapps.credit.api import set_credit_requirement_status, set_credit_requirements
from openedx.core.djangoapps.credit.models import CreditCourse
from openedx.core.djangoapps.oauth_dispatch.jwt import create_jwt_for_user
from openedx.core.lib.courses import course_image_url
from openedx.core.lib.gating import api as gating_api
from openedx.core.lib.url_utils import quote_slashes
from student.models import anonymous_id_for_user, CourseEnrollment
from student.models import CourseEnrollment, anonymous_id_for_user
from verify_student.tests.factories import SoftwareSecurePhotoVerificationFactory
from xblock_django.models import XBlockConfiguration
from xmodule.capa_module import ProblemBlock
@@ -2416,7 +2416,7 @@ class EmptyXModuleDescriptorWithChildren(EmptyXModuleDescriptor): # pylint: dis
BLOCK_TYPES = ['xblock', 'xmodule']
USER_NUMBERS = range(2)
USER_NUMBERS = list(range(2))
@ddt.ddt
@@ -2512,10 +2512,10 @@ class TestFilteredChildren(SharedModuleStoreTestCase):
ItemFactory(category=child_type, parent=self.parent).scope_ids.usage_id
for child_type in BLOCK_TYPES
]
for user in self.users.itervalues()
for user in six.itervalues(self.users)
}
self.all_children = sum(self.children_for_user.values(), [])
self.all_children = sum(list(self.children_for_user.values()), [])
return modulestore().get_item(self.parent.scope_ids.usage_id)

View File

@@ -1,13 +1,16 @@
"""
This test file will run through some LMS test scenarios regarding access and navigation of the LMS
"""
from __future__ import absolute_import
import time
from django.conf import settings
from django.urls import reverse
from django.test.utils import override_settings
from django.urls import reverse
from mock import patch
from six import text_type
from six.moves import range
from courseware.tests.factories import GlobalStaffFactory
from courseware.tests.helpers import LoginEnrollmentTestCase

View File

@@ -1,6 +1,8 @@
"""
This file will test through the LMS some of the password reset features
"""
from __future__ import absolute_import
from uuid import uuid4
import ddt

View File

@@ -1,13 +1,14 @@
"""
Tests for permissions defined in courseware.rules
"""
import ddt
from __future__ import absolute_import
import ddt
import six
from django.test import TestCase
from opaque_keys.edx.locator import CourseLocator
from course_modes.tests.factories import CourseModeFactory
from opaque_keys.edx.locator import CourseLocator
from student.models import CourseEnrollment
from student.tests.factories import UserFactory
@@ -46,5 +47,6 @@ class PermissionTests(TestCase):
"""
if mode is not None:
CourseEnrollment.enroll(self.user, self.course_id, mode=mode)
has_perm = self.user.has_perm('edx_proctoring.can_take_proctored_exam', {'course_id': unicode(self.course_id)})
has_perm = self.user.has_perm('edx_proctoring.can_take_proctored_exam',
{'course_id': six.text_type(self.course_id)})
assert has_perm == should_have_perm

View File

@@ -1,5 +1,7 @@
"""Tests for self-paced course due date overrides."""
# pylint: disable=missing-docstring
from __future__ import absolute_import
import datetime
import pytz

View File

@@ -1,6 +1,9 @@
"""
Test for split test XModule
"""
from __future__ import absolute_import
import six
from django.urls import reverse
from mock import MagicMock
from six import text_type
@@ -134,10 +137,10 @@ class SplitTestBase(SharedModuleStoreTestCase):
unicode_content = content.decode("utf-8")
for key in self.included_usage_keys[user_tag]:
self.assertIn(unicode(key), unicode_content)
self.assertIn(six.text_type(key), unicode_content)
for key in self.excluded_usage_keys[user_tag]:
self.assertNotIn(unicode(key), unicode_content)
self.assertNotIn(six.text_type(key), unicode_content)
# Assert that we can see the data from the appropriate test condition
for visible in self.VISIBLE_CONTENT[user_tag]:

View File

@@ -5,19 +5,23 @@ Integration tests for submitting problem responses and getting grades.
# pylint: disable=attribute-defined-outside-init
from __future__ import absolute_import
import json
import os
from textwrap import dedent
import ddt
import six
from django.conf import settings
from django.contrib.auth.models import User
from django.urls import reverse
from django.test import TestCase
from django.test.client import RequestFactory
from django.urls import reverse
from django.utils.timezone import now
from mock import patch
from six import text_type
from submissions import api as submissions_api
from capa.tests.response_xml_factory import (
CodeResponseXMLFactory,
@@ -34,7 +38,6 @@ from openedx.core.djangoapps.credit.models import CreditCourse, CreditProvider
from openedx.core.djangoapps.user_api.tests.factories import UserCourseTagFactory
from openedx.core.lib.url_utils import quote_slashes
from student.models import CourseEnrollment, anonymous_id_for_user
from submissions import api as submissions_api
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
from xmodule.partitions.partitions import Group, UserPartition
@@ -275,14 +278,15 @@ class TestSubmittingProblems(ModuleStoreTestCase, LoginEnrollmentTestCase, Probl
Returns list of scores: [<points on hw_1>, <points on hw_2>, ..., <points on hw_n>]
"""
return [
s.graded_total.earned for s in self.get_course_grade().graded_subsections_by_format['Homework'].itervalues()
s.graded_total.earned for s in six.itervalues(
self.get_course_grade().graded_subsections_by_format['Homework'])
]
def hw_grade(self, hw_url_name):
"""
Returns SubsectionGrade for given url.
"""
for chapter in self.get_course_grade().chapter_grades.itervalues():
for chapter in six.itervalues(self.get_course_grade().chapter_grades):
for section in chapter['sections']:
if section.url_name == hw_url_name:
return section
@@ -319,7 +323,7 @@ class TestCourseGrades(TestSubmittingProblems):
Verifies the problem score and the homework grade are as expected.
"""
hw_grade = self.hw_grade('homework')
problem_score = hw_grade.problem_scores.values()[0]
problem_score = list(hw_grade.problem_scores.values())[0]
self.assertEquals((problem_score.earned, problem_score.possible), expected_problem_score)
self.assertEquals((hw_grade.graded_total.earned, hw_grade.graded_total.possible), expected_hw_grade)
@@ -405,7 +409,7 @@ class TestCourseGrader(TestSubmittingProblems):
]
}
self.add_grading_policy(grading_policy)
task_compute_all_grades_for_course.apply_async(kwargs={'course_key': unicode(self.course.id)})
task_compute_all_grades_for_course.apply_async(kwargs={'course_key': six.text_type(self.course.id)})
def dropping_setup(self):
"""
@@ -581,8 +585,8 @@ class TestCourseGrader(TestSubmittingProblems):
student_item = {
'student_id': anonymous_id_for_user(self.student_user, self.course.id),
'course_id': unicode(self.course.id),
'item_id': unicode(self.problem_location('p3')),
'course_id': six.text_type(self.course.id),
'item_id': six.text_type(self.problem_location('p3')),
'item_type': 'problem'
}
submission = submissions_api.create_submission(student_item, 'any answer')
@@ -799,8 +803,8 @@ class ProblemWithUploadedFilesTest(TestSubmittingProblems):
self.assertEqual(name, "post")
self.assertEqual(len(args), 1)
self.assertTrue(args[0].endswith("/submit/"))
self.assertItemsEqual(kwargs.keys(), ["files", "data", "timeout"])
self.assertItemsEqual(kwargs['files'].keys(), filenames.split())
self.assertItemsEqual(list(kwargs.keys()), ["files", "data", "timeout"])
self.assertItemsEqual(list(kwargs['files'].keys()), filenames.split())
class TestPythonGradedResponse(TestSubmittingProblems):

View File

@@ -1,13 +1,17 @@
"""
Test cases for tabs.
"""
from __future__ import absolute_import
import six
from crum import set_current_request
from django.contrib.auth.models import AnonymousUser
from django.urls import reverse
from django.http import Http404
from django.urls import reverse
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import MagicMock, Mock, patch
from six import text_type
from crum import set_current_request
from six.moves import range
from courseware.courses import get_course_by_id
from courseware.tabs import (
@@ -381,22 +385,22 @@ class EntranceExamsTabsTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, Mi
)
milestone = {
'name': 'Test Milestone',
'namespace': '{}.entrance_exams'.format(unicode(self.course.id)),
'namespace': '{}.entrance_exams'.format(six.text_type(self.course.id)),
'description': 'Testing Courseware Tabs'
}
self.user.is_staff = False
request = get_mock_request(self.user)
self.course.entrance_exam_enabled = True
self.course.entrance_exam_id = unicode(entrance_exam.location)
self.course.entrance_exam_id = six.text_type(entrance_exam.location)
milestone = add_milestone(milestone)
add_course_milestone(
unicode(self.course.id),
six.text_type(self.course.id),
self.relationship_types['REQUIRES'],
milestone
)
add_course_content_milestone(
unicode(self.course.id),
unicode(entrance_exam.location),
six.text_type(self.course.id),
six.text_type(entrance_exam.location),
self.relationship_types['FULFILLS'],
milestone
)
@@ -416,7 +420,7 @@ class EntranceExamsTabsTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, Mi
self.client.logout()
self.client.login(username=instructor.username, password='test')
url = reverse('mark_student_can_skip_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
url = reverse('mark_student_can_skip_entrance_exam', kwargs={'course_id': six.text_type(self.course.id)})
response = self.client.post(url, {
'unique_student_identifier': student.email,
})
@@ -816,7 +820,7 @@ class DiscussionLinkTestCase(TabTestCase):
"""Custom reverse function"""
def reverse_discussion_link(viewname, args):
"""reverse lookup for discussion link"""
if viewname == "forum_form_discussion" and args == [unicode(course.id)]:
if viewname == "forum_form_discussion" and args == [six.text_type(course.id)]:
return "default_discussion_link"
return reverse_discussion_link

View File

@@ -3,6 +3,8 @@ Black-box tests of the DjangoUserStateClient against the semantics
defined in edx_user_state_client.
"""
from __future__ import absolute_import
from collections import defaultdict
from edx_user_state_client.tests import UserStateClientTestBase

View File

@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
"""Video xmodule tests in mongo."""
from __future__ import absolute_import
import json
import os
import tempfile
@@ -9,8 +11,10 @@ from datetime import timedelta
import ddt
import freezegun
import six
from django.core.files.base import ContentFile
from django.utils.timezone import now
from edxval import api
from mock import MagicMock, Mock, patch
from webob import Request, Response
@@ -21,19 +25,12 @@ from xmodule.contentstore.django import contentstore
from xmodule.exceptions import NotFoundError
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.video_module.transcripts_utils import (
Transcript,
edxval_api,
subs_filename,
)
from xmodule.video_module.transcripts_utils import Transcript, edxval_api, subs_filename
from xmodule.x_module import STUDENT_VIEW
from edxval import api
from .helpers import BaseTestXmodule
from .test_video_xml import SOURCE_XML
TRANSCRIPT = {"start": [10], "end": [100], "text": ["Hi, welcome to Edx."]}
BUMPER_TRANSCRIPT = {"start": [1], "end": [10], "text": ["A bumper"]}
SRT_content = textwrap.dedent("""
@@ -321,7 +318,7 @@ class TestTranscriptAvailableTranslationsDispatch(TestVideo):
Tests available translations with video component's and val's transcript languages
while the feature is enabled.
"""
for lang_code, in_content_store in dict(transcripts).iteritems():
for lang_code, in_content_store in six.iteritems(dict(transcripts)):
if in_content_store:
file_name, __ = os.path.split(self.srt_file.name)
_upload_file(self.srt_file, self.item_descriptor.location, file_name)
@@ -531,7 +528,7 @@ class TestTranscriptDownloadDispatch(TestVideo):
# Assert the actual response
self.assertEqual(response.status_code, 200)
self.assertEqual(response.text, expected_content)
for attribute, value in expected_headers.iteritems():
for attribute, value in six.iteritems(expected_headers):
self.assertEqual(response.headers[attribute], value)
@@ -801,7 +798,7 @@ class TestTranscriptTranslationGetDispatch(TestVideo):
# Assert the actual response
self.assertEqual(response.status_code, 200)
self.assertEqual(response.text, transcript['content'])
for attribute, value in expected_headers.iteritems():
for attribute, value in six.iteritems(expected_headers):
self.assertEqual(response.headers[attribute], value)
@patch('xmodule.video_module.VideoModule.translation', Mock(side_effect=NotFoundError))
@@ -1022,7 +1019,7 @@ class TestStudioTranscriptTranslationDeleteDispatch(TestVideo):
'client_video_id': 'awesome.mp4',
'duration': 0,
'encoded_videos': [],
'courses': [unicode(self.course.id)]
'courses': [six.text_type(self.course.id)]
})
api.create_video_transcript(
video_id=self.EDX_VIDEO_ID,

View File

@@ -3,6 +3,8 @@
Video xmodule tests in mongo.
"""
from __future__ import absolute_import
import json
import shutil
from collections import OrderedDict
@@ -10,6 +12,7 @@ from tempfile import mkdtemp
from uuid import uuid4
import ddt
import six
from django.conf import settings
from django.core.files import File
from django.core.files.base import ContentFile
@@ -32,11 +35,11 @@ from fs.path import combine
from lxml import etree
from mock import MagicMock, Mock, patch
from path import Path as path
from openedx.core.djangolib.testing.utils import CacheIsolationTestCase
from openedx.core.djangoapps.waffle_utils.models import WaffleFlagCourseOverrideModel
from openedx.core.djangoapps.video_pipeline.config.waffle import waffle_flags, DEPRECATE_YOUTUBE
from waffle.testutils import override_flag
from openedx.core.djangoapps.video_pipeline.config.waffle import DEPRECATE_YOUTUBE, waffle_flags
from openedx.core.djangoapps.waffle_utils.models import WaffleFlagCourseOverrideModel
from openedx.core.djangolib.testing.utils import CacheIsolationTestCase
from xmodule.contentstore.content import StaticContent
from xmodule.exceptions import NotFoundError
from xmodule.modulestore import ModuleStoreEnum
@@ -46,11 +49,8 @@ from xmodule.tests.test_import import DummySystem
from xmodule.tests.test_video import VideoDescriptorTestBase, instantiate_descriptor
from xmodule.video_module import VideoDescriptor, bumper_utils, video_utils
from xmodule.video_module.transcripts_utils import Transcript, save_to_store, subs_filename
from xmodule.video_module.video_module import (
EXPORT_IMPORT_COURSE_DIR,
EXPORT_IMPORT_STATIC_DIR,
)
from xmodule.x_module import STUDENT_VIEW, PUBLIC_VIEW
from xmodule.video_module.video_module import EXPORT_IMPORT_COURSE_DIR, EXPORT_IMPORT_STATIC_DIR
from xmodule.x_module import PUBLIC_VIEW, STUDENT_VIEW
from .helpers import BaseTestXmodule
from .test_video_handlers import TestVideo
@@ -1409,7 +1409,7 @@ class TestEditorSavedMethod(BaseTestXmodule):
Verify editor saved when video id contains spaces/tabs.
"""
self.MODULESTORE = MODULESTORES[default_store]
stripped_video_id = unicode(uuid4())
stripped_video_id = six.text_type(uuid4())
unstripped_video_id = u'{video_id}{tabs}'.format(video_id=stripped_video_id, tabs=u'\t\t\t')
self.metadata.update({
'edx_video_id': unstripped_video_id
@@ -1438,7 +1438,7 @@ class TestEditorSavedMethod(BaseTestXmodule):
# Now, modify `edx_video_id` and save should override `youtube_id_1_0`.
old_metadata = own_metadata(item)
item.edx_video_id = unicode(uuid4())
item.edx_video_id = six.text_type(uuid4())
item.editor_saved(self.user, old_metadata, None)
self.assertEqual(item.youtube_id_1_0, 'test_yt_id')
@@ -1491,7 +1491,7 @@ class TestVideoDescriptorStudentViewJson(CacheIsolationTestCase):
'duration': self.TEST_DURATION,
'status': 'dummy',
'encoded_videos': [self.TEST_ENCODED_VIDEO],
'courses': [unicode(self.video.location.course_key)] if associate_course_in_val else [],
'courses': [six.text_type(self.video.location.course_key)] if associate_course_in_val else [],
})
self.val_video = get_video_info(self.TEST_EDX_VIDEO_ID) # pylint: disable=attribute-defined-outside-init
@@ -1635,7 +1635,7 @@ class TestVideoDescriptorStudentViewJson(CacheIsolationTestCase):
self.video.transcripts = transcripts
self.video.sub = english_sub
student_view_response = self.get_result()
self.assertItemsEqual(student_view_response['transcripts'].keys(), expected_transcripts)
self.assertItemsEqual(list(student_view_response['transcripts'].keys()), expected_transcripts)
@ddt.ddt

View File

@@ -14,10 +14,11 @@ You can then use the CourseFactory and XModuleItemFactory as defined in
common/lib/xmodule/xmodule/modulestore/tests/factories.py to create the
course, section, subsection, unit, etc.
"""
from __future__ import absolute_import
from xmodule.tests import LogicTest
from xmodule.video_module import VideoDescriptor
SOURCE_XML = """
<video show_captions="true"
display_name="A Name"

View File

@@ -1,9 +1,16 @@
"""
Check that view authentication works properly.
"""
from __future__ import absolute_import
import datetime
import pytz
from django.urls import reverse
from mock import patch
from six import text_type
from six.moves import range
from courseware.access import has_access
from courseware.tests.factories import (
@@ -84,7 +91,7 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro
urls.extend([
reverse('book', kwargs={'course_id': text_type(course.id),
'book_index': index})
for index in xrange(len(course.textbooks))
for index in range(len(course.textbooks))
])
for url in urls:
self.assert_request_status_code(200, url)

View File

@@ -2,32 +2,36 @@
"""
Tests courseware views.py
"""
from __future__ import absolute_import
import itertools
import json
import unittest
from datetime import datetime, timedelta
from HTMLParser import HTMLParser
from urllib import quote, urlencode
from uuid import uuid4
from crum import set_current_request
from markupsafe import escape
from completion.test_utils import CompletionWaffleTestMixin
import ddt
import six
from completion.test_utils import CompletionWaffleTestMixin
from crum import set_current_request
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.urls import reverse, reverse_lazy
from django.http import Http404, HttpResponseBadRequest
from django.test import TestCase, RequestFactory
from django.test import RequestFactory, TestCase
from django.test.client import Client
from django.test.utils import override_settings
from django.urls import reverse, reverse_lazy
from freezegun import freeze_time
from markupsafe import escape
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import MagicMock, PropertyMock, create_autospec, patch
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
from pytz import UTC
from six import text_type
from six.moves import range
from six.moves.html_parser import HTMLParser # pylint: disable=import-error
from six.moves.urllib.parse import quote, urlencode # pylint: disable=import-error
from web_fragments.fragment import Fragment
from xblock.core import XBlock
from xblock.fields import Scope, String
@@ -40,20 +44,22 @@ from course_modes.tests.factories import CourseModeFactory
from courseware.access_utils import check_course_open_for_learner
from courseware.model_data import FieldDataCache, set_score
from courseware.module_render import get_module, handle_xblock_callback
from courseware.tests.factories import GlobalStaffFactory, StudentModuleFactory, RequestFactoryNoCsrf
from courseware.tests.factories import GlobalStaffFactory, RequestFactoryNoCsrf, StudentModuleFactory
from courseware.tests.helpers import get_expiration_banner_text
from courseware.testutils import RenderXBlockTestMixin
from courseware.url_helpers import get_redirect_url
from courseware.user_state_client import DjangoXBlockUserStateClient
from lms.djangoapps.certificates import api as certs_api
from lms.djangoapps.certificates.models import (
CertificateGenerationConfiguration, CertificateStatuses, CertificateWhitelist,
CertificateGenerationConfiguration,
CertificateStatuses,
CertificateWhitelist
)
from lms.djangoapps.certificates.tests.factories import CertificateInvalidationFactory, GeneratedCertificateFactory
from lms.djangoapps.commerce.models import CommerceConfiguration
from lms.djangoapps.commerce.utils import EcommerceService
from lms.djangoapps.grades.config.waffle import waffle as grades_waffle
from lms.djangoapps.grades.config.waffle import ASSUME_ZERO_GRADE_IF_ABSENT
from lms.djangoapps.grades.config.waffle import waffle as grades_waffle
from lms.djangoapps.verify_student.services import IDVerificationService
from openedx.core.djangoapps.catalog.tests.factories import CourseFactory as CatalogCourseFactory
from openedx.core.djangoapps.catalog.tests.factories import CourseRunFactory, ProgramFactory
@@ -67,27 +73,27 @@ from openedx.core.lib.gating import api as gating_api
from openedx.core.lib.url_utils import quote_slashes
from openedx.features.content_type_gating.models import ContentTypeGatingConfig
from openedx.features.course_duration_limits.models import CourseDurationLimitConfig
from openedx.features.course_experience.tests.views.helpers import add_course_mode
from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseTestConsentRequired
from openedx.features.course_experience import (
COURSE_ENABLE_UNENROLLED_ACCESS_FLAG,
COURSE_OUTLINE_PAGE_FLAG,
UNIFIED_COURSE_TAB_FLAG,
UNIFIED_COURSE_TAB_FLAG
)
from openedx.features.course_experience.tests.views.helpers import add_course_mode
from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseTestConsentRequired
from student.models import CourseEnrollment
from student.tests.factories import TEST_PASSWORD, AdminFactory, CourseEnrollmentFactory, UserFactory
from util.tests.test_date_utils import fake_pgettext, fake_ugettext
from util.url import reload_django_url_config
from util.views import ensure_valid_course_key
from xmodule.course_module import COURSE_VISIBILITY_PRIVATE, COURSE_VISIBILITY_PUBLIC_OUTLINE, COURSE_VISIBILITY_PUBLIC
from xmodule.course_module import COURSE_VISIBILITY_PRIVATE, COURSE_VISIBILITY_PUBLIC, COURSE_VISIBILITY_PUBLIC_OUTLINE
from xmodule.graders import ShowCorrectness
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import (
TEST_DATA_MIXED_MODULESTORE,
ModuleStoreTestCase,
SharedModuleStoreTestCase,
CourseUserType,
ModuleStoreTestCase,
SharedModuleStoreTestCase
)
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls
@@ -112,7 +118,7 @@ class TestJumpTo(ModuleStoreTestCase):
location = self.course_key.make_usage_key(None, 'NoSuchPlace')
# This is fragile, but unfortunately the problem is that within the LMS we
# can't use the reverse calls from the CMS
jumpto_url = '{0}/{1}/jump_to/{2}'.format('/courses', unicode(self.course_key), unicode(location))
jumpto_url = '{0}/{1}/jump_to/{2}'.format('/courses', six.text_type(self.course_key), six.text_type(location))
response = self.client.get(jumpto_url)
self.assertEqual(response.status_code, 404)
@@ -121,15 +127,15 @@ class TestJumpTo(ModuleStoreTestCase):
chapter = ItemFactory.create(category='chapter', parent_location=course.location)
section = ItemFactory.create(category='sequential', parent_location=chapter.location)
expected = '/courses/{course_id}/courseware/{chapter_id}/{section_id}/?{activate_block_id}'.format(
course_id=unicode(course.id),
course_id=six.text_type(course.id),
chapter_id=chapter.url_name,
section_id=section.url_name,
activate_block_id=urlencode({'activate_block_id': unicode(section.location)})
activate_block_id=urlencode({'activate_block_id': six.text_type(section.location)})
)
jumpto_url = '{0}/{1}/jump_to/{2}'.format(
'/courses',
unicode(course.id),
unicode(section.location),
six.text_type(course.id),
six.text_type(section.location),
)
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_code=302)
@@ -144,29 +150,29 @@ class TestJumpTo(ModuleStoreTestCase):
module2 = ItemFactory.create(category='html', parent_location=vertical2.location)
expected = '/courses/{course_id}/courseware/{chapter_id}/{section_id}/1?{activate_block_id}'.format(
course_id=unicode(course.id),
course_id=six.text_type(course.id),
chapter_id=chapter.url_name,
section_id=section.url_name,
activate_block_id=urlencode({'activate_block_id': unicode(module1.location)})
activate_block_id=urlencode({'activate_block_id': six.text_type(module1.location)})
)
jumpto_url = '{0}/{1}/jump_to/{2}'.format(
'/courses',
unicode(course.id),
unicode(module1.location),
six.text_type(course.id),
six.text_type(module1.location),
)
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_code=302)
expected = '/courses/{course_id}/courseware/{chapter_id}/{section_id}/2?{activate_block_id}'.format(
course_id=unicode(course.id),
course_id=six.text_type(course.id),
chapter_id=chapter.url_name,
section_id=section.url_name,
activate_block_id=urlencode({'activate_block_id': unicode(module2.location)})
activate_block_id=urlencode({'activate_block_id': six.text_type(module2.location)})
)
jumpto_url = '{0}/{1}/jump_to/{2}'.format(
'/courses',
unicode(course.id),
unicode(module2.location),
six.text_type(course.id),
six.text_type(module2.location),
)
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_code=302)
@@ -186,15 +192,15 @@ class TestJumpTo(ModuleStoreTestCase):
# internal position of module2 will be 1_2 (2nd item withing 1st item)
expected = '/courses/{course_id}/courseware/{chapter_id}/{section_id}/1?{activate_block_id}'.format(
course_id=unicode(course.id),
course_id=six.text_type(course.id),
chapter_id=chapter.url_name,
section_id=section.url_name,
activate_block_id=urlencode({'activate_block_id': unicode(module2.location)})
activate_block_id=urlencode({'activate_block_id': six.text_type(module2.location)})
)
jumpto_url = '{0}/{1}/jump_to/{2}'.format(
'/courses',
unicode(course.id),
unicode(module2.location),
six.text_type(course.id),
six.text_type(module2.location),
)
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_code=302)
@@ -202,7 +208,9 @@ class TestJumpTo(ModuleStoreTestCase):
def test_jumpto_id_invalid_location(self):
location = BlockUsageLocator(CourseLocator('edX', 'toy', 'NoSuchPlace', deprecated=True),
None, None, deprecated=True)
jumpto_url = '{0}/{1}/jump_to_id/{2}'.format('/courses', unicode(self.course_key), unicode(location))
jumpto_url = '{0}/{1}/jump_to_id/{2}'.format('/courses',
six.text_type(self.course_key),
six.text_type(location))
response = self.client.get(jumpto_url)
self.assertEqual(response.status_code, 404)
@@ -241,9 +249,9 @@ class IndexQueryTestCase(ModuleStoreTestCase):
url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(course.id),
'chapter': unicode(chapter.location.block_id),
'section': unicode(section.location.block_id),
'course_id': six.text_type(course.id),
'chapter': six.text_type(chapter.location.block_id),
'section': six.text_type(section.location.block_id),
}
)
response = self.client.get(url)
@@ -324,15 +332,15 @@ class ViewsTestCase(ModuleStoreTestCase):
def test_index_success(self):
response = self._verify_index_response()
self.assertIn(unicode(self.problem2.location), response.content.decode("utf-8"))
self.assertIn(six.text_type(self.problem2.location), response.content.decode("utf-8"))
# re-access to the main course page redirects to last accessed view.
url = reverse('courseware', kwargs={'course_id': unicode(self.course_key)})
url = reverse('courseware', kwargs={'course_id': six.text_type(self.course_key)})
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
response = self.client.get(response.url)
self.assertNotIn(unicode(self.problem.location), response.content.decode("utf-8"))
self.assertIn(unicode(self.problem2.location), response.content.decode("utf-8"))
self.assertNotIn(six.text_type(self.problem.location), response.content.decode("utf-8"))
self.assertIn(six.text_type(self.problem2.location), response.content.decode("utf-8"))
def test_index_nonexistent_chapter(self):
self._verify_index_response(expected_response_code=404, chapter_name='non-existent')
@@ -360,9 +368,9 @@ class ViewsTestCase(ModuleStoreTestCase):
url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course_key),
'chapter': unicode(self.chapter.location.block_id) if chapter_name is None else chapter_name,
'section': unicode(self.section2.location.block_id) if section_name is None else section_name,
'course_id': six.text_type(self.course_key),
'chapter': six.text_type(self.chapter.location.block_id) if chapter_name is None else chapter_name,
'section': six.text_type(self.section2.location.block_id) if section_name is None else section_name,
}
)
response = self.client.get(url)
@@ -381,7 +389,8 @@ class ViewsTestCase(ModuleStoreTestCase):
url = reverse(
'courseware_chapter',
kwargs={'course_id': unicode(self.course.id), 'chapter': unicode(self.chapter.location.block_id)},
kwargs={'course_id': six.text_type(self.course.id),
'chapter': six.text_type(self.chapter.location.block_id)},
)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
@@ -403,14 +412,14 @@ class ViewsTestCase(ModuleStoreTestCase):
courseware_url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course_key),
'chapter': unicode(self.chapter.location.block_id),
'section': unicode(self.section.location.block_id),
'course_id': six.text_type(self.course_key),
'chapter': six.text_type(self.chapter.location.block_id),
'section': six.text_type(self.section.location.block_id),
}
)
# create the url for enroll_staff view
enroll_url = "{enroll_url}?next={courseware_url}".format(
enroll_url=reverse('enroll_staff', kwargs={'course_id': unicode(self.course.id)}),
enroll_url=reverse('enroll_staff', kwargs={'course_id': six.text_type(self.course.id)}),
courseware_url=courseware_url
)
return courseware_url, enroll_url
@@ -434,7 +443,7 @@ class ViewsTestCase(ModuleStoreTestCase):
if enrollment:
self.assertRedirects(response, courseware_url)
else:
self.assertRedirects(response, '/courses/{}/about'.format(unicode(self.course_key)))
self.assertRedirects(response, '/courses/{}/about'.format(six.text_type(self.course_key)))
def test_enroll_staff_with_invalid_data(self):
"""
@@ -445,7 +454,7 @@ class ViewsTestCase(ModuleStoreTestCase):
__, enroll_url = self._create_url_for_enroll_staff()
response = self.client.post(enroll_url, data={'test': "test"})
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, '/courses/{}/about'.format(unicode(self.course_key)))
self.assertRedirects(response, '/courses/{}/about'.format(six.text_type(self.course_key)))
@unittest.skipUnless(settings.FEATURES.get('ENABLE_SHOPPING_CART'), "Shopping Cart not enabled in settings")
@patch.dict(settings.FEATURES, {'ENABLE_PAID_COURSE_REGISTRATION': True})
@@ -455,20 +464,20 @@ class ViewsTestCase(ModuleStoreTestCase):
course = CourseFactory.create(org="new", number="unenrolled", display_name="course")
self.client.logout()
response = self.client.get(reverse('about_course', args=[unicode(course.id)]))
response = self.client.get(reverse('about_course', args=[six.text_type(course.id)]))
self.assertEqual(response.status_code, 200)
self.assertNotIn(in_cart_span, response.content)
# authenticated user with nothing in cart
self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD))
response = self.client.get(reverse('about_course', args=[unicode(course.id)]))
response = self.client.get(reverse('about_course', args=[six.text_type(course.id)]))
self.assertEqual(response.status_code, 200)
self.assertNotIn(in_cart_span, response.content)
# now add the course to the cart
cart = shoppingcart.models.Order.get_cart_for_user(self.user)
shoppingcart.models.PaidCourseRegistration.add_to_order(cart, course.id)
response = self.client.get(reverse('about_course', args=[unicode(course.id)]))
response = self.client.get(reverse('about_course', args=[six.text_type(course.id)]))
self.assertEqual(response.status_code, 200)
self.assertIn(in_cart_span, response.content)
@@ -500,7 +509,7 @@ class ViewsTestCase(ModuleStoreTestCase):
)
# Generate the course about page content
response = self.client.get(reverse('about_course', args=[unicode(course.id)]))
response = self.client.get(reverse('about_course', args=[six.text_type(course.id)]))
self.assertEqual(response.status_code, 200)
self.assertIn(href, response.content.decode(response.charset))
@@ -560,7 +569,7 @@ class ViewsTestCase(ModuleStoreTestCase):
def test_index_invalid_position(self):
request_url = '/'.join([
'/courses',
unicode(self.course.id),
six.text_type(self.course.id),
'courseware',
self.chapter.location.block_id,
self.section.location.block_id,
@@ -573,7 +582,7 @@ class ViewsTestCase(ModuleStoreTestCase):
def test_unicode_handling_in_url(self):
url_parts = [
'/courses',
unicode(self.course.id),
six.text_type(self.course.id),
'courseware',
self.chapter.location.block_id,
self.section.location.block_id,
@@ -601,7 +610,7 @@ class ViewsTestCase(ModuleStoreTestCase):
If `expected_end_text` is None, verifies that the about page *does not* contain the text
"Classes End".
"""
result = self.client.get(reverse('about_course', args=[unicode(course_id)]))
result = self.client.get(reverse('about_course', args=[six.text_type(course_id)]))
if expected_end_text is not None:
self.assertContains(result, "Classes End")
self.assertContains(result, expected_end_text)
@@ -615,9 +624,9 @@ class ViewsTestCase(ModuleStoreTestCase):
self.assertTrue(self.client.login(username=admin.username, password='test'))
url = reverse('submission_history', kwargs={
'course_id': unicode(self.course_key),
'course_id': six.text_type(self.course_key),
'student_username': 'dummy',
'location': unicode(self.problem.location),
'location': six.text_type(self.problem.location),
})
response = self.client.get(url)
# Tests that we do not get an "Invalid x" response when passing correct arguments to view
@@ -631,7 +640,7 @@ class ViewsTestCase(ModuleStoreTestCase):
# try it with an existing user and a malicious location
url = reverse('submission_history', kwargs={
'course_id': unicode(self.course_key),
'course_id': six.text_type(self.course_key),
'student_username': 'dummy',
'location': '<script>alert("hello");</script>'
})
@@ -640,7 +649,7 @@ class ViewsTestCase(ModuleStoreTestCase):
# try it with a malicious user and a non-existent location
url = reverse('submission_history', kwargs={
'course_id': unicode(self.course_key),
'course_id': six.text_type(self.course_key),
'student_username': '<script>alert("hello");</script>',
'location': 'dummy'
})
@@ -673,9 +682,9 @@ class ViewsTestCase(ModuleStoreTestCase):
set_score(admin.id, usage_key, 3, 3)
url = reverse('submission_history', kwargs={
'course_id': unicode(self.course_key),
'course_id': six.text_type(self.course_key),
'student_username': admin.username,
'location': unicode(usage_key),
'location': six.text_type(usage_key),
})
response = self.client.get(url)
response_content = HTMLParser().unescape(response.content.decode('utf-8'))
@@ -714,9 +723,9 @@ class ViewsTestCase(ModuleStoreTestCase):
state={'field_a': 'x', 'field_b': 'y'}
)
url = reverse('submission_history', kwargs={
'course_id': unicode(course_key),
'course_id': six.text_type(course_key),
'student_username': admin.username,
'location': unicode(usage_key),
'location': six.text_type(usage_key),
})
response = client.get(url)
response_content = HTMLParser().unescape(response.content)
@@ -840,7 +849,7 @@ class ViewsTestCase(ModuleStoreTestCase):
@patch.object(views, '_record_feedback_in_zendesk')
def test_submit_financial_assistance_request(self, mock_record_feedback):
username = self.user.username
course = unicode(self.course_key)
course = six.text_type(self.course_key)
legal_name = 'Jesse Pinkman'
country = 'United States'
income = '1234567890'
@@ -866,7 +875,7 @@ class ViewsTestCase(ModuleStoreTestCase):
mocked_kwargs = mock_record_feedback.call_args[1]
group_name = mocked_kwargs['group_name']
require_update = mocked_kwargs['require_update']
private_comment = '\n'.join(additional_info.values())
private_comment = '\n'.join(list(additional_info.values()))
for info in (country, income, reason_for_applying, goals, effort, username, legal_name, course):
self.assertIn(info, private_comment)
@@ -888,7 +897,7 @@ class ViewsTestCase(ModuleStoreTestCase):
def test_zendesk_submission_failed(self, _mock_record_feedback):
response = self._submit_financial_assistance_form({
'username': self.user.username,
'course': unicode(self.course.id),
'course': six.text_type(self.course.id),
'name': '',
'email': '',
'country': '',
@@ -922,7 +931,7 @@ class ViewsTestCase(ModuleStoreTestCase):
@override_waffle_flag(UNIFIED_COURSE_TAB_FLAG, active=False)
def test_bypass_course_info(self):
course_id = unicode(self.course_key)
course_id = six.text_type(self.course_key)
self.assertFalse(self.course.bypass_home)
@@ -951,9 +960,9 @@ class ViewsTestCase(ModuleStoreTestCase):
returning a render_to_string, so we will render via the courseware URL in order to include
the needed context
"""
course_id = quote(unicode(self.course.id).encode("utf-8"))
course_id = quote(six.text_type(self.course.id).encode("utf-8"))
response = self.client.get(
reverse('courseware', args=[unicode(course_id)]),
reverse('courseware', args=[six.text_type(course_id)]),
follow=True
)
test_responses = [
@@ -977,7 +986,7 @@ class TestProgramMarketingView(SharedModuleStoreTestCase):
super(TestProgramMarketingView, cls).setUpClass()
modulestore_course = CourseFactory()
course_run = CourseRunFactory(key=unicode(modulestore_course.id))
course_run = CourseRunFactory(key=six.text_type(modulestore_course.id))
course = CatalogCourseFactory(course_runs=[course_run])
cls.data = ProgramFactory(
@@ -1093,7 +1102,7 @@ class TestProgressDueDate(BaseDueDateTests):
def get_response(self, course):
""" Returns the HTML for the progress page """
return self.client.get(reverse('progress', args=[unicode(course.id)]))
return self.client.get(reverse('progress', args=[six.text_type(course.id)]))
# TODO: LEARNER-71: Delete entire TestAccordionDueDate class
@@ -1106,7 +1115,7 @@ class TestAccordionDueDate(BaseDueDateTests):
def get_response(self, course):
""" Returns the HTML for the accordion """
return self.client.get(
reverse('courseware', args=[unicode(course.id)]),
reverse('courseware', args=[six.text_type(course.id)]),
follow=True
)
@@ -1160,7 +1169,7 @@ class StartDateTests(ModuleStoreTestCase):
"""
Get the text of the /about page for the course.
"""
return self.client.get(reverse('about_course', args=[unicode(course_key)]))
return self.client.get(reverse('about_course', args=[six.text_type(course_key)]))
@patch('util.date_utils.pgettext', fake_pgettext(translations={
("abbreviated month name", "Sep"): "SEPTEMBER",
@@ -1216,7 +1225,7 @@ class ProgressPageBaseTests(ModuleStoreTestCase):
Gets the progress page for the currently logged-in user.
"""
resp = self.client.get(
reverse('progress', args=[unicode(self.course.id)])
reverse('progress', args=[six.text_type(self.course.id)])
)
self.assertEqual(resp.status_code, expected_status_code)
return resp
@@ -1226,7 +1235,7 @@ class ProgressPageBaseTests(ModuleStoreTestCase):
Gets the progress page for the user in the course.
"""
resp = self.client.get(
reverse('student_progress', args=[unicode(self.course.id), self.user.id])
reverse('student_progress', args=[six.text_type(self.course.id), self.user.id])
)
self.assertEqual(resp.status_code, expected_status_code)
return resp
@@ -1271,7 +1280,7 @@ class ProgressPageTests(ProgressPageBaseTests):
for invalid_id in invalid_student_ids:
resp = self.client.get(
reverse('student_progress', args=[unicode(self.course.id), invalid_id])
reverse('student_progress', args=[six.text_type(self.course.id), invalid_id])
)
self.assertEquals(resp.status_code, 404)
@@ -2171,7 +2180,7 @@ class GenerateUserCertTests(ModuleStoreTestCase):
)
self.enrollment = CourseEnrollment.enroll(self.student, self.course.id, mode='honor')
self.assertTrue(self.client.login(username=self.student, password=TEST_PASSWORD))
self.url = reverse('generate_user_cert', kwargs={'course_id': unicode(self.course.id)})
self.url = reverse('generate_user_cert', kwargs={'course_id': six.text_type(self.course.id)})
def test_user_with_out_passing_grades(self):
# If user has no grading then json will return failed message and badrequest code
@@ -2202,7 +2211,7 @@ class GenerateUserCertTests(ModuleStoreTestCase):
'edx.bi.user.certificate.generate',
{
'category': 'certificates',
'label': unicode(self.course.id)
'label': six.text_type(self.course.id)
},
)
mock_tracker.reset_mock()
@@ -2299,11 +2308,11 @@ class ViewCheckerBlock(XBlock):
matches the block's usage_id.
"""
msg = u"{} != {}".format(self.state, self.scope_ids.usage_id)
assert self.state == unicode(self.scope_ids.usage_id), msg
assert self.state == six.text_type(self.scope_ids.usage_id), msg
fragments = self.runtime.render_children(self)
result = Fragment(
content=u"<p>ViewCheckerPassed: {}</p>\n{}".format(
unicode(self.scope_ids.usage_id),
six.text_type(self.scope_ids.usage_id),
"\n".join(fragment.content for fragment in fragments),
)
)
@@ -2336,7 +2345,7 @@ class TestIndexView(ModuleStoreTestCase):
student=user,
course_id=course.id,
module_state_key=item.scope_ids.usage_id,
state=json.dumps({'state': unicode(item.scope_ids.usage_id)})
state=json.dumps({'state': six.text_type(item.scope_ids.usage_id)})
)
CourseOverview.load_from_module_store(course.id)
@@ -2347,7 +2356,7 @@ class TestIndexView(ModuleStoreTestCase):
reverse(
'courseware_section',
kwargs={
'course_id': unicode(course.id),
'course_id': six.text_type(course.id),
'chapter': chapter.url_name,
'section': section.url_name,
}
@@ -2376,7 +2385,7 @@ class TestIndexView(ModuleStoreTestCase):
reverse(
'courseware_section',
kwargs={
'course_id': unicode(course.id),
'course_id': six.text_type(course.id),
'chapter': chapter.url_name,
'section': section.url_name,
}
@@ -2600,7 +2609,7 @@ class TestIndexViewCompleteOnView(ModuleStoreTestCase, CompletionWaffleTestMixin
self.section_1_url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.chapter.url_name,
'section': self.section_1.url_name,
}
@@ -2609,7 +2618,7 @@ class TestIndexViewCompleteOnView(ModuleStoreTestCase, CompletionWaffleTestMixin
self.section_2_url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.chapter.url_name,
'section': self.section_2.url_name,
}
@@ -2650,8 +2659,8 @@ class TestIndexViewCompleteOnView(ModuleStoreTestCase, CompletionWaffleTestMixin
request.user = self.user
response = handle_xblock_callback(
request,
unicode(self.course.id),
quote_slashes(unicode(self.html_1_1.scope_ids.usage_id)),
six.text_type(self.course.id),
quote_slashes(six.text_type(self.html_1_1.scope_ids.usage_id)),
'publish_completion',
)
self.assertEqual(json.loads(response.content), {'result': "ok"})
@@ -2668,8 +2677,8 @@ class TestIndexViewCompleteOnView(ModuleStoreTestCase, CompletionWaffleTestMixin
request.user = self.user
response = handle_xblock_callback(
request,
unicode(self.course.id),
quote_slashes(unicode(self.html_1_2.scope_ids.usage_id)),
six.text_type(self.course.id),
quote_slashes(six.text_type(self.html_1_2.scope_ids.usage_id)),
'publish_completion',
)
self.assertEqual(json.loads(response.content), {'result': "ok"})
@@ -2718,7 +2727,7 @@ class TestIndexViewWithVerticalPositions(ModuleStoreTestCase):
reverse(
'courseware_position',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.chapter.url_name,
'section': self.section.url_name,
'position': input_position,
@@ -2788,7 +2797,7 @@ class TestIndexViewWithGating(ModuleStoreTestCase, MilestonesTestCaseMixin):
reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.chapter.url_name,
'section': self.gated_seq.url_name,
}
@@ -2830,7 +2839,7 @@ class TestIndexViewWithCourseDurationLimits(ModuleStoreTestCase):
reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.chapter.url_name,
'section': self.sequential.url_name,
}
@@ -2856,7 +2865,7 @@ class TestIndexViewWithCourseDurationLimits(ModuleStoreTestCase):
reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'course_id': six.text_type(self.course.id),
'chapter': self.chapter.url_name,
'section': self.sequential.url_name,
}
@@ -2888,7 +2897,7 @@ class TestRenderXBlock(RenderXBlockTestMixin, ModuleStoreTestCase, CompletionWaf
"""
Overridable method to get the response from the endpoint that is being tested.
"""
url = reverse('render_xblock', kwargs={'usage_key_string': unicode(usage_key)})
url = reverse('render_xblock', kwargs={'usage_key_string': six.text_type(usage_key)})
if url_encoded_params:
url += '?' + url_encoded_params
return self.client.get(url)
@@ -2927,8 +2936,8 @@ class TestRenderXBlock(RenderXBlockTestMixin, ModuleStoreTestCase, CompletionWaf
request.user = self.user
response = handle_xblock_callback(
request,
unicode(self.course.id),
quote_slashes(unicode(self.html_block.location)),
six.text_type(self.course.id),
quote_slashes(six.text_type(self.html_block.location)),
'publish_completion',
)
self.assertEqual(response.status_code, 200)
@@ -3027,9 +3036,9 @@ class TestIndexViewCrawlerStudentStateWrites(SharedModuleStoreTestCase):
url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(self.course.id),
'chapter': unicode(self.chapter.location.block_id),
'section': unicode(self.section.location.block_id),
'course_id': six.text_type(self.course.id),
'chapter': six.text_type(self.chapter.location.block_id),
'section': six.text_type(self.section.location.block_id),
}
)
response = self.client.get(url, HTTP_USER_AGENT=user_agent)
@@ -3058,7 +3067,7 @@ class EnterpriseConsentTestCase(EnterpriseTestConsentRequired, ModuleStoreTestCa
# ENT-924: Temporary solution to replace sensitive SSO usernames.
mock_enterprise_customer_for_request.return_value = None
course_id = unicode(self.course.id)
course_id = six.text_type(self.course.id)
for url in (
reverse("courseware", kwargs=dict(course_id=course_id)),
reverse("progress", kwargs=dict(course_id=course_id)),

View File

@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
"""Word cloud integration tests using mongo modulestore."""
from __future__ import absolute_import
import json
from operator import itemgetter
@@ -224,7 +226,7 @@ class TestWordCloud(BaseTestXmodule):
for user in self.users:
self.assertListEqual(
users_state[user.username]['student_words'].keys(),
list(users_state[user.username]['student_words'].keys()),
correct_words)
def test_handle_ajax_incorrect_dispatch(self):

View File

@@ -1,6 +1,8 @@
"""
Test for LMS courseware app.
"""
from __future__ import absolute_import
from textwrap import dedent
from unittest import TestCase