def _get_capability_property(self, node_template, capability_name, property_name): """Gets a node template capability property.""" caps = node_template.get_capabilities() if caps and capability_name in caps.keys(): cap = caps[capability_name] property = None props = cap.get_properties() if props and property_name in props.keys(): property = props[property_name].value if not property: raise KeyError(_( "Property '{0}' not found in capability '{1}' of node" " template '{2}' referenced from node template" " '{3}'.").format(property_name, capability_name, node_template.name, self.context.name)) return property msg = _("Requirement/Capability '{0}' referenced from '{1}' node " "template not found in '{2}' node template.").format( capability_name, self.context.name, node_template.name) raise KeyError(msg)
def validate(self): """Validate the value by the definition of the datatype.""" # A datatype can not have both 'type' and 'properties' definitions. # If the datatype has 'type' definition if self.datatype.value_type: self.value = DataEntity.validate_datatype(self.datatype.value_type, self.value, None, self.custom_def) schema = Schema(None, self.datatype.defs) for constraint in schema.constraints: constraint.validate(self.value) # If the datatype has 'properties' definition else: if not isinstance(self.value, dict): raise TypeMismatchError(what=self.value, type=self.datatype.type) allowed_props = [] required_props = [] default_props = {} if self.schema: allowed_props = self.schema.keys() for name, prop_def in self.schema.items(): if prop_def.required: required_props.append(name) if prop_def.default: default_props[name] = prop_def.default # check allowed field for value_key in list(self.value.keys()): if value_key not in allowed_props: raise UnknownFieldError(what=_("Data value of type %s") % self.datatype.type, field=value_key) # check default field for def_key, def_value in list(default_props.items()): if def_key not in list(self.value.keys()): self.value[def_key] = def_value # check missing field missingprop = [] for req_key in required_props: if req_key not in list(self.value.keys()): missingprop.append(req_key) if missingprop: raise MissingRequiredFieldError( what=_("Data value of type %s") % self.datatype.type, required=missingprop ) # check every field for name, value in list(self.value.items()): prop_schema = Schema(name, self._find_schema(name)) # check if field value meets type defined DataEntity.validate_datatype(prop_schema.type, value, prop_schema.entry_schema, self.custom_def) # check if field value meets constraints defined if prop_schema.constraints: for constraint in prop_schema.constraints: constraint.validate(value) return self.value
def validate_scalar_unit(self): regex = re.compile("([0-9.]+)\s*(\w+)") try: result = regex.match(str(self.value)).groups() validateutils.str_to_num(result[0]) except Exception: raise ValueError(_('"%s" is not a valid scalar-unit') % self.value) if result[1].upper() in self.SCALAR_UNIT_DICT.keys(): return self.value raise ValueError(_('"%s" is not a valid scalar-unit') % self.value)
def __init__(self, property_name, property_type, constraint): super(InRange, self).__init__(property_name, property_type, constraint) if not isinstance(self.constraint_value, collections.Sequence) or (len(constraint[self.IN_RANGE]) != 2): raise InvalidSchemaError(message=_("in_range must be a list.")) for value in self.constraint_value: if not isinstance(value, self.valid_types): raise InvalidSchemaError(_("in_range value must " "be comparable.")) self.min = self.constraint_value[0] self.max = self.constraint_value[1]
def __new__(cls, property_name, property_type, constraint): if cls is not Constraint: return super(Constraint, cls).__new__(cls) if not isinstance(constraint, collections.Mapping) or len(constraint) != 1: raise InvalidSchemaError(message=_("Invalid constraint schema.")) for type in constraint.keys(): ConstraintClass = get_constraint_class(type) if not ConstraintClass: msg = _('Invalid constraint type "%s".') % type raise InvalidSchemaError(message=msg) return ConstraintClass(property_name, property_type, constraint)
def __init__(self, name, schema_dict): self.name = name if not isinstance(schema_dict, collections.Mapping): msg = _("Schema %(pname)s must be a dict.") % dict(pname=name) raise InvalidSchemaError(message=msg) try: schema_dict["type"] except KeyError: msg = _("Schema %(pname)s must have type.") % dict(pname=name) raise InvalidSchemaError(message=msg) self.schema = schema_dict self._len = None self.constraints_list = []
def validate_integer(value): if not isinstance(value, int): try: value = int(value) except Exception: raise ValueError(_('"%s" is not an integer') % value) return value
def _err_msg(self, value): return _("%(pname)s: %(pvalue)s is out of range " "(min:%(vmin)s, max:%(vmax)s).") % dict( pname=self.property_name, pvalue=self.value_msg, vmin=self.constraint_value_msg[0], vmax=self.constraint_value_msg[1], )
def validate(self): if len(self.args) != 1: raise ValueError(_( 'Expected one argument for get_input function but received: ' '{0}.').format(self.args)) inputs = [input.name for input in self.tosca_tpl.inputs] if self.args[0] not in inputs: raise UnknownInputError(input_name=self.args[0])
def _find_node_template(self, node_template_name): if node_template_name == SELF: return self.context for node_template in self.tosca_tpl.nodetemplates: if node_template.name == node_template_name: return node_template raise KeyError(_( 'No such node template: {0}.').format(node_template_name))
def validate(self): if len(self.args) < 2 or len(self.args) > 3: raise ValueError(_( 'Expected arguments: [node-template-name, req-or-cap ' '(optional), property name.')) if len(self.args) == 2: prop = self._find_property(self.args[1]).value if not isinstance(prop, Function): get_function(self.tosca_tpl, self.context, prop) elif len(self.args) == 3: get_function(self.tosca_tpl, self.context, self._find_req_or_cap_property(self.args[1], self.args[2])) else: raise NotImplementedError(_( 'Nested properties are not supported.'))
def validate_boolean(value): if isinstance(value, bool): return value if isinstance(value, str): normalised = value.lower() if normalised in ['true', 'false']: return normalised == 'true' raise ValueError(_('"%s" is not a boolean') % value)
def _find_property(self, property_name): node_tpl = self._find_node_template(self.args[0]) props = node_tpl.get_properties() found = [props[property_name]] if property_name in props else [] if len(found) == 0: raise KeyError(_( "Property: '{0}' not found in node template: {1}.").format( property_name, node_tpl.name)) return found[0]
def __init__(self, **kwargs): try: self.message = self.msg_fmt % kwargs except KeyError: exc_info = sys.exc_info() log.exception(_('Exception in string format operation: %s') % exc_info[1]) if TOSCAException._FATAL_EXCEPTION_FORMAT_ERRORS: raise exc_info[0]
def __init__(self, property_name, property_type, constraint): self.property_name = property_name self.property_type = property_type self.constraint_value = constraint[self.constraint_key] self.constraint_value_msg = self.constraint_value if self.property_type in scalarunit.ScalarUnit.SCALAR_UNIT_TYPES: self.constraint_value = self._get_scalarunit_constraint_value() # check if constraint is valid for property type if property_type not in self.valid_prop_types: msg = _('Constraint type "%(ctype)s" is not valid ' 'for data type "%(dtype)s".') % dict( ctype=self.constraint_key, dtype=property_type ) raise InvalidSchemaError(message=msg)
def _find_node_template_containing_attribute(self): if self.node_template_name == HOST: # Currently this is the only way to tell whether the function # is used within the outputs section of the TOSCA template. if isinstance(self.context, list): raise ValueError(_( "get_attribute HOST keyword is not allowed within the " "outputs section of the TOSCA template")) node_tpl = self._find_host_containing_attribute() if not node_tpl: raise ValueError(_( "get_attribute HOST keyword is used in '{0}' node " "template but {1} was not found " "in relationship chain").format(self.context.name, HOSTED_ON)) else: node_tpl = self._find_node_template(self.args[0]) if not self._attribute_exists_in_type(node_tpl.type_definition): raise KeyError(_( "Attribute '{0}' not found in node template: {1}.").format( self.attribute_name, node_tpl.name)) return node_tpl
def get_num_from_scalar_unit(self, unit=None): if unit: if unit.upper() not in self.SCALAR_UNIT_DICT.keys(): raise ValueError(_('input unit "%s" is not a valid unit') % unit) else: unit = self.SCALAR_UNIT_DEFAULT self.validate_scalar_unit() regex = re.compile("([0-9.]+)\s*(\w+)") result = regex.match(str(self.value)).groups() converted = ( float(validateutils.str_to_num(result[0])) * self.SCALAR_UNIT_DICT[result[1].upper()] / self.SCALAR_UNIT_DICT[unit.upper()] ) if converted - int(converted) < 0.0000000000001: converted = int(converted) return converted
def __init__(self, property_name, property_type, constraint): super(ValidValues, self).__init__(property_name, property_type, constraint) if not isinstance(self.constraint_value, collections.Sequence): raise InvalidSchemaError(message=_("valid_values must be a list."))
def _err_msg(self, value): allowed = "[%s]" % ", ".join(str(a) for a in self.constraint_value) return _("%(pname)s: %(pvalue)s is not an valid " 'value "%(cvalue)s".') % dict( pname=self.property_name, pvalue=value, cvalue=allowed )
def _err_msg(self, value): return _("Property %s could not be validated.") % self.property_name
def _err_msg(self, value): return _("length of %(pname)s: %(pvalue)s must be " 'at least "%(cvalue)s".') % dict( pname=self.property_name, pvalue=value, cvalue=self.constraint_value )
def _err_msg(self, value): return _("%(pname)s: %(pvalue)s must be less or " 'equal to "%(cvalue)s".') % dict( pname=self.property_name, pvalue=self.value_msg, cvalue=self.constraint_value_msg )
def _err_msg(self, value): return _("length of %(pname)s: %(pvalue)s must be no greater " 'than "%(cvalue)s".') % dict( pname=self.property_name, pvalue=value, cvalue=self.constraint_value )
def _err_msg(self, value): return _('%(pname)s: "%(pvalue)s" does not match ' 'pattern "%(cvalue)s".') % dict( pname=self.property_name, pvalue=value, cvalue=self.constraint_value )
def __init__(self, property_name, property_type, constraint): super(MaxLength, self).__init__(property_name, property_type, constraint) if not isinstance(self.constraint_value, self.valid_types): raise InvalidSchemaError(message=_("max_length must be integer."))
def __init__(self, property_name, property_type, constraint): super(GreaterThan, self).__init__(property_name, property_type, constraint) if not isinstance(constraint[self.GREATER_THAN], self.valid_types): raise InvalidSchemaError(message=_("greater_than must " "be comparable."))
def __init__(self, property_name, property_type, constraint): super(Pattern, self).__init__(property_name, property_type, constraint) if not isinstance(self.constraint_value, self.valid_types): raise InvalidSchemaError(message=_("pattern must be string.")) self.match = re.compile(self.constraint_value).match
def _err_msg(self, value): return _('%(pname)s: %(pvalue)s must be greater than "%(cvalue)s".') % dict( pname=self.property_name, pvalue=self.value_msg, cvalue=self.constraint_value_msg )
def _err_msg(self, value): return _('%(pname)s: %(pvalue)s is not equal to "%(cvalue)s".') % dict( pname=self.property_name, pvalue=self.value_msg, cvalue=self.constraint_value_msg )
def __init__(self, property_name, property_type, constraint): super(LessOrEqual, self).__init__(property_name, property_type, constraint) if not isinstance(self.constraint_value, self.valid_types): raise InvalidSchemaError(message=_("less_or_equal must " "be comparable."))