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
This commit is contained in:
aarif
2019-07-11 16:21:43 +05:00
committed by root
parent c89ecb384f
commit 46fe6fdcea
10 changed files with 121 additions and 139 deletions

View File

@@ -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 <module>\\n'
' exec code in g_dict\\n File "<string>", line 67, in <module>\\n'
' File "<string>", 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("""
<problem>
<p>Title</p>

View File

@@ -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())

View File

@@ -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")

View File

@@ -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):

View File

@@ -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):

View File

@@ -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

View File

@@ -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

View File

@@ -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()
)

View File

@@ -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

View File

@@ -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):