Commit 4446ddb2 by ichuang

cleaned up conditional module a bit; add test for conditional module

parent 95ef1216
...@@ -49,8 +49,8 @@ class ConditionalModule(XModule): ...@@ -49,8 +49,8 @@ class ConditionalModule(XModule):
def _get_required_modules(self): def _get_required_modules(self):
self.required_modules = [] self.required_modules = []
for loc in self.descriptor.required_module_locations: for descriptor in self.descriptor.get_required_module_descriptors():
module = self.system.get_module(loc) module = self.system.get_module(descriptor)
self.required_modules.append(module) self.required_modules.append(module)
#log.debug('required_modules=%s' % (self.required_modules)) #log.debug('required_modules=%s' % (self.required_modules))
...@@ -78,10 +78,10 @@ class ConditionalModule(XModule): ...@@ -78,10 +78,10 @@ class ConditionalModule(XModule):
if not hasattr(module, 'is_attempted'): if not hasattr(module, 'is_attempted'):
raise Exception('Error in conditional module: required module %s has no .is_attempted() method' % module) raise Exception('Error in conditional module: required module %s has no .is_attempted() method' % module)
if not module.is_attempted(): if not module.is_attempted():
log.debug('conditional module: %s not completed' % module) log.debug('conditional module: %s not attempted' % module)
return False return False
else: else:
log.debug('conditional module: %s IS completed' % module) log.debug('conditional module: %s IS attempted' % module)
return True return True
else: else:
raise Exception('Error in conditional module: unknown condition "%s"' % self.condition) raise Exception('Error in conditional module: unknown condition "%s"' % self.condition)
......
import json
from path import path
import unittest
from fs.memoryfs import MemoryFS
from lxml import etree
from mock import Mock, patch
from collections import defaultdict
from xmodule.x_module import XMLParsingSystem, XModuleDescriptor
from xmodule.xml_module import is_pointer_tag
from xmodule.errortracker import make_error_tracker
from xmodule.modulestore import Location
from xmodule.modulestore.xml import ImportSystem, XMLModuleStore
from xmodule.modulestore.exceptions import ItemNotFoundError
from .test_export import DATA_DIR
ORG = 'test_org'
COURSE = 'conditional' # name of directory with course data
from . import test_system
class DummySystem(ImportSystem):
@patch('xmodule.modulestore.xml.OSFS', lambda dir: MemoryFS())
def __init__(self, load_error_modules):
xmlstore = XMLModuleStore("data_dir", course_dirs=[], load_error_modules=load_error_modules)
course_id = "/".join([ORG, COURSE, 'test_run'])
course_dir = "test_dir"
policy = {}
error_tracker = Mock()
parent_tracker = Mock()
super(DummySystem, self).__init__(
xmlstore,
course_id,
course_dir,
policy,
error_tracker,
parent_tracker,
load_error_modules=load_error_modules,
)
def render_template(self, template, context):
raise Exception("Shouldn't be called")
class ConditionalModuleTest(unittest.TestCase):
@staticmethod
def get_system(load_error_modules=True):
'''Get a dummy system'''
return DummySystem(load_error_modules)
def get_course(self, name):
"""Get a test course by directory name. If there's more than one, error."""
print "Importing {0}".format(name)
modulestore = XMLModuleStore(DATA_DIR, course_dirs=[name])
courses = modulestore.get_courses()
self.modulestore = modulestore
self.assertEquals(len(courses), 1)
return courses[0]
def test_conditional_module(self):
"""Make sure that conditional module works"""
print "Starting import"
course = self.get_course('conditional')
print "Course: ", course
print "id: ", course.id
instance_states = dict(problem=None)
shared_state = None
def inner_get_module(descriptor):
if isinstance(descriptor, Location):
location = descriptor
descriptor = self.modulestore.get_instance(course.id, location, depth=None)
location = descriptor.location
instance_state = instance_states.get(location.category,None)
print "inner_get_module, location.category=%s, inst_state=%s" % (location.category, instance_state)
return descriptor.xmodule_constructor(test_system)(instance_state, shared_state)
location = Location(["i4x", "edX", "cond_test", "conditional","condone"])
module = inner_get_module(location)
def replace_urls(text, staticfiles_prefix=None, replace_prefix='/static/', course_namespace=None):
return text
test_system.replace_urls = replace_urls
test_system.get_module = inner_get_module
print "module: ", module
html = module.get_html()
print "html type: ", type(html)
print "html: ", html
html_expect = "{'ajax_url': 'courses/course_id/modx/a_location', 'element_id': 'i4x-edX-cond_test-conditional-condone', 'id': 'i4x://edX/cond_test/conditional/condone'}"
self.assertEqual(html, html_expect)
gdi = module.get_display_items()
print "gdi=", gdi
ajax = json.loads(module.handle_ajax('',''))
self.assertTrue('xmodule.conditional_module' in ajax['html'])
print "ajax: ", ajax
# now change state of the capa problem to make it completed
instance_states['problem'] = json.dumps({'attempts':1})
ajax = json.loads(module.handle_ajax('',''))
self.assertTrue('This is a secret' in ajax['html'])
print "post-attempt ajax: ", ajax
course for testing conditional module
<conditional condition="require_attempted" required="problem/choiceprob">
<html url_name="secret_page" />
</conditional>
<course name="Conditional Course" org="edX" course="cond_test" graceperiod="1 day 5 hours 59 minutes 59 seconds" slug="2012_Fall" start="2015-07-17T12:00">
<chapter name="Problems with Condition">
<sequential>
<problem url_name="choiceprob" />
<conditional url_name="condone"/>
</sequential>
</chapter>
</course>
<html display_name="Secret Page">
<p>This is a secret!</p>
</html>
<problem display_name="S3E2: Lorentz Force">
<startouttext/>
<p>Consider a hypothetical magnetic field pointing out of your computer screen. Now imagine an electron traveling from right to left in the plane of your screen. A diagram of this situation is show below…</p>
<center><img width="400" src="/static/images/LSQimages/LSQ_W01_8.png"/></center>
<p>a. The magnitude of the force experienced by the electron is proportional the product of which of the following? (Select all that apply.)</p>
<endouttext/>
<choiceresponse>
<checkboxgroup>
<!-- include ellipses to test non-ascii characters -->
<choice correct="true"><text>Magnetic field strength…</text></choice>
<choice correct="false"><text>Electric field strength…</text></choice>
<choice correct="true"><text>Electric charge of the electron…</text></choice>
<choice correct="false"><text>Radius of the electron…</text></choice>
<choice correct="false"><text>Mass of the electron…</text></choice>
<choice correct="true"><text>Velocity of the electron…</text></choice>
</checkboxgroup>
</choiceresponse>
</problem>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment