예제 #1
0
def limit_option(value, min=0, max=None, warn_default=0, alert_default=0):
    valid_options = ['WARN', 'ALERT']

    # Check min/max parameters
    if min is not None:
        try:
            min = int(min)
        except ValueError:
            raise VdtParamError('min', min)
    if max is not None:
        try:
            max = int(max)
        except ValueError:
            raise VdtParamError('max', max)

    # Check value is a list
    if not isinstance(value, list):
        raise VdtTypeError(value)

    # Check for too many or too few values
    if len(value) > len(valid_options):
        raise VdtValueTooLongError(value)
    # elif len(value) < 1:
    #     raise VdtValueTooShortError(value)
    returnDict = {'WARN': warn_default, 'ALERT': alert_default}
    valueDict = {}
    for entry in value:
        # Check list value is a string
        try:
            entry = str(entry)
        except ValueError:
            raise VdtValueError(entry)

        optionParts = entry.split(':', 1)

        limitType = optionParts[0].strip().upper()
        limitVal = optionParts[1]

        if limitType not in valid_options:
            raise VdtValueError(limitType)
        try:
            limitVal = int(limitVal)
        except ValueError:
            raise VdtTypeError(limitVal)

        # Check limits values fall in range
        if max is not None and limitVal > max:
            raise VdtValueTooBigError(limitVal)
        elif min is not None and limitVal < min:
            raise VdtValueTooSmallError(limitVal)

        # Check duplicate
        if limitType in valueDict:
            raise VdtValueError(value)
        valueDict[limitType] = limitVal

    returnDict.update(valueDict)
    # print returnDict
    return ','.join(
        ['%s: %s' % (key, value) for (key, value) in returnDict.items()])
def _region(value):
    value = value.lower()
    if not isinstance(value, str):
        raise VdtTypeError(value)
    if value not in ALL_REGIONS:
        raise VdtTypeError(value)
    return value
예제 #3
0
def width_tuple(value):
    """
    test if value is a valid width indicator (for a sub-widget in a column).
    This can either be
    ('fit', min, max): use the length actually needed for the content, padded
                       to use at least width min, and cut of at width max.
                       Here, min and max are positive integers or 0 to disable
                       the boundary.
    ('weight',n): have it relative weight of n compared to other columns.
                  Here, n is an int.
    """
    if value is None:
        res = 'fit', 0, 0
    elif not isinstance(value, (list, tuple)):
        raise VdtTypeError(value)
    elif value[0] not in ['fit', 'weight']:
        raise VdtTypeError(value)
    if value[0] == 'fit':
        if not isinstance(value[1], int) or not isinstance(value[2], int):
            VdtTypeError(value)
        res = 'fit', int(value[1]), int(value[2])
    else:
        if not isinstance(value[1], int):
            VdtTypeError(value)
        res = 'weight', int(value[1])
    return res
def _account(value):
    if len(value) != 12:
        raise VdtTypeError(value)
    try:
        int(value)
    except:
        raise VdtTypeError(value)
    return value
def _project_mapping(value):
    if value is '' or None:
        return ''  # valid case if you have no projects to build
    mappings = value.split(';')
    for mapping in mappings:
        items = mapping.split(':')
        if len(items) != 2:
            raise VdtTypeError(value)
        if items[0] not in ALLOWED_BUILDS:
            raise VdtTypeError(value)
    return value
예제 #6
0
def _chk_engrtime(value):
    ''' Check if value is time in engr notation like 11ns, 5fs, etc. '''
    time_suffix = 's'
    if not isinstance(value, str) or value[-1] != time_suffix or from_engr(
            value[:-1]) == None:
        raise VdtTypeError(value)
    return value
예제 #7
0
def is_date_format(sValue):
    """Validator function to check for date format."""
    try:
        oDate = datetime.datetime.strptime(sValue, '%Y-%m-%d').date()
    except ValueError:
        raise VdtTypeError(sValue)
    return oDate
예제 #8
0
def validate(configfile, inputfilepath=None):
    '''
    Return a validated config object.

    Args:
        configfile (str): Config file to validate.
        inputfilepath (str): Path to input file.

    Returns:
        A validated ConfigObj object or a dictionary of which
        section/parameters failed validation.
    '''
    thispath = os.path.dirname(os.path.abspath(__file__))
    configspec = os.path.join(thispath, 'configspec.ini')
    config = ConfigObj(configfile, configspec=configspec)
    if inputfilepath is not None:
        config = correct_config_filepaths(config)
    validator = __getCustomValidator()
    result = config.validate(validator, preserve_errors=True)
    if result is True:
        return config
    else:
        errormsg = __filterResults(result)
        raise VdtTypeError(errormsg)

    return config
