Exemplo n.º 1
0
def test_change_mutable_default():
    """
    Ensure that mutating the default value for a field causes
    the changes to be saved, and doesn't corrupt other instances
    """
    class MutableTester(XBlock):
        """Test class with mutable fields."""
        list_field = List()

    mutable_test_a = MutableTester(MagicMock(), DictFieldData({}), Mock())
    mutable_test_b = MutableTester(MagicMock(), DictFieldData({}), Mock())

    # Saving without changing the default value shouldn't write to _field_data
    mutable_test_a.list_field  # pylint: disable=W0104
    mutable_test_a.save()
    with assert_raises(KeyError):
        mutable_test_a._field_data.get(mutable_test_a, 'list_field')

    mutable_test_a.list_field.append(1)
    mutable_test_a.save()

    assert_equals([1],
                  mutable_test_a._field_data.get(mutable_test_a, 'list_field'))
    with assert_raises(KeyError):
        mutable_test_b._field_data.get(mutable_test_b, 'list_field')
Exemplo n.º 2
0
def test_change_mutable_default():
    """
    Ensure that mutating the default value for a field causes
    the changes to be saved, and doesn't corrupt other instances
    """

    class MutableTester(XBlock):
        """Test class with mutable fields."""
        list_field = List()

    field_data_a = DictFieldData({})
    mutable_test_a = MutableTester(TestRuntime(services={'field-data': field_data_a}), scope_ids=Mock(spec=ScopeIds))
    field_data_b = DictFieldData({})
    mutable_test_b = MutableTester(TestRuntime(services={'field-data': field_data_b}), scope_ids=Mock(spec=ScopeIds))

    # Saving without changing the default value shouldn't write to field_data
    mutable_test_a.list_field  # pylint: disable=W0104
    mutable_test_a.save()
    with assert_raises(KeyError):
        field_data_a.get(mutable_test_a, 'list_field')

    mutable_test_a.list_field.append(1)
    mutable_test_a.save()

    assert_equals([1], field_data_a.get(mutable_test_a, 'list_field'))
    with assert_raises(KeyError):
        field_data_b.get(mutable_test_b, 'list_field')
Exemplo n.º 3
0
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")
Exemplo n.º 4
0
def test_change_mutable_default():
    """
    Ensure that mutating the default value for a field causes
    the changes to be saved, and doesn't corrupt other instances
    """

    class MutableTester(XBlock):
        """Test class with mutable fields."""
        list_field = List()

    mutable_test_a = MutableTester(MagicMock(), DictFieldData({}), Mock())
    mutable_test_b = MutableTester(MagicMock(), DictFieldData({}), Mock())

    # Saving without changing the default value shouldn't write to _field_data
    mutable_test_a.list_field  # pylint: disable=W0104
    mutable_test_a.save()
    with assert_raises(KeyError):
        mutable_test_a._field_data.get(mutable_test_a, 'list_field')

    mutable_test_a.list_field.append(1)
    mutable_test_a.save()

    assert_equals([1], mutable_test_a._field_data.get(mutable_test_a, 'list_field'))
    with assert_raises(KeyError):
        mutable_test_b._field_data.get(mutable_test_b, 'list_field')
