Esempio n. 1
0
 def decorated(value, *a):
     if self.__validator_leaf__ is True:
         if isinstance(value, dict):
             # convert the 'data' to an actual value. 'data' is of {0: {'key': 'value'}}
             value = dict(i for i in value.values())
     ensure(isinstance(value, self.valid_types), fail_msg)
     func(value)
Esempio n. 2
0
    def enforce(self, data, schema, item_index, tree):
        # yo dawg, a recursive validator within a recursive validator anyone?
        if is_callable(schema) and hasattr(schema, '__validator_leaf__'):
            return schema(data[item_index], tree)
        if isinstance(data[item_index], dict) and isinstance(schema, tuple):
            try:
                _validator = Validator(data[item_index], schema)
                _validator.validate()
            except Invalid:
                e = sys.exc_info()[1]
                tree.append('list[%s]' % item_index)
                tree.extend(e.path)
                raise Invalid(e.schema_item, tree, reason=e._reason, pair='value')

            # FIXME this is utterly redundant, and also happens in
            # RecursiveValidator
            except SchemaError:
                e = sys.exc_info()[1]
                tree.extend(e.path)
                raise SchemaError('', tree, reason=e._reason, pair='value')

        elif isinstance(schema, tuple) and not isinstance(data[item_index], (tuple, dict)):
            raise SchemaError(data, tree, reason='iterable contains single items, schema does not')
        else:
            try:
                if is_callable(schema):
                    schema(data[item_index])
                else:
                    ensure(data[item_index] == schema)
            except AssertionError:
                reason = sys.exc_info()[1]
                tree.append('list[%s]' % item_index)
                raise Invalid(schema, tree, reason=reason, pair='item')
Esempio n. 3
0
def dictionary(_object, *args):
    """
    Validates a given input is of type dictionary.

    Example usage::

        data = {'a' : {'b': 1}}
        schema = ('a', dictionary)

    You can also use this as a decorator, as a way to check for the
    input before it even hits a validator you may be writing.

    .. note::
        If the argument is a callable, the decorating behavior will be
        triggered, otherwise it will act as a normal function.

    """
    error_msg = 'not of type dictionary'
    if is_callable(_object):
        _validator = _object

        @wraps(_validator)
        def decorated(value):
            ensure(isinstance(value, dict), error_msg)
            return _validator(value)
        return decorated
    try:
        ensure(isinstance(_object, dict), error_msg)
    except AssertionError:
        if args:
            msg = 'did not pass validation against callable: dictionary'
            raise Invalid('', msg=msg, reason=error_msg, *args)
        raise
Esempio n. 4
0
def string(_object):
    """
    Validates a given input is of type string.

    Example usage::

        data = {'a' : 21}
        schema = (string, 21)

    You can also use this as a decorator, as a way to check for the
    input before it even hits a validator you may be writing.

    .. note::
        If the argument is a callable, the decorating behavior will be
        triggered, otherwise it will act as a normal function.
    """
    if is_callable(_object):
        _validator = _object

        @wraps(_validator)
        def decorated(value):
            ensure(isinstance(value, basestring), "not of type string")
            return _validator(value)
        return decorated
    ensure(isinstance(_object, basestring), "not of type string")
Esempio n. 5
0
 def decorated(value, *a):
     if self.__validator_leaf__ is True:
         if isinstance(value, dict):
             # convert the 'data' to an actual value. 'data' is of {0: {'key': 'value'}}
             value = dict(i for i in value.values())
     ensure(isinstance(value, self.valid_types), fail_msg)
     func(value)
Esempio n. 6
0
    def enforce(self, data, schema, item_index, tree):
        # yo dawg, a recursive validator within a recursive validator anyone?
        if is_callable(schema) and hasattr(schema, '__validator_leaf__'):
            return schema(data[item_index], tree)
        if isinstance(data[item_index], dict) and isinstance(schema, tuple):
            try:
                _validator = Validator(data[item_index], schema)
                _validator.validate()
            except Invalid:
                e = sys.exc_info()[1]
                tree.append('list[%s]' % item_index)
                tree.extend(e.path)
                raise Invalid(e.schema_item,
                              tree,
                              reason=e._reason,
                              pair='value')

            # FIXME this is utterly redundant, and also happens in
            # RecursiveValidator
            except SchemaError:
                e = sys.exc_info()[1]
                tree.extend(e.path)
                raise SchemaError('', tree, reason=e._reason, pair='value')

        elif isinstance(schema,
                        tuple) and not isinstance(data[item_index],
                                                  (tuple, dict)):
            raise SchemaError(
                data,
                tree,
                reason='iterable contains single items, schema does not')
        else:
            try:
                if is_callable(schema):
                    schema(data[item_index])
                else:
                    ensure(data[item_index] == schema)
            except AssertionError:
                reason = sys.exc_info()[1]
                tree.append('list[%s]' % item_index)
                raise Invalid(schema, tree, reason=reason, pair='item')
Esempio n. 7
0
def not_empty(_object):
    """
    Validates the given input (has to be a valid data structure) is empty.
    Input *has* to be one of: `list`, `dict`, or `string`.

    It is specially useful when most of the validators being created are
    dealing with data structures that should not be empty.
    """
    if is_callable(_object):
        _validator = _object

        @wraps(_validator)
        @instance_of()
        def decorated(value):
            ensure(value, "%s is empty" % safe_repr(value))
            return _validator(value)
        return decorated
    try:
        ensure(len(_object), "%s is empty" % safe_repr(_object))
    except TypeError:
        raise AssertionError("not of any valid types: [list, dict, str]")
Esempio n. 8
0
def not_empty(_object):
    """
    Validates the given input (has to be a valid data structure) is empty.
    Input *has* to be one of: `list`, `dict`, or `string`.

    It is specially useful when most of the validators being created are
    dealing with data structures that should not be empty.
    """
    if is_callable(_object):
        _validator = _object

        @wraps(_validator)
        @instance_of()
        def decorated(value):
            ensure(value, "%s is empty" % safe_repr(value))
            return _validator(value)

        return decorated
    try:
        ensure(len(_object), "%s is empty" % safe_repr(_object))
    except TypeError:
        raise AssertionError("not of any valid types: [list, dict, str]")
Esempio n. 9
0
def enforce(data_item, schema_item, tree, pair):
    schema_is_optional = hasattr(schema_item, 'is_optional')
    if is_callable(schema_item) and not schema_is_optional:
        try:
            schema_item(data_item)
        except AssertionError:
            e = sys.exc_info()[1]
            if pair == 'value':
                tree.append(data_item)
            raise Invalid(schema_item, tree, reason=e, pair=pair)
    else:
        try:
            if schema_is_optional:
                if is_empty(data_item):  # we received nothing here
                    return
                ensure(data_item == schema_item())
            else:
                ensure(data_item == schema_item)
        except AssertionError:
            e = sys.exc_info()[1]
            if pair == 'value':
                tree.append(data_item)
            raise Invalid(schema_item, tree, reason=e, pair=pair)
Esempio n. 10
0
def enforce(data_item, schema_item, tree, pair):
    schema_is_optional = hasattr(schema_item, 'is_optional')
    if is_callable(schema_item) and not schema_is_optional:
        try:
            schema_item(data_item)
        except AssertionError:
            e = sys.exc_info()[1]
            if pair == 'value':
                tree.append(data_item)
            raise Invalid(schema_item, tree, reason=e, pair=pair)
    else:
        try:
            if schema_is_optional:
                if is_empty(data_item):  # we received nothing here
                    return
                ensure(data_item == schema_item())
            else:
                ensure(data_item == schema_item)
        except AssertionError:
            e = sys.exc_info()[1]
            if pair == 'value':
                tree.append(data_item)
            raise Invalid(schema_item, tree, reason=e, pair=pair)
Esempio n. 11
0
 def test_ensure(self):
     assert utils.ensure(1 == 1)
Esempio n. 12
0
 def decorated(value):
     ensure(isinstance(value, self.valid_types), fail_msg)
     func(value)
Esempio n. 13
0
 def test_ensure_raises_assertionerror(self):
     with raises(AssertionError):
         utils.ensure(0 == 1)
Esempio n. 14
0
 def decorated(value):
     ensure(isinstance(value, dict), error_msg)
     return _validator(value)
Esempio n. 15
0
 def decorated(value):
     ensure(isinstance(value, basestring), "not of type string")
     return _validator(value)
Esempio n. 16
0
 def decorated(value):
     ensure(isinstance(value, bool), "not of type boolean")
     return _validator(value)
Esempio n. 17
0
 def decorated(value):
     ensure(isinstance(value, int), "not of type int")
     return _validator(value)
Esempio n. 18
0
 def decorated(value):
     ensure(isinstance(value, list), "not of type array")
     return _validator(value)
Esempio n. 19
0
 def decorated(value):
     ensure(isinstance(value, self.valid_types), fail_msg)
     func(value)
Esempio n. 20
0
 def test_ensure_raises_assertionerror(self):
     with raises(AssertionError):
         utils.ensure(0 == 1)
Esempio n. 21
0
 def decorated(value):
     ensure(value, "%s is empty" % safe_repr(value))
     return _validator(value)
Esempio n. 22
0
 def decorated(value):
     ensure(value, "%s is empty" % safe_repr(value))
     return _validator(value)
Esempio n. 23
0
 def test_ensure(self):
     assert utils.ensure(1 == 1)