Пример #1
0
 def setUp(self):
     self.module = XModule(descriptor=Mock(),
                           field_data=Mock(),
                           runtime=Mock(),
                           scope_ids=Mock())
     self.module.handle_ajax = Mock(return_value='{}')
     self.request = webob.Request({})
Пример #2
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        # NOTE: calling self.get_children() creates a circular reference--
        # it calls get_child_descriptors() internally, but that doesn't work until
        # we've picked a choice
        num_choices = len(self.descriptor.get_children())

        if self.choice > num_choices:
            # Oops.  Children changed. Reset.
            self.choice = None

        if self.choice is None:
            # choose one based on the system seed, or randomly if that's not available
            if num_choices > 0:
                if self.system.seed is not None:
                    self.choice = self.system.seed % num_choices
                else:
                    self.choice = random.randrange(0, num_choices)

        if self.choice is not None:
            self.child_descriptor = self.descriptor.get_children()[self.choice]
            # Now get_children() should return a list with one element
            log.debug("children of randomize module (should be only 1): %s",
                      self.get_children())
            self.child = self.get_children()[0]
        else:
            self.child_descriptor = None
            self.child = None
Пример #3
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        # NOTE: calling self.get_children() creates a circular reference--
        # it calls get_child_descriptors() internally, but that doesn't work until
        # we've picked a choice
        num_choices = len(self.descriptor.get_children())

        if self.choice > num_choices:
            # Oops.  Children changed. Reset.
            self.choice = None

        if self.choice is None:
            # choose one based on the system seed, or randomly if that's not available
            if num_choices > 0:
                if self.system.seed is not None:
                    self.choice = self.system.seed % num_choices
                else:
                    self.choice = random.randrange(0, num_choices)

        if self.choice is not None:
            self.child_descriptor = self.descriptor.get_children()[self.choice]
            # Now get_children() should return a list with one element
            log.debug("children of randomize module (should be only 1): %s",
                      self.get_children())
            self.child = self.get_children()[0]
        else:
            self.child_descriptor = None
            self.child = None
Пример #4
0
class TestXModuleHandler(TestCase):
    """
    Tests that the xmodule_handler function correctly wraps handle_ajax
    """
    def setUp(self):
        self.module = XModule(descriptor=Mock(),
                              field_data=Mock(),
                              runtime=Mock(),
                              scope_ids=Mock())
        self.module.handle_ajax = Mock(return_value='{}')
        self.request = webob.Request({})

    def test_xmodule_handler_passed_data(self):
        self.module.xmodule_handler(self.request)
        self.module.handle_ajax.assert_called_with(None, self.request.POST)

    def test_xmodule_handler_dispatch(self):
        self.module.xmodule_handler(self.request, 'dispatch')
        self.module.handle_ajax.assert_called_with('dispatch',
                                                   self.request.POST)

    def test_xmodule_handler_return_value(self):
        response = self.module.xmodule_handler(self.request)
        self.assertIsInstance(response, webob.Response)
        self.assertEqual(response.body, '{}')
Пример #5
0
    def __init__(self, system, location, descriptor, model_data):
        XModule.__init__(self, system, location, descriptor, model_data)

        due_date = self.due

        if self.graceperiod is not None and due_date:
            self.close_date = due_date + self.graceperiod
        else:
            self.close_date = due_date

        if self.seed is None:
            self.choose_new_seed()

        # Need the problem location in openendedresponse to send out.  Adding
        # it to the system here seems like the least clunky way to get it
        # there.
        self.system.set('location', self.location.url())

        try:
            # TODO (vshnayder): move as much as possible of this work and error
            # checking to descriptor load time
            self.lcp = self.new_lcp(self.get_state_for_lcp())

            # At this point, we need to persist the randomization seed
            # so that when the problem is re-loaded (to check/view/save)
            # it stays the same.
            # However, we do not want to write to the database
            # every time the module is loaded.
            # So we set the seed ONLY when there is not one set already
            if self.seed is None:
                self.seed = self.lcp.seed

        except Exception as err:
            msg = 'cannot create LoncapaProblem {loc}: {err}'.format(
                loc=self.location.url(), err=err)
            # TODO (vshnayder): do modules need error handlers too?
            # We shouldn't be switching on DEBUG.
            if self.system.DEBUG:
                log.warning(msg)
                # TODO (vshnayder): This logic should be general, not here--and may
                # want to preserve the data instead of replacing it.
                # e.g. in the CMS
                msg = '<p>%s</p>' % msg.replace('<', '&lt;')
                msg += '<p><pre>%s</pre></p>' % traceback.format_exc().replace(
                    '<', '&lt;')
                # create a dummy problem with error message instead of failing
                problem_text = (
                    '<problem><text><span class="inline-error">'
                    'Problem %s has an error:</span>%s</text></problem>' %
                    (self.location.url(), msg))
                self.lcp = self.new_lcp(self.get_state_for_lcp(),
                                        text=problem_text)
            else:
                # add extra info and raise
                raise Exception(msg), None, sys.exc_info()[2]

            self.set_state_from_lcp()

        assert self.seed is not None
