• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python tools.TestRuntime类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中xblock.test.tools.TestRuntime的典型用法代码示例。如果您正苦于以下问题:Python TestRuntime类的具体用法?Python TestRuntime怎么用?Python TestRuntime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了TestRuntime类的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_mixin_field_access

def test_mixin_field_access():
    field_data = DictFieldData({"field_a": 5, "field_x": [1, 2, 3]})
    runtime = TestRuntime(Mock(), mixins=[TestSimpleMixin], services={"field-data": field_data})

    field_tester = runtime.construct_xblock_from_class(FieldTester, Mock())

    assert_equals(5, field_tester.field_a)
    assert_equals(10, field_tester.field_b)
    assert_equals(42, field_tester.field_c)
    assert_equals([1, 2, 3], field_tester.field_x)
    assert_equals("default_value", field_tester.field_y)

    field_tester.field_x = ["a", "b"]
    field_tester.save()
    assert_equals(["a", "b"], field_tester._field_data.get(field_tester, "field_x"))

    del field_tester.field_x
    assert_equals([], field_tester.field_x)
    assert_equals([1, 2, 3], field_tester.field_x_with_default)

    with assert_raises(AttributeError):
        getattr(field_tester, "field_z")
    with assert_raises(AttributeError):
        delattr(field_tester, "field_z")

    field_tester.field_z = "foo"
    assert_equals("foo", field_tester.field_z)
    assert_false(field_tester._field_data.has(field_tester, "field_z"))
开发者ID:sudogroot,项目名称:XBlock,代码行数:28,代码来源:test_runtime.py


示例2: test_cached_parent

def test_cached_parent():
    class HasParent(XBlock):
        """
        Dummy empty class
        """
        pass

    runtime = TestRuntime(services={'field-data': DictFieldData({})})
    runtime.get_block = Mock()
    block = HasParent(runtime, scope_ids=Mock(spec=ScopeIds))

    # block has no parent yet, and we don't need to call the runtime to find
    # that out.
    assert_equals(block.get_parent(), None)
    assert not runtime.get_block.called

    # Set a parent id for the block.  Get the parent.  Now we have one, and we
    # used runtime.get_block to get it.
    block.parent = "some_parent_id"
    parent = block.get_parent()
    assert_not_equals(parent, None)
    assert runtime.get_block.called_with("some_parent_id")

    # Get the parent again.  It will be the same parent, and we didn't call the
    # runtime.
    runtime.get_block.reset_mock()
    parent2 = block.get_parent()
    assert parent2 is parent
    assert not runtime.get_block.called
开发者ID:Keeward,项目名称:XBlock,代码行数:29,代码来源:test_core.py


示例3: test_set_field_data

 def test_set_field_data(self):
     field_data = Mock(spec=FieldData)
     runtime = TestRuntime(Mock(spec=IdReader), None)
     with self.assertWarns(FieldDataDeprecationWarning):
         runtime.field_data = field_data
     with self.assertWarns(FieldDataDeprecationWarning):
         self.assertEquals(runtime.field_data, field_data)
开发者ID:Maqlan,项目名称:XBlock,代码行数:7,代码来源:test_runtime.py


示例4: test_lazy_translation

    def test_lazy_translation(self):
        with warnings.catch_warnings(record=True) as caught_warnings:
            warnings.simplefilter('always', FailingEnforceTypeWarning)

            class XBlockTest(XBlock):
                """
                Set up a class that contains a single string field with a translated default.
                """
                STR_DEFAULT_ENG = 'ENG: String to be translated'
                str_field = String(scope=Scope.settings, default=_('ENG: String to be translated'))

        # No FailingEnforceTypeWarning should have been triggered
        assert not caught_warnings

        # Construct a runtime and an XBlock using it.
        key_store = DictKeyValueStore()
        field_data = KvsFieldData(key_store)
        runtime = TestRuntime(Mock(), services={'field-data': field_data})

        # Change language to 'de'.
        user_language = 'de'
        with translation.override(user_language):
            tester = runtime.construct_xblock_from_class(XBlockTest, ScopeIds('s0', 'XBlockTest', 'd0', 'u0'))

            # Assert instantiated XBlock str_field value is not yet evaluated.
            assert 'django.utils.functional.' in str(type(tester.str_field))

            # Assert str_field *is* translated when the value is used.
            assert text_type(tester.str_field) == 'DEU: Translated string'