예제 #9
0
def is_option_list(value, *args):
    """Validator for a list of options"""
    if not isinstance(value, list):
        raise VdtTypeError(value)
    for v in value:
        if v not in args:
            raise VdtValueError(v)
    return value
예제 #10
0
def annotatedfloat_type(value):
    try:
        out = float(value)
    except:
        if value.find('c') < 0 and value.find('m') < 0:
            raise VdtTypeError(value)
    out = []
    if value.find('c') > 0:
        try:
            out = float(value.replace('c', '')) / 3600.0
        except:
            raise VdtTypeError(value)
    if value.find('m') > 0:
        try:
            out = float(value.replace('m', '')) / 60.0
        except:
            raise VdtTypeError(value)
    return out
예제 #11
0
def is_level(value, default=None):
    """Validate a string that can be evaluated"""
    try:
        #res = interpret_level(tuple(force_list(value, 1, 3)))
        res = interpret_level(value, astuple=False)
    except:
        raise VdtTypeError(value)
    #print '*** is_level value: %r, default: %r, res: %r'%(value, default, res)
    return res
예제 #12
0
def mail_container(value):
    """
    Check that the value points to a valid mail container,
    in URI-style, e.g.: `mbox:///home/username/mail/mail.box`.
    `~`-expansion will work, e.g.: `mbox://~/mail/mail.box`.
    The value is cast to a :class:`mailbox.Mailbox` object.
    """
    if not re.match(r'.*://.*', value):
        raise VdtTypeError(value)
    mburl = urlparse(value)
    uri_scheme_to_mbclass = {
        'mbox': mailbox.mbox,
        'maildir': mailbox.Maildir,
        'mh': mailbox.MH,
        'babyl': mailbox.Babyl,
        'mmdf': mailbox.MMDF,
    }
    klass = uri_scheme_to_mbclass.get(mburl.scheme)
    if klass:
        return klass(mburl.netloc + mburl.path)
    raise VdtTypeError(value)
예제 #13
0
def gmpe_type(value, *args):
    if len(args) != len(value):
        raise VdtParamError('gmpe', value)
    out = []
    try:
        minmag = float(value[0])
        maxmag = float(value[1])
        mindep = float(value[2])
        maxdep = float(value[3])
        if not (minmag >= 0.0 and minmag <= 9.9):
            raise VdtTypeError(value)
        if not (maxmag >= 0.0 and maxmag <= 9.9 and maxmag > minmag):
            raise VdtTypeError(value)
        if not (mindep >= 0.0 and mindep <= 10000.0):
            raise VdtTypeError(value)
        if not (maxdep >= 0.0 and maxdep <= 10000.0 and maxdep > mindep):
            raise VdtTypeError(value)
        out += [minmag, maxmag, mindep, maxdep]
    except:
        raise VdtParamError('gmpe', value)
    return out
예제 #14
0
def mail_container(value):
    """
    Check that the value points to a valid mail container,
    in URI-style, e.g.: `mbox:///home/username/mail/mail.box`.
    The value is cast to a :class:`mailbox.Mailbox` object.
    """
    if not re.match(r'.*://.*', value):
        raise VdtTypeError(value)
    mburl = urlparse(value)
    if mburl.scheme == 'mbox':
        box = mailbox.mbox(mburl.path)
    elif mburl.scheme == 'maildir':
        box = mailbox.Maildir(mburl.path)
    elif mburl.scheme == 'mh':
        box = mailbox.MH(mburl.path)
    elif mburl.scheme == 'babyl':
        box = mailbox.Babyl(mburl.path)
    elif mburl.scheme == 'mmdf':
        box = mailbox.MMDF(mburl.path)
    else:
        raise VdtTypeError(value)
    return box
예제 #15
0
def __file_type(value):
    '''Describes a file_type from the ShakeMap config spec.
    A file_type object is simply a string that must be a valid file on the system.

    :param value:
      String representing valid path to a file on the local system.
    :return:
      Input string, if a valid file name.
    :raises VdtTypeError:
      When path is invalid.
    '''
    if not os.path.isfile(value):
        raise VdtTypeError(value)
    return value
예제 #16
0
def __path_type(value):
    """
    Describes a path_type from the groundfailure config spec.
    A path_type object is simply a string that must be a valid file OR
    directory on the system.

    Args:
        value (str): Path to a file or directory on the local system.

    Returns:
        str: Input string, if a valid file/directory name.
    """
    if not os.path.isfile(value) and not os.path.isdir(value):
        raise VdtTypeError(value)
    return value
예제 #17
0
def __file_type(value):
    """
    Describes a file_type from the ShakeMap config spec.
    A file_type object is simply a string that must be a valid file on the
    system.

    Args:
        value (str): Path to a file on the local system.

    Returns:
        str: Input string, if a valid file name.
    """
    if not os.path.isfile(value):
        raise VdtTypeError(value)
    return value