Пример #6
0
    def __init__(self, *args, **kwargs):
        """
        Accepts the same arguments as xmodule.x_module:XModule.__init__
        """
        XModule.__init__(self, *args, **kwargs)

        due_date = self.due

        if self.graceperiod is not None and due_date:
            self.close_date = due_date + self.graceperiod
        else:
            self.close_date = due_date

        if self.seed is None:
            self.choose_new_seed()

        # Need the problem location in openendedresponse to send out.  Adding
        # it to the system here seems like the least clunky way to get it
        # there.
        self.system.set("location", self.location.url())

        try:
            # TODO (vshnayder): move as much as possible of this work and error
            # checking to descriptor load time
            self.lcp = self.new_lcp(self.get_state_for_lcp())

            # At this point, we need to persist the randomization seed
            # so that when the problem is re-loaded (to check/view/save)
            # it stays the same.
            # However, we do not want to write to the database
            # every time the module is loaded.
            # So we set the seed ONLY when there is not one set already
            if self.seed is None:
                self.seed = self.lcp.seed

        except Exception as err:
            msg = u"cannot create LoncapaProblem {loc}: {err}".format(loc=self.location.url(), err=err)
            # TODO (vshnayder): do modules need error handlers too?
            # We shouldn't be switching on DEBUG.
            if self.system.DEBUG:
                log.warning(msg)
                # TODO (vshnayder): This logic should be general, not here--and may
                # want to preserve the data instead of replacing it.
                # e.g. in the CMS
                msg = u"<p>{msg}</p>".format(msg=cgi.escape(msg))
                msg += u"<p><pre>{tb}</pre></p>".format(tb=cgi.escape(traceback.format_exc()))
                # create a dummy problem with error message instead of failing
                problem_text = (
                    u'<problem><text><span class="inline-error">'
                    u"Problem {url} has an error:</span>{msg}</text></problem>".format(url=self.location.url(), msg=msg)
                )
                self.lcp = self.new_lcp(self.get_state_for_lcp(), text=problem_text)
            else:
                # add extra info and raise
                raise Exception(msg), None, sys.exc_info()[2]

            self.set_state_from_lcp()

        assert self.seed is not None
Пример #7
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        # if position is specified in system, then use that instead
        if getattr(self.system, 'position', None) is not None:
            self.position = int(self.system.position)

        self.rendered = False
Пример #8
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        # if position is specified in system, then use that instead
        if getattr(self.system, 'position', None) is not None:
            self.position = int(self.system.position)

        self.rendered = False
Пример #9
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        # if position is specified in system, then use that instead
        if self.system.get('position'):
            self.position = int(self.system.get('position'))

        self.rendered = False
 def setUp(self):
     super(TestXModuleHandler, self).setUp()  # lint-amnesty, pylint: disable=super-with-arguments
     self.module = XModule(descriptor=Mock(),
                           field_data=Mock(),
                           runtime=Mock(),
                           scope_ids=Mock())
     self.module.handle_ajax = Mock(return_value='{}')
     self.request = webob.Request({})
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        if self.group is None:
            self.group = group_from_value(
                self.group_portions.items(),
                random.uniform(0, 1)
            )
Пример #12
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        # if position is specified in system, then use that instead
        if self.system.get('position'):
            self.position = int(self.system.get('position'))

        self.rendered = False
Пример #13
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        xmltree = etree.fromstring(self.data)
        self.youtube = xmltree.get('youtube')
        self.show_captions = xmltree.get('show_captions', 'true')
        self.source = self._get_source(xmltree)
        self.track = self._get_track(xmltree)
        self.start_time, self.end_time = self.get_timeframe(xmltree)
Пример #14
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        xmltree = etree.fromstring(self.data)

        self.instructions = self._extract_instructions(xmltree)
        self.content = etree.tostring(xmltree, encoding='unicode')
        self.element_id = self.location.html_id()
        self.highlight_colors = ['yellow', 'orange', 'purple', 'blue', 'green']
