INCR-162 Migrated and cleaned up imports on /common/lib/capa/capa/tests/

This commit is contained in:
Jolyon Bloomfield
2019-04-01 15:33:14 -04:00
parent 63f799ff8f
commit 932a76c958
14 changed files with 106 additions and 72 deletions

View File

@@ -1,19 +1,20 @@
"""Tools for helping with testing capa."""
from __future__ import absolute_import
import gettext
from path import Path
import os
import os.path
import xml.sax.saxutils as saxutils
import fs.osfs
import six
from mako.lookup import TemplateLookup
from mock import MagicMock, Mock
from path import Path
from capa.capa_problem import LoncapaProblem, LoncapaSystem
from capa.inputtypes import Status
from mock import Mock, MagicMock
from mako.lookup import TemplateLookup
import xml.sax.saxutils as saxutils
TEST_DIR = os.path.dirname(os.path.realpath(__file__))

View File

@@ -1,14 +1,17 @@
from lxml import etree
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
import six
from lxml import etree
from six.moves import range, zip
class ResponseXMLFactory(object):
class ResponseXMLFactory(six.with_metaclass(ABCMeta, object)):
""" Abstract base class for capa response XML factories.
Subclasses override create_response_element and
create_input_element to produce XML of particular response types"""
__metaclass__ = ABCMeta
@abstractmethod
def create_response_element(self, **kwargs):
""" Subclasses override to return an etree element
@@ -541,7 +544,7 @@ class FormulaResponseXMLFactory(ResponseXMLFactory):
low_range_vals = [str(f[0]) for f in sample_dict.values()]
high_range_vals = [str(f[1]) for f in sample_dict.values()]
sample_str = (
",".join(sample_dict.keys()) + "@" +
",".join(list(sample_dict.keys())) + "@" +
",".join(low_range_vals) + ":" +
",".join(high_range_vals) +
"#" + str(num_samples)
@@ -727,7 +730,7 @@ class StringResponseXMLFactory(ResponseXMLFactory):
response_element = etree.Element("stringresponse")
# Set the answer attribute
response_element.set("answer", unicode(answer))
response_element.set("answer", six.text_type(answer))
# Set the case sensitivity and regexp:
type_value = ''

View File

@@ -3,10 +3,13 @@ Tests the logic of the "answer-pool" attribute, e.g.
<choicegroup answer-pool="4">
"""
import unittest
from __future__ import absolute_import
import textwrap
from capa.tests.helpers import test_capa_system, new_loncapa_problem
import unittest
from capa.responsetypes import LoncapaProblemError
from capa.tests.helpers import new_loncapa_problem, test_capa_system
class CapaAnswerPoolTest(unittest.TestCase):
@@ -58,7 +61,7 @@ class CapaAnswerPoolTest(unittest.TestCase):
self.assertRegexpMatches(the_html, r"<div>\{.*'1_solution_2'.*\}</div>")
self.assertEqual(the_html, problem.get_html(), 'should be able to call get_html() twice')
# Check about masking
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertTrue(response.has_answerpool())
self.assertEqual(response.unmask_order(), ['choice_3', 'choice_5', 'choice_1', 'choice_4'])
@@ -70,7 +73,7 @@ class CapaAnswerPoolTest(unittest.TestCase):
self.assertRegexpMatches(the_html, r"<div>.*\[.*'wrong-1'.*'wrong-4'.*'wrong-3'.*'correct-1'.*\].*</div>")
self.assertRegexpMatches(the_html, r"<div>\{.*'1_solution_1'.*\}</div>")
# Check about masking
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertTrue(hasattr(response, 'has_answerpool'))
self.assertEqual(response.unmask_order(), ['choice_0', 'choice_4', 'choice_3', 'choice_2'])
@@ -117,7 +120,7 @@ class CapaAnswerPoolTest(unittest.TestCase):
self.assertRegexpMatches(the_html, r"<div>\{.*'1_solution_1'.*'1_solution_2'.*\}</div>")
self.assertEqual(the_html, problem.get_html(), 'should be able to call get_html() twice')
# Check about masking
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertFalse(response.has_answerpool())
@@ -161,7 +164,7 @@ class CapaAnswerPoolTest(unittest.TestCase):
the_html = problem.get_html()
self.assertRegexpMatches(the_html, r"<div>.*\[.*'wrong-1'.*'wrong-2'.*'correct-1'.*'wrong-3'.*'wrong-4'.*'correct-2'.*\].*</div>")
self.assertRegexpMatches(the_html, r"<div>\{.*'1_solution_1'.*'1_solution_2'.*\}</div>")
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertFalse(response.has_answerpool())
@@ -279,7 +282,7 @@ class CapaAnswerPoolTest(unittest.TestCase):
the_html = problem.get_html()
self.assertRegexpMatches(the_html, r"<div>.*\[.*'correct-2'.*'wrong-1'.*'wrong-2'.*.*'wrong-3'.*'wrong-4'.*\].*</div>")
self.assertRegexpMatches(the_html, r"<div>\{.*'1_solution_2'.*\}</div>")
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertEqual(response.unmask_order(), ['choice_5', 'choice_0', 'choice_1', 'choice_3', 'choice_4'])
@@ -540,7 +543,7 @@ class CapaAnswerPoolTest(unittest.TestCase):
self.assertRegexpMatches(the_html, str1)
# attributes *not* present
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertFalse(response.has_answerpool())

