コード例 #1
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
    def __call__(self, value):
        try:
            if value not in self.choices:
                raise ValidationError(self._format_error(value))
        except TypeError:
            raise ValidationError(self._format_error(value))

        return value
コード例 #2
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
    def __call__(self, value):
        if self.min is not None and value < self.min:
            message = (
                self.message_min if self.max is None else self.message_all
            )
            raise ValidationError(self._format_error(value, message))

        if self.max is not None and value > self.max:
            message = (
                self.message_max if self.min is None else self.message_all
            )
            raise ValidationError(self._format_error(value, message))

        return value
コード例 #3
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
    def __call__(self, value):
        method = getattr(value, self.method)

        if not method(**self.kwargs):
            raise ValidationError(self._format_error(value))

        return value
コード例 #4
0
ファイル: schema.py プロジェクト: CyberGRX/marshmallow
    def dump(self, obj, *, many=None):
        """Serialize an object to native Python data types according to this
        Schema's fields.

        :param obj: The object to serialize.
        :param bool many: Whether to serialize `obj` as a collection. If `None`, the value
            for `self.many` is used.
        :return: A dict of serialized data
        :rtype: dict

        .. versionadded:: 1.0.0
        .. versionchanged:: 3.0.0b7
            This method returns the serialized data rather than a ``(data, errors)`` duple.
            A :exc:`ValidationError <marshmallow_muffin.exceptions.ValidationError>` is raised
            if ``obj`` is invalid.
        """
        error_store = ErrorStore()
        errors = {}
        many = self.many if many is None else bool(many)
        if many and is_iterable_but_not_string(obj):
            obj = list(obj)

        if self._has_processors(PRE_DUMP):
            try:
                processed_obj = self._invoke_dump_processors(
                    PRE_DUMP, obj, many=many, original_data=obj
                )
            except ValidationError as error:
                errors = error.normalized_messages()
                result = None
        else:
            processed_obj = obj

        if not errors:
            result = self._serialize(
                processed_obj,
                fields_dict=self.fields,
                error_store=error_store,
                many=many,
                accessor=self.get_attribute,
                dict_class=self.dict_class,
                index_errors=self.opts.index_errors,
            )
            errors = error_store.errors

        if not errors and self._has_processors(POST_DUMP):
            try:
                result = self._invoke_dump_processors(
                    POST_DUMP, result, many=many, original_data=obj
                )
            except ValidationError as error:
                errors = error.normalized_messages()
        if errors:
            exc = ValidationError(errors, data=obj, valid_data=result)
            # User-defined error handler
            self.handle_error(exc, obj)
            raise exc

        return result
コード例 #5
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
    def __call__(self, value):
        try:
            if value in self.iterable:
                raise ValidationError(self._format_error(value))
        except TypeError:
            pass

        return value
コード例 #6
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
    def __call__(self, value):
        message = self._format_error(value)
        if not value:
            raise ValidationError(message)

        # Check first if the scheme is valid
        if "://" in value:
            scheme = value.split("://")[0].lower()
            if scheme not in self.schemes:
                raise ValidationError(message)

        regex = self._regex(self.relative, self.require_tld)

        if not regex.search(value):
            raise ValidationError(message)

        return value
コード例 #7
0
 def get_is_old(self, obj):
     if obj is None:
         return missing
     if isinstance(obj, dict):
         age = obj.get("age")
     else:
         age = obj.age
     try:
         return age > 80
     except TypeError as te:
         raise ValidationError(str(te))
コード例 #8
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
    def __call__(self, value):
        message = self._format_error(value)

        if not value or "@" not in value:
            raise ValidationError(message)

        user_part, domain_part = value.rsplit("@", 1)

        if not self.USER_REGEX.match(user_part):
            raise ValidationError(message)

        if domain_part not in self.DOMAIN_WHITELIST:
            if not self.DOMAIN_REGEX.match(domain_part):
                try:
                    domain_part = domain_part.encode("idna").decode("ascii")
                except UnicodeError:
                    pass
                else:
                    if self.DOMAIN_REGEX.match(domain_part):
                        return value
                raise ValidationError(message)

        return value
コード例 #9
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
    def __call__(self, value):
        length = len(value)

        if self.equal is not None:
            if length != self.equal:
                raise ValidationError(
                    self._format_error(value, self.message_equal)
                )
            return value

        if self.min is not None and length < self.min:
            message = (
                self.message_min if self.max is None else self.message_all
            )
            raise ValidationError(self._format_error(value, message))

        if self.max is not None and length > self.max:
            message = (
                self.message_max if self.min is None else self.message_all
            )
            raise ValidationError(self._format_error(value, message))

        return value
コード例 #10
0
 def test_can_pass_list_of_messages(self):
     err = ValidationError(["foo", "bar"])
     assert err.messages == ["foo", "bar"]
コード例 #11
0
 def test_stores_message_in_list(self):
     err = ValidationError("foo")
     assert err.messages == ["foo"]
コード例 #12
0
    def test_str(self):
        err = ValidationError("invalid email")
        assert str(err) == "invalid email"

        err2 = ValidationError("invalid email", "email")
        assert str(err2) == "invalid email"
コード例 #13
0
 def test_can_store_field_name(self):
     err = ValidationError("invalid email", field_name="email")
     assert err.field_name == "email"
コード例 #14
0
 def test_stores_dictionaries(self):
     messages = {"user": {"email": ["email is invalid"]}}
     err = ValidationError(messages)
     assert err.messages == messages
コード例 #15
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
 def __call__(self, value):
     # We can't use set.issubset because does not handle unhashable types
     for val in value:
         if val not in self.choices:
             raise ValidationError(self._format_error(value))
     return value
コード例 #16
0
ファイル: schema.py プロジェクト: CyberGRX/marshmallow
    def _do_load(
        self, data, *, many=None, partial=None, unknown=None, postprocess=True
    ):
        """Deserialize `data`, returning the deserialized result.

        :param data: The data to deserialize.
        :param bool many: Whether to deserialize `data` as a collection. If `None`, the
            value for `self.many` is used.
        :param bool|tuple partial: Whether to validate required fields. If its value is an iterable,
            only fields listed in that iterable will be ignored will be allowed missing.
            If `True`, all fields will be allowed missing.
            If `None`, the value for `self.partial` is used.
        :param unknown: Whether to exclude, include, or raise an error for unknown
            fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`.
            If `None`, the value for `self.unknown` is used.
        :param bool postprocess: Whether to run post_load methods..
        :return: A dict of deserialized data
        :rtype: dict
        """
        error_store = ErrorStore()
        errors = {}
        many = self.many if many is None else bool(many)
        unknown = unknown or self.unknown
        if partial is None:
            partial = self.partial
        # Run preprocessors
        if self._has_processors(PRE_LOAD):
            try:
                processed_data = self._invoke_load_processors(
                    PRE_LOAD, data, many=many, original_data=data
                )
            except ValidationError as err:
                errors = err.normalized_messages()
                result = None
        else:
            processed_data = data
        if not errors:
            # Deserialize data
            result = self._deserialize(
                processed_data,
                fields_dict=self.fields,
                error_store=error_store,
                many=many,
                partial=partial,
                unknown=unknown,
                dict_class=self.dict_class,
                index_errors=self.opts.index_errors,
            )
            # Run field-level validation
            self._invoke_field_validators(
                error_store=error_store, data=result, many=many
            )
            # Run schema-level validation
            if self._has_processors(VALIDATES_SCHEMA):
                field_errors = bool(error_store.errors)
                self._invoke_schema_validators(
                    error_store=error_store,
                    pass_many=True,
                    data=result,
                    original_data=data,
                    many=many,
                    field_errors=field_errors,
                )
                self._invoke_schema_validators(
                    error_store=error_store,
                    pass_many=False,
                    data=result,
                    original_data=data,
                    many=many,
                    field_errors=field_errors,
                )
            errors = error_store.errors
            # Run post processors
            if not errors and postprocess and self._has_processors(POST_LOAD):
                try:
                    result = self._invoke_load_processors(
                        POST_LOAD, result, many=many, original_data=data
                    )
                except ValidationError as err:
                    errors = err.normalized_messages()
        if errors:
            exc = ValidationError(errors, data=data, valid_data=result)
            self.handle_error(exc, data)
            raise exc

        return result
コード例 #17
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
    def __call__(self, value):
        if self.regex.match(value) is None:
            raise ValidationError(self._format_error(value))

        return value
コード例 #18
0
ファイル: validate.py プロジェクト: CyberGRX/marshmallow
 def __call__(self, value):
     if value != self.comparable:
         raise ValidationError(self._format_error(value))
     return value