Пример #15
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        xmltree = etree.fromstring(self.data)

        self.instructions = self._extract_instructions(xmltree)
        self.content = etree.tostring(xmltree, encoding='unicode')
        self.element_id = self.location.html_id()
        self.highlight_colors = ['yellow', 'orange', 'purple', 'blue', 'green']
Пример #16
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        xmltree = etree.fromstring(self.data)
        self.youtube = xmltree.get('youtube')
        self.show_captions = xmltree.get('show_captions', 'true')
        self.source = self._get_source(xmltree)
        self.track = self._get_track(xmltree)
        self.start_time, self.end_time = self.get_timeframe(xmltree)
Пример #17
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        xmltree = etree.fromstring(self.data)

        self.instructions = self._extract_instructions(xmltree)
        self.content = etree.tostring(xmltree, encoding="unicode")
        self.element_id = self.location.html_id()
        self.highlight_colors = ["yellow", "orange", "purple", "blue", "green"]
Пример #18
0
 def __init__(self, *args, **kwargs):
     """
     Example:
      <foldit show_basic_score="true"
         required_level="4"
         required_sublevel="3"
         required_level_half_credit="2"
         required_sublevel_half_credit="3"
         show_leaderboard="false"/>
     """
     XModule.__init__(self, *args, **kwargs)
     self.due_time = self.due
Пример #19
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)
        """

        Example:
         <foldit show_basic_score="true"
            required_level="4"
            required_sublevel="3"
            show_leaderboard="false"/>
        """

        self.due_time = time_to_datetime(self.due)
Пример #20
0
 def __init__(self, *args, **kwargs):
     """
     Example:
      <foldit show_basic_score="true"
         required_level="4"
         required_sublevel="3"
         required_level_half_credit="2"
         required_sublevel_half_credit="3"
         show_leaderboard="false"/>
     """
     XModule.__init__(self, *args, **kwargs)
     self.due_time = self.due
Пример #21
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)
        """

        Example:
         <foldit show_basic_score="true"
            required_level="4"
            required_sublevel="3"
            show_leaderboard="false"/>
        """

        self.due_time = time_to_datetime(self.due)
Пример #22
0
 def __init__(self, *args, **kwargs):
     XModule.__init__(self, *args, **kwargs)
     xmltree = etree.fromstring(self.data)
     self.youtube_streams = xmltree.get('youtube')
     self.sub = xmltree.get('sub')
     self.position = 0
     self.show_captions = xmltree.get('show_captions', 'true')
     self.sources = {
         'main': self._get_source(xmltree),
         'mp4': self._get_source(xmltree, ['mp4']),
         'webm': self._get_source(xmltree, ['webm']),
         'ogv': self._get_source(xmltree, ['ogv']),
     }
     self.track = self._get_track(xmltree)
     self.start_time, self.end_time = self._get_timeframe(xmltree)
Пример #23
0
 def __init__(self, *args, **kwargs):
     XModule.__init__(self, *args, **kwargs)
     xmltree = etree.fromstring(self.data)
     self.youtube_streams = xmltree.get('youtube')
     self.sub = xmltree.get('sub')
     self.position = 0
     self.show_captions = xmltree.get('show_captions', 'true')
     self.sources = {
         'main': self._get_source(xmltree),
         'mp4': self._get_source(xmltree, ['mp4']),
         'webm': self._get_source(xmltree, ['webm']),
         'ogv': self._get_source(xmltree, ['ogv']),
     }
     self.track = self._get_track(xmltree)
     self.start_time, self.end_time = self._get_timeframe(xmltree)
Пример #24
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)
        xmltree = etree.fromstring(self.data)

        # Front-end expects an empty string, or a properly formatted string with YouTube IDs.
        self.youtube_streams = xmltree.get('youtube', '')

        self.sub = xmltree.get('sub')
        self.position = 0
        self.show_captions = xmltree.get('show_captions', 'true')
        self.sources = {
            'main': self._get_source(xmltree),
            'mp4': self._get_source(xmltree, ['mp4']),
            'webm': self._get_source(xmltree, ['webm']),
            'ogv': self._get_source(xmltree, ['ogv']),
        }
        self.track = self._get_track(xmltree)
        self.start_time, self.end_time = self.get_timeframe(xmltree)
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)
        xmltree = etree.fromstring(self.data)

        # Front-end expects an empty string, or a properly formatted string with YouTube IDs.
        self.youtube_streams = xmltree.get('youtube', '')

        self.sub = xmltree.get('sub')
        self.position = 0
        self.show_captions = xmltree.get('show_captions', 'true')
        self.sources = {
            'main': self._get_source(xmltree),
            'mp4': self._get_source(xmltree, ['mp4']),
            'webm': self._get_source(xmltree, ['webm']),
            'ogv': self._get_source(xmltree, ['ogv']),
        }
        self.track = self._get_track(xmltree)
        self.start_time, self.end_time = self.get_timeframe(xmltree)
