def _validate_version(self, key, version): if self.min_version and self.min_version > version: msg = _('%(key)s (min_version=%(min)s) is not supported by ' 'spec version %(version)s.') % { 'key': key, 'min': self.min_version, 'version': version } raise exc.ESchema(message=msg) if self.max_version: if version > self.max_version: msg = _('%(key)s (max_version=%(max)s) is not supported ' 'by spec version %(version)s.') % { 'version': version, 'max': self.max_version, 'key': key } raise exc.ESchema(message=msg) else: LOG.warning( 'Warning: %(key)s will be deprecated after ' 'version %(version)s!', { 'key': key, 'version': self.max_version })
def resolve(self, value, context=None): if isinstance(value, str): try: value = jsonutils.loads(value) except (TypeError, ValueError): msg = _("'%s' is not a Map") % value raise exc.ESchema(message=msg) if not isinstance(value, collections.Mapping): msg = _("'%s' is not a Map") % value raise exc.ESchema(message=msg) return dict(self._get_children(value.items(), context))
def resolve_value(self, key): if key not in self: raise exc.ESchema(message="Invalid spec item: %s" % key) schema_item = self._schema[key] if key in self._data: raw_value = self._data[key] return schema_item.resolve(raw_value) elif schema_item.has_default(): return schema_item.get_default() elif schema_item.required: msg = _("Required spec item '%s' not provided") % key raise exc.ESchema(message=msg)
def get_spec_version(spec): if not isinstance(spec, dict): msg = _('The provided spec is not a map.') raise exc.ESchema(message=msg) if 'type' not in spec: msg = _("The 'type' key is missing from the provided spec map.") raise exc.ESchema(message=msg) if 'version' not in spec: msg = _("The 'version' key is missing from the provided spec map.") raise exc.ESchema(message=msg) return spec['type'], str(spec['version'])
def __init__(self, description=None, default=None, required=False, schema=None, constraints=None, min_version=None, max_version=None): if schema is not None: if type(self) not in (List, Map, Operation): msg = _('Schema valid only for List or Map, not %s') % self[ self.TYPE] raise exc.ESchema(message=msg) if self[self.TYPE] == self.LIST: self.schema = AnyIndexDict(schema) else: self.schema = schema self.description = description self.default = default self.required = required self.constraints = constraints or [] self._len = None self.min_version = min_version self.max_version = max_version
def validate(self, value, context=None): if value is None: msg = _("The value '%s' is not a valid string.") % value raise exc.ESchema(message=msg) self.resolve(value) self.validate_constraints(value, schema=self, context=context)
def __init__(self, allowed_values): if (not isinstance(allowed_values, collections.Sequence) or isinstance(allowed_values, six.string_types)): msg = _('AllowedValues must be a list or a string') raise exc.ESchema(message=msg) self.allowed = tuple(allowed_values)
def validate(self): """Validate the schema.""" for (k, s) in self._schema.items(): try: # Validate through resolve self.resolve_value(k) # Validate schema for version if self._version: self._schema[k]._validate_version(k, self._version) except (TypeError, ValueError) as err: raise exc.ESchema(message=six.text_type(err)) for key in self._data: if key not in self._schema: msg = _("Unrecognizable spec item '%s'") % key raise exc.ESchema(message=msg)
def validate(self, value, context=None): if not isinstance(value, collections.Mapping): msg = _("'%s' is not a Map") % value raise exc.ESchema(message=msg) for key, child in self.schema.items(): item_value = value.get(key) child.validate(item_value, context)
def validate(self, value, context=None): # if not isinstance(value, collections.Mapping): if not isinstance(value, collections.Sequence): msg = _("'%s' is not a List") % value raise exc.ESchema(message=msg) for v in value: self.schema['*'].validate(v, context=context)
def validate(self, context, validate_props=False): super(HealthPolicy, self).validate(context, validate_props=validate_props) if len(self.recover_actions) > 1: message = _( "Only one '%s' is supported for now.") % self.RECOVERY_ACTIONS raise exc.ESchema(message=message)
def test_create_failed_validation(self, mock_creds, mock_validate): mock_creds.return_value = {} mock_validate.side_effect = exception.ESchema(message="Boom") ex = self.assertRaises(exception.InvalidSpec, pb.Profile.create, self.ctx, 'my_profile', self.spec) self.assertEqual("Failed in creating profile my_profile: " "Boom", six.text_type(ex))
def validate(self, data, version=None): for k in data: if k not in self.schema: msg = _("Unrecognizable parameter '%s'") % k raise exc.ESchema(message=msg) for (k, s) in self.schema.items(): try: if k in data: s.validate(data[k]) elif s.required: msg = _("Required parameter '%s' not provided") % k raise exc.ESchema(message=msg) if version: s._validate_version(k, version) except (TypeError, ValueError) as ex: raise exc.ESchema(message=str(ex))
def get_default(self): if self.default is None: return {} if not isinstance(self.default, collections.Mapping): msg = _("'%s' is not a Map") % self.default raise exc.ESchema(message=msg) return self.default
def to_schema_type(self, value): if isinstance(value, six.integer_types): return value try: num = int(value) except ValueError: msg = _("The value '%s' is not a valid Integer") % value raise exc.ESchema(message=msg) return num
def _validate_default(self, context): if self.default is None: return try: # NOTE: this is the subclass's version of 'validate' self.validate(self.default, context) except (ValueError, TypeError) as ex: msg = _('Invalid default %(default)s: %(exc)s') % dict( default=self.default, exc=ex) raise exc.ESchema(message=msg)
def to_schema_type(self, value): if isinstance(value, numbers.Number): return value try: return int(value) except ValueError: try: return float(value) except ValueError: msg = _("The value '%s' is not a valid number.") % value raise exc.ESchema(message=msg)
def test_profile_validate_failed(self): self._setup_fakes() mock_do_validate = self.patchobject(fakes.TestProfile, 'do_validate') mock_do_validate.side_effect = exc.ESchema(message='BOOM') body = vorp.ProfileValidateRequestBody(spec=self.spec) request = vorp.ProfileValidateRequest(profile=body) ex = self.assertRaises(rpc.ExpectedException, self.svc.profile_validate, self.ctx, request.obj_to_primitive()) self.assertEqual(exc.InvalidSpec, ex.exc_info[0]) self.assertEqual('BOOM', six.text_type(ex.exc_info[1]))
def validate(self, validate_props=False): """Validate the schema and the data provided.""" # general validation self.spec_data.validate() self.properties.validate() ctx_dict = self.properties.get('context', {}) if ctx_dict: argspec = inspect.getargspec(context.RequestContext.__init__) valid_keys = argspec.args bad_keys = [k for k in ctx_dict if k not in valid_keys] if bad_keys: msg = _("Some keys in 'context' are invalid: %s") % bad_keys raise exc.ESchema(message=msg) if validate_props: self.do_validate(obj=self)
def validate(self, context, validate_props=False): super(HealthPolicy, self).validate(context, validate_props=validate_props) if len(self.recover_actions) > 1: message = _( "Only one '%s' is supported for now.") % self.RECOVERY_ACTIONS raise exc.ESchema(message=message) if self.interval < cfg.CONF.health_check_interval_min: message = _("Specified interval of %(interval)d seconds has to be " "larger than health_check_interval_min of " "%(min_interval)d seconds set in configuration.") % { "interval": self.interval, "min_interval": cfg.CONF.health_check_interval_min } raise exc.InvalidSpec(message=message)
def test_cluster_op_bad_parameters(self, mock_find, mock_cluster): x_db_cluster = mock.Mock(id='12345678AB') mock_find.return_value = x_db_cluster x_schema = mock.Mock() x_schema.validate.side_effect = exc.ESchema(message='Boom') x_profile = mock.Mock(OPERATIONS={'dance': x_schema}) x_cluster = mock.Mock() x_cluster.rt = {'profile': x_profile} mock_cluster.return_value = x_cluster req = orco.ClusterOperationRequest(identity='node1', operation='dance', params={'style': 'tango'}) ex = self.assertRaises(rpc.ExpectedException, self.eng.cluster_op, self.ctx, req.obj_to_primitive()) self.assertEqual(exc.BadRequest, ex.exc_info[0]) self.assertEqual("Boom.", six.text_type(ex.exc_info[1])) mock_find.assert_called_once_with(self.ctx, 'node1') mock_cluster.assert_called_once_with(self.ctx, db_cluster=x_db_cluster) x_schema.validate.assert_called_once_with({'style': 'tango'})
def validate(self, context, validate_props=False): super(HealthPolicy, self).validate(context, validate_props=validate_props) if len(self.recover_actions) > 1: message = _( "Only one '%s' is supported for now.") % self.RECOVERY_ACTIONS raise exc.ESchema(message=message) if self.interval < cfg.CONF.health_check_interval_min: message = _("Specified interval of %(interval)d seconds has to be " "larger than health_check_interval_min of " "%(min_interval)d seconds set in configuration.") % { "interval": self.interval, "min_interval": cfg.CONF.health_check_interval_min } raise exc.InvalidSpec(message=message) # check valid detection types polling_types = [ consts.NODE_STATUS_POLLING, consts.NODE_STATUS_POLL_URL ] has_valid_polling_types = all(d.type in polling_types for d in self.detection_modes) has_valid_lifecycle_type = (len(self.detection_modes) == 1 and self.detection_modes[0].type == consts.LIFECYCLE_EVENTS) if not has_valid_polling_types and not has_valid_lifecycle_type: message = ("Invalid detection modes in health policy: %s" % ', '.join([d.type for d in self.detection_modes])) raise exc.InvalidSpec(message=message) if len(self.detection_modes) != len(set(self.detection_modes)): message = ("Duplicate detection modes are not allowed in " "health policy: %s" % ', '.join([d.type for d in self.detection_modes])) raise exc.InvalidSpec(message=message)
def validate_constraints(self, value, schema=None, context=None): try: for constraint in self.constraints: constraint.validate(value, schema=schema, context=context) except ValueError as ex: raise exc.ESchema(message=str(ex))
def to_schema_type(self, value): try: return strutils.bool_from_string(str(value), strict=True) except ValueError: msg = _("The value '%s' is not a valid Boolean") % value raise exc.ESchema(message=msg)