开发者ID:edx,项目名称:XBlock,代码行数:29,代码来源:test_field_translation.py


示例5: test_mixin_field_access

def test_mixin_field_access():
    field_data = DictFieldData({
        'field_a': 5,
        'field_x': [1, 2, 3],
    })
    runtime = TestRuntime(Mock(), mixins=[TestSimpleMixin], services={'field-data': field_data})

    field_tester = runtime.construct_xblock_from_class(FieldTester, Mock())

    assert_equals(5, field_tester.field_a)
    assert_equals(10, field_tester.field_b)
    assert_equals(42, field_tester.field_c)
    assert_equals([1, 2, 3], field_tester.field_x)
    assert_equals('default_value', field_tester.field_y)

    field_tester.field_x = ['a', 'b']
    field_tester.save()
    assert_equals(['a', 'b'], field_tester._field_data.get(field_tester, 'field_x'))

    del field_tester.field_x
    assert_equals([], field_tester.field_x)
    assert_equals([1, 2, 3], field_tester.field_x_with_default)

    with assert_raises(AttributeError):
        getattr(field_tester, 'field_z')
    with assert_raises(AttributeError):
        delattr(field_tester, 'field_z')

    field_tester.field_z = 'foo'
    assert_equals('foo', field_tester.field_z)
    assert_false(field_tester._field_data.has(field_tester, 'field_z'))
开发者ID:Maqlan,项目名称:XBlock,代码行数:31,代码来源:test_runtime.py


示例6: test_mixin_field_access

def test_mixin_field_access():
    field_data = DictFieldData({
        'field_a': 5,
        'field_x': [1, 2, 3],
    })
    runtime = TestRuntime(Mock(), mixins=[TestSimpleMixin], services={'field-data': field_data})

    field_tester = runtime.construct_xblock_from_class(FieldTester, Mock())

    assert field_tester.field_a == 5
    assert field_tester.field_b == 10
    assert field_tester.field_c == 42
    assert field_tester.field_x == [1, 2, 3]
    assert field_tester.field_y == 'default_value'

    field_tester.field_x = ['a', 'b']
    field_tester.save()
    assert ['a', 'b'] == field_tester._field_data.get(field_tester, 'field_x')

    del field_tester.field_x
    assert [] == field_tester.field_x
    assert [1, 2, 3] == field_tester.field_x_with_default

    with pytest.raises(AttributeError):
        getattr(field_tester, 'field_z')
    with pytest.raises(AttributeError):
        delattr(field_tester, 'field_z')

    field_tester.field_z = 'foo'
    assert field_tester.field_z == 'foo'
    assert not field_tester._field_data.has(field_tester, 'field_z')
开发者ID:edx,项目名称:XBlock,代码行数:31,代码来源:test_runtime.py


示例7: test_db_model_keys

def test_db_model_keys():
    # Tests that updates to fields are properly recorded in the KeyValueStore,
    # and that the keys have been constructed correctly
    key_store = DictKeyValueStore()
    field_data = KvsFieldData(key_store)
    runtime = TestRuntime(Mock(), mixins=[TestMixin], services={'field-data': field_data})
    tester = runtime.construct_xblock_from_class(TestXBlock, ScopeIds('s0', 'TestXBlock', 'd0', 'u0'))

    assert not field_data.has(tester, 'not a field')

    for field in six.itervalues(tester.fields):
        new_value = 'new ' + field.name
        assert not field_data.has(tester, field.name)
        if isinstance(field, List):
            new_value = [new_value]
        setattr(tester, field.name, new_value)

    # Write out the values
    tester.save()

    # Make sure everything saved correctly
    for field in six.itervalues(tester.fields):
        assert field_data.has(tester, field.name)

    def get_key_value(scope, user_id, block_scope_id, field_name):
        """Gets the value, from `key_store`, of a Key with the given values."""
        new_key = KeyValueStore.Key(scope, user_id, block_scope_id, field_name)
        return key_store.db_dict[new_key]

    # Examine each value in the database and ensure that keys were constructed correctly
    assert get_key_value(Scope.content, None, 'd0', 'content') == 'new content'
    assert get_key_value(Scope.settings, None, 'u0', 'settings') == 'new settings'
    assert get_key_value(Scope.user_state, 's0', 'u0', 'user_state') == 'new user_state'
    assert get_key_value(Scope.preferences, 's0', 'TestXBlock', 'preferences') == 'new preferences'
    assert get_key_value(Scope.user_info, 's0', None, 'user_info') == 'new user_info'
    assert get_key_value(Scope(UserScope.NONE, BlockScope.TYPE), None, 'TestXBlock', 'by_type') == 'new by_type'
    assert get_key_value(Scope(UserScope.NONE, BlockScope.ALL), None, None, 'for_all') == 'new for_all'
    assert get_key_value(Scope(UserScope.ONE, BlockScope.DEFINITION), 's0', 'd0', 'user_def') == 'new user_def'
    assert get_key_value(Scope(UserScope.ALL, BlockScope.ALL), None, None, 'agg_global') == 'new agg_global'
    assert get_key_value(Scope(UserScope.ALL, BlockScope.TYPE), None, 'TestXBlock', 'agg_type') == 'new agg_type'
    assert get_key_value(Scope(UserScope.ALL, BlockScope.DEFINITION), None, 'd0', 'agg_def') == 'new agg_def'
    assert get_key_value(Scope.user_state_summary, None, 'u0', 'agg_usage') == 'new agg_usage'
    assert get_key_value(Scope.content, None, 'd0', 'mixin_content') == 'new mixin_content'
    assert get_key_value(Scope.settings, None, 'u0', 'mixin_settings') == 'new mixin_settings'
    assert get_key_value(Scope.user_state, 's0', 'u0', 'mixin_user_state') == 'new mixin_user_state'
    assert get_key_value(Scope.preferences, 's0', 'TestXBlock', 'mixin_preferences') == 'new mixin_preferences'
    assert get_key_value(Scope.user_info, 's0', None, 'mixin_user_info') == 'new mixin_user_info'
    assert get_key_value(Scope(UserScope.NONE, BlockScope.TYPE), None, 'TestXBlock', 'mixin_by_type') == \
        'new mixin_by_type'
    assert get_key_value(Scope(UserScope.NONE, BlockScope.ALL), None, None, 'mixin_for_all') == \
        'new mixin_for_all'
    assert get_key_value(Scope(UserScope.ONE, BlockScope.DEFINITION), 's0', 'd0', 'mixin_user_def') == \
        'new mixin_user_def'
    assert get_key_value(Scope(UserScope.ALL, BlockScope.ALL), None, None, 'mixin_agg_global') == \
        'new mixin_agg_global'
    assert get_key_value(Scope(UserScope.ALL, BlockScope.TYPE), None, 'TestXBlock', 'mixin_agg_type') == \
        'new mixin_agg_type'
    assert get_key_value(Scope(UserScope.ALL, BlockScope.DEFINITION), None, 'd0', 'mixin_agg_def') == \
        'new mixin_agg_def'
    assert get_key_value(Scope.user_state_summary, None, 'u0', 'mixin_agg_usage') == 'new mixin_agg_usage'
开发者ID:edx,项目名称:XBlock,代码行数:60,代码来源:test_runtime.py


示例8: test_sub_service

def test_sub_service():
    runtime = TestRuntime(id_reader=Mock(), services={
        'secret_service': 17,
        'field-data': DictFieldData({}),
    })
    tester = SubXBlockWithServices(runtime, scope_ids=Mock(spec=ScopeIds))

    # Call the student_view to run its assertions.
    runtime.render(tester, 'student_view')
开发者ID:edx-solutions,项目名称:XBlock,代码行数:9,代码来源:test_runtime.py


示例9: test_service

def test_service():
    runtime = TestRuntime(services={"secret_service": 17, "field-data": DictFieldData({})})
    block_type = "test"
    def_id = runtime.id_generator.create_definition(block_type)
    usage_id = runtime.id_generator.create_usage(def_id)
    tester = XBlockWithServices(runtime, scope_ids=ScopeIds("user", block_type, def_id, usage_id))

    # Call the student_view to run its assertions.
    runtime.render(tester, "student_view")
开发者ID:sudogroot,项目名称:XBlock,代码行数:9,代码来源:test_runtime.py


示例10: test_runtime_handle