Пример #26
0
 def __init__(self, *args, **kwargs):
     XModule.__init__(self, *args, **kwargs)
     if self.data:
         try:
             xml = etree.fromstring(self.data)
             if xml.tag == 'video':
                 if xml.get('display_name'):
                     self.display_name = xml.get('display_name')
                 if xml.findall('source'):
                     self.source = [ele.get('src') for ele in xml.findall('source')][0]
                 for ele in xml.findall('track'):
                     if ele.get('srclang') == 'zh' and ele.get('src'):
                         self.track_zh = ele.get('src')
                     if ele.get('srclang') == 'en' and ele.get('src'):
                         self.track_en = ele.get('src')
         except Exception as e:
             log.debug("error parsing video xml data")
             pass
     
     self.sourceType = self._get_source_type(self.source)
Пример #27
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)
        if self.data:
            try:
                xml = etree.fromstring(self.data)
                if xml.tag == 'video':
                    if xml.get('display_name'):
                        self.display_name = xml.get('display_name')
                    if xml.findall('source'):
                        self.source = [
                            ele.get('src') for ele in xml.findall('source')
                        ][0]
                    for ele in xml.findall('track'):
                        if ele.get('srclang') == 'zh' and ele.get('src'):
                            self.track_zh = ele.get('src')
                        if ele.get('srclang') == 'en' and ele.get('src'):
                            self.track_en = ele.get('src')
            except Exception as e:
                log.debug("error parsing video xml data")
                pass

        self.sourceType = self._get_source_type(self.source)
Пример #28
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)
        # We need to know whether we are working with a FormulaResponse problem.
        try:
            responder = self.get_display_items()[0].lcp.responders.values()[0]
        except (IndexError, AttributeError):
            log.exception('Unable to find a capa problem child.')
            return

        self.is_formula = isinstance(self, FormulaResponse)
        if self.is_formula:
            self.answer_to_str = self.formula_answer_to_str
        else:
            self.answer_to_str = self.numerical_answer_to_str
        # compare_answer is expected to return whether its two inputs are close enough
        # to be equal, or raise a StudentInputError if one of the inputs is malformatted.
        if hasattr(responder, 'compare_answer') and hasattr(responder, 'validate_answer'):
            self.compare_answer = responder.compare_answer
            self.validate_answer = responder.validate_answer
        else:
            # This response type is not supported!
            log.exception('Response type not supported for hinting: ' + str(responder))
Пример #29
0
class TestXModuleHandler(TestCase):
    """
    Tests that the xmodule_handler function correctly wraps handle_ajax
    """

    def setUp(self):
        self.module = XModule(descriptor=Mock(), field_data=Mock(), runtime=Mock(), scope_ids=Mock())
        self.module.handle_ajax = Mock(return_value='{}')
        self.request = webob.Request({})

    def test_xmodule_handler_passed_data(self):
        self.module.xmodule_handler(self.request)
        self.module.handle_ajax.assert_called_with(None, self.request.POST)

    def test_xmodule_handler_dispatch(self):
        self.module.xmodule_handler(self.request, 'dispatch')
        self.module.handle_ajax.assert_called_with('dispatch', self.request.POST)

    def test_xmodule_handler_return_value(self):
        response = self.module.xmodule_handler(self.request)
        self.assertIsInstance(response, webob.Response)
        self.assertEqual(response.body, '{}')
Пример #30
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)
        xmltree = etree.fromstring(self.data)

        # Front-end expects an empty string, or a properly formatted string with YouTube IDs.
        self.youtube_streams = xmltree.get("youtube", "")

        self.sub = xmltree.get("sub")

        self.autoplay = xmltree.get("autoplay") or ""
        if self.autoplay.lower() not in ["true", "false"]:
            self.autoplay = "true"

        self.position = 0
        self.show_captions = xmltree.get("show_captions", "true")
        self.sources = {
            "main": self._get_source(xmltree),
            "mp4": self._get_source(xmltree, ["mp4"]),
            "webm": self._get_source(xmltree, ["webm"]),
            "ogv": self._get_source(xmltree, ["ogv"]),
        }
        self.track = self._get_track(xmltree)
        self.start_time, self.end_time = self.get_timeframe(xmltree)
