diff --git a/common/djangoapps/course_action_state/managers.py b/common/djangoapps/course_action_state/managers.py index 6603e51678..d6b9729f5b 100644 --- a/common/djangoapps/course_action_state/managers.py +++ b/common/djangoapps/course_action_state/managers.py @@ -2,6 +2,7 @@ Model Managers for Course Actions """ import traceback + from django.db import models, transaction diff --git a/common/djangoapps/course_action_state/migrations/0001_initial.py b/common/djangoapps/course_action_state/migrations/0001_initial.py index e725bb5bce..66f577ccbe 100644 --- a/common/djangoapps/course_action_state/migrations/0001_initial.py +++ b/common/djangoapps/course_action_state/migrations/0001_initial.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models + from openedx.core.djangoapps.xmodule_django.models import CourseKeyField diff --git a/common/djangoapps/course_action_state/models.py b/common/djangoapps/course_action_state/models.py index be1c47ff5a..7114365a03 100644 --- a/common/djangoapps/course_action_state/models.py +++ b/common/djangoapps/course_action_state/models.py @@ -11,8 +11,9 @@ file and check it in at the same time as your model changes. To do that, """ from django.contrib.auth.models import User from django.db import models -from openedx.core.djangoapps.xmodule_django.models import CourseKeyField + from course_action_state.managers import CourseActionStateManager, CourseRerunUIStateManager +from openedx.core.djangoapps.xmodule_django.models import CourseKeyField class CourseActionState(models.Model): diff --git a/common/djangoapps/course_action_state/tests/test_managers.py b/common/djangoapps/course_action_state/tests/test_managers.py index 97ba24a161..523c3fbede 100644 --- a/common/djangoapps/course_action_state/tests/test_managers.py +++ b/common/djangoapps/course_action_state/tests/test_managers.py @@ -2,13 +2,14 @@ """ Tests for basic common operations related to Course Action State managers """ -from ddt import ddt, data -from django.test import TestCase from collections import namedtuple -from opaque_keys.edx.locations import CourseLocator -from course_action_state.models import CourseRerunState -from course_action_state.managers import CourseActionStateItemNotFoundError +from ddt import data, ddt +from django.test import TestCase +from opaque_keys.edx.locations import CourseLocator + +from course_action_state.managers import CourseActionStateItemNotFoundError +from course_action_state.models import CourseRerunState # Sequence of Action models to be tested with ddt. COURSE_ACTION_STATES = (CourseRerunState, ) diff --git a/common/djangoapps/course_action_state/tests/test_rerun_manager.py b/common/djangoapps/course_action_state/tests/test_rerun_manager.py index e563c682ef..3f5ab762f8 100644 --- a/common/djangoapps/course_action_state/tests/test_rerun_manager.py +++ b/common/djangoapps/course_action_state/tests/test_rerun_manager.py @@ -4,8 +4,9 @@ Tests specific to the CourseRerunState Model and Manager. from django.test import TestCase from opaque_keys.edx.locations import CourseLocator -from course_action_state.models import CourseRerunState + from course_action_state.managers import CourseRerunUIStateManager +from course_action_state.models import CourseRerunState from student.tests.factories import UserFactory diff --git a/common/djangoapps/course_modes/helpers.py b/common/djangoapps/course_modes/helpers.py index 4a3ceae231..a7a04e85e9 100644 --- a/common/djangoapps/course_modes/helpers.py +++ b/common/djangoapps/course_modes/helpers.py @@ -2,11 +2,7 @@ from django.utils.translation import ugettext_lazy as _ from course_modes.models import CourseMode -from student.helpers import ( - VERIFY_STATUS_NEED_TO_VERIFY, - VERIFY_STATUS_SUBMITTED, - VERIFY_STATUS_APPROVED -) +from student.helpers import VERIFY_STATUS_APPROVED, VERIFY_STATUS_NEED_TO_VERIFY, VERIFY_STATUS_SUBMITTED DISPLAY_VERIFIED = "verified" DISPLAY_HONOR = "honor" diff --git a/common/djangoapps/course_modes/migrations/0001_initial.py b/common/djangoapps/course_modes/migrations/0001_initial.py index be40d77c0b..e65065763a 100644 --- a/common/djangoapps/course_modes/migrations/0001_initial.py +++ b/common/djangoapps/course_modes/migrations/0001_initial.py @@ -2,6 +2,7 @@ from __future__ import unicode_literals from django.db import migrations, models + from openedx.core.djangoapps.xmodule_django.models import CourseKeyField diff --git a/common/djangoapps/course_modes/migrations/0004_auto_20151113_1457.py b/common/djangoapps/course_modes/migrations/0004_auto_20151113_1457.py index 3504d15cbc..ec11036d4d 100644 --- a/common/djangoapps/course_modes/migrations/0004_auto_20151113_1457.py +++ b/common/djangoapps/course_modes/migrations/0004_auto_20151113_1457.py @@ -1,10 +1,11 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals + from datetime import timedelta -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/course_modes/models.py b/common/djangoapps/course_modes/models.py index ad29d2d4a8..37df4c707b 100644 --- a/common/djangoapps/course_modes/models.py +++ b/common/djangoapps/course_modes/models.py @@ -1,19 +1,19 @@ """ Add and create new modes for running courses on this particular LMS """ +from collections import defaultdict, namedtuple from datetime import datetime, timedelta -import pytz -from collections import namedtuple, defaultdict +import pytz from config_models.models import ConfigurationModel from django.core.exceptions import ValidationError from django.db import models from django.db.models import Q from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ -from openedx.core.djangoapps.xmodule_django.models import CourseKeyField -from request_cache.middleware import ns_request_cached, RequestCache +from openedx.core.djangoapps.xmodule_django.models import CourseKeyField +from request_cache.middleware import RequestCache, ns_request_cached Mode = namedtuple('Mode', [ diff --git a/common/djangoapps/course_modes/signals.py b/common/djangoapps/course_modes/signals.py index 066004ab09..ed8c550211 100644 --- a/common/djangoapps/course_modes/signals.py +++ b/common/djangoapps/course_modes/signals.py @@ -3,6 +3,7 @@ Signal handler for setting default course mode expiration dates """ from django.core.exceptions import ObjectDoesNotExist from django.dispatch.dispatcher import receiver + from xmodule.modulestore.django import SignalHandler, modulestore from .models import CourseMode, CourseModeExpirationConfig diff --git a/common/djangoapps/course_modes/tests/factories.py b/common/djangoapps/course_modes/tests/factories.py index 7470b0530f..3f3d876997 100644 --- a/common/djangoapps/course_modes/tests/factories.py +++ b/common/djangoapps/course_modes/tests/factories.py @@ -3,11 +3,12 @@ Factories for course mode models. """ import random -from course_modes.models import CourseMode -from factory.django import DjangoModelFactory from factory import lazy_attribute +from factory.django import DjangoModelFactory from opaque_keys.edx.locations import SlashSeparatedCourseKey +from course_modes.models import CourseMode + # Factories are self documenting # pylint: disable=missing-docstring diff --git a/common/djangoapps/course_modes/tests/test_admin.py b/common/djangoapps/course_modes/tests/test_admin.py index 23844811bb..f81395b4f0 100644 --- a/common/djangoapps/course_modes/tests/test_admin.py +++ b/common/djangoapps/course_modes/tests/test_admin.py @@ -5,24 +5,22 @@ import unittest from datetime import datetime, timedelta import ddt -from pytz import timezone, UTC - from django.conf import settings from django.core.urlresolvers import reverse +from pytz import UTC, timezone -from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase -from util.date_utils import get_time_display -from xmodule.modulestore.tests.factories import CourseFactory -from student.tests.factories import UserFactory -from course_modes.models import CourseMode from course_modes.admin import CourseModeForm +from course_modes.models import CourseMode from course_modes.tests.factories import CourseModeFactory - # Technically, we shouldn't be importing verify_student, since it's # defined in the LMS and course_modes is in common. However, the benefits # of putting all this configuration in one place outweigh the downsides. # Once the course admin tool is deployed, we can remove this dependency. from lms.djangoapps.verify_student.models import VerificationDeadline +from student.tests.factories import UserFactory +from util.date_utils import get_time_display +from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory # We can only test this in the LMS because the course modes admin relies diff --git a/common/djangoapps/course_modes/tests/test_models.py b/common/djangoapps/course_modes/tests/test_models.py index 1dd761cd3e..fc5bb8987f 100644 --- a/common/djangoapps/course_modes/tests/test_models.py +++ b/common/djangoapps/course_modes/tests/test_models.py @@ -5,15 +5,15 @@ when you run "manage.py test". Replace this with more appropriate tests for your application. """ -from datetime import datetime, timedelta import itertools +from datetime import datetime, timedelta import ddt +import pytz from django.core.exceptions import ValidationError from django.test import TestCase from opaque_keys.edx.locations import SlashSeparatedCourseKey from opaque_keys.edx.locator import CourseLocator -import pytz from course_modes.helpers import enrollment_mode_display from course_modes.models import CourseMode, Mode, invalidate_course_mode_cache diff --git a/common/djangoapps/course_modes/tests/test_signals.py b/common/djangoapps/course_modes/tests/test_signals.py index 984f231f3c..853622808b 100644 --- a/common/djangoapps/course_modes/tests/test_signals.py +++ b/common/djangoapps/course_modes/tests/test_signals.py @@ -3,15 +3,15 @@ Unit tests for the course_mode signals """ from datetime import datetime, timedelta -from mock import patch import ddt +from mock import patch from pytz import UTC -from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase -from xmodule.modulestore.tests.factories import CourseFactory from course_modes.models import CourseMode from course_modes.signals import _listen_for_course_publish +from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory @ddt.ddt diff --git a/common/djangoapps/course_modes/tests/test_views.py b/common/djangoapps/course_modes/tests/test_views.py index b60edc050e..81daf6020f 100644 --- a/common/djangoapps/course_modes/tests/test_views.py +++ b/common/djangoapps/course_modes/tests/test_views.py @@ -2,34 +2,33 @@ Tests for course_modes views. """ -from datetime import datetime -import unittest import decimal +import unittest +from datetime import datetime + import ddt -import httpretty import freezegun +import httpretty +from django.conf import settings +from django.core.urlresolvers import reverse from mock import patch from nose.plugins.attrib import attr -from django.conf import settings -from django.core.urlresolvers import reverse - -from lms.djangoapps.commerce.tests import test_utils as ecomm_test_utils -from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase -from xmodule.modulestore.django import modulestore -from xmodule.modulestore.tests.factories import CourseFactory - from course_modes.models import CourseMode, Mode from course_modes.tests.factories import CourseModeFactory +from lms.djangoapps.commerce.tests import test_utils as ecomm_test_utils +from openedx.core.djangoapps.catalog.tests.mixins import CatalogIntegrationMixin from openedx.core.djangoapps.embargo.test_utils import restrict_course +from openedx.core.djangoapps.theming.tests.test_util import with_comprehensive_theme from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseServiceMockMixin from student.models import CourseEnrollment from student.tests.factories import CourseEnrollmentFactory, UserFactory -from util.testing import UrlResetMixin -from openedx.core.djangoapps.theming.tests.test_util import with_comprehensive_theme -from util.tests.mixins.discovery import CourseCatalogServiceMockMixin from util import organizations_helpers as organizations_api -from openedx.core.djangoapps.catalog.tests.mixins import CatalogIntegrationMixin +from util.testing import UrlResetMixin +from util.tests.mixins.discovery import CourseCatalogServiceMockMixin +from xmodule.modulestore.django import modulestore +from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory @attr(shard=3) diff --git a/common/djangoapps/course_modes/urls.py b/common/djangoapps/course_modes/urls.py index 4d21362575..3613ddf83e 100644 --- a/common/djangoapps/course_modes/urls.py +++ b/common/djangoapps/course_modes/urls.py @@ -1,5 +1,5 @@ -from django.conf.urls import patterns, url from django.conf import settings +from django.conf.urls import patterns, url from course_modes import views diff --git a/common/djangoapps/course_modes/views.py b/common/djangoapps/course_modes/views.py index 69bf5a08e8..e7058f7311 100644 --- a/common/djangoapps/course_modes/views.py +++ b/common/djangoapps/course_modes/views.py @@ -12,23 +12,24 @@ from django.db import transaction from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import redirect from django.utils.decorators import method_decorator -from django.utils.translation import get_language, to_locale, ugettext as _ +from django.utils.translation import ugettext as _ +from django.utils.translation import get_language, to_locale from django.views.generic.base import View from ipware.ip import get_ip from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locations import SlashSeparatedCourseKey -from xmodule.modulestore.django import modulestore -from lms.djangoapps.commerce.utils import EcommerceService from course_modes.models import CourseMode from courseware.access import has_access from edxmako.shortcuts import render_to_response +from lms.djangoapps.commerce.utils import EcommerceService from openedx.core.djangoapps.embargo import api as embargo_api from openedx.features.enterprise_support import api as enterprise_api from student.models import CourseEnrollment -from util.db import outer_atomic -from util import organizations_helpers as organization_api from third_party_auth.decorators import tpa_hint_ends_existing_session +from util import organizations_helpers as organization_api +from util.db import outer_atomic +from xmodule.modulestore.django import modulestore class ChooseModeView(View): diff --git a/common/djangoapps/database_fixups/migrations/0001_initial.py b/common/djangoapps/database_fixups/migrations/0001_initial.py index 110104fdea..1a1c2d3db4 100644 --- a/common/djangoapps/database_fixups/migrations/0001_initial.py +++ b/common/djangoapps/database_fixups/migrations/0001_initial.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals from django.db import migrations, models + # We used to have a uniqueness constraint on auth_user.email: # https://github.com/edx/edx-platform/commit/c52727b0e0fb241d8211900975d3b69fe5a1bd57 # diff --git a/common/djangoapps/django_comment_common/admin.py b/common/djangoapps/django_comment_common/admin.py index d2187e77e2..57e30eb147 100644 --- a/common/djangoapps/django_comment_common/admin.py +++ b/common/djangoapps/django_comment_common/admin.py @@ -5,5 +5,4 @@ from django.contrib import admin from .models import ForumsConfig - admin.site.register(ForumsConfig) diff --git a/common/djangoapps/django_comment_common/migrations/0001_initial.py b/common/djangoapps/django_comment_common/migrations/0001_initial.py index be2b46e29b..ddf4a0728e 100644 --- a/common/djangoapps/django_comment_common/migrations/0001_initial.py +++ b/common/djangoapps/django_comment_common/migrations/0001_initial.py @@ -1,8 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models from django.conf import settings +from django.db import migrations, models + from openedx.core.djangoapps.xmodule_django.models import CourseKeyField diff --git a/common/djangoapps/django_comment_common/migrations/0002_forumsconfig.py b/common/djangoapps/django_comment_common/migrations/0002_forumsconfig.py index 8694e91018..c4c24e8586 100644 --- a/common/djangoapps/django_comment_common/migrations/0002_forumsconfig.py +++ b/common/djangoapps/django_comment_common/migrations/0002_forumsconfig.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/django_comment_common/migrations/0003_enable_forums.py b/common/djangoapps/django_comment_common/migrations/0003_enable_forums.py index 1280a2cfd1..50f3cad4c6 100644 --- a/common/djangoapps/django_comment_common/migrations/0003_enable_forums.py +++ b/common/djangoapps/django_comment_common/migrations/0003_enable_forums.py @@ -1,7 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals + from django.db import migrations, models + def add_default_enable(apps, schema_editor): ForumsConfig = apps.get_model("django_comment_common", "ForumsConfig") settings_count = ForumsConfig.objects.count() diff --git a/common/djangoapps/django_comment_common/models.py b/common/djangoapps/django_comment_common/models.py index 333df46451..1a6370a0fb 100644 --- a/common/djangoapps/django_comment_common/models.py +++ b/common/djangoapps/django_comment_common/models.py @@ -1,19 +1,17 @@ import logging +from config_models.models import ConfigurationModel from django.conf import settings -from django.db import models from django.contrib.auth.models import User - -from django.dispatch import receiver +from django.db import models from django.db.models.signals import post_save +from django.dispatch import receiver from django.utils.translation import ugettext_noop -from config_models.models import ConfigurationModel +from openedx.core.djangoapps.xmodule_django.models import CourseKeyField, NoneToEmptyManager from student.models import CourseEnrollment - from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError -from openedx.core.djangoapps.xmodule_django.models import CourseKeyField, NoneToEmptyManager FORUM_ROLE_ADMINISTRATOR = ugettext_noop('Administrator') FORUM_ROLE_MODERATOR = ugettext_noop('Moderator') diff --git a/common/djangoapps/django_comment_common/signals.py b/common/djangoapps/django_comment_common/signals.py index f58486a34b..36d75a87ab 100644 --- a/common/djangoapps/django_comment_common/signals.py +++ b/common/djangoapps/django_comment_common/signals.py @@ -3,7 +3,6 @@ from django.dispatch import Signal - thread_created = Signal(providing_args=['user', 'post']) thread_edited = Signal(providing_args=['user', 'post']) thread_voted = Signal(providing_args=['user', 'post']) diff --git a/common/djangoapps/django_comment_common/tests.py b/common/djangoapps/django_comment_common/tests.py index 8e1cf9382f..a76012bb47 100644 --- a/common/djangoapps/django_comment_common/tests.py +++ b/common/djangoapps/django_comment_common/tests.py @@ -1,6 +1,6 @@ from django.test import TestCase - from opaque_keys.edx.locations import SlashSeparatedCourseKey + from django_comment_common.models import Role from student.models import CourseEnrollment, User diff --git a/common/djangoapps/django_comment_common/utils.py b/common/djangoapps/django_comment_common/utils.py index a87aaed698..978c06b1e3 100644 --- a/common/djangoapps/django_comment_common/utils.py +++ b/common/djangoapps/django_comment_common/utils.py @@ -2,8 +2,13 @@ Common comment client utility functions. """ -from django_comment_common.models import Role, FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, \ - FORUM_ROLE_COMMUNITY_TA, FORUM_ROLE_STUDENT +from django_comment_common.models import ( + FORUM_ROLE_ADMINISTRATOR, + FORUM_ROLE_COMMUNITY_TA, + FORUM_ROLE_MODERATOR, + FORUM_ROLE_STUDENT, + Role +) class ThreadContext(object): diff --git a/common/djangoapps/edxmako/makoloader.py b/common/djangoapps/edxmako/makoloader.py index 8a21a1d0f1..8ec7466217 100644 --- a/common/djangoapps/edxmako/makoloader.py +++ b/common/djangoapps/edxmako/makoloader.py @@ -2,13 +2,12 @@ import logging from django.conf import settings from django.core.exceptions import ImproperlyConfigured -from django.template.base import TemplateDoesNotExist -from django.template.loaders.filesystem import Loader as FilesystemLoader -from django.template.loaders.app_directories import Loader as AppDirectoriesLoader from django.template import Engine +from django.template.base import TemplateDoesNotExist +from django.template.loaders.app_directories import Loader as AppDirectoriesLoader +from django.template.loaders.filesystem import Loader as FilesystemLoader from edxmako.template import Template - from openedx.core.lib.tempdir import mkdtemp_clean log = logging.getLogger(__name__) diff --git a/common/djangoapps/edxmako/paths.py b/common/djangoapps/edxmako/paths.py index ed41818f53..f7791da090 100644 --- a/common/djangoapps/edxmako/paths.py +++ b/common/djangoapps/edxmako/paths.py @@ -2,21 +2,19 @@ Set up lookup paths for mako templates. """ -import hashlib import contextlib +import hashlib import os -import pkg_resources +import pkg_resources from django.conf import settings -from mako.lookup import TemplateLookup from mako.exceptions import TopLevelLookupException +from mako.lookup import TemplateLookup + +from openedx.core.djangoapps.theming.helpers import get_template as themed_template +from openedx.core.djangoapps.theming.helpers import get_template_path_with_theme, strip_site_theme_templates_path from . import LOOKUP -from openedx.core.djangoapps.theming.helpers import ( - get_template as themed_template, - get_template_path_with_theme, - strip_site_theme_templates_path, -) class DynamicTemplateLookup(TemplateLookup): diff --git a/common/djangoapps/edxmako/request_context.py b/common/djangoapps/edxmako/request_context.py index b10b8753ae..41b0f466fa 100644 --- a/common/djangoapps/edxmako/request_context.py +++ b/common/djangoapps/edxmako/request_context.py @@ -19,14 +19,14 @@ Methods for creating RequestContext for using with Mako templates. """ +from crum import get_current_request from django.conf import settings from django.template import RequestContext from django.template.context import _builtin_context_processors from django.utils.module_loading import import_string -from util.request import safe_get_host -from crum import get_current_request import request_cache +from util.request import safe_get_host def get_template_context_processors(): diff --git a/common/djangoapps/edxmako/shortcuts.py b/common/djangoapps/edxmako/shortcuts.py index c3279058bb..d3187e08fe 100644 --- a/common/djangoapps/edxmako/shortcuts.py +++ b/common/djangoapps/edxmako/shortcuts.py @@ -15,15 +15,15 @@ import logging from urlparse import urljoin +from django.conf import settings +from django.core.urlresolvers import reverse from django.http import HttpResponse from django.template import Context from edxmako import lookup_template from edxmako.request_context import get_template_request_context -from django.conf import settings -from django.core.urlresolvers import reverse -from openedx.core.djangoapps.theming.helpers import get_template_path, is_request_in_themed_site from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers +from openedx.core.djangoapps.theming.helpers import get_template_path, is_request_in_themed_site log = logging.getLogger(__name__) diff --git a/common/djangoapps/edxmako/startup.py b/common/djangoapps/edxmako/startup.py index 7d291b4bc0..4fc94a1024 100644 --- a/common/djangoapps/edxmako/startup.py +++ b/common/djangoapps/edxmako/startup.py @@ -2,6 +2,7 @@ Initialize the mako template lookup """ from django.conf import settings + from . import add_lookup, clear_lookups diff --git a/common/djangoapps/edxmako/template.py b/common/djangoapps/edxmako/template.py index 47dde3fabf..2be367f966 100644 --- a/common/djangoapps/edxmako/template.py +++ b/common/djangoapps/edxmako/template.py @@ -12,12 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import edxmako - from django.conf import settings +from mako.template import Template as MakoTemplate + +import edxmako from edxmako.request_context import get_template_request_context from edxmako.shortcuts import marketing_link -from mako.template import Template as MakoTemplate + # TODO: We should make this a Django Template subclass that simply has the MakoTemplate inside of it? (Intead of inheriting from MakoTemplate) diff --git a/common/djangoapps/edxmako/templatetag_helpers.py b/common/djangoapps/edxmako/templatetag_helpers.py index cd871a0fc5..153944bb77 100644 --- a/common/djangoapps/edxmako/templatetag_helpers.py +++ b/common/djangoapps/edxmako/templatetag_helpers.py @@ -1,5 +1,5 @@ from django.template import loader -from django.template.base import Template, Context +from django.template.base import Context, Template from django.template.loader import get_template, select_template diff --git a/common/djangoapps/edxmako/tests.py b/common/djangoapps/edxmako/tests.py index 4e945b5af3..44e0903954 100644 --- a/common/djangoapps/edxmako/tests.py +++ b/common/djangoapps/edxmako/tests.py @@ -1,22 +1,18 @@ -from mock import patch, Mock import unittest -import ddt -from request_cache.middleware import RequestCache +import ddt from django.conf import settings +from django.core.urlresolvers import reverse from django.http import HttpResponse from django.test import TestCase -from django.test.utils import override_settings from django.test.client import RequestFactory -from django.core.urlresolvers import reverse +from django.test.utils import override_settings +from mock import Mock, patch + +from edxmako import LOOKUP, add_lookup from edxmako.request_context import get_template_request_context -from edxmako import add_lookup, LOOKUP -from edxmako.shortcuts import ( - marketing_link, - is_marketing_link_set, - is_any_marketing_link_set, - render_to_string, -) +from edxmako.shortcuts import is_any_marketing_link_set, is_marketing_link_set, marketing_link, render_to_string +from request_cache.middleware import RequestCache from student.tests.factories import UserFactory from util.testing import UrlResetMixin diff --git a/common/djangoapps/enrollment/api.py b/common/djangoapps/enrollment/api.py index e35539479c..2833bcc3b0 100644 --- a/common/djangoapps/enrollment/api.py +++ b/common/djangoapps/enrollment/api.py @@ -5,6 +5,7 @@ course level, such as available course modes. """ import importlib import logging + from django.conf import settings from django.core.cache import cache from opaque_keys.edx.keys import CourseKey diff --git a/common/djangoapps/enrollment/data.py b/common/djangoapps/enrollment/data.py index ab82543be0..004f339218 100644 --- a/common/djangoapps/enrollment/data.py +++ b/common/djangoapps/enrollment/data.py @@ -8,18 +8,24 @@ from django.contrib.auth.models import User from opaque_keys.edx.keys import CourseKey from enrollment.errors import ( - CourseEnrollmentClosedError, CourseEnrollmentFullError, - CourseEnrollmentExistsError, UserNotFoundError, InvalidEnrollmentAttribute + CourseEnrollmentClosedError, + CourseEnrollmentExistsError, + CourseEnrollmentFullError, + InvalidEnrollmentAttribute, + UserNotFoundError ) from enrollment.serializers import CourseEnrollmentSerializer, CourseSerializer from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.lib.exceptions import CourseNotFoundError from student.models import ( - CourseEnrollment, NonExistentCourseError, EnrollmentClosedError, - CourseFullError, AlreadyEnrolledError, CourseEnrollmentAttribute + AlreadyEnrolledError, + CourseEnrollment, + CourseEnrollmentAttribute, + CourseFullError, + EnrollmentClosedError, + NonExistentCourseError ) - log = logging.getLogger(__name__) diff --git a/common/djangoapps/enrollment/serializers.py b/common/djangoapps/enrollment/serializers.py index 8f4d5357c9..e0e7ad3e87 100644 --- a/common/djangoapps/enrollment/serializers.py +++ b/common/djangoapps/enrollment/serializers.py @@ -8,7 +8,6 @@ from rest_framework import serializers from course_modes.models import CourseMode from student.models import CourseEnrollment - log = logging.getLogger(__name__) diff --git a/common/djangoapps/enrollment/tests/fake_data_api.py b/common/djangoapps/enrollment/tests/fake_data_api.py index f9ec55a33d..2c306e9f4e 100644 --- a/common/djangoapps/enrollment/tests/fake_data_api.py +++ b/common/djangoapps/enrollment/tests/fake_data_api.py @@ -4,7 +4,6 @@ A Fake Data API for testing purposes. import copy import datetime - _DEFAULT_FAKE_MODE = { "slug": "honor", "name": "Honor Code Certificate", diff --git a/common/djangoapps/enrollment/tests/test_api.py b/common/djangoapps/enrollment/tests/test_api.py index f9cfe5a0a9..edc70a35ba 100644 --- a/common/djangoapps/enrollment/tests/test_api.py +++ b/common/djangoapps/enrollment/tests/test_api.py @@ -1,17 +1,17 @@ """ Tests for student enrollment. """ -from mock import patch, Mock +import unittest import ddt -from nose.tools import raises -import unittest -from django.test.utils import override_settings from django.conf import settings +from django.test.utils import override_settings +from mock import Mock, patch +from nose.tools import raises from course_modes.models import CourseMode from enrollment import api -from enrollment.errors import EnrollmentApiLoadError, EnrollmentNotFoundError, CourseModeNotFoundError +from enrollment.errors import CourseModeNotFoundError, EnrollmentApiLoadError, EnrollmentNotFoundError from enrollment.tests import fake_data_api from openedx.core.djangolib.testing.utils import CacheIsolationTestCase diff --git a/common/djangoapps/enrollment/tests/test_data.py b/common/djangoapps/enrollment/tests/test_data.py index 36185cbb6d..3c9be7c40b 100644 --- a/common/djangoapps/enrollment/tests/test_data.py +++ b/common/djangoapps/enrollment/tests/test_data.py @@ -6,20 +6,22 @@ import datetime import unittest import ddt +from django.conf import settings from mock import patch from nose.tools import raises from pytz import UTC -from django.conf import settings from course_modes.models import CourseMode from enrollment import data from enrollment.errors import ( - UserNotFoundError, CourseEnrollmentClosedError, - CourseEnrollmentFullError, CourseEnrollmentExistsError, + CourseEnrollmentClosedError, + CourseEnrollmentExistsError, + CourseEnrollmentFullError, + UserNotFoundError ) from openedx.core.lib.exceptions import CourseNotFoundError -from student.tests.factories import UserFactory, CourseModeFactory -from student.models import CourseEnrollment, EnrollmentClosedError, CourseFullError, AlreadyEnrolledError +from student.models import AlreadyEnrolledError, CourseEnrollment, CourseFullError, EnrollmentClosedError +from student.tests.factories import CourseModeFactory, UserFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory diff --git a/common/djangoapps/enrollment/tests/test_views.py b/common/djangoapps/enrollment/tests/test_views.py index 6a623810ae..90817c36e8 100644 --- a/common/djangoapps/enrollment/tests/test_views.py +++ b/common/djangoapps/enrollment/tests/test_views.py @@ -1,42 +1,42 @@ """ Tests for user enrollment. """ -import json -import itertools -import unittest import datetime +import itertools +import json +import unittest import ddt +import httpretty +import pytz +from django.conf import settings from django.core.cache import cache -from mock import patch -from nose.plugins.attrib import attr -from django.test import Client from django.core.handlers.wsgi import WSGIRequest from django.core.urlresolvers import reverse -from rest_framework.test import APITestCase -from rest_framework import status -from django.conf import settings -from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase -from xmodule.modulestore.tests.factories import CourseFactory, check_mongo_calls_range +from django.test import Client from django.test.utils import override_settings -import pytz -import httpretty +from mock import patch +from nose.plugins.attrib import attr +from rest_framework import status +from rest_framework.test import APITestCase from course_modes.models import CourseMode -from enrollment.views import EnrollmentUserThrottle -from util.models import RateLimitConfiguration -from util.testing import UrlResetMixin -from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseServiceMockMixin from enrollment import api from enrollment.errors import CourseEnrollmentError +from enrollment.views import EnrollmentUserThrottle from openedx.core.djangoapps.content.course_overviews.models import CourseOverview +from openedx.core.djangoapps.embargo.models import Country, CountryAccessRule, RestrictedCourse +from openedx.core.djangoapps.embargo.test_utils import restrict_course from openedx.core.djangoapps.user_api.models import UserOrgTag from openedx.core.lib.django_test_client_utils import get_absolute_url +from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseServiceMockMixin from student.models import CourseEnrollment from student.roles import CourseStaffRole from student.tests.factories import AdminFactory, CourseModeFactory, UserFactory -from openedx.core.djangoapps.embargo.models import CountryAccessRule, Country, RestrictedCourse -from openedx.core.djangoapps.embargo.test_utils import restrict_course +from util.models import RateLimitConfiguration +from util.testing import UrlResetMixin +from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory, check_mongo_calls_range class EnrollmentTestMixin(object): diff --git a/common/djangoapps/enrollment/urls.py b/common/djangoapps/enrollment/urls.py index 8b7b41652a..1c5456406f 100644 --- a/common/djangoapps/enrollment/urls.py +++ b/common/djangoapps/enrollment/urls.py @@ -5,12 +5,7 @@ URLs for the Enrollment API from django.conf import settings from django.conf.urls import patterns, url -from .views import ( - EnrollmentView, - EnrollmentListView, - EnrollmentCourseDetailView -) - +from .views import EnrollmentCourseDetailView, EnrollmentListView, EnrollmentView urlpatterns = patterns( 'enrollment.views', diff --git a/common/djangoapps/enrollment/views.py b/common/djangoapps/enrollment/views.py index 9996cbd4ba..65cdf8e8ad 100644 --- a/common/djangoapps/enrollment/views.py +++ b/common/djangoapps/enrollment/views.py @@ -16,23 +16,20 @@ from rest_framework.throttling import UserRateThrottle from rest_framework.views import APIView from course_modes.models import CourseMode +from enrollment import api +from enrollment.errors import CourseEnrollmentError, CourseEnrollmentExistsError, CourseModeNotFoundError from openedx.core.djangoapps.cors_csrf.authentication import SessionAuthenticationCrossDomainCsrf from openedx.core.djangoapps.cors_csrf.decorators import ensure_csrf_cookie_cross_domain from openedx.core.djangoapps.embargo import api as embargo_api from openedx.core.djangoapps.user_api.preferences.api import update_email_opt_in -from openedx.features.enterprise_support.api import enterprise_enabled, EnterpriseApiClient, EnterpriseApiException from openedx.core.lib.api.authentication import ( - SessionAuthenticationAllowInactiveUser, OAuth2AuthenticationAllowInactiveUser, + OAuth2AuthenticationAllowInactiveUser, + SessionAuthenticationAllowInactiveUser ) from openedx.core.lib.api.permissions import ApiKeyHeaderPermission, ApiKeyHeaderPermissionIsAuthenticated from openedx.core.lib.exceptions import CourseNotFoundError from openedx.core.lib.log_utils import audit_log -from enrollment import api -from enrollment.errors import ( - CourseEnrollmentError, - CourseModeNotFoundError, - CourseEnrollmentExistsError -) +from openedx.features.enterprise_support.api import EnterpriseApiClient, EnterpriseApiException, enterprise_enabled from student.auth import user_has_role from student.models import User from student.roles import CourseStaffRole, GlobalStaff diff --git a/common/djangoapps/microsite_configuration/admin.py b/common/djangoapps/microsite_configuration/admin.py index d9d1759128..516fee8f09 100644 --- a/common/djangoapps/microsite_configuration/admin.py +++ b/common/djangoapps/microsite_configuration/admin.py @@ -1,17 +1,13 @@ """ Django admin page for microsite models """ -from django.contrib import admin from django import forms +from django.contrib import admin -from .models import ( - Microsite, - MicrositeHistory, - MicrositeOrganizationMapping, - MicrositeTemplate -) from util.organizations_helpers import get_organizations +from .models import Microsite, MicrositeHistory, MicrositeOrganizationMapping, MicrositeTemplate + class MicrositeAdmin(admin.ModelAdmin): """ Admin interface for the Microsite object. """ diff --git a/common/djangoapps/microsite_configuration/backends/database.py b/common/djangoapps/microsite_configuration/backends/database.py index 0d9a7ec5e1..ccd5126e20 100644 --- a/common/djangoapps/microsite_configuration/backends/database.py +++ b/common/djangoapps/microsite_configuration/backends/database.py @@ -1,25 +1,17 @@ """ Microsite backend that reads the configuration from the database """ -from mako.template import Template -from util.cache import cache - from django.conf import settings -from django.dispatch import receiver from django.db.models.signals import post_save +from django.dispatch import receiver +from mako.template import Template +from microsite_configuration.backends.base import BaseMicrositeBackend, BaseMicrositeTemplateBackend +from microsite_configuration.microsite import get_value as microsite_get_value +from microsite_configuration.models import Microsite, MicrositeOrganizationMapping, MicrositeTemplate +from util.cache import cache from util.memcache import fasthash from util.url import strip_port_from_host -from microsite_configuration.backends.base import ( - BaseMicrositeBackend, - BaseMicrositeTemplateBackend, -) -from microsite_configuration.models import ( - Microsite, - MicrositeOrganizationMapping, - MicrositeTemplate -) -from microsite_configuration.microsite import get_value as microsite_get_value class DatabaseMicrositeBackend(BaseMicrositeBackend): diff --git a/common/djangoapps/microsite_configuration/backends/filebased.py b/common/djangoapps/microsite_configuration/backends/filebased.py index 3c5b012643..e14eba9f14 100644 --- a/common/djangoapps/microsite_configuration/backends/filebased.py +++ b/common/djangoapps/microsite_configuration/backends/filebased.py @@ -3,10 +3,7 @@ Microsite backend that reads the configuration from a file """ -from microsite_configuration.backends.base import ( - BaseMicrositeBackend, - BaseMicrositeTemplateBackend, -) +from microsite_configuration.backends.base import BaseMicrositeBackend, BaseMicrositeTemplateBackend class FilebasedMicrositeBackend(BaseMicrositeBackend): diff --git a/common/djangoapps/microsite_configuration/microsite.py b/common/djangoapps/microsite_configuration/microsite.py index 35716d7899..959c7bd93e 100644 --- a/common/djangoapps/microsite_configuration/microsite.py +++ b/common/djangoapps/microsite_configuration/microsite.py @@ -7,11 +7,11 @@ A microsite enables the following features: 3) Ability to swap out some branding elements in the website """ import inspect - from importlib import import_module -from django.conf import settings -from microsite_configuration.backends.base import BaseMicrositeBackend, BaseMicrositeTemplateBackend +from django.conf import settings + +from microsite_configuration.backends.base import BaseMicrositeBackend, BaseMicrositeTemplateBackend __all__ = [ 'is_request_in_microsite', 'get_value', 'has_override_value', diff --git a/common/djangoapps/microsite_configuration/middleware.py b/common/djangoapps/microsite_configuration/middleware.py index fa56c8c3bb..7d7f578a1d 100644 --- a/common/djangoapps/microsite_configuration/middleware.py +++ b/common/djangoapps/microsite_configuration/middleware.py @@ -8,6 +8,7 @@ A microsite enables the following features: """ from django.conf import settings + from microsite_configuration import microsite diff --git a/common/djangoapps/microsite_configuration/migrations/0001_initial.py b/common/djangoapps/microsite_configuration/migrations/0001_initial.py index 94d1e4a968..3e005e355d 100644 --- a/common/djangoapps/microsite_configuration/migrations/0001_initial.py +++ b/common/djangoapps/microsite_configuration/migrations/0001_initial.py @@ -1,12 +1,12 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models -import jsonfield.fields import django.db.models.deletion -from django.conf import settings -import model_utils.fields import django.utils.timezone +import jsonfield.fields +import model_utils.fields +from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/microsite_configuration/models.py b/common/djangoapps/microsite_configuration/models.py index e186c82563..2ec3d074f1 100644 --- a/common/djangoapps/microsite_configuration/models.py +++ b/common/djangoapps/microsite_configuration/models.py @@ -7,12 +7,11 @@ that would have been used in the settings. """ import collections -from django.db import models -from django.dispatch import receiver -from django.db.models.signals import pre_save, pre_delete -from django.db.models.base import ObjectDoesNotExist from django.contrib.sites.models import Site - +from django.db import models +from django.db.models.base import ObjectDoesNotExist +from django.db.models.signals import pre_delete, pre_save +from django.dispatch import receiver from jsonfield.fields import JSONField from model_utils.models import TimeStampedModel from simple_history.models import HistoricalRecords diff --git a/common/djangoapps/microsite_configuration/tests/factories.py b/common/djangoapps/microsite_configuration/tests/factories.py index 27e84b9a10..64826891c3 100644 --- a/common/djangoapps/microsite_configuration/tests/factories.py +++ b/common/djangoapps/microsite_configuration/tests/factories.py @@ -2,15 +2,10 @@ Factories module to hold microsite factories """ import factory +from django.contrib.sites.models import Site from factory.django import DjangoModelFactory -from django.contrib.sites.models import Site - -from microsite_configuration.models import ( - Microsite, - MicrositeOrganizationMapping, - MicrositeTemplate, -) +from microsite_configuration.models import Microsite, MicrositeOrganizationMapping, MicrositeTemplate class SiteFactory(DjangoModelFactory): diff --git a/common/djangoapps/microsite_configuration/tests/test_logic.py b/common/djangoapps/microsite_configuration/tests/test_logic.py index d6e41fb85f..e8f905b758 100644 --- a/common/djangoapps/microsite_configuration/tests/test_logic.py +++ b/common/djangoapps/microsite_configuration/tests/test_logic.py @@ -5,15 +5,9 @@ some additional coverage import ddt from mock import patch -from microsite_configuration.microsite import ( - get_value_for_org, - get_backend, -) from microsite_configuration.backends.base import BaseMicrositeBackend -from microsite_configuration.tests.tests import ( - DatabaseMicrositeTestCase, - MICROSITE_BACKENDS, -) +from microsite_configuration.microsite import get_backend, get_value_for_org +from microsite_configuration.tests.tests import MICROSITE_BACKENDS, DatabaseMicrositeTestCase @ddt.ddt diff --git a/common/djangoapps/microsite_configuration/tests/test_microsites.py b/common/djangoapps/microsite_configuration/tests/test_microsites.py index 49e1c1b819..db0acdb30d 100644 --- a/common/djangoapps/microsite_configuration/tests/test_microsites.py +++ b/common/djangoapps/microsite_configuration/tests/test_microsites.py @@ -4,14 +4,15 @@ Tests configuration templatetags and helper functions. """ import logging -from mock import patch -from django.test import TestCase from django.conf import settings +from django.test import TestCase +from mock import patch + from microsite_configuration import microsite from microsite_configuration.backends.base import BaseMicrositeBackend from microsite_configuration.backends.database import DatabaseMicrositeBackend -from openedx.core.djangoapps.site_configuration.templatetags import configuration as configuration_tags from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers +from openedx.core.djangoapps.site_configuration.templatetags import configuration as configuration_tags log = logging.getLogger(__name__) diff --git a/common/djangoapps/microsite_configuration/tests/tests.py b/common/djangoapps/microsite_configuration/tests/tests.py index ef688ff1b8..c53c63116f 100644 --- a/common/djangoapps/microsite_configuration/tests/tests.py +++ b/common/djangoapps/microsite_configuration/tests/tests.py @@ -1,13 +1,10 @@ """ Holds base classes for microsite tests """ +from django.test import TestCase from mock import DEFAULT -from django.test import TestCase -from microsite_configuration.tests.factories import ( - MicrositeFactory, - MicrositeOrganizationMappingFactory, -) +from microsite_configuration.tests.factories import MicrositeFactory, MicrositeOrganizationMappingFactory MICROSITE_BACKENDS = ( 'microsite_configuration.backends.filebased.FilebasedMicrositeBackend', diff --git a/common/djangoapps/pipeline_mako/tests/test_render.py b/common/djangoapps/pipeline_mako/tests/test_render.py index 4ed13753cb..9a7d6254ac 100644 --- a/common/djangoapps/pipeline_mako/tests/test_render.py +++ b/common/djangoapps/pipeline_mako/tests/test_render.py @@ -1,13 +1,13 @@ """ Tests for rendering functions in the mako pipeline. """ -import ddt from unittest import skipUnless +import ddt from django.conf import settings from django.test import TestCase from paver.easy import call_task -from pipeline_mako import render_require_js_path_overrides, compressed_css, compressed_js +from pipeline_mako import compressed_css, compressed_js, render_require_js_path_overrides class RequireJSPathOverridesTest(TestCase): diff --git a/common/djangoapps/request_cache/middleware.py b/common/djangoapps/request_cache/middleware.py index f2f3a40fdd..525fb36f66 100644 --- a/common/djangoapps/request_cache/middleware.py +++ b/common/djangoapps/request_cache/middleware.py @@ -2,10 +2,10 @@ An implementation of a RequestCache. This cache is reset at the beginning and end of every request. """ -from django.utils.encoding import force_text +import threading import crum -import threading +from django.utils.encoding import force_text class _RequestCache(threading.local): diff --git a/common/djangoapps/static_replace/admin.py b/common/djangoapps/static_replace/admin.py index 8d9426cf7c..acb324d2dc 100644 --- a/common/djangoapps/static_replace/admin.py +++ b/common/djangoapps/static_replace/admin.py @@ -2,9 +2,9 @@ Django admin page for AssetBaseUrlConfig, which allows you to set the base URL that gets prepended to asset URLs in order to serve them from, say, a CDN. """ +from config_models.admin import ConfigurationModelAdmin from django.contrib import admin -from config_models.admin import ConfigurationModelAdmin from .models import AssetBaseUrlConfig, AssetExcludedExtensionsConfig diff --git a/common/djangoapps/static_replace/migrations/0001_initial.py b/common/djangoapps/static_replace/migrations/0001_initial.py index b408eb7be9..8c485265c1 100644 --- a/common/djangoapps/static_replace/migrations/0001_initial.py +++ b/common/djangoapps/static_replace/migrations/0001_initial.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/static_replace/migrations/0002_assetexcludedextensionsconfig.py b/common/djangoapps/static_replace/migrations/0002_assetexcludedextensionsconfig.py index 54a6ca4a48..594576ad3f 100644 --- a/common/djangoapps/static_replace/migrations/0002_assetexcludedextensionsconfig.py +++ b/common/djangoapps/static_replace/migrations/0002_assetexcludedextensionsconfig.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/static_replace/models.py b/common/djangoapps/static_replace/models.py index b3c09e3945..e598178a57 100644 --- a/common/djangoapps/static_replace/models.py +++ b/common/djangoapps/static_replace/models.py @@ -2,8 +2,8 @@ Models for static_replace """ -from django.db.models.fields import TextField from config_models.models import ConfigurationModel +from django.db.models.fields import TextField class AssetBaseUrlConfig(ConfigurationModel): diff --git a/common/djangoapps/static_replace/test/test_static_replace.py b/common/djangoapps/static_replace/test/test_static_replace.py index 05d0c053a4..0e8443c815 100644 --- a/common/djangoapps/static_replace/test/test_static_replace.py +++ b/common/djangoapps/static_replace/test/test_static_replace.py @@ -1,34 +1,35 @@ # -*- coding: utf-8 -*- """Tests for static_replace""" -import ddt import re - -from django.test import override_settings -from django.utils.http import urlquote, urlencode -from urlparse import urlparse, urlunparse, parse_qsl -from PIL import Image from cStringIO import StringIO -from nose.tools import assert_equals, assert_true, assert_false # pylint: disable=no-name-in-module -from static_replace import ( - replace_static_urls, - replace_course_urls, - _url_replace_regex, - process_static_urls, - make_static_urls_absolute -) -from mock import patch, Mock +from urlparse import parse_qsl, urlparse, urlunparse + +import ddt +from django.test import override_settings +from django.utils.http import urlencode, urlquote +from mock import Mock, patch +from nose.tools import assert_equals, assert_false, assert_true # pylint: disable=no-name-in-module from opaque_keys.edx.locations import SlashSeparatedCourseKey +from PIL import Image + +from static_replace import ( + _url_replace_regex, + make_static_urls_absolute, + process_static_urls, + replace_course_urls, + replace_static_urls +) +from xmodule.assetstore.assetmgr import AssetManager from xmodule.contentstore.content import StaticContent from xmodule.contentstore.django import contentstore +from xmodule.exceptions import NotFoundError from xmodule.modulestore import ModuleStoreEnum +from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.mongo import MongoModuleStore from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory, check_mongo_calls from xmodule.modulestore.xml import XMLModuleStore -from xmodule.modulestore.exceptions import ItemNotFoundError -from xmodule.exceptions import NotFoundError -from xmodule.assetstore.assetmgr import AssetManager DATA_DIRECTORY = 'data_dir' COURSE_KEY = SlashSeparatedCourseKey('org', 'course', 'run') diff --git a/common/djangoapps/status/migrations/0001_initial.py b/common/djangoapps/status/migrations/0001_initial.py index 80efc998db..c93d2921dc 100644 --- a/common/djangoapps/status/migrations/0001_initial.py +++ b/common/djangoapps/status/migrations/0001_initial.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models + from openedx.core.djangoapps.xmodule_django.models import CourseKeyField diff --git a/common/djangoapps/status/models.py b/common/djangoapps/status/models.py index c9bf4f6145..894891f1b1 100644 --- a/common/djangoapps/status/models.py +++ b/common/djangoapps/status/models.py @@ -2,15 +2,14 @@ Store status messages in the database. """ -from django.db import models +from config_models.admin import ConfigurationModelAdmin +from config_models.models import ConfigurationModel from django.contrib import admin from django.core.cache import cache +from django.db import models from openedx.core.djangoapps.xmodule_django.models import CourseKeyField -from config_models.models import ConfigurationModel -from config_models.admin import ConfigurationModelAdmin - class GlobalStatusMessage(ConfigurationModel): """ diff --git a/common/djangoapps/status/tests.py b/common/djangoapps/status/tests.py index 5e37e722c3..6b0ce0ac71 100644 --- a/common/djangoapps/status/tests.py +++ b/common/djangoapps/status/tests.py @@ -1,15 +1,15 @@ # -*- coding: utf-8 -*- """ Tests for setting and displaying the site status message. """ -import ddt import unittest -from django.test import TestCase -from django.core.cache import cache +import ddt from django.conf import settings +from django.core.cache import cache +from django.test import TestCase from opaque_keys.edx.locations import CourseLocator +from .models import CourseMessage, GlobalStatusMessage from .status import get_site_status_msg -from .models import GlobalStatusMessage, CourseMessage @ddt.ddt diff --git a/common/djangoapps/student/admin.py b/common/djangoapps/student/admin.py index 99857b2903..98b1767d7a 100644 --- a/common/djangoapps/student/admin.py +++ b/common/djangoapps/student/admin.py @@ -1,4 +1,5 @@ """ Django admin pages for student app """ +from config_models.admin import ConfigurationModelAdmin from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin as BaseUserAdmin @@ -6,15 +7,23 @@ from django.utils.translation import ugettext_lazy as _ from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from ratelimitbackend import admin -from xmodule.modulestore.django import modulestore -from config_models.admin import ConfigurationModelAdmin from student.models import ( - UserProfile, UserTestGroup, CourseEnrollmentAllowed, DashboardConfiguration, CourseEnrollment, Registration, - PendingNameChange, CourseAccessRole, LinkedInAddToProfileConfiguration, UserAttribute, LogoutViewConfiguration, - RegistrationCookieConfiguration + CourseAccessRole, + CourseEnrollment, + CourseEnrollmentAllowed, + DashboardConfiguration, + LinkedInAddToProfileConfiguration, + LogoutViewConfiguration, + PendingNameChange, + Registration, + RegistrationCookieConfiguration, + UserAttribute, + UserProfile, + UserTestGroup ) from student.roles import REGISTERED_ACCESS_ROLES +from xmodule.modulestore.django import modulestore User = get_user_model() # pylint:disable=invalid-name diff --git a/common/djangoapps/student/auth.py b/common/djangoapps/student/auth.py index efb93cde52..1bb23ae03f 100644 --- a/common/djangoapps/student/auth.py +++ b/common/djangoapps/student/auth.py @@ -4,14 +4,23 @@ authorization has authorization to do so, which infers authorization via role hi (GlobalStaff is superset of auths of course instructor, ...), which consults the config to decide whether to check course creator role, and other such functions. """ -from django.core.exceptions import PermissionDenied +from ccx_keys.locator import CCXBlockUsageLocator, CCXLocator from django.conf import settings +from django.core.exceptions import PermissionDenied from opaque_keys.edx.locator import LibraryLocator -from ccx_keys.locator import CCXLocator, CCXBlockUsageLocator - -from student.roles import GlobalStaff, CourseCreatorRole, CourseStaffRole, CourseInstructorRole, CourseRole, \ - CourseBetaTesterRole, OrgInstructorRole, OrgStaffRole, LibraryUserRole, OrgLibraryUserRole +from student.roles import ( + CourseBetaTesterRole, + CourseCreatorRole, + CourseInstructorRole, + CourseRole, + CourseStaffRole, + GlobalStaff, + LibraryUserRole, + OrgInstructorRole, + OrgLibraryUserRole, + OrgStaffRole +) # Studio permissions: STUDIO_EDIT_ROLES = 8 diff --git a/common/djangoapps/student/cookies.py b/common/djangoapps/student/cookies.py index d204020ab9..417dd3f5f6 100644 --- a/common/djangoapps/student/cookies.py +++ b/common/djangoapps/student/cookies.py @@ -8,7 +8,7 @@ import time import six from django.conf import settings -from django.core.urlresolvers import reverse, NoReverseMatch +from django.core.urlresolvers import NoReverseMatch, reverse from django.dispatch import Signal from django.utils.http import cookie_date diff --git a/common/djangoapps/student/forms.py b/common/djangoapps/student/forms.py index ff1511bd9a..81038f5076 100644 --- a/common/djangoapps/student/forms.py +++ b/common/djangoapps/student/forms.py @@ -1,25 +1,24 @@ """ Utility functions for validating forms """ -from importlib import import_module import re +from importlib import import_module from django import forms -from django.forms import widgets -from django.core.exceptions import ValidationError -from django.contrib.auth.models import User +from django.conf import settings from django.contrib.auth.forms import PasswordResetForm from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX +from django.contrib.auth.models import User from django.contrib.auth.tokens import default_token_generator - +from django.core.exceptions import ValidationError +from django.forms import widgets +from django.template import loader from django.utils.http import int_to_base36 from django.utils.translation import ugettext_lazy as _ -from django.template import loader -from django.conf import settings +from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from student.models import CourseEnrollmentAllowed from util.password_policy_validators import validate_password_strength -from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers class PasswordResetFormNoActive(PasswordResetForm): diff --git a/common/djangoapps/student/helpers.py b/common/djangoapps/student/helpers.py index bb7aeca853..e231cb7ab1 100644 --- a/common/djangoapps/student/helpers.py +++ b/common/djangoapps/student/helpers.py @@ -1,28 +1,23 @@ """Helpers for the student app. """ -from datetime import datetime import logging -import urllib import mimetypes +import urllib +from datetime import datetime from django.conf import settings -from django.core.urlresolvers import reverse, NoReverseMatch +from django.core.urlresolvers import NoReverseMatch, reverse from django.utils import http -from oauth2_provider.models import ( - AccessToken as dot_access_token, - RefreshToken as dot_refresh_token -) -from provider.oauth2.models import ( - AccessToken as dop_access_token, - RefreshToken as dop_refresh_token -) +from oauth2_provider.models import AccessToken as dot_access_token +from oauth2_provider.models import RefreshToken as dot_refresh_token +from provider.oauth2.models import AccessToken as dop_access_token +from provider.oauth2.models import RefreshToken as dop_refresh_token from pytz import UTC import third_party_auth -from lms.djangoapps.verify_student.models import VerificationDeadline, SoftwareSecurePhotoVerification from course_modes.models import CourseMode +from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification, VerificationDeadline from openedx.core.djangoapps.theming.helpers import get_themes - # Enumeration of per-course verification statuses # we display on the student dashboard. VERIFY_STATUS_NEED_TO_VERIFY = "verify_need_to_verify" diff --git a/common/djangoapps/student/middleware.py b/common/djangoapps/student/middleware.py index 055a76309f..ffde2e0a2e 100644 --- a/common/djangoapps/student/middleware.py +++ b/common/djangoapps/student/middleware.py @@ -2,9 +2,10 @@ Middleware that checks user standing for the purpose of keeping users with disabled accounts from accessing the site. """ +from django.conf import settings from django.http import HttpResponseForbidden from django.utils.translation import ugettext as _ -from django.conf import settings + from student.models import UserStanding diff --git a/common/djangoapps/student/migrations/0001_initial.py b/common/djangoapps/student/migrations/0001_initial.py index f4ed4cfcba..6bec6586a4 100644 --- a/common/djangoapps/student/migrations/0001_initial.py +++ b/common/djangoapps/student/migrations/0001_initial.py @@ -1,11 +1,12 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models +import django.db.models.deletion import django.utils.timezone import django_countries.fields -import django.db.models.deletion from django.conf import settings +from django.db import migrations, models + from openedx.core.djangoapps.xmodule_django.models import CourseKeyField diff --git a/common/djangoapps/student/migrations/0003_auto_20160516_0938.py b/common/djangoapps/student/migrations/0003_auto_20160516_0938.py index 9d2295ed86..a15c1b7960 100644 --- a/common/djangoapps/student/migrations/0003_auto_20160516_0938.py +++ b/common/djangoapps/student/migrations/0003_auto_20160516_0938.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.utils.timezone -from django.conf import settings import model_utils.fields +from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/student/migrations/0006_logoutviewconfiguration.py b/common/djangoapps/student/migrations/0006_logoutviewconfiguration.py index 33bb40038c..009fb87d7a 100644 --- a/common/djangoapps/student/migrations/0006_logoutviewconfiguration.py +++ b/common/djangoapps/student/migrations/0006_logoutviewconfiguration.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/student/migrations/0007_registrationcookieconfiguration.py b/common/djangoapps/student/migrations/0007_registrationcookieconfiguration.py index 822d502924..7dd87d7ce7 100644 --- a/common/djangoapps/student/migrations/0007_registrationcookieconfiguration.py +++ b/common/djangoapps/student/migrations/0007_registrationcookieconfiguration.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/student/models.py b/common/djangoapps/student/models.py index b75e043599..ca3e8a0af7 100644 --- a/common/djangoapps/student/models.py +++ b/common/djangoapps/student/models.py @@ -14,41 +14,41 @@ import hashlib import json import logging import uuid -from collections import defaultdict, OrderedDict, namedtuple +from collections import OrderedDict, defaultdict, namedtuple from datetime import datetime, timedelta from functools import total_ordering from importlib import import_module from urllib import urlencode import analytics -import dogstats_wrapper as dog_stats_api from config_models.models import ConfigurationModel from django.conf import settings from django.contrib.auth.hashers import make_password from django.contrib.auth.models import User from django.contrib.auth.signals import user_logged_in, user_logged_out from django.core.cache import cache -from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned -from django.db import models, IntegrityError +from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist +from django.db import IntegrityError, models from django.db.models import Count -from django.db.models.signals import pre_save, post_save -from django.dispatch import receiver, Signal +from django.db.models.signals import post_save, pre_save +from django.dispatch import Signal, receiver from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_noop from django_countries.fields import CountryField -from eventtracking import tracker from model_utils.models import TimeStampedModel from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locations import SlashSeparatedCourseKey from pytz import UTC from simple_history.models import HistoricalRecords +import dogstats_wrapper as dog_stats_api import lms.lib.comment_client as cc import request_cache from certificates.models import GeneratedCertificate from course_modes.models import CourseMode from enrollment.api import _default_course_mode +from eventtracking import tracker from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.djangoapps.xmodule_django.models import CourseKeyField, NoneToEmptyManager diff --git a/common/djangoapps/student/roles.py b/common/djangoapps/student/roles.py index 0fd10873c0..c14ea5b234 100644 --- a/common/djangoapps/student/roles.py +++ b/common/djangoapps/student/roles.py @@ -3,16 +3,15 @@ Classes used to model the roles used in the courseware. Each role is responsible adding users, removing users, and listing members """ +import logging from abc import ABCMeta, abstractmethod from collections import defaultdict from django.contrib.auth.models import User -import logging +from openedx.core.djangoapps.xmodule_django.models import CourseKeyField from request_cache import get_cache from student.models import CourseAccessRole -from openedx.core.djangoapps.xmodule_django.models import CourseKeyField - log = logging.getLogger(__name__) diff --git a/common/djangoapps/student/tasks.py b/common/djangoapps/student/tasks.py index 9ab3908acc..23b9481c30 100644 --- a/common/djangoapps/student/tasks.py +++ b/common/djangoapps/student/tasks.py @@ -2,13 +2,13 @@ This file contains celery tasks for sending email """ import logging + +from boto.exception import NoAuthHandlerFound +from celery.exceptions import MaxRetriesExceededError +from celery.task import task # pylint: disable=no-name-in-module, import-error from django.conf import settings from django.core import mail -from celery.task import task # pylint: disable=no-name-in-module, import-error -from celery.exceptions import MaxRetriesExceededError -from boto.exception import NoAuthHandlerFound - log = logging.getLogger('edx.celery.task') diff --git a/common/djangoapps/student/tests/factories.py b/common/djangoapps/student/tests/factories.py index ac7b2175e5..e5c39de629 100644 --- a/common/djangoapps/student/tests/factories.py +++ b/common/djangoapps/student/tests/factories.py @@ -1,20 +1,27 @@ """Provides factories for student models.""" import random +from datetime import datetime +from uuid import uuid4 -from student.models import (User, UserProfile, Registration, - CourseEnrollmentAllowed, CourseEnrollment, - PendingEmailChange, UserStanding, - CourseAccessRole) -from course_modes.models import CourseMode +import factory from django.contrib.auth.models import AnonymousUser, Group, Permission from django.contrib.contenttypes.models import ContentType -from datetime import datetime -import factory from factory import lazy_attribute from factory.django import DjangoModelFactory -from uuid import uuid4 -from pytz import UTC from opaque_keys.edx.locations import SlashSeparatedCourseKey +from pytz import UTC + +from course_modes.models import CourseMode +from student.models import ( + CourseAccessRole, + CourseEnrollment, + CourseEnrollmentAllowed, + PendingEmailChange, + Registration, + User, + UserProfile, + UserStanding +) # Factories are self documenting # pylint: disable=missing-docstring diff --git a/common/djangoapps/student/tests/test_activate_account.py b/common/djangoapps/student/tests/test_activate_account.py index 29876fe437..309ebbce59 100644 --- a/common/djangoapps/student/tests/test_activate_account.py +++ b/common/djangoapps/student/tests/test_activate_account.py @@ -1,17 +1,16 @@ """Tests for account activation""" -from mock import patch import unittest - -from django.conf import settings -from django.test import TestCase, override_settings -from django.core.urlresolvers import reverse - from uuid import uuid4 +from django.conf import settings +from django.core.urlresolvers import reverse +from django.test import TestCase, override_settings +from mock import patch + from edxmako.shortcuts import render_to_string +from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from student.models import Registration from student.tests.factories import UserFactory -from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') diff --git a/common/djangoapps/student/tests/test_admin_views.py b/common/djangoapps/student/tests/test_admin_views.py index 411b9a4e47..faa9456f18 100644 --- a/common/djangoapps/student/tests/test_admin_views.py +++ b/common/djangoapps/student/tests/test_admin_views.py @@ -3,9 +3,9 @@ Tests student admin.py """ from django.core.urlresolvers import reverse +from student.tests.factories import UserFactory from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory -from student.tests.factories import UserFactory class AdminCourseRolesPageTest(SharedModuleStoreTestCase): diff --git a/common/djangoapps/student/tests/test_authz.py b/common/djangoapps/student/tests/test_authz.py index bafa96ca9c..51b9282120 100644 --- a/common/djangoapps/student/tests/test_authz.py +++ b/common/djangoapps/student/tests/test_authz.py @@ -2,16 +2,15 @@ Tests authz.py """ import mock - -from django.test import TestCase -from django.contrib.auth.models import User, AnonymousUser -from django.core.exceptions import PermissionDenied - -from student.roles import CourseInstructorRole, CourseStaffRole, CourseCreatorRole -from student.tests.factories import AdminFactory -from student.auth import user_has_role, add_users, remove_users, has_studio_write_access, has_studio_read_access -from opaque_keys.edx.locations import SlashSeparatedCourseKey from ccx_keys.locator import CCXLocator +from django.contrib.auth.models import AnonymousUser, User +from django.core.exceptions import PermissionDenied +from django.test import TestCase +from opaque_keys.edx.locations import SlashSeparatedCourseKey + +from student.auth import add_users, has_studio_read_access, has_studio_write_access, remove_users, user_has_role +from student.roles import CourseCreatorRole, CourseInstructorRole, CourseStaffRole +from student.tests.factories import AdminFactory class CreatorGroupTest(TestCase): diff --git a/common/djangoapps/student/tests/test_auto_auth.py b/common/djangoapps/student/tests/test_auto_auth.py index 79c847e7e6..9a2dfab249 100644 --- a/common/djangoapps/student/tests/test_auto_auth.py +++ b/common/djangoapps/student/tests/test_auto_auth.py @@ -1,17 +1,18 @@ +import json + +import ddt +from django.conf import settings +from django.contrib.auth.models import User from django.test import TestCase from django.test.client import Client -from django.contrib.auth.models import User -from django.conf import settings -from django_comment_common.models import ( - Role, FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_STUDENT) -from django_comment_common.utils import seed_permissions_roles -from student.models import anonymous_id_for_user, CourseEnrollment, UserProfile -from util.testing import UrlResetMixin +from mock import Mock, patch from opaque_keys.edx.locations import SlashSeparatedCourseKey from opaque_keys.edx.locator import CourseLocator -from mock import patch, Mock -import ddt -import json + +from django_comment_common.models import FORUM_ROLE_ADMINISTRATOR, FORUM_ROLE_MODERATOR, FORUM_ROLE_STUDENT, Role +from django_comment_common.utils import seed_permissions_roles +from student.models import CourseEnrollment, UserProfile, anonymous_id_for_user +from util.testing import UrlResetMixin class AutoAuthTestCase(UrlResetMixin, TestCase): diff --git a/common/djangoapps/student/tests/test_bulk_email_settings.py b/common/djangoapps/student/tests/test_bulk_email_settings.py index e03bca37f5..ede3d3f4bc 100644 --- a/common/djangoapps/student/tests/test_bulk_email_settings.py +++ b/common/djangoapps/student/tests/test_bulk_email_settings.py @@ -10,14 +10,12 @@ from django.conf import settings from django.core.urlresolvers import reverse from opaque_keys.edx.locations import SlashSeparatedCourseKey -from student.tests.factories import UserFactory, CourseEnrollmentFactory -from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase -from xmodule.modulestore.tests.django_utils import TEST_DATA_MIXED_MODULESTORE -from xmodule.modulestore.tests.factories import CourseFactory - # This import is for an lms djangoapp. # Its testcases are only run under lms. -from bulk_email.models import CourseAuthorization, BulkEmailFlag # pylint: disable=import-error +from bulk_email.models import BulkEmailFlag, CourseAuthorization # pylint: disable=import-error +from student.tests.factories import CourseEnrollmentFactory, UserFactory +from xmodule.modulestore.tests.django_utils import TEST_DATA_MIXED_MODULESTORE, SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') diff --git a/common/djangoapps/student/tests/test_certificates.py b/common/djangoapps/student/tests/test_certificates.py index 0408cee519..9f6c8989cf 100644 --- a/common/djangoapps/student/tests/test_certificates.py +++ b/common/djangoapps/student/tests/test_certificates.py @@ -1,24 +1,24 @@ """Tests for display of certificates on the student dashboard. """ import unittest + import ddt import mock - from django.conf import settings from django.core.urlresolvers import reverse -from mock import patch from django.test.utils import override_settings -from xmodule.modulestore import ModuleStoreEnum +from mock import patch -from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase -from xmodule.modulestore.tests.factories import CourseFactory -from student.tests.factories import UserFactory, CourseEnrollmentFactory -from certificates.tests.factories import GeneratedCertificateFactory # pylint: disable=import-error from certificates.api import get_certificate_url # pylint: disable=import-error from certificates.models import CertificateStatuses # pylint: disable=import-error +from certificates.tests.factories import GeneratedCertificateFactory # pylint: disable=import-error from course_modes.models import CourseMode - from student.models import LinkedInAddToProfileConfiguration +from student.tests.factories import CourseEnrollmentFactory, UserFactory +from xmodule.modulestore import ModuleStoreEnum +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory + # pylint: disable=no-member diff --git a/common/djangoapps/student/tests/test_configuration_overrides.py b/common/djangoapps/student/tests/test_configuration_overrides.py index 279bfd21e3..4b14a6c340 100644 --- a/common/djangoapps/student/tests/test_configuration_overrides.py +++ b/common/djangoapps/student/tests/test_configuration_overrides.py @@ -1,12 +1,14 @@ """ Test for user creation from sites with configuration overrides. """ -from django.test import TestCase -from student.models import UserSignupSource -import mock import json -from django.core.urlresolvers import reverse + +import mock from django.contrib.auth.models import User +from django.core.urlresolvers import reverse +from django.test import TestCase + +from student.models import UserSignupSource FAKE_SITE = { "SITE_NAME": "openedx.localhost", diff --git a/common/djangoapps/student/tests/test_cookies.py b/common/djangoapps/student/tests/test_cookies.py index f1ca250d86..026c094c78 100644 --- a/common/djangoapps/student/tests/test_cookies.py +++ b/common/djangoapps/student/tests/test_cookies.py @@ -5,12 +5,12 @@ import six from django.conf import settings from django.core.urlresolvers import reverse from django.test import RequestFactory -from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase -from xmodule.modulestore.tests.factories import CourseFactory from student.cookies import get_user_info_cookie_data from student.models import CourseEnrollment from student.tests.factories import UserFactory +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory class CookieTests(SharedModuleStoreTestCase): diff --git a/common/djangoapps/student/tests/test_course_listing.py b/common/djangoapps/student/tests/test_course_listing.py index b9c8782ce2..68f9c5ec36 100644 --- a/common/djangoapps/student/tests/test_course_listing.py +++ b/common/djangoapps/student/tests/test_course_listing.py @@ -4,25 +4,22 @@ by reversing group name formats. """ import unittest +import mock from django.conf import settings from django.test.client import Client -import mock +from milestones.tests.utils import MilestonesTestCaseMixin from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from student.models import CourseEnrollment from student.roles import GlobalStaff from student.tests.factories import UserFactory from student.views import get_course_enrollments +from util.milestones_helpers import get_pre_requisite_courses_not_completed, set_prerequisite_courses from xmodule.error_module import ErrorDescriptor from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory -from util.milestones_helpers import ( - get_pre_requisite_courses_not_completed, - set_prerequisite_courses, -) -from milestones.tests.utils import MilestonesTestCaseMixin class TestCourseListing(ModuleStoreTestCase, MilestonesTestCaseMixin): diff --git a/common/djangoapps/student/tests/test_create_account.py b/common/djangoapps/student/tests/test_create_account.py index 0553ef0d5e..98d5a8b8dc 100644 --- a/common/djangoapps/student/tests/test_create_account.py +++ b/common/djangoapps/student/tests/test_create_account.py @@ -1,29 +1,29 @@ """Tests for account creation""" -from datetime import datetime import json import unittest +from datetime import datetime import ddt -from mock import patch +import mock +import pytz from django.conf import settings -from django.contrib.auth.models import User, AnonymousUser +from django.contrib.auth.models import AnonymousUser, User from django.core.urlresolvers import reverse from django.test import TestCase, TransactionTestCase from django.test.client import RequestFactory from django.test.utils import override_settings from django.utils.importlib import import_module -import mock -import pytz +from mock import patch -from openedx.core.djangoapps.user_api.preferences.api import get_user_preference -from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY -from openedx.core.djangoapps.site_configuration.tests.mixins import SiteMixin +import student +from django_comment_common.models import ForumsConfig from notification_prefs import NOTIFICATION_PREF_KEY from openedx.core.djangoapps.external_auth.models import ExternalAuthMap -import student +from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY +from openedx.core.djangoapps.site_configuration.tests.mixins import SiteMixin +from openedx.core.djangoapps.user_api.preferences.api import get_user_preference from student.models import UserAttribute -from student.views import REGISTRATION_AFFILIATE_ID, REGISTRATION_UTM_PARAMETERS, REGISTRATION_UTM_CREATED_AT -from django_comment_common.models import ForumsConfig +from student.views import REGISTRATION_AFFILIATE_ID, REGISTRATION_UTM_CREATED_AT, REGISTRATION_UTM_PARAMETERS TEST_CS_URL = 'https://comments.service.test:123/' diff --git a/common/djangoapps/student/tests/test_credit.py b/common/djangoapps/student/tests/test_credit.py index bdf5412dbb..73c3373bad 100644 --- a/common/djangoapps/student/tests/test_credit.py +++ b/common/djangoapps/student/tests/test_credit.py @@ -1,24 +1,22 @@ """ Tests for credit courses on the student dashboard. """ -import unittest import datetime +import unittest import ddt -from mock import patch import pytz from django.conf import settings from django.core.urlresolvers import reverse from django.test.utils import override_settings +from mock import patch +from openedx.core.djangoapps.credit import api as credit_api +from openedx.core.djangoapps.credit.models import CreditCourse, CreditEligibility, CreditProvider +from student.models import CourseEnrollmentAttribute +from student.tests.factories import CourseEnrollmentFactory, UserFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory -from student.models import CourseEnrollmentAttribute -from student.tests.factories import UserFactory, CourseEnrollmentFactory - -from openedx.core.djangoapps.credit.models import CreditCourse, CreditProvider, CreditEligibility -from openedx.core.djangoapps.credit import api as credit_api - TEST_CREDIT_PROVIDER_SECRET_KEY = "931433d583c84ca7ba41784bad3232e6" diff --git a/common/djangoapps/student/tests/test_email.py b/common/djangoapps/student/tests/test_email.py index 9033a00fba..9df658bddb 100644 --- a/common/djangoapps/student/tests/test_email.py +++ b/common/djangoapps/student/tests/test_email.py @@ -1,29 +1,34 @@ import json import unittest -import mock -from student.tests.factories import UserFactory, RegistrationFactory, PendingEmailChangeFactory -from student.views import ( - reactivation_email_for_user, do_email_change_request, confirm_email_change, - validate_new_email, SETTING_CHANGE_INITIATED, generate_activation_email_context -) -from student.models import UserProfile, PendingEmailChange, Registration -from third_party_auth.views import inactive_user_view -from django.core.urlresolvers import reverse -from django.core import mail +import mock +from django.conf import settings from django.contrib.auth.models import User +from django.core import mail +from django.core.urlresolvers import reverse from django.db import transaction +from django.http import HttpResponse from django.test import TestCase, TransactionTestCase from django.test.client import RequestFactory from mock import Mock, patch -from django.http import HttpResponse -from django.conf import settings + from edxmako.shortcuts import render_to_string -from util.request import safe_get_host -from util.testing import EventTestMixin from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.djangoapps.theming.tests.test_util import with_comprehensive_theme +from student.models import PendingEmailChange, Registration, UserProfile +from student.tests.factories import PendingEmailChangeFactory, RegistrationFactory, UserFactory +from student.views import ( + SETTING_CHANGE_INITIATED, + confirm_email_change, + do_email_change_request, + generate_activation_email_context, + reactivation_email_for_user, + validate_new_email +) +from third_party_auth.views import inactive_user_view +from util.request import safe_get_host +from util.testing import EventTestMixin class TestException(Exception): diff --git a/common/djangoapps/student/tests/test_enrollment.py b/common/djangoapps/student/tests/test_enrollment.py index b7a73f50b4..9aaf3f23aa 100644 --- a/common/djangoapps/student/tests/test_enrollment.py +++ b/common/djangoapps/student/tests/test_enrollment.py @@ -1,24 +1,22 @@ """ Tests for student enrollment. """ -import ddt import unittest + +import ddt +from django.conf import settings +from django.core.urlresolvers import reverse from mock import patch from nose.plugins.attrib import attr -from django.conf import settings -from django.core.urlresolvers import reverse from course_modes.models import CourseMode +from openedx.core.djangoapps.embargo.test_utils import restrict_course +from student.models import CourseEnrollment, CourseFullError +from student.roles import CourseInstructorRole, CourseStaffRole +from student.tests.factories import CourseModeFactory, UserFactory +from util.testing import UrlResetMixin from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory -from util.testing import UrlResetMixin -from openedx.core.djangoapps.embargo.test_utils import restrict_course -from student.tests.factories import UserFactory, CourseModeFactory -from student.models import CourseEnrollment, CourseFullError -from student.roles import ( - CourseInstructorRole, - CourseStaffRole, -) @attr(shard=3) diff --git a/common/djangoapps/student/tests/test_events.py b/common/djangoapps/student/tests/test_events.py index 158dd4b7dc..fc7c712f8e 100644 --- a/common/djangoapps/student/tests/test_events.py +++ b/common/djangoapps/student/tests/test_events.py @@ -2,15 +2,14 @@ """ Test that various events are fired for models in the student app. """ +import mock +from django.db.utils import IntegrityError from django.test import TestCase - from django_countries.fields import Country from student.models import PasswordHistory from student.tests.factories import UserFactory from student.tests.tests import UserSettingsEventTestMixin -import mock -from django.db.utils import IntegrityError class TestUserProfileEvents(UserSettingsEventTestMixin, TestCase): diff --git a/common/djangoapps/student/tests/test_helpers.py b/common/djangoapps/student/tests/test_helpers.py index db23ced5d6..708f5bd2c5 100644 --- a/common/djangoapps/student/tests/test_helpers.py +++ b/common/djangoapps/student/tests/test_helpers.py @@ -1,8 +1,8 @@ """ Test Student helpers """ import logging -import ddt +import ddt from django.conf import settings from django.core.urlresolvers import reverse from django.test import TestCase @@ -11,7 +11,6 @@ from testfixtures import LogCapture from student.helpers import get_next_url_for_login_page - LOGGER_NAME = "student.helpers" diff --git a/common/djangoapps/student/tests/test_linkedin.py b/common/djangoapps/student/tests/test_linkedin.py index 01a3e6481d..e91af411da 100644 --- a/common/djangoapps/student/tests/test_linkedin.py +++ b/common/djangoapps/student/tests/test_linkedin.py @@ -1,12 +1,13 @@ # -*- coding: utf-8 -*- """Tests for LinkedIn Add to Profile configuration. """ -import ddt -from urllib import urlencode, quote +from urllib import quote, urlencode +import ddt from django.conf import settings from django.test import TestCase from opaque_keys.edx.locator import CourseLocator + from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration_context from student.models import LinkedInAddToProfileConfiguration diff --git a/common/djangoapps/student/tests/test_login.py b/common/djangoapps/student/tests/test_login.py index cc0e6d766f..02b1c86c2e 100644 --- a/common/djangoapps/student/tests/test_login.py +++ b/common/djangoapps/student/tests/test_login.py @@ -4,29 +4,29 @@ Tests for student activation and login import json import unittest -from django.test import TestCase -from django.test.client import Client -from django.test.utils import override_settings +import httpretty from django.conf import settings from django.contrib.auth.models import User from django.core.cache import cache -from django.core.urlresolvers import reverse, NoReverseMatch -from django.http import HttpResponseBadRequest, HttpResponse -import httpretty +from django.core.urlresolvers import NoReverseMatch, reverse +from django.http import HttpResponse, HttpResponseBadRequest +from django.test import TestCase +from django.test.client import Client +from django.test.utils import override_settings from mock import patch from social.apps.django_app.default.models import UserSocialAuth from openedx.core.djangoapps.external_auth.models import ExternalAuthMap from openedx.core.djangolib.testing.utils import CacheIsolationTestCase -from student.tests.factories import UserFactory, RegistrationFactory, UserProfileFactory +from student.tests.factories import RegistrationFactory, UserFactory, UserProfileFactory from student.views import login_oauth_token from third_party_auth.tests.utils import ( ThirdPartyOAuthTestMixin, ThirdPartyOAuthTestMixinFacebook, ThirdPartyOAuthTestMixinGoogle ) -from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory class LoginTest(CacheIsolationTestCase): diff --git a/common/djangoapps/student/tests/test_login_registration_forms.py b/common/djangoapps/student/tests/test_login_registration_forms.py index 5cb44a8586..3ddd0ed402 100644 --- a/common/djangoapps/student/tests/test_login_registration_forms.py +++ b/common/djangoapps/student/tests/test_login_registration_forms.py @@ -1,16 +1,16 @@ """Tests for the login and registration form rendering. """ -import urllib import unittest +import urllib import ddt -from mock import patch from django.conf import settings from django.core.urlresolvers import reverse +from mock import patch -from util.testing import UrlResetMixin -from xmodule.modulestore.tests.factories import CourseFactory from third_party_auth.tests.testutil import ThirdPartyAuthTestMixin +from util.testing import UrlResetMixin from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory # This relies on third party auth being enabled in the test # settings with the feature flag `ENABLE_THIRD_PARTY_AUTH` diff --git a/common/djangoapps/student/tests/test_long_username_email.py b/common/djangoapps/student/tests/test_long_username_email.py index 4bdd7f6fba..b1e15adbbf 100644 --- a/common/djangoapps/student/tests/test_long_username_email.py +++ b/common/djangoapps/student/tests/test_long_username_email.py @@ -1,8 +1,9 @@ # -*- coding: utf-8 -*- import json -from django.test import TestCase + from django.core.urlresolvers import reverse +from django.test import TestCase class TestLongUsernameEmail(TestCase): diff --git a/common/djangoapps/student/tests/test_models.py b/common/djangoapps/student/tests/test_models.py index aaf8ac595f..4f1f3421cc 100644 --- a/common/djangoapps/student/tests/test_models.py +++ b/common/djangoapps/student/tests/test_models.py @@ -5,11 +5,11 @@ import hashlib from django.contrib.auth.models import AnonymousUser from django.core.cache import cache from django.db.models.functions import Lower -from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase -from xmodule.modulestore.tests.factories import CourseFactory from student.models import CourseEnrollment -from student.tests.factories import UserFactory, CourseEnrollmentFactory +from student.tests.factories import CourseEnrollmentFactory, UserFactory +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory class CourseEnrollmentTests(SharedModuleStoreTestCase): diff --git a/common/djangoapps/student/tests/test_parental_controls.py b/common/djangoapps/student/tests/test_parental_controls.py index d37bd96729..9382ea00d6 100644 --- a/common/djangoapps/student/tests/test_parental_controls.py +++ b/common/djangoapps/student/tests/test_parental_controls.py @@ -1,6 +1,7 @@ """Unit tests for parental controls.""" import datetime + from django.test import TestCase from django.test.utils import override_settings diff --git a/common/djangoapps/student/tests/test_password_history.py b/common/djangoapps/student/tests/test_password_history.py index b964694f47..74769ca5b2 100644 --- a/common/djangoapps/student/tests/test_password_history.py +++ b/common/djangoapps/student/tests/test_password_history.py @@ -2,16 +2,16 @@ """ This test file will verify proper password history enforcement """ -from django.test import TestCase -from django.utils import timezone -from mock import patch -from student.tests.factories import UserFactory, AdminFactory - -from student.models import PasswordHistory -from freezegun import freeze_time from datetime import timedelta +from django.test import TestCase from django.test.utils import override_settings +from django.utils import timezone +from freezegun import freeze_time +from mock import patch + +from student.models import PasswordHistory +from student.tests.factories import AdminFactory, UserFactory @patch.dict("django.conf.settings.FEATURES", {'ADVANCED_SECURITY': True}) diff --git a/common/djangoapps/student/tests/test_password_policy.py b/common/djangoapps/student/tests/test_password_policy.py index 84bd039664..148e73792a 100644 --- a/common/djangoapps/student/tests/test_password_policy.py +++ b/common/djangoapps/student/tests/test_password_policy.py @@ -3,14 +3,16 @@ This test file will verify proper password policy enforcement, which is an option feature """ import json +from importlib import import_module + +from django.conf import settings +from django.contrib.auth.models import AnonymousUser +from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import RequestFactory -from django.core.urlresolvers import reverse -from django.contrib.auth.models import AnonymousUser -from importlib import import_module from django.test.utils import override_settings -from django.conf import settings from mock import patch + from openedx.core.djangoapps.external_auth.models import ExternalAuthMap from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory from student.views import create_account diff --git a/common/djangoapps/student/tests/test_recent_enrollments.py b/common/djangoapps/student/tests/test_recent_enrollments.py index 209dd45796..bb647703c0 100644 --- a/common/djangoapps/student/tests/test_recent_enrollments.py +++ b/common/djangoapps/student/tests/test_recent_enrollments.py @@ -2,23 +2,24 @@ Tests for the recently enrolled messaging within the Dashboard. """ import datetime +import unittest + +import ddt from django.conf import settings from django.core.urlresolvers import reverse +from nose.plugins.attrib import attr from opaque_keys.edx import locator from pytz import UTC -from nose.plugins.attrib import attr -import unittest -import ddt -from shoppingcart.models import DonationConfiguration +from common.test.utils import XssTestMixin +from course_modes.tests.factories import CourseModeFactory +from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration_context +from shoppingcart.models import DonationConfiguration +from student.models import CourseEnrollment, DashboardConfiguration from student.tests.factories import UserFactory +from student.views import _get_recently_enrolled_courses, get_course_enrollments from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory -from course_modes.tests.factories import CourseModeFactory -from student.models import CourseEnrollment, DashboardConfiguration -from student.views import get_course_enrollments, _get_recently_enrolled_courses -from common.test.utils import XssTestMixin -from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration_context @attr(shard=3) diff --git a/common/djangoapps/student/tests/test_refunds.py b/common/djangoapps/student/tests/test_refunds.py index 24046a85b0..71c0038aa9 100644 --- a/common/djangoapps/student/tests/test_refunds.py +++ b/common/djangoapps/student/tests/test_refunds.py @@ -1,32 +1,30 @@ """ Tests for enrollment refund capabilities. """ +import logging +import unittest from datetime import datetime, timedelta + import ddt import httpretty -import logging import pytz -import unittest - +# Explicitly import the cache from ConfigurationModel so we can reset it after each test +from config_models.models import cache from django.conf import settings from django.core.urlresolvers import reverse from django.test.client import Client from django.test.utils import override_settings from mock import patch -from student.models import CourseEnrollment, CourseEnrollmentAttribute -from student.tests.factories import UserFactory, CourseModeFactory -from xmodule.modulestore.tests.factories import CourseFactory -from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase - # These imports refer to lms djangoapps. # Their testcases are only run under lms. from certificates.models import CertificateStatuses, GeneratedCertificate # pylint: disable=import-error from certificates.tests.factories import GeneratedCertificateFactory # pylint: disable=import-error from openedx.core.djangoapps.commerce.utils import ECOMMERCE_DATE_FORMAT - -# Explicitly import the cache from ConfigurationModel so we can reset it after each test -from config_models.models import cache +from student.models import CourseEnrollment, CourseEnrollmentAttribute +from student.tests.factories import CourseModeFactory, UserFactory +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory log = logging.getLogger(__name__) TEST_API_URL = 'http://www-internal.example.com/api' diff --git a/common/djangoapps/student/tests/test_reset_password.py b/common/djangoapps/student/tests/test_reset_password.py index 8c7262ca58..0a973060fd 100644 --- a/common/djangoapps/student/tests/test_reset_password.py +++ b/common/djangoapps/student/tests/test_reset_password.py @@ -5,31 +5,29 @@ import json import re import unittest +import ddt +from django.conf import settings +from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX +from django.contrib.auth.models import User +from django.contrib.auth.tokens import default_token_generator from django.core.cache import cache from django.core.urlresolvers import reverse -from django.conf import settings from django.test.client import RequestFactory -from django.contrib.auth.models import User -from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX -from django.contrib.auth.tokens import default_token_generator -from edx_oauth2_provider.tests.factories import ClientFactory, AccessTokenFactory, RefreshTokenFactory +from django.utils.http import int_to_base36 +from edx_oauth2_provider.tests.factories import AccessTokenFactory, ClientFactory, RefreshTokenFactory +from mock import Mock, patch from oauth2_provider import models as dot_models from provider.oauth2 import models as dop_models -from django.utils.http import int_to_base36 - -from mock import Mock, patch -import ddt - from openedx.core.djangoapps.oauth_dispatch.tests import factories as dot_factories +from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.djangolib.testing.utils import CacheIsolationTestCase -from student.views import password_reset, password_reset_confirm_wrapper, SETTING_CHANGE_INITIATED from student.tests.factories import UserFactory from student.tests.test_email import mock_render_to_string +from student.views import SETTING_CHANGE_INITIATED, password_reset, password_reset_confirm_wrapper from util.testing import EventTestMixin from .test_configuration_overrides import fake_get_value -from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers @unittest.skipUnless( diff --git a/common/djangoapps/student/tests/test_roles.py b/common/djangoapps/student/tests/test_roles.py index f73b578242..20c24dae51 100644 --- a/common/djangoapps/student/tests/test_roles.py +++ b/common/djangoapps/student/tests/test_roles.py @@ -3,16 +3,21 @@ Tests of student.roles """ import ddt from django.test import TestCase - -from courseware.tests.factories import UserFactory, StaffFactory, InstructorFactory -from student.tests.factories import AnonymousUserFactory - -from student.roles import ( - GlobalStaff, CourseRole, CourseStaffRole, CourseInstructorRole, - OrgStaffRole, OrgInstructorRole, RoleCache, CourseBetaTesterRole -) from opaque_keys.edx.locations import SlashSeparatedCourseKey +from courseware.tests.factories import InstructorFactory, StaffFactory, UserFactory +from student.roles import ( + CourseBetaTesterRole, + CourseInstructorRole, + CourseRole, + CourseStaffRole, + GlobalStaff, + OrgInstructorRole, + OrgStaffRole, + RoleCache +) +from student.tests.factories import AnonymousUserFactory + class RolesTestCase(TestCase): """ diff --git a/common/djangoapps/student/tests/test_tasks.py b/common/djangoapps/student/tests/test_tasks.py index 2618a8a898..d75af35a2f 100644 --- a/common/djangoapps/student/tests/test_tasks.py +++ b/common/djangoapps/student/tests/test_tasks.py @@ -3,13 +3,12 @@ Tests for the Sending activation email celery tasks """ import mock - -from django.test import TestCase -from django.conf import settings -from student.tasks import send_activation_email from boto.exception import NoAuthHandlerFound +from django.conf import settings +from django.test import TestCase from lms.djangoapps.courseware.tests.factories import UserFactory +from student.tasks import send_activation_email class SendActivationEmailTestCase(TestCase): diff --git a/common/djangoapps/student/tests/test_user_profile_properties.py b/common/djangoapps/student/tests/test_user_profile_properties.py index 7649859ce8..678d027053 100644 --- a/common/djangoapps/student/tests/test_user_profile_properties.py +++ b/common/djangoapps/student/tests/test_user_profile_properties.py @@ -1,12 +1,13 @@ """Unit tests for custom UserProfile properties.""" import datetime -import ddt +import ddt +from django.core.cache import cache + +from openedx.core.djangolib.testing.utils import CacheIsolationTestCase from student.models import UserProfile from student.tests.factories import UserFactory -from django.core.cache import cache -from openedx.core.djangolib.testing.utils import CacheIsolationTestCase @ddt.ddt diff --git a/common/djangoapps/student/tests/test_userstanding.py b/common/djangoapps/student/tests/test_userstanding.py index c65bd9264e..011019dfc0 100644 --- a/common/djangoapps/student/tests/test_userstanding.py +++ b/common/djangoapps/student/tests/test_userstanding.py @@ -4,11 +4,12 @@ that students with disabled accounts are unable to access the courseware. """ import unittest -from student.tests.factories import UserFactory, UserStandingFactory -from student.models import UserStanding from django.conf import settings -from django.test import TestCase, Client from django.core.urlresolvers import reverse +from django.test import Client, TestCase + +from student.models import UserStanding +from student.tests.factories import UserFactory, UserStandingFactory class UserStandingTest(TestCase): diff --git a/common/djangoapps/student/tests/test_verification_status.py b/common/djangoapps/student/tests/test_verification_status.py index a4e023f93a..75f58848cd 100644 --- a/common/djangoapps/student/tests/test_verification_status.py +++ b/common/djangoapps/student/tests/test_verification_status.py @@ -1,30 +1,29 @@ """Tests for per-course verification status on the dashboard. """ +import unittest from datetime import datetime, timedelta -import unittest import ddt +from django.conf import settings +from django.core.urlresolvers import reverse +from django.test import override_settings from mock import patch from nose.plugins.attrib import attr from pytz import UTC -from django.core.urlresolvers import reverse -from django.conf import settings -from django.test import override_settings +from course_modes.tests.factories import CourseModeFactory +from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification, VerificationDeadline from student.helpers import ( - VERIFY_STATUS_NEED_TO_VERIFY, - VERIFY_STATUS_SUBMITTED, - VERIFY_STATUS_RESUBMITTED, VERIFY_STATUS_APPROVED, VERIFY_STATUS_MISSED_DEADLINE, - VERIFY_STATUS_NEED_TO_REVERIFY + VERIFY_STATUS_NEED_TO_REVERIFY, + VERIFY_STATUS_NEED_TO_VERIFY, + VERIFY_STATUS_RESUBMITTED, + VERIFY_STATUS_SUBMITTED ) - -from xmodule.modulestore.tests.factories import CourseFactory -from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase -from student.tests.factories import UserFactory, CourseEnrollmentFactory -from course_modes.tests.factories import CourseModeFactory -from lms.djangoapps.verify_student.models import VerificationDeadline, SoftwareSecurePhotoVerification +from student.tests.factories import CourseEnrollmentFactory, UserFactory from util.testing import UrlResetMixin +from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory @attr(shard=3) diff --git a/common/djangoapps/student/tests/test_views.py b/common/djangoapps/student/tests/test_views.py index 54fea87b6b..8ccd12ee02 100644 --- a/common/djangoapps/student/tests/test_views.py +++ b/common/djangoapps/student/tests/test_views.py @@ -4,26 +4,25 @@ Test the student dashboard view. import datetime import itertools import json -import pytz import unittest import ddt +import pytz from django.conf import settings from django.core.urlresolvers import reverse -from django.test import RequestFactory -from django.test import TestCase +from django.test import RequestFactory, TestCase from edx_oauth2_provider.constants import AUTHORIZED_CLIENTS_SESSION_KEY from edx_oauth2_provider.tests.factories import ClientFactory, TrustedClientFactory from mock import patch from pyquery import PyQuery as pq -from xmodule.modulestore import ModuleStoreEnum -from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase -from xmodule.modulestore.tests.factories import CourseFactory from student.cookies import get_user_info_cookie_data from student.helpers import DISABLE_UNENROLL_CERT_STATES from student.models import CourseEnrollment, LogoutViewConfiguration, UserProfile -from student.tests.factories import UserFactory, CourseEnrollmentFactory +from student.tests.factories import CourseEnrollmentFactory, UserFactory +from xmodule.modulestore import ModuleStoreEnum +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory PASSWORD = 'test' diff --git a/common/djangoapps/student/tests/tests.py b/common/djangoapps/student/tests/tests.py index 5034cdad1c..0052115d95 100644 --- a/common/djangoapps/student/tests/tests.py +++ b/common/djangoapps/student/tests/tests.py @@ -2,63 +2,54 @@ """ Miscellaneous tests for the student app. """ -from datetime import datetime, timedelta import json import logging import unittest +from datetime import datetime, timedelta from urllib import quote import ddt +import httpretty +import pytz +from config_models.models import cache from django.conf import settings -from django.contrib.auth.models import User, AnonymousUser +from django.contrib.auth.models import AnonymousUser, User from django.core.urlresolvers import reverse from django.test import TestCase, override_settings from django.test.client import Client -import httpretty from markupsafe import escape from mock import Mock, patch from nose.plugins.attrib import attr -from opaque_keys.edx.locations import SlashSeparatedCourseKey, CourseLocator +from opaque_keys.edx.locations import CourseLocator, SlashSeparatedCourseKey from provider.constants import CONFIDENTIAL from pyquery import PyQuery as pq -import pytz +import shoppingcart # pylint: disable=import-error from bulk_email.models import Optout # pylint: disable=import-error from certificates.models import CertificateStatuses # pylint: disable=import-error from certificates.tests.factories import GeneratedCertificateFactory # pylint: disable=import-error -from config_models.models import cache from course_modes.models import CourseMode from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification -from openedx.core.djangoapps.catalog.tests.factories import ( - generate_course_run_key, - ProgramFactory, - CourseFactory as CatalogCourseFactory, - CourseRunFactory, -) +from openedx.core.djangoapps.catalog.tests.factories import CourseFactory as CatalogCourseFactory +from openedx.core.djangoapps.catalog.tests.factories import CourseRunFactory, ProgramFactory, generate_course_run_key from openedx.core.djangoapps.programs.tests.mixins import ProgramsApiConfigMixin from openedx.core.djangoapps.site_configuration.tests.mixins import SiteMixin from openedx.core.djangolib.testing.utils import CacheIsolationTestCase, skip_unless_lms -import shoppingcart # pylint: disable=import-error from student.models import ( - anonymous_id_for_user, user_by_anonymous_id, CourseEnrollment, - unique_id_for_user, LinkedInAddToProfileConfiguration, UserAttribute -) -from student.tests.factories import UserFactory, CourseModeFactory, CourseEnrollmentFactory -from student.views import ( - process_survey_link, - _cert_info, - complete_course_mode_info, + CourseEnrollment, + LinkedInAddToProfileConfiguration, + UserAttribute, + anonymous_id_for_user, + unique_id_for_user, + user_by_anonymous_id ) +from student.tests.factories import CourseEnrollmentFactory, CourseModeFactory, UserFactory +from student.views import _cert_info, complete_course_mode_info, process_survey_link from util.model_utils import USER_SETTINGS_CHANGED_EVENT_NAME from util.testing import EventTestMixin -from xmodule.modulestore.tests.django_utils import ( - ModuleStoreTestCase, - ModuleStoreEnum, - SharedModuleStoreTestCase, -) +from xmodule.modulestore.tests.django_utils import ModuleStoreEnum, ModuleStoreTestCase, SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory, check_mongo_calls - log = logging.getLogger(__name__) diff --git a/common/djangoapps/student/views.py b/common/djangoapps/student/views.py index d658eeb374..7167cf7ba7 100644 --- a/common/djangoapps/student/views.py +++ b/common/djangoapps/student/views.py @@ -2,139 +2,132 @@ Student Views """ import datetime +import json import logging import uuid -import json import warnings -from collections import defaultdict -from urlparse import urljoin, urlsplit, parse_qs, urlunsplit - -from django.views.generic import TemplateView -from pytz import UTC -from requests import HTTPError -from ipware.ip import get_ip +from collections import defaultdict, namedtuple +from urlparse import parse_qs, urljoin, urlsplit, urlunsplit +import analytics import edx_oauth2_provider from django.conf import settings -from django.contrib.auth import logout, authenticate, login -from django.contrib.auth.models import User, AnonymousUser -from django.contrib.auth.decorators import login_required -from django.contrib.auth.views import password_reset_confirm from django.contrib import messages -from django.core.context_processors import csrf +from django.contrib.auth import authenticate, login, logout +from django.contrib.auth.decorators import login_required +from django.contrib.auth.models import AnonymousUser, User +from django.contrib.auth.views import password_reset_confirm from django.core import mail -from django.core.exceptions import PermissionDenied, ObjectDoesNotExist -from django.core.urlresolvers import reverse, NoReverseMatch, reverse_lazy -from django.core.validators import validate_email, ValidationError +from django.core.context_processors import csrf +from django.core.exceptions import ObjectDoesNotExist, PermissionDenied +from django.core.urlresolvers import NoReverseMatch, reverse, reverse_lazy +from django.core.validators import ValidationError, validate_email from django.db import IntegrityError, transaction -from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseServerError, Http404 -from django.shortcuts import redirect -from django.utils.encoding import force_bytes, force_text -from django.utils.translation import ungettext -from django.utils.http import base36_to_int, is_safe_url, urlsafe_base64_encode, urlencode -from django.utils.translation import ugettext as _, get_language -from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie -from django.views.decorators.http import require_POST, require_GET from django.db.models.signals import post_save -from django.dispatch import receiver, Signal +from django.dispatch import Signal, receiver +from django.http import Http404, HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseServerError +from django.shortcuts import redirect from django.template.response import TemplateResponse -from provider.oauth2.models import Client -from ratelimitbackend.exceptions import RateLimitException - -from social.apps.django_app import utils as social_utils -from social.backends import oauth as social_oauth -from social.exceptions import AuthException, AuthAlreadyAssociated - -from edxmako.shortcuts import render_to_response, render_to_string - -from course_modes.models import CourseMode -from shoppingcart.api import order_history -from student.models import ( - Registration, UserProfile, - PendingEmailChange, CourseEnrollment, CourseEnrollmentAttribute, unique_id_for_user, - CourseEnrollmentAllowed, UserStanding, LoginFailures, - create_comments_service_user, PasswordHistory, UserSignupSource, - DashboardConfiguration, LinkedInAddToProfileConfiguration, ManualEnrollmentAudit, ALLOWEDTOENROLL_TO_ENROLLED, - LogoutViewConfiguration, RegistrationCookieConfiguration) -from student.forms import AccountCreationForm, PasswordResetFormNoActive, get_registration_extension_form -from student.tasks import send_activation_email -from lms.djangoapps.commerce.utils import EcommerceService # pylint: disable=import-error -from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification # pylint: disable=import-error -from bulk_email.models import Optout, BulkEmailFlag # pylint: disable=import-error -from certificates.models import ( # pylint: disable=import-error - CertificateStatuses, GeneratedCertificate, certificate_status_for_student -) -from certificates.api import ( # pylint: disable=import-error - get_certificate_url, - has_html_certificates_enabled, -) -from lms.djangoapps.grades.new.course_grade_factory import CourseGradeFactory - -from xmodule.modulestore.django import modulestore +from django.utils.encoding import force_bytes, force_text +from django.utils.http import base36_to_int, is_safe_url, urlencode, urlsafe_base64_encode +from django.utils.translation import ugettext as _ +from django.utils.translation import get_language, ungettext +from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie +from django.views.decorators.http import require_GET, require_POST +from django.views.generic import TemplateView +from ipware.ip import get_ip from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locations import SlashSeparatedCourseKey from opaque_keys.edx.locator import CourseLocator - -from collections import namedtuple - -from courseware.courses import get_courses, sort_by_announcement, sort_by_start_date # pylint: disable=import-error -from courseware.access import has_access - -from django_comment_common.models import Role - -from openedx.core.djangoapps.external_auth.models import ExternalAuthMap -import openedx.core.djangoapps.external_auth.views -from openedx.core.djangoapps.external_auth.login_and_register import ( - login as external_auth_login, - register as external_auth_register -) -from openedx.core.djangoapps import monitoring_utils -from openedx.core.djangolib.markup import HTML - -import track.views +from provider.oauth2.models import Client +from pytz import UTC +from ratelimitbackend.exceptions import RateLimitException +from requests import HTTPError +from social.apps.django_app import utils as social_utils +from social.backends import oauth as social_oauth +from social.exceptions import AuthAlreadyAssociated, AuthException import dogstats_wrapper as dog_stats_api - -from util.db import outer_atomic -from util.json_request import JsonResponse -from util.bad_request_rate_limiter import BadRequestRateLimiter -from util.milestones_helpers import ( - get_pre_requisite_courses_not_completed, -) - -from util.password_policy_validators import validate_password_strength +import openedx.core.djangoapps.external_auth.views import third_party_auth -from third_party_auth import pipeline, provider -from student.helpers import ( - check_verify_status_by_course, - auth_pipeline_urls, get_next_url_for_login_page, - DISABLE_UNENROLL_CERT_STATES, - destroy_oauth_tokens +import track.views +from bulk_email.models import BulkEmailFlag, Optout # pylint: disable=import-error +from certificates.api import get_certificate_url, has_html_certificates_enabled # pylint: disable=import-error +from certificates.models import ( # pylint: disable=import-error + CertificateStatuses, + GeneratedCertificate, + certificate_status_for_student ) -from student.cookies import set_logged_in_cookies, delete_logged_in_cookies, set_user_info_cookie -from student.models import anonymous_id_for_user, UserAttribute, EnrollStatusChange -from shoppingcart.models import DonationConfiguration, CourseRegistrationCode - -from openedx.core.djangoapps.embargo import api as embargo_api -from openedx.features.course_experience import course_home_url_name -from openedx.features.enterprise_support.api import get_dashboard_consent_notification - -import analytics +from course_modes.models import CourseMode +from courseware.access import has_access +from courseware.courses import get_courses, sort_by_announcement, sort_by_start_date # pylint: disable=import-error +from django_comment_common.models import Role +from edxmako.shortcuts import render_to_response, render_to_string from eventtracking import tracker - +from lms.djangoapps.commerce.utils import EcommerceService # pylint: disable=import-error +from lms.djangoapps.grades.new.course_grade_factory import CourseGradeFactory +from lms.djangoapps.verify_student.models import SoftwareSecurePhotoVerification # pylint: disable=import-error # Note that this lives in LMS, so this dependency should be refactored. from notification_prefs.views import enable_notifications - +from openedx.core.djangoapps import monitoring_utils from openedx.core.djangoapps.catalog.utils import get_programs_with_type from openedx.core.djangoapps.credit.email_utils import get_credit_provider_display_names, make_providers_strings +from openedx.core.djangoapps.embargo import api as embargo_api +from openedx.core.djangoapps.external_auth.login_and_register import login as external_auth_login +from openedx.core.djangoapps.external_auth.login_and_register import register as external_auth_register +from openedx.core.djangoapps.external_auth.models import ExternalAuthMap from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY from openedx.core.djangoapps.programs.models import ProgramsApiConfig from openedx.core.djangoapps.programs.utils import ProgramProgressMeter from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.djangoapps.theming import helpers as theming_helpers from openedx.core.djangoapps.user_api.preferences import api as preferences_api - +from openedx.core.djangolib.markup import HTML +from openedx.features.course_experience import course_home_url_name +from openedx.features.enterprise_support.api import get_dashboard_consent_notification +from shoppingcart.api import order_history +from shoppingcart.models import CourseRegistrationCode, DonationConfiguration +from student.cookies import delete_logged_in_cookies, set_logged_in_cookies, set_user_info_cookie +from student.forms import AccountCreationForm, PasswordResetFormNoActive, get_registration_extension_form +from student.helpers import ( + DISABLE_UNENROLL_CERT_STATES, + auth_pipeline_urls, + check_verify_status_by_course, + destroy_oauth_tokens, + get_next_url_for_login_page +) +from student.models import ( + ALLOWEDTOENROLL_TO_ENROLLED, + CourseEnrollment, + CourseEnrollmentAllowed, + CourseEnrollmentAttribute, + DashboardConfiguration, + EnrollStatusChange, + LinkedInAddToProfileConfiguration, + LoginFailures, + LogoutViewConfiguration, + ManualEnrollmentAudit, + PasswordHistory, + PendingEmailChange, + Registration, + RegistrationCookieConfiguration, + UserAttribute, + UserProfile, + UserSignupSource, + UserStanding, + anonymous_id_for_user, + create_comments_service_user, + unique_id_for_user +) +from student.tasks import send_activation_email +from third_party_auth import pipeline, provider +from util.bad_request_rate_limiter import BadRequestRateLimiter +from util.db import outer_atomic +from util.json_request import JsonResponse +from util.milestones_helpers import get_pre_requisite_courses_not_completed +from util.password_policy_validators import validate_password_strength +from xmodule.modulestore.django import modulestore log = logging.getLogger("edx.student") AUDIT_LOG = logging.getLogger("audit") diff --git a/common/djangoapps/terrain/browser.py b/common/djangoapps/terrain/browser.py index 287d8917b3..6c59c5da6e 100644 --- a/common/djangoapps/terrain/browser.py +++ b/common/djangoapps/terrain/browser.py @@ -5,16 +5,17 @@ Browser set up for acceptance tests. # pylint: disable=no-member # pylint: disable=unused-argument -from lettuce import before, after, world -from splinter.browser import Browser -from logging import getLogger -from django.core.management import call_command -from django.conf import settings -from selenium.common.exceptions import WebDriverException -from selenium.webdriver.common.desired_capabilities import DesiredCapabilities -import requests from base64 import encodestring from json import dumps +from logging import getLogger + +import requests +from django.conf import settings +from django.core.management import call_command +from lettuce import after, before, world +from selenium.common.exceptions import WebDriverException +from selenium.webdriver.common.desired_capabilities import DesiredCapabilities +from splinter.browser import Browser import xmodule.modulestore.django from xmodule.contentstore.django import _CONTENTSTORE diff --git a/common/djangoapps/terrain/course_helpers.py b/common/djangoapps/terrain/course_helpers.py index 802d5d66cb..92988f72d4 100644 --- a/common/djangoapps/terrain/course_helpers.py +++ b/common/djangoapps/terrain/course_helpers.py @@ -1,11 +1,13 @@ # pylint: disable=missing-docstring import urllib -from lettuce import world + from django.contrib.auth.models import User +from lettuce import world + from student.models import CourseEnrollment -from xmodule.modulestore.django import modulestore, clear_existing_modulestores from xmodule.contentstore.django import _CONTENTSTORE +from xmodule.modulestore.django import clear_existing_modulestores, modulestore @world.absorb diff --git a/common/djangoapps/terrain/factories.py b/common/djangoapps/terrain/factories.py index 29df3c0f43..c8009277ef 100644 --- a/common/djangoapps/terrain/factories.py +++ b/common/djangoapps/terrain/factories.py @@ -3,10 +3,11 @@ Factories are defined in other modules and absorbed here into the lettuce world so that they can be used by both unit tests and integration / BDD tests. ''' +from lettuce import world + +import course_modes.tests.factories as cmf import student.tests.factories as sf import xmodule.modulestore.tests.factories as xf -import course_modes.tests.factories as cmf -from lettuce import world # Unlock XBlock factories, because we're randomizing the collection # name above to prevent collisions diff --git a/common/djangoapps/terrain/setup_prereqs.py b/common/djangoapps/terrain/setup_prereqs.py index 7faec1803f..62ade03575 100644 --- a/common/djangoapps/terrain/setup_prereqs.py +++ b/common/djangoapps/terrain/setup_prereqs.py @@ -5,18 +5,18 @@ This includes initialization and teardown for stub and video HTTP services and checking for external URLs that need to be accessible and responding. """ -from lettuce import before, after, world +import re +from logging import getLogger + +import requests from django.conf import settings -from terrain.stubs.youtube import StubYouTubeService -from terrain.stubs.xqueue import StubXQueueService -from terrain.stubs.lti import StubLtiService -from terrain.stubs.video_source import VideoSourceHttpService +from lettuce import after, before, world from selenium.common.exceptions import NoAlertPresentException -import re -import requests - -from logging import getLogger +from terrain.stubs.lti import StubLtiService +from terrain.stubs.video_source import VideoSourceHttpService +from terrain.stubs.xqueue import StubXQueueService +from terrain.stubs.youtube import StubYouTubeService LOGGER = getLogger(__name__) diff --git a/common/djangoapps/terrain/steps.py b/common/djangoapps/terrain/steps.py index dd16eddcdd..a8acf5f474 100644 --- a/common/djangoapps/terrain/steps.py +++ b/common/djangoapps/terrain/steps.py @@ -12,18 +12,18 @@ # pylint: disable=unused-argument # django_url is assigned late in the process of loading lettuce, +from logging import getLogger + # so we import this as a module, and then read django_url from # it to get the correct value import lettuce.django - -from lettuce import world, step -from .course_helpers import * -from .ui_helpers import * +from lettuce import step, world from nose.tools import assert_equals # pylint: disable=no-name-in-module - from opaque_keys.edx.locations import SlashSeparatedCourseKey -from logging import getLogger +from .course_helpers import * +from .ui_helpers import * + logger = getLogger(__name__) diff --git a/common/djangoapps/terrain/stubs/comments.py b/common/djangoapps/terrain/stubs/comments.py index 38e7efdf53..dfaf01b6c6 100644 --- a/common/djangoapps/terrain/stubs/comments.py +++ b/common/djangoapps/terrain/stubs/comments.py @@ -4,6 +4,7 @@ Stub implementation of cs_comments_service for acceptance tests import re import urlparse + from .http import StubHttpRequestHandler, StubHttpService diff --git a/common/djangoapps/terrain/stubs/ecommerce.py b/common/djangoapps/terrain/stubs/ecommerce.py index 6db67537fa..54a7fa1499 100644 --- a/common/djangoapps/terrain/stubs/ecommerce.py +++ b/common/djangoapps/terrain/stubs/ecommerce.py @@ -4,6 +4,7 @@ Stub implementation of ecommerce service for acceptance tests import re import urlparse + from .http import StubHttpRequestHandler, StubHttpService diff --git a/common/djangoapps/terrain/stubs/edxnotes.py b/common/djangoapps/terrain/stubs/edxnotes.py index 8fde3b4974..0a180ffc6e 100644 --- a/common/djangoapps/terrain/stubs/edxnotes.py +++ b/common/djangoapps/terrain/stubs/edxnotes.py @@ -4,11 +4,11 @@ Stub implementation of EdxNotes for acceptance tests import json import re -from uuid import uuid4 -from datetime import datetime from copy import deepcopy +from datetime import datetime from math import ceil from urllib import urlencode +from uuid import uuid4 from .http import StubHttpRequestHandler, StubHttpService diff --git a/common/djangoapps/terrain/stubs/http.py b/common/djangoapps/terrain/stubs/http.py index dedfa0a980..11fab8a753 100644 --- a/common/djangoapps/terrain/stubs/http.py +++ b/common/djangoapps/terrain/stubs/http.py @@ -2,16 +2,17 @@ Stub implementation of an HTTP service. """ -from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler -from SocketServer import ThreadingMixIn +import json +import threading import urllib import urlparse -import threading -import json +from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from functools import wraps +from logging import getLogger +from SocketServer import ThreadingMixIn + from lazy import lazy -from logging import getLogger LOGGER = getLogger(__name__) diff --git a/common/djangoapps/terrain/stubs/lti.py b/common/djangoapps/terrain/stubs/lti.py index 537c3dc5f2..7a545a837b 100644 --- a/common/djangoapps/terrain/stubs/lti.py +++ b/common/djangoapps/terrain/stubs/lti.py @@ -9,16 +9,17 @@ not possible to have this LTI multiple times on a single page in LMS. """ -from uuid import uuid4 +import base64 +import hashlib import textwrap import urllib -from oauthlib.oauth1.rfc5849 import signature, parameters -import oauthlib.oauth1 -import hashlib -import base64 +from uuid import uuid4 + import mock +import oauthlib.oauth1 import requests from http import StubHttpRequestHandler, StubHttpService +from oauthlib.oauth1.rfc5849 import parameters, signature class StubLtiHandler(StubHttpRequestHandler): diff --git a/common/djangoapps/terrain/stubs/start.py b/common/djangoapps/terrain/stubs/start.py index 1e02f63a96..ca8b30b466 100644 --- a/common/djangoapps/terrain/stubs/start.py +++ b/common/djangoapps/terrain/stubs/start.py @@ -1,19 +1,18 @@ """ Command-line utility to start a stub service. """ +import logging import sys import time -import logging +from .catalog import StubCatalogService from .comments import StubCommentsService from .ecommerce import StubEcommerceService -from .xqueue import StubXQueueService -from .youtube import StubYouTubeService +from .edxnotes import StubEdxNotesService from .lti import StubLtiService from .video_source import VideoSourceHttpService -from .edxnotes import StubEdxNotesService -from .catalog import StubCatalogService - +from .xqueue import StubXQueueService +from .youtube import StubYouTubeService USAGE = "USAGE: python -m stubs.start SERVICE_NAME PORT_NUM [CONFIG_KEY=CONFIG_VAL, ...]" diff --git a/common/djangoapps/terrain/stubs/video_source.py b/common/djangoapps/terrain/stubs/video_source.py index 1265ba286d..1fcda039e8 100644 --- a/common/djangoapps/terrain/stubs/video_source.py +++ b/common/djangoapps/terrain/stubs/video_source.py @@ -1,12 +1,13 @@ """ Serve HTML5 video sources for acceptance tests """ -from SimpleHTTPServer import SimpleHTTPRequestHandler -from .http import StubHttpService -from contextlib import contextmanager import os - +from contextlib import contextmanager from logging import getLogger +from SimpleHTTPServer import SimpleHTTPRequestHandler + +from .http import StubHttpService + LOGGER = getLogger(__name__) diff --git a/common/djangoapps/terrain/stubs/xqueue.py b/common/djangoapps/terrain/stubs/xqueue.py index 0f128fba65..9cf6889a47 100644 --- a/common/djangoapps/terrain/stubs/xqueue.py +++ b/common/djangoapps/terrain/stubs/xqueue.py @@ -9,12 +9,14 @@ Configuration values: If no grade response is configured, a default response will be returned. """ -from .http import StubHttpRequestHandler, StubHttpService, require_params -import json import copy -from requests import post +import json from threading import Timer +from requests import post + +from .http import StubHttpRequestHandler, StubHttpService, require_params + class StubXQueueHandler(StubHttpRequestHandler): """ diff --git a/common/djangoapps/terrain/stubs/youtube.py b/common/djangoapps/terrain/stubs/youtube.py index b6a00f8f87..df963bdaf0 100644 --- a/common/djangoapps/terrain/stubs/youtube.py +++ b/common/djangoapps/terrain/stubs/youtube.py @@ -16,12 +16,14 @@ To start this stub server on its own from Vagrant: 3.) Locally, try accessing http://localhost:8031/ and see that you get "Unused url" message inside the browser. """ -from .http import StubHttpRequestHandler, StubHttpService import json import time -import requests -from urlparse import urlparse from collections import OrderedDict +from urlparse import urlparse + +import requests + +from .http import StubHttpRequestHandler, StubHttpService class StubYouTubeHandler(StubHttpRequestHandler): diff --git a/common/djangoapps/terrain/ui_helpers.py b/common/djangoapps/terrain/ui_helpers.py index bca9f0150c..86aa39ca4b 100644 --- a/common/djangoapps/terrain/ui_helpers.py +++ b/common/djangoapps/terrain/ui_helpers.py @@ -1,27 +1,27 @@ # pylint: disable=missing-docstring -from lettuce import world - -import time import json -import re import platform +import re +import time +from textwrap import dedent +from urllib import quote_plus # django_url is assigned late in the process of loading lettuce, # so we import this as a module, and then read django_url from # it to get the correct value import lettuce.django - - -from textwrap import dedent -from urllib import quote_plus -from selenium.common.exceptions import ( - WebDriverException, TimeoutException, - StaleElementReferenceException, InvalidElementStateException) -from selenium.webdriver.support import expected_conditions as EC -from selenium.webdriver.common.by import By -from selenium.webdriver.support.ui import WebDriverWait +from lettuce import world from nose.tools import assert_true +from selenium.common.exceptions import ( + InvalidElementStateException, + StaleElementReferenceException, + TimeoutException, + WebDriverException +) +from selenium.webdriver.common.by import By +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.support.ui import WebDriverWait GLOBAL_WAIT_FOR_TIMEOUT = 60 diff --git a/common/djangoapps/third_party_auth/admin.py b/common/djangoapps/third_party_auth/admin.py index 7877e24778..b3d19095c8 100644 --- a/common/djangoapps/third_party_auth/admin.py +++ b/common/djangoapps/third_party_auth/admin.py @@ -2,23 +2,23 @@ """ Admin site configuration for third party authentication """ +from config_models.admin import ConfigurationModelAdmin, KeyedConfigurationModelAdmin from django import forms - from django.contrib import admin -from config_models.admin import ConfigurationModelAdmin, KeyedConfigurationModelAdmin +from third_party_auth.provider import Registry + from .models import ( - OAuth2ProviderConfig, - SAMLProviderConfig, - SAMLConfiguration, - SAMLProviderData, - LTIProviderConfig, - ProviderApiPermissions, _PSA_OAUTH2_BACKENDS, - _PSA_SAML_BACKENDS + _PSA_SAML_BACKENDS, + LTIProviderConfig, + OAuth2ProviderConfig, + ProviderApiPermissions, + SAMLConfiguration, + SAMLProviderConfig, + SAMLProviderData ) from .tasks import fetch_saml_metadata -from third_party_auth.provider import Registry class OAuth2ProviderConfigForm(forms.ModelForm): diff --git a/common/djangoapps/third_party_auth/api/urls.py b/common/djangoapps/third_party_auth/api/urls.py index 5908c2a7bd..39056c43e3 100644 --- a/common/djangoapps/third_party_auth/api/urls.py +++ b/common/djangoapps/third_party_auth/api/urls.py @@ -2,7 +2,7 @@ from django.conf.urls import patterns, url -from .views import UserView, UserMappingView +from .views import UserMappingView, UserView USERNAME_PATTERN = r'(?P[\w.+-]+)' PROVIDER_PATTERN = r'(?P[\w.+-]+)(?:\:(?P[\w.+-]+))?' diff --git a/common/djangoapps/third_party_auth/api/views.py b/common/djangoapps/third_party_auth/api/views.py index d508a73179..6101bddd9c 100644 --- a/common/djangoapps/third_party_auth/api/views.py +++ b/common/djangoapps/third_party_auth/api/views.py @@ -4,19 +4,18 @@ Third Party Auth REST API views from django.contrib.auth.models import User from django.db.models import Q from django.http import Http404 +from rest_framework import exceptions, status from rest_framework.generics import ListAPIView -from rest_framework_oauth.authentication import OAuth2Authentication -from social.apps.django_app.default.models import UserSocialAuth -from openedx.core.lib.api.authentication import ( - OAuth2AuthenticationAllowInactiveUser, - SessionAuthenticationAllowInactiveUser, -) -from openedx.core.lib.api.permissions import ( - ApiKeyHeaderPermission, -) -from rest_framework import status, exceptions from rest_framework.response import Response from rest_framework.views import APIView +from rest_framework_oauth.authentication import OAuth2Authentication +from social.apps.django_app.default.models import UserSocialAuth + +from openedx.core.lib.api.authentication import ( + OAuth2AuthenticationAllowInactiveUser, + SessionAuthenticationAllowInactiveUser +) +from openedx.core.lib.api.permissions import ApiKeyHeaderPermission from third_party_auth import pipeline from third_party_auth.api import serializers from third_party_auth.api.permissions import ThirdPartyAuthProviderApiPermission diff --git a/common/djangoapps/third_party_auth/decorators.py b/common/djangoapps/third_party_auth/decorators.py index 05385b11b2..74ef1f3024 100644 --- a/common/djangoapps/third_party_auth/decorators.py +++ b/common/djangoapps/third_party_auth/decorators.py @@ -3,15 +3,14 @@ Decorators that can be used to interact with third_party_auth. """ from functools import wraps -from six.moves.urllib.parse import urlencode, urlparse - from django.conf import settings +from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.utils.decorators import available_attrs -from django.core.urlresolvers import reverse -from third_party_auth.provider import Registry +from six.moves.urllib.parse import urlencode, urlparse from third_party_auth.models import LTIProviderConfig +from third_party_auth.provider import Registry def xframe_allow_whitelisted(view_func): diff --git a/common/djangoapps/third_party_auth/lti.py b/common/djangoapps/third_party_auth/lti.py index 53c4088408..8d3e8ee927 100644 --- a/common/djangoapps/third_party_auth/lti.py +++ b/common/djangoapps/third_party_auth/lti.py @@ -1,18 +1,18 @@ """ Third-party-auth module for Learning Tools Interoperability """ -import logging import calendar +import logging import time from django.contrib.auth import REDIRECT_FIELD_NAME from oauthlib.common import Request from oauthlib.oauth1.rfc5849.signature import ( - normalize_base_string_uri, - normalize_parameters, collect_parameters, construct_base_string, - sign_hmac_sha1, + normalize_base_string_uri, + normalize_parameters, + sign_hmac_sha1 ) from social.backends.base import BaseAuth from social.exceptions import AuthFailed diff --git a/common/djangoapps/third_party_auth/migrations/0001_initial.py b/common/djangoapps/third_party_auth/migrations/0001_initial.py index 9bd9f7aee1..a476ab75a5 100644 --- a/common/djangoapps/third_party_auth/migrations/0001_initial.py +++ b/common/djangoapps/third_party_auth/migrations/0001_initial.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models -import provider.utils import django.db.models.deletion +import provider.utils from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/third_party_auth/models.py b/common/djangoapps/third_party_auth/models.py index 626fd22d05..1956a91036 100644 --- a/common/djangoapps/third_party_auth/models.py +++ b/common/djangoapps/third_party_auth/models.py @@ -5,6 +5,9 @@ Models used to implement SAML SSO support in third_party_auth """ from __future__ import absolute_import +import json +import logging + from config_models.models import ConfigurationModel, cache from django.conf import settings from django.contrib.sites.models import Site @@ -12,20 +15,20 @@ from django.core.exceptions import ValidationError from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ -import json -import logging -from provider.utils import long_token from provider.oauth2.models import Client +from provider.utils import long_token from social.backends.base import BaseAuth from social.backends.oauth import OAuthAuth from social.backends.saml import SAMLAuth, SAMLIdentityProvider -from .lti import LTIAuthBackend, LTI_PARAMS_KEY -from .saml import STANDARD_SAML_PROVIDER_KEY, get_saml_idp_choices, get_saml_idp_class from social.exceptions import SocialAuthBaseException from social.utils import module_member + from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.djangoapps.theming.helpers import get_current_request +from .lti import LTI_PARAMS_KEY, LTIAuthBackend +from .saml import STANDARD_SAML_PROVIDER_KEY, get_saml_idp_choices, get_saml_idp_class + log = logging.getLogger(__name__) diff --git a/common/djangoapps/third_party_auth/pipeline.py b/common/djangoapps/third_party_auth/pipeline.py index afc58478b9..cff8442445 100644 --- a/common/djangoapps/third_party_auth/pipeline.py +++ b/common/djangoapps/third_party_auth/pipeline.py @@ -63,11 +63,11 @@ import hmac import json import random import string -from collections import OrderedDict import urllib -import analytics -from eventtracking import tracker +from collections import OrderedDict +from logging import getLogger +import analytics from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse @@ -80,12 +80,10 @@ from social.pipeline import partial from social.pipeline.social_auth import associate_by_email import student - -from logging import getLogger +from eventtracking import tracker from . import provider - # These are the query string params you can pass # to the URL that starts the authentication process. # diff --git a/common/djangoapps/third_party_auth/provider.py b/common/djangoapps/third_party_auth/provider.py index 1b3d04ac52..93f2ff0044 100644 --- a/common/djangoapps/third_party_auth/provider.py +++ b/common/djangoapps/third_party_auth/provider.py @@ -2,11 +2,17 @@ Third-party auth provider configuration API. """ from django.contrib.sites.models import Site + from openedx.core.djangoapps.theming.helpers import get_current_request from .models import ( - OAuth2ProviderConfig, SAMLConfiguration, SAMLProviderConfig, LTIProviderConfig, - _PSA_OAUTH2_BACKENDS, _PSA_SAML_BACKENDS, _LTI_BACKENDS, + _LTI_BACKENDS, + _PSA_OAUTH2_BACKENDS, + _PSA_SAML_BACKENDS, + LTIProviderConfig, + OAuth2ProviderConfig, + SAMLConfiguration, + SAMLProviderConfig ) diff --git a/common/djangoapps/third_party_auth/saml.py b/common/djangoapps/third_party_auth/saml.py index f3134803fb..123bc1cb88 100644 --- a/common/djangoapps/third_party_auth/saml.py +++ b/common/djangoapps/third_party_auth/saml.py @@ -2,14 +2,16 @@ Slightly customized python-social-auth backend for SAML 2.0 support """ import logging + +import requests from django.contrib.sites.models import Site from django.http import Http404 from django.utils.functional import cached_property -from openedx.core.djangoapps.theming.helpers import get_current_request -import requests -from social.backends.saml import SAMLAuth, SAMLIdentityProvider, OID_EDU_PERSON_ENTITLEMENT +from social.backends.saml import OID_EDU_PERSON_ENTITLEMENT, SAMLAuth, SAMLIdentityProvider from social.exceptions import AuthForbidden, AuthMissingParameter +from openedx.core.djangoapps.theming.helpers import get_current_request + STANDARD_SAML_PROVIDER_KEY = 'standard_saml_provider' SAP_SUCCESSFACTORS_SAML_KEY = 'sap_success_factors' log = logging.getLogger(__name__) diff --git a/common/djangoapps/third_party_auth/strategy.py b/common/djangoapps/third_party_auth/strategy.py index 5f67d3a6ad..df1582b946 100644 --- a/common/djangoapps/third_party_auth/strategy.py +++ b/common/djangoapps/third_party_auth/strategy.py @@ -2,12 +2,14 @@ A custom Strategy for python-social-auth that allows us to fetch configuration from ConfigurationModels rather than django.settings """ -from .models import OAuth2ProviderConfig -from .pipeline import AUTH_ENTRY_CUSTOM, get as get_pipeline_from_request -from .provider import Registry from social.backends.oauth import OAuthAuth from social.strategies.django_strategy import DjangoStrategy +from .models import OAuth2ProviderConfig +from .pipeline import get as get_pipeline_from_request +from .pipeline import AUTH_ENTRY_CUSTOM +from .provider import Registry + class ConfigurationModelStrategy(DjangoStrategy): """ diff --git a/common/djangoapps/third_party_auth/tasks.py b/common/djangoapps/third_party_auth/tasks.py index d1a138769b..b53e7f9850 100644 --- a/common/djangoapps/third_party_auth/tasks.py +++ b/common/djangoapps/third_party_auth/tasks.py @@ -3,15 +3,17 @@ Code to manage fetching and storing the metadata of IdPs. """ -from celery.task import task import datetime +import logging + import dateutil.parser import pytz -import logging -from lxml import etree import requests -from requests import exceptions +from celery.task import task +from lxml import etree from onelogin.saml2.utils import OneLogin_Saml2_Utils +from requests import exceptions + from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig, SAMLProviderData log = logging.getLogger(__name__) diff --git a/common/djangoapps/third_party_auth/tests/factories.py b/common/djangoapps/third_party_auth/tests/factories.py index c145f2296c..a6e4243be4 100644 --- a/common/djangoapps/third_party_auth/tests/factories.py +++ b/common/djangoapps/third_party_auth/tests/factories.py @@ -4,8 +4,8 @@ Provides factories for third_party_auth models. from factory import SubFactory from factory.django import DjangoModelFactory -from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory +from third_party_auth.models import SAMLConfiguration, SAMLProviderConfig class SAMLConfigurationFactory(DjangoModelFactory): diff --git a/common/djangoapps/third_party_auth/tests/test_admin.py b/common/djangoapps/third_party_auth/tests/test_admin.py index 9c3b2b3ed8..12f613b2b7 100644 --- a/common/djangoapps/third_party_auth/tests/test_admin.py +++ b/common/djangoapps/third_party_auth/tests/test_admin.py @@ -5,8 +5,8 @@ import unittest from django.conf import settings from django.contrib.admin.sites import AdminSite -from django.core.urlresolvers import reverse from django.core.files.uploadedfile import SimpleUploadedFile +from django.core.urlresolvers import reverse from django.forms import models from student.tests.factories import UserFactory diff --git a/common/djangoapps/third_party_auth/tests/test_decorators.py b/common/djangoapps/third_party_auth/tests/test_decorators.py index 40fe3bc98c..1dfa6e723d 100644 --- a/common/djangoapps/third_party_auth/tests/test_decorators.py +++ b/common/djangoapps/third_party_auth/tests/test_decorators.py @@ -1,17 +1,16 @@ """ Tests for third_party_auth decorators. """ -import ddt import json import unittest -from mock import MagicMock -from six.moves.urllib.parse import urlencode - +import ddt from django.conf import settings from django.http import HttpResponse, JsonResponse from django.test import RequestFactory +from mock import MagicMock +from six.moves.urllib.parse import urlencode from third_party_auth.decorators import tpa_hint_ends_existing_session, xframe_allow_whitelisted from third_party_auth.tests.testutil import TestCase diff --git a/common/djangoapps/third_party_auth/tests/test_lti.py b/common/djangoapps/third_party_auth/tests/test_lti.py index 9e0f9122c3..2458c7df42 100644 --- a/common/djangoapps/third_party_auth/tests/test_lti.py +++ b/common/djangoapps/third_party_auth/tests/test_lti.py @@ -3,8 +3,10 @@ Unit tests for third_party_auth LTI auth providers """ import unittest + from oauthlib.common import Request -from third_party_auth.lti import LTIAuthBackend, LTI_PARAMS_KEY + +from third_party_auth.lti import LTI_PARAMS_KEY, LTIAuthBackend from third_party_auth.tests.testutil import ThirdPartyAuthTestMixin diff --git a/common/djangoapps/third_party_auth/tests/test_pipeline.py b/common/djangoapps/third_party_auth/tests/test_pipeline.py index 79635e2210..af6421746f 100644 --- a/common/djangoapps/third_party_auth/tests/test_pipeline.py +++ b/common/djangoapps/third_party_auth/tests/test_pipeline.py @@ -1,10 +1,10 @@ """Unit tests for third_party_auth/pipeline.py.""" import random +import unittest from third_party_auth import pipeline from third_party_auth.tests import testutil -import unittest # Allow tests access to protected methods (or module-protected methods) under test. diff --git a/common/djangoapps/third_party_auth/tests/test_pipeline_integration.py b/common/djangoapps/third_party_auth/tests/test_pipeline_integration.py index c15a8a9f31..5d6efa097c 100644 --- a/common/djangoapps/third_party_auth/tests/test_pipeline_integration.py +++ b/common/djangoapps/third_party_auth/tests/test_pipeline_integration.py @@ -2,15 +2,14 @@ import unittest -from django.conf import settings -from django import test -from django.contrib.auth import models import mock +from django import test +from django.conf import settings +from django.contrib.auth import models +from social.apps.django_app.default import models as social_models from third_party_auth import pipeline, provider from third_party_auth.tests import testutil -from social.apps.django_app.default import models as social_models - # Get Django User model by reference from python-social-auth. Not a type # constant, pylint. diff --git a/common/djangoapps/third_party_auth/tests/test_provider.py b/common/djangoapps/third_party_auth/tests/test_provider.py index bab94b01ee..47c5fe2fc2 100644 --- a/common/djangoapps/third_party_auth/tests/test_provider.py +++ b/common/djangoapps/third_party_auth/tests/test_provider.py @@ -1,11 +1,13 @@ """Unit tests for provider.py.""" +import unittest + from django.contrib.sites.models import Site from mock import Mock, patch + from openedx.core.djangoapps.site_configuration.tests.test_util import with_site_configuration from third_party_auth import provider from third_party_auth.tests import testutil -import unittest SITE_DOMAIN_A = 'professionalx.example.com' SITE_DOMAIN_B = 'somethingelse.example.com' diff --git a/common/djangoapps/third_party_auth/tests/test_settings.py b/common/djangoapps/third_party_auth/tests/test_settings.py index 09c02583b5..906a4ded14 100644 --- a/common/djangoapps/third_party_auth/tests/test_settings.py +++ b/common/djangoapps/third_party_auth/tests/test_settings.py @@ -1,11 +1,10 @@ """Unit tests for settings.py.""" -from third_party_auth import provider, settings -from third_party_auth.tests import testutil import unittest from openedx.features.enterprise_support.api import enterprise_enabled - +from third_party_auth import provider, settings +from third_party_auth.tests import testutil _ORIGINAL_AUTHENTICATION_BACKENDS = ('first_authentication_backend',) _ORIGINAL_INSTALLED_APPS = ('first_installed_app',) diff --git a/common/djangoapps/third_party_auth/tests/test_views.py b/common/djangoapps/third_party_auth/tests/test_views.py index 138b170fdd..c99d9e8687 100644 --- a/common/djangoapps/third_party_auth/tests/test_views.py +++ b/common/djangoapps/third_party_auth/tests/test_views.py @@ -2,17 +2,18 @@ Test the views served by third_party_auth. """ -import ddt -from lxml import etree -from onelogin.saml2.errors import OneLogin_Saml2_Error import unittest +import ddt from django.conf import settings - -from .testutil import AUTH_FEATURE_ENABLED, SAMLTestCase +from lxml import etree +from onelogin.saml2.errors import OneLogin_Saml2_Error # Define some XML namespaces: from third_party_auth.tasks import SAML_XML_NS + +from .testutil import AUTH_FEATURE_ENABLED, SAMLTestCase + XMLDSIG_XML_NS = 'http://www.w3.org/2000/09/xmldsig#' diff --git a/common/djangoapps/third_party_auth/tests/testutil.py b/common/djangoapps/third_party_auth/tests/testutil.py index 7d79acf252..b1c11bf0fe 100644 --- a/common/djangoapps/third_party_auth/tests/testutil.py +++ b/common/djangoapps/third_party_auth/tests/testutil.py @@ -4,29 +4,28 @@ Utilities for writing third_party_auth tests. Used by Django and non-Django tests; must not have Django deps. """ +import os.path from contextlib import contextmanager + +import django.test +import mock from django.conf import settings from django.contrib.auth.models import User from django.contrib.sites.models import Site -from provider.oauth2.models import Client as OAuth2Client -from provider import constants -import django.test from mako.template import Template -import mock -import os.path +from provider import constants +from provider.oauth2.models import Client as OAuth2Client from storages.backends.overwrite import OverwriteStorage +from third_party_auth.models import cache as config_cache from third_party_auth.models import ( - OAuth2ProviderConfig, - SAMLProviderConfig, - SAMLConfiguration, LTIProviderConfig, - cache as config_cache, + OAuth2ProviderConfig, ProviderApiPermissions, + SAMLConfiguration, + SAMLProviderConfig ) - -from third_party_auth.saml import get_saml_idp_class, SAMLIdentityProvider - +from third_party_auth.saml import SAMLIdentityProvider, get_saml_idp_class AUTH_FEATURES_KEY = 'ENABLE_THIRD_PARTY_AUTH' AUTH_FEATURE_ENABLED = AUTH_FEATURES_KEY in settings.FEATURES diff --git a/common/djangoapps/third_party_auth/tests/utils.py b/common/djangoapps/third_party_auth/tests/utils.py index 81435ee6a4..2aac08b63a 100644 --- a/common/djangoapps/third_party_auth/tests/utils.py +++ b/common/djangoapps/third_party_auth/tests/utils.py @@ -6,6 +6,7 @@ from provider.constants import PUBLIC from provider.oauth2.models import Client from social.apps.django_app.default.models import UserSocialAuth from social.backends.facebook import FacebookOAuth2 + from student.tests.factories import UserFactory from .testutil import ThirdPartyAuthTestMixin diff --git a/common/djangoapps/third_party_auth/urls.py b/common/djangoapps/third_party_auth/urls.py index a85226f52b..0953e89b09 100644 --- a/common/djangoapps/third_party_auth/urls.py +++ b/common/djangoapps/third_party_auth/urls.py @@ -2,7 +2,7 @@ from django.conf.urls import include, patterns, url -from .views import inactive_user_view, saml_metadata_view, lti_login_and_complete_view, post_to_custom_auth_form +from .views import inactive_user_view, lti_login_and_complete_view, post_to_custom_auth_form, saml_metadata_view urlpatterns = patterns( '', diff --git a/common/djangoapps/third_party_auth/views.py b/common/djangoapps/third_party_auth/views.py index 1a0003f7d7..6f7e470435 100644 --- a/common/djangoapps/third_party_auth/views.py +++ b/common/djangoapps/third_party_auth/views.py @@ -1,17 +1,19 @@ """ Extra views required for SSO """ +import social from django.conf import settings from django.core.urlresolvers import reverse -from django.http import HttpResponse, HttpResponseServerError, Http404, HttpResponseNotAllowed +from django.http import Http404, HttpResponse, HttpResponseNotAllowed, HttpResponseServerError from django.shortcuts import redirect, render from django.views.decorators.csrf import csrf_exempt -import social +from social.apps.django_app.utils import load_backend, load_strategy from social.apps.django_app.views import complete -from social.apps.django_app.utils import load_strategy, load_backend from social.utils import setting_name + from student.models import UserProfile from student.views import compose_and_send_activation_email + from .models import SAMLConfiguration URL_NAMESPACE = getattr(settings, setting_name('URL_NAMESPACE'), None) or 'social' diff --git a/common/djangoapps/track/admin.py b/common/djangoapps/track/admin.py index e0835f5a8a..6aa141a3e2 100644 --- a/common/djangoapps/track/admin.py +++ b/common/djangoapps/track/admin.py @@ -2,7 +2,8 @@ django admin pages for courseware model ''' -from track.models import TrackingLog from ratelimitbackend import admin +from track.models import TrackingLog + admin.site.register(TrackingLog) diff --git a/common/djangoapps/track/backends/django.py b/common/djangoapps/track/backends/django.py index cc06e7cf36..d6eb58f63b 100644 --- a/common/djangoapps/track/backends/django.py +++ b/common/djangoapps/track/backends/django.py @@ -15,7 +15,6 @@ from django.db import models from track.backends import BaseBackend - log = logging.getLogger('track.backends.django') diff --git a/common/djangoapps/track/backends/logger.py b/common/djangoapps/track/backends/logger.py index da9b960d0f..6d212138c4 100644 --- a/common/djangoapps/track/backends/logger.py +++ b/common/djangoapps/track/backends/logger.py @@ -2,8 +2,8 @@ from __future__ import absolute_import -import logging import json +import logging from django.conf import settings diff --git a/common/djangoapps/track/backends/mongodb.py b/common/djangoapps/track/backends/mongodb.py index fb891c386b..9445311879 100644 --- a/common/djangoapps/track/backends/mongodb.py +++ b/common/djangoapps/track/backends/mongodb.py @@ -5,13 +5,12 @@ from __future__ import absolute_import import logging import pymongo +from bson.errors import BSONError from pymongo import MongoClient from pymongo.errors import PyMongoError -from bson.errors import BSONError from track.backends import BaseBackend - log = logging.getLogger(__name__) diff --git a/common/djangoapps/track/contexts.py b/common/djangoapps/track/contexts.py index 1f7c94c26e..f4656ff42a 100644 --- a/common/djangoapps/track/contexts.py +++ b/common/djangoapps/track/contexts.py @@ -1,9 +1,10 @@ """Generates common contexts""" import logging -from opaque_keys.edx.locations import SlashSeparatedCourseKey -from opaque_keys.edx.keys import CourseKey from opaque_keys import InvalidKeyError +from opaque_keys.edx.keys import CourseKey +from opaque_keys.edx.locations import SlashSeparatedCourseKey + from util.request import COURSE_REGEX log = logging.getLogger(__name__) diff --git a/common/djangoapps/track/event_transaction_utils.py b/common/djangoapps/track/event_transaction_utils.py index fae9815b6a..c81dde824c 100644 --- a/common/djangoapps/track/event_transaction_utils.py +++ b/common/djangoapps/track/event_transaction_utils.py @@ -2,7 +2,8 @@ Helper functions to access and update the id and type used in event tracking. """ -from uuid import uuid4, UUID +from uuid import UUID, uuid4 + from request_cache import get_cache diff --git a/common/djangoapps/track/middleware.py b/common/djangoapps/track/middleware.py index d08f8df2c8..99a1c0e975 100644 --- a/common/djangoapps/track/middleware.py +++ b/common/djangoapps/track/middleware.py @@ -16,10 +16,8 @@ import sys from django.conf import settings from ipware.ip import get_ip -from track import views -from track import contexts from eventtracking import tracker - +from track import contexts, views log = logging.getLogger(__name__) diff --git a/common/djangoapps/track/shim.py b/common/djangoapps/track/shim.py index 76e4a40a93..5773539f94 100644 --- a/common/djangoapps/track/shim.py +++ b/common/djangoapps/track/shim.py @@ -4,7 +4,6 @@ import json from .transformers import EventTransformerRegistry - CONTEXT_FIELDS_TO_INCLUDE = [ 'username', 'session', diff --git a/common/djangoapps/track/tests/test_contexts.py b/common/djangoapps/track/tests/test_contexts.py index e3cc91759e..503ee88b77 100644 --- a/common/djangoapps/track/tests/test_contexts.py +++ b/common/djangoapps/track/tests/test_contexts.py @@ -1,8 +1,9 @@ # pylint: disable=missing-docstring -import ddt from unittest import TestCase +import ddt + from track import contexts diff --git a/common/djangoapps/track/tests/test_logs.py b/common/djangoapps/track/tests/test_logs.py index 484af73d53..3b66a45329 100644 --- a/common/djangoapps/track/tests/test_logs.py +++ b/common/djangoapps/track/tests/test_logs.py @@ -1,10 +1,11 @@ """Tests that tracking data are successfully logged""" -import mock import unittest -from django.test import TestCase -from django.core.urlresolvers import reverse +import mock from django.conf import settings +from django.core.urlresolvers import reverse +from django.test import TestCase + from track.models import TrackingLog from track.views import user_track diff --git a/common/djangoapps/track/tests/test_middleware.py b/common/djangoapps/track/tests/test_middleware.py index 1609b96357..c56b426b60 100644 --- a/common/djangoapps/track/tests/test_middleware.py +++ b/common/djangoapps/track/tests/test_middleware.py @@ -1,14 +1,12 @@ # -*- coding: utf-8 -*- """Tests for tracking middleware.""" import ddt -from mock import patch -from mock import sentinel - from django.contrib.auth.models import User from django.contrib.sessions.middleware import SessionMiddleware from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings +from mock import patch, sentinel from eventtracking import tracker from track.middleware import TrackMiddleware diff --git a/common/djangoapps/track/tests/test_shim.py b/common/djangoapps/track/tests/test_shim.py index 039a0d6cbd..c5f975663a 100644 --- a/common/djangoapps/track/tests/test_shim.py +++ b/common/djangoapps/track/tests/test_shim.py @@ -3,15 +3,14 @@ from collections import namedtuple import ddt -from mock import sentinel from django.test.utils import override_settings +from mock import sentinel from openedx.core.lib.tests.assertions.events import assert_events_equal -from . import EventTrackingTestCase, FROZEN_TIME -from ..shim import PrefixedEventProcessor +from . import FROZEN_TIME, EventTrackingTestCase from .. import transformers - +from ..shim import PrefixedEventProcessor LEGACY_SHIM_PROCESSOR = [ { diff --git a/common/djangoapps/track/tests/test_tracker.py b/common/djangoapps/track/tests/test_tracker.py index 4914503d16..9b3fc76440 100644 --- a/common/djangoapps/track/tests/test_tracker.py +++ b/common/djangoapps/track/tests/test_tracker.py @@ -5,7 +5,6 @@ from django.test.utils import override_settings import track.tracker as tracker from track.backends import BaseBackend - SIMPLE_SETTINGS = { 'default': { 'ENGINE': 'track.tests.test_tracker.DummyBackend', diff --git a/common/djangoapps/track/tests/test_util.py b/common/djangoapps/track/tests/test_util.py index 123dbfbfb0..865c1a4d06 100644 --- a/common/djangoapps/track/tests/test_util.py +++ b/common/djangoapps/track/tests/test_util.py @@ -1,9 +1,8 @@ -from datetime import datetime import json - -from pytz import UTC +from datetime import datetime from django.test import TestCase +from pytz import UTC from track.utils import DateTimeJSONEncoder diff --git a/common/djangoapps/track/tracker.py b/common/djangoapps/track/tracker.py index 0014d98eef..10bf71bbb1 100644 --- a/common/djangoapps/track/tracker.py +++ b/common/djangoapps/track/tracker.py @@ -21,13 +21,11 @@ below:: import inspect from importlib import import_module +from django.conf import settings from dogapi import dog_stats_api -from django.conf import settings - from track.backends import BaseBackend - __all__ = ['send'] diff --git a/common/djangoapps/track/utils.py b/common/djangoapps/track/utils.py index cec62d3bff..9a20fe249e 100644 --- a/common/djangoapps/track/utils.py +++ b/common/djangoapps/track/utils.py @@ -1,7 +1,7 @@ """Utility functions and classes for track backends""" import json -from datetime import datetime, date +from datetime import date, datetime from pytz import UTC diff --git a/common/djangoapps/track/views/segmentio.py b/common/djangoapps/track/views/segmentio.py index 9a4847085c..3d6cb92500 100644 --- a/common/djangoapps/track/views/segmentio.py +++ b/common/djangoapps/track/views/segmentio.py @@ -7,12 +7,12 @@ import logging from django.conf import settings from django.contrib.auth.models import User from django.http import HttpResponse -from django.views.decorators.http import require_POST from django.views.decorators.csrf import csrf_exempt +from django.views.decorators.http import require_POST +from opaque_keys import InvalidKeyError +from opaque_keys.edx.keys import CourseKey from eventtracking import tracker -from opaque_keys.edx.keys import CourseKey -from opaque_keys import InvalidKeyError from util.json_request import expect_json log = logging.getLogger(__name__) diff --git a/common/djangoapps/util/admin.py b/common/djangoapps/util/admin.py index de82409cc3..c8da7cf4d6 100644 --- a/common/djangoapps/util/admin.py +++ b/common/djangoapps/util/admin.py @@ -1,7 +1,7 @@ """Admin interface for the util app. """ from ratelimitbackend import admin + from util.models import RateLimitConfiguration - admin.site.register(RateLimitConfiguration) diff --git a/common/djangoapps/util/cache.py b/common/djangoapps/util/cache.py index 5b912ec3e4..b9737765ff 100644 --- a/common/djangoapps/util/cache.py +++ b/common/djangoapps/util/cache.py @@ -10,8 +10,6 @@ from functools import wraps from django.conf import settings from django.core import cache - - # If we can't find a 'general' CACHE defined in settings.py, we simply fall back # to returning the default cache. This will happen with dev machines. from django.utils.translation import get_language diff --git a/common/djangoapps/util/date_utils.py b/common/djangoapps/util/date_utils.py index 5772238289..3d9ff08674 100644 --- a/common/djangoapps/util/date_utils.py +++ b/common/djangoapps/util/date_utils.py @@ -2,11 +2,11 @@ Convenience methods for working with datetime objects """ -from datetime import datetime, timedelta import re +from datetime import datetime, timedelta from django.utils.translation import pgettext, ugettext -from pytz import timezone, utc, UnknownTimeZoneError +from pytz import UnknownTimeZoneError, timezone, utc def get_default_time_display(dtime): diff --git a/common/djangoapps/util/db.py b/common/djangoapps/util/db.py index cd01235ba5..340a50a5c4 100644 --- a/common/djangoapps/util/db.py +++ b/common/djangoapps/util/db.py @@ -1,15 +1,15 @@ """ Utility functions related to databases. """ +import random # TransactionManagementError used below actually *does* derive from the standard "Exception" class. # pylint: disable=nonstandard-exception from contextlib import contextmanager from functools import wraps -import random from django.db import DEFAULT_DB_ALIAS, DatabaseError, Error, transaction -import request_cache +import request_cache OUTER_ATOMIC_CACHE_NAME = 'db.outer_atomic' diff --git a/common/djangoapps/util/disable_rate_limit.py b/common/djangoapps/util/disable_rate_limit.py index a342953d88..c160d03a1e 100644 --- a/common/djangoapps/util/disable_rate_limit.py +++ b/common/djangoapps/util/disable_rate_limit.py @@ -13,11 +13,12 @@ To disable rate limiting: Note: You should NEVER disable rate limiting in production. """ -from functools import wraps import logging -from rest_framework.views import APIView -from util.models import RateLimitConfiguration +from functools import wraps +from rest_framework.views import APIView + +from util.models import RateLimitConfiguration LOGGER = logging.getLogger(__name__) diff --git a/common/djangoapps/util/file.py b/common/djangoapps/util/file.py index 46b2663c35..c0af52ab9a 100644 --- a/common/djangoapps/util/file.py +++ b/common/djangoapps/util/file.py @@ -2,14 +2,14 @@ Utility methods related to file handling. """ -from datetime import datetime import os -from pytz import UTC +from datetime import datetime from django.core.exceptions import PermissionDenied from django.core.files.storage import DefaultStorage, get_valid_filename from django.utils.translation import ugettext as _ from django.utils.translation import ungettext +from pytz import UTC class FileValidationException(Exception): diff --git a/common/djangoapps/util/json_request.py b/common/djangoapps/util/json_request.py index 593723c37d..6086cd065d 100644 --- a/common/djangoapps/util/json_request.py +++ b/common/djangoapps/util/json_request.py @@ -1,6 +1,7 @@ -from functools import wraps -import json import decimal +import json +from functools import wraps + from django.core.serializers import serialize from django.core.serializers.json import DjangoJSONEncoder from django.db.models.query import QuerySet diff --git a/common/djangoapps/util/keyword_substitution.py b/common/djangoapps/util/keyword_substitution.py index c7156e54b2..9c3d4c0aff 100644 --- a/common/djangoapps/util/keyword_substitution.py +++ b/common/djangoapps/util/keyword_substitution.py @@ -19,6 +19,7 @@ Usage: """ from django.contrib.auth.models import User + from student.models import anonymous_id_for_user diff --git a/common/djangoapps/util/memcache.py b/common/djangoapps/util/memcache.py index ee450e68cb..683a124e97 100644 --- a/common/djangoapps/util/memcache.py +++ b/common/djangoapps/util/memcache.py @@ -2,10 +2,11 @@ This module provides a KEY_FUNCTION suitable for use with a memcache backend so that we can cache any keys, not just ones that memcache would ordinarily accept """ -from django.utils.encoding import smart_str import hashlib import urllib +from django.utils.encoding import smart_str + def fasthash(string): """ diff --git a/common/djangoapps/util/migrations/0001_initial.py b/common/djangoapps/util/migrations/0001_initial.py index 6880b5da35..bce61dccd2 100644 --- a/common/djangoapps/util/migrations/0001_initial.py +++ b/common/djangoapps/util/migrations/0001_initial.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/util/migrations/0002_data__default_rate_limit_config.py b/common/djangoapps/util/migrations/0002_data__default_rate_limit_config.py index cda9c543d6..cb343e1095 100644 --- a/common/djangoapps/util/migrations/0002_data__default_rate_limit_config.py +++ b/common/djangoapps/util/migrations/0002_data__default_rate_limit_config.py @@ -1,9 +1,11 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals +from django.db import migrations, models + + # Converted from the original South migration 0002_default_rate_limit_config.py -from django.db import migrations, models def forwards(apps, schema_editor): diff --git a/common/djangoapps/util/milestones_helpers.py b/common/djangoapps/util/milestones_helpers.py index 41b7047958..bbe54b3dcf 100644 --- a/common/djangoapps/util/milestones_helpers.py +++ b/common/djangoapps/util/milestones_helpers.py @@ -4,17 +4,16 @@ Utility library for working with the edx-milestones app """ from django.conf import settings from django.utils.translation import ugettext as _ - -from opaque_keys import InvalidKeyError -from opaque_keys.edx.keys import CourseKey - from milestones import api as milestones_api from milestones.exceptions import InvalidMilestoneRelationshipTypeException from milestones.models import MilestoneRelationshipType from milestones.services import MilestonesService +from opaque_keys import InvalidKeyError +from opaque_keys.edx.keys import CourseKey + +import request_cache from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from xmodule.modulestore.django import modulestore -import request_cache NAMESPACE_CHOICES = { 'ENTRANCE_EXAM': 'entrance_exams' diff --git a/common/djangoapps/util/model_utils.py b/common/djangoapps/util/model_utils.py index 06cbfac85e..5aec1bada0 100644 --- a/common/djangoapps/util/model_utils.py +++ b/common/djangoapps/util/model_utils.py @@ -1,18 +1,17 @@ """ Utilities for django models. """ -import unicodedata import re - -from eventtracking import tracker +import unicodedata from django.conf import settings +from django.dispatch import Signal from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe -from django.dispatch import Signal - from django_countries.fields import Country +from eventtracking import tracker + # The setting name used for events when "settings" (account settings, preferences, profile information) change. USER_SETTINGS_CHANGED_EVENT_NAME = u'edx.user.settings.changed' # Used to signal a field value change diff --git a/common/djangoapps/util/models.py b/common/djangoapps/util/models.py index 9cfe1c5fbd..65a10e2a6d 100644 --- a/common/djangoapps/util/models.py +++ b/common/djangoapps/util/models.py @@ -3,11 +3,10 @@ import cStringIO import gzip import logging +from config_models.models import ConfigurationModel from django.db import models from django.utils.text import compress_string -from config_models.models import ConfigurationModel - logger = logging.getLogger(__name__) # pylint: disable=invalid-name diff --git a/common/djangoapps/util/password_policy_validators.py b/common/djangoapps/util/password_policy_validators.py index a268e635e8..a0d7ee0be9 100644 --- a/common/djangoapps/util/password_policy_validators.py +++ b/common/djangoapps/util/password_policy_validators.py @@ -6,13 +6,13 @@ This file was inspired by the django-passwords project at https://github.com/dst authored by dstufft (https://github.com/dstufft) """ from __future__ import division + import string +import nltk +from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ -from django.conf import settings - -import nltk def validate_password_strength(value): diff --git a/common/djangoapps/util/request.py b/common/djangoapps/util/request.py index 63befd8be9..3576cdfeec 100644 --- a/common/djangoapps/util/request.py +++ b/common/djangoapps/util/request.py @@ -2,9 +2,9 @@ import re from django.conf import settings - from opaque_keys import InvalidKeyError from opaque_keys.edx.locations import SlashSeparatedCourseKey + from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers # accommodates course api urls, excluding any course api routes that do not fall under v*/courses, such as v1/blocks. diff --git a/common/djangoapps/util/sandboxing.py b/common/djangoapps/util/sandboxing.py index 8fcfa6dfbc..0c47cf2471 100644 --- a/common/djangoapps/util/sandboxing.py +++ b/common/djangoapps/util/sandboxing.py @@ -1,4 +1,5 @@ import re + from django.conf import settings # We'll make assets named this be importable by Python code in the sandbox. diff --git a/common/djangoapps/util/testing.py b/common/djangoapps/util/testing.py index 4b1556ff6e..4e242805c2 100644 --- a/common/djangoapps/util/testing.py +++ b/common/djangoapps/util/testing.py @@ -5,13 +5,12 @@ Utility Mixins for unit tests import json import sys -from mock import patch - from django.conf import settings from django.core.urlresolvers import clear_url_caches, resolve from django.test import TestCase +from mock import patch -from util.db import OuterAtomic, CommitOnSuccessManager +from util.db import CommitOnSuccessManager, OuterAtomic class UrlResetMixin(object): diff --git a/common/djangoapps/util/tests/test_course.py b/common/djangoapps/util/tests/test_course.py index dacdd15b02..ddc2b9ebb7 100644 --- a/common/djangoapps/util/tests/test_course.py +++ b/common/djangoapps/util/tests/test_course.py @@ -3,16 +3,14 @@ Tests for course utils. """ import ddt import mock - from django.conf import settings from openedx.core.djangoapps.content.course_overviews.models import CourseOverview +from util.course import get_link_for_about_page from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory -from util.course import get_link_for_about_page - @ddt.ddt class TestCourseSharingLinks(ModuleStoreTestCase): diff --git a/common/djangoapps/util/tests/test_date_utils.py b/common/djangoapps/util/tests/test_date_utils.py index a2222813cb..c7bfceb8d2 100644 --- a/common/djangoapps/util/tests/test_date_utils.py +++ b/common/djangoapps/util/tests/test_date_utils.py @@ -3,17 +3,15 @@ Tests for util.date_utils """ -from datetime import datetime, timedelta, tzinfo import unittest +from datetime import datetime, timedelta, tzinfo import ddt from mock import patch from nose.tools import assert_equals, assert_false # pylint: disable=no-name-in-module from pytz import utc -from util.date_utils import ( - get_default_time_display, get_time_display, almost_same_datetime, - strftime_localized, -) + +from util.date_utils import almost_same_datetime, get_default_time_display, get_time_display, strftime_localized def test_get_default_time_display(): diff --git a/common/djangoapps/util/tests/test_db.py b/common/djangoapps/util/tests/test_db.py index 0b9bb3774a..d6529ca26f 100644 --- a/common/djangoapps/util/tests/test_db.py +++ b/common/djangoapps/util/tests/test_db.py @@ -1,20 +1,18 @@ """Tests for util.db module.""" -import ddt import threading import time import unittest +import ddt from django.contrib.auth.models import User from django.core.management import call_command -from django.db import connection, IntegrityError -from django.db.transaction import atomic, TransactionManagementError +from django.db import IntegrityError, connection +from django.db.transaction import TransactionManagementError, atomic from django.test import TestCase, TransactionTestCase from django.test.utils import override_settings -from util.db import ( - commit_on_success, enable_named_outer_atomic, outer_atomic, generate_int_id, NoOpMigrationModules -) +from util.db import NoOpMigrationModules, commit_on_success, enable_named_outer_atomic, generate_int_id, outer_atomic def do_nothing(): diff --git a/common/djangoapps/util/tests/test_disable_rate_limit.py b/common/djangoapps/util/tests/test_disable_rate_limit.py index 1582f131f4..4e0dbabe4a 100644 --- a/common/djangoapps/util/tests/test_disable_rate_limit.py +++ b/common/djangoapps/util/tests/test_disable_rate_limit.py @@ -1,13 +1,13 @@ """Tests for disabling rate limiting. """ import unittest -from django.test import TestCase -from django.core.cache import cache -from django.conf import settings -import mock -from rest_framework.views import APIView -from rest_framework.throttling import BaseThrottle +import mock +from django.conf import settings +from django.core.cache import cache +from django.test import TestCase from rest_framework.exceptions import Throttled +from rest_framework.throttling import BaseThrottle +from rest_framework.views import APIView from util.disable_rate_limit import can_disable_rate_limit from util.models import RateLimitConfiguration diff --git a/common/djangoapps/util/tests/test_file.py b/common/djangoapps/util/tests/test_file.py index afb11c19dd..d49c5dd257 100644 --- a/common/djangoapps/util/tests/test_file.py +++ b/common/djangoapps/util/tests/test_file.py @@ -2,26 +2,27 @@ """ Tests for file.py """ -import ddt +import os +from datetime import datetime from io import StringIO -from django.test import TestCase -from datetime import datetime -from django.utils.timezone import UTC -from mock import patch, Mock -from django.http import HttpRequest +import ddt +from django.core import exceptions from django.core.files.uploadedfile import SimpleUploadedFile +from django.http import HttpRequest +from django.test import TestCase +from django.utils.timezone import UTC +from mock import Mock, patch +from opaque_keys.edx.locations import CourseLocator, SlashSeparatedCourseKey + import util.file from util.file import ( + FileValidationException, + UniversalNewlineIterator, course_and_time_based_filename_generator, course_filename_prefix_generator, - store_uploaded_file, - FileValidationException, - UniversalNewlineIterator + store_uploaded_file ) -from opaque_keys.edx.locations import CourseLocator, SlashSeparatedCourseKey -from django.core import exceptions -import os @ddt.ddt diff --git a/common/djangoapps/util/tests/test_json_request.py b/common/djangoapps/util/tests/test_json_request.py index f65d7ca6b2..a7983c2f6f 100644 --- a/common/djangoapps/util/tests/test_json_request.py +++ b/common/djangoapps/util/tests/test_json_request.py @@ -2,11 +2,13 @@ Test for JsonResponse and JsonResponseBadRequest util classes. """ -from django.http import HttpResponse, HttpResponseBadRequest -from util.json_request import JsonResponse, JsonResponseBadRequest import json import unittest + import mock +from django.http import HttpResponse, HttpResponseBadRequest + +from util.json_request import JsonResponse, JsonResponseBadRequest class JsonResponseTestCase(unittest.TestCase): diff --git a/common/djangoapps/util/tests/test_keyword_sub_utils.py b/common/djangoapps/util/tests/test_keyword_sub_utils.py index 978aa794b0..0bd97c939c 100644 --- a/common/djangoapps/util/tests/test_keyword_sub_utils.py +++ b/common/djangoapps/util/tests/test_keyword_sub_utils.py @@ -2,15 +2,14 @@ Tests for keyword_substitution.py """ -from student.tests.factories import UserFactory -from xmodule.modulestore.tests.factories import CourseFactory -from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from ddt import ddt, file_data from mock import patch - -from util.date_utils import get_default_time_display +from student.tests.factories import UserFactory from util import keyword_substitution as Ks +from util.date_utils import get_default_time_display +from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory @ddt diff --git a/common/djangoapps/util/tests/test_memcache.py b/common/djangoapps/util/tests/test_memcache.py index 939765e3a4..d9dcd26222 100644 --- a/common/djangoapps/util/tests/test_memcache.py +++ b/common/djangoapps/util/tests/test_memcache.py @@ -2,8 +2,9 @@ Tests for memcache in util app """ -from django.test import TestCase from django.core.cache import caches +from django.test import TestCase + from util.memcache import safe_key diff --git a/common/djangoapps/util/tests/test_milestones_helpers.py b/common/djangoapps/util/tests/test_milestones_helpers.py index c614e2d9a1..63263ef810 100644 --- a/common/djangoapps/util/tests/test_milestones_helpers.py +++ b/common/djangoapps/util/tests/test_milestones_helpers.py @@ -3,9 +3,9 @@ Tests for the milestones helpers library, which is the integration point for the """ import ddt +from milestones.exceptions import InvalidCourseKeyException, InvalidUserException from mock import patch -from milestones.exceptions import InvalidCourseKeyException, InvalidUserException from util import milestones_helpers from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory diff --git a/common/djangoapps/util/tests/test_request.py b/common/djangoapps/util/tests/test_request.py index 79e0e78f25..4b5a129dbf 100644 --- a/common/djangoapps/util/tests/test_request.py +++ b/common/djangoapps/util/tests/test_request.py @@ -5,6 +5,7 @@ import unittest from django.conf import settings from django.core.exceptions import SuspiciousOperation from django.test.client import RequestFactory + from util.request import course_id_from_url, safe_get_host diff --git a/common/djangoapps/util/tests/test_sandboxing.py b/common/djangoapps/util/tests/test_sandboxing.py index 21179b1dfa..2b944a25a4 100644 --- a/common/djangoapps/util/tests/test_sandboxing.py +++ b/common/djangoapps/util/tests/test_sandboxing.py @@ -3,10 +3,11 @@ Tests for sandboxing.py in util app """ from django.test import TestCase -from opaque_keys.edx.locator import LibraryLocator -from util.sandboxing import can_execute_unsafe_code from django.test.utils import override_settings from opaque_keys.edx.locations import SlashSeparatedCourseKey +from opaque_keys.edx.locator import LibraryLocator + +from util.sandboxing import can_execute_unsafe_code class SandboxingTest(TestCase): diff --git a/common/djangoapps/util/tests/test_string_utils.py b/common/djangoapps/util/tests/test_string_utils.py index 84cbf1e469..949b6c9ee9 100644 --- a/common/djangoapps/util/tests/test_string_utils.py +++ b/common/djangoapps/util/tests/test_string_utils.py @@ -3,6 +3,7 @@ Tests for string_utils.py """ from django.test import TestCase + from util.string_utils import str_to_bool diff --git a/common/djangoapps/util/tests/test_submit_feedback.py b/common/djangoapps/util/tests/test_submit_feedback.py index e43dc04684..8323f10c49 100644 --- a/common/djangoapps/util/tests/test_submit_feedback.py +++ b/common/djangoapps/util/tests/test_submit_feedback.py @@ -1,23 +1,23 @@ """Tests for the Zendesk""" +import json +from smtplib import SMTPException + +import httpretty +import mock +from ddt import data, ddt, unpack from django.contrib.auth.models import AnonymousUser from django.http import Http404 from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings -from smtplib import SMTPException -from student.tests.factories import UserFactory +from zendesk import ZendeskError + from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseServiceMockMixin -from util import views -from zendesk import ZendeskError -import httpretty -import json -import mock -from ddt import ddt, data, unpack - +from student.tests.factories import CourseEnrollmentFactory, UserFactory from student.tests.test_configuration_overrides import fake_get_value -from student.tests.factories import CourseEnrollmentFactory +from util import views TEST_SUPPORT_EMAIL = "support@example.com" TEST_ZENDESK_CUSTOM_FIELD_CONFIG = { diff --git a/common/djangoapps/util/url.py b/common/djangoapps/util/url.py index ffe20e4885..38d6f35012 100644 --- a/common/djangoapps/util/url.py +++ b/common/djangoapps/util/url.py @@ -3,9 +3,10 @@ Utility functions related to urls. """ import sys +from importlib import import_module + from django.conf import settings from django.core.urlresolvers import set_urlconf -from importlib import import_module def reload_django_url_config(): diff --git a/common/djangoapps/util/views.py b/common/djangoapps/util/views.py index 6bf13364f0..8b9166ccfe 100644 --- a/common/djangoapps/util/views.py +++ b/common/djangoapps/util/views.py @@ -1,32 +1,29 @@ import json import logging -from smtplib import SMTPException import sys from functools import wraps +from smtplib import SMTPException +import zendesk from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.cache import caches from django.core.mail import send_mail from django.core.validators import ValidationError, validate_email +from django.http import Http404, HttpResponse, HttpResponseForbidden, HttpResponseNotAllowed, HttpResponseServerError from django.views.decorators.csrf import requires_csrf_token from django.views.defaults import server_error -from django.http import (Http404, HttpResponse, HttpResponseNotAllowed, - HttpResponseServerError, HttpResponseForbidden) -import dogstats_wrapper as dog_stats_api -import zendesk -import calc - from opaque_keys import InvalidKeyError - from opaque_keys.edx.keys import CourseKey, UsageKey +import calc +import dogstats_wrapper as dog_stats_api +import track.views from edxmako.shortcuts import render_to_response, render_to_string from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.features.enterprise_support import api as enterprise_api -import track.views -from student.roles import GlobalStaff from student.models import CourseEnrollment +from student.roles import GlobalStaff log = logging.getLogger(__name__) diff --git a/common/djangoapps/xblock_django/admin.py b/common/djangoapps/xblock_django/admin.py index 0c36384c89..ec7246181d 100644 --- a/common/djangoapps/xblock_django/admin.py +++ b/common/djangoapps/xblock_django/admin.py @@ -2,13 +2,12 @@ Django admin dashboard configuration. """ -from django.contrib import admin from config_models.admin import ConfigurationModelAdmin, KeyedConfigurationModelAdmin -from xblock_django.models import ( - XBlockConfiguration, XBlockStudioConfiguration, XBlockStudioConfigurationFlag -) +from django.contrib import admin from django.utils.translation import ugettext_lazy as _ +from xblock_django.models import XBlockConfiguration, XBlockStudioConfiguration, XBlockStudioConfigurationFlag + class XBlockConfigurationAdmin(KeyedConfigurationModelAdmin): """ diff --git a/common/djangoapps/xblock_django/migrations/0001_initial.py b/common/djangoapps/xblock_django/migrations/0001_initial.py index 21231c122a..a12132d0cb 100644 --- a/common/djangoapps/xblock_django/migrations/0001_initial.py +++ b/common/djangoapps/xblock_django/migrations/0001_initial.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/xblock_django/migrations/0003_add_new_config_models.py b/common/djangoapps/xblock_django/migrations/0003_add_new_config_models.py index ea619e5861..44a7c53294 100644 --- a/common/djangoapps/xblock_django/migrations/0003_add_new_config_models.py +++ b/common/djangoapps/xblock_django/migrations/0003_add_new_config_models.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals -from django.db import migrations, models import django.db.models.deletion from django.conf import settings +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/common/djangoapps/xblock_django/models.py b/common/djangoapps/xblock_django/models.py index d0f578a6e6..78ac02ca0f 100644 --- a/common/djangoapps/xblock_django/models.py +++ b/common/djangoapps/xblock_django/models.py @@ -2,11 +2,10 @@ Models. """ +from config_models.models import ConfigurationModel from django.db import models from django.utils.translation import ugettext_lazy as _ -from config_models.models import ConfigurationModel - class XBlockConfiguration(ConfigurationModel): """ diff --git a/common/djangoapps/xblock_django/tests/test_api.py b/common/djangoapps/xblock_django/tests/test_api.py index 2778bab620..d71345b716 100644 --- a/common/djangoapps/xblock_django/tests/test_api.py +++ b/common/djangoapps/xblock_django/tests/test_api.py @@ -1,9 +1,9 @@ """ Tests related to XBlock support API. """ -from xblock_django.models import XBlockConfiguration, XBlockStudioConfiguration, XBlockStudioConfigurationFlag -from xblock_django.api import deprecated_xblocks, disabled_xblocks, authorable_xblocks from openedx.core.djangolib.testing.utils import CacheIsolationTestCase +from xblock_django.api import authorable_xblocks, deprecated_xblocks, disabled_xblocks +from xblock_django.models import XBlockConfiguration, XBlockStudioConfiguration, XBlockStudioConfigurationFlag class XBlockSupportTestCase(CacheIsolationTestCase): diff --git a/common/djangoapps/xblock_django/tests/test_user_service.py b/common/djangoapps/xblock_django/tests/test_user_service.py index 1783bd274f..43fe824bb2 100644 --- a/common/djangoapps/xblock_django/tests/test_user_service.py +++ b/common/djangoapps/xblock_django/tests/test_user_service.py @@ -2,19 +2,20 @@ Tests for the DjangoXBlockUserService. """ from django.test import TestCase +from opaque_keys.edx.keys import CourseKey + +from openedx.core.djangoapps.user_api.preferences.api import set_user_preference +from student.models import anonymous_id_for_user +from student.tests.factories import AnonymousUserFactory, UserFactory from xblock_django.user_service import ( - DjangoXBlockUserService, ATTR_KEY_IS_AUTHENTICATED, ATTR_KEY_USER_ID, - ATTR_KEY_USERNAME, ATTR_KEY_USER_IS_STAFF, ATTR_KEY_USER_PREFERENCES, + ATTR_KEY_USERNAME, USER_PREFERENCES_WHITE_LIST, + DjangoXBlockUserService ) -from student.models import anonymous_id_for_user -from student.tests.factories import UserFactory, AnonymousUserFactory -from opaque_keys.edx.keys import CourseKey -from openedx.core.djangoapps.user_api.preferences.api import set_user_preference class UserServiceTestCase(TestCase): diff --git a/common/djangoapps/xblock_django/user_service.py b/common/djangoapps/xblock_django/user_service.py index 3816c29690..0b6b60ea81 100644 --- a/common/djangoapps/xblock_django/user_service.py +++ b/common/djangoapps/xblock_django/user_service.py @@ -3,9 +3,10 @@ Support for converting a django user to an XBlock user """ from django.contrib.auth.models import User from opaque_keys.edx.keys import CourseKey +from xblock.reference.user_service import UserService, XBlockUser + from openedx.core.djangoapps.user_api.preferences.api import get_user_preferences from student.models import anonymous_id_for_user, get_user_by_username_or_email -from xblock.reference.user_service import XBlockUser, UserService ATTR_KEY_IS_AUTHENTICATED = 'edx-platform.is_authenticated' ATTR_KEY_USER_ID = 'edx-platform.user_id' diff --git a/common/lib/calc/calc/calc.py b/common/lib/calc/calc/calc.py index 7d50c8e38e..611b84ce44 100644 --- a/common/lib/calc/calc/calc.py +++ b/common/lib/calc/calc/calc.py @@ -5,17 +5,31 @@ Uses pyparsing to parse. Main function as of now is evaluator(). """ import math -import operator import numbers +import operator + import numpy import scipy.constants -import functions - from pyparsing import ( - Word, Literal, CaselessLiteral, ZeroOrMore, MatchFirst, Optional, Forward, - Group, ParseResults, stringEnd, Suppress, Combine, alphas, nums, alphanums + CaselessLiteral, + Combine, + Forward, + Group, + Literal, + MatchFirst, + Optional, + ParseResults, + Suppress, + Word, + ZeroOrMore, + alphanums, + alphas, + nums, + stringEnd ) +import functions + DEFAULT_FUNCTIONS = { 'sin': numpy.sin, 'cos': numpy.cos, diff --git a/common/lib/calc/calc/preview.py b/common/lib/calc/calc/preview.py index 075a134303..d11d611de9 100644 --- a/common/lib/calc/calc/preview.py +++ b/common/lib/calc/calc/preview.py @@ -8,7 +8,7 @@ Because intermediate values of the render contain more data than simply the string of latex, store it in a custom class `LatexRendered`. """ -from calc import ParseAugmenter, DEFAULT_VARIABLES, DEFAULT_FUNCTIONS, SUFFIXES +from calc import DEFAULT_FUNCTIONS, DEFAULT_VARIABLES, SUFFIXES, ParseAugmenter class LatexRendered(object): diff --git a/common/lib/capa/capa/capa_problem.py b/common/lib/capa/capa/capa_problem.py index 1f44f79260..fa8bfc4158 100644 --- a/common/lib/capa/capa/capa_problem.py +++ b/common/lib/capa/capa/capa_problem.py @@ -13,28 +13,27 @@ Main module which shows problems (of "capa" type). This is used by capa_module. """ -from collections import OrderedDict -from copy import deepcopy -from datetime import datetime import logging import os.path import re +from collections import OrderedDict +from copy import deepcopy +from datetime import datetime +from xml.sax.saxutils import unescape from lxml import etree from pytz import UTC -from xml.sax.saxutils import unescape -from capa.correctmap import CorrectMap -import capa.inputtypes as inputtypes import capa.customrender as customrender +import capa.inputtypes as inputtypes import capa.responsetypes as responsetypes -from capa.util import contextualize_text, convert_files_to_filenames import capa.xqueue_interface as xqueue_interface +from capa.correctmap import CorrectMap from capa.safe_exec import safe_exec +from capa.util import contextualize_text, convert_files_to_filenames from openedx.core.djangolib.markup import HTML from xmodule.stringify import stringify_children - # extra things displayed after "show answers" is pressed solution_tags = ['solution'] diff --git a/common/lib/capa/capa/checker.py b/common/lib/capa/capa/checker.py index 504c490d3b..a481be0c44 100755 --- a/common/lib/capa/capa/checker.py +++ b/common/lib/capa/capa/checker.py @@ -7,13 +7,13 @@ from __future__ import unicode_literals import argparse import logging import sys -from path import Path as path - from cStringIO import StringIO +from mako.lookup import TemplateLookup +from path import Path as path + from calc import UndefinedVariable from capa.capa_problem import LoncapaProblem -from mako.lookup import TemplateLookup logging.basicConfig(format="%(levelname)s %(message)s") log = logging.getLogger('capa.checker') diff --git a/common/lib/capa/capa/customrender.py b/common/lib/capa/capa/customrender.py index c333fb8f87..bf89e102ff 100644 --- a/common/lib/capa/capa/customrender.py +++ b/common/lib/capa/capa/customrender.py @@ -8,10 +8,11 @@ and the xml element. import logging import re - -from cgi import escape as cgi_escape -from lxml import etree import xml.sax.saxutils as saxutils +from cgi import escape as cgi_escape + +from lxml import etree + from .registry import TagRegistry log = logging.getLogger(__name__) diff --git a/common/lib/capa/capa/inputtypes.py b/common/lib/capa/capa/inputtypes.py index 1432762ef2..29cc634b13 100644 --- a/common/lib/capa/capa/inputtypes.py +++ b/common/lib/capa/capa/inputtypes.py @@ -40,6 +40,7 @@ graded status as'status' import json import logging +import re import shlex # for splitting quoted strings import sys import time @@ -48,15 +49,15 @@ from datetime import datetime import bleach import html5lib import pyparsing -import re -from calc.preview import latex_preview -from chem import chemcalc from lxml import etree -from openedx.core.djangolib.markup import HTML, Text import xqueue_interface -from xmodule.stringify import stringify_children +from calc.preview import latex_preview from capa.xqueue_interface import XQUEUE_TIMEOUT +from chem import chemcalc +from openedx.core.djangolib.markup import HTML, Text +from xmodule.stringify import stringify_children + from .registry import TagRegistry from .util import sanitize_html diff --git a/common/lib/capa/capa/responsetypes.py b/common/lib/capa/capa/responsetypes.py index f9cfa0281c..a5ae98a880 100644 --- a/common/lib/capa/capa/responsetypes.py +++ b/common/lib/capa/capa/responsetypes.py @@ -7,52 +7,57 @@ of a variety of types. Used by capa_problem.py """ -# TODO: Refactor this code and fix this issue. + # pylint: disable=attribute-defined-outside-init # standard library imports import abc +# TODO: Refactor this code and fix this issue. import cgi import inspect import json import logging -import html5lib import numbers -import numpy import os -from pyparsing import ParseException -import sys import random import re -import requests import subprocess +import sys import textwrap import traceback import xml.sax.saxutils as saxutils -from cmath import isnan +from collections import namedtuple +from datetime import datetime from sys import float_info -from collections import namedtuple -from shapely.geometry import Point, MultiPoint - -import dogstats_wrapper as dog_stats_api - -# specific library imports -from calc import evaluator, UndefinedVariable -from . import correctmap -from .registry import TagRegistry -from datetime import datetime -from pytz import UTC -from .util import ( - compare_with_tolerance, contextualize_text, convert_files_to_filenames, - is_list_of_files, find_with_default, default_tolerance, get_inner_html_from_xpath -) +import html5lib +import numpy +import requests from lxml import etree -from lxml.html.soupparser import fromstring as fromstring_bs # uses Beautiful Soup!!! FIXME? -import capa.xqueue_interface as xqueue_interface +from lxml.html.soupparser import fromstring as fromstring_bs # uses Beautiful Soup!!! FIXME? +from pyparsing import ParseException +from pytz import UTC +from shapely.geometry import MultiPoint, Point import capa.safe_exec as safe_exec +import capa.xqueue_interface as xqueue_interface +import dogstats_wrapper as dog_stats_api +# specific library imports +from calc import UndefinedVariable, evaluator +from cmath import isnan from openedx.core.djangolib.markup import HTML, Text +from . import correctmap +from .registry import TagRegistry +from .util import ( + compare_with_tolerance, + contextualize_text, + convert_files_to_filenames, + default_tolerance, + find_with_default, + get_inner_html_from_xpath, + is_list_of_files +) + log = logging.getLogger(__name__) registry = TagRegistry() diff --git a/common/lib/capa/capa/util.py b/common/lib/capa/capa/util.py index 6dd0e35adb..c700d07387 100644 --- a/common/lib/capa/capa/util.py +++ b/common/lib/capa/capa/util.py @@ -1,14 +1,17 @@ """ Utility functions for capa. """ -import bleach +import re from decimal import Decimal +import bleach +from lxml import etree + from calc import evaluator from cmath import isinf, isnan -import re -from lxml import etree from openedx.core.djangolib.markup import HTML + + #----------------------------------------------------------------------------- # # Utility functions used in CAPA responsetypes diff --git a/common/lib/capa/capa/xqueue_interface.py b/common/lib/capa/capa/xqueue_interface.py index fe47e9b597..a407205519 100644 --- a/common/lib/capa/capa/xqueue_interface.py +++ b/common/lib/capa/capa/xqueue_interface.py @@ -4,9 +4,10 @@ import hashlib import json import logging -import requests -import dogstats_wrapper as dog_stats_api +import requests + +import dogstats_wrapper as dog_stats_api log = logging.getLogger(__name__) dateformat = '%Y%m%d%H%M%S' diff --git a/common/lib/capa/setup.py b/common/lib/capa/setup.py index 6edde294eb..d7b42a80cb 100644 --- a/common/lib/capa/setup.py +++ b/common/lib/capa/setup.py @@ -1,4 +1,4 @@ -from setuptools import setup, find_packages +from setuptools import find_packages, setup setup( name="capa", diff --git a/common/lib/chem/chem/chemcalc.py b/common/lib/chem/chem/chemcalc.py index b8424e96dc..d21d420359 100644 --- a/common/lib/chem/chem/chemcalc.py +++ b/common/lib/chem/chem/chemcalc.py @@ -1,9 +1,10 @@ from __future__ import division + from fractions import Fraction -from pyparsing import (Literal, StringEnd, OneOrMore, ParseException) import nltk from nltk.tree import Tree +from pyparsing import Literal, OneOrMore, ParseException, StringEnd ARROWS = ('<->', '->') diff --git a/common/lib/chem/chem/chemtools.py b/common/lib/chem/chem/chemtools.py index ad6633fc00..acb86a6b3a 100644 --- a/common/lib/chem/chem/chemtools.py +++ b/common/lib/chem/chem/chemtools.py @@ -3,9 +3,9 @@ Also, may be this module is the place for other chemistry-related grade functions. TODO: discuss it. """ +import itertools import json import unittest -import itertools def vsepr_parse_user_answer(user_input): diff --git a/common/lib/chem/chem/miller.py b/common/lib/chem/chem/miller.py index 3be90117e9..5f8fca7df2 100644 --- a/common/lib/chem/chem/miller.py +++ b/common/lib/chem/chem/miller.py @@ -1,10 +1,11 @@ """ Calculation of Miller indices """ -import numpy as np -import math -import fractions as fr import decimal +import fractions as fr import json +import math + +import numpy as np def lcm(a, b): diff --git a/common/lib/chem/chem/tests.py b/common/lib/chem/chem/tests.py index 75a044c7ee..93f6132798 100644 --- a/common/lib/chem/chem/tests.py +++ b/common/lib/chem/chem/tests.py @@ -1,16 +1,11 @@ import codecs -from fractions import Fraction import unittest - -from .chemcalc import ( - compare_chemical_expression, - divide_chemical_expression, - render_to_html, - chemical_equations_equal, -) +from fractions import Fraction import chem.miller +from .chemcalc import chemical_equations_equal, compare_chemical_expression, divide_chemical_expression, render_to_html + LOCAL_DEBUG = None diff --git a/common/lib/safe_lxml/safe_lxml/etree.py b/common/lib/safe_lxml/safe_lxml/etree.py index 1b5b9fad1a..696e1b2103 100644 --- a/common/lib/safe_lxml/safe_lxml/etree.py +++ b/common/lib/safe_lxml/safe_lxml/etree.py @@ -7,12 +7,11 @@ It also includes a safer XMLParser. For processing xml always prefer this over using lxml.etree directly. """ -from lxml.etree import * # pylint: disable=wildcard-import, unused-wildcard-import -from lxml.etree import XMLParser as _XMLParser -from lxml.etree import _Element, _ElementTree # pylint: disable=unused-import - # This should be imported after lxml.etree so that it overrides the following attributes. -from defusedxml.lxml import parse, fromstring, XML +from defusedxml.lxml import XML, fromstring, parse +from lxml.etree import XMLParser as _XMLParser +from lxml.etree import * # pylint: disable=wildcard-import, unused-wildcard-import; pylint: disable=unused-import +from lxml.etree import _Element, _ElementTree class XMLParser(_XMLParser): # pylint: disable=function-redefined diff --git a/common/lib/sandbox-packages/loncapa/loncapa_check.py b/common/lib/sandbox-packages/loncapa/loncapa_check.py index b873c4d685..d7d3ad44ea 100644 --- a/common/lib/sandbox-packages/loncapa/loncapa_check.py +++ b/common/lib/sandbox-packages/loncapa/loncapa_check.py @@ -6,8 +6,9 @@ # Used in translating LON-CAPA problems to i4x problem specification language. from __future__ import division -import random + import math +import random def lc_random(lower, upper, stepsize): diff --git a/common/lib/sandbox-packages/verifiers/tests_draganddrop.py b/common/lib/sandbox-packages/verifiers/tests_draganddrop.py index 8a27dd9287..79abe37fc2 100644 --- a/common/lib/sandbox-packages/verifiers/tests_draganddrop.py +++ b/common/lib/sandbox-packages/verifiers/tests_draganddrop.py @@ -1,8 +1,9 @@ +import json import unittest import draganddrop + from .draganddrop import PositionsCompare -import json class Test_PositionsCompare(unittest.TestCase): diff --git a/common/lib/symmath/symmath/formula.py b/common/lib/symmath/symmath/formula.py index 2e7a4971de..9317582502 100644 --- a/common/lib/symmath/symmath/formula.py +++ b/common/lib/symmath/symmath/formula.py @@ -11,24 +11,24 @@ Provides sympy representation. # Author: I. Chuang # -import os -import string -import re import logging import operator +import os +import re +import string +import unicodedata +#import subprocess +from copy import deepcopy +from xml.sax.saxutils import unescape + import requests import sympy -from sympy.printing.latex import LatexPrinter -from sympy.printing.str import StrPrinter +from lxml import etree from sympy import latex, sympify from sympy.physics.quantum.qubit import Qubit from sympy.physics.quantum.state import Ket - -from xml.sax.saxutils import unescape -import unicodedata -from lxml import etree -#import subprocess -from copy import deepcopy +from sympy.printing.latex import LatexPrinter +from sympy.printing.str import StrPrinter log = logging.getLogger(__name__) diff --git a/common/lib/symmath/symmath/symmath_check.py b/common/lib/symmath/symmath/symmath_check.py index 6e5f05212c..85afc3d879 100644 --- a/common/lib/symmath/symmath/symmath_check.py +++ b/common/lib/symmath/symmath/symmath_check.py @@ -8,9 +8,10 @@ # # Takes in math expressions given as Presentation MathML (from ASCIIMathML), converts to Content MathML using SnuggleTeX -import traceback -from .formula import * import logging +import traceback + +from .formula import * log = logging.getLogger(__name__) diff --git a/common/lib/symmath/symmath/test_formula.py b/common/lib/symmath/symmath/test_formula.py index 40361ed33c..2db506c564 100644 --- a/common/lib/symmath/symmath/test_formula.py +++ b/common/lib/symmath/symmath/test_formula.py @@ -1,11 +1,13 @@ """ Tests of symbolic math """ -import unittest -import formula import re +import unittest + from lxml import etree +import formula + def stripXML(xml): xml = xml.replace('\n', '') diff --git a/common/lib/symmath/symmath/test_symmath_check.py b/common/lib/symmath/symmath/test_symmath_check.py index 4d1dd87ac7..c3b725d4e7 100644 --- a/common/lib/symmath/symmath/test_symmath_check.py +++ b/common/lib/symmath/symmath/test_symmath_check.py @@ -1,4 +1,5 @@ from unittest import TestCase + from .symmath_check import symmath_check diff --git a/common/lib/xmodule/setup.py b/common/lib/xmodule/setup.py index c70fd3cbcf..4f216ce1f8 100644 --- a/common/lib/xmodule/setup.py +++ b/common/lib/xmodule/setup.py @@ -1,4 +1,4 @@ -from setuptools import setup, find_packages +from setuptools import find_packages, setup XMODULES = [ "book = xmodule.backcompat_module:TranslateCustomTagDescriptor", diff --git a/common/lib/xmodule/xmodule/annotatable_module.py b/common/lib/xmodule/xmodule/annotatable_module.py index 36428d2acb..1046f8853d 100644 --- a/common/lib/xmodule/xmodule/annotatable_module.py +++ b/common/lib/xmodule/xmodule/annotatable_module.py @@ -1,12 +1,12 @@ import logging +import textwrap from lxml import etree from pkg_resources import resource_string - -from xmodule.x_module import XModule -from xmodule.raw_module import RawDescriptor from xblock.fields import Scope, String -import textwrap + +from xmodule.raw_module import RawDescriptor +from xmodule.x_module import XModule log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/annotator_mixin.py b/common/lib/xmodule/xmodule/annotator_mixin.py index aa597702db..48e75d9ba0 100644 --- a/common/lib/xmodule/xmodule/annotator_mixin.py +++ b/common/lib/xmodule/xmodule/annotator_mixin.py @@ -2,10 +2,11 @@ Annotations Tool Mixin This file contains global variables and functions used in the various Annotation Tools. """ -from lxml import etree -from urlparse import urlparse -from os.path import splitext, basename from HTMLParser import HTMLParser +from os.path import basename, splitext +from urlparse import urlparse + +from lxml import etree def get_instructions(xmltree): diff --git a/common/lib/xmodule/xmodule/annotator_token.py b/common/lib/xmodule/xmodule/annotator_token.py index 80ad30cc9b..5822727cf8 100644 --- a/common/lib/xmodule/xmodule/annotator_token.py +++ b/common/lib/xmodule/xmodule/annotator_token.py @@ -6,6 +6,7 @@ It can be called from other files by using the following: from xmodule.annotator_token import retrieve_token """ import datetime + from firebase_token_generator import create_token diff --git a/common/lib/xmodule/xmodule/backcompat_module.py b/common/lib/xmodule/xmodule/backcompat_module.py index 7df2dcd496..71fcce8977 100644 --- a/common/lib/xmodule/xmodule/backcompat_module.py +++ b/common/lib/xmodule/xmodule/backcompat_module.py @@ -1,11 +1,13 @@ """ These modules exist to translate old format XML into newer, semantic forms """ -from .x_module import XModuleDescriptor -from lxml import etree -from functools import wraps import logging import traceback +from functools import wraps + +from lxml import etree + +from .x_module import XModuleDescriptor log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/capa_module.py b/common/lib/xmodule/xmodule/capa_module.py index d873b21ae1..905411f7b3 100644 --- a/common/lib/xmodule/xmodule/capa_module.py +++ b/common/lib/xmodule/xmodule/capa_module.py @@ -1,20 +1,21 @@ """Implements basics of Capa, including class CapaModule.""" import json import logging -import sys import re -from lxml import etree +import sys +from lxml import etree from pkg_resources import resource_string import dogstats_wrapper as dog_stats_api -from .capa_base import CapaMixin, CapaFields, ComplexEncoder from capa import responsetypes -from .progress import Progress -from xmodule.util.misc import escape_html_characters -from xmodule.x_module import XModule, module_attr, DEPRECATION_VSCOMPAT_EVENT -from xmodule.raw_module import RawDescriptor from xmodule.exceptions import NotFoundError, ProcessingError +from xmodule.raw_module import RawDescriptor +from xmodule.util.misc import escape_html_characters +from xmodule.x_module import DEPRECATION_VSCOMPAT_EVENT, XModule, module_attr + +from .capa_base import CapaFields, CapaMixin, ComplexEncoder +from .progress import Progress log = logging.getLogger("edx.courseware") diff --git a/common/lib/xmodule/xmodule/conditional_module.py b/common/lib/xmodule/xmodule/conditional_module.py index 0c7fc1e9d2..7ea3483aef 100644 --- a/common/lib/xmodule/xmodule/conditional_module.py +++ b/common/lib/xmodule/xmodule/conditional_module.py @@ -4,18 +4,18 @@ some xmodules by conditions. import json import logging + from lazy import lazy from lxml import etree from pkg_resources import resource_string - -from xmodule.x_module import XModule, STUDENT_VIEW -from xmodule.seq_module import SequenceDescriptor -from xmodule.studio_editable import StudioEditableModule, StudioEditableDescriptor -from xmodule.modulestore.exceptions import ItemNotFoundError -from xmodule.validation import StudioValidation, StudioValidationMessage -from xblock.fields import Scope, ReferenceList, String +from xblock.fields import ReferenceList, Scope, String from xblock.fragment import Fragment +from xmodule.modulestore.exceptions import ItemNotFoundError +from xmodule.seq_module import SequenceDescriptor +from xmodule.studio_editable import StudioEditableDescriptor, StudioEditableModule +from xmodule.validation import StudioValidation, StudioValidationMessage +from xmodule.x_module import STUDENT_VIEW, XModule log = logging.getLogger('edx.' + __name__) diff --git a/common/lib/xmodule/xmodule/course_metadata_utils.py b/common/lib/xmodule/xmodule/course_metadata_utils.py index e0a2e996ed..2a93628f08 100644 --- a/common/lib/xmodule/xmodule/course_metadata_utils.py +++ b/common/lib/xmodule/xmodule/course_metadata_utils.py @@ -7,9 +7,9 @@ classes, which both need these type of functions. """ from base64 import b32encode from datetime import datetime, timedelta -import dateutil.parser from math import exp +import dateutil.parser from pytz import utc DEFAULT_START_DATE = datetime(2030, 1, 1, tzinfo=utc) diff --git a/common/lib/xmodule/xmodule/editing_module.py b/common/lib/xmodule/xmodule/editing_module.py index 969a6d1476..92e2bdf906 100644 --- a/common/lib/xmodule/xmodule/editing_module.py +++ b/common/lib/xmodule/xmodule/editing_module.py @@ -1,10 +1,12 @@ """Descriptors for XBlocks/Xmodules, that provide editing of atrributes""" -from pkg_resources import resource_string -from xmodule.mako_module import MakoModuleDescriptor -from xblock.fields import Scope, String import logging +from pkg_resources import resource_string +from xblock.fields import Scope, String + +from xmodule.mako_module import MakoModuleDescriptor + log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/error_module.py b/common/lib/xmodule/xmodule/error_module.py index cdcd092177..0d7e44248f 100644 --- a/common/lib/xmodule/xmodule/error_module.py +++ b/common/lib/xmodule/xmodule/error_module.py @@ -4,17 +4,17 @@ loading or rendering other modules """ import hashlib -import logging import json +import logging import sys from lxml import etree -from xmodule.x_module import XModule, XModuleDescriptor -from xmodule.errortracker import exc_info_to_str -from xblock.fields import String, Scope, ScopeIds from xblock.field_data import DictFieldData -from xmodule.modulestore import EdxJSONEncoder +from xblock.fields import Scope, ScopeIds, String +from xmodule.errortracker import exc_info_to_str +from xmodule.modulestore import EdxJSONEncoder +from xmodule.x_module import XModule, XModuleDescriptor log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/errortracker.py b/common/lib/xmodule/xmodule/errortracker.py index e39604805a..282fb71e35 100644 --- a/common/lib/xmodule/xmodule/errortracker.py +++ b/common/lib/xmodule/xmodule/errortracker.py @@ -1,7 +1,6 @@ import logging import sys import traceback - from collections import namedtuple log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/fields.py b/common/lib/xmodule/xmodule/fields.py index 2b73d5b63f..379b6e5979 100644 --- a/common/lib/xmodule/xmodule/fields.py +++ b/common/lib/xmodule/xmodule/fields.py @@ -1,12 +1,11 @@ -import time +import datetime import logging import re +import time -from xblock.fields import JSONField -import datetime import dateutil.parser - from pytz import UTC +from xblock.fields import JSONField log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/graders.py b/common/lib/xmodule/xmodule/graders.py index dc904e1f02..0bd7ece904 100644 --- a/common/lib/xmodule/xmodule/graders.py +++ b/common/lib/xmodule/xmodule/graders.py @@ -5,12 +5,12 @@ Code used to calculate learner grades. from __future__ import division import abc -from collections import OrderedDict -from datetime import datetime # Used by pycontracts. pylint: disable=unused-import import inspect import logging import random import sys +from collections import OrderedDict +from datetime import datetime # Used by pycontracts. pylint: disable=unused-import from contracts import contract diff --git a/common/lib/xmodule/xmodule/hidden_module.py b/common/lib/xmodule/xmodule/hidden_module.py index 692f153ebf..149390a4ec 100644 --- a/common/lib/xmodule/xmodule/hidden_module.py +++ b/common/lib/xmodule/xmodule/hidden_module.py @@ -1,5 +1,5 @@ -from xmodule.x_module import XModule from xmodule.raw_module import RawDescriptor +from xmodule.x_module import XModule class HiddenModule(XModule): diff --git a/common/lib/xmodule/xmodule/html_module.py b/common/lib/xmodule/xmodule/html_module.py index 1d70ab4cb4..fce51db3fc 100644 --- a/common/lib/xmodule/xmodule/html_module.py +++ b/common/lib/xmodule/xmodule/html_module.py @@ -1,27 +1,28 @@ import copy -from datetime import datetime -from fs.errors import ResourceNotFoundError import logging -from lxml import etree import os -from path import Path as path -from pkg_resources import resource_string import re import sys import textwrap +from datetime import datetime + +from fs.errors import ResourceNotFoundError +from lxml import etree +from path import Path as path +from pkg_resources import resource_string +from xblock.core import XBlock +from xblock.fields import Boolean, List, Scope, String +from xblock.fragment import Fragment import dogstats_wrapper as dog_stats_api -from xmodule.util.misc import escape_html_characters from xmodule.contentstore.content import StaticContent from xmodule.editing_module import EditingDescriptor from xmodule.edxnotes_utils import edxnotes from xmodule.html_checker import check_html from xmodule.stringify import stringify_children -from xmodule.x_module import XModule, DEPRECATION_VSCOMPAT_EVENT +from xmodule.util.misc import escape_html_characters +from xmodule.x_module import DEPRECATION_VSCOMPAT_EVENT, XModule from xmodule.xml_module import XmlDescriptor, name_to_pathname -from xblock.core import XBlock -from xblock.fields import Scope, String, Boolean, List -from xblock.fragment import Fragment log = logging.getLogger("edx.courseware") diff --git a/common/lib/xmodule/xmodule/imageannotation_module.py b/common/lib/xmodule/xmodule/imageannotation_module.py index c9b361b84a..172dd36f40 100644 --- a/common/lib/xmodule/xmodule/imageannotation_module.py +++ b/common/lib/xmodule/xmodule/imageannotation_module.py @@ -1,17 +1,17 @@ """ Module for Image annotations using annotator. """ +import textwrap + from lxml import etree from pkg_resources import resource_string - -from xmodule.x_module import XModule -from xmodule.raw_module import RawDescriptor from xblock.core import Scope, String -from xmodule.annotator_mixin import get_instructions, html_to_text -from xmodule.annotator_token import retrieve_token from xblock.fragment import Fragment -import textwrap +from xmodule.annotator_mixin import get_instructions, html_to_text +from xmodule.annotator_token import retrieve_token +from xmodule.raw_module import RawDescriptor +from xmodule.x_module import XModule # Make '_' a no-op so we can scrape strings. Using lambda instead of # `django.utils.translation.ugettext_noop` because Django cannot be imported in this file diff --git a/common/lib/xmodule/xmodule/library_content_module.py b/common/lib/xmodule/xmodule/library_content_module.py index 027bcede56..7e52ba15f5 100644 --- a/common/lib/xmodule/xmodule/library_content_module.py +++ b/common/lib/xmodule/xmodule/library_content_module.py @@ -3,24 +3,26 @@ LibraryContent: The XBlock used to include blocks from a library in a course. """ import json -from lxml import etree -from copy import copy -from capa.responsetypes import registry -from gettext import ngettext -from lazy import lazy - -from .mako_module import MakoModuleDescriptor -from opaque_keys.edx.locator import LibraryLocator import random +from copy import copy +from gettext import ngettext + +from lazy import lazy +from lxml import etree +from opaque_keys.edx.locator import LibraryLocator +from pkg_resources import resource_string from webob import Response from xblock.core import XBlock -from xblock.fields import Scope, String, List, Integer, Boolean +from xblock.fields import Boolean, Integer, List, Scope, String from xblock.fragment import Fragment -from xmodule.validation import StudioValidationMessage, StudioValidation -from xmodule.x_module import XModule, STUDENT_VIEW -from xmodule.studio_editable import StudioEditableModule, StudioEditableDescriptor + +from capa.responsetypes import registry +from xmodule.studio_editable import StudioEditableDescriptor, StudioEditableModule +from xmodule.validation import StudioValidation, StudioValidationMessage +from xmodule.x_module import STUDENT_VIEW, XModule + +from .mako_module import MakoModuleDescriptor from .xml_module import XmlDescriptor -from pkg_resources import resource_string # Make '_' a no-op so we can scrape strings. Using lambda instead of # `django.utils.translation.ugettext_noop` because Django cannot be imported in this file diff --git a/common/lib/xmodule/xmodule/library_root_xblock.py b/common/lib/xmodule/xmodule/library_root_xblock.py index b5c239be2d..96dc512323 100644 --- a/common/lib/xmodule/xmodule/library_root_xblock.py +++ b/common/lib/xmodule/xmodule/library_root_xblock.py @@ -3,11 +3,11 @@ """ import logging -from xmodule.studio_editable import StudioEditableModule - -from xblock.fields import Scope, String, List, Boolean -from xblock.fragment import Fragment from xblock.core import XBlock +from xblock.fields import Boolean, List, Scope, String +from xblock.fragment import Fragment + +from xmodule.studio_editable import StudioEditableModule log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/library_tools.py b/common/lib/xmodule/xmodule/library_tools.py index 37e431c5e0..8f6f3eaeba 100644 --- a/common/lib/xmodule/xmodule/library_tools.py +++ b/common/lib/xmodule/xmodule/library_tools.py @@ -4,10 +4,11 @@ XBlock runtime services for LibraryContentModule from django.core.exceptions import PermissionDenied from opaque_keys.edx.locator import LibraryLocator, LibraryUsageLocator from search.search_engine_base import SearchEngine + +from xmodule.capa_module import CapaDescriptor from xmodule.library_content_module import ANY_CAPA_TYPE_VALUE from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.exceptions import ItemNotFoundError -from xmodule.capa_module import CapaDescriptor def normalize_key_for_search(library_key): diff --git a/common/lib/xmodule/xmodule/lti_2_util.py b/common/lib/xmodule/xmodule/lti_2_util.py index 0afed3bf24..3585d1e9d2 100644 --- a/common/lib/xmodule/xmodule/lti_2_util.py +++ b/common/lib/xmodule/xmodule/lti_2_util.py @@ -3,17 +3,17 @@ A mixin class for LTI 2.0 functionality. This is really just done to refactor the code to keep the LTIModule class from getting too big """ -import json -import re -import mock -import urllib -import hashlib import base64 +import hashlib +import json import logging +import re +import urllib +import mock +from oauthlib.oauth1 import Client from webob import Response from xblock.core import XBlock -from oauthlib.oauth1 import Client log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/lti_module.py b/common/lib/xmodule/xmodule/lti_module.py index 84153f621c..733fa0bab7 100644 --- a/common/lib/xmodule/xmodule/lti_module.py +++ b/common/lib/xmodule/xmodule/lti_module.py @@ -51,28 +51,29 @@ What is supported: GET / PUT / DELETE HTTP methods respectively """ -import datetime -from django.utils.timezone import UTC -import logging -import oauthlib.oauth1 -from oauthlib.oauth1.rfc5849 import signature -import hashlib import base64 -import urllib +import datetime +import hashlib +import logging import textwrap -import bleach -from lxml import etree -from webob import Response -import mock +import urllib from xml.sax.saxutils import escape +import bleach +import mock +import oauthlib.oauth1 +from django.utils.timezone import UTC +from lxml import etree +from oauthlib.oauth1.rfc5849 import signature +from pkg_resources import resource_string +from webob import Response +from xblock.core import List, Scope, String, XBlock +from xblock.fields import Boolean, Float + from xmodule.editing_module import MetadataOnlyEditingDescriptor +from xmodule.lti_2_util import LTI20ModuleMixin, LTIError from xmodule.raw_module import EmptyDataRawDescriptor from xmodule.x_module import XModule, module_attr -from xmodule.lti_2_util import LTI20ModuleMixin, LTIError -from pkg_resources import resource_string -from xblock.core import String, Scope, List, XBlock -from xblock.fields import Boolean, Float log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/mako_module.py b/common/lib/xmodule/xmodule/mako_module.py index 0185e86643..f7223d5927 100644 --- a/common/lib/xmodule/xmodule/mako_module.py +++ b/common/lib/xmodule/xmodule/mako_module.py @@ -3,7 +3,7 @@ Code to handle mako templating for XModules and XBlocks. """ from xblock.fragment import Fragment -from .x_module import XModuleDescriptor, DescriptorSystem, shim_xmodule_js +from .x_module import DescriptorSystem, XModuleDescriptor, shim_xmodule_js class MakoDescriptorSystem(DescriptorSystem): diff --git a/common/lib/xmodule/xmodule/mongo_utils.py b/common/lib/xmodule/xmodule/mongo_utils.py index 710a556d76..a36ce5cb2a 100644 --- a/common/lib/xmodule/xmodule/mongo_utils.py +++ b/common/lib/xmodule/xmodule/mongo_utils.py @@ -1,10 +1,10 @@ """ Common MongoDB connection functions. """ -import pymongo -from mongodb_proxy import MongoProxy import logging +import pymongo +from mongodb_proxy import MongoProxy logger = logging.getLogger(__name__) # pylint: disable=invalid-name diff --git a/common/lib/xmodule/xmodule/partitions/partitions.py b/common/lib/xmodule/xmodule/partitions/partitions.py index c54630edd8..f2630744e0 100644 --- a/common/lib/xmodule/xmodule/partitions/partitions.py +++ b/common/lib/xmodule/xmodule/partitions/partitions.py @@ -1,6 +1,7 @@ """Defines ``Group`` and ``UserPartition`` models for partitioning""" from collections import namedtuple + from stevedore.extension import ExtensionManager # We use ``id`` in this file as the IDs of our Groups and UserPartitions, diff --git a/common/lib/xmodule/xmodule/poll_module.py b/common/lib/xmodule/xmodule/poll_module.py index a39cd34a9a..d9cbfac540 100644 --- a/common/lib/xmodule/xmodule/poll_module.py +++ b/common/lib/xmodule/xmodule/poll_module.py @@ -9,18 +9,18 @@ If student have answered - Question with statistics for each answers. import cgi import json import logging -from copy import deepcopy from collections import OrderedDict +from copy import deepcopy from lxml import etree -from openedx.core.djangolib.markup import Text from pkg_resources import resource_string +from xblock.fields import Boolean, Dict, List, Scope, String -from xmodule.x_module import XModule -from xmodule.stringify import stringify_children +from openedx.core.djangolib.markup import Text from xmodule.mako_module import MakoModuleDescriptor +from xmodule.stringify import stringify_children +from xmodule.x_module import XModule from xmodule.xml_module import XmlDescriptor -from xblock.fields import Scope, String, Dict, Boolean, List log = logging.getLogger(__name__) _ = lambda text: text diff --git a/common/lib/xmodule/xmodule/randomize_module.py b/common/lib/xmodule/xmodule/randomize_module.py index 93a5d5824a..3ada822833 100644 --- a/common/lib/xmodule/xmodule/randomize_module.py +++ b/common/lib/xmodule/xmodule/randomize_module.py @@ -1,14 +1,13 @@ import logging import random -from xmodule.x_module import XModule, STUDENT_VIEW -from xmodule.seq_module import SequenceDescriptor - from lxml import etree - -from xblock.fields import Scope, Integer +from xblock.fields import Integer, Scope from xblock.fragment import Fragment +from xmodule.seq_module import SequenceDescriptor +from xmodule.x_module import STUDENT_VIEW, XModule + log = logging.getLogger('edx.' + __name__) diff --git a/common/lib/xmodule/xmodule/raw_module.py b/common/lib/xmodule/xmodule/raw_module.py index 5533f5f9d6..b0e38b63f1 100644 --- a/common/lib/xmodule/xmodule/raw_module.py +++ b/common/lib/xmodule/xmodule/raw_module.py @@ -1,9 +1,11 @@ +import logging +from exceptions import SerializationError + from lxml import etree +from xblock.fields import Scope, String + from xmodule.editing_module import XMLEditingDescriptor from xmodule.xml_module import XmlDescriptor -import logging -from xblock.fields import String, Scope -from exceptions import SerializationError log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/static_content.py b/common/lib/xmodule/xmodule/static_content.py index cad0fabb6b..6ea10e2a92 100755 --- a/common/lib/xmodule/xmodule/static_content.py +++ b/common/lib/xmodule/xmodule/static_content.py @@ -4,18 +4,18 @@ This module has utility functions for gathering up the static content that is defined by XModules and XModuleDescriptors (javascript and css) """ -import logging -import hashlib -import os import errno +import hashlib +import logging +import os import sys from collections import defaultdict + from docopt import docopt from path import Path as path from xmodule.x_module import XModuleDescriptor - LOG = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/studio_editable.py b/common/lib/xmodule/xmodule/studio_editable.py index a54ffb3978..6ff5dd2133 100644 --- a/common/lib/xmodule/xmodule/studio_editable.py +++ b/common/lib/xmodule/xmodule/studio_editable.py @@ -1,7 +1,7 @@ """ Mixin to support editing in Studio. """ -from xmodule.x_module import module_attr, STUDENT_VIEW, AUTHOR_VIEW +from xmodule.x_module import AUTHOR_VIEW, STUDENT_VIEW, module_attr class StudioEditableBlock(object): diff --git a/common/lib/xmodule/xmodule/tabs.py b/common/lib/xmodule/xmodule/tabs.py index de7838fc8f..b4a8dd6fba 100644 --- a/common/lib/xmodule/xmodule/tabs.py +++ b/common/lib/xmodule/xmodule/tabs.py @@ -1,13 +1,13 @@ """ Implement CourseTab """ -from abc import ABCMeta import logging - -from xblock.fields import List -from openedx.core.lib.api.plugins import PluginError +from abc import ABCMeta from django.core.files.storage import get_storage_class +from xblock.fields import List + +from openedx.core.lib.api.plugins import PluginError log = logging.getLogger("edx.courseware") diff --git a/common/lib/xmodule/xmodule/template_module.py b/common/lib/xmodule/xmodule/template_module.py index d3fd79c2f6..76297953aa 100644 --- a/common/lib/xmodule/xmodule/template_module.py +++ b/common/lib/xmodule/xmodule/template_module.py @@ -1,11 +1,12 @@ """ Template module """ -from xmodule.x_module import XModule, DEPRECATION_VSCOMPAT_EVENT -from xmodule.raw_module import RawDescriptor from lxml import etree from mako.template import Template + import dogstats_wrapper as dog_stats_api +from xmodule.raw_module import RawDescriptor +from xmodule.x_module import DEPRECATION_VSCOMPAT_EVENT, XModule class CustomTagModule(XModule): diff --git a/common/lib/xmodule/xmodule/templates.py b/common/lib/xmodule/xmodule/templates.py index d5d45619f1..3df220b1a7 100644 --- a/common/lib/xmodule/xmodule/templates.py +++ b/common/lib/xmodule/xmodule/templates.py @@ -10,8 +10,8 @@ samples. # should this move to cms since it's really only for module crud? import logging - from collections import defaultdict + from xblock.core import XBlock log = logging.getLogger(__name__) diff --git a/common/lib/xmodule/xmodule/textannotation_module.py b/common/lib/xmodule/xmodule/textannotation_module.py index beff2b8454..8f1e661db9 100644 --- a/common/lib/xmodule/xmodule/textannotation_module.py +++ b/common/lib/xmodule/xmodule/textannotation_module.py @@ -1,14 +1,15 @@ """Text annotation module""" +import textwrap + from lxml import etree from pkg_resources import resource_string - -from xmodule.x_module import XModule -from xmodule.raw_module import RawDescriptor from xblock.core import Scope, String +from xblock.fragment import Fragment + from xmodule.annotator_mixin import get_instructions from xmodule.annotator_token import retrieve_token -from xblock.fragment import Fragment -import textwrap +from xmodule.raw_module import RawDescriptor +from xmodule.x_module import XModule # Make '_' a no-op so we can scrape strings. Using lambda instead of # `django.utils.translation.ugettext_noop` because Django cannot be imported in this file diff --git a/common/lib/xmodule/xmodule/vertical_block.py b/common/lib/xmodule/xmodule/vertical_block.py index 73b1717a8c..d253a1f67e 100644 --- a/common/lib/xmodule/xmodule/vertical_block.py +++ b/common/lib/xmodule/xmodule/vertical_block.py @@ -3,9 +3,11 @@ VerticalBlock - an XBlock which renders its children in a column. """ import logging from copy import copy + from lxml import etree from xblock.core import XBlock from xblock.fragment import Fragment + from xmodule.mako_module import MakoTemplateBlockBase from xmodule.progress import Progress from xmodule.seq_module import SequenceFields diff --git a/common/lib/xmodule/xmodule/videoannotation_module.py b/common/lib/xmodule/xmodule/videoannotation_module.py index 30ad2bfdf7..6071bf755e 100644 --- a/common/lib/xmodule/xmodule/videoannotation_module.py +++ b/common/lib/xmodule/xmodule/videoannotation_module.py @@ -1,17 +1,17 @@ """ Module for Video annotations using annotator. """ +import textwrap + from lxml import etree from pkg_resources import resource_string - -from xmodule.x_module import XModule -from xmodule.raw_module import RawDescriptor from xblock.core import Scope, String -from xmodule.annotator_mixin import get_instructions, get_extension -from xmodule.annotator_token import retrieve_token from xblock.fragment import Fragment -import textwrap +from xmodule.annotator_mixin import get_extension, get_instructions +from xmodule.annotator_token import retrieve_token +from xmodule.raw_module import RawDescriptor +from xmodule.x_module import XModule # Make '_' a no-op so we can scrape strings. Using lambda instead of # `django.utils.translation.ugettext_noop` because Django cannot be imported in this file diff --git a/common/lib/xmodule/xmodule/word_cloud_module.py b/common/lib/xmodule/xmodule/word_cloud_module.py index e80c556d8f..c21588e327 100644 --- a/common/lib/xmodule/xmodule/word_cloud_module.py +++ b/common/lib/xmodule/xmodule/word_cloud_module.py @@ -8,15 +8,15 @@ If student have answered - words he entered and cloud. import json import logging + from pkg_resources import resource_string - -from xmodule.raw_module import EmptyDataRawDescriptor -from xmodule.editing_module import MetadataOnlyEditingDescriptor -from xmodule.x_module import XModule - -from xblock.fields import Scope, Dict, Boolean, List, Integer, String +from xblock.fields import Boolean, Dict, Integer, List, Scope, String from xblock.fragment import Fragment +from xmodule.editing_module import MetadataOnlyEditingDescriptor +from xmodule.raw_module import EmptyDataRawDescriptor +from xmodule.x_module import XModule + log = logging.getLogger(__name__) # Make '_' a no-op so we can scrape strings. Using lambda instead of diff --git a/common/lib/xmodule/xmodule/wrapper_module.py b/common/lib/xmodule/xmodule/wrapper_module.py index 63e132716d..6c03dd59d3 100644 --- a/common/lib/xmodule/xmodule/wrapper_module.py +++ b/common/lib/xmodule/xmodule/wrapper_module.py @@ -3,6 +3,7 @@ from xmodule.vertical_block import VerticalBlock + # HACK: This shouldn't be hard-coded to two types # OBSOLETE: This obsoletes 'type' class_priority = ['video', 'problem'] diff --git a/common/lib/xmodule/xmodule/xml_module.py b/common/lib/xmodule/xmodule/xml_module.py index fa70cc3634..053b456cbc 100644 --- a/common/lib/xmodule/xmodule/xml_module.py +++ b/common/lib/xmodule/xmodule/xml_module.py @@ -1,22 +1,19 @@ -import json import copy +import json import logging import os import sys -from lxml import etree +from lxml import etree +from lxml.etree import Element, ElementTree, XMLParser from xblock.core import XML_NAMESPACES from xblock.fields import Dict, Scope, ScopeIds from xblock.runtime import KvsFieldData -from xmodule.x_module import XModuleDescriptor, DEPRECATION_VSCOMPAT_EVENT -from xmodule.modulestore.inheritance import own_metadata, InheritanceKeyValueStore -from xmodule.modulestore import EdxJSONEncoder import dogstats_wrapper as dog_stats_api - -from lxml.etree import ( - Element, ElementTree, XMLParser, -) +from xmodule.modulestore import EdxJSONEncoder +from xmodule.modulestore.inheritance import InheritanceKeyValueStore, own_metadata +from xmodule.x_module import DEPRECATION_VSCOMPAT_EVENT, XModuleDescriptor log = logging.getLogger(__name__) diff --git a/common/test/utils.py b/common/test/utils.py index 26bf81271c..cab85a9970 100644 --- a/common/test/utils.py +++ b/common/test/utils.py @@ -3,10 +3,11 @@ General testing utilities. """ import sys from contextlib import contextmanager + +import moto from django.dispatch import Signal from markupsafe import escape from mock import Mock, patch -import moto @contextmanager diff --git a/openedx/core/djangoapps/api_admin/admin.py b/openedx/core/djangoapps/api_admin/admin.py index 3521a1cd52..45add91f45 100644 --- a/openedx/core/djangoapps/api_admin/admin.py +++ b/openedx/core/djangoapps/api_admin/admin.py @@ -1,10 +1,10 @@ """Admin views for API managment.""" +from config_models.admin import ConfigurationModelAdmin from django.contrib import admin from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ -from config_models.admin import ConfigurationModelAdmin -from openedx.core.djangoapps.api_admin.models import ApiAccessRequest, ApiAccessConfig +from openedx.core.djangoapps.api_admin.models import ApiAccessConfig, ApiAccessRequest @admin.register(ApiAccessRequest) diff --git a/openedx/core/djangoapps/api_admin/decorators.py b/openedx/core/djangoapps/api_admin/decorators.py index 3c406932bc..089f2cf2d2 100644 --- a/openedx/core/djangoapps/api_admin/decorators.py +++ b/openedx/core/djangoapps/api_admin/decorators.py @@ -5,7 +5,7 @@ from django.core.urlresolvers import reverse from django.http import HttpResponseNotFound from django.shortcuts import redirect -from openedx.core.djangoapps.api_admin.models import ApiAccessRequest, ApiAccessConfig +from openedx.core.djangoapps.api_admin.models import ApiAccessConfig, ApiAccessRequest def api_access_enabled_or_404(view_func): diff --git a/openedx/core/djangoapps/api_admin/models.py b/openedx/core/djangoapps/api_admin/models.py index d8963cac2a..cfa0b9afba 100644 --- a/openedx/core/djangoapps/api_admin/models.py +++ b/openedx/core/djangoapps/api_admin/models.py @@ -3,6 +3,7 @@ import logging from smtplib import SMTPException from urlparse import urlunsplit +from config_models.models import ConfigurationModel from django.conf import settings from django.contrib.auth.models import User from django.contrib.sites.models import Site @@ -13,10 +14,9 @@ from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.utils.translation import ugettext as _ from django_extensions.db.models import TimeStampedModel -from edxmako.shortcuts import render_to_string from simple_history.models import HistoricalRecords -from config_models.models import ConfigurationModel +from edxmako.shortcuts import render_to_string from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/api_admin/urls.py b/openedx/core/djangoapps/api_admin/urls.py index cb84c9613e..8458057c49 100644 --- a/openedx/core/djangoapps/api_admin/urls.py +++ b/openedx/core/djangoapps/api_admin/urls.py @@ -6,8 +6,13 @@ from django.contrib.auth.decorators import login_required from openedx.core.djangoapps.api_admin.decorators import api_access_enabled_or_404 from openedx.core.djangoapps.api_admin.views import ( - ApiRequestView, ApiRequestStatusView, ApiTosView, CatalogListView, CatalogEditView, - CatalogPreviewView, CatalogSearchView + ApiRequestStatusView, + ApiRequestView, + ApiTosView, + CatalogEditView, + CatalogListView, + CatalogPreviewView, + CatalogSearchView ) urlpatterns = ( diff --git a/openedx/core/djangoapps/api_admin/views.py b/openedx/core/djangoapps/api_admin/views.py index 4bd78ffdc3..d03f670417 100644 --- a/openedx/core/djangoapps/api_admin/views.py +++ b/openedx/core/djangoapps/api_admin/views.py @@ -3,13 +3,13 @@ import logging from django.conf import settings from django.contrib.sites.shortcuts import get_current_site -from django.core.urlresolvers import reverse_lazy, reverse +from django.core.urlresolvers import reverse, reverse_lazy from django.http.response import JsonResponse from django.shortcuts import redirect from django.views.generic import View from django.views.generic.base import TemplateView from django.views.generic.edit import CreateView -from oauth2_provider.generators import generate_client_secret, generate_client_id +from oauth2_provider.generators import generate_client_id, generate_client_secret from oauth2_provider.models import get_application_model from oauth2_provider.views import ApplicationRegistration from slumber.exceptions import HttpNotFoundError diff --git a/openedx/core/djangoapps/api_admin/widgets.py b/openedx/core/djangoapps/api_admin/widgets.py index 1841daf596..8f2b754a21 100644 --- a/openedx/core/djangoapps/api_admin/widgets.py +++ b/openedx/core/djangoapps/api_admin/widgets.py @@ -7,6 +7,7 @@ from django.forms.widgets import CheckboxInput from django.utils.encoding import force_text from django.utils.html import format_html from django.utils.translation import ugettext as _ + from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers diff --git a/openedx/core/djangoapps/auth_exchange/forms.py b/openedx/core/djangoapps/auth_exchange/forms.py index 8caf61799d..870de4a0d0 100644 --- a/openedx/core/djangoapps/auth_exchange/forms.py +++ b/openedx/core/djangoapps/auth_exchange/forms.py @@ -1,14 +1,14 @@ """ Forms to support third-party to first-party OAuth 2.0 access token exchange """ +import provider.constants from django.contrib.auth.models import User from django.forms import CharField from edx_oauth2_provider.constants import SCOPE_NAMES -import provider.constants +from oauth2_provider.models import Application from provider.forms import OAuthForm, OAuthValidationError from provider.oauth2.forms import ScopeChoiceField, ScopeMixin from provider.oauth2.models import Client -from oauth2_provider.models import Application from requests import HTTPError from social.backends import oauth as social_oauth from social.exceptions import AuthException diff --git a/openedx/core/djangoapps/auth_exchange/views.py b/openedx/core/djangoapps/auth_exchange/views.py index ea1d270ad5..844c8fc2dd 100644 --- a/openedx/core/djangoapps/auth_exchange/views.py +++ b/openedx/core/djangoapps/auth_exchange/views.py @@ -9,9 +9,10 @@ The following are currently implemented: # pylint: disable=abstract-method +import django.contrib.auth as auth +import social.apps.django_app.utils as social_utils from django.conf import settings from django.contrib.auth import login -import django.contrib.auth as auth from django.http import HttpResponse from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt @@ -24,7 +25,6 @@ from provider.oauth2.views import AccessTokenView as DOPAccessTokenView from rest_framework import permissions from rest_framework.response import Response from rest_framework.views import APIView -import social.apps.django_app.utils as social_utils from openedx.core.djangoapps.auth_exchange.forms import AccessTokenExchangeForm from openedx.core.djangoapps.oauth_dispatch import adapters diff --git a/openedx/core/djangoapps/bookmarks/api.py b/openedx/core/djangoapps/bookmarks/api.py index 3aa81dd306..632dfd1426 100644 --- a/openedx/core/djangoapps/bookmarks/api.py +++ b/openedx/core/djangoapps/bookmarks/api.py @@ -1,11 +1,13 @@ """ Bookmarks Python API. """ -from eventtracking import tracker -from . import DEFAULT_FIELDS, OPTIONAL_FIELDS -from xmodule.modulestore.django import modulestore from django.conf import settings + +from eventtracking import tracker +from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError + +from . import DEFAULT_FIELDS, OPTIONAL_FIELDS from .models import Bookmark from .serializers import BookmarkSerializer diff --git a/openedx/core/djangoapps/bookmarks/models.py b/openedx/core/djangoapps/bookmarks/models.py index d048bb214a..de0dfaae0d 100644 --- a/openedx/core/djangoapps/bookmarks/models.py +++ b/openedx/core/djangoapps/bookmarks/models.py @@ -5,15 +5,14 @@ import logging from django.contrib.auth.models import User from django.db import models - from jsonfield.fields import JSONField from model_utils.models import TimeStampedModel - from opaque_keys.edx.keys import UsageKey + +from openedx.core.djangoapps.xmodule_django.models import CourseKeyField, LocationKeyField from xmodule.modulestore import search from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError, NoPathToItem -from openedx.core.djangoapps.xmodule_django.models import CourseKeyField, LocationKeyField from . import PathItem diff --git a/openedx/core/djangoapps/bookmarks/serializers.py b/openedx/core/djangoapps/bookmarks/serializers.py index b7479fd1ef..2aba8d168d 100644 --- a/openedx/core/djangoapps/bookmarks/serializers.py +++ b/openedx/core/djangoapps/bookmarks/serializers.py @@ -2,6 +2,7 @@ Serializers for Bookmarks. """ from rest_framework import serializers + from openedx.core.lib.api.serializers import CourseKeyField, UsageKeyField from . import DEFAULT_FIELDS diff --git a/openedx/core/djangoapps/bookmarks/services.py b/openedx/core/djangoapps/bookmarks/services.py index 7e40343f8a..92e22b3bd0 100644 --- a/openedx/core/djangoapps/bookmarks/services.py +++ b/openedx/core/djangoapps/bookmarks/services.py @@ -5,11 +5,10 @@ import logging from django.core.exceptions import ObjectDoesNotExist +from request_cache.middleware import RequestCache from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError -from request_cache.middleware import RequestCache - from . import DEFAULT_FIELDS, api log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/bookmarks/tasks.py b/openedx/core/djangoapps/bookmarks/tasks.py index 5443e29fe5..4c7caf4cd9 100644 --- a/openedx/core/djangoapps/bookmarks/tasks.py +++ b/openedx/core/djangoapps/bookmarks/tasks.py @@ -2,10 +2,11 @@ Tasks for bookmarks. """ import logging -from django.db import transaction from celery.task import task # pylint: disable=import-error,no-name-in-module +from django.db import transaction from opaque_keys.edx.keys import CourseKey + from xmodule.modulestore.django import modulestore from . import PathItem diff --git a/openedx/core/djangoapps/bookmarks/urls.py b/openedx/core/djangoapps/bookmarks/urls.py index 2b0553df40..c2dcc5b8bc 100644 --- a/openedx/core/djangoapps/bookmarks/urls.py +++ b/openedx/core/djangoapps/bookmarks/urls.py @@ -5,8 +5,7 @@ URL routes for the bookmarks app. from django.conf import settings from django.conf.urls import patterns, url -from .views import BookmarksListView, BookmarksDetailView - +from .views import BookmarksDetailView, BookmarksListView urlpatterns = patterns( 'bookmarks', diff --git a/openedx/core/djangoapps/bookmarks/views.py b/openedx/core/djangoapps/bookmarks/views.py index c81a69ac0b..d1dc1af009 100644 --- a/openedx/core/djangoapps/bookmarks/views.py +++ b/openedx/core/djangoapps/bookmarks/views.py @@ -4,31 +4,27 @@ HTTP end-points for the Bookmarks API. For more information, see: https://openedx.atlassian.net/wiki/display/TNL/Bookmarks+API """ -import eventtracking import logging +from django.conf import settings from django.core.exceptions import ObjectDoesNotExist -from django.utils.translation import ugettext as _, ugettext_noop - -from rest_framework import status -from rest_framework import permissions +from django.utils.translation import ugettext as _ +from django.utils.translation import ugettext_noop +from opaque_keys import InvalidKeyError +from opaque_keys.edx.keys import CourseKey, UsageKey +from rest_framework import permissions, status from rest_framework.authentication import SessionAuthentication from rest_framework.generics import ListCreateAPIView from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_oauth.authentication import OAuth2Authentication -from opaque_keys import InvalidKeyError -from opaque_keys.edx.keys import CourseKey, UsageKey -from django.conf import settings +import eventtracking from openedx.core.djangoapps.bookmarks.api import BookmarksLimitReachedError - -from openedx.core.lib.api.permissions import IsUserInUrl - -from xmodule.modulestore.exceptions import ItemNotFoundError - from openedx.core.lib.api.paginators import DefaultPagination +from openedx.core.lib.api.permissions import IsUserInUrl from openedx.core.lib.url_utils import unquote_slashes +from xmodule.modulestore.exceptions import ItemNotFoundError from . import DEFAULT_FIELDS, OPTIONAL_FIELDS, api from .serializers import BookmarkSerializer diff --git a/openedx/core/djangoapps/cache_toolbox/middleware.py b/openedx/core/djangoapps/cache_toolbox/middleware.py index 4fdeb3c6be..1032e43eac 100644 --- a/openedx/core/djangoapps/cache_toolbox/middleware.py +++ b/openedx/core/djangoapps/cache_toolbox/middleware.py @@ -78,16 +78,17 @@ choice for most environments but you may be happy with the trade-offs of the """ -from django.conf import settings -from django.contrib.auth import HASH_SESSION_KEY -from django.contrib.auth.models import User, AnonymousUser -from django.contrib.auth.middleware import AuthenticationMiddleware -from django.utils.crypto import constant_time_compare from logging import getLogger -from openedx.core.djangoapps.safe_sessions.middleware import SafeSessionMiddleware -from .model import cache_model +from django.conf import settings +from django.contrib.auth import HASH_SESSION_KEY +from django.contrib.auth.middleware import AuthenticationMiddleware +from django.contrib.auth.models import AnonymousUser, User +from django.utils.crypto import constant_time_compare +from openedx.core.djangoapps.safe_sessions.middleware import SafeSessionMiddleware + +from .model import cache_model log = getLogger(__name__) diff --git a/openedx/core/djangoapps/cache_toolbox/model.py b/openedx/core/djangoapps/cache_toolbox/model.py index c5600c5e6a..dd7e1973d0 100644 --- a/openedx/core/djangoapps/cache_toolbox/model.py +++ b/openedx/core/djangoapps/cache_toolbox/model.py @@ -54,9 +54,9 @@ instance:: ... Foo.DoesNotExist """ -from django.db.models.signals import post_save, post_delete +from django.db.models.signals import post_delete, post_save -from .core import get_instance, delete_instance +from .core import delete_instance, get_instance def cache_model(model, timeout=None): diff --git a/openedx/core/djangoapps/cache_toolbox/relation.py b/openedx/core/djangoapps/cache_toolbox/relation.py index a6216907d2..6d1b2bf304 100644 --- a/openedx/core/djangoapps/cache_toolbox/relation.py +++ b/openedx/core/djangoapps/cache_toolbox/relation.py @@ -69,9 +69,9 @@ Support ``cache_relation`` currently only works with ``OneToOneField`` fields. Support for regular ``ForeignKey`` fields is planned. """ -from django.db.models.signals import post_save, post_delete +from django.db.models.signals import post_delete, post_save -from .core import get_instance, delete_instance +from .core import delete_instance, get_instance def cache_relation(descriptor, timeout=None): diff --git a/openedx/core/djangoapps/catalog/admin.py b/openedx/core/djangoapps/catalog/admin.py index da4309260e..545ffd4886 100644 --- a/openedx/core/djangoapps/catalog/admin.py +++ b/openedx/core/djangoapps/catalog/admin.py @@ -1,10 +1,9 @@ """ Django admin bindings for catalog support models. """ +from config_models.admin import ConfigurationModelAdmin from django.contrib import admin -from config_models.admin import ConfigurationModelAdmin from openedx.core.djangoapps.catalog.models import CatalogIntegration - admin.site.register(CatalogIntegration, ConfigurationModelAdmin) diff --git a/openedx/core/djangoapps/catalog/models.py b/openedx/core/djangoapps/catalog/models.py index 735f1cdb0f..d916f41188 100644 --- a/openedx/core/djangoapps/catalog/models.py +++ b/openedx/core/djangoapps/catalog/models.py @@ -1,8 +1,7 @@ """Models governing integration with the catalog service.""" -from django.utils.translation import ugettext_lazy as _ -from django.db import models - from config_models.models import ConfigurationModel +from django.db import models +from django.utils.translation import ugettext_lazy as _ class CatalogIntegration(ConfigurationModel): diff --git a/openedx/core/djangoapps/catalog/urls.py b/openedx/core/djangoapps/catalog/urls.py index 0961e7194d..2090f9956c 100644 --- a/openedx/core/djangoapps/catalog/urls.py +++ b/openedx/core/djangoapps/catalog/urls.py @@ -2,7 +2,6 @@ from django.conf.urls import url from . import views - urlpatterns = [ url(r'^management/cache_programs/$', views.cache_programs, name='cache_programs'), ] diff --git a/openedx/core/djangoapps/catalog/utils.py b/openedx/core/djangoapps/catalog/utils.py index 06f5dd4d0c..7ce02b134b 100644 --- a/openedx/core/djangoapps/catalog/utils.py +++ b/openedx/core/djangoapps/catalog/utils.py @@ -12,7 +12,6 @@ from openedx.core.djangoapps.catalog.models import CatalogIntegration from openedx.core.lib.edx_api_utils import get_edx_api_data from openedx.core.lib.token_utils import JwtBuilder - logger = logging.getLogger(__name__) User = get_user_model() # pylint: disable=invalid-name diff --git a/openedx/core/djangoapps/ccxcon/api.py b/openedx/core/djangoapps/ccxcon/api.py index dbb2853f48..43c40c6e80 100644 --- a/openedx/core/djangoapps/ccxcon/api.py +++ b/openedx/core/djangoapps/ccxcon/api.py @@ -5,20 +5,18 @@ Module containing API functions for the CCXCon import logging import urlparse -from django.core.validators import URLValidator from django.core.exceptions import ValidationError +from django.core.validators import URLValidator from django.http import Http404 from oauthlib.oauth2 import BackendApplicationClient from requests_oauthlib import OAuth2Session -from rest_framework.status import ( - HTTP_200_OK, - HTTP_201_CREATED, -) +from rest_framework.status import HTTP_200_OK, HTTP_201_CREATED from lms.djangoapps.courseware.courses import get_course_by_id from openedx.core.djangoapps.models.course_details import CourseDetails from student.models import anonymous_id_for_user from student.roles import CourseInstructorRole + from .models import CCXCon log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/ccxcon/tasks.py b/openedx/core/djangoapps/ccxcon/tasks.py index 642afc869d..3ff0391ce6 100644 --- a/openedx/core/djangoapps/ccxcon/tasks.py +++ b/openedx/core/djangoapps/ccxcon/tasks.py @@ -4,18 +4,11 @@ This file contains celery tasks for ccxcon from celery.task import task # pylint: disable=no-name-in-module, import-error from celery.utils.log import get_task_logger # pylint: disable=no-name-in-module, import-error -from requests.exceptions import ( - ConnectionError, - HTTPError, - RequestException, - TooManyRedirects -) - from opaque_keys.edx.keys import CourseKey +from requests.exceptions import ConnectionError, HTTPError, RequestException, TooManyRedirects from openedx.core.djangoapps.ccxcon import api - log = get_task_logger(__name__) diff --git a/openedx/core/djangoapps/commerce/utils.py b/openedx/core/djangoapps/commerce/utils.py index 1f86373878..a7971cd0b8 100644 --- a/openedx/core/djangoapps/commerce/utils.py +++ b/openedx/core/djangoapps/commerce/utils.py @@ -1,8 +1,8 @@ """ Commerce API Service. """ from django.conf import settings from edx_rest_api_client.client import EdxRestApiClient -from eventtracking import tracker +from eventtracking import tracker from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.lib.token_utils import JwtBuilder diff --git a/openedx/core/djangoapps/common_views/xblock.py b/openedx/core/djangoapps/common_views/xblock.py index 4062208d61..28176a00a8 100644 --- a/openedx/core/djangoapps/common_views/xblock.py +++ b/openedx/core/djangoapps/common_views/xblock.py @@ -6,11 +6,9 @@ from __future__ import absolute_import import logging import mimetypes -from xblock.core import XBlock - from django.conf import settings from django.http import Http404, HttpResponse - +from xblock.core import XBlock log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/contentserver/admin.py b/openedx/core/djangoapps/contentserver/admin.py index 893b267f0b..cf663403f0 100644 --- a/openedx/core/djangoapps/contentserver/admin.py +++ b/openedx/core/djangoapps/contentserver/admin.py @@ -2,9 +2,10 @@ Django admin page for CourseAssetCacheTtlConfig, which allows you to configure the TTL that gets used when sending cachability headers back with request course assets. """ -from django.contrib import admin from config_models.admin import ConfigurationModelAdmin -from .models import CourseAssetCacheTtlConfig, CdnUserAgentsConfig +from django.contrib import admin + +from .models import CdnUserAgentsConfig, CourseAssetCacheTtlConfig class CourseAssetCacheTtlConfigAdmin(ConfigurationModelAdmin): diff --git a/openedx/core/djangoapps/contentserver/caching.py b/openedx/core/djangoapps/contentserver/caching.py index ba55a38812..b7bfdb2b75 100644 --- a/openedx/core/djangoapps/contentserver/caching.py +++ b/openedx/core/djangoapps/contentserver/caching.py @@ -4,6 +4,7 @@ Helper functions for caching course assets. from django.core.cache import caches from django.core.cache.backends.base import InvalidCacheBackendError from opaque_keys import InvalidKeyError + from xmodule.contentstore.content import STATIC_CONTENT_VERSION # See if there's a "course_assets" cache configured, and if not, fallback to the default cache. diff --git a/openedx/core/djangoapps/contentserver/models.py b/openedx/core/djangoapps/contentserver/models.py index 013ff364f1..ba4c08d97a 100644 --- a/openedx/core/djangoapps/contentserver/models.py +++ b/openedx/core/djangoapps/contentserver/models.py @@ -2,8 +2,8 @@ Models for contentserver """ -from django.db.models.fields import PositiveIntegerField, TextField from config_models.models import ConfigurationModel +from django.db.models.fields import PositiveIntegerField, TextField class CourseAssetCacheTtlConfig(ConfigurationModel): diff --git a/openedx/core/djangoapps/cors_csrf/admin.py b/openedx/core/djangoapps/cors_csrf/admin.py index 7aa4233f32..34449cd9b4 100644 --- a/openedx/core/djangoapps/cors_csrf/admin.py +++ b/openedx/core/djangoapps/cors_csrf/admin.py @@ -2,10 +2,9 @@ Manage cross-domain configuration. """ -from django.contrib import admin from config_models.admin import ConfigurationModelAdmin +from django.contrib import admin from .models import XDomainProxyConfiguration - admin.site.register(XDomainProxyConfiguration, ConfigurationModelAdmin) diff --git a/openedx/core/djangoapps/cors_csrf/helpers.py b/openedx/core/djangoapps/cors_csrf/helpers.py index c1a059c1a9..6131de5074 100644 --- a/openedx/core/djangoapps/cors_csrf/helpers.py +++ b/openedx/core/djangoapps/cors_csrf/helpers.py @@ -1,7 +1,7 @@ """Helper methods for CORS and CSRF checks. """ +import contextlib import logging import urlparse -import contextlib from django.conf import settings diff --git a/openedx/core/djangoapps/cors_csrf/middleware.py b/openedx/core/djangoapps/cors_csrf/middleware.py index ac03243133..53bed42aad 100644 --- a/openedx/core/djangoapps/cors_csrf/middleware.py +++ b/openedx/core/djangoapps/cors_csrf/middleware.py @@ -45,8 +45,8 @@ CSRF cookie. import logging from django.conf import settings +from django.core.exceptions import ImproperlyConfigured, MiddlewareNotUsed from django.middleware.csrf import CsrfViewMiddleware -from django.core.exceptions import MiddlewareNotUsed, ImproperlyConfigured from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check diff --git a/openedx/core/djangoapps/cors_csrf/models.py b/openedx/core/djangoapps/cors_csrf/models.py index 1274f4f17a..02b66ac1af 100644 --- a/openedx/core/djangoapps/cors_csrf/models.py +++ b/openedx/core/djangoapps/cors_csrf/models.py @@ -1,7 +1,7 @@ """Models for cross-domain configuration. """ +from config_models.models import ConfigurationModel from django.db import models from django.utils.translation import ugettext_lazy as _ -from config_models.models import ConfigurationModel class XDomainProxyConfiguration(ConfigurationModel): diff --git a/openedx/core/djangoapps/cors_csrf/views.py b/openedx/core/djangoapps/cors_csrf/views.py index 17f794bbdc..e3fa8fcee1 100644 --- a/openedx/core/djangoapps/cors_csrf/views.py +++ b/openedx/core/djangoapps/cors_csrf/views.py @@ -1,14 +1,15 @@ """Views for enabling cross-domain requests. """ -import logging import json +import logging + from django.conf import settings -from django.views.decorators.cache import cache_page from django.http import HttpResponseNotFound +from django.views.decorators.cache import cache_page + from edxmako.shortcuts import render_to_response from .models import XDomainProxyConfiguration - log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/course_groups/cohorts.py b/openedx/core/djangoapps/course_groups/cohorts.py index 963934d625..fb8f833c5a 100644 --- a/openedx/core/djangoapps/course_groups/cohorts.py +++ b/openedx/core/djangoapps/course_groups/cohorts.py @@ -7,26 +7,25 @@ import logging import random from django.db import IntegrityError, transaction -from django.db.models.signals import post_save, m2m_changed +from django.db.models.signals import m2m_changed, post_save from django.dispatch import receiver from django.http import Http404 from django.utils.translation import ugettext as _ +import request_cache from courseware import courses from eventtracking import tracker -import request_cache from request_cache.middleware import request_cached from student.models import get_user_by_username_or_email from .models import ( - CourseUserGroup, + CohortMembership, CourseCohort, CourseCohortsSettings, - CourseUserGroupPartitionGroup, - CohortMembership + CourseUserGroup, + CourseUserGroupPartitionGroup ) - log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/course_groups/models.py b/openedx/core/djangoapps/course_groups/models.py index 1b59faa4f2..6daaba5b53 100644 --- a/openedx/core/djangoapps/course_groups/models.py +++ b/openedx/core/djangoapps/course_groups/models.py @@ -6,12 +6,13 @@ import json import logging from django.contrib.auth.models import User -from django.db import models, transaction -from util.db import outer_atomic from django.core.exceptions import ValidationError +from django.db import models, transaction from django.db.models.signals import pre_delete from django.dispatch import receiver + from openedx.core.djangoapps.xmodule_django.models import CourseKeyField +from util.db import outer_atomic log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/course_groups/views.py b/openedx/core/djangoapps/course_groups/views.py index 43aa91b5ad..c648792572 100644 --- a/openedx/core/djangoapps/course_groups/views.py +++ b/openedx/core/djangoapps/course_groups/views.py @@ -2,30 +2,29 @@ Views related to course groups functionality. """ -from django.views.decorators.csrf import ensure_csrf_cookie -from django.views.decorators.http import require_POST -from django.contrib.auth.models import User -from django.core.paginator import Paginator, EmptyPage -from django.core.urlresolvers import reverse -from django.http import Http404, HttpResponseBadRequest -from django.views.decorators.http import require_http_methods -from util.json_request import expect_json, JsonResponse -from django.db import transaction -from django.contrib.auth.decorators import login_required -from django.utils.translation import ugettext - import logging import re +from django.contrib.auth.decorators import login_required +from django.contrib.auth.models import User +from django.core.paginator import EmptyPage, Paginator +from django.core.urlresolvers import reverse +from django.db import transaction +from django.http import Http404, HttpResponseBadRequest +from django.utils.translation import ugettext +from django.views.decorators.csrf import ensure_csrf_cookie +from django.views.decorators.http import require_http_methods, require_POST from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locations import SlashSeparatedCourseKey + from courseware.courses import get_course_with_access from edxmako.shortcuts import render_to_response +from lms.djangoapps.django_comment_client.constants import TYPE_ENTRY +from lms.djangoapps.django_comment_client.utils import get_discussion_categories_ids, get_discussion_category_map +from util.json_request import JsonResponse, expect_json from . import cohorts -from lms.djangoapps.django_comment_client.utils import get_discussion_category_map, get_discussion_categories_ids -from lms.djangoapps.django_comment_client.constants import TYPE_ENTRY -from .models import CourseUserGroup, CourseUserGroupPartitionGroup, CohortMembership +from .models import CohortMembership, CourseUserGroup, CourseUserGroupPartitionGroup log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/coursetalk/admin.py b/openedx/core/djangoapps/coursetalk/admin.py index 91d034416d..1c1da65601 100644 --- a/openedx/core/djangoapps/coursetalk/admin.py +++ b/openedx/core/djangoapps/coursetalk/admin.py @@ -1,8 +1,7 @@ """Manage coursetalk configuration. """ +from config_models.admin import ConfigurationModelAdmin from django.contrib import admin -from config_models.admin import ConfigurationModelAdmin from openedx.core.djangoapps.coursetalk.models import CourseTalkWidgetConfiguration - admin.site.register(CourseTalkWidgetConfiguration, ConfigurationModelAdmin) diff --git a/openedx/core/djangoapps/coursetalk/models.py b/openedx/core/djangoapps/coursetalk/models.py index 781774d85d..aee503d952 100644 --- a/openedx/core/djangoapps/coursetalk/models.py +++ b/openedx/core/djangoapps/coursetalk/models.py @@ -3,11 +3,10 @@ Models for CourseTalk configurations """ from __future__ import unicode_literals +from config_models.models import ConfigurationModel from django.db import models from django.utils.translation import ugettext_lazy as _ -from config_models.models import ConfigurationModel - class CourseTalkWidgetConfiguration(ConfigurationModel): """ diff --git a/openedx/core/djangoapps/crawlers/admin.py b/openedx/core/djangoapps/crawlers/admin.py index 45085716e3..a2d2953069 100644 --- a/openedx/core/djangoapps/crawlers/admin.py +++ b/openedx/core/djangoapps/crawlers/admin.py @@ -1,7 +1,7 @@ """Admin panel for configuring which user agents we consider to be Crawlers.""" +from config_models.admin import ConfigurationModelAdmin from django.contrib import admin -from config_models.admin import ConfigurationModelAdmin from .models import CrawlersConfig admin.site.register(CrawlersConfig, ConfigurationModelAdmin) diff --git a/openedx/core/djangoapps/crawlers/models.py b/openedx/core/djangoapps/crawlers/models.py index 33f02305e2..c39c6ba5eb 100644 --- a/openedx/core/djangoapps/crawlers/models.py +++ b/openedx/core/djangoapps/crawlers/models.py @@ -2,9 +2,8 @@ This module handles the detection of crawlers, so that we can handle them appropriately in other parts of the code. """ -from django.db import models - from config_models.models import ConfigurationModel +from django.db import models class CrawlersConfig(ConfigurationModel): diff --git a/openedx/core/djangoapps/credentials/admin.py b/openedx/core/djangoapps/credentials/admin.py index 6d94abb06e..d56e394ed3 100644 --- a/openedx/core/djangoapps/credentials/admin.py +++ b/openedx/core/djangoapps/credentials/admin.py @@ -2,9 +2,8 @@ Django admin pages for credentials support models. """ -from django.contrib import admin - from config_models.admin import ConfigurationModelAdmin +from django.contrib import admin from openedx.core.djangoapps.credentials.models import CredentialsApiConfig diff --git a/openedx/core/djangoapps/credit/admin.py b/openedx/core/djangoapps/credit/admin.py index b30803e3d2..d16d89c972 100644 --- a/openedx/core/djangoapps/credit/admin.py +++ b/openedx/core/djangoapps/credit/admin.py @@ -4,7 +4,12 @@ Django admin page for credit eligibility from ratelimitbackend import admin from openedx.core.djangoapps.credit.models import ( - CreditConfig, CreditCourse, CreditProvider, CreditEligibility, CreditRequest, CreditRequirement, + CreditConfig, + CreditCourse, + CreditEligibility, + CreditProvider, + CreditRequest, + CreditRequirement, CreditRequirementStatus ) diff --git a/openedx/core/djangoapps/credit/email_utils.py b/openedx/core/djangoapps/credit/email_utils.py index ae32e0e9d7..cc7ebadf29 100644 --- a/openedx/core/djangoapps/credit/email_utils.py +++ b/openedx/core/djangoapps/credit/email_utils.py @@ -2,12 +2,13 @@ This file contains utility functions which will responsible for sending emails. """ -import os - +import HTMLParser import logging +import os import urlparse import uuid -import HTMLParser +from email.mime.image import MIMEImage +from email.mime.multipart import MIMEMultipart from django.conf import settings from django.contrib.auth.models import User @@ -17,16 +18,13 @@ from django.core.mail import EmailMessage, SafeMIMEText from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ -from email.mime.image import MIMEImage -from email.mime.multipart import MIMEMultipart -from eventtracking import tracker from edxmako.shortcuts import render_to_string from edxmako.template import Template +from eventtracking import tracker from openedx.core.djangoapps.commerce.utils import ecommerce_api_client from openedx.core.djangoapps.credit.models import CreditConfig, CreditProvider -from xmodule.modulestore.django import modulestore from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers - +from xmodule.modulestore.django import modulestore log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/credit/exceptions.py b/openedx/core/djangoapps/credit/exceptions.py index 04d58c8c30..306985cdc4 100644 --- a/openedx/core/djangoapps/credit/exceptions.py +++ b/openedx/core/djangoapps/credit/exceptions.py @@ -1,9 +1,11 @@ """Exceptions raised by the credit API. """ from __future__ import unicode_literals + from django.utils.translation import ugettext_lazy as _ from rest_framework import status from rest_framework.exceptions import APIException + # TODO: Cleanup this mess! ECOM-2908 diff --git a/openedx/core/djangoapps/credit/models.py b/openedx/core/djangoapps/credit/models.py index a6829f2fbe..e7a126c8ff 100644 --- a/openedx/core/djangoapps/credit/models.py +++ b/openedx/core/djangoapps/credit/models.py @@ -6,24 +6,25 @@ Credit courses allow students to receive university credit for successful completion of a course on EdX """ -from collections import defaultdict import datetime import logging +from collections import defaultdict +import pytz from config_models.models import ConfigurationModel from django.conf import settings from django.core.cache import cache from django.core.validators import RegexValidator -from django.db import models, transaction, IntegrityError +from django.db import IntegrityError, models, transaction from django.dispatch import receiver -from django.utils.translation import ugettext_lazy, ugettext as _ +from django.utils.translation import ugettext as _ +from django.utils.translation import ugettext_lazy from jsonfield.fields import JSONField from model_utils.models import TimeStampedModel -import pytz from simple_history.models import HistoricalRecords -from openedx.core.djangoapps.xmodule_django.models import CourseKeyField -from request_cache.middleware import ns_request_cached, RequestCache +from openedx.core.djangoapps.xmodule_django.models import CourseKeyField +from request_cache.middleware import RequestCache, ns_request_cached CREDIT_PROVIDER_ID_REGEX = r"[a-z,A-Z,0-9,\-]+" log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/credit/serializers.py b/openedx/core/djangoapps/credit/serializers.py index a2c7fca6a7..ccb2e691e1 100644 --- a/openedx/core/djangoapps/credit/serializers.py +++ b/openedx/core/djangoapps/credit/serializers.py @@ -1,15 +1,16 @@ """ Credit API Serializers """ from __future__ import unicode_literals + import datetime import logging -from django.conf import settings import pytz +from django.conf import settings from rest_framework import serializers from rest_framework.exceptions import PermissionDenied -from openedx.core.djangoapps.credit.models import CreditCourse, CreditProvider, CreditEligibility, CreditRequest +from openedx.core.djangoapps.credit.models import CreditCourse, CreditEligibility, CreditProvider, CreditRequest from openedx.core.djangoapps.credit.signature import get_shared_secret_key, signature from openedx.core.lib.api.serializers import CourseKeyField from util.date_utils import from_timestamp diff --git a/openedx/core/djangoapps/credit/services.py b/openedx/core/djangoapps/credit/services.py index e38db41f22..57cc57d9f7 100644 --- a/openedx/core/djangoapps/credit/services.py +++ b/openedx/core/djangoapps/credit/services.py @@ -6,7 +6,6 @@ import logging from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist - from opaque_keys.edx.keys import CourseKey from student.models import CourseEnrollment diff --git a/openedx/core/djangoapps/credit/signals.py b/openedx/core/djangoapps/credit/signals.py index 982ff87be3..0a3e5e2af8 100644 --- a/openedx/core/djangoapps/credit/signals.py +++ b/openedx/core/djangoapps/credit/signals.py @@ -7,9 +7,9 @@ import logging from django.dispatch import receiver from django.utils import timezone from opaque_keys.edx.keys import CourseKey -from xmodule.modulestore.django import SignalHandler from openedx.core.djangoapps.signals.signals import COURSE_GRADE_CHANGED +from xmodule.modulestore.django import SignalHandler log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/credit/signature.py b/openedx/core/djangoapps/credit/signature.py index 343a3c833b..34a685c294 100644 --- a/openedx/core/djangoapps/credit/signature.py +++ b/openedx/core/djangoapps/credit/signature.py @@ -16,13 +16,12 @@ we receive from the credit provider. """ -import logging import hashlib import hmac +import logging from django.conf import settings - log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/credit/urls.py b/openedx/core/djangoapps/credit/urls.py index 1f495acb3a..93a130c836 100644 --- a/openedx/core/djangoapps/credit/urls.py +++ b/openedx/core/djangoapps/credit/urls.py @@ -1,9 +1,9 @@ """ URLs for the credit app. """ -from django.conf.urls import patterns, url, include +from django.conf.urls import include, patterns, url -from openedx.core.djangoapps.credit import views, routers, models +from openedx.core.djangoapps.credit import models, routers, views PROVIDER_ID_PATTERN = r'(?P{})'.format(models.CREDIT_PROVIDER_ID_REGEX) diff --git a/openedx/core/djangoapps/credit/views.py b/openedx/core/djangoapps/credit/views.py index c376a9a0c5..0dce4a102e 100644 --- a/openedx/core/djangoapps/credit/views.py +++ b/openedx/core/djangoapps/credit/views.py @@ -13,7 +13,7 @@ from django.views.decorators.csrf import csrf_exempt from edx_rest_framework_extensions.authentication import JwtAuthentication from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey -from rest_framework import viewsets, mixins, permissions, views, generics +from rest_framework import generics, mixins, permissions, views, viewsets from rest_framework.authentication import SessionAuthentication from rest_framework.exceptions import ValidationError from rest_framework.response import Response @@ -21,15 +21,23 @@ from rest_framework_oauth.authentication import OAuth2Authentication from openedx.core.djangoapps.credit.api import create_credit_request from openedx.core.djangoapps.credit.exceptions import ( - UserNotEligibleException, InvalidCourseKey, CreditApiBadRequest, InvalidCreditRequest, + CreditApiBadRequest, + InvalidCourseKey, + InvalidCreditRequest, + UserNotEligibleException ) from openedx.core.djangoapps.credit.models import ( - CreditCourse, CreditProvider, CREDIT_PROVIDER_ID_REGEX, - CreditEligibility, CreditRequest, + CREDIT_PROVIDER_ID_REGEX, + CreditCourse, + CreditEligibility, + CreditProvider, + CreditRequest ) from openedx.core.djangoapps.credit.serializers import ( - CreditCourseSerializer, CreditProviderSerializer, - CreditEligibilitySerializer, CreditProviderCallbackSerializer, + CreditCourseSerializer, + CreditEligibilitySerializer, + CreditProviderCallbackSerializer, + CreditProviderSerializer ) from openedx.core.lib.api.mixins import PutAsCreateMixin from openedx.core.lib.api.permissions import IsStaffOrOwner diff --git a/openedx/core/djangoapps/dark_lang/admin.py b/openedx/core/djangoapps/dark_lang/admin.py index fec604d3f3..3ae70e24ec 100644 --- a/openedx/core/djangoapps/dark_lang/admin.py +++ b/openedx/core/djangoapps/dark_lang/admin.py @@ -2,9 +2,9 @@ Admin site bindings for dark_lang """ +from config_models.admin import ConfigurationModelAdmin from django.contrib import admin -from config_models.admin import ConfigurationModelAdmin from openedx.core.djangoapps.dark_lang.models import DarkLangConfig admin.site.register(DarkLangConfig, ConfigurationModelAdmin) diff --git a/openedx/core/djangoapps/dark_lang/middleware.py b/openedx/core/djangoapps/dark_lang/middleware.py index 510438c7d5..a08590425b 100644 --- a/openedx/core/djangoapps/dark_lang/middleware.py +++ b/openedx/core/djangoapps/dark_lang/middleware.py @@ -8,14 +8,12 @@ This middleware must be placed before the LocaleMiddleware, but after the SessionMiddleware. """ from django.conf import settings -from django.utils.translation.trans_real import parse_accept_lang_header from django.utils.translation import LANGUAGE_SESSION_KEY +from django.utils.translation.trans_real import parse_accept_lang_header from openedx.core.djangoapps.dark_lang import DARK_LANGUAGE_KEY from openedx.core.djangoapps.dark_lang.models import DarkLangConfig -from openedx.core.djangoapps.user_api.preferences.api import ( - get_user_preference -) +from openedx.core.djangoapps.user_api.preferences.api import get_user_preference # If django 1.7 or higher is used, the right-side can be updated with new-style codes. CHINESE_LANGUAGE_CODE_MAP = { diff --git a/openedx/core/djangoapps/dark_lang/models.py b/openedx/core/djangoapps/dark_lang/models.py index 101ab0b4d3..58d3468825 100644 --- a/openedx/core/djangoapps/dark_lang/models.py +++ b/openedx/core/djangoapps/dark_lang/models.py @@ -1,9 +1,8 @@ """ Models for the dark-launching languages """ -from django.db import models - from config_models.models import ConfigurationModel +from django.db import models class DarkLangConfig(ConfigurationModel): diff --git a/openedx/core/djangoapps/dark_lang/tests.py b/openedx/core/djangoapps/dark_lang/tests.py index 2101ed9038..328bb1e71d 100644 --- a/openedx/core/djangoapps/dark_lang/tests.py +++ b/openedx/core/djangoapps/dark_lang/tests.py @@ -4,12 +4,11 @@ Tests of DarkLangMiddleware import unittest import ddt -from mock import Mock - from django.http import HttpRequest from django.test import TestCase from django.test.client import Client from django.utils.translation import LANGUAGE_SESSION_KEY +from mock import Mock from openedx.core.djangoapps.dark_lang.middleware import DarkLangMiddleware from openedx.core.djangoapps.dark_lang.models import DarkLangConfig diff --git a/openedx/core/djangoapps/dark_lang/views.py b/openedx/core/djangoapps/dark_lang/views.py index df3f7621e7..69c4d484e9 100644 --- a/openedx/core/djangoapps/dark_lang/views.py +++ b/openedx/core/djangoapps/dark_lang/views.py @@ -3,15 +3,18 @@ Views file for the Darklang Django App """ from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator -from django.utils.translation import LANGUAGE_SESSION_KEY from django.utils.translation import ugettext as _ +from django.utils.translation import LANGUAGE_SESSION_KEY from django.views.generic.base import View + from edxmako.shortcuts import render_to_response from openedx.core.djangoapps.dark_lang import DARK_LANGUAGE_KEY from openedx.core.djangoapps.dark_lang.models import DarkLangConfig from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY from openedx.core.djangoapps.user_api.preferences.api import ( - delete_user_preference, get_user_preference, set_user_preference + delete_user_preference, + get_user_preference, + set_user_preference ) from openedx.core.lib.api.view_utils import view_auth_classes diff --git a/openedx/core/djangoapps/datadog/startup.py b/openedx/core/djangoapps/datadog/startup.py index f8874cd1d6..8c02244742 100644 --- a/openedx/core/djangoapps/datadog/startup.py +++ b/openedx/core/djangoapps/datadog/startup.py @@ -2,8 +2,7 @@ Start up initialization of datadog. """ from django.conf import settings - -from dogapi import dog_stats_api, dog_http_api +from dogapi import dog_http_api, dog_stats_api def run(): diff --git a/openedx/core/djangoapps/debug/views.py b/openedx/core/djangoapps/debug/views.py index 6591f07bc1..ed5e42b6bf 100644 --- a/openedx/core/djangoapps/debug/views.py +++ b/openedx/core/djangoapps/debug/views.py @@ -3,9 +3,10 @@ Views that are only activated when the project is running in development mode. These views will NOT be shown on production: trying to access them will result in a 404 error. """ -from edxmako.shortcuts import render_to_response -from mako.exceptions import TopLevelLookupException from django.http import HttpResponseNotFound +from mako.exceptions import TopLevelLookupException + +from edxmako.shortcuts import render_to_response def show_reference_template(request, template): diff --git a/openedx/core/djangoapps/embargo/admin.py b/openedx/core/djangoapps/embargo/admin.py index 72b267e70f..e6be3d1bd9 100644 --- a/openedx/core/djangoapps/embargo/admin.py +++ b/openedx/core/djangoapps/embargo/admin.py @@ -1,16 +1,13 @@ """ Django admin page for embargo models """ -from django.contrib import admin import textwrap from config_models.admin import ConfigurationModelAdmin -from .models import ( - IPFilter, CountryAccessRule, RestrictedCourse -) -from .forms import ( - IPFilterForm, RestrictedCourseForm -) +from django.contrib import admin + +from .forms import IPFilterForm, RestrictedCourseForm +from .models import CountryAccessRule, IPFilter, RestrictedCourse class IPFilterAdmin(ConfigurationModelAdmin): diff --git a/openedx/core/djangoapps/embargo/api.py b/openedx/core/djangoapps/embargo/api.py index 7ba8878808..0c2d39171c 100644 --- a/openedx/core/djangoapps/embargo/api.py +++ b/openedx/core/djangoapps/embargo/api.py @@ -6,17 +6,17 @@ This API is exposed via the middleware(emabargo/middileware.py) layer but may be """ import logging -import pygeoip -from django.core.cache import cache from django.conf import settings -from rest_framework.response import Response -from rest_framework import status +from django.core.cache import cache from ipware.ip import get_ip +from rest_framework import status +from rest_framework.response import Response +import pygeoip from student.auth import has_course_author_access -from .models import CountryAccessRule, RestrictedCourse +from .models import CountryAccessRule, RestrictedCourse log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/embargo/forms.py b/openedx/core/djangoapps/embargo/forms.py index 9529f84b8b..61037afec5 100644 --- a/openedx/core/djangoapps/embargo/forms.py +++ b/openedx/core/djangoapps/embargo/forms.py @@ -2,15 +2,14 @@ Defines forms for providing validation of embargo admin details. """ +import ipaddr from django import forms from django.utils.translation import ugettext as _ - -import ipaddr - -from xmodule.modulestore.django import modulestore from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey +from xmodule.modulestore.django import modulestore + from .models import IPFilter, RestrictedCourse diff --git a/openedx/core/djangoapps/embargo/messages.py b/openedx/core/djangoapps/embargo/messages.py index 04c7cd871d..7cf0c11c80 100644 --- a/openedx/core/djangoapps/embargo/messages.py +++ b/openedx/core/djangoapps/embargo/messages.py @@ -6,7 +6,6 @@ from either enrolling in or accessing a course. """ from collections import namedtuple - BlockedMessage = namedtuple('BlockedMessage', [ # A user-facing description of the message 'description', diff --git a/openedx/core/djangoapps/embargo/middleware.py b/openedx/core/djangoapps/embargo/middleware.py index c0d72524e9..d657644fd7 100644 --- a/openedx/core/djangoapps/embargo/middleware.py +++ b/openedx/core/djangoapps/embargo/middleware.py @@ -28,16 +28,16 @@ Usage: import logging import re +from django.conf import settings from django.core.exceptions import MiddlewareNotUsed from django.core.urlresolvers import reverse -from django.conf import settings from django.shortcuts import redirect from ipware.ip import get_ip + from util.request import course_id_from_url -from .models import IPFilter from . import api as embargo_api - +from .models import IPFilter log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/embargo/models.py b/openedx/core/djangoapps/embargo/models.py index a95dbf3e6b..e10ee76a11 100644 --- a/openedx/core/djangoapps/embargo/models.py +++ b/openedx/core/djangoapps/embargo/models.py @@ -11,25 +11,24 @@ file and check it in at the same time as your model changes. To do that, 3. Add the migration file created in edx-platform/openedx/core/djangoapps/embargo/migrations/ """ -import ipaddr import json import logging -from django.db import models -from django.utils.translation import ugettext as _, ugettext_lazy +import ipaddr +from config_models.models import ConfigurationModel from django.core.cache import cache from django.core.urlresolvers import reverse -from django.db.models.signals import post_save, post_delete - -from django_countries.fields import CountryField +from django.db import models +from django.db.models.signals import post_delete, post_save +from django.utils.translation import ugettext as _ +from django.utils.translation import ugettext_lazy from django_countries import countries +from django_countries.fields import CountryField -from config_models.models import ConfigurationModel from openedx.core.djangoapps.xmodule_django.models import CourseKeyField, NoneToEmptyManager from .exceptions import InvalidAccessPoint -from .messages import ENROLL_MESSAGES, COURSEWARE_MESSAGES - +from .messages import COURSEWARE_MESSAGES, ENROLL_MESSAGES log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/embargo/test_utils.py b/openedx/core/djangoapps/embargo/test_utils.py index 450e970fe7..5108c9bf49 100644 --- a/openedx/core/djangoapps/embargo/test_utils.py +++ b/openedx/core/djangoapps/embargo/test_utils.py @@ -1,11 +1,12 @@ """Utilities for writing unit tests that involve course embargos. """ import contextlib + import mock +from django.core.cache import cache +from django.core.urlresolvers import reverse import pygeoip -from django.core.urlresolvers import reverse -from django.core.cache import cache from .models import Country, CountryAccessRule, RestrictedCourse diff --git a/openedx/core/djangoapps/embargo/urls.py b/openedx/core/djangoapps/embargo/urls.py index defd923d2c..abad7a5f9e 100644 --- a/openedx/core/djangoapps/embargo/urls.py +++ b/openedx/core/djangoapps/embargo/urls.py @@ -4,7 +4,6 @@ from django.conf.urls import patterns, url from .views import CourseAccessMessageView - urlpatterns = patterns( 'openedx.core.djangoapps.embargo.views', url( diff --git a/openedx/core/djangoapps/external_auth/admin.py b/openedx/core/djangoapps/external_auth/admin.py index d6278e2be0..0ee4997e02 100644 --- a/openedx/core/djangoapps/external_auth/admin.py +++ b/openedx/core/djangoapps/external_auth/admin.py @@ -2,9 +2,10 @@ django admin pages for courseware model ''' -from openedx.core.djangoapps.external_auth.models import ExternalAuthMap from ratelimitbackend import admin +from openedx.core.djangoapps.external_auth.models import ExternalAuthMap + class ExternalAuthMapAdmin(admin.ModelAdmin): """ diff --git a/openedx/core/djangoapps/external_auth/djangostore.py b/openedx/core/djangoapps/external_auth/djangostore.py index 0e16f7783d..e69ce85806 100644 --- a/openedx/core/djangoapps/external_auth/djangostore.py +++ b/openedx/core/djangoapps/external_auth/djangostore.py @@ -1,13 +1,12 @@ """A openid store using django cache""" -from openid.store.interface import OpenIDStore -from openid.store import nonce - -from django.core.cache import cache - import logging import time +from django.core.cache import cache +from openid.store import nonce +from openid.store.interface import OpenIDStore + DEFAULT_ASSOCIATIONS_TIMEOUT = 60 DEFAULT_NONCE_TIMEOUT = 600 diff --git a/openedx/core/djangoapps/external_auth/login_and_register.py b/openedx/core/djangoapps/external_auth/login_and_register.py index 20a4f808ec..d49a920964 100644 --- a/openedx/core/djangoapps/external_auth/login_and_register.py +++ b/openedx/core/djangoapps/external_auth/login_and_register.py @@ -5,13 +5,13 @@ This module contains legacy code originally from `student.views`. import re from django.conf import settings -from django.shortcuts import redirect from django.core.urlresolvers import reverse -import openedx.core.djangoapps.external_auth.views - -from xmodule.modulestore.django import modulestore +from django.shortcuts import redirect from opaque_keys.edx.keys import CourseKey +import openedx.core.djangoapps.external_auth.views +from xmodule.modulestore.django import modulestore + # pylint: disable=fixme # TODO: This function is kind of gnarly/hackish/etc and is only used in one location. diff --git a/openedx/core/djangoapps/external_auth/models.py b/openedx/core/djangoapps/external_auth/models.py index 03e076eb35..fddbaeb3cd 100644 --- a/openedx/core/djangoapps/external_auth/models.py +++ b/openedx/core/djangoapps/external_auth/models.py @@ -9,8 +9,8 @@ file and check it in at the same time as your model changes. To do that, 3. Add the migration file created in edx-platform/openedx/core/djangoapps/external_auth/migrations/ """ -from django.db import models from django.contrib.auth.models import User +from django.db import models class ExternalAuthMap(models.Model): diff --git a/openedx/core/djangoapps/external_auth/views.py b/openedx/core/djangoapps/external_auth/views.py index c38e8b7ceb..d2fdb3e3d7 100644 --- a/openedx/core/djangoapps/external_auth/views.py +++ b/openedx/core/djangoapps/external_auth/views.py @@ -1,53 +1,47 @@ """ External Auth Views """ +import fnmatch import functools import json import logging import random import re import string -import fnmatch import unicodedata import urllib - from textwrap import dedent -from openedx.core.djangoapps.external_auth.models import ExternalAuthMap -from openedx.core.djangoapps.external_auth.djangostore import DjangoOpenIDStore +import django_openid_auth.views as openid_views from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME, authenticate, login from django.contrib.auth.models import User +from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.core.validators import validate_email -from django.core.exceptions import ValidationError - -if settings.FEATURES.get('AUTH_USE_CAS'): - from django_cas.views import login as django_cas_login - -from student.helpers import get_next_url_for_login_page -from student.models import UserProfile - -from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden -from django.utils.http import urlquote, is_safe_url +from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect from django.shortcuts import redirect +from django.utils.http import is_safe_url, urlquote from django.utils.translation import ugettext as _ - -from edxmako.shortcuts import render_to_response, render_to_string from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie - -import django_openid_auth.views as openid_views from django_openid_auth import auth as openid_auth +from opaque_keys.edx.locations import SlashSeparatedCourseKey from openid.consumer.consumer import SUCCESS - -from openid.server.server import Server, ProtocolError, UntrustedReturnURL -from openid.server.trustroot import TrustRoot from openid.extensions import ax, sreg +from openid.server.server import ProtocolError, Server, UntrustedReturnURL +from openid.server.trustroot import TrustRoot from ratelimitbackend.exceptions import RateLimitException import student.views +from edxmako.shortcuts import render_to_response, render_to_string +from openedx.core.djangoapps.external_auth.djangostore import DjangoOpenIDStore +from openedx.core.djangoapps.external_auth.models import ExternalAuthMap +from student.helpers import get_next_url_for_login_page +from student.models import UserProfile from xmodule.modulestore.django import modulestore -from opaque_keys.edx.locations import SlashSeparatedCourseKey + +if settings.FEATURES.get('AUTH_USE_CAS'): + from django_cas.views import login as django_cas_login log = logging.getLogger("edx.external_auth") AUDIT_LOG = logging.getLogger("audit") diff --git a/openedx/core/djangoapps/geoinfo/middleware.py b/openedx/core/djangoapps/geoinfo/middleware.py index 1f648d6d2d..d256501777 100644 --- a/openedx/core/djangoapps/geoinfo/middleware.py +++ b/openedx/core/djangoapps/geoinfo/middleware.py @@ -11,10 +11,11 @@ decorator `django.utils.decorators.decorator_from_middleware(middleware_class)` """ import logging -import pygeoip -from ipware.ip import get_real_ip from django.conf import settings +from ipware.ip import get_real_ip + +import pygeoip log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/header_control/decorators.py b/openedx/core/djangoapps/header_control/decorators.py index 34f37951e5..2f33901da3 100644 --- a/openedx/core/djangoapps/header_control/decorators.py +++ b/openedx/core/djangoapps/header_control/decorators.py @@ -3,7 +3,8 @@ Middleware decorator for removing headers. """ from functools import wraps -from openedx.core.djangoapps.header_control import remove_headers_from_response, force_header_for_response + +from openedx.core.djangoapps.header_control import force_header_for_response, remove_headers_from_response def remove_headers(*headers): diff --git a/openedx/core/djangoapps/heartbeat/urls.py b/openedx/core/djangoapps/heartbeat/urls.py index 6648dfc56d..10cc72487c 100644 --- a/openedx/core/djangoapps/heartbeat/urls.py +++ b/openedx/core/djangoapps/heartbeat/urls.py @@ -1,7 +1,7 @@ """ Urls for verifying health (heartbeat) of the app. """ -from django.conf.urls import url, patterns +from django.conf.urls import patterns, url urlpatterns = patterns( '', diff --git a/openedx/core/djangoapps/heartbeat/views.py b/openedx/core/djangoapps/heartbeat/views.py index e61b986e09..5128618e26 100644 --- a/openedx/core/djangoapps/heartbeat/views.py +++ b/openedx/core/djangoapps/heartbeat/views.py @@ -1,12 +1,13 @@ """ Views for verifying the health (heartbeat) of the app. """ -from xmodule.modulestore.django import modulestore -from dogapi import dog_stats_api -from util.json_request import JsonResponse from django.db import connection from django.db.utils import DatabaseError +from dogapi import dog_stats_api + +from util.json_request import JsonResponse from xmodule.exceptions import HeartbeatFailure +from xmodule.modulestore.django import modulestore @dog_stats_api.timed('edxapp.heartbeat') diff --git a/openedx/core/djangoapps/lang_pref/api.py b/openedx/core/djangoapps/lang_pref/api.py index 9ff4312065..27df7fd7ab 100644 --- a/openedx/core/djangoapps/lang_pref/api.py +++ b/openedx/core/djangoapps/lang_pref/api.py @@ -9,7 +9,6 @@ from django.utils.translation import ugettext as _ from openedx.core.djangoapps.dark_lang.models import DarkLangConfig from openedx.core.djangoapps.site_configuration.helpers import get_value - # Named tuples can be referenced using object-like variable # deferencing, making the use of tuples more readable by # eliminating the need to see the context of the tuple packing. diff --git a/openedx/core/djangoapps/lang_pref/middleware.py b/openedx/core/djangoapps/lang_pref/middleware.py index 0759337ab7..f144ac69e7 100644 --- a/openedx/core/djangoapps/lang_pref/middleware.py +++ b/openedx/core/djangoapps/lang_pref/middleware.py @@ -6,13 +6,13 @@ from django.conf import settings from django.utils.translation import LANGUAGE_SESSION_KEY from django.utils.translation.trans_real import parse_accept_lang_header -from openedx.core.djangoapps.lang_pref import ( - LANGUAGE_KEY, LANGUAGE_HEADER, COOKIE_DURATION -) -from openedx.core.djangoapps.user_api.preferences.api import ( - get_user_preference, delete_user_preference, set_user_preference -) +from openedx.core.djangoapps.lang_pref import COOKIE_DURATION, LANGUAGE_HEADER, LANGUAGE_KEY from openedx.core.djangoapps.user_api.errors import UserAPIInternalError, UserAPIRequestError +from openedx.core.djangoapps.user_api.preferences.api import ( + delete_user_preference, + get_user_preference, + set_user_preference +) class LanguagePreferenceMiddleware(object): diff --git a/openedx/core/djangoapps/lang_pref/views.py b/openedx/core/djangoapps/lang_pref/views.py index cd47008c8a..e86760b834 100644 --- a/openedx/core/djangoapps/lang_pref/views.py +++ b/openedx/core/djangoapps/lang_pref/views.py @@ -6,10 +6,10 @@ import json from django.conf import settings from django.http import HttpResponse -from django.views.decorators.csrf import ensure_csrf_cookie from django.utils.translation import LANGUAGE_SESSION_KEY +from django.views.decorators.csrf import ensure_csrf_cookie -from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY, COOKIE_DURATION +from openedx.core.djangoapps.lang_pref import COOKIE_DURATION, LANGUAGE_KEY @ensure_csrf_cookie diff --git a/openedx/core/djangoapps/monitoring/exceptions.py b/openedx/core/djangoapps/monitoring/exceptions.py index 2704324938..7006db11e7 100644 --- a/openedx/core/djangoapps/monitoring/exceptions.py +++ b/openedx/core/djangoapps/monitoring/exceptions.py @@ -1,9 +1,10 @@ """ Signal handler for exceptions. """ +import logging + from django.core.signals import got_request_exception from django.dispatch import receiver -import logging @receiver(got_request_exception) diff --git a/openedx/core/djangoapps/monitoring_utils/tests.py b/openedx/core/djangoapps/monitoring_utils/tests.py index 4410e234a3..16763b45e8 100644 --- a/openedx/core/djangoapps/monitoring_utils/tests.py +++ b/openedx/core/djangoapps/monitoring_utils/tests.py @@ -2,7 +2,7 @@ Tests for monitoring custom metrics. """ from django.test import TestCase -from mock import patch, call +from mock import call, patch from openedx.core.djangoapps import monitoring_utils from openedx.core.djangoapps.monitoring_utils.middleware import MonitoringCustomMetrics diff --git a/openedx/core/djangoapps/oauth_dispatch/dot_overrides.py b/openedx/core/djangoapps/oauth_dispatch/dot_overrides.py index 69db994dcb..0e8ff6ffdc 100644 --- a/openedx/core/djangoapps/oauth_dispatch/dot_overrides.py +++ b/openedx/core/djangoapps/oauth_dispatch/dot_overrides.py @@ -3,16 +3,16 @@ Classes that override default django-oauth-toolkit behavior """ from __future__ import unicode_literals -from .models import RestrictedApplication - from datetime import datetime + from django.contrib.auth import authenticate, get_user_model from django.db.models.signals import pre_save from django.dispatch import receiver -from pytz import utc - from oauth2_provider.models import AccessToken from oauth2_provider.oauth2_validators import OAuth2Validator +from pytz import utc + +from .models import RestrictedApplication @receiver(pre_save, sender=AccessToken) diff --git a/openedx/core/djangoapps/oauth_dispatch/models.py b/openedx/core/djangoapps/oauth_dispatch/models.py index 45236c5196..406b69fcc6 100644 --- a/openedx/core/djangoapps/oauth_dispatch/models.py +++ b/openedx/core/djangoapps/oauth_dispatch/models.py @@ -3,10 +3,10 @@ Specialized models for oauth_dispatch djangoapp """ from datetime import datetime -from django.db import models -from pytz import utc +from django.db import models from oauth2_provider.settings import oauth2_settings +from pytz import utc class RestrictedApplication(models.Model): diff --git a/openedx/core/djangoapps/oauth_dispatch/urls.py b/openedx/core/djangoapps/oauth_dispatch/urls.py index 9da7b5125b..0811b68d34 100644 --- a/openedx/core/djangoapps/oauth_dispatch/urls.py +++ b/openedx/core/djangoapps/oauth_dispatch/urls.py @@ -8,7 +8,6 @@ from django.views.decorators.csrf import csrf_exempt from . import views - urlpatterns = patterns( '', url(r'^authorize/?$', csrf_exempt(views.AuthorizationView.as_view()), name='authorize'), diff --git a/openedx/core/djangoapps/oauth_dispatch/views.py b/openedx/core/djangoapps/oauth_dispatch/views.py index 5104a0a602..10889ef2ef 100644 --- a/openedx/core/djangoapps/oauth_dispatch/views.py +++ b/openedx/core/djangoapps/oauth_dispatch/views.py @@ -15,10 +15,12 @@ from django.http import JsonResponse from django.views.generic import View from edx_oauth2_provider import views as dop_views # django-oauth2-provider views from jwkest.jwk import RSAKey -from oauth2_provider import models as dot_models, views as dot_views # django-oauth-toolkit +from oauth2_provider import models as dot_models # django-oauth-toolkit +from oauth2_provider import views as dot_views from openedx.core.djangoapps.auth_exchange import views as auth_exchange_views from openedx.core.lib.token_utils import JwtBuilder + from . import adapters diff --git a/openedx/core/djangoapps/profile_images/images.py b/openedx/core/djangoapps/profile_images/images.py index 1085fb147a..15d7c5c44b 100644 --- a/openedx/core/djangoapps/profile_images/images.py +++ b/openedx/core/djangoapps/profile_images/images.py @@ -1,19 +1,19 @@ """ Image file manipulation functions related to profile images. """ -from cStringIO import StringIO from collections import namedtuple from contextlib import closing +from cStringIO import StringIO +import piexif from django.conf import settings from django.core.files.base import ContentFile from django.utils.translation import ugettext as _ -import piexif from PIL import Image from openedx.core.djangoapps.user_api.accounts.image_helpers import get_profile_image_storage -from .exceptions import ImageValidationError +from .exceptions import ImageValidationError ImageType = namedtuple('ImageType', ('extensions', 'mimetypes', 'magic')) diff --git a/openedx/core/djangoapps/profile_images/urls.py b/openedx/core/djangoapps/profile_images/urls.py index 9f922e59d6..b9307d8cc4 100644 --- a/openedx/core/djangoapps/profile_images/urls.py +++ b/openedx/core/djangoapps/profile_images/urls.py @@ -6,11 +6,10 @@ NOTE: These views are deprecated. These routes are superseded by ``openedx.core.djangoapps.user_api.urls``. """ +from django.conf import settings from django.conf.urls import patterns, url -from .views import ProfileImageUploadView, ProfileImageRemoveView -from django.conf import settings - +from .views import ProfileImageRemoveView, ProfileImageUploadView urlpatterns = patterns( '', diff --git a/openedx/core/djangoapps/profile_images/views.py b/openedx/core/djangoapps/profile_images/views.py index a7dfddc6a4..d4aa052b66 100644 --- a/openedx/core/djangoapps/profile_images/views.py +++ b/openedx/core/djangoapps/profile_images/views.py @@ -1,31 +1,30 @@ """ This module implements the upload and remove endpoints of the profile image api. """ -from contextlib import closing import datetime import itertools import logging +from contextlib import closing -from django.utils.translation import ugettext as _ from django.utils.timezone import utc +from django.utils.translation import ugettext as _ from rest_framework import permissions, status -from rest_framework.parsers import MultiPartParser, FormParser +from rest_framework.parsers import FormParser, MultiPartParser from rest_framework.response import Response from rest_framework.views import APIView +from openedx.core.djangoapps.user_api.accounts.image_helpers import get_profile_image_names, set_has_profile_image from openedx.core.djangoapps.user_api.errors import UserNotFound from openedx.core.lib.api.authentication import ( OAuth2AuthenticationAllowInactiveUser, - SessionAuthenticationAllowInactiveUser, + SessionAuthenticationAllowInactiveUser ) from openedx.core.lib.api.parsers import TypedFileUploadParser from openedx.core.lib.api.permissions import IsUserInUrl from openedx.core.lib.api.view_utils import DeveloperErrorViewMixin -from openedx.core.djangoapps.user_api.accounts.image_helpers import get_profile_image_names, set_has_profile_image + from .exceptions import ImageValidationError -from .images import ( - IMAGE_TYPES, validate_uploaded_image, create_profile_images, remove_profile_images -) +from .images import IMAGE_TYPES, create_profile_images, remove_profile_images, validate_uploaded_image log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/programs/admin.py b/openedx/core/djangoapps/programs/admin.py index 0676e93ad4..97be43e64b 100644 --- a/openedx/core/djangoapps/programs/admin.py +++ b/openedx/core/djangoapps/programs/admin.py @@ -1,9 +1,8 @@ """ django admin pages for program support models """ -from django.contrib import admin - from config_models.admin import ConfigurationModelAdmin +from django.contrib import admin from openedx.core.djangoapps.programs.models import ProgramsApiConfig diff --git a/openedx/core/djangoapps/programs/models.py b/openedx/core/djangoapps/programs/models.py index decec1dfe2..58ebad0529 100644 --- a/openedx/core/djangoapps/programs/models.py +++ b/openedx/core/djangoapps/programs/models.py @@ -1,10 +1,9 @@ """Models providing Programs support for the LMS and Studio.""" from urlparse import urljoin -from django.utils.translation import ugettext_lazy as _ -from django.db import models - from config_models.models import ConfigurationModel +from django.db import models +from django.utils.translation import ugettext_lazy as _ class ProgramsApiConfig(ConfigurationModel): diff --git a/openedx/core/djangoapps/programs/signals.py b/openedx/core/djangoapps/programs/signals.py index 56d5d85b17..da63c9b9c2 100644 --- a/openedx/core/djangoapps/programs/signals.py +++ b/openedx/core/djangoapps/programs/signals.py @@ -7,7 +7,6 @@ from django.dispatch import receiver from openedx.core.djangoapps.signals.signals import COURSE_CERT_AWARDED - LOGGER = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/programs/utils.py b/openedx/core/djangoapps/programs/utils.py index 44aecaf177..6cf250ec7b 100644 --- a/openedx/core/djangoapps/programs/utils.py +++ b/openedx/core/djangoapps/programs/utils.py @@ -1,8 +1,9 @@ # -*- coding: utf-8 -*- """Helper functions for working with Programs.""" +import datetime from collections import defaultdict from copy import deepcopy -import datetime +from itertools import chain from urlparse import urljoin from dateutil.parser import parse @@ -12,7 +13,6 @@ from django.core.urlresolvers import reverse from django.utils.functional import cached_property from opaque_keys.edx.keys import CourseKey from pytz import utc -from itertools import chain from course_modes.models import CourseMode from lms.djangoapps.certificates import api as certificate_api @@ -25,7 +25,6 @@ from student.models import CourseEnrollment from util.date_utils import strftime_localized from xmodule.modulestore.django import modulestore - # The datetime module's strftime() methods require a year >= 1900. DEFAULT_ENROLLMENT_START_DATE = datetime.datetime(1900, 1, 1, tzinfo=utc) diff --git a/openedx/core/djangoapps/safe_sessions/middleware.py b/openedx/core/djangoapps/safe_sessions/middleware.py index 6285167d57..2b8869e405 100644 --- a/openedx/core/djangoapps/safe_sessions/middleware.py +++ b/openedx/core/djangoapps/safe_sessions/middleware.py @@ -57,6 +57,9 @@ the entire cookie and use it to impersonate the victim. """ from contextlib import contextmanager +from hashlib import sha256 +from logging import ERROR, getLogger + from django.conf import settings from django.contrib.auth import SESSION_KEY from django.contrib.auth.views import redirect_to_login @@ -64,8 +67,6 @@ from django.contrib.sessions.middleware import SessionMiddleware from django.core import signing from django.http import HttpResponse from django.utils.crypto import get_random_string -from hashlib import sha256 -from logging import getLogger, ERROR from openedx.core.lib.mobile_utils import is_request_from_mobile_app diff --git a/openedx/core/djangoapps/self_paced/admin.py b/openedx/core/djangoapps/self_paced/admin.py index ae85d9343f..0745cc57b8 100644 --- a/openedx/core/djangoapps/self_paced/admin.py +++ b/openedx/core/djangoapps/self_paced/admin.py @@ -2,9 +2,9 @@ Admin site bindings for self-paced courses. """ +from config_models.admin import ConfigurationModelAdmin from django.contrib import admin -from config_models.admin import ConfigurationModelAdmin from .models import SelfPacedConfiguration admin.site.register(SelfPacedConfiguration, ConfigurationModelAdmin) diff --git a/openedx/core/djangoapps/self_paced/models.py b/openedx/core/djangoapps/self_paced/models.py index 35d41f979f..e01f8be8b2 100644 --- a/openedx/core/djangoapps/self_paced/models.py +++ b/openedx/core/djangoapps/self_paced/models.py @@ -2,11 +2,10 @@ Configuration for self-paced courses. """ +from config_models.models import ConfigurationModel from django.db.models import BooleanField from django.utils.translation import ugettext_lazy as _ -from config_models.models import ConfigurationModel - class SelfPacedConfiguration(ConfigurationModel): """ diff --git a/openedx/core/djangoapps/service_status/tasks.py b/openedx/core/djangoapps/service_status/tasks.py index 40367120b2..5ff7a6aab7 100644 --- a/openedx/core/djangoapps/service_status/tasks.py +++ b/openedx/core/djangoapps/service_status/tasks.py @@ -4,9 +4,8 @@ Django Celery tasks for service status app import time -from dogapi import dog_stats_api - from djcelery import celery +from dogapi import dog_stats_api @celery.task diff --git a/openedx/core/djangoapps/service_status/test.py b/openedx/core/djangoapps/service_status/test.py index b80c836daf..1f39e45b53 100644 --- a/openedx/core/djangoapps/service_status/test.py +++ b/openedx/core/djangoapps/service_status/test.py @@ -1,10 +1,11 @@ """Test for async task service status""" -from django.utils import unittest -from django.test.client import Client -from django.core.urlresolvers import reverse import json +from django.core.urlresolvers import reverse +from django.test.client import Client +from django.utils import unittest + class CeleryConfigTest(unittest.TestCase): """ diff --git a/openedx/core/djangoapps/service_status/urls.py b/openedx/core/djangoapps/service_status/urls.py index a5c388f582..cd46da4ebd 100644 --- a/openedx/core/djangoapps/service_status/urls.py +++ b/openedx/core/djangoapps/service_status/urls.py @@ -4,7 +4,6 @@ Django URLs for service status app from django.conf.urls import patterns, url - urlpatterns = patterns( '', url(r'^$', 'openedx.core.djangoapps.service_status.views.index', name='status.service.index'), diff --git a/openedx/core/djangoapps/service_status/views.py b/openedx/core/djangoapps/service_status/views.py index e0db84010b..db0f0b3bb9 100644 --- a/openedx/core/djangoapps/service_status/views.py +++ b/openedx/core/djangoapps/service_status/views.py @@ -5,12 +5,10 @@ Django Views for service status app import json import time -from django.http import HttpResponse - -from dogapi import dog_stats_api - -from djcelery import celery from celery.exceptions import TimeoutError +from django.http import HttpResponse +from djcelery import celery +from dogapi import dog_stats_api from openedx.core.djangoapps.service_status.tasks import delayed_ping diff --git a/openedx/core/djangoapps/session_inactivity_timeout/middleware.py b/openedx/core/djangoapps/session_inactivity_timeout/middleware.py index 1473d3cef8..5ca4b1747c 100644 --- a/openedx/core/djangoapps/session_inactivity_timeout/middleware.py +++ b/openedx/core/djangoapps/session_inactivity_timeout/middleware.py @@ -9,6 +9,7 @@ To enable this feature, set in a settings.py: This was taken from StackOverflow (http://stackoverflow.com/questions/14830669/how-to-expire-django-session-in-5minutes) """ from datetime import datetime, timedelta + from django.conf import settings from django.contrib import auth diff --git a/openedx/core/djangoapps/signals/signals.py b/openedx/core/djangoapps/signals/signals.py index b232e70fb8..c50a3efce3 100644 --- a/openedx/core/djangoapps/signals/signals.py +++ b/openedx/core/djangoapps/signals/signals.py @@ -4,7 +4,6 @@ This module contains all signals. from django.dispatch import Signal - # Signal that fires when a user is graded COURSE_GRADE_CHANGED = Signal(providing_args=["user", "course_grade", "course_key", "deadline"]) diff --git a/openedx/core/djangoapps/site_configuration/admin.py b/openedx/core/djangoapps/site_configuration/admin.py index 956a3ec034..670b1c3592 100644 --- a/openedx/core/djangoapps/site_configuration/admin.py +++ b/openedx/core/djangoapps/site_configuration/admin.py @@ -3,10 +3,7 @@ Django admin page for Site Configuration models """ from django.contrib import admin -from .models import ( - SiteConfiguration, - SiteConfigurationHistory, -) +from .models import SiteConfiguration, SiteConfigurationHistory class SiteConfigurationAdmin(admin.ModelAdmin): diff --git a/openedx/core/djangoapps/site_configuration/helpers.py b/openedx/core/djangoapps/site_configuration/helpers.py index 8cc61d1652..559cc36f3d 100644 --- a/openedx/core/djangoapps/site_configuration/helpers.py +++ b/openedx/core/djangoapps/site_configuration/helpers.py @@ -2,8 +2,9 @@ Helpers methods for site configuration. """ from django.conf import settings -from openedx.core.djangoapps.site_configuration.models import SiteConfiguration + from microsite_configuration import microsite +from openedx.core.djangoapps.site_configuration.models import SiteConfiguration def get_current_site_configuration(): diff --git a/openedx/core/djangoapps/site_configuration/middleware.py b/openedx/core/djangoapps/site_configuration/middleware.py index 3df414c7f0..60e7ef6cd0 100644 --- a/openedx/core/djangoapps/site_configuration/middleware.py +++ b/openedx/core/djangoapps/site_configuration/middleware.py @@ -3,6 +3,7 @@ This file contains Django middleware related to the site_configuration app. """ from django.conf import settings + from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers diff --git a/openedx/core/djangoapps/site_configuration/models.py b/openedx/core/djangoapps/site_configuration/models.py index cb6fbde5c2..d22d4e8495 100644 --- a/openedx/core/djangoapps/site_configuration/models.py +++ b/openedx/core/djangoapps/site_configuration/models.py @@ -2,17 +2,15 @@ Django models for site configurations. """ import collections +from logging import getLogger -from django.db import models from django.contrib.sites.models import Site +from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver - from django_extensions.db.models import TimeStampedModel from jsonfield.fields import JSONField - -from logging import getLogger logger = getLogger(__name__) # pylint: disable=invalid-name diff --git a/openedx/core/djangoapps/theming/admin.py b/openedx/core/djangoapps/theming/admin.py index 690016f8c8..f8bce31414 100644 --- a/openedx/core/djangoapps/theming/admin.py +++ b/openedx/core/djangoapps/theming/admin.py @@ -3,9 +3,7 @@ Django admin page for theming models """ from django.contrib import admin -from .models import ( - SiteTheme, -) +from .models import SiteTheme class SiteThemeAdmin(admin.ModelAdmin): diff --git a/openedx/core/djangoapps/theming/core.py b/openedx/core/djangoapps/theming/core.py index 5004686d50..d2e68c7dd1 100644 --- a/openedx/core/djangoapps/theming/core.py +++ b/openedx/core/djangoapps/theming/core.py @@ -1,12 +1,13 @@ """ Core logic for Comprehensive Theming. """ +from logging import getLogger + from django.conf import settings from path import Path as path from .helpers import get_themes -from logging import getLogger logger = getLogger(__name__) # pylint: disable=invalid-name diff --git a/openedx/core/djangoapps/theming/helpers.py b/openedx/core/djangoapps/theming/helpers.py index c7b241f988..16b93c02be 100644 --- a/openedx/core/djangoapps/theming/helpers.py +++ b/openedx/core/djangoapps/theming/helpers.py @@ -1,19 +1,18 @@ """ Helpers for accessing comprehensive theming related variables. """ -import re import os -from path import Path +import re +from logging import getLogger -from django.conf import settings, ImproperlyConfigured +from django.conf import ImproperlyConfigured, settings from django.contrib.staticfiles.storage import staticfiles_storage - -from request_cache.middleware import RequestCache +from path import Path from microsite_configuration import microsite from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers +from request_cache.middleware import RequestCache -from logging import getLogger logger = getLogger(__name__) # pylint: disable=invalid-name diff --git a/openedx/core/djangoapps/theming/middleware.py b/openedx/core/djangoapps/theming/middleware.py index 3bfc1216e2..bb4b0970ef 100644 --- a/openedx/core/djangoapps/theming/middleware.py +++ b/openedx/core/djangoapps/theming/middleware.py @@ -6,6 +6,7 @@ Note: So it must be added to INSTALLED_APPS in django settings files. """ from django.conf import settings + from openedx.core.djangoapps.theming.models import SiteTheme diff --git a/openedx/core/djangoapps/theming/models.py b/openedx/core/djangoapps/theming/models.py index a3ab9ba1d8..9efc21a3c0 100644 --- a/openedx/core/djangoapps/theming/models.py +++ b/openedx/core/djangoapps/theming/models.py @@ -1,9 +1,9 @@ """ Django models supporting the Comprehensive Theming subsystem """ -from django.db import models from django.conf import settings from django.contrib.sites.models import Site +from django.db import models class SiteTheme(models.Model): diff --git a/openedx/core/djangoapps/theming/storage.py b/openedx/core/djangoapps/theming/storage.py index af565c7c71..31d5a6671e 100644 --- a/openedx/core/djangoapps/theming/storage.py +++ b/openedx/core/djangoapps/theming/storage.py @@ -2,24 +2,22 @@ Comprehensive Theming support for Django's collectstatic functionality. See https://docs.djangoproject.com/en/1.8/ref/contrib/staticfiles/ """ -import posixpath import os.path -from django.conf import settings -from django.utils._os import safe_join -from django.contrib.staticfiles.storage import StaticFilesStorage, CachedFilesMixin -from django.contrib.staticfiles.finders import find -from django.utils.six.moves.urllib.parse import ( # pylint: disable=no-name-in-module, import-error - unquote, urlsplit, -) +import posixpath +from django.conf import settings +from django.contrib.staticfiles.finders import find +from django.contrib.staticfiles.storage import CachedFilesMixin, StaticFilesStorage +from django.utils._os import safe_join +from django.utils.six.moves.urllib.parse import unquote, urlsplit # pylint: disable=no-name-in-module, import-error from pipeline.storage import PipelineMixin from openedx.core.djangoapps.theming.helpers import ( - get_theme_base_dir, - get_project_root_name, get_current_theme, + get_project_root_name, + get_theme_base_dir, get_themes, - is_comprehensive_theming_enabled, + is_comprehensive_theming_enabled ) diff --git a/openedx/core/djangoapps/theming/template_loaders.py b/openedx/core/djangoapps/theming/template_loaders.py index 198388fa8c..8315d98861 100644 --- a/openedx/core/djangoapps/theming/template_loaders.py +++ b/openedx/core/djangoapps/theming/template_loaders.py @@ -1,13 +1,12 @@ """ Theming aware template loaders. """ -from django.utils._os import safe_join from django.core.exceptions import SuspiciousFileOperation from django.template.loaders.filesystem import Loader as FilesystemLoader +from django.utils._os import safe_join from edxmako.makoloader import MakoLoader -from openedx.core.djangoapps.theming.helpers import get_current_request, \ - get_current_theme, get_all_theme_template_dirs +from openedx.core.djangoapps.theming.helpers import get_all_theme_template_dirs, get_current_request, get_current_theme class ThemeTemplateLoader(MakoLoader): diff --git a/openedx/core/djangoapps/user_api/helpers.py b/openedx/core/djangoapps/user_api/helpers.py index d9459b1f59..92a7bb7a8b 100644 --- a/openedx/core/djangoapps/user_api/helpers.py +++ b/openedx/core/djangoapps/user_api/helpers.py @@ -2,11 +2,11 @@ Helper functions for the account/profile Python APIs. This is NOT part of the public API. """ +import json +import logging +import traceback from collections import defaultdict from functools import wraps -import logging -import json -import traceback from django import forms from django.core.serializers.json import DjangoJSONEncoder diff --git a/openedx/core/djangoapps/user_api/middleware.py b/openedx/core/djangoapps/user_api/middleware.py index 144ab8220e..1c529153fd 100644 --- a/openedx/core/djangoapps/user_api/middleware.py +++ b/openedx/core/djangoapps/user_api/middleware.py @@ -3,10 +3,10 @@ Middleware for user api. Adds user's tags to tracking event context. """ -from eventtracking import tracker from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey +from eventtracking import tracker from track.contexts import COURSE_REGEX from .models import UserCourseTag diff --git a/openedx/core/djangoapps/user_api/models.py b/openedx/core/djangoapps/user_api/models.py index a8e6162cd3..5729d92702 100644 --- a/openedx/core/djangoapps/user_api/models.py +++ b/openedx/core/djangoapps/user_api/models.py @@ -4,20 +4,19 @@ Django ORM model specifications for the User API application from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.db import models -from django.db.models.signals import post_delete, pre_save, post_save +from django.db.models.signals import post_delete, post_save, pre_save from django.dispatch import receiver from model_utils.models import TimeStampedModel -from util.model_utils import get_changed_fields_dict, emit_setting_changed_event from openedx.core.djangoapps.xmodule_django.models import CourseKeyField - # Currently, the "student" app is responsible for # accounts, profiles, enrollments, and the student dashboard. # We are trying to move some of this functionality into separate apps, # but currently the rest of the system assumes that "student" defines # certain models. For now we will leave the models in "student" and # create an alias in "user_api". -from student.models import UserProfile, Registration, PendingEmailChange # pylint: disable=unused-import +from student.models import PendingEmailChange, Registration, UserProfile # pylint: disable=unused-import +from util.model_utils import emit_setting_changed_event, get_changed_fields_dict class UserPreference(models.Model): diff --git a/openedx/core/djangoapps/user_api/urls.py b/openedx/core/djangoapps/user_api/urls.py index d6ccbf329f..38891f488e 100644 --- a/openedx/core/djangoapps/user_api/urls.py +++ b/openedx/core/djangoapps/user_api/urls.py @@ -7,7 +7,7 @@ from django.conf.urls import patterns, url from ..profile_images.views import ProfileImageView from .accounts.views import AccountDeactivationView, AccountViewSet -from .preferences.views import PreferencesView, PreferencesDetailView +from .preferences.views import PreferencesDetailView, PreferencesView from .verification_api.views import PhotoVerificationStatusView ME = AccountViewSet.as_view({ diff --git a/openedx/core/djangoapps/user_api/views.py b/openedx/core/djangoapps/user_api/views.py index 3730468da9..f35bc6da1a 100644 --- a/openedx/core/djangoapps/user_api/views.py +++ b/openedx/core/djangoapps/user_api/views.py @@ -1,45 +1,47 @@ """HTTP end-points for the User API. """ import copy -from opaque_keys import InvalidKeyError from django.conf import settings from django.contrib.auth.models import User -from django.http import HttpResponse, HttpResponseForbidden +from django.core.exceptions import NON_FIELD_ERRORS, ImproperlyConfigured, PermissionDenied, ValidationError from django.core.urlresolvers import reverse -from django.core.exceptions import ImproperlyConfigured, NON_FIELD_ERRORS, ValidationError, PermissionDenied -from django.utils.translation import ugettext as _ +from django.http import HttpResponse, HttpResponseForbidden from django.utils.decorators import method_decorator -from django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect, csrf_exempt -from opaque_keys.edx import locator -from rest_framework import authentication -from rest_framework import filters -from rest_framework import generics -from rest_framework import status -from rest_framework import viewsets -from rest_framework.views import APIView -from rest_framework.exceptions import ParseError +from django.utils.translation import ugettext as _ +from django.views.decorators.csrf import csrf_exempt, csrf_protect, ensure_csrf_cookie from django_countries import countries +from opaque_keys import InvalidKeyError +from opaque_keys.edx import locator from opaque_keys.edx.locations import SlashSeparatedCourseKey +from rest_framework import authentication, filters, generics, status, viewsets +from rest_framework.exceptions import ParseError +from rest_framework.views import APIView -from openedx.core.lib.api.permissions import ApiKeyHeaderPermission import third_party_auth from django_comment_common.models import Role from edxmako.shortcuts import marketing_link -from student.forms import get_registration_extension_form -from student.views import create_account_with_params -from student.cookies import set_logged_in_cookies from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.lib.api.authentication import SessionAuthenticationAllowInactiveUser +from openedx.core.lib.api.permissions import ApiKeyHeaderPermission +from student.cookies import set_logged_in_cookies +from student.forms import get_registration_extension_form +from student.views import create_account_with_params from util.json_request import JsonResponse -from .preferences.api import get_country_time_zones, update_email_opt_in -from .helpers import FormDescription, shim_student_view, require_post_params -from .models import UserPreference, UserProfile + from .accounts import ( - NAME_MAX_LENGTH, EMAIL_MIN_LENGTH, EMAIL_MAX_LENGTH, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH, - USERNAME_MIN_LENGTH, USERNAME_MAX_LENGTH + EMAIL_MAX_LENGTH, + EMAIL_MIN_LENGTH, + NAME_MAX_LENGTH, + PASSWORD_MAX_LENGTH, + PASSWORD_MIN_LENGTH, + USERNAME_MAX_LENGTH, + USERNAME_MIN_LENGTH ) from .accounts.api import check_account_exists -from .serializers import CountryTimeZoneSerializer, UserSerializer, UserPreferenceSerializer +from .helpers import FormDescription, require_post_params, shim_student_view +from .models import UserPreference, UserProfile +from .preferences.api import get_country_time_zones, update_email_opt_in +from .serializers import CountryTimeZoneSerializer, UserPreferenceSerializer, UserSerializer class LoginSessionView(APIView): diff --git a/openedx/core/djangoapps/verified_track_content/forms.py b/openedx/core/djangoapps/verified_track_content/forms.py index 53eddf9719..bd82973900 100644 --- a/openedx/core/djangoapps/verified_track_content/forms.py +++ b/openedx/core/djangoapps/verified_track_content/forms.py @@ -2,14 +2,12 @@ Forms for configuring courses for verified track cohorting """ from django import forms - from django.utils.translation import ugettext as _ - -from xmodule.modulestore.django import modulestore from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from openedx.core.djangoapps.verified_track_content.models import VerifiedTrackCohortedCourse +from xmodule.modulestore.django import modulestore class VerifiedTrackCourseForm(forms.ModelForm): diff --git a/openedx/core/djangoapps/verified_track_content/models.py b/openedx/core/djangoapps/verified_track_content/models.py index 8c96960261..62b677aeb3 100644 --- a/openedx/core/djangoapps/verified_track_content/models.py +++ b/openedx/core/djangoapps/verified_track_content/models.py @@ -1,21 +1,24 @@ """ Models for verified track selections. """ -from django.db import models -from django.utils.translation import ugettext_lazy -from django.dispatch import receiver -from django.db.models.signals import post_save, pre_save import logging -from lms.djangoapps.courseware.courses import get_course_by_id -from openedx.core.djangoapps.xmodule_django.models import CourseKeyField -from openedx.core.djangoapps.verified_track_content.tasks import sync_cohort_with_mode -from openedx.core.djangoapps.course_groups.cohorts import ( - get_course_cohorts, CourseCohort, is_course_cohorted, get_random_cohort -) -from request_cache.middleware import ns_request_cached, RequestCache -from student.models import CourseEnrollment +from django.db import models +from django.db.models.signals import post_save, pre_save +from django.dispatch import receiver +from django.utils.translation import ugettext_lazy +from lms.djangoapps.courseware.courses import get_course_by_id +from openedx.core.djangoapps.course_groups.cohorts import ( + CourseCohort, + get_course_cohorts, + get_random_cohort, + is_course_cohorted +) +from openedx.core.djangoapps.verified_track_content.tasks import sync_cohort_with_mode +from openedx.core.djangoapps.xmodule_django.models import CourseKeyField +from request_cache.middleware import RequestCache, ns_request_cached +from student.models import CourseEnrollment log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/verified_track_content/tasks.py b/openedx/core/djangoapps/verified_track_content/tasks.py index f646460972..bca6f0ab1c 100644 --- a/openedx/core/djangoapps/verified_track_content/tasks.py +++ b/openedx/core/djangoapps/verified_track_content/tasks.py @@ -1,16 +1,13 @@ """ Celery task for Automatic Verifed Track Cohorting MVP feature. """ -from django.contrib.auth.models import User - from celery.task import task from celery.utils.log import get_task_logger - +from django.contrib.auth.models import User from opaque_keys.edx.keys import CourseKey + +from openedx.core.djangoapps.course_groups.cohorts import add_user_to_cohort, get_cohort, get_cohort_by_name from student.models import CourseEnrollment, CourseMode -from openedx.core.djangoapps.course_groups.cohorts import ( - get_cohort_by_name, get_cohort, add_user_to_cohort -) LOGGER = get_task_logger(__name__) diff --git a/openedx/core/djangoapps/verified_track_content/views.py b/openedx/core/djangoapps/verified_track_content/views.py index 4067a87a34..389b0b29da 100644 --- a/openedx/core/djangoapps/verified_track_content/views.py +++ b/openedx/core/djangoapps/verified_track_content/views.py @@ -2,13 +2,12 @@ View methods for verified track content. """ -from util.json_request import expect_json, JsonResponse from django.contrib.auth.decorators import login_required - from opaque_keys.edx.keys import CourseKey -from lms.djangoapps.courseware.courses import get_course_with_access +from lms.djangoapps.courseware.courses import get_course_with_access from openedx.core.djangoapps.verified_track_content.models import VerifiedTrackCohortedCourse +from util.json_request import JsonResponse, expect_json @expect_json diff --git a/openedx/core/djangoapps/video_config/admin.py b/openedx/core/djangoapps/video_config/admin.py index dbc56de70b..521524fcf5 100644 --- a/openedx/core/djangoapps/video_config/admin.py +++ b/openedx/core/djangoapps/video_config/admin.py @@ -2,8 +2,8 @@ Django admin dashboard configuration for Video XModule. """ -from django.contrib import admin from config_models.admin import ConfigurationModelAdmin, KeyedConfigurationModelAdmin +from django.contrib import admin from openedx.core.djangoapps.video_config.forms import CourseHLSPlaybackFlagAdminForm from openedx.core.djangoapps.video_config.models import CourseHLSPlaybackEnabledFlag, HLSPlaybackEnabledFlag diff --git a/openedx/core/djangoapps/video_config/forms.py b/openedx/core/djangoapps/video_config/forms.py index 30ce6cea0b..93aab18a87 100644 --- a/openedx/core/djangoapps/video_config/forms.py +++ b/openedx/core/djangoapps/video_config/forms.py @@ -4,12 +4,11 @@ Defines a form for providing validation of HLS Playback course-specific configur import logging from django import forms +from opaque_keys import InvalidKeyError +from opaque_keys.edx.locator import CourseLocator from openedx.core.djangoapps.video_config.models import CourseHLSPlaybackEnabledFlag - -from opaque_keys import InvalidKeyError from xmodule.modulestore.django import modulestore -from opaque_keys.edx.locator import CourseLocator log = logging.getLogger(__name__) diff --git a/openedx/core/djangoapps/xmodule_django/models.py b/openedx/core/djangoapps/xmodule_django/models.py index b82c60875c..af4cc61dcd 100644 --- a/openedx/core/djangoapps/xmodule_django/models.py +++ b/openedx/core/djangoapps/xmodule_django/models.py @@ -1,14 +1,14 @@ """ Useful django models for implementing XBlock infrastructure in django. """ -import warnings import logging +import warnings -from django.db import models from django.core.exceptions import ValidationError -from opaque_keys.edx.keys import CourseKey, UsageKey, BlockTypeKey -from xmodule.modulestore.django import modulestore +from django.db import models +from opaque_keys.edx.keys import BlockTypeKey, CourseKey, UsageKey +from xmodule.modulestore.django import modulestore log = logging.getLogger(__name__) diff --git a/openedx/core/djangolib/markup.py b/openedx/core/djangolib/markup.py index 3d8e4fa472..77b081737c 100644 --- a/openedx/core/djangolib/markup.py +++ b/openedx/core/djangolib/markup.py @@ -4,7 +4,6 @@ Utilities for use in Mako markup. import markupsafe - # Text() can be used to declare a string as plain text, as HTML() is used # for HTML. It simply wraps markupsafe's escape, which will HTML-escape if # it isn't already escaped. diff --git a/openedx/core/djangolib/nose.py b/openedx/core/djangolib/nose.py index fb79993986..116456ceda 100644 --- a/openedx/core/djangolib/nose.py +++ b/openedx/core/djangolib/nose.py @@ -1,9 +1,9 @@ """ Utilities related to nose. """ +import django_nose from django.core.management import call_command from django.db import DEFAULT_DB_ALIAS, connections, transaction -import django_nose class NoseTestSuiteRunner(django_nose.NoseTestSuiteRunner): diff --git a/openedx/core/djangolib/testing/utils.py b/openedx/core/djangolib/testing/utils.py index 10d106c403..9d6f1a8e72 100644 --- a/openedx/core/djangolib/testing/utils.py +++ b/openedx/core/djangolib/testing/utils.py @@ -13,11 +13,11 @@ from unittest import skipUnless import crum from django import db +from django.conf import settings +from django.contrib import sites from django.contrib.auth.models import AnonymousUser from django.core.cache import caches from django.test import RequestFactory, TestCase, override_settings -from django.conf import settings -from django.contrib import sites from nose.plugins import Plugin from request_cache.middleware import RequestCache diff --git a/openedx/core/djangolib/tests/test_js_utils.py b/openedx/core/djangolib/tests/test_js_utils.py index 1de4a91df4..495a211405 100644 --- a/openedx/core/djangolib/tests/test_js_utils.py +++ b/openedx/core/djangolib/tests/test_js_utils.py @@ -2,16 +2,14 @@ """ Tests for js_utils.py """ -import json -from nose.plugins.attrib import attr -from unittest import TestCase import HTMLParser +import json +from unittest import TestCase from mako.template import Template +from nose.plugins.attrib import attr -from openedx.core.djangolib.js_utils import ( - dump_js_escaped_json, js_escaped_string -) +from openedx.core.djangolib.js_utils import dump_js_escaped_json, js_escaped_string @attr(shard=2) diff --git a/openedx/core/djangolib/tests/test_markup.py b/openedx/core/djangolib/tests/test_markup.py index 861d7ca536..cd6b9b01ec 100644 --- a/openedx/core/djangolib/tests/test_markup.py +++ b/openedx/core/djangolib/tests/test_markup.py @@ -3,12 +3,13 @@ Tests for openedx.core.djangolib.markup """ -from nose.plugins.attrib import attr import unittest import ddt -from django.utils.translation import ugettext as _, ungettext +from django.utils.translation import ugettext as _ +from django.utils.translation import ungettext from mako.template import Template +from nose.plugins.attrib import attr from openedx.core.djangolib.markup import HTML, Text diff --git a/openedx/core/djangolib/waffle_utils.py b/openedx/core/djangolib/waffle_utils.py index 5658b9ae33..893e3b107b 100644 --- a/openedx/core/djangolib/waffle_utils.py +++ b/openedx/core/djangolib/waffle_utils.py @@ -1,16 +1,15 @@ """ Utilities for waffle usage. """ +import logging from abc import ABCMeta from contextlib import contextmanager -import logging -from waffle.testutils import override_switch as waffle_override_switch from waffle import switch_is_active +from waffle.testutils import override_switch as waffle_override_switch from request_cache import get_cache as get_request_cache - log = logging.getLogger(__name__) diff --git a/openedx/core/lib/api/authentication.py b/openedx/core/lib/api/authentication.py index 95a296d5b4..283c7becdb 100644 --- a/openedx/core/lib/api/authentication.py +++ b/openedx/core/lib/api/authentication.py @@ -3,16 +3,14 @@ import logging import django.utils.timezone -from rest_framework.authentication import SessionAuthentication +from oauth2_provider import models as dot_models +from provider.oauth2 import models as dop_models from rest_framework import exceptions as drf_exceptions +from rest_framework.authentication import SessionAuthentication from rest_framework_oauth.authentication import OAuth2Authentication -from provider.oauth2 import models as dop_models -from oauth2_provider import models as dot_models - from openedx.core.lib.api.exceptions import AuthenticationFailed - OAUTH2_TOKEN_ERROR = u'token_error' OAUTH2_TOKEN_ERROR_EXPIRED = u'token_expired' OAUTH2_TOKEN_ERROR_MALFORMED = u'token_malformed' diff --git a/openedx/core/lib/api/paginators.py b/openedx/core/lib/api/paginators.py index c332fb6b1c..e94cfe9d5d 100644 --- a/openedx/core/lib/api/paginators.py +++ b/openedx/core/lib/api/paginators.py @@ -1,10 +1,9 @@ """ Paginatator methods for edX API implementations.""" +from django.core.paginator import InvalidPage, Paginator from django.http import Http404 -from django.core.paginator import Paginator, InvalidPage - -from rest_framework.response import Response from rest_framework import pagination +from rest_framework.response import Response class DefaultPagination(pagination.PageNumberPagination): diff --git a/openedx/core/lib/api/permissions.py b/openedx/core/lib/api/permissions.py index 9c70d3cdd4..d15b9c739a 100644 --- a/openedx/core/lib/api/permissions.py +++ b/openedx/core/lib/api/permissions.py @@ -4,13 +4,12 @@ API library for Django REST Framework permissions-oriented workflows from django.conf import settings from django.http import Http404 -from rest_framework import permissions - from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey -from student.roles import CourseStaffRole, CourseInstructorRole +from rest_framework import permissions from openedx.core.lib.log_utils import audit_log +from student.roles import CourseInstructorRole, CourseStaffRole class ApiKeyHeaderPermission(permissions.BasePermission): diff --git a/openedx/core/lib/api/serializers.py b/openedx/core/lib/api/serializers.py index 5befa8184a..2b0913813f 100644 --- a/openedx/core/lib/api/serializers.py +++ b/openedx/core/lib/api/serializers.py @@ -2,9 +2,9 @@ Serializers to be used in APIs. """ -from rest_framework import serializers from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey, UsageKey +from rest_framework import serializers class CollapsedReferenceSerializer(serializers.HyperlinkedModelSerializer): diff --git a/openedx/core/lib/api/test_utils.py b/openedx/core/lib/api/test_utils.py index 9638a842a6..181429add3 100644 --- a/openedx/core/lib/api/test_utils.py +++ b/openedx/core/lib/api/test_utils.py @@ -3,8 +3,8 @@ Helpers for API tests. """ import base64 import json - import re + from django.test import TestCase from django.test.utils import override_settings diff --git a/openedx/core/lib/api/view_utils.py b/openedx/core/lib/api/view_utils.py index 02a838735f..0ee5c63a42 100644 --- a/openedx/core/lib/api/view_utils.py +++ b/openedx/core/lib/api/view_utils.py @@ -1,22 +1,21 @@ """ Utilities related to API views """ -from django.core.exceptions import NON_FIELD_ERRORS, ValidationError, ObjectDoesNotExist +from django.core.exceptions import NON_FIELD_ERRORS, ObjectDoesNotExist, ValidationError from django.http import Http404 from django.utils.translation import ugettext as _ - +from edx_rest_framework_extensions.authentication import JwtAuthentication from rest_framework import status from rest_framework.exceptions import APIException +from rest_framework.generics import GenericAPIView +from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin from rest_framework.permissions import IsAuthenticated from rest_framework.request import clone_request from rest_framework.response import Response -from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin -from rest_framework.generics import GenericAPIView -from edx_rest_framework_extensions.authentication import JwtAuthentication from openedx.core.lib.api.authentication import ( - SessionAuthenticationAllowInactiveUser, OAuth2AuthenticationAllowInactiveUser, + SessionAuthenticationAllowInactiveUser ) from openedx.core.lib.api.permissions import IsUserInUrl diff --git a/openedx/core/lib/cache_utils.py b/openedx/core/lib/cache_utils.py index c9234c26ad..983129aff8 100644 --- a/openedx/core/lib/cache_utils.py +++ b/openedx/core/lib/cache_utils.py @@ -5,6 +5,7 @@ import collections import cPickle as pickle import functools import zlib + from xblock.core import XBlock diff --git a/openedx/core/lib/celery/routers.py b/openedx/core/lib/celery/routers.py index 7c94412f23..dd3dd7823f 100644 --- a/openedx/core/lib/celery/routers.py +++ b/openedx/core/lib/celery/routers.py @@ -3,9 +3,10 @@ Custom routers used by both lms and cms when routing tasks to worker queues. For more, see http://celery.readthedocs.io/en/latest/userguide/routing.html#routers """ -from abc import ABCMeta, abstractproperty -from django.conf import settings import logging +from abc import ABCMeta, abstractproperty + +from django.conf import settings log = logging.getLogger(__name__) diff --git a/openedx/core/lib/command_utils.py b/openedx/core/lib/command_utils.py index 66bec9dabb..e68a3e6ba1 100644 --- a/openedx/core/lib/command_utils.py +++ b/openedx/core/lib/command_utils.py @@ -3,7 +3,6 @@ Useful utilities for management commands. """ from django.core.management.base import CommandError - from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey diff --git a/openedx/core/lib/course_tabs.py b/openedx/core/lib/course_tabs.py index 8e71467edc..4ce547c8fc 100644 --- a/openedx/core/lib/course_tabs.py +++ b/openedx/core/lib/course_tabs.py @@ -3,7 +3,6 @@ Tabs for courseware. """ from openedx.core.lib.api.plugins import PluginManager - # Stevedore extension point namespaces COURSE_TAB_NAMESPACE = 'openedx.course_tab' diff --git a/openedx/core/lib/django_require/staticstorage.py b/openedx/core/lib/django_require/staticstorage.py index 2e068055b6..b4b2b7ae11 100644 --- a/openedx/core/lib/django_require/staticstorage.py +++ b/openedx/core/lib/django_require/staticstorage.py @@ -2,8 +2,8 @@ :class:`~django_require.staticstorage.OptimizedCachedRequireJsStorage` """ -from require.storage import OptimizedFilesMixin from django_pipeline_forgiving.storages import PipelineForgivingStorage +from require.storage import OptimizedFilesMixin class OptimizedCachedRequireJsStorage(OptimizedFilesMixin, PipelineForgivingStorage): diff --git a/openedx/core/lib/django_startup.py b/openedx/core/lib/django_startup.py index 19f0f8babe..675ca2a64c 100644 --- a/openedx/core/lib/django_startup.py +++ b/openedx/core/lib/django_startup.py @@ -3,6 +3,7 @@ Automatic execution of startup modules in Django apps. """ from importlib import import_module + from django.conf import settings diff --git a/openedx/core/lib/edx_api_utils.py b/openedx/core/lib/edx_api_utils.py index c765842076..ce9e9d85ba 100644 --- a/openedx/core/lib/edx_api_utils.py +++ b/openedx/core/lib/edx_api_utils.py @@ -1,5 +1,6 @@ """Helper functions to get data from APIs""" from __future__ import unicode_literals + import logging from django.conf import settings @@ -11,7 +12,6 @@ from provider.oauth2.models import Client from openedx.core.lib.cache_utils import zpickle, zunpickle from openedx.core.lib.token_utils import JwtBuilder - log = logging.getLogger(__name__) diff --git a/openedx/core/lib/extract_tar.py b/openedx/core/lib/extract_tar.py index 58079ad065..db46038801 100644 --- a/openedx/core/lib/extract_tar.py +++ b/openedx/core/lib/extract_tar.py @@ -5,10 +5,12 @@ be, or symlink to a file that is, outside of the directory extracted in. Adapted from: http://stackoverflow.com/questions/10060069/safely-extract-zip-or-tar-using-python """ -from os.path import abspath, realpath, dirname, join as joinpath -from django.core.exceptions import SuspiciousOperation -from django.conf import settings import logging +from os.path import join as joinpath +from os.path import abspath, dirname, realpath + +from django.conf import settings +from django.core.exceptions import SuspiciousOperation log = logging.getLogger(__name__) diff --git a/openedx/core/lib/gating/api.py b/openedx/core/lib/gating/api.py index f7087b57d3..546635d3ef 100644 --- a/openedx/core/lib/gating/api.py +++ b/openedx/core/lib/gating/api.py @@ -4,11 +4,12 @@ API for the gating djangoapp import logging from django.utils.translation import ugettext as _ -from lms.djangoapps.courseware.access import _has_access_to_course from milestones import api as milestones_api from opaque_keys.edx.keys import UsageKey -from xmodule.modulestore.django import modulestore + +from lms.djangoapps.courseware.access import _has_access_to_course from openedx.core.lib.gating.exceptions import GatingValidationError +from xmodule.modulestore.django import modulestore log = logging.getLogger(__name__) diff --git a/openedx/core/lib/html_to_text.py b/openedx/core/lib/html_to_text.py index c1f1993c17..fd181dc9bc 100644 --- a/openedx/core/lib/html_to_text.py +++ b/openedx/core/lib/html_to_text.py @@ -1,6 +1,6 @@ """Provides a function to convert html to plaintext.""" import logging -from subprocess import Popen, PIPE +from subprocess import PIPE, Popen log = logging.getLogger(__name__) diff --git a/openedx/core/lib/mobile_utils.py b/openedx/core/lib/mobile_utils.py index 8c90e6a8b1..4e71112b8a 100644 --- a/openedx/core/lib/mobile_utils.py +++ b/openedx/core/lib/mobile_utils.py @@ -3,6 +3,7 @@ Common utilities related to the mobile apps. """ import re + from django.conf import settings diff --git a/openedx/core/lib/rsa_key_utils.py b/openedx/core/lib/rsa_key_utils.py index fd4853a5ec..d17124425e 100644 --- a/openedx/core/lib/rsa_key_utils.py +++ b/openedx/core/lib/rsa_key_utils.py @@ -1,9 +1,7 @@ """ Utils for RSA keys""" from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa -from cryptography.hazmat.primitives.serialization import( - Encoding, PublicFormat, PrivateFormat, NoEncryption -) +from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, PrivateFormat, PublicFormat def generate_rsa_key_pair(key_size=2048): diff --git a/openedx/core/lib/tests/test_cache_utils.py b/openedx/core/lib/tests/test_cache_utils.py index 97e973baa9..5179e4bc99 100644 --- a/openedx/core/lib/tests/test_cache_utils.py +++ b/openedx/core/lib/tests/test_cache_utils.py @@ -1,9 +1,10 @@ """ Tests for cache_utils.py """ +from unittest import TestCase + import ddt from mock import MagicMock -from unittest import TestCase from openedx.core.lib.cache_utils import memoize_in_request_cache diff --git a/openedx/core/lib/tests/test_course_tabs.py b/openedx/core/lib/tests/test_course_tabs.py index a1929706d5..13484f60da 100644 --- a/openedx/core/lib/tests/test_course_tabs.py +++ b/openedx/core/lib/tests/test_course_tabs.py @@ -1,11 +1,11 @@ """ Tests of specific tabs. """ -from mock import patch, Mock -from nose.plugins.attrib import attr from unittest import TestCase -import xmodule.tabs as xmodule_tabs +from mock import Mock, patch +from nose.plugins.attrib import attr +import xmodule.tabs as xmodule_tabs from openedx.core.lib.course_tabs import CourseTabPluginManager diff --git a/openedx/core/lib/tests/test_courses.py b/openedx/core/lib/tests/test_courses.py index 277fa1472c..29519de99d 100644 --- a/openedx/core/lib/tests/test_courses.py +++ b/openedx/core/lib/tests/test_courses.py @@ -7,8 +7,8 @@ from django.test.utils import override_settings from nose.plugins.attrib import attr from xmodule.modulestore import ModuleStoreEnum -from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory from ..courses import course_image_url diff --git a/openedx/core/lib/tests/test_edx_api_utils.py b/openedx/core/lib/tests/test_edx_api_utils.py index de7093de55..99fa215ca3 100644 --- a/openedx/core/lib/tests/test_edx_api_utils.py +++ b/openedx/core/lib/tests/test_edx_api_utils.py @@ -2,12 +2,12 @@ # pylint: disable=missing-docstring import json -from django.core.cache import cache -from django.test.utils import override_settings import httpretty import mock -from nose.plugins.attrib import attr +from django.core.cache import cache +from django.test.utils import override_settings from edx_oauth2_provider.tests.factories import ClientFactory +from nose.plugins.attrib import attr from provider.constants import CONFIDENTIAL from openedx.core.djangoapps.catalog.models import CatalogIntegration @@ -19,7 +19,6 @@ from openedx.core.djangolib.testing.utils import CacheIsolationTestCase, skip_un from openedx.core.lib.edx_api_utils import get_edx_api_data from student.tests.factories import UserFactory - UTILITY_MODULE = 'openedx.core.lib.edx_api_utils' TEST_API_URL = 'http://www-internal.example.com/api' diff --git a/openedx/core/lib/tests/test_graph_traversals.py b/openedx/core/lib/tests/test_graph_traversals.py index a1867d477f..cc1d164214 100644 --- a/openedx/core/lib/tests/test_graph_traversals.py +++ b/openedx/core/lib/tests/test_graph_traversals.py @@ -3,12 +3,11 @@ Tests for graph traversal generator functions. """ from collections import defaultdict -from nose.plugins.attrib import attr from unittest import TestCase -from ..graph_traversals import ( - traverse_pre_order, traverse_post_order, traverse_topologically -) +from nose.plugins.attrib import attr + +from ..graph_traversals import traverse_post_order, traverse_pre_order, traverse_topologically @attr(shard=2) diff --git a/openedx/core/lib/tests/test_time_zone_utils.py b/openedx/core/lib/tests/test_time_zone_utils.py index a231467b4a..4b5afdecaa 100644 --- a/openedx/core/lib/tests/test_time_zone_utils.py +++ b/openedx/core/lib/tests/test_time_zone_utils.py @@ -1,14 +1,12 @@ """Tests covering time zone utilities.""" -from freezegun import freeze_time -from student.tests.factories import UserFactory -from openedx.core.lib.time_zone_utils import ( - get_display_time_zone, - get_time_zone_abbr, - get_time_zone_offset, -) -from pytz import timezone, utc from unittest import TestCase +from freezegun import freeze_time +from pytz import timezone, utc + +from openedx.core.lib.time_zone_utils import get_display_time_zone, get_time_zone_abbr, get_time_zone_offset +from student.tests.factories import UserFactory + class TestTimeZoneUtils(TestCase): """ diff --git a/openedx/core/lib/tests/test_token_utils.py b/openedx/core/lib/tests/test_token_utils.py index bd62a372c1..59ba8cdab6 100644 --- a/openedx/core/lib/tests/test_token_utils.py +++ b/openedx/core/lib/tests/test_token_utils.py @@ -1,7 +1,7 @@ """Tests covering JWT construction utilities.""" import ddt -from django.test import TestCase import jwt +from django.test import TestCase from nose.plugins.attrib import attr from openedx.core.djangoapps.oauth_dispatch.tests import mixins diff --git a/openedx/core/lib/tests/test_url_utils.py b/openedx/core/lib/tests/test_url_utils.py index 2fb293d889..ec6bcd6b60 100644 --- a/openedx/core/lib/tests/test_url_utils.py +++ b/openedx/core/lib/tests/test_url_utils.py @@ -1,10 +1,10 @@ """ Tests for url_utils module. """ -from ddt import ddt, data +from ddt import data, ddt from django.test import TestCase -from openedx.core.lib.url_utils import quote_slashes, unquote_slashes +from openedx.core.lib.url_utils import quote_slashes, unquote_slashes TEST_STRINGS = [ '', diff --git a/openedx/core/lib/tests/test_xblock_utils.py b/openedx/core/lib/tests/test_xblock_utils.py index a2db4765f2..5915eb8215 100644 --- a/openedx/core/lib/tests/test_xblock_utils.py +++ b/openedx/core/lib/tests/test_xblock_utils.py @@ -1,34 +1,30 @@ """ Tests for xblock_utils.py """ -from __future__ import unicode_literals, absolute_import +from __future__ import absolute_import, unicode_literals -import ddt -from nose.plugins.attrib import attr import uuid +import ddt from django.test.client import RequestFactory +from nose.plugins.attrib import attr +from xblock.fragment import Fragment from openedx.core.lib.url_utils import quote_slashes -from xblock.fragment import Fragment +from openedx.core.lib.xblock_builtin import get_css_dependencies, get_js_dependencies +from openedx.core.lib.xblock_utils import ( + replace_course_urls, + replace_jump_to_id_urls, + replace_static_urls, + request_token, + sanitize_html_id, + wrap_fragment, + wrap_xblock +) from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory -from openedx.core.lib.xblock_utils import ( - wrap_fragment, - request_token, - wrap_xblock, - replace_jump_to_id_urls, - replace_course_urls, - replace_static_urls, - sanitize_html_id, -) -from openedx.core.lib.xblock_builtin import ( - get_css_dependencies, - get_js_dependencies, -) - @attr(shard=2) @ddt.ddt diff --git a/openedx/core/lib/time_zone_utils.py b/openedx/core/lib/time_zone_utils.py index 27bad00626..d068510474 100644 --- a/openedx/core/lib/time_zone_utils.py +++ b/openedx/core/lib/time_zone_utils.py @@ -2,6 +2,7 @@ Utilities related to timezones """ from datetime import datetime + from pytz import common_timezones, timezone, utc diff --git a/openedx/core/lib/xblock_pipeline/finder.py b/openedx/core/lib/xblock_pipeline/finder.py index 96bc52f9c6..3dde96d757 100644 --- a/openedx/core/lib/xblock_pipeline/finder.py +++ b/openedx/core/lib/xblock_pipeline/finder.py @@ -1,16 +1,15 @@ """ Django pipeline finder for handling static assets required by XBlocks. """ -from datetime import datetime import os -from pkg_resources import resource_exists, resource_listdir, resource_isdir, resource_filename - -from xblock.core import XBlock +from datetime import datetime from django.contrib.staticfiles import utils from django.contrib.staticfiles.finders import BaseFinder from django.contrib.staticfiles.storage import FileSystemStorage from django.core.files.storage import Storage +from pkg_resources import resource_exists, resource_filename, resource_isdir, resource_listdir +from xblock.core import XBlock class XBlockPackageStorage(Storage): diff --git a/openedx/core/operations.py b/openedx/core/operations.py index ec0d607b69..87721c843a 100644 --- a/openedx/core/operations.py +++ b/openedx/core/operations.py @@ -1,12 +1,12 @@ """ Workflows useful for reporting on runtime characteristics of the system """ +import gc import os import signal import tempfile -import gc - from datetime import datetime + from meliae import scanner diff --git a/openedx/core/storage.py b/openedx/core/storage.py index e67b72ca22..9aef5f0c5c 100644 --- a/openedx/core/storage.py +++ b/openedx/core/storage.py @@ -1,20 +1,16 @@ """ Django storage backends for Open edX. """ -from django_pipeline_forgiving.storages import PipelineForgivingStorage from django.contrib.staticfiles.storage import StaticFilesStorage from django.core.files.storage import get_storage_class from django.utils.lru_cache import lru_cache - +from django_pipeline_forgiving.storages import PipelineForgivingStorage from pipeline.storage import NonPackagingMixin from require.storage import OptimizedFilesMixin -from openedx.core.djangoapps.theming.storage import ( - ThemeStorage, - ThemeCachedFilesMixin, - ThemePipelineMixin -) from storages.backends.s3boto import S3BotoStorage +from openedx.core.djangoapps.theming.storage import ThemeCachedFilesMixin, ThemePipelineMixin, ThemeStorage + class ProductionStorage( PipelineForgivingStorage, diff --git a/openedx/features/course_bookmarks/views/course_bookmarks.py b/openedx/features/course_bookmarks/views/course_bookmarks.py index 04f2cdb0bc..3767ea1b75 100644 --- a/openedx/features/course_bookmarks/views/course_bookmarks.py +++ b/openedx/features/course_bookmarks/views/course_bookmarks.py @@ -11,13 +11,13 @@ from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_control from django.views.decorators.csrf import ensure_csrf_cookie from django.views.generic import View +from opaque_keys.edx.keys import CourseKey +from web_fragments.fragment import Fragment from courseware.courses import get_course_with_access -from opaque_keys.edx.keys import CourseKey from openedx.core.djangoapps.plugin_api.views import EdxFragmentView from openedx.features.course_experience import default_course_url_name from util.views import ensure_valid_course_key -from web_fragments.fragment import Fragment class CourseBookmarksView(View): diff --git a/openedx/features/enterprise_support/tests/test_api.py b/openedx/features/enterprise_support/tests/test_api.py index 3fd4e1125e..42affbc144 100644 --- a/openedx/features/enterprise_support/tests/test_api.py +++ b/openedx/features/enterprise_support/tests/test_api.py @@ -1,23 +1,23 @@ """ Test the enterprise support APIs. """ -import mock import unittest +import mock from django.conf import settings from django.http import HttpResponseRedirect from django.test.utils import override_settings from openedx.features.enterprise_support.api import ( - enterprise_enabled, - enterprise_customer_for_request, - insert_enterprise_pipeline_elements, data_sharing_consent_required, - set_enterprise_branding_filter_param, + enterprise_customer_for_request, + enterprise_enabled, get_dashboard_consent_notification, get_enterprise_branding_filter_param, get_enterprise_consent_url, - get_enterprise_customer_logo_url + get_enterprise_customer_logo_url, + insert_enterprise_pipeline_elements, + set_enterprise_branding_filter_param ) diff --git a/openedx/tests/xblock_integration/test_crowdsource_hinter.py b/openedx/tests/xblock_integration/test_crowdsource_hinter.py index bbb35271f3..3ca4c75986 100644 --- a/openedx/tests/xblock_integration/test_crowdsource_hinter.py +++ b/openedx/tests/xblock_integration/test_crowdsource_hinter.py @@ -4,13 +4,12 @@ Test scenarios for the crowdsource hinter xblock. import json import unittest -from nose.plugins.attrib import attr - from django.conf import settings from django.core.urlresolvers import reverse +from nose.plugins.attrib import attr -from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase from lms.djangoapps.courseware.tests.factories import GlobalStaffFactory +from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase from openedx.core.lib.url_utils import quote_slashes from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory diff --git a/openedx/tests/xblock_integration/test_recommender.py b/openedx/tests/xblock_integration/test_recommender.py index f9ced9b3da..cb1eef10a7 100644 --- a/openedx/tests/xblock_integration/test_recommender.py +++ b/openedx/tests/xblock_integration/test_recommender.py @@ -3,24 +3,22 @@ This test file will run through some XBlock test scenarios regarding the recommender system """ -from copy import deepcopy -import json import itertools +import json import StringIO import unittest +from copy import deepcopy -from ddt import ddt, data -from nose.plugins.attrib import attr - +from ddt import data, ddt from django.conf import settings from django.core.urlresolvers import reverse +from nose.plugins.attrib import attr -from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory -from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase - -from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase from lms.djangoapps.courseware.tests.factories import GlobalStaffFactory +from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase from openedx.core.lib.url_utils import quote_slashes +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory class TestRecommender(SharedModuleStoreTestCase, LoginEnrollmentTestCase): diff --git a/openedx/tests/xblock_integration/xblock_testcase.py b/openedx/tests/xblock_integration/xblock_testcase.py index 0c5cde7d04..b96bc898bd 100644 --- a/openedx/tests/xblock_integration/xblock_testcase.py +++ b/openedx/tests/xblock_integration/xblock_testcase.py @@ -35,28 +35,24 @@ Our next steps would be to: blocks themselves. """ -import HTMLParser import collections -from datetime import datetime, timedelta +import HTMLParser import json -import mock import sys -import pytz import unittest +from datetime import datetime, timedelta +import mock +import pytz from bs4 import BeautifulSoup - -from xblock.plugin import Plugin - from django.conf import settings from django.core.urlresolvers import reverse - -from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory -from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase - -from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase +from xblock.plugin import Plugin import lms.djangoapps.lms_xblock.runtime +from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase +from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase +from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory class XBlockEventTestMixin(object): diff --git a/pavelib/acceptance_test.py b/pavelib/acceptance_test.py index ceca56e5cc..24b976c6fb 100644 --- a/pavelib/acceptance_test.py +++ b/pavelib/acceptance_test.py @@ -1,12 +1,14 @@ """ Acceptance test tasks """ -from paver.easy import cmdopts, needs -from pavelib.utils.test.suites import AcceptanceTestSuite -from pavelib.utils.passthrough_opts import PassthroughTask -from pavelib.utils.timer import timed from optparse import make_option +from paver.easy import cmdopts, needs + +from pavelib.utils.passthrough_opts import PassthroughTask +from pavelib.utils.test.suites import AcceptanceTestSuite +from pavelib.utils.timer import timed + try: from pygments.console import colorize except ImportError: diff --git a/pavelib/assets.py b/pavelib/assets.py index f86cc37b36..1d5e1f3efe 100644 --- a/pavelib/assets.py +++ b/pavelib/assets.py @@ -3,26 +3,27 @@ Asset compilation and collection. """ from __future__ import print_function -from datetime import datetime -from functools import wraps -from threading import Timer + import argparse import glob import os import traceback +from datetime import datetime +from functools import wraps +from threading import Timer from paver import tasks -from paver.easy import sh, path, task, cmdopts, needs, consume_args, call_task, no_help -from watchdog.observers.polling import PollingObserver +from paver.easy import call_task, cmdopts, consume_args, needs, no_help, path, sh, task from watchdog.events import PatternMatchingEventHandler - -from .utils.envs import Env -from .utils.cmd import cmd, django_cmd -from .utils.timer import timed -from .utils.process import run_background_process +from watchdog.observers.polling import PollingObserver from openedx.core.djangoapps.theming.paver_helpers import get_theme_paths +from .utils.cmd import cmd, django_cmd +from .utils.envs import Env +from .utils.process import run_background_process +from .utils.timer import timed + # setup baseline paths ALL_SYSTEMS = ['lms', 'studio'] diff --git a/pavelib/bok_choy.py b/pavelib/bok_choy.py index f239f30ca6..2ea562f61e 100644 --- a/pavelib/bok_choy.py +++ b/pavelib/bok_choy.py @@ -2,21 +2,23 @@ Run acceptance tests that use the bok-choy framework http://bok-choy.readthedocs.org/en/latest/ """ -from paver.easy import task, needs, cmdopts, sh -from pavelib.utils.test.suites.bokchoy_suite import BokChoyTestSuite, Pa11yCrawler +import os +from optparse import make_option + +from paver.easy import cmdopts, needs, sh, task + +from pavelib.utils.envs import Env +from pavelib.utils.passthrough_opts import PassthroughTask from pavelib.utils.test.bokchoy_options import ( BOKCHOY_OPTS, - PA11Y_HTML, PA11Y_COURSE_KEY, PA11Y_FETCH_COURSE, + PA11Y_HTML, PA11Y_SINGLE_URL ) -from pavelib.utils.envs import Env +from pavelib.utils.test.suites.bokchoy_suite import BokChoyTestSuite, Pa11yCrawler from pavelib.utils.test.utils import check_firefox_version -from pavelib.utils.passthrough_opts import PassthroughTask from pavelib.utils.timer import timed -from optparse import make_option -import os try: from pygments.console import colorize diff --git a/pavelib/docs.py b/pavelib/docs.py index b96580714a..54343f236b 100644 --- a/pavelib/docs.py +++ b/pavelib/docs.py @@ -3,13 +3,13 @@ Open edX Documentation Builder Ties into Sphinx to generate files at the specified location(s) """ from __future__ import print_function + import sys from paver.easy import cmdopts, needs, sh, task from .utils.timer import timed - DOC_PATHS = { "dev": "docs/en_us/developers", "author": "docs/en_us/course_authors", diff --git a/pavelib/i18n.py b/pavelib/i18n.py index 5767264fe8..2e0f2035c2 100644 --- a/pavelib/i18n.py +++ b/pavelib/i18n.py @@ -3,11 +3,11 @@ Internationalization tasks """ import re -import sys import subprocess +import sys from path import Path as path -from paver.easy import task, cmdopts, needs, sh +from paver.easy import cmdopts, needs, sh, task from .utils.cmd import django_cmd from .utils.timer import timed diff --git a/pavelib/js_test.py b/pavelib/js_test.py index 7102d7471f..0b44353819 100644 --- a/pavelib/js_test.py +++ b/pavelib/js_test.py @@ -2,9 +2,11 @@ Javascript test tasks """ import sys -from paver.easy import task, cmdopts, needs -from pavelib.utils.test.suites import JsTestSuite + +from paver.easy import cmdopts, needs, task + from pavelib.utils.envs import Env +from pavelib.utils.test.suites import JsTestSuite from pavelib.utils.timer import timed __test__ = False # do not collect diff --git a/pavelib/paver_tests/test_assets.py b/pavelib/paver_tests/test_assets.py index aa6686272d..548f6e5286 100644 --- a/pavelib/paver_tests/test_assets.py +++ b/pavelib/paver_tests/test_assets.py @@ -1,12 +1,15 @@ """Unit tests for the Paver asset tasks.""" -import ddt import os from unittest import TestCase -from pavelib.assets import collect_assets, COLLECTSTATIC_LOG_DIR_ARG -from paver.easy import call_task, path + +import ddt from mock import patch +from paver.easy import call_task, path from watchdog.observers.polling import PollingObserver + +from pavelib.assets import COLLECTSTATIC_LOG_DIR_ARG, collect_assets + from .utils import PaverTestCase ROOT_PATH = path(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) diff --git a/pavelib/paver_tests/test_eslint.py b/pavelib/paver_tests/test_eslint.py index 3d4c7b4086..8a326cf0cd 100644 --- a/pavelib/paver_tests/test_eslint.py +++ b/pavelib/paver_tests/test_eslint.py @@ -2,10 +2,11 @@ Tests for paver quality tasks """ import unittest + from mock import patch +from paver.easy import BuildFailure import pavelib.quality -from paver.easy import BuildFailure class TestPaverESLint(unittest.TestCase): diff --git a/pavelib/paver_tests/test_extract_and_generate.py b/pavelib/paver_tests/test_extract_and_generate.py index de7076ae06..12b04aaaca 100644 --- a/pavelib/paver_tests/test_extract_and_generate.py +++ b/pavelib/paver_tests/test_extract_and_generate.py @@ -1,24 +1,20 @@ """ This test tests that i18n extraction (`paver i18n_extract -v`) works properly. """ -from datetime import datetime, timedelta import os import random import re -import sys import string import subprocess +import sys +from datetime import datetime, timedelta from unittest import TestCase +from i18n import config, dummy, extract, generate from mock import patch from polib import pofile from pytz import UTC -from i18n import config -from i18n import dummy -from i18n import extract -from i18n import generate - class TestGenerate(TestCase): """ diff --git a/pavelib/paver_tests/test_i18n.py b/pavelib/paver_tests/test_i18n.py index 2dcbda09ac..cbacb17f57 100644 --- a/pavelib/paver_tests/test_i18n.py +++ b/pavelib/paver_tests/test_i18n.py @@ -7,12 +7,12 @@ import textwrap import unittest from mock import mock_open, patch -from paver.easy import task, call_task +from paver.easy import call_task, task import pavelib.i18n - from pavelib.paver_tests.utils import PaverTestCase + TX_CONFIG_SIMPLE = """\ [main] host = https://www.transifex.com diff --git a/pavelib/paver_tests/test_js_test.py b/pavelib/paver_tests/test_js_test.py index 085fdcab8d..17fcf31d4c 100644 --- a/pavelib/paver_tests/test_js_test.py +++ b/pavelib/paver_tests/test_js_test.py @@ -5,9 +5,10 @@ from mock import patch from paver.easy import call_task import pavelib.js_test -from .utils import PaverTestCase from pavelib.utils.envs import Env +from .utils import PaverTestCase + @ddt.ddt class TestPaverJavaScriptTestTasks(PaverTestCase): diff --git a/pavelib/paver_tests/test_paver_bok_choy_cmds.py b/pavelib/paver_tests/test_paver_bok_choy_cmds.py index 54267cc5aa..fdd2a4263e 100644 --- a/pavelib/paver_tests/test_paver_bok_choy_cmds.py +++ b/pavelib/paver_tests/test_paver_bok_choy_cmds.py @@ -4,14 +4,15 @@ Run just this test with: paver test_lib -t pavelib/paver_tests/test_paver_bok_ch """ import os import unittest +from test.test_support import EnvironmentVarGuard from textwrap import dedent import ddt -from mock import patch, call, Mock -from test.test_support import EnvironmentVarGuard +from mock import Mock, call, patch from paver.easy import BuildFailure, call_task, environment + from pavelib.utils.test.suites import BokChoyTestSuite, Pa11yCrawler -from pavelib.utils.test.suites.bokchoy_suite import DEMO_COURSE_TAR_GZ, DEMO_COURSE_IMPORT_DIR +from pavelib.utils.test.suites.bokchoy_suite import DEMO_COURSE_IMPORT_DIR, DEMO_COURSE_TAR_GZ REPO_DIR = os.getcwd() diff --git a/pavelib/paver_tests/test_paver_get_quality_reports.py b/pavelib/paver_tests/test_paver_get_quality_reports.py index cf9f1caa3f..2b8ef5fc49 100644 --- a/pavelib/paver_tests/test_paver_get_quality_reports.py +++ b/pavelib/paver_tests/test_paver_get_quality_reports.py @@ -2,7 +2,9 @@ Tests to ensure only the report files we want are returned as part of run_quality. """ import unittest + from mock import patch + import pavelib.quality diff --git a/pavelib/paver_tests/test_paver_quality.py b/pavelib/paver_tests/test_paver_quality.py index 2ae4bdfee3..8aaf3e68cc 100644 --- a/pavelib/paver_tests/test_paver_quality.py +++ b/pavelib/paver_tests/test_paver_quality.py @@ -1,20 +1,20 @@ """ Tests for paver quality tasks """ +import os import tempfile import textwrap import unittest -import os import paver.easy import paver.tasks from ddt import ddt, file_data -from mock import patch, MagicMock, mock_open +from mock import MagicMock, mock_open, patch from path import Path as path from paver.easy import BuildFailure import pavelib.quality -from pavelib.paver_tests.utils import fail_on_pylint, fail_on_eslint +from pavelib.paver_tests.utils import fail_on_eslint, fail_on_pylint @ddt diff --git a/pavelib/paver_tests/test_prereqs.py b/pavelib/paver_tests/test_prereqs.py index dba0c748a6..efbae4ab64 100644 --- a/pavelib/paver_tests/test_prereqs.py +++ b/pavelib/paver_tests/test_prereqs.py @@ -4,12 +4,12 @@ Tests covering the Open edX Paver prequisites installation workflow import os import unittest + from mock import call, patch from paver.easy import BuildFailure + +from pavelib.paver_tests.utils import PaverTestCase, fail_on_npm_install, unexpected_fail_on_npm_install from pavelib.prereqs import no_prereq_install, node_prereqs_installation -from pavelib.paver_tests.utils import ( - PaverTestCase, unexpected_fail_on_npm_install, fail_on_npm_install -) class TestPaverPrereqInstall(unittest.TestCase): diff --git a/pavelib/paver_tests/test_safecommit.py b/pavelib/paver_tests/test_safecommit.py index 75055a381e..f4dace4101 100644 --- a/pavelib/paver_tests/test_safecommit.py +++ b/pavelib/paver_tests/test_safecommit.py @@ -2,9 +2,9 @@ Tests for paver safecommit quality tasks """ from mock import patch +from paver.easy import call_task import pavelib.quality -from paver.easy import call_task from .utils import PaverTestCase diff --git a/pavelib/paver_tests/test_safelint.py b/pavelib/paver_tests/test_safelint.py index f653ae505a..b5b332b580 100644 --- a/pavelib/paver_tests/test_safelint.py +++ b/pavelib/paver_tests/test_safelint.py @@ -2,9 +2,9 @@ Tests for paver safelint quality tasks """ from mock import patch +from paver.easy import call_task import pavelib.quality -from paver.easy import call_task from .utils import PaverTestCase diff --git a/pavelib/paver_tests/test_servers.py b/pavelib/paver_tests/test_servers.py index 8f7c2c4214..7c517f8a71 100644 --- a/pavelib/paver_tests/test_servers.py +++ b/pavelib/paver_tests/test_servers.py @@ -3,8 +3,8 @@ import ddt from paver.easy import call_task -from .utils import PaverTestCase from ..utils.envs import Env +from .utils import PaverTestCase EXPECTED_COFFEE_COMMAND = ( u"node_modules/.bin/coffee --compile `find {platform_root}/lms " diff --git a/pavelib/paver_tests/test_timer.py b/pavelib/paver_tests/test_timer.py index 742e6a34a3..82ce790088 100644 --- a/pavelib/paver_tests/test_timer.py +++ b/pavelib/paver_tests/test_timer.py @@ -3,9 +3,10 @@ Tests of the pavelib.utils.timer module. """ from datetime import datetime, timedelta -from mock import patch, MagicMock from unittest import TestCase +from mock import MagicMock, patch + from pavelib.utils import timer diff --git a/pavelib/paver_tests/test_utils.py b/pavelib/paver_tests/test_utils.py index 3d19ba1d3f..65bdc966a6 100644 --- a/pavelib/paver_tests/test_utils.py +++ b/pavelib/paver_tests/test_utils.py @@ -2,10 +2,12 @@ Tests for pavelib/utils/test/utils """ -from pavelib.utils.test.utils import check_firefox_version, MINIMUM_FIREFOX_VERSION import unittest + from mock import patch +from pavelib.utils.test.utils import MINIMUM_FIREFOX_VERSION, check_firefox_version + class TestUtils(unittest.TestCase): """ diff --git a/pavelib/paver_tests/utils.py b/pavelib/paver_tests/utils.py index 168b9c4556..36819c23a1 100644 --- a/pavelib/paver_tests/utils.py +++ b/pavelib/paver_tests/utils.py @@ -1,10 +1,10 @@ """Unit tests for the Paver server tasks.""" import os -import paver.easy -from paver import tasks from unittest import TestCase +import paver.easy +from paver import tasks from paver.easy import BuildFailure diff --git a/pavelib/prereqs.py b/pavelib/prereqs.py index acf61336ae..8cb9d9e8e9 100644 --- a/pavelib/prereqs.py +++ b/pavelib/prereqs.py @@ -2,18 +2,17 @@ Install Python and Node prerequisites. """ -from distutils import sysconfig import hashlib import os import re import sys +from distutils import sysconfig -from paver.easy import sh, task, BuildFailure +from paver.easy import BuildFailure, sh, task from .utils.envs import Env from .utils.timer import timed - PREREQS_STATE_DIR = os.getenv('PREREQ_CACHE_DIR', Env.REPO_ROOT / '.prereqs_cache') NPM_REGISTRY = "https://registry.npmjs.org/" NO_PREREQ_MESSAGE = "NO_PREREQ_INSTALL is set, not installing prereqs" diff --git a/pavelib/quality.py b/pavelib/quality.py index 8228ac8fc7..8c663ec870 100644 --- a/pavelib/quality.py +++ b/pavelib/quality.py @@ -1,12 +1,13 @@ """ Check code quality using pep8, pylint, and diff_quality. """ -from paver.easy import sh, task, cmdopts, needs, BuildFailure import json import os import re from string import join +from paver.easy import BuildFailure, cmdopts, needs, sh, task + from openedx.core.djangolib.markup import HTML from .utils.envs import Env diff --git a/pavelib/servers.py b/pavelib/servers.py index e2c3bbe234..81579b1c51 100644 --- a/pavelib/servers.py +++ b/pavelib/servers.py @@ -2,6 +2,7 @@ Run and manage servers for local development. """ from __future__ import print_function + import argparse import sys @@ -9,10 +10,9 @@ from paver.easy import call_task, cmdopts, consume_args, needs, sh, task from .assets import collect_assets from .utils.cmd import django_cmd -from .utils.process import run_process, run_multi_processes +from .utils.process import run_multi_processes, run_process from .utils.timer import timed - DEFAULT_PORT = {"lms": 8000, "studio": 8001} DEFAULT_SETTINGS = 'devstack' OPTIMIZED_SETTINGS = "devstack_optimized" diff --git a/pavelib/tests.py b/pavelib/tests.py index 407c9f3692..772d4215f7 100644 --- a/pavelib/tests.py +++ b/pavelib/tests.py @@ -1,16 +1,18 @@ """ Unit test tasks """ -import re import os +import re import sys -from paver.easy import sh, task, cmdopts, needs -from pavelib.utils.test import suites -from pavelib.utils.envs import Env -from pavelib.utils.timer import timed -from pavelib.utils.passthrough_opts import PassthroughTask from optparse import make_option +from paver.easy import cmdopts, needs, sh, task + +from pavelib.utils.envs import Env +from pavelib.utils.passthrough_opts import PassthroughTask +from pavelib.utils.test import suites +from pavelib.utils.timer import timed + try: from pygments.console import colorize except ImportError: diff --git a/pavelib/utils/envs.py b/pavelib/utils/envs.py index 2c229e0d19..700032e30b 100644 --- a/pavelib/utils/envs.py +++ b/pavelib/utils/envs.py @@ -2,14 +2,17 @@ Helper functions for loading environment settings. """ from __future__ import print_function + +import json import os import sys -import json + +import memcache from lazy import lazy from path import Path as path -from pavelib.utils.cmd import django_cmd from paver.easy import sh -import memcache + +from pavelib.utils.cmd import django_cmd class Env(object): diff --git a/pavelib/utils/passthrough_opts.py b/pavelib/utils/passthrough_opts.py index 9a4995deba..cff98f46c3 100644 --- a/pavelib/utils/passthrough_opts.py +++ b/pavelib/utils/passthrough_opts.py @@ -8,7 +8,8 @@ Provides: as the `passthrough_options` argument to the decorated function """ -from optparse import OptionParser, BadOptionError +from optparse import BadOptionError, OptionParser + import paver.tasks from mock import patch diff --git a/pavelib/utils/process.py b/pavelib/utils/process.py index d2e2b3bafd..9b88783a7e 100644 --- a/pavelib/utils/process.py +++ b/pavelib/utils/process.py @@ -2,13 +2,14 @@ Helper functions for managing processes. """ from __future__ import print_function -import sys -import os -import subprocess -import signal -import psutil -import atexit +import atexit +import os +import signal +import subprocess +import sys + +import psutil from paver import tasks diff --git a/pavelib/utils/test/bokchoy_options.py b/pavelib/utils/test/bokchoy_options.py index 53e192d0d9..8631da945f 100644 --- a/pavelib/utils/test/bokchoy_options.py +++ b/pavelib/utils/test/bokchoy_options.py @@ -2,12 +2,11 @@ Definitions of all options used by the various bok_choy tasks. """ -from optparse import make_option import os +from optparse import make_option from pavelib.utils.envs import Env - BOKCHOY_IMPORTS_DIR = ('imports-dir=', 'i', 'Directory containing (un-archived) courses to be imported') BOKCHOY_IMPORTS_DIR_DEPR = ('imports_dir=', None, 'deprecated in favor of imports-dir') BOKCHOY_DEFAULT_STORE = make_option( diff --git a/pavelib/utils/test/bokchoy_utils.py b/pavelib/utils/test/bokchoy_utils.py index ea9e7a49d2..d3df89c21e 100644 --- a/pavelib/utils/test/bokchoy_utils.py +++ b/pavelib/utils/test/bokchoy_utils.py @@ -1,18 +1,18 @@ """ Helper functions for bok_choy test tasks """ -import sys -import os -import time import httplib +import os import subprocess +import sys +import time + from paver import tasks -from paver.easy import sh, task, cmdopts, needs +from paver.easy import cmdopts, needs, sh, task + from pavelib.utils.envs import Env from pavelib.utils.process import run_background_process -from pavelib.utils.test.bokchoy_options import ( - BOKCHOY_COVERAGERC, BOKCHOY_DEFAULT_STORE, BOKCHOY_DEFAULT_STORE_DEPR -) +from pavelib.utils.test.bokchoy_options import BOKCHOY_COVERAGERC, BOKCHOY_DEFAULT_STORE, BOKCHOY_DEFAULT_STORE_DEPR from pavelib.utils.timer import timed try: diff --git a/pavelib/utils/test/utils.py b/pavelib/utils/test/utils.py index ea189c625d..d6aed364a6 100644 --- a/pavelib/utils/test/utils.py +++ b/pavelib/utils/test/utils.py @@ -1,13 +1,15 @@ """ Helper functions for test tasks """ -from paver.easy import sh, task, cmdopts -from pavelib.utils.envs import Env -from pavelib.utils.timer import timed import os import re import subprocess +from paver.easy import cmdopts, sh, task + +from pavelib.utils.envs import Env +from pavelib.utils.timer import timed + MONGO_PORT_NUM = int(os.environ.get('EDXAPP_TEST_MONGO_PORT', '27017')) MONGO_HOST = os.environ.get('EDXAPP_TEST_MONGO_HOST', 'localhost') MINIMUM_FIREFOX_VERSION = 28.0 diff --git a/pavelib/utils/timer.py b/pavelib/utils/timer.py index 4432caf2e5..6115e9c20d 100644 --- a/pavelib/utils/timer.py +++ b/pavelib/utils/timer.py @@ -2,13 +2,14 @@ Tools for timing paver tasks """ -from datetime import datetime import json import logging import os -from os.path import dirname, exists import sys import traceback +from datetime import datetime +from os.path import dirname, exists + import wrapt LOGGER = logging.getLogger(__file__) diff --git a/scripts/hotfix.py b/scripts/hotfix.py index fd0abda955..e50609cfd4 100644 --- a/scripts/hotfix.py +++ b/scripts/hotfix.py @@ -9,10 +9,11 @@ The script should be run with the hotfix's git hash as a command-line argument. i.e. `python scripts/hotfix.py ` """ from __future__ import print_function -from datetime import date -import sys + import argparse +import sys import textwrap +from datetime import date def generate_alton_commands(hotfix_hash): diff --git a/scripts/release.py b/scripts/release.py index 00f25b0b5d..38867c3b52 100755 --- a/scripts/release.py +++ b/scripts/release.py @@ -3,15 +3,16 @@ a release-master multitool """ from __future__ import print_function, unicode_literals -import sys + import argparse -from datetime import date, timedelta -import re import collections import functools -import textwrap -import json import getpass +import json +import re +import sys +import textwrap +from datetime import date, timedelta try: from path import Path as path diff --git a/scripts/run_watch_data.py b/scripts/run_watch_data.py index 08481b48de..b8eb91d84d 100755 --- a/scripts/run_watch_data.py +++ b/scripts/run_watch_data.py @@ -3,14 +3,15 @@ # This script requires that you have watchdog installed. You can install # watchdog via 'pip install watchdog' -import sys -import time import logging import os -from subprocess import Popen +import sys +import time from signal import SIGTERM +from subprocess import Popen + +from watchdog.events import FileSystemEventHandler, LoggingEventHandler from watchdog.observers import Observer -from watchdog.events import LoggingEventHandler, FileSystemEventHandler # To watch more (or more specific) directories, change WATCH_DIRS to include the # directories you want to watch. Note that this is recursive. If you want to diff --git a/scripts/runone.py b/scripts/runone.py index ea25c8365c..75b36725d5 100755 --- a/scripts/runone.py +++ b/scripts/runone.py @@ -4,6 +4,7 @@ import argparse import os import sys + # I want this: # ERROR: test_update_and_fetch (edx-platform.cms.djangoapps.contentstore.tests.test_course_settings.CourseDetailsViewTest) # to become: diff --git a/scripts/safe_template_linter.py b/scripts/safe_template_linter.py index b2ebf182aa..2dca424e54 100755 --- a/scripts/safe_template_linter.py +++ b/scripts/safe_template_linter.py @@ -3,14 +3,16 @@ A linting tool to check if templates are safe """ from __future__ import print_function + import argparse import ast -from enum import Enum import os import re import sys import textwrap +from enum import Enum + class StringLines(object): """ diff --git a/scripts/show_events.py b/scripts/show_events.py index 4ed85f45ed..ed2d833188 100644 --- a/scripts/show_events.py +++ b/scripts/show_events.py @@ -1,6 +1,7 @@ import json import sys import traceback + try: import dateutil.parser except ImportError: diff --git a/scripts/tests/test_safe_template_linter.py b/scripts/tests/test_safe_template_linter.py index f2f4d22a10..e1c6f2b492 100644 --- a/scripts/tests/test_safe_template_linter.py +++ b/scripts/tests/test_safe_template_linter.py @@ -2,16 +2,25 @@ """ Tests for safe_template_linter.py """ -from ddt import ddt, data -import mock import re -from StringIO import StringIO import textwrap +from StringIO import StringIO from unittest import TestCase +import mock +from ddt import data, ddt + from scripts.safe_template_linter import ( - _lint, FileResults, JavaScriptLinter, MakoTemplateLinter, ParseString, - StringLines, PythonLinter, SummaryResults, UnderscoreTemplateLinter, Rules + FileResults, + JavaScriptLinter, + MakoTemplateLinter, + ParseString, + PythonLinter, + Rules, + StringLines, + SummaryResults, + UnderscoreTemplateLinter, + _lint ) diff --git a/scripts/xblock/xblock_counts.py b/scripts/xblock/xblock_counts.py index 2a2703face..c58036c861 100644 --- a/scripts/xblock/xblock_counts.py +++ b/scripts/xblock/xblock_counts.py @@ -1,10 +1,10 @@ import argparse import csv import json +import os import sys from datetime import datetime -import os import requests # Keys for the CSV and JSON interpretation