Ejemplo n.º 1
0
    def validate(self, value):

        _validated_value = None

        if self._required and self._default is None and value is None:
            raise exception.RequiredAttributeError()
        elif self._required and value is None:
            value = self._default
        elif not self._required and self._default is None and value is None:
            return _validated_value
        elif not self._required and value is None:
            value = self._default

        try:
            from prestans.util import string_types

            if isinstance(value, string_types):
                _validated_value = value
            else:
                _validated_value = str(value)
        except Exception as exp:
            raise exception.ParseFailedError(
                "unicode or string encoding failed, %s" % exp)

        if self._trim:
            _validated_value = _validated_value.strip()

        # check for required and empty string
        if self._required and len(_validated_value) == 0:
            raise exception.RequiredAttributeError()

        if not self._required and len(_validated_value) == 0:
            return _validated_value

        if _validated_value is not None and self._min_length is not None and \
                len(_validated_value) < self._min_length:
            raise exception.MinimumLengthError(value, self._min_length)
        if _validated_value is not None and self._max_length is not None and \
                len(_validated_value) > self._max_length:
            raise exception.MaximumLengthError(value, self._max_length)

        if self._choices is not None and not _validated_value in self._choices:
            raise exception.InvalidChoiceError(value, self._choices)

        if self._format is not None and re.search(self._format,
                                                  _validated_value) is None:
            raise exception.InvalidFormatError(_validated_value)

        return _validated_value
Ejemplo n.º 2
0
    def validate(self, value):

        if not self._required and self._default is None and value is None:
            return None
        if self._required and self._default is None and value is None:
            raise exception.RequiredAttributeError()
        elif self._required and value is None:
            value = self._default
        elif not self._required and value is None:
            value = self._default

        try:
            _validated_value = float(value)
        except Exception as exp:
            raise exception.ParseFailedError("float encoding failed %s" % exp)

        if _validated_value is not None and self._minimum is not None and _validated_value < self._minimum:
            raise exception.LessThanMinimumError(value, self._minimum)

        if _validated_value is not None and self._maximum is not None and _validated_value > self._maximum:
            raise exception.MoreThanMaximumError(value, self._maximum)

        if self._choices is not None and _validated_value not in self._choices:
            raise exception.InvalidChoiceError(value, self._choices)

        return _validated_value
Ejemplo n.º 3
0
    def validate(self, value):

        if not self._required and self._default is None and value is None:
            return None
        elif self._required and self._default is None and value is None:
            raise exception.RequiredAttributeError()
        elif self._default is not None and value is None:
            value = self._default

        try:
            from prestans.util import integer_types

            if isinstance(value, integer_types):
                _validated_value = value
            else:
                _validated_value = int(value)
        except Exception:
            raise exception.ParseFailedError("encoding failed: value is not an integer or a long")

        if _validated_value is not None and self._minimum is not None and _validated_value < self._minimum:
            raise exception.LessThanMinimumError(value, self._minimum)
        if _validated_value is not None and self._maximum is not None and _validated_value > self._maximum:
            raise exception.MoreThanMaximumError(value, self._maximum)

        if self._choices is not None and not _validated_value in self._choices:
            raise exception.InvalidChoiceError(value, self._choices)

        return _validated_value
Ejemplo n.º 4
0
    def validate(self, value):

        _validated_value = None

        if self._required and self._default is None and value is None:
            raise exception.RequiredAttributeError()
        elif self._required and value is None:
            if self._default == Date.TODAY:
                value = date.today()
            else:
                value = self._default
        elif not self._required and self._default is None and value is None:
            return _validated_value
        elif not self._required and value is None:
            if self._default == Date.TODAY:
                value = date.today()
            else:
                value = self._default

        from prestans.util import string_types

        if isinstance(value, date_type):
            _validated_value = value
        elif isinstance(value, string_types):
            try:
                _validated_value = datetime.strptime(value,
                                                     self._format).date()
            except ValueError as exp:
                raise exception.ParseFailedError("date parsing failed %s" %
                                                 exp)
        else:
            raise exception.ParseFailedError("cannot parse value of type %s" %
                                             value.__class__.__name__)

        return _validated_value
Ejemplo n.º 5
0
    def validate(self, value):
        from prestans.util import string_types

        _validated_value = None

        # no need to do any validation if None, not required and default provided
        if not self._required and self._default is None and value is None:
            return value
        elif self._required and self._default is None and value is None:
            raise exception.RequiredAttributeError()
        elif value is None and self._default is not None:
            if self._default == Time.NOW:
                value = datetime.now()
            elif self._default == Time.UTC_NOW:
                value = datetime.utcnow()
            else:
                value = self._default

        if isinstance(value, time):
            _validated_value = value
        elif isinstance(value, string_types):
            try:
                _validated_value = datetime.strptime(value,
                                                     self._format).time()
            except ValueError as exp:
                raise exception.ParseFailedError("time parsing failed %s" %
                                                 exp)
        else:
            raise exception.ParseFailedError("cannot parse value of type %s" %
                                             value.__class__.__name__)

        return _validated_value
