Beispiel #1
0
    def __init__(self, value, **kwargs):
        # set to None so we do not get attribute errors:
        self.value = None

        # do we allow null/NaN? If not explicitly given, assume we do NOT allow nulls
        try:
            allow_null = bool(kwargs.pop('allow_null'))
        except KeyError:
            allow_null = False

        # are we setting the value, or just using the constructor as a way to 
        # validate?
        try:
            set_value = bool(kwargs.pop('set_value'))
        except KeyError:
            set_value = True

        # go ahead and validate if we do have a value to check
        if value is not None:
            self.value_validator(value, allow_null=allow_null, set_value=set_value)
        else:
            # value is None...is that ok? If not, raise an exception
            if not allow_null:
                raise AttributeValueError('Received a null/None value which is not allowed.')

        # if kwargs is not an empty dict, raise an exception
        if kwargs != {}:
            raise AttributeValueError('This type of attribute does not '
            ' accept additional keyword arguments.'
            ' Received: {keys}'.format(keys=','.join(kwargs.keys())))
Beispiel #2
0
 def value_validator(self, val, set_value=True, allow_null=False):
     if (val is None) and (not allow_null):
         raise AttributeValueError('Cannot set this to be null/None.')
     
     if not val in self.options:
         raise AttributeValueError('The value "{val}" was not among the valid options: {opts}'.format(
             val = val,
             opts = ','.join(self.options)
         ))
     elif set_value:
         self.value = val
Beispiel #3
0
    def value_validator(self, val, set_value=True, allow_null=False):
        '''
        Validates that the value (or values)
        are proper UUIDs. 
        '''
        # if a single UUID was passed, place it into a list:
        
        if (type(val) == str) or (type(val) == uuid.UUID):
            all_vals = [val,]
        elif type(val) == list:
            if self.many == False:
                raise AttributeValueError('The values ({val})'
                    ' are inconsistent with the many=False'
                    ' parameter.'.format(
                        val=val
                    )
                )
            all_vals = val
        else:
            raise AttributeValueError('Value needs to be either'
                ' a single UUID or a list of UUIDs'
            )

        try:
            all_vals = [str(x) for x in all_vals]
        except Exception as ex:
            logger.error('An unexpected exception occurred when trying'
                ' to validate a DataResource attribute.'
            )
            raise ex

        for v in all_vals:
            try:
                # check that it is a UUID
                # Note that we can't explicitly check that a UUID
                # corresponds to a Resource database instance
                # as that creates a circular import dependency.
                uuid.UUID(v)
            except ValueError as ex:
                raise AttributeValueError('The passed value ({val}) was'
                    ' not a valid UUID.'.format(val=v)
                )
            except Exception as ex:
                raise AttributeValueError('Encountered an unknown exception'
                    ' when validating a DataResourceAttribute instance. Value was'
                    ' {value}'.format(
                        value = v
                    )
                )
        
        if set_value:
            self.value = val
Beispiel #4
0
 def value_validator(self, val, set_value=True, allow_null=False):
     if type(val) == int:
         if val >= 0:
             if set_value:
                 self.value = val
         else:
             raise AttributeValueError(
                 'The value {val} is not a non-' 
                 'negative integer.'.format(val=val))    
     else:
         raise AttributeValueError(
             'A non-negative integer attribute was expected,'
             ' but "{val}" is not.'.format(val=val))
Beispiel #5
0
 def value_validator(self, val, set_value=True, allow_null=False):
     
     if (type(val) == float) or (type(val) == int):
         if val >= 0:
             if set_value:
                 self.value = float(val)
         else:
             raise AttributeValueError('Received a valid float, but'
                 ' it was not >= 0.')
     elif val == settings.POSITIVE_INF_MARKER:
         self.value = val
     else:
         raise AttributeValueError(
             'A float attribute was expected, but'
             ' received "{val}"'.format(val=val))
Beispiel #6
0
 def handle_list_of_attributes(self, values, **kwargs):
     self._value = []
     if type(values) != list:
         raise AttributeValueError('To create a list-type attribute'
             ' you must supply a list.'
         )
     for v in values:
         try:
             t = self.base_attribute_type(v, **kwargs)
             self._value.append(t)
         except AttributeValueError as ex:
             err_string = ('Encountered an issue validating one of the nested'
                 ' attributes. Problem was: {ex}'.format(ex=ex)
             )
             raise AttributeValueError(err_string)
