From 46fe6fdcea7a7f9911e11bba7dedd4346fcfdc09 Mon Sep 17 00:00:00 2001 From: aarif Date: Thu, 11 Jul 2019 16:21:43 +0500 Subject: [PATCH] ran python-modernize and isort on files mentioned in INCR-415 changes made to comply with quality changes made to comply with quality changes made to comply with quality --- .../xmodule/xmodule/tests/test_capa_module.py | 125 ++++++------------ .../lib/xmodule/xmodule/tests/test_content.py | 14 +- .../lib/xmodule/xmodule/tests/test_export.py | 23 ++-- .../lib/xmodule/xmodule/tests/test_graders.py | 9 +- .../xmodule/xmodule/tests/test_html_module.py | 9 +- .../xmodule/xmodule/tests/test_lti20_unit.py | 7 +- .../xmodule/xmodule/tests/test_mako_module.py | 3 + .../xmodule/tests/test_split_test_module.py | 23 ++-- .../xmodule/xmodule/tests/test_word_cloud.py | 4 + .../xmodule/tests/test_xblock_wrappers.py | 43 +++--- 10 files changed, 121 insertions(+), 139 deletions(-) diff --git a/common/lib/xmodule/xmodule/tests/test_capa_module.py b/common/lib/xmodule/xmodule/tests/test_capa_module.py index eeb1490a81..c695d7b6ab 100644 --- a/common/lib/xmodule/xmodule/tests/test_capa_module.py +++ b/common/lib/xmodule/xmodule/tests/test_capa_module.py @@ -5,39 +5,41 @@ Tests of the Capa XModule # pylint: disable=missing-docstring # pylint: disable=invalid-name +from __future__ import absolute_import + import datetime import json -import random -import requests import os +import random import textwrap import unittest import ddt +import requests +import six +import webob from django.utils.encoding import smart_text from edx_user_state_client.interface import XBlockUserState from lxml import etree -from mock import Mock, patch, DEFAULT -import six -import webob -from webob.multidict import MultiDict - -import xmodule -from xmodule.tests import DATA_DIR -from capa import responsetypes -from capa.responsetypes import (StudentInputError, LoncapaProblemError, - ResponseError) -from capa.xqueue_interface import XQueueInterface -from xmodule.capa_module import ComplexEncoder, ProblemBlock +from mock import DEFAULT, Mock, patch from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator +from pytz import UTC +from six.moves import range, zip +from webob.multidict import MultiDict from xblock.field_data import DictFieldData from xblock.fields import ScopeIds from xblock.scorable import Score -from . import get_test_system -from pytz import UTC +import xmodule +from capa import responsetypes from capa.correctmap import CorrectMap +from capa.responsetypes import LoncapaProblemError, ResponseError, StudentInputError +from capa.xqueue_interface import XQueueInterface +from xmodule.capa_module import ComplexEncoder, ProblemBlock +from xmodule.tests import DATA_DIR + from ..capa_base import RANDOMIZATION, SHOWANSWER +from . import get_test_system class CapaFactory(object): @@ -76,13 +78,8 @@ class CapaFactory(object): """ Return the key stored in the capa problem answer dict """ - return ( - "%s_%d_%d" % ( - "-".join(['i4x', 'edX', 'capa_test', 'problem', 'SampleProblem%d' % cls.num]), - response_num, - input_num - ) - ) + return ("%s_%d_%d" % ("-".join(['i4x', 'edX', 'capa_test', 'problem', 'SampleProblem%d' % cls.num]), + response_num, input_num)) @classmethod def create(cls, attempts=None, problem_state=None, correct=False, xml=None, override_get_score=True, **kwargs): @@ -272,34 +269,18 @@ class ProblemBlockTest(unittest.TestCase): @ddt.data( # If show_correctness=always, Answer is visible after attempted - ({ - 'showanswer': 'attempted', - 'max_attempts': '1', - 'show_correctness': 'always', - }, False, True), + ({'showanswer': 'attempted', 'max_attempts': '1', 'show_correctness': 'always', }, False, True), # If show_correctness=never, Answer is never visible - ({ - 'showanswer': 'attempted', - 'max_attempts': '1', - 'show_correctness': 'never', - }, False, False), + ({'showanswer': 'attempted', 'max_attempts': '1', 'show_correctness': 'never', }, False, False), # If show_correctness=past_due, answer is not visible before due date - ({ - 'showanswer': 'attempted', - 'show_correctness': 'past_due', - 'max_attempts': '1', - 'due': 'tomorrow_str', - }, False, False), + ({'showanswer': 'attempted', 'show_correctness': 'past_due', 'max_attempts': '1', 'due': 'tomorrow_str', }, + False, False), # If show_correctness=past_due, answer is visible after due date - ({ - 'showanswer': 'attempted', - 'show_correctness': 'past_due', - 'max_attempts': '1', - 'due': 'yesterday_str', - }, True, True), - ) + ({'showanswer': 'attempted', 'show_correctness': 'past_due', 'max_attempts': '1', 'due': 'yesterday_str', }, + True, True)) @ddt.unpack - def test_showanswer_hide_correctness(self, problem_data, answer_available_no_attempt, answer_available_after_attempt): + def test_showanswer_hide_correctness(self, problem_data, answer_available_no_attempt, + answer_available_after_attempt): """ Ensure that the answer will not be shown when correctness is being hidden. """ @@ -618,36 +599,15 @@ class ProblemBlockTest(unittest.TestCase): @ddt.data( # Correctness not visible if due date in the future, even after using up all attempts - ({ - 'show_correctness': 'past_due', - 'max_attempts': '1', - 'attempts': '1', - 'due': 'tomorrow_str', - }, False), + ({'show_correctness': 'past_due', 'max_attempts': '1', 'attempts': '1', 'due': 'tomorrow_str', }, False), # Correctness visible if due date in the past - ({ - 'show_correctness': 'past_due', - 'max_attempts': '1', - 'attempts': '0', - 'due': 'yesterday_str', - }, True), + ({'show_correctness': 'past_due', 'max_attempts': '1', 'attempts': '0', 'due': 'yesterday_str', }, True), # Correctness not visible if due date in the future - ({ - 'show_correctness': 'past_due', - 'max_attempts': '1', - 'attempts': '0', - 'due': 'tomorrow_str', - }, False), + ({'show_correctness': 'past_due', 'max_attempts': '1', 'attempts': '0', 'due': 'tomorrow_str', }, False), # Correctness not visible because grace period hasn't expired, # even after using up all attempts - ({ - 'show_correctness': 'past_due', - 'max_attempts': '1', - 'attempts': '1', - 'due': 'yesterday_str', - 'graceperiod': 'two_day_delta_str', - }, False), - ) + ({'show_correctness': 'past_due', 'max_attempts': '1', 'attempts': '1', 'due': 'yesterday_str', + 'graceperiod': 'two_day_delta_str', }, False)) @ddt.unpack def test_show_correctness_past_due(self, problem_data, expected_result): """ @@ -903,8 +863,8 @@ class ProblemBlockTest(unittest.TestCase): self.assertEqual(xqueue_interface._http_post.call_count, 1) _, kwargs = xqueue_interface._http_post.call_args # pylint: disable=unpacking-non-sequence - self.assertItemsEqual(fpaths, kwargs['files'].keys()) - for fpath, fileobj in kwargs['files'].iteritems(): + self.assertItemsEqual(fpaths, list(kwargs['files'].keys())) + for fpath, fileobj in six.iteritems(kwargs['files']): self.assertEqual(fpath, fileobj.name) def test_submit_problem_with_files_as_xblock(self): @@ -936,8 +896,8 @@ class ProblemBlockTest(unittest.TestCase): self.assertEqual(xqueue_interface._http_post.call_count, 1) _, kwargs = xqueue_interface._http_post.call_args # pylint: disable=unpacking-non-sequence - self.assertItemsEqual(fnames, kwargs['files'].keys()) - for fpath, fileobj in kwargs['files'].iteritems(): + self.assertItemsEqual(fnames, list(kwargs['files'].keys())) + for fpath, fileobj in six.iteritems(kwargs['files']): self.assertEqual(fpath, fileobj.name) def test_submit_problem_error(self): @@ -947,7 +907,6 @@ class ProblemBlockTest(unittest.TestCase): LoncapaProblemError, ResponseError] for exception_class in exception_classes: - # Create the module module = CapaFactory.create(attempts=1, user_is_staff=False) @@ -988,7 +947,7 @@ class ProblemBlockTest(unittest.TestCase): ' File "jailed_code", line 15, in \\n' ' exec code in g_dict\\n File "", line 67, in \\n' ' File "", line 65, in check_func\\n' - 'Exception: Couldn\'t execute jailed code\\n\' with status code: 1',) + 'Exception: Couldn\'t execute jailed code\\n\' with status code: 1', ) except ResponseError as err: mock_grade.side_effect = exception_class(six.text_type(err)) get_request_dict = {CapaFactory.input_key(): '3.14'} @@ -1047,7 +1006,6 @@ class ProblemBlockTest(unittest.TestCase): LoncapaProblemError, ResponseError] for exception_class in exception_classes: - # Create the module module = CapaFactory.create(attempts=1, user_is_staff=False) @@ -1074,7 +1032,6 @@ class ProblemBlockTest(unittest.TestCase): for exception_class in [StudentInputError, LoncapaProblemError, ResponseError]: - # Create the module module = CapaFactory.create(attempts=1, user_is_staff=True) @@ -1685,7 +1642,7 @@ class ProblemBlockTest(unittest.TestCase): # check to make sure that the input_state and the keys have the same values module1.set_state_from_lcp() - self.assertEqual(module1.lcp.inputs.keys(), module1.input_state.keys()) + self.assertEqual(list(module1.lcp.inputs.keys()), list(module1.input_state.keys())) module2.set_state_from_lcp() @@ -1877,6 +1834,7 @@ class ProblemBlockTest(unittest.TestCase): """ Run the test for each possible rerandomize value """ + def _reset_and_get_seed(module): """ Reset the XModule and return the module's seed @@ -1896,7 +1854,7 @@ class ProblemBlockTest(unittest.TestCase): seed = module.seed self.assertIsNotNone(seed) - #the seed should never change because the student hasn't finished the problem + # the seed should never change because the student hasn't finished the problem self.assertEqual(seed, _reset_and_get_seed(module)) @ddt.data( @@ -2122,7 +2080,6 @@ class ProblemBlockTest(unittest.TestCase): @ddt.ddt class ProblemBlockXMLTest(unittest.TestCase): - sample_checkbox_problem_xml = textwrap.dedent("""

