def validate_items(self): from python_jsonschema_objects import classbuilder if self.__itemtype__ is None: return type_checks = self.__itemtype__ if not isinstance(type_checks, (tuple, list)): # we were given items = {'type': 'blah'} ; thus ensure the type for all data. type_checks = [type_checks] * len(self.data) elif len(type_checks) > len(self.data): raise ValidationError( "{1} does not have sufficient elements to validate against {0}" .format(self.__itemtype__, self.data)) typed_elems = [] for elem, typ in zip(self.data, type_checks): if isinstance(typ, dict): for param, paramval in six.iteritems(typ): validator = registry(param) if validator is not None: validator(paramval, elem, typ) elif util.safe_issubclass(typ, classbuilder.LiteralValue): val = typ(elem) val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, classbuilder.ProtocolBase): if not isinstance(elem, typ): try: if isinstance(elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError("'{0}' is not a valid value for '{1}': {2}" .format(elem, typ, e)) else: val = elem val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, ArrayValidator): val = typ(elem) val.validate() typed_elems.append(val) elif isinstance(typ, classbuilder.TypeProxy): try: if isinstance(elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError("'{0}' is not a valid value for '{1}': {2}" .format(elem, typ, e)) val.validate() typed_elems.append(val) return typed_elems
def __setattr__(self, name, val): if name.startswith("_"): object.__setattr__(self, name, val) elif name in self.__propinfo__: # If its in __propinfo__, then it actually has a property defined. # The property does special validation, so we actually need to # run its setter. We get it from the class definition and call # it directly. XXX Heinous. prop = self.__class__.__dict__[self.__prop_names__[name]] prop.fset(self, val) else: # This is an additional property of some kind typ = getattr(self, '__extensible__', None) if typ is False: raise validators.ValidationError( "Attempted to set unknown property '{0}', " "but 'additionalProperties' is false.".format(name)) if typ is True: # There is no type defined, so just make it a basic literal # Pick the type based on the type of the values valtype = [k for k, t in six.iteritems(self.__SCHEMA_TYPES__) if t is not None and isinstance(val, t)] valtype = valtype[0] val = MakeLiteral(name, valtype, val) elif isinstance(typ, type) and getattr(typ, 'isLiteralClass', None) is True: val = typ(val) elif isinstance(typ, type) and util.safe_issubclass(typ, ProtocolBase): val = typ(**util.coerce_for_expansion(val)) self._extended_properties[name] = val
def __setattr__(self, name, val): if name.startswith("_"): object.__setattr__(self, name, val) elif name in self.__propinfo__: # If its in __propinfo__, then it actually has a property defined. # The property does special validation, so we actually need to # run its setter. We get it from the class definition and call # it directly. XXX Heinous. prop = self.__class__.__dict__[self.__prop_names__[name]] prop.fset(self, val) else: # This is an additional property of some kind typ = getattr(self, '__extensible__', None) if typ is False: raise validators.ValidationError( "Attempted to set unknown property '{0}', " "but 'additionalProperties' is false.".format(name)) if typ is True: # There is no type defined, so just make it a basic literal # Pick the type based on the type of the values valtype = [ k for k, t in six.iteritems(self.__SCHEMA_TYPES__) if t is not None and isinstance(val, t) ] valtype = valtype[0] val = MakeLiteral(name, valtype, val) elif isinstance( typ, type) and getattr(typ, 'isLiteralClass', None) is True: val = typ(val) elif isinstance(typ, type) and util.safe_issubclass( typ, ProtocolBase): val = typ(**util.coerce_for_expansion(val)) self._extended_properties[name] = val
def _make_type(self, typ, val): import python_jsonschema_objects.classbuilder as cb if getattr(typ, 'isLiteralClass', None) is True: return typ(val) if util.safe_issubclass(typ, cb.ProtocolBase): return typ(**util.coerce_for_expansion(val)) if util.safe_issubclass(typ, validators.ArrayValidator): return typ(val) raise validators.ValidationError( "additionalProperty type {0} was neither a literal " "nor a schema wrapper: {1}".format(typ, val))
def _make_type(self, typ, val): import python_jsonschema_objects.classbuilder as cb if getattr( typ, 'isLiteralClass', None) is True: return typ(val) if util.safe_issubclass(typ, cb.ProtocolBase): return typ(**util.coerce_for_expansion(val)) if util.safe_issubclass(typ, validators.ArrayValidator): return typ(val) raise validators.ValidationError( "additionalProperty type {0} was neither a literal " "nor a schema wrapper: {1}".format(typ, val))
def setprop(self, val): if isinstance(info['type'], (list, tuple)): ok = False errors = [] type_checks = [] for typ in info['type']: if not isinstance(typ, dict): type_checks.append(typ) continue typ = ProtocolBase.__SCHEMA_TYPES__[typ['type']] if typ == None: typ = type(None) if isinstance(typ, (list, tuple)): type_checks.extend(typ) else: type_checks.append(typ) for typ in type_checks: if isinstance(val, typ): ok = True break elif hasattr(typ, 'isLiteralClass'): try: validator = typ(val) except Exception as e: errors.append( "Failed to coerce to '{0}': {1}".format(typ, e)) pass else: validator.validate() ok = True break elif util.safe_issubclass(typ, ProtocolBase): # force conversion- thus the val rather than validator assignment try: val = typ(**util.coerce_for_expansion(val)) except Exception as e: errors.append( "Failed to coerce to '{0}': {1}".format(typ, e)) pass else: val.validate() ok = True break if not ok: errstr = "\n".join(errors) raise validators.ValidationError( "Object must be one of {0}: \n{1}".format(info['type'], errstr)) elif info['type'] == 'array': instance = info['validator'](val) val = instance.validate() elif getattr(info['type'], 'isLiteralClass', False) is True: if not isinstance(val, info['type']): validator = info['type'](val) validator.validate() elif util.safe_issubclass(info['type'], ProtocolBase): if not isinstance(val, info['type']): val = info['type'](**util.coerce_for_expansion(val)) val.validate() else: raise TypeError("Unknown object type: '{0}'".format(info['type'])) self._properties[prop] = val
def setprop(self, val): if isinstance(info['type'], (list, tuple)): ok = False errors = [] type_checks = [] for typ in info['type']: if not isinstance(typ, dict): type_checks.append(typ) continue typ = ProtocolBase.__SCHEMA_TYPES__[typ['type']] if typ is None: typ = type(None) if isinstance(typ, (list, tuple)): type_checks.extend(typ) else: type_checks.append(typ) for typ in type_checks: if isinstance(val, typ): ok = True break elif hasattr(typ, 'isLiteralClass'): try: validator = typ(val) except Exception as e: errors.append("Failed to coerce to '{0}': {1}".format( typ, e)) pass else: validator.validate() ok = True break elif util.safe_issubclass(typ, ProtocolBase): # force conversion- thus the val rather than validator assignment try: val = typ(**util.coerce_for_expansion(val)) except Exception as e: errors.append("Failed to coerce to '{0}': {1}".format( typ, e)) pass else: val.validate() ok = True break elif util.safe_issubclass(typ, validators.ArrayValidator): try: val = typ(val) except Exception as e: errors.append("Failed to coerce to '{0}': {1}".format( typ, e)) pass else: val.validate() ok = True break if not ok: errstr = "\n".join(errors) raise validators.ValidationError( "Object must be one of {0}: \n{1}".format( info['type'], errstr)) elif info['type'] == 'array': instance = info['validator'](val) val = instance.validate() elif getattr(info['type'], 'isLiteralClass', False) is True: if not isinstance(val, info['type']): validator = info['type'](val) validator.validate() elif util.safe_issubclass(info['type'], ProtocolBase): if not isinstance(val, info['type']): val = info['type'](**util.coerce_for_expansion(val)) val.validate() elif isinstance(info['type'], TypeProxy): val = info['type'](val) elif info['type'] is None: # This is the null value if val is not None: raise validators.ValidationError( "None is only valid value for null") else: raise TypeError("Unknown object type: '{0}'".format(info['type'])) self._properties[prop] = val
def setprop(self, val): if isinstance(info['type'], (list, tuple)): ok = False errors = [] type_checks = [] for typ in info['type']: if not isinstance(typ, dict): type_checks.append(typ) continue typ = next(t for n, t in validators.SCHEMA_TYPE_MAPPING if typ['type'] == n) if typ is None: typ = type(None) if isinstance(typ, (list, tuple)): type_checks.extend(typ) else: type_checks.append(typ) for typ in type_checks: if isinstance(val, typ): ok = True break elif hasattr(typ, 'isLiteralClass'): try: validator = typ(val) except Exception as e: errors.append("Failed to coerce to '{0}': {1}".format( typ, e)) pass else: validator.validate() ok = True break elif util.safe_issubclass(typ, ProtocolBase): # force conversion- thus the val rather than validator assignment try: val = typ(**util.coerce_for_expansion(val)) except Exception as e: errors.append("Failed to coerce to '{0}': {1}".format( typ, e)) pass else: val.validate() ok = True break elif util.safe_issubclass( typ, python_jsonschema_objects.wrapper_types.ArrayWrapper): try: val = typ(val) except Exception as e: errors.append("Failed to coerce to '{0}': {1}".format( typ, e)) pass else: val.validate() ok = True break if not ok: errstr = "\n".join(errors) raise validators.ValidationError( "Object must be one of {0}: \n{1}".format( info['type'], errstr)) elif info['type'] == 'array': val = info['validator'](val) val.validate() elif util.safe_issubclass( info['type'], python_jsonschema_objects.wrapper_types.ArrayWrapper): # An array type may have already been converted into an ArrayValidator val = info['type'](val) val.validate() elif getattr(info['type'], 'isLiteralClass', False) is True: if not isinstance(val, info['type']): validator = info['type'](val) validator.validate() if validator._value is not None: # This allows setting of default Literal values val = validator elif util.safe_issubclass(info['type'], ProtocolBase): if not isinstance(val, info['type']): val = info['type'](**util.coerce_for_expansion(val)) val.validate() elif isinstance(info['type'], TypeProxy): val = info['type'](val) elif isinstance(info['type'], TypeRef): if not isinstance(val, info['type'].ref_class): val = info['type'](**val) val.validate() elif info['type'] is None: # This is the null value if val is not None: raise validators.ValidationError( "None is only valid value for null") else: raise TypeError("Unknown object type: '{0}'".format(info['type'])) self._properties[prop] = val
def validate_items(self): """ Validates the items in the backing array, including performing type validation. Sets the _typed property and clears the dirty flag as a side effect Returns: The typed array """ logger.debug(fmt("Validating {}", self)) from python_jsonschema_objects import classbuilder if self.__itemtype__ is None: return type_checks = self.__itemtype__ if not isinstance(type_checks, (tuple, list)): # we were given items = {'type': 'blah'} ; thus ensure the type for all data. type_checks = [type_checks] * len(self.data) elif len(type_checks) > len(self.data): raise ValidationError( "{1} does not have sufficient elements to validate against {0}" .format(self.__itemtype__, self.data)) typed_elems = [] for elem, typ in zip(self.data, type_checks): if isinstance(typ, dict): for param, paramval in six.iteritems(typ): validator = registry(param) if validator is not None: validator(paramval, elem, typ) typed_elems.append(elem) elif util.safe_issubclass(typ, classbuilder.LiteralValue): val = typ(elem) val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, classbuilder.ProtocolBase): if not isinstance(elem, typ): try: if isinstance( elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError( "'{0}' is not a valid value for '{1}': {2}".format( elem, typ, e)) else: val = elem val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, ArrayWrapper): val = typ(elem) val.validate() typed_elems.append(val) elif isinstance(typ, (classbuilder.TypeProxy, classbuilder.TypeRef)): try: if isinstance( elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError( "'{0}' is not a valid value for '{1}': {2}".format( elem, typ, e)) else: val.validate() typed_elems.append(val) self._dirty = False self._typed = typed_elems return typed_elems
def validate_items(self): """ Validates the items in the backing array, including performing type validation. Sets the _typed property and clears the dirty flag as a side effect Returns: The typed array """ logger.debug(fmt("Validating {}", self)) from python_jsonschema_objects import classbuilder if self.__itemtype__ is None: return type_checks = self.__itemtype__ if not isinstance(type_checks, (tuple, list)): # we were given items = {'type': 'blah'} ; thus ensure the type for all data. type_checks = [type_checks] * len(self.data) elif len(type_checks) > len(self.data): raise ValidationError( "{1} does not have sufficient elements to validate against {0}" .format(self.__itemtype__, self.data)) typed_elems = [] for elem, typ in zip(self.data, type_checks): if isinstance(typ, dict): for param, paramval in six.iteritems(typ): validator = registry(param) if validator is not None: validator(paramval, elem, typ) typed_elems.append(elem) elif util.safe_issubclass(typ, classbuilder.LiteralValue): val = typ(elem) val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, classbuilder.ProtocolBase): if not isinstance(elem, typ): try: if isinstance(elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError("'{0}' is not a valid value for '{1}': {2}" .format(elem, typ, e)) else: val = elem val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, ArrayWrapper): val = typ(elem) val.validate() typed_elems.append(val) elif isinstance(typ, (classbuilder.TypeProxy, classbuilder.TypeRef)): try: if isinstance(elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError("'{0}' is not a valid value for '{1}': {2}" .format(elem, typ, e)) else: val.validate() typed_elems.append(val) self._dirty = False self._typed = typed_elems return typed_elems
def setprop(self, val): if isinstance(info['type'], (list, tuple)): ok = False errors = [] type_checks = [] for typ in info['type']: if not isinstance(typ, dict): type_checks.append(typ) continue typ = next(t for n, t in validators.SCHEMA_TYPE_MAPPING if typ['type'] == t) if typ is None: typ = type(None) if isinstance(typ, (list, tuple)): type_checks.extend(typ) else: type_checks.append(typ) for typ in type_checks: if isinstance(val, typ): ok = True break elif hasattr(typ, 'isLiteralClass'): try: validator = typ(val) except Exception as e: errors.append( "Failed to coerce to '{0}': {1}".format(typ, e)) pass else: validator.validate() ok = True break elif util.safe_issubclass(typ, ProtocolBase): # force conversion- thus the val rather than validator assignment try: val = typ(**util.coerce_for_expansion(val)) except Exception as e: errors.append( "Failed to coerce to '{0}': {1}".format(typ, e)) pass else: val.validate() ok = True break elif util.safe_issubclass(typ, validators.ArrayValidator): try: val = typ(val) except Exception as e: errors.append( "Failed to coerce to '{0}': {1}".format(typ, e)) pass else: val.validate() ok = True break if not ok: errstr = "\n".join(errors) raise validators.ValidationError( "Object must be one of {0}: \n{1}".format(info['type'], errstr)) elif info['type'] == 'array': instance = info['validator'](val) val = instance.validate() elif util.safe_issubclass(info['type'], validators.ArrayValidator): # An array type may have already been converted into an ArrayValidator instance = info['type'](val) val = instance.validate() elif getattr(info['type'], 'isLiteralClass', False) is True: if not isinstance(val, info['type']): validator = info['type'](val) validator.validate() elif util.safe_issubclass(info['type'], ProtocolBase): if not isinstance(val, info['type']): val = info['type'](**util.coerce_for_expansion(val)) val.validate() elif isinstance(info['type'], TypeProxy): val = info['type'](val) elif info['type'] is None: # This is the null value if val is not None: raise validators.ValidationError( "None is only valid value for null") else: raise TypeError("Unknown object type: '{0}'".format(info['type'])) self._properties[prop] = val