Exemplo n.º 5
0
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'))
Exemplo n.º 6
0
def test_mixin_field_access():
    field_data = DictFieldData({
        'field_a': 5,
        'field_x': [1, 2, 3],
    })
    runtime = TestRuntime(Mock(), field_data, [TestSimpleMixin])

    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('field c', 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'))
Exemplo n.º 7
0
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"))
Exemplo n.º 8
0
def test_field_access():
    class FieldTester(XBlock):
        """Test XBlock for field access testing"""
        field_a = Integer(scope=Scope.settings)
        field_b = Integer(scope=Scope.content, default=10)
        field_c = Integer(scope=Scope.user_state, default=42)
        float_a = Float(scope=Scope.settings, default=5.8)
        float_b = Float(scope=Scope.settings)

    field_tester = FieldTester(
        MagicMock(),
        DictFieldData({
            'field_a': 5,
            'float_a': 6.1,
            'field_x': 15
        }), Mock())
    # Verify that the fields have been set
    assert_equals(5, field_tester.field_a)
    assert_equals(10, field_tester.field_b)
    assert_equals(42, field_tester.field_c)
    assert_equals(6.1, field_tester.float_a)
    assert_equals(None, field_tester.float_b)
    assert not hasattr(field_tester, 'field_x')

    # Set two of the fields.
    field_tester.field_a = 20
    field_tester.float_a = 20.5
    # field_a should be updated in the cache, but /not/ in the underlying db.
    assert_equals(20, field_tester.field_a)
    assert_equals(20.5, field_tester.float_a)
    assert_equals(5, field_tester._field_data.get(field_tester, 'field_a'))
    assert_equals(6.1, field_tester._field_data.get(field_tester, 'float_a'))
    # save the XBlock
    field_tester.save()
    # verify that the fields have been updated correctly
    assert_equals(20, field_tester.field_a)
    assert_equals(20.5, field_tester.float_a)
    # Now, field_a should be updated in the underlying db
    assert_equals(20, field_tester._field_data.get(field_tester, 'field_a'))
    assert_equals(20.5, field_tester._field_data.get(field_tester, 'float_a'))
    assert_equals(10, field_tester.field_b)
    assert_equals(42, field_tester.field_c)
    assert_equals(None, field_tester.float_b)

    # Deletes happen immediately (do not require a save)
    del field_tester.field_a
    del field_tester.float_a

    # After delete, we should find default values in the cache
    assert_equals(None, field_tester.field_a)
    assert_equals(5.8, field_tester.float_a)
    # But the fields should not actually be present in the underlying kvstore
    with assert_raises(KeyError):
        field_tester._field_data.get(field_tester, 'field_a')
    assert_false(field_tester._field_data.has(field_tester, 'field_a'))
    with assert_raises(KeyError):
        field_tester._field_data.get(field_tester, 'float_a')
    assert_false(field_tester._field_data.has(field_tester, 'float_a'))
Exemplo n.º 9
0
    def test_bad_parameters(self):
        """
        Test that `TypeError`s are thrown for bad input parameters.
        """
        with assert_raises(TypeError):
            ValidationMessage("unknown type", "Unknown type info")

        with assert_raises(TypeError):
            ValidationMessage(ValidationMessage.WARNING, b"Non-unicode message")
Exemplo n.º 10
0
    def test_delete(self):
        assert_equals(1, self.agg.first)
        del self.agg.first
        assert_false(hasattr(self.first, 'first'))
        with assert_raises(AttributeError):
            self.agg.first  # pylint: disable=W0104

        with assert_raises(AttributeError):
            del self.agg.other
Exemplo n.º 11
0
    def test_bad_parameters(self):
        """
        Test that `TypeError`s are thrown for bad input parameters.
        """
        with assert_raises(TypeError):
            ValidationMessage("unknown type", u"Unknown type info")

        with assert_raises(TypeError):
            ValidationMessage(ValidationMessage.WARNING, "Non-unicode message")
Exemplo n.º 12
0
    def test_delete(self):
        assert_equals(1, self.agg.first)
        del self.agg.first
        assert_false(hasattr(self.first, 'first'))
        with assert_raises(AttributeError):
            self.agg.first  # pylint: disable=W0104

        with assert_raises(AttributeError):
            del self.agg.other
Exemplo n.º 13
0
def test_field_access():
    class FieldTester(XBlock):
        """Test XBlock for field access testing"""

        field_a = Integer(scope=Scope.settings)
        field_b = Integer(scope=Scope.content, default=10)
        field_c = Integer(scope=Scope.user_state, default=42)
        float_a = Float(scope=Scope.settings, default=5.8)
        float_b = Float(scope=Scope.settings)

    field_data = DictFieldData({"field_a": 5, "float_a": 6.1, "field_x": 15})

    field_tester = FieldTester(TestRuntime(services={"field-data": field_data}), scope_ids=Mock())
    # Verify that the fields have been set
    assert_equals(5, field_tester.field_a)
    assert_equals(10, field_tester.field_b)
    assert_equals(42, field_tester.field_c)
    assert_equals(6.1, field_tester.float_a)
    assert_equals(None, field_tester.float_b)
    assert not hasattr(field_tester, "field_x")

    # Set two of the fields.
    field_tester.field_a = 20
    field_tester.float_a = 20.5
    # field_a should be updated in the cache, but /not/ in the underlying db.
    assert_equals(20, field_tester.field_a)
    assert_equals(20.5, field_tester.float_a)
    assert_equals(5, field_data.get(field_tester, "field_a"))
    assert_equals(6.1, field_data.get(field_tester, "float_a"))
    # save the XBlock
    field_tester.save()
    # verify that the fields have been updated correctly
    assert_equals(20, field_tester.field_a)
    assert_equals(20.5, field_tester.float_a)
    # Now, field_a should be updated in the underlying db
    assert_equals(20, field_data.get(field_tester, "field_a"))
    assert_equals(20.5, field_data.get(field_tester, "float_a"))
    assert_equals(10, field_tester.field_b)
    assert_equals(42, field_tester.field_c)
    assert_equals(None, field_tester.float_b)

    # Deletes happen immediately (do not require a save)
    del field_tester.field_a
    del field_tester.float_a

    # After delete, we should find default values in the cache
    assert_equals(None, field_tester.field_a)
    assert_equals(5.8, field_tester.float_a)
    # But the fields should not actually be present in the underlying kvstore
    with assert_raises(KeyError):
        field_data.get(field_tester, "field_a")
    assert_false(field_data.has(field_tester, "field_a"))
    with assert_raises(KeyError):
        field_data.get(field_tester, "float_a")
    assert_false(field_data.has(field_tester, "float_a"))
Exemplo n.º 14
0
    def test_bad_parameters(self):
        """
        Test that `TypeError`s are thrown for bad input parameters.
        """
        with assert_raises(TypeError):
            StudioValidationMessage("unknown type", u"Unknown type info")

        with assert_raises(TypeError):
            StudioValidationMessage(StudioValidationMessage.WARNING, u"bad warning", action_class=0)

        with assert_raises(TypeError):
            StudioValidationMessage(StudioValidationMessage.WARNING, u"bad warning", action_runtime_event=0)

        with assert_raises(TypeError):
            StudioValidationMessage(StudioValidationMessage.WARNING, u"bad warning", action_label="Non-unicode string")
Exemplo n.º 15
0
    def test_bad_parameters(self):
        """
        Test that `TypeError`s are thrown for bad input parameters.
        """
        with assert_raises(TypeError):
            StudioValidationMessage("unknown type", u"Unknown type info")

        with assert_raises(TypeError):
            StudioValidationMessage(StudioValidationMessage.WARNING, u"bad warning", action_class=0)

        with assert_raises(TypeError):
            StudioValidationMessage(StudioValidationMessage.WARNING, u"bad warning", action_runtime_event=0)

        with assert_raises(TypeError):
            StudioValidationMessage(StudioValidationMessage.WARNING, u"bad warning", action_label="Non-unicode string")
Exemplo n.º 16
0
def test_runtime_render():
    key_store = DictKeyValueStore()
    field_data = KvsFieldData(key_store)
    runtime = MockRuntimeForQuerying(services={'field-data': field_data})
    tester = TestXBlock(runtime, scope_ids=Mock(spec=ScopeIds))
    # string we want to update using the handler
    update_string = u"user state update"

    # test against the student view
    frag = runtime.render(tester, 'student_view', [update_string])
    assert_equals(frag.body_html(), update_string)
    assert_equals(tester.preferences, update_string)

    # test against the fallback view
    update_string = u"new update"
    frag = runtime.render(tester, 'test_fallback_view', [update_string])
    assert_equals(frag.body_html(), update_string)
    assert_equals(tester.preferences, update_string)

    # test block-first
    update_string = u"penultimate update"
    frag = tester.render('student_view', [update_string])
    assert_equals(frag.body_html(), update_string)
    assert_equals(tester.preferences, update_string)

    # test against the no-fallback XBlock
    update_string = u"ultimate update"
    tester = TestXBlockNoFallback(Mock(), scope_ids=Mock(spec=ScopeIds))
    with assert_raises(NoSuchViewError):
        runtime.render(tester, 'test_nonexistant_view', [update_string])
Exemplo n.º 17
0
def test_dummy_user_service_exception():
    """
    Tests NotImplemented error raised by UserService when not instantiated with kwarg get_current_user
    """
    user_service = UserService()
    with assert_raises(NotImplementedError):
        user_service.get_current_user()
Exemplo n.º 18
0
def test_dummy_user_service_exception():
    """
    Tests NotImplemented error raised by UserService when not instantiated with kwarg get_current_user
    """
    user_service = UserService()
    with assert_raises(NotImplementedError):
        user_service.get_current_user()
Exemplo n.º 19
0
def test_runtime_render():
    key_store = DictKeyValueStore()
    db_model = KvsFieldData(key_store)
    runtime = MockRuntimeForQuerying()
    tester = TestXBlock(runtime, db_model, Mock())
    # string we want to update using the handler
    update_string = u"user state update"

    # test against the student view
    frag = runtime.render(tester, 'student_view', [update_string])
    assert_equals(frag.body_html(), update_string)
    assert_equals(tester.preferences, update_string)

    # test against the fallback view
    update_string = u"new update"
    frag = runtime.render(tester, 'test_fallback_view', [update_string])
    assert_equals(frag.body_html(), update_string)
    assert_equals(tester.preferences, update_string)

    # test block-first
    update_string = u"penultimate update"
    frag = tester.render('student_view', [update_string])
    assert_equals(frag.body_html(), update_string)
    assert_equals(tester.preferences, update_string)

    # test against the no-fallback XBlock
    update_string = u"ultimate update"
    tester = TestXBlockNoFallback(Mock(), db_model, Mock())
    with assert_raises(NoSuchViewError):
        runtime.render(tester, 'test_nonexistant_view', [update_string])
Exemplo n.º 20
0
    def student_view(self, _context):
        """Try out some services."""
        # i18n is available, and works.
        def assert_equals_unicode(str1, str2):
            """`str1` equals `str2`, and both are Unicode strings."""
            assert_equals(str1, str2)
            assert isinstance(str1, unicode)
            assert isinstance(str2, unicode)

        i18n = self.runtime.service(self, "i18n")
        assert_equals_unicode(u"Welcome!", i18n.ugettext("Welcome!"))

        assert_equals_unicode(u"Plural", i18n.ungettext("Singular", "Plural", 0))
        assert_equals_unicode(u"Singular", i18n.ungettext("Singular", "Plural", 1))
        assert_equals_unicode(u"Plural", i18n.ungettext("Singular", "Plural", 2))

        # secret_service is available.
        assert_equals(self.runtime.service(self, "secret_service"), 17)

        # no_such_service is not available, and raises an exception, because we
        # said we needed it.
        with assert_raises(NoSuchServiceError):
            self.runtime.service(self, "no_such_service")

        # another_not_service is not available, and returns None, because we
        # didn't need it, we only wanted it.
        assert_is(self.runtime.service(self, "another_not_service"), None)
Exemplo n.º 21
0
def test_xblock_save_one():
    # Mimics a save failure when we only manage to save one of the values

    # Pylint, please allow this method to accept arguments.
    # pylint: disable=W0613
    def fake_set_many(block, update_dict):
        """Mock update method that throws a KeyValueMultiSaveError indicating
           that only one field was correctly saved."""
        raise KeyValueMultiSaveError([update_dict.keys()[0]])

    # pylint: enable=W0613

    field_tester = setup_save_failure(fake_set_many)

    field_tester.field_a = 20
    field_tester.field_b = 40
    field_tester.field_c = 60

    with assert_raises(XBlockSaveError) as save_error:
        # This call should raise an XBlockSaveError
        field_tester.save()

    # Verify that the correct data is getting stored by the error
    assert_equals(len(save_error.exception.saved_fields), 1)
    assert_equals(len(save_error.exception.dirty_fields), 2)
Exemplo n.º 22
0
def test_runtime_render():
    key_store = DictKeyValueStore()
    db_model = DbModel(key_store)
    runtime = MockRuntimeForQuerying()
    tester = TestXBlock(runtime, db_model, Mock())
    # string we want to update using the handler
    update_string = u"user state update"

    # test against the student view
    frag = runtime.render(tester, 'student_view', [update_string])
    assert_equals(frag.body_html(), update_string)
    assert_equals(tester.preferences, update_string)

    # test against the fallback view
    update_string = u"new update"
    frag = runtime.render(tester, 'test_fallback_view', [update_string])
    assert_equals(frag.body_html(), update_string)
    assert_equals(tester.preferences, update_string)

    # test block-first
    update_string = u"penultimate update"
    frag = tester.render('student_view', [update_string])
    assert_equals(frag.body_html(), update_string)
    assert_equals(tester.preferences, update_string)

    # test against the no-fallback XBlock
    update_string = u"ultimate update"
    tester = TestXBlockNoFallback(Mock(), db_model, Mock())
    with assert_raises(NoSuchViewError):
        runtime.render(tester, 'test_nonexistant_view', [update_string])
Exemplo n.º 23
0
def test_runtime_render():
    key_store = DictKeyValueStore()
    field_data = KvsFieldData(key_store)
    runtime = MockRuntimeForQuerying(services={'field-data': field_data})
    block_type = 'test'
    def_id = runtime.id_generator.create_definition(block_type)
    usage_id = runtime.id_generator.create_usage(def_id)
    tester = TestXBlock(runtime, scope_ids=ScopeIds('user', block_type, def_id, usage_id))
    # string we want to update using the handler
    update_string = u"user state update"

    # test against the student view
    frag = runtime.render(tester, 'student_view', [update_string])
    assert_in(update_string, frag.body_html())
    assert_equals(tester.preferences, update_string)

    # test against the fallback view
    update_string = u"new update"
    frag = runtime.render(tester, 'test_fallback_view', [update_string])
    assert_in(update_string, frag.body_html())
    assert_equals(tester.preferences, update_string)

    # test block-first
    update_string = u"penultimate update"
    frag = tester.render('student_view', [update_string])
    assert_in(update_string, frag.body_html())
    assert_equals(tester.preferences, update_string)

    # test against the no-fallback XBlock
    update_string = u"ultimate update"
    tester = TestXBlockNoFallback(Mock(), scope_ids=Mock(spec=ScopeIds))
    with assert_raises(NoSuchViewError):
        runtime.render(tester, 'test_nonexistent_view', [update_string])
Exemplo n.º 24
0
def test_runtime_render():
    key_store = DictKeyValueStore()
    field_data = KvsFieldData(key_store)
    runtime = MockRuntimeForQuerying(services={'field-data': field_data})
    block_type = 'test'
    def_id = runtime.id_generator.create_definition(block_type)
    usage_id = runtime.id_generator.create_usage(def_id)
    tester = TestXBlock(runtime, scope_ids=ScopeIds('user', block_type, def_id, usage_id))
    # string we want to update using the handler
    update_string = "user state update"

    # test against the student view
    frag = runtime.render(tester, 'student_view', [update_string])
    assert_in(update_string, frag.body_html())
    assert_equals(tester.preferences, update_string)

    # test against the fallback view
    update_string = "new update"
    frag = runtime.render(tester, 'test_fallback_view', [update_string])
    assert_in(update_string, frag.body_html())
    assert_equals(tester.preferences, update_string)

    # test block-first
    update_string = "penultimate update"
    frag = tester.render('student_view', [update_string])
    assert_in(update_string, frag.body_html())
    assert_equals(tester.preferences, update_string)

    # test against the no-fallback XBlock
    update_string = "ultimate update"
    no_fallback_tester = TestXBlockNoFallback(Mock(), scope_ids=Mock(spec=ScopeIds))
    with assert_raises(NoSuchViewError):
        runtime.render(no_fallback_tester, 'test_nonexistent_view', [update_string])
Exemplo n.º 25
0
    def test_add_messages_error(self):
        """
        Test that calling `add_messages` with something that is not a `Validation` instances throw an error.
        """
        validation = Validation("id")

        with assert_raises(TypeError):
            validation.add_messages("foo")
Exemplo n.º 26
0
    def test_add_messages_error(self):
        """
        Test that calling `add_messages` with something that is not a `Validation` instances throw an error.
        """
        validation = Validation("id")

        with assert_raises(TypeError):
            validation.add_messages("foo")
Exemplo n.º 27
0
    def test_set(self):
        assert_equals(1, self.agg.first)
        self.agg.first = 10
        assert_equals(10, self.agg.first)
        assert_equals(10, self.first.first)  # pylint: disable=E1101

        with assert_raises(AttributeError):
            self.agg.other = 99
        assert_false(hasattr(self.first, 'other'))
        assert_false(hasattr(self.second, 'other'))
Exemplo n.º 28
0
def test_runtime_handle():
    # Test a simple handler and a fallback handler

    key_store = DictKeyValueStore()
    field_data = KvsFieldData(key_store)
    test_runtime = TestRuntime(services={'field-data': field_data})
    basic_tester = TestXBlock(test_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(basic_tester, 'existing_handler', update_string),
        'I am the existing test handler')
    assert_equals(basic_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(basic_tester, 'test_fallback_handler',
                       new_update_string), 'I have been handled')
    assert_equals(basic_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(basic_tester, 'handler_without_correct_decoration',
                       new_update_string), 'gone to fallback')
    assert_equals(basic_tester.user_state, new_update_string)

    # handler can't be found & no fallback handler supplied, should throw an exception
    no_fallback_tester = TestXBlockNoFallback(runtime,
                                              scope_ids=Mock(spec=ScopeIds))
    ultimate_string = "ultimate update"
    with assert_raises(NoSuchHandlerError):
        runtime.handle(no_fallback_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(no_fallback_tester,
                       'handler_without_correct_decoration', 'handled')
Exemplo n.º 29
0
    def test_set(self):
        assert_equals(1, self.agg.first)
        self.agg.first = 10
        assert_equals(10, self.agg.first)
        assert_equals(10, self.first.first)  # pylint: disable=E1101

        with assert_raises(AttributeError):
            self.agg.other = 99
        assert_false(hasattr(self.first, 'other'))
        assert_false(hasattr(self.second, 'other'))
Exemplo n.º 30
0
def test_ugettext_calls():
    """
    Test ugettext calls in xblock.
    """
    runtime = TestRuntime()
    block = XBlockWithServices(runtime, scope_ids=Mock(spec=[]))
    assert_equals(block.ugettext('test'), u'test')
    assert_true(isinstance(block.ugettext('test'), unicode))

    # NoSuchServiceError exception should raise if i18n is none/empty.
    runtime = TestRuntime(services={'i18n': None})
    block = XBlockWithServices(runtime, scope_ids=Mock(spec=[]))
    with assert_raises(NoSuchServiceError):
        block.ugettext('test')
Exemplo n.º 31
0
def test_runtime_handle():
    # Test a simple handler and a fallback handler

    key_store = DictKeyValueStore()
    db_model = DbModel(key_store)
    tester = TestXBlock(Mock(), db_model, Mock())
    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(Mock(), db_model, Mock())
    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')
Exemplo n.º 32
0
def test_runtime_handle():
    # Test a simple handler and a fallback handler

    key_store = DictKeyValueStore()
    db_model = DbModel(key_store)
    tester = TestXBlock(Mock(), db_model, Mock())
    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(Mock(), db_model, Mock())
    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')
Exemplo n.º 33
0
def test_ugettext_calls():
    """
    Test ugettext calls in xblock.
    """
    runtime = TestRuntime()
    block = XBlockWithServices(runtime, scope_ids=Mock(spec=[]))
    assert_equals(block.ugettext('test'), 'test')
    assert_true(isinstance(block.ugettext('test'), six.text_type))

    # NoSuchServiceError exception should raise if i18n is none/empty.
    runtime = TestRuntime(services={
        'i18n': None
    })
    block = XBlockWithServices(runtime, scope_ids=Mock(spec=[]))
    with assert_raises(NoSuchServiceError):
        block.ugettext('test')
Exemplo n.º 34
0
def test_xblock_without_handler():
    # Test that an XBlock without a handler raises an Exception
    # when we try to hit a handler on it
    client = Client()

    # Pick a random usage_id from the USAGE_STORE because we
    # need to ensure the usage is a valid id.
    # TODO: Make a usage in this test instead.
    usage_id = USAGE_STORE._usages.keys()[0]
    # Plug that usage_id into a mock handler URL
    # /handler/[usage_id]/[handler_name]
    handler_url = "/handler/" + usage_id + "/does_not_exist/?student=student_doesntexist"

    # The default XBlock implementation doesn't provide
    # a handler, so this call should raise an exception
    # (from xblock.runtime.Runtime.handle)
    with assert_raises(NoSuchHandlerError):
        client.post(handler_url, '{}', 'text/json')
Exemplo n.º 35
0
def test_xblock_without_handler():
    # Test that an XBlock without a handler raises an Exception
    # when we try to hit a handler on it
    client = Client()

    # Pick the most usage ID we just made in the temp_scenario setup...
    usage_id = ID_MANAGER.last_created_usage_id()

    # Plug that usage_id into a mock handler URL
    # /handler/[usage_id]/[handler_name]
    handler_url = (
        reverse("handler", kwargs={"usage_id": usage_id, "handler_slug": "does_not_exist", "suffix": ""})
        + "?student=student_doesntexist"
    )

    # The default XBlock implementation doesn't provide
    # a handler, so this call should raise an exception
    # (from xblock.runtime.Runtime.handle)
    with assert_raises(NoSuchHandlerError):
        client.post(handler_url, "{}", "text/json")
Exemplo n.º 36
0
def test_xblock_save_failure_none():
    # Mimics a save failure when we don't manage to save any of the values

    def fake_set_many(block, update_dict):  # pylint: disable=unused-argument
        """Mock update method that throws a KeyValueMultiSaveError indicating
           that no fields were correctly saved."""
        raise KeyValueMultiSaveError([])

    field_tester = setup_save_failure(fake_set_many)
    field_tester.field_a = 20
    field_tester.field_b = 30
    field_tester.field_c = 40

    with assert_raises(XBlockSaveError) as save_error:
        # This call should raise an XBlockSaveError
        field_tester.save()

    # Verify that the correct data is getting stored by the error
    assert_equals(len(save_error.exception.saved_fields), 0)
    assert_equals(len(save_error.exception.dirty_fields), 3)
Exemplo n.º 37
0
def test_xblock_without_handler():
    # Test that an XBlock without a handler raises an Exception
    # when we try to hit a handler on it
    client = Client()

    # Pick the most-recent usage ID just made in the temp_scenario setup...
    usage_id = ID_MANAGER.last_created_usage_id()

    # Plug that usage_id into a mock handler URL
    # /handler/[usage_id]/[handler_name]
    handler_url = reverse('handler', kwargs={
        'usage_id': usage_id,
        'handler_slug': 'does_not_exist',
        'suffix': ''
    }) + '?student=student_doesntexist'

    # The default XBlock implementation doesn't provide
    # a handler, so this call should raise an exception
    # (from xblock.runtime.Runtime.handle)
    with assert_raises(NoSuchHandlerError):
        client.post(handler_url, '{}', 'text/json')
Exemplo n.º 38
0
def test_xblock_without_handler():
    # Test that an XBlock without a handler raises an Exception
    # when we try to hit a handler on it
    client = Client()

    # Pick a random usage_id from the USAGE_STORE because we
    # need to ensure the usage is a valid id.
    # TODO: Make a usage in this test instead.
    usage_id = USAGE_STORE._usages.keys()[0]
    # Plug that usage_id into a mock handler URL
    # /handler/[usage_id]/[handler_name]
    handler_url = reverse('handler', kwargs={
        'usage_id': usage_id,
        'handler_slug': 'does_not_exist',
        'suffix': ''
    }) + '?student=student_doesntexist'

    # The default XBlock implementation doesn't provide
    # a handler, so this call should raise an exception
    # (from xblock.runtime.Runtime.handle)
    with assert_raises(NoSuchHandlerError):
        client.post(handler_url, '{}', 'text/json')
Exemplo n.º 39
0
def test_xblock_without_handler():
    # Test that an XBlock without a handler raises an Exception
    # when we try to hit a handler on it
    client = Client()

    # Pick the most usage ID we just made in the temp_scenario setup...
    usage_id = ID_MANAGER.last_created_usage_id()

    # Plug that usage_id into a mock handler URL
    # /handler/[usage_id]/[handler_name]
    handler_url = reverse('handler',
                          kwargs={
                              'usage_id': usage_id,
                              'handler_slug': 'does_not_exist',
                              'suffix': ''
                          }) + '?student=student_doesntexist'

    # The default XBlock implementation doesn't provide
    # a handler, so this call should raise an exception
    # (from xblock.runtime.Runtime.handle)
    with assert_raises(NoSuchHandlerError):
        client.post(handler_url, '{}', 'text/json')
Exemplo n.º 40
0
def test_xblock_without_handler():
    # Test that an XBlock without a handler raises an Exception
    # when we try to hit a handler on it
    client = Client()

    # Pick a random usage_id from the ID_MANAGER because we
    # need to ensure the usage is a valid id.
    # TODO: Make a usage in this test instead.
    usage_id = ID_MANAGER._usages.keys()[0]
    # Plug that usage_id into a mock handler URL
    # /handler/[usage_id]/[handler_name]
    handler_url = reverse('handler', kwargs={
        'usage_id': usage_id,
        'handler_slug': 'does_not_exist',
        'suffix': ''
    }) + '?student=student_doesntexist'

    # The default XBlock implementation doesn't provide
    # a handler, so this call should raise an exception
    # (from xblock.runtime.Runtime.handle)
    with assert_raises(NoSuchHandlerError):
        client.post(handler_url, '{}', 'text/json')
Exemplo n.º 41
0
def test_xblock_save_one():
    # Mimics a save failure when we only manage to save one of the values

    # Pylint, please allow this method to accept arguments.
    # pylint: disable=W0613
    def fake_set_many(block, update_dict):
        """Mock update method that throws a KeyValueMultiSaveError indicating
           that only one field was correctly saved."""
        raise KeyValueMultiSaveError([update_dict.keys()[0]])
    # pylint: enable=W0613

    field_tester = setup_save_failure(fake_set_many)

    field_tester.field_a = 20
    field_tester.field_b = 40
    field_tester.field_c = 60

    with assert_raises(XBlockSaveError) as save_error:
        # This call should raise an XBlockSaveError
        field_tester.save()

    # Verify that the correct data is getting stored by the error
    assert_equals(len(save_error.exception.saved_fields), 1)
    assert_equals(len(save_error.exception.dirty_fields), 2)
Exemplo n.º 42
0
 def test_get(self):
     assert_equals(1, self.agg.first)
     assert_equals(2, self.agg.second)
     assert_false(hasattr(self.agg, 'other'))
     with assert_raises(AttributeError):
         self.agg.other  # pylint: disable=W0104
Exemplo n.º 43
0
 def test_delete(self):
     with assert_raises(InvalidScopeError):
         self.read_only.delete(self.block, 'content')
Exemplo n.º 44
0
 def test_set_many(self):
     with assert_raises(InvalidScopeError):
         self.read_only.set_many(self.block, {
             'content': 'foo',
             'settings': 'bar'
         })
Exemplo n.º 45
0
 def test_invalid_scope(self):
     with assert_raises(InvalidScopeError):
         self.split.get(self.block, 'user_state')
Exemplo n.º 46
0
 def test_set_many(self):
     with assert_raises(InvalidScopeError):
         self.read_only.set_many(self.block, {'content': 'foo', 'settings': 'bar'})
Exemplo n.º 47
0
 def test_set(self):
     with assert_raises(InvalidScopeError):
         self.read_only.set(self.block, 'content', 'foo')
Exemplo n.º 48
0
 def test_get(self):
     assert_equals(1, self.agg.first)
     assert_equals(2, self.agg.second)
     assert_false(hasattr(self.agg, 'other'))
     with assert_raises(AttributeError):
         self.agg.other  # pylint: disable=W0104
Exemplo n.º 49
0
 def test_copy_errors(self):
     with assert_raises(TypeError):
         StudioValidation.copy("foo")
Exemplo n.º 50
0
 def test_set_summary_errors(self):
     """
     Test that `set_summary` errors if argument is not a ValidationMessage.
     """
     with assert_raises(TypeError):
         StudioValidation("id").set_summary("foo")
Exemplo n.º 51
0
 def test_set(self):
     with assert_raises(InvalidScopeError):
         self.read_only.set(self.block, 'content', 'foo')
Exemplo n.º 52
0
 def test_set_summary_errors(self):
     """
     Test that `set_summary` errors if argument is not a ValidationMessage.
     """
     with assert_raises(TypeError):
         StudioValidation("id").set_summary("foo")
Exemplo n.º 53
0
 def test_invalid_scope(self):
     with assert_raises(InvalidScopeError):
         self.split.get(self.block, 'user_state')
Exemplo n.º 54
0
 def test_copy_errors(self):
     with assert_raises(TypeError):
         StudioValidation.copy("foo")