Ejemplo n.º 6
0
    def validate(self, value):

        _validated_value = self.__class__()

        if self._required and value is None:
            raise exception.RequiredAttributeError()

        if self._required is False and value is None:
            return value

        try:
            data_url, delimiter, base64_content = value.partition(',')
            _validated_value._mime_type = data_url.replace(';base64',
                                                           '').replace(
                                                               'data:', '')
            _validated_value._file_contents = base64.b64decode(base64_content)
        except Exception as exp:
            raise exception.ParseFailedError(
                "data url file encoding failed %s" % exp)

        if self._allowed_mime_types and len(self._allowed_mime_types) > 0 \
           and _validated_value._mime_type not in self._allowed_mime_types:
            raise exception.InvalidChoiceError(_validated_value._mime_type,
                                               self._allowed_mime_types)

        return _validated_value
Ejemplo n.º 7
0
    def validate(self, value):

        if not self._required and self._default is None and value is None:
            return None
        elif self._required and self._default is None and value is None:
            raise exception.RequiredAttributeError()
        elif value is None and self.default is not None:
            value = self._default

        if not isinstance(value, bool):
            raise exception.ParseFailedError()

        return value
Ejemplo n.º 8
0
    def validate(self, value, attribute_filter=None, minified=False):
        """
        :param value:
        :type value: list | None
        :param attribute_filter:
        :type attribute_filter: prestans.parser.AttributeFilter
        :param minified:
        :type minified: bool
        :return:
        """

        if not self._required and value is None:
            return None
        elif self._required and value is None:
            raise exception.RequiredAttributeError()

        _validated_value = self.__class__(
            element_template=self._element_template,
            min_length=self._min_length,
            max_length=self._max_length)

        if not isinstance(value, (list, tuple)):
            raise TypeError(value)

        for array_element in value:

            if isinstance(self._element_template, DataCollection):
                validated_array_element = self._element_template.validate(
                    array_element, attribute_filter, minified)
            else:
                validated_array_element = self._element_template.validate(
                    array_element)

            _validated_value.append(validated_array_element)

        if self._min_length is not None and len(
                _validated_value) < self._min_length:
            raise exception.LessThanMinimumError(value, self._min_length)

        if self._max_length is not None and len(
                _validated_value) > self._max_length:
            raise exception.MoreThanMaximumError(value, self._max_length)

        return _validated_value
Ejemplo n.º 9
0
 def test_init(self):
     exp = exception.RequiredAttributeError()
     self.assertEqual(exp.http_status, STATUS.BAD_REQUEST)
     self.assertEqual(
         exp.message,
         "attribute is required and does not provide a default value")
Ejemplo n.º 10
0
    def validate(self, value, attribute_filter=None, minified=False):
        """
        :param value: serializable input to validate
        :type value: dict | None
        :param attribute_filter:
        :type: prestans.parser.AttributeFilter | None
        :param minified: whether or not the input is minified
        :type minified: bool
        :return: the validated model
        :rtype: Model
        """

        if self._required and (value is None or not isinstance(value, dict)):
            """
            Model level validation requires a parsed dictionary
            this is done by the serializer
            """
            raise exception.RequiredAttributeError()

        if not self._required and not value:
            """
            Value was not provided by caller, but require a template
            """
            return None

        _model_instance = self.__class__()

        rewrite_map = self.attribute_rewrite_map()

        from prestans.parser import AttributeFilter
        from prestans.parser import AttributeFilterImmutable

        for attribute_name, type_instance in self.getmembers():
            if not isinstance(type_instance, DataType):
                raise TypeError("%s must be a DataType subclass" %
                                attribute_name)

            if isinstance(attribute_filter, (AttributeFilter, AttributeFilterImmutable)) and \
               not attribute_filter.is_attribute_visible(attribute_name):
                _model_instance._attributes[attribute_name] = None
                continue

            validation_input = None

            input_value_key = attribute_name

            # minification support
            if minified is True:
                input_value_key = rewrite_map[attribute_name]

            if input_value_key in value:
                validation_input = value[input_value_key]

            try:

                if isinstance(type_instance, DataCollection):
                    sub_attribute_filter = None
                    if attribute_filter and attribute_name in attribute_filter:
                        sub_attribute_filter = getattr(attribute_filter,
                                                       attribute_name)

                    validated_object = type_instance.validate(
                        validation_input, sub_attribute_filter, minified)
                else:
                    validated_object = type_instance.validate(validation_input)

                _model_instance._attributes[attribute_name] = validated_object

            except exception.DataValidationException as exp:
                raise exception.ValidationError(
                    message=str(exp),
                    attribute_name=attribute_name,
                    value=validation_input,
                    blueprint=type_instance.blueprint())

        return _model_instance