Title

diff --git a/common/lib/xmodule/xmodule/tests/test_content.py b/common/lib/xmodule/xmodule/tests/test_content.py index 91beed4ba7..769cddc99c 100644 --- a/common/lib/xmodule/xmodule/tests/test_content.py +++ b/common/lib/xmodule/xmodule/tests/test_content.py @@ -1,16 +1,18 @@ """Tests for contents""" +from __future__ import absolute_import + import os import unittest + import ddt from mock import Mock, patch -from path import Path as path - -from xmodule.contentstore.content import StaticContent, StaticContentStream -from xmodule.contentstore.content import ContentStore from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locator import AssetLocator, CourseLocator -from xmodule.static_content import _write_js, _list_descriptors +from path import Path as path + +from xmodule.contentstore.content import ContentStore, StaticContent, StaticContentStream +from xmodule.static_content import _list_descriptors, _write_js SAMPLE_STRING = """ This is a sample string with more than 1024 bytes, the default STREAM_DATA_CHUNK_SIZE @@ -221,6 +223,6 @@ class ContentTest(unittest.TestCase): """ output_root = path(u'common/static/xmodule/descriptors/js') file_owners = _write_js(output_root, _list_descriptors(), 'get_studio_view_js') - js_file_paths = set(file_path for file_path in sum(file_owners.values(), []) if os.path.basename(file_path).startswith('000-')) + js_file_paths = set(file_path for file_path in sum(list(file_owners.values()), []) if os.path.basename(file_path).startswith('000-')) self.assertEqual(len(js_file_paths), 1) self.assertIn("XModule.Descriptor = (function() {", open(js_file_paths.pop()).read()) diff --git a/common/lib/xmodule/xmodule/tests/test_export.py b/common/lib/xmodule/xmodule/tests/test_export.py index 41b8071687..f5b774d156 100644 --- a/common/lib/xmodule/xmodule/tests/test_export.py +++ b/common/lib/xmodule/xmodule/tests/test_export.py @@ -2,28 +2,27 @@ """ Tests of XML export """ -from __future__ import print_function +from __future__ import absolute_import, print_function + +import shutil +import unittest +from datetime import datetime, timedelta, tzinfo +from tempfile import mkdtemp +from textwrap import dedent import ddt import lxml.etree import mock import pytz -import shutil -import unittest - -from datetime import datetime, timedelta, tzinfo from django.utils.translation import ugettext_lazy from fs.osfs import OSFS +from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator from path import Path as path from six import text_type -from tempfile import mkdtemp -from textwrap import dedent - from xblock.core import XBlock -from xblock.fields import String, Scope, Integer +from xblock.fields import Integer, Scope, String from xblock.test.tools import blocks_are_equivalent -from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator from xmodule.modulestore import EdxJSONEncoder from xmodule.modulestore.xml import XMLModuleStore from xmodule.tests import DATA_DIR @@ -138,8 +137,8 @@ class RoundTripTestCase(unittest.TestCase): print("Checking key equality") self.assertItemsEqual( - initial_import.modules[course_id].keys(), - second_import.modules[course_id].keys() + list(initial_import.modules[course_id].keys()), + list(second_import.modules[course_id].keys()) ) print("Checking module equality") diff --git a/common/lib/xmodule/xmodule/tests/test_graders.py b/common/lib/xmodule/xmodule/tests/test_graders.py index 9ef6614627..e4bc0a9346 100644 --- a/common/lib/xmodule/xmodule/tests/test_graders.py +++ b/common/lib/xmodule/xmodule/tests/test_graders.py @@ -2,17 +2,18 @@ Grading tests """ +from __future__ import absolute_import + import unittest from datetime import datetime, timedelta import ddt from pytz import UTC -from lms.djangoapps.grades.scores import compute_percent from six import text_type + +from lms.djangoapps.grades.scores import compute_percent from xmodule import graders -from xmodule.graders import ( - AggregatedScore, ProblemScore, ShowCorrectness, aggregate_scores -) +from xmodule.graders import AggregatedScore, ProblemScore, ShowCorrectness, aggregate_scores class GradesheetTest(unittest.TestCase): diff --git a/common/lib/xmodule/xmodule/tests/test_html_module.py b/common/lib/xmodule/xmodule/tests/test_html_module.py index 29f23b9aed..019e1b2ff1 100644 --- a/common/lib/xmodule/xmodule/tests/test_html_module.py +++ b/common/lib/xmodule/xmodule/tests/test_html_module.py @@ -1,17 +1,18 @@ +from __future__ import absolute_import + import unittest -from mock import Mock + import ddt - from django.test.utils import override_settings - +from mock import Mock from opaque_keys.edx.locator import CourseLocator from xblock.field_data import DictFieldData from xblock.fields import ScopeIds from xmodule.html_module import CourseInfoModule, HtmlDescriptor, HtmlModule -from . import get_test_descriptor_system, get_test_system from ..x_module import PUBLIC_VIEW, STUDENT_VIEW +from . import get_test_descriptor_system, get_test_system def instantiate_descriptor(**field_data): diff --git a/common/lib/xmodule/xmodule/tests/test_lti20_unit.py b/common/lib/xmodule/xmodule/tests/test_lti20_unit.py index 43011d7a7b..d16254e5a0 100644 --- a/common/lib/xmodule/xmodule/tests/test_lti20_unit.py +++ b/common/lib/xmodule/xmodule/tests/test_lti20_unit.py @@ -1,12 +1,15 @@ # -*- coding: utf-8 -*- """Tests for LTI Xmodule LTIv2.0 functional logic.""" +from __future__ import absolute_import + import datetime import textwrap -from pytz import UTC from mock import Mock -from xmodule.lti_module import LTIDescriptor +from pytz import UTC + from xmodule.lti_2_util import LTIError +from xmodule.lti_module import LTIDescriptor from . import LogicTest diff --git a/common/lib/xmodule/xmodule/tests/test_mako_module.py b/common/lib/xmodule/xmodule/tests/test_mako_module.py index 7ba023bda7..fe68ae776a 100644 --- a/common/lib/xmodule/xmodule/tests/test_mako_module.py +++ b/common/lib/xmodule/xmodule/tests/test_mako_module.py @@ -1,6 +1,9 @@ """ Test mako_module.py """ +from __future__ import absolute_import + from unittest import TestCase + from mock import Mock from xmodule.mako_module import MakoModuleDescriptor diff --git a/common/lib/xmodule/xmodule/tests/test_split_test_module.py b/common/lib/xmodule/xmodule/tests/test_split_test_module.py index 42ce47ac8c..776856b22e 100644 --- a/common/lib/xmodule/xmodule/tests/test_split_test_module.py +++ b/common/lib/xmodule/xmodule/tests/test_split_test_module.py @@ -1,19 +1,22 @@ """ Tests for the Split Testing Module """ +from __future__ import absolute_import + import ddt import lxml -from mock import Mock, patch +import six from fs.memoryfs import MemoryFS +from mock import Mock, patch -from xmodule.partitions.tests.test_partitions import MockPartitionService, PartitionTestCase, MockUserPartitionScheme -from xmodule.tests.xml import factories as xml -from xmodule.tests.xml import XModuleXmlImportTest -from xmodule.tests import get_test_system -from xmodule.x_module import AUTHOR_VIEW, STUDENT_VIEW -from xmodule.validation import StudioValidationMessage +from xmodule.partitions.partitions import MINIMUM_STATIC_PARTITION_ID, Group, UserPartition +from xmodule.partitions.tests.test_partitions import MockPartitionService, MockUserPartitionScheme, PartitionTestCase from xmodule.split_test_module import SplitTestDescriptor, SplitTestFields, get_split_user_partitions -from xmodule.partitions.partitions import Group, UserPartition, MINIMUM_STATIC_PARTITION_ID +from xmodule.tests import get_test_system +from xmodule.tests.xml import XModuleXmlImportTest +from xmodule.tests.xml import factories as xml +from xmodule.validation import StudioValidationMessage +from xmodule.x_module import AUTHOR_VIEW, STUDENT_VIEW class SplitTestModuleFactory(xml.XmlImportFactory): @@ -88,8 +91,8 @@ class SplitTestModuleTest(XModuleXmlImportTest, PartitionTestCase): UserPartition( MINIMUM_STATIC_PARTITION_ID, 'second_partition', 'Second Partition', [ - Group(unicode(MINIMUM_STATIC_PARTITION_ID + 1), 'abel'), - Group(unicode(MINIMUM_STATIC_PARTITION_ID + 2), 'baker'), Group("103", 'charlie') + Group(six.text_type(MINIMUM_STATIC_PARTITION_ID + 1), 'abel'), + Group(six.text_type(MINIMUM_STATIC_PARTITION_ID + 2), 'baker'), Group("103", 'charlie') ], MockUserPartitionScheme() ) diff --git a/common/lib/xmodule/xmodule/tests/test_word_cloud.py b/common/lib/xmodule/xmodule/tests/test_word_cloud.py index 7c7e545894..e0f59941cb 100644 --- a/common/lib/xmodule/xmodule/tests/test_word_cloud.py +++ b/common/lib/xmodule/xmodule/tests/test_word_cloud.py @@ -1,8 +1,12 @@ # -*- coding: utf-8 -*- """Test for Word cloud Xmodule functional logic.""" +from __future__ import absolute_import + from webob.multidict import MultiDict + from xmodule.word_cloud_module import WordCloudDescriptor + from . import LogicTest diff --git a/common/lib/xmodule/xmodule/tests/test_xblock_wrappers.py b/common/lib/xmodule/xmodule/tests/test_xblock_wrappers.py index dd18e3ab88..ba3f6a04a9 100644 --- a/common/lib/xmodule/xmodule/tests/test_xblock_wrappers.py +++ b/common/lib/xmodule/xmodule/tests/test_xblock_wrappers.py @@ -6,41 +6,50 @@ functionality # For tests, ignore access to protected members # pylint: disable=protected-access -import webob +from __future__ import absolute_import + +from unittest.case import SkipTest, TestCase + import ddt +import webob from factory import ( BUILD_STRATEGY, Factory, - lazy_attribute, LazyAttributeSequence, - post_generation, SubFactory, - use_strategy, + lazy_attribute, + post_generation, + use_strategy ) from fs.memoryfs import MemoryFS from lxml import etree from mock import Mock -from unittest.case import SkipTest, TestCase - +from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator +from six.moves import range +from xblock.core import XBlock from xblock.field_data import DictFieldData from xblock.fields import ScopeIds -from xblock.core import XBlock -from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator - -from xmodule.x_module import ModuleSystem, XModule, XModuleDescriptor, DescriptorSystem, STUDENT_VIEW, STUDIO_VIEW, PUBLIC_VIEW from xmodule.annotatable_module import AnnotatableDescriptor +from xmodule.conditional_module import ConditionalDescriptor from xmodule.course_module import CourseDescriptor from xmodule.html_module import HtmlDescriptor from xmodule.poll_module import PollDescriptor -from xmodule.word_cloud_module import WordCloudDescriptor -from xmodule.seq_module import SequenceDescriptor -from xmodule.conditional_module import ConditionalDescriptor from xmodule.randomize_module import RandomizeDescriptor -from xmodule.vertical_block import VerticalBlock -from xmodule.wrapper_module import WrapperBlock +from xmodule.seq_module import SequenceDescriptor from xmodule.tests import get_test_descriptor_system, get_test_system - +from xmodule.vertical_block import VerticalBlock +from xmodule.word_cloud_module import WordCloudDescriptor +from xmodule.wrapper_module import WrapperBlock +from xmodule.x_module import ( + PUBLIC_VIEW, + STUDENT_VIEW, + STUDIO_VIEW, + DescriptorSystem, + ModuleSystem, + XModule, + XModuleDescriptor +) # A dictionary that maps specific XModuleDescriptor classes without children # to a list of sample field values to test with. @@ -238,7 +247,7 @@ class ContainerDescriptorFactory(LeafDescriptorFactory): Factory to generate XModuleDescriptors that are containers. """ runtime = SubFactory(ContainerDescriptorRuntimeFactory) - children = range(3) + children = list(range(3)) class ContainerModuleFactory(LeafModuleFactory):