Пример #31
0
class TestXModuleHandler(TestCase):
    """
    Tests that the xmodule_handler function correctly wraps handle_ajax
    """
    def setUp(self):
        super(TestXModuleHandler, self).setUp()
        self.module = XModule(descriptor=Mock(),
                              field_data=Mock(),
                              runtime=Mock(),
                              scope_ids=Mock())
        self.module.handle_ajax = Mock(return_value='{}')
        self.request = webob.Request({})

    def test_xmodule_handler_passed_data(self):
        self.module.xmodule_handler(self.request)
        self.module.handle_ajax.assert_called_with(
            None, MultiDict(self.request.POST))

    def test_xmodule_handler_dispatch(self):
        self.module.xmodule_handler(self.request, 'dispatch')
        self.module.handle_ajax.assert_called_with(
            'dispatch', MultiDict(self.request.POST))

    def test_xmodule_handler_return_value(self):
        response = self.module.xmodule_handler(self.request)
        self.assertIsInstance(response, webob.Response)
        self.assertEqual(response.body.decode('utf-8'), '{}')

    @ddt.data(
        u'{"test_key": "test_value"}',
        '{"test_key": "test_value"}',
    )
    def test_xmodule_handler_with_data(self, response_data):
        """
        Tests that xmodule_handler function correctly wraps handle_ajax when handle_ajax response is either
        str or unicode.
        """

        self.module.handle_ajax = Mock(return_value=response_data)
        response = self.module.xmodule_handler(self.request)
        self.assertIsInstance(response, webob.Response)
        self.assertEqual(response.body.decode('utf-8'),
                         '{"test_key": "test_value"}')
Пример #32
0
class TestXModuleHandler(TestCase):
    """
    Tests that the xmodule_handler function correctly wraps handle_ajax
    """
    shard = 1

    def setUp(self):
        super(TestXModuleHandler, self).setUp()
        self.module = XModule(descriptor=Mock(), field_data=Mock(), runtime=Mock(), scope_ids=Mock())
        self.module.handle_ajax = Mock(return_value='{}')
        self.request = webob.Request({})

    def test_xmodule_handler_passed_data(self):
        self.module.xmodule_handler(self.request)
        self.module.handle_ajax.assert_called_with(None, self.request.POST)

    def test_xmodule_handler_dispatch(self):
        self.module.xmodule_handler(self.request, 'dispatch')
        self.module.handle_ajax.assert_called_with('dispatch', self.request.POST)

    def test_xmodule_handler_return_value(self):
        response = self.module.xmodule_handler(self.request)
        self.assertIsInstance(response, webob.Response)
        self.assertEqual(response.body, '{}')

    @ddt.data(
        u'{"test_key": "test_value"}',
        '{"test_key": "test_value"}',
    )
    def test_xmodule_handler_with_data(self, response_data):
        """
        Tests that xmodule_handler function correctly wraps handle_ajax when handle_ajax response is either
        str or unicode.
        """

        self.module.handle_ajax = Mock(return_value=response_data)
        response = self.module.xmodule_handler(self.request)
        self.assertIsInstance(response, webob.Response)
        self.assertEqual(response.body, '{"test_key": "test_value"}')
 def setUp(self):
     super(TestXModuleHandler, self).setUp()
     self.module = XModule(descriptor=Mock(), field_data=Mock(), runtime=Mock(), scope_ids=Mock())
     self.module.handle_ajax = Mock(return_value='{}')
     self.request = webob.Request({})
Пример #34
0
 def __init__(self, *args, **kwargs):
     XModule.__init__(self, *args, **kwargs)
Пример #35
0
 def __init__(self, *args, **kwargs):
     XModule.__init__(self, *args, **kwargs)
     self.contents = None
Пример #36
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        self.rendered = False
Пример #37
0
 def setUp(self):
     self.module = XModule(descriptor=Mock(), field_data=Mock(), runtime=Mock(), scope_ids=Mock())
     self.module.handle_ajax = Mock(return_value='{}')
     self.request = Mock()
Пример #38
0
    def __init__(self, *args, **kwargs):
        XModule.__init__(self, *args, **kwargs)

        self.rendered = False
Пример #39
0
 def __init__(self, *args, **kwargs):
     XModule.__init__(self, *args, **kwargs)
Пример #40
0
 def __init__(self, *args, **kwargs):
     XModule.__init__(self, *args, **kwargs)
     self.contents = None