def test_runtime_handle():
    # Test a simple handler and a fallback handler

    key_store = DictKeyValueStore()
    field_data = KvsFieldData(key_store)
    runtime = TestRuntime(services={"field-data": field_data})
    tester = TestXBlock(runtime, scope_ids=Mock(spec=ScopeIds))
    runtime = MockRuntimeForQuerying()
    # string we want to update using the handler
    update_string = "user state update"
    assert_equals(runtime.handle(tester, "existing_handler", update_string), "I am the existing test handler")
    assert_equals(tester.user_state, update_string)

    # when the handler needs to use the fallback as given name can't be found
    new_update_string = "new update"
    assert_equals(runtime.handle(tester, "test_fallback_handler", new_update_string), "I have been handled")
    assert_equals(tester.user_state, new_update_string)

    # request to use a handler which doesn't have XBlock.handler decoration
    # should use the fallback
    new_update_string = "new update"
    assert_equals(runtime.handle(tester, "handler_without_correct_decoration", new_update_string), "gone to fallback")
    assert_equals(tester.user_state, new_update_string)

    # handler can't be found & no fallback handler supplied, should throw an exception
    tester = TestXBlockNoFallback(runtime, scope_ids=Mock(spec=ScopeIds))
    ultimate_string = "ultimate update"
    with assert_raises(NoSuchHandlerError):
        runtime.handle(tester, "test_nonexistant_fallback_handler", ultimate_string)

    # request to use a handler which doesn't have XBlock.handler decoration
    # and no fallback should raise NoSuchHandlerError
    with assert_raises(NoSuchHandlerError):
        runtime.handle(tester, "handler_without_correct_decoration", "handled")
开发者ID:sudogroot,项目名称:XBlock,代码行数:34,代码来源:test_runtime.py


示例11: test_service

def test_service():
    runtime = TestRuntime(services={
        'secret_service': 17,
        'field-data': DictFieldData({}),
    })
    block_type = 'test'
    def_id = runtime.id_generator.create_definition(block_type)
    usage_id = runtime.id_generator.create_usage(def_id)
    tester = XBlockWithServices(runtime, scope_ids=ScopeIds('user', block_type, def_id, usage_id))

    # Call the student_view to run its assertions.
    runtime.render(tester, 'student_view')
开发者ID:edx-solutions,项目名称:XBlock,代码行数:12,代码来源:test_runtime.py


示例12: setUp

 def setUp(self):
     key_store = DictKeyValueStore()
     field_data = KvsFieldData(key_store)
     self.runtime = TestRuntime(services={'field-data': field_data})
     block_type = 'test'
     def_id = self.runtime.id_generator.create_definition(block_type)
     usage_id = self.runtime.id_generator.create_usage(def_id)
     self.tester = TestXBlock(self.runtime, scope_ids=ScopeIds('user', block_type, def_id, usage_id))
开发者ID:Jianbinma,项目名称:XBlock,代码行数:8,代码来源:test_asides.py


示例13: TestAsides

class TestAsides(TestCase):
    """
    Tests of XBlockAsides.
    """
    def setUp(self):
        key_store = DictKeyValueStore()
        field_data = KvsFieldData(key_store)
        self.runtime = TestRuntime(services={'field-data': field_data})
        block_type = 'test'
        def_id = self.runtime.id_generator.create_definition(block_type)
        usage_id = self.runtime.id_generator.create_usage(def_id)
        self.tester = TestXBlock(self.runtime, scope_ids=ScopeIds('user', block_type, def_id, usage_id))

    @XBlockAside.register_temp_plugin(TestAside)
    def test_render_aside(self):
        """
        Test that rendering the xblock renders its aside
        """

        frag = self.runtime.render(self.tester, 'student_view', [u"ignore"])
        self.assertIn(TestAside.FRAG_CONTENT, frag.body_html())

        frag = self.runtime.render(self.tester, 'author_view', [u"ignore"])
        self.assertNotIn(TestAside.FRAG_CONTENT, frag.body_html())

    @XBlockAside.register_temp_plugin(TestAside)
    @XBlockAside.register_temp_plugin(TestInheritedAside)
    def test_inherited_aside_view(self):
        """
        Test that rendering the xblock renders its aside (when the aside view is
        inherited).
        """
        frag = self.runtime.render(self.tester, 'student_view', [u"ignore"])
        self.assertIn(TestAside.FRAG_CONTENT, frag.body_html())
        self.assertIn(TestInheritedAside.FRAG_CONTENT, frag.body_html())

        frag = self.runtime.render(self.tester, 'author_view', [u"ignore"])
        self.assertNotIn(TestAside.FRAG_CONTENT, frag.body_html())
        self.assertNotIn(TestInheritedAside.FRAG_CONTENT, frag.body_html())
