本文整理汇总了Python中xblock.core.XBlock类的典型用法代码示例。如果您正苦于以下问题:Python XBlock类的具体用法?Python XBlock怎么用?Python XBlock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了XBlock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_ambiguous_plugins
def test_ambiguous_plugins():
# We can load ok blocks even if there are bad blocks.
cls = XBlock.load_class("good_block")
assert_is(cls, UnambiguousBlock)
# Trying to load bad blocks raises an exception.
expected_msg = (
"Ambiguous entry points for bad_block: "
"xblock.test.test_plugin.AmbiguousBlock1, "
"xblock.test.test_plugin.AmbiguousBlock2"
)
with assert_raises_regexp(AmbiguousPluginError, expected_msg):
XBlock.load_class("bad_block")
# We can use our own function as the select function.
class MyOwnException(Exception):
"""We'll raise this from `boom`."""
pass
def boom(identifier, entry_points):
"""A select function to prove user-defined functions are called."""
assert len(entry_points) == 2
assert identifier == "bad_block"
raise MyOwnException("This is boom")
with assert_raises_regexp(MyOwnException, "This is boom"):
XBlock.load_class("bad_block", select=boom)
示例2: test_nosuch_plugin
def test_nosuch_plugin():
# We can provide a default class to return for missing plugins.
cls = XBlock.load_class("nosuch_block", default=UnambiguousBlock)
assert_is(cls, UnambiguousBlock)
# If we don't provide a default class, an exception is raised.
with assert_raises_regexp(PluginMissingError, "nosuch_block"):
XBlock.load_class("nosuch_block")
示例3: test_nosuch_plugin
def test_nosuch_plugin():
# We can provide a default class to return for missing plugins.
cls = XBlock.load_class("nosuch_block", default=UnambiguousBlock)
assert cls is UnambiguousBlock
# If we don't provide a default class, an exception is raised.
with pytest.raises(PluginMissingError, match="nosuch_block"):
XBlock.load_class("nosuch_block")
示例4: test_plugin_caching
def test_plugin_caching():
plugin.PLUGIN_CACHE = {}
assert _num_plugins_cached() == 0
XBlock.load_class("thumbs")
assert _num_plugins_cached() == 1
XBlock.load_class("thumbs")
assert _num_plugins_cached() == 1
示例5: test_plugin_caching
def test_plugin_caching():
plugin.PLUGIN_CACHE = {}
assert_equals(_num_plugins_cached(), 0)
XBlock.load_class("thumbs")
assert_equals(_num_plugins_cached(), 1)
XBlock.load_class("thumbs")
assert_equals(_num_plugins_cached(), 1)
示例6: test_handle_shortcut
def test_handle_shortcut():
runtime = Mock(spec=["handle"])
scope_ids = Mock(spec=[])
request = Mock(spec=[])
block = XBlock(runtime, None, scope_ids)
block.handle("handler_name", request)
runtime.handle.assert_called_with(block, "handler_name", request, "")
runtime.handle.reset_mock()
block.handle("handler_name", request, "suffix")
runtime.handle.assert_called_with(block, "handler_name", request, "suffix")
示例7: test_handle_shortcut
def test_handle_shortcut():
runtime = Mock(spec=['handle'])
scope_ids = Mock(spec=[])
request = Mock(spec=[])
block = XBlock(runtime, None, scope_ids)
block.handle('handler_name', request)
runtime.handle.assert_called_with(block, 'handler_name', request, '')
runtime.handle.reset_mock()
block.handle('handler_name', request, 'suffix')
runtime.handle.assert_called_with(block, 'handler_name', request, 'suffix')
示例8: __init__
def __init__(self, *args, **kwargs):
try:
XBlock.__init__(self, *args, **kwargs)
# FIXME: technically, we're not supposed to provide __init__. This
# works for now, though...
self.scorm_path = DEFAULT_SCORM_PATH
if self.override_scorm_path:
self.scorm_path = self.override_scorm_path
except:
pass
示例9: construct_xblock
def construct_xblock(self, plugin_name, field_data, scope_ids, default_class=None, *args, **kwargs):
"""
Construct a new xblock of the type identified by plugin_name,
passing *args and **kwargs into __init__
"""
block_class = XBlock.load_class(plugin_name, default_class)
return self.construct_xblock_from_class(cls=block_class, field_data=field_data, scope_ids=scope_ids, *args, **kwargs)
示例10: create_block_from_xml
def create_block_from_xml(xml_data, system, org=None, course=None, default_class=None):
"""
Create an XBlock instance from XML data.
`xml_data' is a string containing valid xml.
`system` is an XMLParsingSystem.
`org` and `course` are optional strings that will be used in the generated
block's url identifiers.
`default_class` is the class to instantiate of the XML indicates a class
that can't be loaded.
Returns the fully instantiated XBlock.
"""
node = etree.fromstring(xml_data)
raw_class = XBlock.load_class(node.tag, default_class, select=prefer_xmodules)
xblock_class = system.mixologist.mix(raw_class)
# leave next line commented out - useful for low-level debugging
# log.debug('[create_block_from_xml] tag=%s, class=%s' % (node.tag, xblock_class))
url_name = node.get('url_name', node.get('slug'))
location = Location('i4x', org, course, node.tag, url_name)
scope_ids = ScopeIds(None, location.category, location, location)
xblock = xblock_class.parse_xml(node, system, scope_ids)
return xblock
示例11: _do_once
def _do_once():
"""
Called once when the module is imported to create the global scenarios.
"""
# Get all the XBlock classes, and add their scenarios.
for class_name, cls in XBlock.load_classes():
add_class_scenarios(class_name, cls)
示例12: test_all_scenarios
def test_all_scenarios():
"""Load the home page, get every URL, make a test from it."""
client = Client()
response = client.get("/")
assert response.status_code == 200
html = lxml.html.fromstring(response.content)
a_tags = list(html.xpath('//a'))
for a_tag in a_tags:
yield try_scenario, a_tag.get('href'), a_tag.text
# Load the scenarios from the classes.
scenarios = []
for _, cls in XBlock.load_classes():
if hasattr(cls, "workbench_scenarios"):
for _, xml in cls.workbench_scenarios():
scenarios.append(xml)
# We should have an <a> tag for each scenario.
assert_equals(len(a_tags), len(scenarios))
# We should have at least one scenario with a vertical tag, since we use
# empty verticals as our canary in the coal mine that something has gone
# horribly wrong with loading the scenarios.
assert any("<vertical>" in xml for xml in scenarios)
# Since we are claiming in try_scenario that no vertical is empty, let's
# eliminate the possibility that a scenario has an actual empty vertical.
assert all("<vertical></vertical>" not in xml for xml in scenarios)
assert all("<vertical/>" not in xml for xml in scenarios)
示例13: load_from_json
def load_from_json(json_data, system, default_class=None, parent_xblock=None):
"""
This method instantiates the correct subclass of XModuleDescriptor based
on the contents of json_data. It does not persist it and can create one which
has no usage id.
parent_xblock is used to compute inherited metadata as well as to append the new xblock.
json_data:
- 'location' : must have this field
- 'category': the xmodule category (required or location must be a Location)
- 'metadata': a dict of locally set metadata (not inherited)
- 'children': a list of children's usage_ids w/in this course
- 'definition':
- '_id' (optional): the usage_id of this. Will generate one if not given one.
"""
class_ = XBlock.load_class(
json_data.get("category", json_data.get("location", {}).get("category")),
default_class,
select=settings.XBLOCK_SELECT_FUNCTION,
)
usage_id = json_data.get("_id", None)
if not "_inherited_settings" in json_data and parent_xblock is not None:
json_data["_inherited_settings"] = parent_xblock.xblock_kvs.inherited_settings.copy()
json_fields = json_data.get("fields", {})
for field_name in inheritance.InheritanceMixin.fields:
if field_name in json_fields:
json_data["_inherited_settings"][field_name] = json_fields[field_name]
new_block = system.xblock_from_json(class_, usage_id, json_data)
if parent_xblock is not None:
parent_xblock.children.append(new_block.scope_ids.usage_id)
# decache pending children field settings
parent_xblock.save()
return new_block
示例14: xblock_type_display_name
def xblock_type_display_name(xblock, default_display_name=None):
"""
Returns the display name for the specified type of xblock. Note that an instance can be passed in
for context dependent names, e.g. a vertical beneath a sequential is a Unit.
:param xblock: An xblock instance or the type of xblock.
:param default_display_name: The default value to return if no display name can be found.
:return:
"""
if hasattr(xblock, "category"):
category = xblock.category
if category == "vertical" and not is_unit(xblock):
return _("Vertical")
else:
category = xblock
if category == "chapter":
return _("Section")
elif category == "sequential":
return _("Subsection")
elif category == "vertical":
return _("Unit")
component_class = XBlock.load_class(category, select=settings.XBLOCK_SELECT_FUNCTION)
if hasattr(component_class, "display_name") and component_class.display_name.default:
return _(component_class.display_name.default)
else:
return default_display_name
示例15: setUp
def setUp(self):
super(TestCourseDetailSerializer, self).setUp()
# update the expected_data to include the 'overview' data.
about_descriptor = XBlock.load_class('about')
overview_template = about_descriptor.get_template('overview.yaml')
self.expected_data['overview'] = overview_template.get('data')