How to use the voluptuous.error.Invalid function in voluptuous

To help you get started, we’ve selected a few voluptuous examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github alecthomas / voluptuous / voluptuous / error.py View on Github external
"""The literal values do not match."""


class LengthInvalid(Invalid):
    pass


class DatetimeInvalid(Invalid):
    """The value is not a formatted datetime string."""


class DateInvalid(Invalid):
    """The value is not a formatted date string."""


class InInvalid(Invalid):
    pass


class NotInInvalid(Invalid):
    pass


class ExactSequenceInvalid(Invalid):
    pass
github lxdock / lxdock / lxdock / conf / config.py View on Github external
# Loads the YML.
        config.load()

        # Validates the content of the configuration. We chdir into the home directory of the
        # project in order to ensure that IsFile/IsDir validators keep working properly if the
        # config is initialized from a subfolder of the project.
        cwd = os.getcwd()
        os.chdir(config.homedir)

        # Performs variable substitution / interpolation in the configuration values.
        config.interpolate()

        try:
            config._dict = schema(config._dict)
        except Invalid as e:
            # Formats the voluptuous error
            path = ' @ %s' % '.'.join(map(str, e.path)) if e.path else ''
            msg = 'The LXDock file is invalid because: {0}'.format(e.msg + path)
            raise ConfigFileValidationError(msg)
        finally:
            os.chdir(cwd)

        config.extract_config_from_dict()

        return config
github alecthomas / voluptuous / voluptuous / validators.py View on Github external
def _get_precision_scale(self, number):
        """
        :param number:
        :return: tuple(precision, scale, decimal_number)
        """
        try:
            decimal_num = Decimal(number)
        except InvalidOperation:
            raise Invalid(self.msg or 'Value must be a number enclosed with string')

        return (len(decimal_num.as_tuple().digits), -(decimal_num.as_tuple().exponent), decimal_num)
github servo / mozjs / mozjs / third_party / python / voluptuous / voluptuous / schema_builder.py View on Github external
def validate_set(path, data):
            if not isinstance(data, type_):
                raise er.Invalid('expected a %s' % type_name, path)

            _compiled = [self._compile(s) for s in schema]
            errors = []
            for value in data:
                for validate in _compiled:
                    try:
                        validate(path, value)
                        break
                    except er.Invalid:
                        pass
                else:
                    invalid = er.Invalid('invalid value in %s' % type_name, path)
                    errors.append(invalid)

            if errors:
                raise er.MultipleInvalid(errors)
github alecthomas / voluptuous / voluptuous / validators.py View on Github external
def _exec(self, funcs, v, path=None):
        errors = []
        funcs = list(funcs)
        for func in funcs:
            try:
                if path is None:
                    v = func(v)
                else:
                    v = func(path, v)
            except Invalid as e:
                errors.append(e)

        passed_count = len(funcs) - len(errors)
        if self.min_valid <= passed_count <= self.max_valid:
            return v

        msg = self.msg
        if not msg:
            msg = ', '.join(map(str, errors))

        if passed_count > self.max_valid:
            raise TooManyValid(msg)
        raise NotEnoughValid(msg)
github alecthomas / voluptuous / voluptuous / error.py View on Github external
"""More than one value found in exclusion group."""


class InclusiveInvalid(Invalid):
    """Not all values found in inclusion group."""


class SequenceTypeInvalid(Invalid):
    """The type found is not a sequence type."""


class TypeInvalid(Invalid):
    """The value was not of required type."""


class ValueInvalid(Invalid):
    """The value was found invalid by evaluation function."""


class ScalarInvalid(Invalid):
    """Scalars did not match."""


class CoerceInvalid(Invalid):
    """Impossible to coerce value to type."""


class AnyInvalid(Invalid):
    """The value did not pass any validator."""


class AllInvalid(Invalid):
github servo / mozjs / mozjs / third_party / python / voluptuous / voluptuous / schema_builder.py View on Github external
required_keys.discard(skey)
                        break

                    # Key and value okay, mark as found in case it was
                    # a Required() field.
                    required_keys.discard(skey)

                    break
                else:
                    if remove_key:
                        # remove key
                        continue
                    elif self.extra == ALLOW_EXTRA:
                        out[key] = value
                    elif self.extra != REMOVE_EXTRA:
                        errors.append(er.Invalid('extra keys not allowed', key_path))
                        # else REMOVE_EXTRA: ignore the key so it's removed from output

            # for any required keys left that weren't found and don't have defaults:
            for key in required_keys:
                msg = key.msg if hasattr(key, 'msg') and key.msg else 'required key not provided'
                errors.append(er.RequiredFieldInvalid(msg, path + [key]))
            if errors:
                raise er.MultipleInvalid(errors)

            return out
github alecthomas / voluptuous / voluptuous / error.py View on Github external
"""Scalars did not match."""


class CoerceInvalid(Invalid):
    """Impossible to coerce value to type."""


class AnyInvalid(Invalid):
    """The value did not pass any validator."""


class AllInvalid(Invalid):
    """The value did not pass all validators."""


class MatchInvalid(Invalid):
    """The value does not match the given regular expression."""


class RangeInvalid(Invalid):
    """The value is not in given range."""


class TrueInvalid(Invalid):
    """The value is not True."""


class FalseInvalid(Invalid):
    """The value is not False."""


class BooleanInvalid(Invalid):
github servo / mozjs / mozjs / third_party / python / voluptuous / voluptuous / schema_builder.py View on Github external
The message can be overridden on a per validator basis:

        >>> validate = Schema(isint('bad'))
        >>> with raises(er.MultipleInvalid, 'bad'):
        ...   validate('a')

    The class thrown too:

        >>> class IntegerInvalid(er.Invalid): pass
        >>> validate = Schema(isint('bad', clsoverride=IntegerInvalid))
        >>> try:
        ...  validate('a')
        ... except er.MultipleInvalid as e:
        ...   assert isinstance(e.errors[0], IntegerInvalid)
    """
    if cls and not issubclass(cls, er.Invalid):
        raise er.SchemaError("message can only use subclases of Invalid as custom class")

    def decorator(f):
        @wraps(f)
        def check(msg=None, clsoverride=None):
            @wraps(f)
            def wrapper(*args, **kwargs):
                try:
                    return f(*args, **kwargs)
                except ValueError:
                    raise (clsoverride or cls or er.ValueInvalid)(msg or default or 'invalid value')

            return wrapper

        return check
github home-assistant / home-assistant / homeassistant / components / bom / sensor.py View on Github external
def validate_station(station):
    """Check that the station ID is well-formed."""
    if station is None:
        return
    station = station.replace(".shtml", "")
    if not re.fullmatch(r"ID[A-Z]\d\d\d\d\d\.\d\d\d\d\d", station):
        raise vol.error.Invalid("Malformed station ID")
    return station