View File

@@ -1,14 +1,16 @@
"""
Test capa problem.
"""
import ddt
import textwrap
from __future__ import absolute_import
import textwrap
import unittest
import ddt
import six
from lxml import etree
from markupsafe import Markup
from mock import patch
import unittest
from capa.tests.helpers import new_loncapa_problem
from openedx.core.djangolib.markup import HTML

View File

@@ -2,9 +2,12 @@
Tests to verify that CorrectMap behaves correctly
"""
import unittest
from capa.correctmap import CorrectMap
from __future__ import absolute_import
import datetime
import unittest
from capa.correctmap import CorrectMap
class CorrectMapTest(unittest.TestCase):

View File

@@ -1,9 +1,12 @@
from lxml import etree
from __future__ import absolute_import
import unittest
import xml.sax.saxutils as saxutils
from capa.tests.helpers import test_capa_system
from lxml import etree
from capa import customrender
from capa.tests.helpers import test_capa_system
# just a handy shortcut
lookup_tag = customrender.registry.get_class_for_tag

View File

@@ -3,10 +3,13 @@
Tests of extended hints
"""
from __future__ import absolute_import
import unittest
from ddt import ddt, data, unpack
from ddt import data, ddt, unpack
from capa.tests.helpers import load_fixture, new_loncapa_problem
# With the use of ddt, some of the data expected_string cases below are naturally long stretches
# of text text without whitespace. I think it's best to leave such lines intact
@@ -14,8 +17,6 @@ from ddt import ddt, data, unpack
# pylint: disable=line-too-long
# For out many ddt data cases, prefer a compact form of { .. }
from capa.tests.helpers import new_loncapa_problem, load_fixture
class HintTest(unittest.TestCase):
"""Base class for tests of extended hinting functionality."""

View File

@@ -1,19 +1,22 @@
"""
CAPA HTML rendering tests.
"""
from __future__ import absolute_import
import os
import textwrap
import unittest
import ddt
import mock
import os
from lxml import etree
# Changes formatting of empty elements; import here to avoid test order dependence
import xmodule.modulestore.xml # pylint: disable=unused-import
from capa.tests.helpers import test_capa_system, new_loncapa_problem
from lxml import etree
from capa.tests.helpers import new_loncapa_problem, test_capa_system
from openedx.core.djangolib.markup import HTML
from .response_xml_factory import StringResponseXMLFactory, CustomResponseXMLFactory
from .response_xml_factory import CustomResponseXMLFactory, StringResponseXMLFactory
@ddt.ddt

View File

@@ -2,16 +2,19 @@
Tests for the logic in input type mako templates.
"""
from __future__ import absolute_import
import json
import unittest
from collections import OrderedDict
from capa.inputtypes import Status
from capa.tests.helpers import capa_render_template
from lxml import etree
from mako import exceptions
from openedx.core.djangolib.markup import HTML
from six.moves import range
from capa.inputtypes import Status
from capa.tests.helpers import capa_render_template
from openedx.core.djangolib.markup import HTML
from xmodule.stringify import stringify_children
@@ -39,7 +42,7 @@ class TemplateTestCase(unittest.TestCase):
('desc-2', '<em>description</em> <mark>text</mark> 2')
]
)
DESCRIPTION_IDS = ' '.join(DESCRIPTIONS.keys())
DESCRIPTION_IDS = ' '.join(list(DESCRIPTIONS.keys()))
RESPONSE_DATA = {
'label': 'question text 101',
'descriptions': DESCRIPTIONS

View File

@@ -16,21 +16,26 @@ TODO:
- test funny xml chars -- should never get xml parse error if things are escaped properly.
"""
from __future__ import absolute_import
import json
import textwrap
import unittest
import xml.sax.saxutils as saxutils
from collections import OrderedDict
import six
from lxml import etree
from lxml.html import fromstring
from mock import ANY, patch
from pyparsing import ParseException
from six.moves import zip
from capa import inputtypes
from capa.checker import DemoSystem
from capa.tests.helpers import test_capa_system
from capa.xqueue_interface import XQUEUE_TIMEOUT
from lxml import etree
from lxml.html import fromstring
from mock import ANY, patch
from openedx.core.djangolib.markup import HTML
from pyparsing import ParseException
# just a handy shortcut
lookup_tag = inputtypes.registry.get_class_for_tag
@@ -1608,7 +1613,7 @@ class TestStatus(unittest.TestCase):
"""
statobj = inputtypes.Status('test')
self.assertEqual(str(statobj), 'test')
self.assertEqual(unicode(statobj), u'test')
self.assertEqual(six.text_type(statobj), u'test')
def test_classes(self):
"""