Beispiel #7
0
    def value_validator(self, val, set_value=True, allow_null=False):
        '''
        Validates that the value can be interpreted
        as a boolean.  Either true/false or 1/0
        '''
        val_type = type(val)
        final_val = None
        if val_type == str:
            if val.lower() in ['true', 'false']:
                final_val = val.lower()
        elif val_type == bool:
            final_val = val
        elif val_type == int:
            if val in [0,1]:
                final_val = val

        if final_val is not None:
            if final_val in ['true', 1, True]:
                if set_value:
                    self.value = True
            elif final_val in ['false', 0, False]:
                if set_value:
                    self.value = False
            else:
                raise Exception('Hit an edge case when trying to validate'
                    ' boolean value.  Value was {val} and the "final value"'
                    ' was {final_val}'.format(
                        val = val,
                        final_val = final_val
                    )
                )
        else:
            raise AttributeValueError(
                'A boolean attribute was expected,'
                ' but "{val}" cannot be interpreted as such.'.format(val=val)) 
Beispiel #8
0
 def value_validator(self, val, set_value=True, allow_null=False):
     try:
         val = api_utils.normalize_identifier(val)
         if set_value:
             self.value = val
     except StringIdentifierException as ex:
         raise AttributeValueError(str(ex))
 def convert(self, input_key, user_input, op_dir, staging_dir):
     s = UnrestrictedStringListAttribute(user_input)
     try:
         s = [normalize_identifier(x) for x in s.value]
     except StringIdentifierException as ex:
         raise AttributeValueError(str(ex))
     return {input_key: self.to_string(s)}
Beispiel #10
0
 def convert(self, input_key, user_input, op_dir, staging_dir):
     s = UnrestrictedStringAttribute(user_input)
     try:
         s = normalize_identifier(s.value)
     except StringIdentifierException as ex:
         raise AttributeValueError(str(ex))
     return {input_key: s}
Beispiel #11
0
 def set_bounds(self, kwargs_dict):
     try: 
         self.min_value = kwargs_dict.pop(self.MINIMUM_KEY)
         self.max_value = kwargs_dict.pop(self.MAXIMUM_KEY)
     except KeyError as ex:
         missing_key = str(ex)
         raise AttributeValueError('Need bounds to specify a BoundedInteger.'
             ' Was missing {key}'.format(key=missing_key))
Beispiel #12
0
 def value_validator(self, val, set_value=True, allow_null=False):
     if type(val) == int:
         if set_value:
             self.value = val
     else:
         raise AttributeValueError(
             'An integer attribute was expected, but the'
             ' value "{val}" could not'
             ' be cast as an integer'.format(val=val)
         )
Beispiel #13
0
    def value_validator(self, val, set_value=True, allow_null=False):

        # here we also validate that the bounds are of
        # the same integer type
        self.check_bound_types([int, float])

        if (type(val) == float) or (type(val) == int):
            if (val >= self.min_value) and (val <= self.max_value):
                if set_value:
                    self.value = val
            else:
                raise AttributeValueError(
                    'The value {val} is not within the bounds' 
                    ' of [{min},{max}]'.format(
                        val=val,
                        min=self.min_value,
                        max=self.max_value)
                    ) 
        else:
            raise AttributeValueError(
                'A bounded float attribute was expected,'
                ' but "{val}" is not a float, or is not bounded.'.format(val=val))
Beispiel #14
0
 def check_bound_types(self, primitive_type_list):
     '''
     This checks that the bounds are sensible for the specific
     implementation of the bounded type.  For example, if we are
     creating a bounded integer, the bounds are also integers.
     
     The child implementations call this and provide the 
     acceptable types as a list.
     '''
     d = {
         'minimum': self.min_value,
         'maximum': self.max_value
     }
     for k in d.keys():
         dtype = type(d[k])
         if not dtype in primitive_type_list:
             raise AttributeValueError('The {bound} value {val}'
             ' specified does not match the expected type'
             ' for this bounded attribute.'.format(
                 bound=k,
                 val = d[k]
             ))