开发者ID:Jianbinma,项目名称:XBlock,代码行数:39,代码来源:test_asides.py


示例14: setUp

    def setUp(self):
        patcher = patch.object(TestRuntime, 'construct_xblock')
        self.construct_block = patcher.start()
        self.addCleanup(patcher.stop)

        self.id_reader = Mock(IdReader)
        self.user_id = Mock()
        self.field_data = Mock(FieldData)
        self.runtime = TestRuntime(self.id_reader, services={'field-data': self.field_data})
        self.runtime.user_id = self.user_id

        self.usage_id = 'usage_id'

        # Can only get a definition id from the id_reader
        self.def_id = self.id_reader.get_definition_id.return_value

        # Can only get a block type from the id_reader
        self.block_type = self.id_reader.get_block_type.return_value
开发者ID:Maqlan,项目名称:XBlock,代码行数:18,代码来源:test_runtime.py


示例15: TestRuntimeGetBlock

class TestRuntimeGetBlock(TestCase):
    """
    Test the get_block default method on Runtime.
    """
    def setUp(self):
        patcher = patch.object(TestRuntime, 'construct_xblock')
        self.construct_block = patcher.start()
        self.addCleanup(patcher.stop)

        self.id_reader = Mock(IdReader)
        self.user_id = Mock()
        self.field_data = Mock(FieldData)
        self.runtime = TestRuntime(self.id_reader, services={'field-data': self.field_data})
        self.runtime.user_id = self.user_id

        self.usage_id = 'usage_id'

        # Can only get a definition id from the id_reader
        self.def_id = self.id_reader.get_definition_id.return_value

        # Can only get a block type from the id_reader
        self.block_type = self.id_reader.get_block_type.return_value

    def test_basic(self):
        self.runtime.get_block(self.usage_id)

        self.id_reader.get_definition_id.assert_called_with(self.usage_id)
        self.id_reader.get_block_type.assert_called_with(self.def_id)
        self.construct_block.assert_called_with(
            self.block_type,
            ScopeIds(self.user_id, self.block_type, self.def_id, self.usage_id),
            for_parent=None,
        )

    def test_missing_usage(self):
        self.id_reader.get_definition_id.side_effect = NoSuchUsage
        with self.assertRaises(NoSuchUsage):
            self.runtime.get_block(self.usage_id)

    def test_missing_definition(self):
        self.id_reader.get_block_type.side_effect = NoSuchDefinition

        # If we don't have a definition, then the usage doesn't exist
        with self.assertRaises(NoSuchUsage):
            self.runtime.get_block(self.usage_id)
开发者ID:edx-solutions,项目名称:XBlock,代码行数:45,代码来源:test_runtime.py


示例16: test_db_model_keys