예제 #18
0
def __path_type(value):
    '''Describes a path_type from the groundfailure config spec.
    A path_type object is simply a string that must be a valid file OR
    directory on the system.

    :param value:
      String representing valid path to a file or directory on the local system.
    :return:
      Input string, if a valid file/directory name.
    :raises VdtTypeError:
      When path is invalid.
    '''
    if not os.path.isfile(value) and not os.path.isdir(value):
        raise VdtTypeError(value)
    return value
예제 #19
0
    def _is_dict(self, value, min=None, max=None):
        """
        Validation function for dict values.

        Reference: https://github.com/DiffSK/configobj/blob/master/src/configobj/validate.py
        """
        # Get boundary values
        (min_val, max_val) = _is_num_param(('min', 'max'), (min, max))

        # Check if value is string
        if isinstance(value, str):
            # Convert string value
            try:
                value = ast.literal_eval(value)
            except ValueError:
                if value == 'dict()' or value == 'dict':
                    value = dict()
                else:
                    raise ValidateError(
                        'A value "{}" could not be converted to a dict!'.
                        format(value))
            except Exception as e:
                raise e

            # Validate whether the value is a dict
            if not isinstance(value, dict):
                raise ValidateError(
                    'A value of type {} was passed when a dict was expected!'.
                    format(type(value)))

        elif isinstance(value, dict):
            pass

        else:
            raise VdtTypeError(value)

        # Validate whether the value is within the boundaries
        if (min_val is not None) and (len(value) < min_val):
            raise VdtValueTooShortError(value)

        if (max_val is not None) and (len(value) > max_val):
            raise VdtValueTooLongError(value)

        return value
예제 #20
0
def option_list(value, options=None, min=None, max=None):
    if options and not isinstance(options, list):
        raise VdtParamError('options', options)

    if min is not None:
        try:
            min = int(min)
        except ValueError:
            raise VdtParamError('min', min)

    if max is not None:
        try:
            max = int(max)
        except ValueError:
            raise VdtParamError('max', max)

    if min < 0:
        raise VdtParamError('min', min)

    if max < min:
        raise VdtParamError('max', max)

    if isinstance(value, str):
        strVal = value.strip()
        value = []
        if strVal:
            value = [strVal]

    if not isinstance(value, list):
        raise VdtTypeError(value)

    if max and len(value) > max:
        raise VdtValueTooLongError(value)
    elif min and len(value) < min:
        raise VdtValueTooShortError(value)

    if not options:
        return value

    for entry in value:
        if entry not in options:
            raise VdtValueError(value)

    return value
예제 #21
0
def sample_option(value, samples_default=1, interval_default=1):

    valid_options = ['SAMPLES', 'INTERVAL']

    # Check samples_default and interval_default parameters
    try:
        samples_default = int(samples_default)
    except ValueError:
        raise VdtParamError('samples_default', samples_default)
    if samples_default < 1:
        raise VdtParamError('samples_default', samples_default)
    try:
        interval_default = int(interval_default)
    except ValueError:
        raise VdtParamError('interval_default', interval_default)
    if interval_default < 1:
        raise VdtParamError('interval_default', interval_default)

    returnDict = {'SAMPLES': samples_default, 'INTERVAL': interval_default}

    if value and not isinstance(value, list):
        raise VdtTypeError(value)

    if value is None or len(value) == 0:
        return returnDict

    if len(value) > len(valid_options):
        raise VdtValueTooLongError(value)

    updateDict = {}
    for entry in value:
        try:
            entry = str(entry)
        except ValueError:
            raise VdtValueError(entry)

        optionParts = entry.split(':', 1)
        if len(optionParts) != 2:
            raise VdtValueError(entry)

        limitType = optionParts[0].strip().upper()
        limitVal = optionParts[1]

        if limitType not in valid_options:
            raise VdtValueError(limitType)
        try:
            limitVal = int(limitVal)
        except ValueError:
            raise VdtTypeError(limitVal)

        if limitVal < 1:
            raise VdtValueTooSmallError(limitVal)

        if limitType in updateDict:
            raise VdtValueError(value)

        updateDict[limitType] = limitVal

    returnDict.update(updateDict)
    return ','.join(
        ['%s: %s' % (key, value) for (key, value) in returnDict.items()])
예제 #22
0
def port(value):
    try:
        return validate_port_number(int(value))
    except ValueError:
        raise VdtTypeError(value)
예제 #23
0
def directory_type(value):
    if not os.path.isdir(value):
        raise VdtTypeError(value)
    return value
예제 #24
0
def file_type(value):
    if not os.path.isfile(value):
        raise VdtTypeError(value)
    return value