Exemplo n.º 1
0
 def __call__(self, date):
     now = datetime.datetime.now()
     if not self.allow_future and date > now:
         raise ValidationError('Date cannot be in the future')
     if not self.allow_past and date < now:
         raise ValidationError('Date cannot be in the past')
     return date
Exemplo n.º 2
0
 def __call__(self, value):
     if self._strip:
         value = value.strip()
     if not self._multi and ('\n' in value or '\r' in value):
         raise ValidationError(u'String have to be a single line')
     if value == '':
         raise ValidationError('This should not be empty')
     return value
Exemplo n.º 3
0
 def validate_resource_password(self, password):
     #avoid injections
     if '\n' in password:
         raise ValidationError(r'Password cannot contain `\n`')
     #check the minimum size of the password
     if len(password) < self.PASS_MIN_SIZE:
         raise ValidationError(r'Password must be at least {0} characters long'.format(self.PASS_MIN_SIZE))
     #always return the valid value
     return password
Exemplo n.º 4
0
    def test_validate_continue(self):
        self.f1.validate.side_effect = ValidationError({'f1': 'E1'})
        self.f2.validate.side_effect = ValidationError({'f2': 'E2'})

        try:
            self.rfd.validate({'f1': 1, 'f2': 'oh snap'})
        except ValidationError as ve:
            self.assertEqual(ve, ValidationError({
                'f1': 'E1',
                'f2': 'E2',
            }))
Exemplo n.º 5
0
    def validate_id(self, id_):
        """
        Check that the id given as an argument is a valid ID

        The id is always a string extracted from the url.

        If the id is not valid, raises a :exc:`napixd.exceptions.ValidationError`.
        If necessary, modify the id and return it.
        this method MUST return the ID even if it wasn't modified.

        Example:

        >>> class IntID(Manager):
        ...     def validate_id(self, id_):
        ...         "The id must be an int"
        ...         try:
        ...             return int(id_)
        ...         except ValueError:
        ...             raise ValidationError

        >>> class MinLength(Manager):
        ...     def validate_id(self,id_):
        ...         "The id must be a string containing at least 3 characters"
        ...         if len(id_) < 3:
        ...             raise ValidationError
        ...         #always return the id
        ...         return id_

        By default, this method checks if the id is not an empty string.
        """
        if id_ == '':
            raise ValidationError('A non empty ID is expected')
        return id_
Exemplo n.º 6
0
 def validate_resource_hostnames(self, hostname):
     """
     Check that the hostname are a list of strings
     """
     if not all(isinstance(x, unicode) for x in hostname):
         raise ValidationError('hostname must be a list of strings')
     return hostname
Exemplo n.º 7
0
 def validate_resource_ip(self, proposed_ip):
     """
     Check if an IP submitted by the user in his request is valid
     """
     ip_components = proposed_ip.split('.')
     if len(ip_components) != 4:
         # 123.45.67 is not an ip
         raise ValidationError('Not an ip 1')
     try:
         ip_components = map(int, ip_components)
     except ValueError:
         # 123.45.lol.99 is not an ip
         raise ValidationError('Not an ip 2')
     if not all([0 <= x <= 255 for x in ip_components]):
         # 123.45.67.890 is not an ip
         raise ValidationError('Not an ip 3')
     # filter the useless 0 out of 123.045.012.001
     return '.'.join(map(str, ip_components))
Exemplo n.º 8
0
    def test_map_bad(self):
        self.v1.side_effect = ValidationError('OH SNAP :(')

        try:
            self.validate([1, 2, 3])
        except ValidationError as ve:
            self.assertEqual(
                dict(ve), {
                    0: ValidationError('OH SNAP :('),
                    1: ValidationError('OH SNAP :('),
                    2: ValidationError('OH SNAP :('),
                })
        except Exception as e:
            self.fail('Unexpected %s', e)
        else:
            self.fail('ValidationError not raised')

        self.assertEqual(self.v2.call_count, 0)
Exemplo n.º 9
0
    def validate(self, input, original=None):
        """
        Validate the **input**.
        *original* is the actual value.

        Field are ignored and removed from *input* if

        * The property :attr:`ResourceField.computed` is set.
        * The property :attr:`ResourceField.editable` is not set and **original** is not None.

        A :exc:`napixd.exceptions.ValidationError` is raised when

        * A field is missing and is :attr:`ResourceField.required`.
        * A field does not satisfies :meth:`ResourceField.validate`.

        """
        for_edit = original is not None
        output = {}
        errors = []
        for resource_field in self:
            key = resource_field.name
            if (resource_field.computed
                    or for_edit and not resource_field.editable):
                if for_edit:
                    output[key] = original.get(key)
                continue
            elif key not in input:
                if resource_field.default_on_null:
                    value = None
                elif not resource_field.required:
                    continue
                else:
                    raise ValidationError({key: u'Required'})
            else:
                value = input[key]

            try:
                output[key] = resource_field.validate(self.manager, value)
            except ValidationError as ve:
                errors.append(ve)
        if errors:
            raise ValidationError(errors)
        return output
Exemplo n.º 10
0
def ISO8601_datetime(iso_string):
    """
    Parses a datetime and returns a :class:`datetime.datetime` object.

    Invalid datetimes raise a :exc:`napixd.exceptions.ValidationError`.
    """
    try:
        return datetime.datetime.strptime(iso_string, '%Y-%m-%dT%H:%M:%S')
    except ValueError:
        raise ValidationError('Bad datetime format, Use ISO 8601 standard: yyyy-mm-ddThh:mm:ss')
Exemplo n.º 11
0
    def _run_callback(self, callback, value):
        try:
            result = callback(value)
        except ValidationError as e:
            raise ValidationError({self.name: unicode(e)})

        if result is None:
            raise ValueError('Validator {0} returned None'.format(
                callback.__name__))
        return result
Exemplo n.º 12
0
    def __call__(self, value_list):
        errors = {}
        for i, value in enumerate(value_list):
            try:
                for validator in self.validators:
                    value = validator(value)
            except ValidationError as ve:
                errors[i] = ve

            value_list[i] = value

        if errors:
            raise ValidationError(errors)
        return value_list
Exemplo n.º 13
0
    def test_handle_put_validation_error(self):
        self.context.method = 'PUT'
        self.manager.validate.side_effect = ValidationError({
            'mpm': 'This is prefork or worker'
        })

        try:
            self.srr().handle()
        except HTTPError as err:
            self.assertEqual(err.status, 400)
            self.assertEqual(err.body, {
                'mpm': 'This is prefork or worker'
            })
        else:
            self.fail()
Exemplo n.º 14
0
    def check_choice(self, value):
        """
        Check that the value(s) fits the choices.

        If value is an iterable (except strings),
        it checks that **value** is a subset of :attr:`choices`
        else it checks that **value** is in :attr:`choices`.
        """
        choices = self.get_choices()
        if isinstance(value, basestring) or not hasattr(value, '__iter__'):
            value = [value]

        for v in value:
            if v not in choices:
                raise ValidationError({
                    self.name:
                    u'{0} is not one of the available choices'.format(v)
                })
Exemplo n.º 15
0
    def test_map_some(self):
        def v2(x):
            if x & 1:
                return 2 * x
            raise ValidationError('OH SNAP :(')

        self.v1.side_effect = lambda x: x
        self.v2.side_effect = v2

        try:
            self.validate([1, 2, 3])
        except ValidationError as ve:
            self.assertEqual(dict(ve), {
                1: ValidationError('OH SNAP :('),
            })
        except Exception as e:
            self.fail('Unexpected {0}'.format(e))
        else:
            self.fail('ValidationError not raised')
Exemplo n.º 16
0
    def validate(self, manager, value):
        """
        Validate the input **value**.
        """
        manager_validator = getattr(manager,
                                    'validate_resource_{0}'.format(self.name),
                                    None)

        if value is None and self.default_on_null:
            if not callable(manager_validator):
                raise ImproperlyConfigured(
                    'manager must implement a `validate_resource_{0}` to validate default_no_null'
                    .format(self.name))
            return manager_validator(None)

        if not self.check_type(value):
            raise ValidationError({
                self.name:
                u'Bad type: {0} has type {2} but should be {1}'.format(
                    self.name, self.type.__name__,
                    type(value).__name__)
            })

        if not self._dynamic_typing and self.type in (int, long, float):
            value = self.type(value)

        if self.choices is not None:
            self.check_choice(value)

        for validator in self.validators:
            value = self._run_callback(validator, value)

        if manager_validator:
            value = self._run_callback(manager_validator, value)

        return value
Exemplo n.º 17
0
 def validate_id(self, id):
     if id != 'world':
         raise ValidationError('id is world')
     return id
Exemplo n.º 18
0
def validate_id(value):
    if value.isdigit():
        return int(value)
    raise ValidationError()
Exemplo n.º 19
0
 def __call__(self, value):
     value = super(MatchRegexp, self).__call__(value)
     if not self.regex.match(value):
         raise ValidationError(
             self.error.format(value=value, regex=self.regex))
     return value
Exemplo n.º 20
0
 def validate_resource_uid(self, uid):
     try:
         uuid.UUID(uid)
     except ValueError:
         raise ValidationError('uid is not an UUID')
     return uid
Exemplo n.º 21
0
 def validate_resource_managers(self, managers):
     if (not isinstance(managers, list)
             or not all(isinstance(x, basestring) for x in managers)):
         raise ValidationError('managers should be a list of strings')
     return managers
Exemplo n.º 22
0
 def v2(x):
     if x & 1:
         return 2 * x
     raise ValidationError('OH SNAP :(')
Exemplo n.º 23
0
 def validate_resource_username(self, username):
     #avoid injections
     if '\n' in username or ':' in username:
         raise ValidationError(r'Username cannot contain `\n` nor `:`')
     #always return the valid value
     return username
Exemplo n.º 24
0
 def validate_resource(self, resource_dict):
     if resource_dict['username'] in resource_dict['password']:
         raise ValidationError('Password must not contain the username')
     return resource_dict
Exemplo n.º 25
0
def not_empty(values):
    """The list must not be empty"""
    if len(values) == 0:
        raise ValidationError('This list cannot be empty')
    return values
Exemplo n.º 26
0
 def validate_id(self, id_):
     if '/' in id_:
         raise ValidationError('ID do not contain a /')
     return id_
Exemplo n.º 27
0
 def validate_resource_authname(self, message):
     if not isinstance(message, basestring):
         raise ValidationError('message should be a string')
     return message.replace('\n', ' ')