def test_db_model_keys():
    # Tests that updates to fields are properly recorded in the KeyValueStore,
    # and that the keys have been constructed correctly
    key_store = DictKeyValueStore()
    field_data = KvsFieldData(key_store)
    runtime = TestRuntime(Mock(), mixins=[TestMixin], services={"field-data": field_data})
    tester = runtime.construct_xblock_from_class(TestXBlock, ScopeIds("s0", "TestXBlock", "d0", "u0"))

    assert_false(field_data.has(tester, "not a field"))

    for field in tester.fields.values():
        new_value = "new " + field.name
        assert_false(field_data.has(tester, field.name))
        if isinstance(field, List):
            new_value = [new_value]
        setattr(tester, field.name, new_value)

    # Write out the values
    tester.save()

    # Make sure everything saved correctly
    for field in tester.fields.values():
        assert_true(field_data.has(tester, field.name))

    def get_key_value(scope, user_id, block_scope_id, field_name):
        """Gets the value, from `key_store`, of a Key with the given values."""
        new_key = KeyValueStore.Key(scope, user_id, block_scope_id, field_name)
        return key_store.db_dict[new_key]

    # Examine each value in the database and ensure that keys were constructed correctly
    assert_equals("new content", get_key_value(Scope.content, None, "d0", "content"))
    assert_equals("new settings", get_key_value(Scope.settings, None, "u0", "settings"))
    assert_equals("new user_state", get_key_value(Scope.user_state, "s0", "u0", "user_state"))
    assert_equals("new preferences", get_key_value(Scope.preferences, "s0", "TestXBlock", "preferences"))
    assert_equals("new user_info", get_key_value(Scope.user_info, "s0", None, "user_info"))
    assert_equals("new by_type", get_key_value(Scope(UserScope.NONE, BlockScope.TYPE), None, "TestXBlock", "by_type"))
    assert_equals("new for_all", get_key_value(Scope(UserScope.NONE, BlockScope.ALL), None, None, "for_all"))
    assert_equals("new user_def", get_key_value(Scope(UserScope.ONE, BlockScope.DEFINITION), "s0", "d0", "user_def"))
    assert_equals("new agg_global", get_key_value(Scope(UserScope.ALL, BlockScope.ALL), None, None, "agg_global"))
    assert_equals("new agg_type", get_key_value(Scope(UserScope.ALL, BlockScope.TYPE), None, "TestXBlock", "agg_type"))
    assert_equals("new agg_def", get_key_value(Scope(UserScope.ALL, BlockScope.DEFINITION), None, "d0", "agg_def"))
    assert_equals("new agg_usage", get_key_value(Scope.user_state_summary, None, "u0", "agg_usage"))
    assert_equals("new mixin_content", get_key_value(Scope.content, None, "d0", "mixin_content"))
    assert_equals("new mixin_settings", get_key_value(Scope.settings, None, "u0", "mixin_settings"))
    assert_equals("new mixin_user_state", get_key_value(Scope.user_state, "s0", "u0", "mixin_user_state"))
    assert_equals("new mixin_preferences", get_key_value(Scope.preferences, "s0", "TestXBlock", "mixin_preferences"))
    assert_equals("new mixin_user_info", get_key_value(Scope.user_info, "s0", None, "mixin_user_info"))
    assert_equals(
        "new mixin_by_type", get_key_value(Scope(UserScope.NONE, BlockScope.TYPE), None, "TestXBlock", "mixin_by_type")
    )
    assert_equals(
        "new mixin_for_all", get_key_value(Scope(UserScope.NONE, BlockScope.ALL), None, None, "mixin_for_all")
    )
    assert_equals(
        "new mixin_user_def", get_key_value(Scope(UserScope.ONE, BlockScope.DEFINITION), "s0", "d0", "mixin_user_def")
    )
    assert_equals(
        "new mixin_agg_global", get_key_value(Scope(UserScope.ALL, BlockScope.ALL), None, None, "mixin_agg_global")
    )
    assert_equals(
        "new mixin_agg_type", get_key_value(Scope(UserScope.ALL, BlockScope.TYPE), None, "TestXBlock", "mixin_agg_type")
    )
    assert_equals(
        "new mixin_agg_def", get_key_value(Scope(UserScope.ALL, BlockScope.DEFINITION), None, "d0", "mixin_agg_def")
    )
    assert_equals("new mixin_agg_usage", get_key_value(Scope.user_state_summary, None, "u0", "mixin_agg_usage"))
开发者ID:sudogroot,项目名称:XBlock,代码行数:66,代码来源:test_runtime.py


示例17: test_service

def test_service():
    runtime = TestRuntime(services={'secret_service': 17})
    tester = XBlockWithServices(runtime, scope_ids=Mock(spec=ScopeIds))

    # Call the student_view to run its assertions.
    runtime.render(tester, 'student_view')
开发者ID:Maqlan,项目名称:XBlock,代码行数:6,代码来源:test_runtime.py


示例18: setUp

 def setUp(self):
     self.runtime = TestRuntime(field_data=KvsFieldData(DictKeyValueStore()))
开发者ID:Semi-global,项目名称:problem-builder,代码行数:2,代码来源:test_upgrade.py


示例19: TestUpgrade

