Python voluptuous.MultipleInvalid() Examples

The following are 30 code examples of voluptuous.MultipleInvalid(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module voluptuous , or try the search function .
Example #1
Source File: policy.py    From nmeta with Apache License 2.0 6 votes vote down vote up
def validate(logger, data, schema, where):
    """
    Generic validation of a data structure against schema
    using Voluptuous data validation library
    Parameters:
     - logger: valid logger reference
     - data: structure to validate
     - schema: a valid Voluptuous schema
     - where: string for debugging purposes to identity the policy location
    """
    logger.debug("validating data=%s", data)
    try:
        #*** Check correctness of data against schema with Voluptuous:
        schema(data)
    except MultipleInvalid as exc:
        #*** There was a problem with the data:
        logger.critical("Voluptuous detected a problem where=%s, exception=%s",
                                                                    where, exc)
        sys.exit("Exiting nmeta. Please fix error in main_policy.yaml")
    return 1 
Example #2
Source File: step.py    From takeoff with GNU General Public License v3.0 6 votes vote down vote up
def validate(self, config: dict) -> dict:
        """Validates a given voluptuous schema

        Args:
            config: Takeoff configuration

        Returns:
            The validated schema

        Raises:
            MultipleInvalid
            Invalid
        """
        try:
            return self.schema()(config)
        except (vol.MultipleInvalid, vol.Invalid) as e:
            logger.error(e)
            logger.error(pprint.pformat(config))
            raise e 
Example #3
Source File: test_schemas.py    From pkictl with Mozilla Public License 2.0 6 votes vote down vote up
def test_root_schema_invalid(self):

        test_data = {
            'kind': 'RootCA',
            'metadata': {
                'name': 'test-root-ca',
                'description': 'Test Root CA'
            },
            'spec': {
                'key_type': 'rsa',
                'key_bits': 4096,
            }
        }

        with self.assertRaises(voluptuous.MultipleInvalid):
            self.assertIsInstance(schemas.RootCASchema(test_data), dict) 
Example #4
Source File: test_schemas.py    From pkictl with Mozilla Public License 2.0 6 votes vote down vote up
def test_intermediate_schema_invalid(self):

        test_data = {
            'kind': 'IntermediateCA',
            'metadata': {
                'name': 'test-intermediate-ca',
                'description': 'Test Intermediate CA',
                'issuer': 'test-root-ca'
            },
            'spec': {
                'type': 'internal',
                'key_type': 'ec',
                'key_bits': 8192
            }
        }

        with self.assertRaises(voluptuous.MultipleInvalid):
            self.assertIsInstance(schemas.IntermediateCASchema(test_data), dict) 
Example #5
Source File: common.py    From picoCTF with MIT License 6 votes vote down vote up
def validate(schema, data):
    """
    Wrap the call to voluptuous schema to raise the proper exception.

    Args:
        schema: The voluptuous Schema object
        data: The validation data for the schema object

    Raises:
        PicoException with 400 status code and the voluptuous error message

    """
    try:
        schema(data)
    except MultipleInvalid as error:
        raise PicoException(error.msg, 400) 
Example #6
Source File: validators.py    From spid-testenv2 with GNU Affero General Public License v3.0 6 votes vote down vote up
def _check_certificate(cert):
    _errors = []
    cert = load_certificate(cert)
    is_expired = verify_certificate_expiration(cert)
    has_supported_alg = verify_certificate_algorithm(cert)
    no_sha1 = verify_bad_certificate_algorithm(cert)
    if is_expired:
        _errors.append(
            Invalid('Il certificato รจ scaduto.')
        )
    if not has_supported_alg:
        _errors.append(
            Invalid('Il certificato deve essere firmato con un algoritmo valido.')
        )
    if not no_sha1:
        _errors.append(
            Invalid('Il certificato non deve essere firmato tramite algoritmo SHA1 (deprecato).')
        )
    if _errors:
        raise MultipleInvalid(errors=_errors)
    return cert 
Example #7
Source File: info.py    From cloudkitty with Apache License 2.0 6 votes vote down vote up
def get_all_metrics():
    try:
        metrics_conf = collector.validate_conf(
            ck_utils.load_conf(CONF.collect.metrics_conf))
    except (voluptuous.Invalid, voluptuous.MultipleInvalid):
        msg = 'Invalid endpoint: no metrics in current configuration.'
        pecan.abort(405, msg)

    policy.authorize(pecan.request.context, 'info:list_metrics_info', {})
    metrics_info_list = []
    for metric_name, metric in metrics_conf.items():
        info = metric.copy()
        info['metric_id'] = info['alt_name']
        metrics_info_list.append(
            info_models.CloudkittyMetricInfo(**info))
    return info_models.CloudkittyMetricInfoCollection(
        metrics=metrics_info_list) 
Example #8
Source File: cleanup.py    From foreman-yml with GNU General Public License v3.0 6 votes vote down vote up
def process_cleanup_ptable(self):
        log.log(log.LOG_INFO, "Processing Cleanup of Partition Tables")
        for ptable in self.get_config_section('cleanup-partition-table'):
            try:
                self.validator.cleanup_ptable(ptable)
            except MultipleInvalid as e:
                log.log(log.LOG_WARN, "Cannot delete Partition Table '{0}': YAML validation Error: {1}".format(ptable['name'], e))
                continue

            try:
                self.fm.ptables.show(ptable['name'])['id']
                log.log(log.LOG_INFO, "Delete Partition Table '{0}'".format(ptable['name']))

                self.fm.ptables.destroy( ptable['name'] )
            except:
                log.log(log.LOG_WARN, "Partition Table '{0}' already absent.".format(ptable['name'])) 
Example #9
Source File: cleanup.py    From foreman-yml with GNU General Public License v3.0 6 votes vote down vote up
def process_cleanup_medium(self):
        log.log(log.LOG_INFO, "Processing Cleanup of Media")
        medialist = self.fm.media.index(per_page=99999)['results']
        for medium in self.get_config_section('cleanup-medium'):
            try:
                self.validator.cleanup_medium(medium)
            except MultipleInvalid as e:
                log.log(log.LOG_WARN, "Cannot delete Medium '{0}': YAML validation Error: {1}".format(medium['name'], e))
                continue

            medium_deleted = False
            # fm.media.show(name) does not work, we need to iterate over fm.media.index()
            for mediac in medialist:
                if (mediac['name'] == medium['name']):
                    medium_deleted = True
                    log.log(log.LOG_INFO, "Delete Medium '{0}'".format(medium['name']))

                    self.fm.media.destroy( medium['name'] )
                    continue
            if not medium_deleted:
                log.log(log.LOG_WARN, "Medium '{0}' already absent.".format(medium['name'])) 
Example #10
Source File: cleanup.py    From foreman-yml with GNU General Public License v3.0 6 votes vote down vote up
def process_cleanup_computeprfl(self):
        log.log(log.LOG_INFO, "Processing Cleanup of Compute profiles")
        for computeprfl in self.get_config_section('cleanup-compute-profile'):
            try:
                self.validator.cleanup_computeprfl(computeprfl)
            except MultipleInvalid as e:
                log.log(log.LOG_WARN, "Cannot delete Compute profile '{0}': YAML validation Error: {1}".format(computeprfl['name'], e))
                continue

            try:
                self.fm.compute_profiles.show(computeprfl['name'])['id']
                log.log(log.LOG_INFO, "Delete Compute profile '{0}'".format(computeprfl['name']))

                self.fm.compute_profiles.destroy( computeprfl['name'] )
            except:
                log.log(log.LOG_WARN, "Compute profile '{0}' already absent.".format(computeprfl['name'])) 
Example #11
Source File: importer.py    From foreman-yml with GNU General Public License v3.0 6 votes vote down vote up
def process_auth_sources_ldap(self):
        log.log(log.LOG_INFO, "Processing LDAP auth sources")
        for auth in self.get_config_section('auth-source-ldap'):
            # validate yaml
            try:
                self.validator.auth_source_ldaps(auth)
            except MultipleInvalid as e:
                log.log(log.LOG_WARN, "Cannot create LDAP source '{0}': YAML validation Error: {1}".format(auth['name'], e))
                continue
            try:
                as_id   = self.fm.auth_source_ldaps.show(auth['name'])['id']
                log.log(log.LOG_WARN, "LDAP source {0} allready exists".format(auth['name']))
                continue
            except TypeError:
                pass
            ldap_auth_obj = self.dict_underscore(auth)
            try:
                self.fm.auth_source_ldaps.create( auth_source_ldap=ldap_auth_obj )
            except:
                log.log(log.LOG_ERROR, "Something went wrong creating LDAP source {0}".format(auth['name'])) 
Example #12
Source File: __init__.py    From LedFx with MIT License 6 votes vote down vote up
def create_from_config(self, config):
        for device in config:
            _LOGGER.info("Loading device from config: {}".format(device))
            self._ledfx.devices.create(
                id = device['id'],
                type = device['type'],
                config = device['config'],
                ledfx = self._ledfx)
            if 'effect' in device:
                try:
                    effect = self._ledfx.effects.create(
                        ledfx = self._ledfx,
                        type = device['effect']['type'],
                        config = device['effect']['config'])
                    self._ledfx.devices.get_device(device['id']).set_effect(effect)
                except vol.MultipleInvalid:
                    _LOGGER.warning('Effect schema changed. Not restoring effect') 
Example #13
Source File: importer.py    From foreman-yml with GNU General Public License v3.0 6 votes vote down vote up
def process_config_ptable(self):
        log.log(log.LOG_INFO, "Processing Partition Tables")
        for ptable in self.get_config_section('partition-table'):
            try:
                self.validator.ptable(ptable)
            except MultipleInvalid as e:
                log.log(log.LOG_WARN, "Cannot create Partition Table '{0}': YAML validation Error: {1}".format(ptable['name'], e))
                continue
            try:
                ptable_id = self.fm.ptables.show(ptable['name'])['id']
                log.log(log.LOG_DEBUG, "Partition Table '{0}' (id={1}) already present.".format(ptable['name'], ptable_id))
            except:
                log.log(log.LOG_INFO, "Create Partition Table '{0}'".format(ptable['name']))
                ptable_tpl = {
                    'name':             ptable['name'],
                    'layout':           ptable['layout'],
                    'snippet':          ptable['snippet'],
                    'audit_comment':    ptable['audit-comment'],
                    'locked':           ptable['locked'],
                    'os_family':        ptable['os-family']
                }
                self.fm.ptables.create( ptable = ptable_tpl ) 
Example #14
Source File: importer.py    From foreman-yml with GNU General Public License v3.0 6 votes vote down vote up
def process_config_medium(self):
        log.log(log.LOG_INFO, "Processing Media")
        medialist = self.fm.media.index(per_page=99999)['results']
        for medium in self.get_config_section('medium'):
            try:
                self.validator.medium(medium)
            except MultipleInvalid as e:
                log.log(log.LOG_WARN, "Cannot create Media '{0}': YAML validation Error: {1}".format(medium['name'], e))
                continue

            medium_id = False
            # fm.media.show(name) does not work, we need to iterate over fm.media.index()
            for mediac in medialist:
                if (mediac['name'] == medium['name']):
                    medium_id = mediac['id']
                    log.log(log.LOG_DEBUG, "Medium '{0}' (id={1}) already present.".format(medium['name'], medium_id))
            if not medium_id:
                log.log(log.LOG_INFO, "Create Medium '{0}'".format(medium['name']))
                medium_tpl = {
                    'name':        medium['name'],
                    'path':        medium['path'],
                    'os_family':   medium['os-family']
                }
                self.fm.media.create( medium = medium_tpl ) 
Example #15
Source File: importer.py    From foreman-yml with GNU General Public License v3.0 6 votes vote down vote up
def process_config_model(self):
        log.log(log.LOG_INFO, "Processing Models")
        for model in self.get_config_section('model'):
            try:
                self.validator.model(model)
            except MultipleInvalid as e:
                log.log(log.LOG_WARN, "Cannot create Model '{0}': YAML validation Error: {1}".format(model['name'], e))
                continue
            try:
                model_id = self.fm.models.show(model['name'])['id']
                log.log(log.LOG_DEBUG, "Model '{0}' (id={1}) already present.".format(model['name'], model_id))
            except:
                log.log(log.LOG_INFO, "Create Model '{0}'".format(model['name']))
                model_tpl = {
                    'name':             model['name'],
                    'info':             model['info'],
                    'vendor_class':     model['vendor-class'],
                    'hardware_model':   model['hardware-model']
                }
                self.fm.models.create( model = model_tpl ) 
Example #16
Source File: importer.py    From foreman-yml with GNU General Public License v3.0 6 votes vote down vote up
def process_config_enviroment(self):
        log.log(log.LOG_INFO, "Processing Environments")
        envlist = self.fm.environments.index(per_page=99999)['results']
        for env in self.get_config_section('environment'):
            try:
                self.validator.enviroment(env)
            except MultipleInvalid as e:
                log.log(log.LOG_WARN, "Cannot create Environment '{0}': YAML validation Error: {1}".format(env['name'], e))
                continue

            env_id = False
            # fm.media.show(name) does not work, we need to iterate over fm.media.index()
            for envc in envlist:
                if (env['name'] == envc['name']):
                    env_id = envc['id']
                    log.log(log.LOG_DEBUG, "Environment '{0}' (id={1}) already present.".format(env['name'], env_id))
                    continue
            if not env_id:
                log.log(log.LOG_INFO, "Create Environment '{0}'".format(env['name']))
                self.fm.environments.create( environment = { 'name': env['name'] } ) 
Example #17
Source File: test_deploy_to_databricks.py    From takeoff with GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_config_empty_jobs(self, _):
        config = {**takeoff_config(), **BASE_CONF, "jobs": []}
        with pytest.raises(vol.MultipleInvalid):
            DeployToDatabricks(ApplicationVersion("DEV", "local", "foo"), config) 
Example #18
Source File: test_create_application_insights.py    From takeoff with GNU General Public License v3.0 5 votes vote down vote up
def test_validate_invalid_schema(self):
        INVALID_CONF = {
             'task': 'create_application_insights',
             'application_type': 'invalid',
             'kind': 'invalid'
        }
        conf = {**takeoff_config(), **INVALID_CONF}
        with pytest.raises(MultipleInvalid):
            CreateApplicationInsights(ApplicationVersion("dev", "v", "branch"), conf) 
Example #19
Source File: test_publish_artifact.py    From takeoff with GNU General Public License v3.0 5 votes vote down vote up
def test_validate_schema_invalid_target(self, _):
        conf = {**takeoff_config(), **BASE_CONF, "target": ["WRONG"]}

        with pytest.raises(vol.MultipleInvalid):
            victim(ApplicationVersion("dev", "v", "branch"), conf) 
Example #20
Source File: test_configure_eventhub.py    From takeoff with GNU General Public License v3.0 5 votes vote down vote up
def test_validate_minimal_schema_missing_key(self, _, __):
        conf = {**takeoff_config(), 'task': 'createEventHubConsumerGroups'}
        conf['azure'].update({"eventhub_naming": "eventhub{env}"})

        with pytest.raises(vol.MultipleInvalid):
            ConfigureEventHub(ApplicationVersion("dev", "v", "branch"), conf) 
Example #21
Source File: test_validation.py    From minfraud-api-python with Apache License 2.0 5 votes vote down vote up
def check_invalid_transaction(self, transaction):
        self.setup_transaction(transaction)
        with self.assertRaises(
            MultipleInvalid, msg="{0!s} is invalid".format(transaction)
        ):
            validate_transaction(transaction) 
Example #22
Source File: test_schemas.py    From pkictl with Mozilla Public License 2.0 5 votes vote down vote up
def test_kvengine_schema_invalid(self):

        test_data = {
            'kind': 'KV',
            'metadata': {
                'name': 'test-kv-engine',
                'description': 'Test KV engine'
            }
        }

        with self.assertRaises(voluptuous.MultipleInvalid):
            self.assertIsInstance(schemas.KeyValueSchema(test_data), dict) 
Example #23
Source File: info.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def get_one_metric(metric_name):
    try:
        metrics_conf = collector.validate_conf(
            ck_utils.load_conf(CONF.collect.metrics_conf))
    except (voluptuous.Invalid, voluptuous.MultipleInvalid):
        msg = 'Invalid endpoint: no metrics in current configuration.'
        pecan.abort(405, msg)

    policy.authorize(pecan.request.context, 'info:get_metric_info', {})
    metric = _find_metric(metric_name, metrics_conf)
    if not metric:
        pecan.abort(404, six.text_type(metric_name))
    info = metric.copy()
    info['metric_id'] = info['alt_name']
    return info_models.CloudkittyMetricInfo(**info) 
Example #24
Source File: event.py    From aodh with Apache License 2.0 5 votes vote down vote up
def validate_alarm(cls, alarm):
        super(AlarmEventRule, cls).validate_alarm(alarm)
        for i in alarm.event_rule.query:
            i.get_value()
            try:
                _q_validator({"field": i.field, "op": i.op,
                              "value": i.type})
            except voluptuous.MultipleInvalid as e:
                raise base.ClientSideError(
                    _("Query value or traits invalid: %s") % str(e)) 
Example #25
Source File: test_voluptuous.py    From pydantic with MIT License 5 votes vote down vote up
def validate(self, data):
        try:
            return True, self.schema(data)
        except v.MultipleInvalid as e:
            return False, humanize_error(data, e) 
Example #26
Source File: user_config.py    From stestr with Apache License 2.0 5 votes vote down vote up
def __init__(self, path):
        self.schema = vp.Schema({
            vp.Optional('run'): {
                vp.Optional('concurrency'): int,
                vp.Optional('random'): bool,
                vp.Optional('no-subunit-trace'): bool,
                vp.Optional('color'): bool,
                vp.Optional('abbreviate'): bool,
                vp.Optional('slowest'): bool,
                vp.Optional('suppress-attachments'): bool,
                vp.Optional('all-attachments'): bool,
            },
            vp.Optional('failing'): {
                vp.Optional('list'): bool,
            },
            vp.Optional('last'): {
                vp.Optional('no-subunit-trace'): bool,
                vp.Optional('color'): bool,
                vp.Optional('suppress-attachments'): bool,
                vp.Optional('all-attachments'): bool,
            },
            vp.Optional('load'): {
                vp.Optional('force-init'): bool,
                vp.Optional('subunit-trace'): bool,
                vp.Optional('color'): bool,
                vp.Optional('abbreviate'): bool,
                vp.Optional('suppress-attachments'): bool,
                vp.Optional('all-attachments'): bool,
            }
        })
        with open(path, 'r') as fd:
            self.config = yaml.safe_load(fd.read())
        if self.config is None:
            self.config = {}
        try:
            self.schema(self.config)
        except vp.MultipleInvalid as e:
            msg = ('Provided user config file {} is invalid '
                   'because:\n{}'.format(path, str(e)))
            sys.exit(msg) 
Example #27
Source File: test_validation.py    From minfraud-api-python with Apache License 2.0 5 votes vote down vote up
def test_missing_device(self):
        with self.assertRaises(MultipleInvalid):
            validate_transaction({}) 
Example #28
Source File: test_validation.py    From minfraud-api-python with Apache License 2.0 5 votes vote down vote up
def test_missing_ip(self):
        with self.assertRaises(MultipleInvalid):
            validate_transaction({"device": {}}) 
Example #29
Source File: test_validation.py    From minfraud-api-python with Apache License 2.0 5 votes vote down vote up
def check_invalid_report(self, report):
        self.setup_report(report)
        with self.assertRaises(MultipleInvalid, msg="{0!s} is invalid".format(report)):
            validate_report(report) 
Example #30
Source File: test_validation.py    From minfraud-api-python with Apache License 2.0 5 votes vote down vote up
def check_transaction(self, transaction):
        self.setup_transaction(transaction)
        try:
            validate_transaction(transaction)
        except MultipleInvalid as e:
            self.fail("MultipleInvalid {0} thrown for {1}".format(e.msg, transaction))