View File

@@ -3,32 +3,33 @@
Tests of responsetypes
"""
from cStringIO import StringIO
from datetime import datetime
from __future__ import absolute_import
import json
import os
import pyparsing
import random
import textwrap
import unittest
import zipfile
from cStringIO import StringIO
from datetime import datetime
import mock
import pyparsing
import requests
import six
from pytz import UTC
from six import text_type
import requests
from capa.tests.helpers import new_loncapa_problem, test_capa_system, load_fixture
import calc
from capa.responsetypes import LoncapaProblemError, \
StudentInputError, ResponseError
from capa.correctmap import CorrectMap
from capa.responsetypes import LoncapaProblemError, ResponseError, StudentInputError
from capa.tests.helpers import load_fixture, new_loncapa_problem, test_capa_system
from capa.tests.response_xml_factory import (
AnnotationResponseXMLFactory,
ChoiceResponseXMLFactory,
CodeResponseXMLFactory,
ChoiceTextResponseXMLFactory,
CodeResponseXMLFactory,
CustomResponseXMLFactory,
FormulaResponseXMLFactory,
ImageResponseXMLFactory,
@@ -38,7 +39,7 @@ from capa.tests.response_xml_factory import (
SchematicResponseXMLFactory,
StringResponseXMLFactory,
SymbolicResponseXMLFactory,
TrueFalseResponseXMLFactory,
TrueFalseResponseXMLFactory
)
from capa.util import convert_files_to_filenames
from capa.xqueue_interface import dateformat
@@ -572,8 +573,8 @@ class FormulaResponseTest(ResponseTest):
tolerance="1%",
answer="x"
)
self.assertTrue(problem.responders.values()[0].validate_answer('14*x'))
self.assertFalse(problem.responders.values()[0].validate_answer('3*y+2*x'))
self.assertTrue(list(problem.responders.values())[0].validate_answer('14*x'))
self.assertFalse(list(problem.responders.values())[0].validate_answer('3*y+2*x'))
class StringResponseTest(ResponseTest): # pylint: disable=missing-docstring
@@ -1349,7 +1350,7 @@ class NumericalResponseTest(ResponseTest): # pylint: disable=missing-docstring
Test `get_score` is working for additional answers.
"""
problem = self.build_problem(answer='100', additional_answers={'1': ''})
responder = problem.responders.values()[0]
responder = list(problem.responders.values())[0]
# Check primary answer.
new_cmap = responder.get_score({'1_2_1': '100'})
@@ -1648,14 +1649,14 @@ class NumericalResponseTest(ResponseTest): # pylint: disable=missing-docstring
def test_compare_answer(self):
"""Tests the answer compare function."""
problem = self.build_problem(answer="42")
responder = problem.responders.values()[0]
responder = list(problem.responders.values())[0]
self.assertTrue(responder.compare_answer('48', '8*6'))
self.assertFalse(responder.compare_answer('48', '9*5'))
def test_validate_answer(self):
"""Tests the answer validation function."""
problem = self.build_problem(answer="42")
responder = problem.responders.values()[0]
responder = list(problem.responders.values())[0]
self.assertTrue(responder.validate_answer('23.5'))
self.assertFalse(responder.validate_answer('fish'))
@@ -2365,10 +2366,10 @@ class CustomResponseTest(ResponseTest): # pylint: disable=missing-docstring
correct_map = problem.grade_answers(input_dict)
self.assertNotEqual(problem.student_answers.keys(), correct_order)
self.assertNotEqual(list(problem.student_answers.keys()), correct_order)
# euqal to correct order after sorting at get_score
self.assertListEqual(problem.responders.values()[0].context['idset'], correct_order)
self.assertListEqual(list(problem.responders.values())[0].context['idset'], correct_order)
self.assertEqual(correct_map.get_correctness('1_2_1'), 'correct')
self.assertEqual(correct_map.get_correctness('1_2_9'), 'correct')
@@ -2719,7 +2720,7 @@ class ChoiceTextResponseTest(ResponseTest):
radiotextgroup.
"""
for name, inputs in self.TEST_INPUTS.iteritems():
for name, inputs in six.iteritems(self.TEST_INPUTS):
# Turn submission into the form expected when grading this problem.
submission = self._make_answer_dict(inputs)
# Lookup the problem_name, and the whether this test problem
@@ -2799,7 +2800,7 @@ class ChoiceTextResponseTest(ResponseTest):
"checkbox_2_choices_2_inputs": checkbox_two_choices_two_inputs
}
for name, inputs in inputs.iteritems():
for name, inputs in six.iteritems(inputs):
submission = self._make_answer_dict(inputs)
# Load the test problem's name and desired correctness
problem_name, correctness = scenarios[name]

View File

@@ -1,11 +1,11 @@
"""Tests the capa shuffle and name-masking."""
from __future__ import print_function
from __future__ import absolute_import, print_function
import unittest
import textwrap
import unittest
from capa.tests.helpers import test_capa_system, new_loncapa_problem
from capa.responsetypes import LoncapaProblemError
from capa.tests.helpers import new_loncapa_problem, test_capa_system
class CapaShuffleTest(unittest.TestCase):
@@ -34,7 +34,7 @@ class CapaShuffleTest(unittest.TestCase):
the_html = problem.get_html()
self.assertRegexpMatches(the_html, r"<div>.*\[.*'Banana'.*'Apple'.*'Chocolate'.*'Donut'.*\].*</div>")
# Check that choice name masking is enabled and that unmasking works
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertEqual(response.unmask_order(), ['choice_1', 'choice_0', 'choice_2', 'choice_3'])
self.assertEqual(the_html, problem.get_html(), 'should be able to call get_html() twice')
@@ -55,7 +55,7 @@ class CapaShuffleTest(unittest.TestCase):
problem = new_loncapa_problem(xml_str, seed=0)
# B A C D
# Check that the custom name= names come through
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertTrue(response.has_shuffle())
self.assertEqual(response.unmask_order(), ['choice_0', 'choice_aaa', 'choice_1', 'choice_ddd'])
@@ -90,7 +90,7 @@ class CapaShuffleTest(unittest.TestCase):
problem = new_loncapa_problem(xml_str, seed=0)
the_html = problem.get_html()
self.assertRegexpMatches(the_html, r"<div>.*\[.*'Apple'.*\].*</div>")
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertTrue(response.has_shuffle())
self.assertEqual(response.unmask_order(), ['choice_0'])
@@ -131,7 +131,7 @@ class CapaShuffleTest(unittest.TestCase):
problem = new_loncapa_problem(xml_str)
the_html = problem.get_html()
self.assertRegexpMatches(the_html, r"<div>.*\[.*'Apple'.*'Banana'.*'Chocolate'.*'Donut'.*\].*</div>")
response = problem.responders.values()[0]
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())
self.assertFalse(response.has_shuffle())
@@ -281,7 +281,7 @@ class CapaShuffleTest(unittest.TestCase):
self.assertRegexpMatches(html, r"<div>.*\[.*'Banana'.*'Apple'.*'Chocolate'.*'Donut'.*\].*</div>.*" +
r"<div>.*\[.*'C'.*'A'.*'D'.*'B'.*\].*</div>")
# Look at the responses in their authored order
responses = sorted(problem.responders.values(), key=lambda resp: int(resp.id[resp.id.rindex('_') + 1:]))
responses = sorted(list(problem.responders.values()), key=lambda resp: int(resp.id[resp.id.rindex('_') + 1:]))
self.assertFalse(responses[0].has_mask())
self.assertTrue(responses[0].has_shuffle())
self.assertTrue(responses[1].has_shuffle())

View File

@@ -3,11 +3,14 @@ Tests the logic of the "targeted-feedback" attribute for MultipleChoice question
i.e. those with the <multiplechoiceresponse> element
"""
import unittest
from __future__ import absolute_import
import textwrap
import unittest
# Changes formatting of empty elements; import here to avoid test order dependence
import xmodule.modulestore.xml # pylint: disable=unused-import
from capa.tests.helpers import test_capa_system, new_loncapa_problem, load_fixture
from capa.tests.helpers import load_fixture, new_loncapa_problem, test_capa_system
class CapaTargetedFeedbackTest(unittest.TestCase):

View File

@@ -1,11 +1,14 @@
"""
Tests capa util
"""
from __future__ import absolute_import
import unittest
from lxml import etree
from capa.tests.helpers import test_capa_system
from capa.util import compare_with_tolerance, sanitize_html, get_inner_html_from_xpath, remove_markup
from capa.util import compare_with_tolerance, get_inner_html_from_xpath, remove_markup, sanitize_html
class UtilTest(unittest.TestCase):