class TestUpgrade(unittest.TestCase):
    """
    Test upgrade from mentoring v1 (which uses xml_content even in Studio) to v2.

    We can't test the steps that depend on Studio, so we just test the XML conversion.
    """

    def setUp(self):
        self.runtime = TestRuntime(field_data=KvsFieldData(DictKeyValueStore()))

    @ddt.data(
        "v1_upgrade_a",
        "v1_upgrade_b",
        "v1_upgrade_c",
        "v1_upgrade_d",
    )
    @XBlock.register_temp_plugin(HtmlBlock, "html")
    @XBlock.register_temp_plugin(MentoringBlock, "mentoring")
    def test_xml_upgrade(self, file_name):
        """
        Convert a v1 mentoring block to v2 and then compare the resulting block to a pre-converted one.
        """
        with open("{}/{}_old.xml".format(xml_path, file_name)) as xmlfile:
            temp_node = etree.parse(xmlfile).getroot()
            old_block = self.create_block_from_node(temp_node)

        parser = etree.XMLParser(remove_blank_text=True)
        xml_root = etree.parse(StringIO(old_block.xml_content), parser=parser).getroot()
        convert_xml_to_v2(xml_root)
        converted_block = self.create_block_from_node(xml_root)

        with open("{}/{}_new.xml".format(xml_path, file_name)) as xmlfile:
            temp_node = etree.parse(xmlfile).getroot()
            new_block = self.create_block_from_node(temp_node)

        try:
            self.assertBlocksAreEquivalent(converted_block, new_block)
        except AssertionError:
            xml_result = etree.tostring(xml_root, pretty_print=True, encoding="UTF-8")
            print("Converted XML:\n{}".format(xml_result))
            raise

    def create_block_from_node(self, node):
        """
        Parse an XML node representing an XBlock (and children), and return the XBlock.
        """
        block_type = node.tag
        def_id = self.runtime.id_generator.create_definition(block_type)
        usage_id = self.runtime.id_generator.create_usage(def_id)
        keys = ScopeIds(None, block_type, def_id, usage_id)
        block_class = self.runtime.mixologist.mix(self.runtime.load_block_type(block_type))
        block = block_class.parse_xml(node, self.runtime, keys, self.runtime.id_generator)
        block.save()
        return block

    def assertBlocksAreEquivalent(self, block1, block2):
        """
        Compare two blocks for equivalence.
        Borrowed from xblock.test.tools.blocks_are_equivalent but modified to use assertions.
        """
        # The two blocks have to be the same class.
        self.assertEqual(block1.__class__, block2.__class__)
        # They have to have the same fields.
        self.assertEqual(set(block1.fields), set(block2.fields))
        # The data fields have to have the same values.
        for field_name in block1.fields:
            if field_name in ('parent', 'children'):
                continue
            if field_name == "content":
                # Inner HTML/XML content may have varying whitespace which we don't care about:
                self.assertEqual(
                    self.clean_html(getattr(block1, field_name)),
                    self.clean_html(getattr(block2, field_name))
                )
            else:
                self.assertEqual(getattr(block1, field_name), getattr(block2, field_name))
        # The children need to be equal.
        self.assertEqual(block1.has_children, block2.has_children)

        if block1.has_children:
            self.assertEqual(len(block1.children), len(block2.children))
            for child_id1, child_id2 in zip(block1.children, block2.children):
                # Load up the actual children to see if they are equal.
                child1 = block1.runtime.get_block(child_id1)
                child2 = block2.runtime.get_block(child_id2)
                self.assertBlocksAreEquivalent(child1, child2)

    def clean_html(self, html_str):
        """
        Standardize the given HTML string for a consistent comparison.
        Assumes the HTML is valid XML.
        """
        # We wrap it in <x></x> so that the given HTML string doesn't need a single root element.
        parser = etree.XMLParser(remove_blank_text=True)
        parsed = etree.parse(StringIO(u"<x>{}</x>".format(html_str)), parser=parser).getroot()
        return etree.tostring(parsed, pretty_print=False, encoding="UTF-8")[3:-3]
开发者ID:Semi-global,项目名称:problem-builder,代码行数:96,代码来源:test_upgrade.py



注:本文中的xblock.test.tools.TestRuntime类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python xbmc.convertLanguage函数代码示例发布时间:2022-05-26
下一篇:
Python tools.assert_raises函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap