Ejemplo n.º 1
0
def valid_value(var_value, invalid_values=[""], valid_values=[]):
    r"""
    Return True if var_value is a valid value.  Otherwise, return False and
    print an error message to stderr.

    Description of arguments:
    var_value                       The value being validated.
    invalid_values                  A list of invalid values.  If var_value is
                                    equal to any of these, it is invalid.
                                    Note that if you specify anything for
                                    invalid_values (below), the valid_values
                                    list is not even processed.
    valid_values                    A list of invalid values.  var_value must
                                    be equal to one of these values to be
                                    considered valid.
    """

    len_valid_values = len(valid_values)
    len_invalid_values = len(invalid_values)
    if len_valid_values > 0 and len_invalid_values > 0:
        gp.print_error_report("Programmer error - You must provide either an" +
                              " invalid_values list or a valid_values" +
                              " list but NOT both.")
        return False

    if len_valid_values > 0:
        # Processing the valid_values list.
        if var_value in valid_values:
            return True
        var_name = gp.get_arg_name(0, 1, 2)
        gp.print_error_report("The following variable has an invalid" +
                              " value:\n" +
                              gp.sprint_varx(var_name, var_value) +
                              "\nIt must be one of the following values:\n" +
                              gp.sprint_varx("valid_values", valid_values))
        return False

    if len_invalid_values == 0:
        gp.print_error_report("Programmer error - You must provide either an" +
                              " invalid_values list or a valid_values" +
                              " list.  Both are empty.")
        return False

    # Assertion: We have an invalid_values list.  Processing it now.
    if var_value not in invalid_values:
        return True

    var_name = gp.get_arg_name(0, 1, 2)
    gp.print_error_report("The following variable has an invalid value:\n" +
                          gp.sprint_varx(var_name, var_value) + "\nIt must" +
                          " NOT be one of the following values:\n" +
                          gp.sprint_varx("invalid_values", invalid_values))
    return False
Ejemplo n.º 2
0
def svalid_dict(var_value, required_keys=[], var_name=""):
    r"""
    Return an empty string if var_value is a valid dictionary.  Otherwise,
    return an error string.

    Description of arguments:
    var_value                       The value (i.e. dictionary) being
                                    validated.
    required_keys                   A list of keys which must be found in the
                                    dictionary for it to be considered valid.
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    error_message = ""

    keys_missing = list(set(required_keys) - set(var_value.keys()))
    if len(keys_missing) > 0:
        show_blanks = 1
        var_name = get_var_name(var_name)
        error_message = "The following key fields are missing from "
        error_message += var_name + ":\n"
        error_message += gp.sprint_var(keys_missing)
        error_message += gp.sprint_varx(var_name, var_value, show_blanks)
        return error_message

    return ""
Ejemplo n.º 3
0
def svalid_file_path(var_value,
                     var_name=""):

    r"""
    Return an empty string if var_value is a valid file path.  Otherwise,
    return an error string.

    Description of arguments:
    var_value                       The value being validated.
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    error_message = ""
    if not os.path.isfile(str(var_value)):
        if var_name is "":
            stack_index = 3
            var_name = gp.get_arg_name(0, 1, stack_index)
        error_message += "Invalid file (does not exist):\n" +\
                         gp.sprint_varx(var_name, var_value)

    return error_message
Ejemplo n.º 4
0
def sprint_vars(*args, **kwargs):
    r"""
    Sprint the values of one or more variables to the console.

    This is a robot re-definition of the sprint_vars function in gen_print.py.  Given a list of variable
    names, this keyword will string print each variable name and value such that each value lines up in the
    same column as messages printed with sprint_time().

    Description of argument(s):
    args                            The names of the variables to be printed (e.g. var1 rather than ${var1}).
    kwargs                          See sprint_varx in gen_print.py for descriptions of all other arguments.
    """

    if 'fmt' in kwargs:
        # Find format option names in kwargs['fmt'] and wrap them with "gp." and "()" to make them into
        # function calls.  For example, verbose would be converted to "gp.verbose()".  This allows the user
        # to simply specify "fmt=verbose" (vs. fmt=gp.verbose()).
        # Note "terse" has been explicitly added for backward compatibility.  Once the repo has been purged
        # of its use, this code can return to its original form.
        regex = "(" + "|".join(gp.valid_fmts()) + "|terse)"
        kwargs['fmt'] = \
            re.sub(regex, "gp.\\1()", kwargs['fmt'])
    kwargs = fa.args_to_objects(kwargs)
    buffer = ""
    for var_name in args:
        var_value = BuiltIn().get_variable_value("${" + str(var_name) + "}")
        buffer += gp.sprint_varx(var_name, var_value, **kwargs)

    return buffer
def sprint_plug_vars(headers=1, **kwargs):
    r"""
    Sprint the plug-in environment variables (i.e. those that begin with the global PLUG_VAR_PREFIX value or
    those that begin with <plug-in package_name>_ in upper case letters.).

    Example excerpt of output:
    AUTOBOOT_BASE_TOOL_DIR_PATH=/tmp/
    AUTOBOOT_BB_LEVEL=
    AUTOBOOT_BOOT_FAIL=0
    AUTOBOOT_BOOT_FAIL_THRESHOLD=1000000

    Description of argument(s):
    headers                         Print a header and a footer.
    kwargs                          These are passed directly to return_plug_vars.  See return_plug_vars doc
                                    string for details.
    """
    plug_var_dict = return_plug_vars(**kwargs)
    buffer = ""
    if headers:
        buffer += "\n" + gp.sprint_dashes()
    for key, value in plug_var_dict.items():
        buffer += gp.sprint_varx(key, value)
    if headers:
        buffer += gp.sprint_dashes() + "\n"

    return buffer
def svalid_file_path(var_value, var_name=""):
    r"""
    Return an empty string if var_value is a valid file path.  Otherwise,
    return an error string.

    Description of arguments:
    var_value                       The value being validated.
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    error_message = ""
    if not os.path.isfile(str(var_value)):
        if var_name is "":
            stack_index = 3
            var_name = gp.get_arg_name(0, 1, stack_index)
        error_message += "Invalid file (does not exist):\n" +\
                         gp.sprint_varx(var_name, var_value)

    return error_message
Ejemplo n.º 7
0
def svalid_integer(var_value,
                   var_name=""):
    r"""
    Return an empty string if var_value is a valid integer.  Otherwise, return
    an error string.

    Description of arguments:
    var_value                       The value being validated.
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    success_message = ""
    error_message = ""
    try:
        if isinstance(int(str(var_value), 0), int):
            return success_message
    except ValueError:
        pass

    # If we get to this point, the validation has failed.
    show_blanks = 1
    error_message +=\
        "Invalid integer value:\n" +\
        gp.sprint_varx(get_var_name(var_name), var_value, show_blanks)

    return error_message
Ejemplo n.º 8
0
def valid_length(var_value, min_length=None, max_length=None, var_name=None):
    r"""
    The variable value is valid if it is an object (e.g. list, dictionary) whose length is within the
    specified range.

    Description of argument(s):
    var_value                       The value being validated.
    min_length                      The minimum length of the object.  If not None, the length of var_value
                                    must be greater than or equal to min_length.
    max_length                      The maximum length of the object.  If not None, the length of var_value
                                    must be less than or equal to min_length.
    """

    error_message = ""
    length = len(var_value)
    error_message = valid_range(length, min_length, max_length)
    if error_message:
        var_name = get_var_name(var_name)
        error_message = "The length of the following object is not within the"
        error_message += " expected range:\n"
        error_message += gp.sprint_vars(min_length, max_length)
        error_message += gp.sprint_var(length)
        error_message += gp.sprint_varx(var_name, var_value, gp.blank())
        error_message += "\n"
        return process_error_message(error_message)

    return process_error_message(error_message)
Ejemplo n.º 9
0
def valid_integer(var_value):
    r"""
    Return True if var_value is a valid integer.  Otherwise, return False and
    print an error message to stderr.

    Description of arguments:
    var_value                       The value being validated.
    """

    # This currently allows floats which is not good.

    try:
        if type(int(var_value)) is int:
            return True
    except ValueError:
        pass

    # If we get to this point, the validation has failed.

    var_name = gp.get_arg_name(0, 1, 2)
    gp.print_varx("var_name", var_name)

    gp.print_error_report("Invalid integer value:\n" +
                          gp.sprint_varx(var_name, var_value))

    return False
def rvalidate_plug_ins(plug_in_dir_paths,
                       quiet=1):

    r"""
    Call the external validate_plug_ins.py program which validates the plug-in
    dir paths given to it.  Return a list containing a normalized path for
    each plug-in selected.

    Description of arguments:
    plug_in_dir_paths               A colon-separated list of plug-in
                                    directory paths.
    quiet                           If quiet is set to 1, this function will
                                    NOT write status messages to stdout.
    """

    cmd_buf = "validate_plug_ins.py \"" + plug_in_dir_paths + "\""
    if int(quiet) != 1:
        grp.rpissuing(cmd_buf)
    rc, out_buf = commands.getstatusoutput(cmd_buf)
    if rc != 0:
        message = gp.sprint_varx("rc", rc, 1) + out_buf
        grp.rprintn(out_buf, 'STDERR')
        BuiltIn().fail(gp.sprint_error("Validate plug ins call failed.  See" +
                                       " stderr text for details.\n"))

    plug_in_packages_list = out_buf.split("\n")
    if len(plug_in_packages_list) == 1 and plug_in_packages_list[0] == "":
        return []

    return plug_in_packages_list
def rvalidate_plug_ins(plug_in_dir_paths, quiet=1):
    r"""
    Call the external validate_plug_ins.py program which validates the plug-in
    dir paths given to it.  Return a list containing a normalized path for
    each plug-in selected.

    Description of arguments:
    plug_in_dir_paths               A colon-separated list of plug-in
                                    directory paths.
    quiet                           If quiet is set to 1, this function will
                                    NOT write status messages to stdout.
    """

    cmd_buf = "validate_plug_ins.py \"" + plug_in_dir_paths + "\""
    if int(quiet) != 1:
        grp.rpissuing(cmd_buf)
    rc, out_buf = commands.getstatusoutput(cmd_buf)
    if rc != 0:
        message = gp.sprint_varx("rc", rc, 1) + out_buf
        grp.rprintn(out_buf, 'STDERR')
        BuiltIn().fail(
            gp.sprint_error("Validate plug ins call failed.  See" +
                            " stderr text for details.\n"))

    plug_in_packages_list = out_buf.split("\n")
    if len(plug_in_packages_list) == 1 and plug_in_packages_list[0] == "":
        return []

    return plug_in_packages_list
Ejemplo n.º 12
0
def valid_type(var_value, required_type, var_name=None):
    r"""
    The variable value is valid if it is of the required type.

    Examples:

    valid_type(var1, int)

    valid_type(var1, (list, dict))

    Description of argument(s):
    var_value                       The value being validated.
    required_type                   A type or a tuple of types (e.g. str, int, etc.).
    """

    error_message = ""
    if type(required_type) is tuple:
        if type(var_value) in required_type:
            return process_error_message(error_message)
    else:
        if type(var_value) is required_type:
            return process_error_message(error_message)

    # If we get to this point, the validation has failed.
    var_name = get_var_name(var_name)
    error_message += "Invalid variable type:\n"
    error_message += gp.sprint_varx(var_name, var_value,
                                    gp.blank() | gp.show_type())
    error_message += "\n"
    error_message += gp.sprint_var(required_type)

    return process_error_message(error_message)
Ejemplo n.º 13
0
def valid_float(var_value, lower=None, upper=None, var_name=None):
    r"""
    The variable value is valid if it is a floating point value or can be interpreted as a floating point
    value (e.g. 7.5, "7.5", etc.).

    This function also calls valid_range to make sure the float value is within the specified range (if any).

    Description of argument(s):
    var_value                       The value being validated.
    lower                           The lower end of the range.  If not None, the var_value must be greater
                                    than or equal to lower.
    upper                           The upper end of the range.  If not None, the var_value must be less than
                                    or equal to upper.
    """

    error_message = ""
    var_name = get_var_name(var_name)
    try:
        var_value = float(str(var_value))
    except ValueError:
        error_message += "Invalid float value:\n"
        error_message += gp.sprint_varx(var_name, var_value,
                                        gp.blank() | gp.show_type())
        return process_error_message(error_message)

    # Check the range (if any).
    if lower:
        lower = float(str(lower))
    if upper:
        upper = float(str(upper))
    error_message = valid_range(var_value, lower, upper, var_name=var_name)

    return process_error_message(error_message)
def sprint_vars(*args):
    r"""
    Sprint the values of one or more variables to the console.

    This is a robot re=definition of the sprint_vars function in gen_print.py.
    Given a list of variable names, this keyword will string print each
    variable name and value such that each value lines up in the same column
    as messages printed with sprint_time().

    Description of arguments:
    args:
        If the first argument is an integer, it will be interpreted to be the
        "hex" value.
        If the second argument is an integer, it will be interpreted to be the
        "indent" value.
        If the third argument is an integer, it will be interpreted to be the
        "col1_width" value.
        All remaining parms are considered variable names which are to be
        sprinted.
    """

    if len(args) == 0:
        return

    # Create list from args (which is a tuple) so that it can be modified.
    args_list = list(args)

    # See if parm 1 is to be interpreted as "hex".
    try:
        if isinstance(int(args_list[0]), int):
            hex = int(args_list[0])
            args_list.pop(0)
    except ValueError:
        hex = 0

    # See if parm 2 is to be interpreted as "indent".
    try:
        if isinstance(int(args_list[0]), int):
            indent = int(args_list[0])
            args_list.pop(0)
    except ValueError:
        indent = 0

    # See if parm 3 is to be interpreted as "col1_width".
    try:
        if isinstance(int(args_list[0]), int):
            loc_col1_width = int(args_list[0])
            args_list.pop(0)
    except ValueError:
        loc_col1_width = gp.col1_width

    buffer = ""
    for var_name in args_list:
        var_value = BuiltIn().get_variable_value("${" + str(var_name) + "}")
        buffer += gp.sprint_varx(var_name, var_value, hex, indent,
                                 loc_col1_width)

    return buffer
def sprint_vars(*args):

    r"""
    sprint_vars stands for "String Print Vars".  This is a robot redefinition
    of the sprint_vars function in gen_print.py.  Given a list of variable
    names, this keyword will string print each variable name and value such
    that the value lines up in the same column as messages printed with rptime.

    Description of arguments:
    args:
        If the first argument is an integer, it will be interpreted to be the
        "hex" value.
        If the second argument is an integer, it will be interpreted to be the
        "indent" value.
        If the third argument is an integer, it will be interpreted to be the
        "col1_width" value.
        All remaining parms are considered variable names which are to be
        sprinted.
    """

    if len(args) == 0:
        return

    # Create list from args (which is a tuple) so that it can be modified.
    args_list = list(args)

    # See if parm 1 is to be interpreted as "hex".
    try:
        if type(int(args_list[0])) is int:
            hex = int(args_list[0])
            args_list.pop(0)
    except ValueError:
        hex = 0

    # See if parm 2 is to be interpreted as "indent".
    try:
        if type(int(args_list[0])) is int:
            indent = int(args_list[0])
            args_list.pop(0)
    except ValueError:
        indent = 0

    # See if parm 3 is to be interpreted as "col1_width".
    try:
        if type(int(args_list[0])) is int:
            loc_col1_width = int(args_list[0])
            args_list.pop(0)
    except ValueError:
        loc_col1_width = gp.col1_width

    buffer = ""
    for var_name in args_list:
        var_value = BuiltIn().get_variable_value("${" + str(var_name) + "}")
        buffer += gp.sprint_varx(var_name, var_value, hex, indent,
                                 loc_col1_width)

    return buffer
Ejemplo n.º 16
0
    def sprint_obj(self):
        r"""
        sprint the fields of this object.  This would normally be for debug purposes.
        """

        buffer = ""
        buffer += self.__class__.__name__ + ":\n"
        indent = 2
        try:
            func_name = self.__func.__name__
        except AttributeError:
            func_name = ""
        buffer += gp.sprint_var(func_name, indent=indent)
        buffer += gp.sprint_varx("time_out", self.__time_out, indent=indent)
        buffer += gp.sprint_varx("child_pid", self.__child_pid, indent=indent)
        buffer += gp.sprint_varx("original_SIGUSR1_handler",
                                 self.__original_SIGUSR1_handler,
                                 indent=indent)
        return buffer
Ejemplo n.º 17
0
    def sprint_obj(self):
        r"""
        sprint the fields of this object.  This would normally be for debug purposes.
        """

        buffer = ""

        buffer += self.__obj_name + ":\n"
        indent = 2
        buffer += gp.sprint_varx('stack_dict', self.__stack_dict, indent)

        return buffer
Ejemplo n.º 18
0
    def sprint_obj(self):
        r"""
        sprint the fields of this object.  This would normally be for debug
        purposes.
        """

        buffer = ""

        buffer += self.__obj_name + ":\n"
        indent = 2
        buffer += gp.sprint_varx('stack_dict', self.__stack_dict, 1, indent)

        return buffer
Ejemplo n.º 19
0
def validate_plug_in_package(plug_in_dir_path,
                             mch_class="obmc"):

    r"""
    Validate the plug in package and return the normalized plug-in directory
    path.

    Description of arguments:
    plug_in_dir_path                The "relative" or absolute path to a plug
                                    in package directory.
    mch_class                       The class of machine that we are testing
                                    (e.g. "op" = "open power", "obmc" = "open
                                    bmc", etc).
    """

    gp.dprint_executing()

    if os.path.isabs(plug_in_dir_path):
        # plug_in_dir_path begins with a slash so it is an absolute path.
        candidate_plug_in_dir_path = os.path.normpath(plug_in_dir_path) +\
                                     os.sep
        if not os.path.isdir(candidate_plug_in_dir_path):
            gp.print_error_report("Plug-in directory path \"" +
                                  plug_in_dir_path + "\" does not exist.\n")
            exit(1)
    else:
        # The plug_in_dir_path is actually a simple name (e.g.
        # "OBMC_Sample")...
        candidate_plug_in_dir_path = find_plug_in_package(plug_in_dir_path)
        if candidate_plug_in_dir_path == "":
            global PATH_LIST
            gp.print_error_report("Plug-in directory path \"" +
                                  plug_in_dir_path + "\" could not be found" +
                                  " in any of the following directories:\n" +
                                  gp.sprint_var(PATH_LIST))
            exit(1)
    # Make sure that this plug-in supports us...
    supports_file_path = candidate_plug_in_dir_path + "supports_" + mch_class
    if not os.path.exists(supports_file_path):
        gp.print_error_report("The following file path could not be" +
                              " found:\n" +
                              gp.sprint_varx("supports_file_path",
                                             supports_file_path) +
                              "\nThis file is necessary to indicate that" +
                              " the given plug-in supports the class of" +
                              " machine we are testing, namely \"" +
                              mch_class + "\".\n")
        exit(1)

    return candidate_plug_in_dir_path
Ejemplo n.º 20
0
def validate_plug_in_package(plug_in_dir_path,
                             mch_class="obmc"):

    r"""
    Validate the plug in package and return the normalized plug-in directory
    path.

    Description of arguments:
    plug_in_dir_path                The "relative" or absolute path to a plug
                                    in package directory.
    mch_class                       The class of machine that we are testing
                                    (e.g. "op" = "open power", "obmc" = "open
                                    bmc", etc).
    """

    gp.dprint_executing()

    if os.path.isabs(plug_in_dir_path):
        # plug_in_dir_path begins with a slash so it is an absolute path.
        candidate_plug_in_dir_path = os.path.normpath(plug_in_dir_path) +\
            os.sep
        if not os.path.isdir(candidate_plug_in_dir_path):
            gp.print_error_report("Plug-in directory path \"" +
                                  plug_in_dir_path + "\" does not exist.\n")
            exit(1)
    else:
        # The plug_in_dir_path is actually a simple name (e.g.
        # "OBMC_Sample")...
        candidate_plug_in_dir_path = find_plug_in_package(plug_in_dir_path)
        if candidate_plug_in_dir_path == "":
            global PATH_LIST
            gp.print_error_report("Plug-in directory path \"" +
                                  plug_in_dir_path + "\" could not be found" +
                                  " in any of the following directories:\n" +
                                  gp.sprint_var(PATH_LIST))
            exit(1)
    # Make sure that this plug-in supports us...
    supports_file_path = candidate_plug_in_dir_path + "supports_" + mch_class
    if not os.path.exists(supports_file_path):
        gp.print_error_report("The following file path could not be" +
                              " found:\n" +
                              gp.sprint_varx("supports_file_path",
                                             supports_file_path) +
                              "\nThis file is necessary to indicate that" +
                              " the given plug-in supports the class of" +
                              " machine we are testing, namely \"" +
                              mch_class + "\".\n")
        exit(1)

    return candidate_plug_in_dir_path
Ejemplo n.º 21
0
def valid_path(var_value, var_name=None):
    r"""
    The variable value is valid if it contains the path of an existing file or directory.

    Description of argument(s):
    var_value                       The value being validated.
    """

    error_message = ""
    if not (os.path.isfile(str(var_value)) or os.path.isdir(str(var_value))):
        var_name = get_var_name(var_name)
        error_message += "Invalid path (file or directory does not exist):\n"
        error_message += gp.sprint_varx(var_name, var_value, gp.blank())

    return process_error_message(error_message)
Ejemplo n.º 22
0
def valid_file_path(var_value, var_name=None):
    r"""
    The variable value is valid if it contains the path of an existing file.

    Description of argument(s):
    var_value                       The value being validated.
    """

    error_message = ""
    if not os.path.isfile(str(var_value)):
        var_name = get_var_name(var_name)
        error_message += "The following file does not exist:\n"
        error_message += gp.sprint_varx(var_name, var_value, gp.blank())

    return process_error_message(error_message)
Ejemplo n.º 23
0
def valid_dir_path(var_value, *args, **kwargs):
    r"""
    The variable value is valid if it contains the path of an existing
    directory.

    Description of argument(s):
    var_value                       The value being validated.
    """

    error_message = ""
    if not os.path.isdir(str(var_value)):
        var_name = get_var_name(*args, **kwargs)
        error_message += "The following directory does not exist:\n"
        error_message += gp.sprint_varx(var_name, var_value, gp.blank())

    return process_error_message(error_message)
Ejemplo n.º 24
0
def sprint_args(arg_obj, indent=0):
    r"""
    sprint_var all of the arguments found in arg_obj and return the result as a string.

    Description of arguments:
    arg_obj                         An argument object such as is returned by the argparse parse_args()
                                    method.
    indent                          The number of spaces to indent each line of output.
    """

    col1_width = gp.dft_col1_width + indent

    buffer = ""
    for key in arg_obj.__dict__:
        buffer += gp.sprint_varx(key, getattr(arg_obj, key), 0, indent,
                                 col1_width)
    return buffer
Ejemplo n.º 25
0
def svalid_list(var_value,
                valid_values=[],
                var_name=""):
    r"""
    Return an empty string if var_value is a valid list.  Otherwise, return an
    error string.

    Description of arguments:
    var_value                       The value (i.e. list) being validated.
    valid_values                    A list of valid values.  Each element in
                                    the var_value list must be equal to one of
                                    these values to be considered valid.
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    error_message = ""
    if len(var_value) == 0:
        show_blanks = 1
        error_message += "The \"" + get_var_name(var_name)
        error_message += "\" list is empty and is therefore invalid:\n"
        return error_message

    found_error = 0
    display_var_value = list(var_value)
    for ix in range(0, len(var_value)):
        if var_value[ix] not in valid_values:
            found_error = 1
            display_var_value[ix] = var_value[ix] + "*"

    if found_error:
        show_blanks = 1
        error_message += "The list entries marked with \"*\" are not valid:\n"
        error_message += gp.sprint_varx(get_var_name(var_name),
                                        display_var_value, show_blanks)
        error_message += gp.sprint_var(valid_values)
        return error_message

    return ""
Ejemplo n.º 26
0
def valid_date_time(var_value, var_name=None):
    r"""
    The variable value is valid if it can be interpreted as a date/time (e.g. "14:49:49.981", "tomorrow",
    etc.) by the linux date command.

    Description of argument(s):
    var_value                       The value being validated.
    """

    error_message = ""
    rc, out_buf = gc.shell_cmd("date -d '" + str(var_value) + "'", quiet=1, show_err=0, ignore_err=1)
    if rc:
        var_name = get_var_name(var_name)
        error_message += "Invalid date/time value:\n"
        error_message += gp.sprint_varx(var_name, var_value,
                                        gp.blank() | gp.show_type())
        return process_error_message(error_message)

    return process_error_message(error_message)
Ejemplo n.º 27
0
def valid_range(var_value, lower=None, upper=None, *args, **kwargs):
    r"""
    The variable value is valid if it is within the specified range.

    This function can be used with any type of operands where they can have a
    greater than/less than relationship to each other (e.g. int, float, str).

    Description of argument(s):
    var_value                       The value being validated.
    lower                           The lower end of the range.  If not None,
                                    the var_value must be greater than or
                                    equal to lower.
    upper                           The upper end of the range.  If not None,
                                    the var_value must be less than or equal
                                    to upper.
    """

    error_message = ""
    if lower is None and upper is None:
        return process_error_message(error_message)
    if lower is None and var_value <= upper:
        return process_error_message(error_message)
    if upper is None and var_value >= lower:
        return process_error_message(error_message)
    if lower and upper:
        if lower > upper:
            var_name = get_var_name(*args, **kwargs)
            error_message += "Programmer error - the lower value is greater"
            error_message += " than the upper value:\n"
            error_message += gp.sprint_vars(lower, upper, fmt=gp.show_type())
            return process_error_message(error_message)
        if lower <= var_value <= upper:
            return process_error_message(error_message)

    var_name = get_var_name(*args, **kwargs)
    error_message += "The following variable is not within the expected"
    error_message += " range:\n"
    error_message += gp.sprint_varx(var_name, var_value, gp.show_type())
    error_message += "\n"
    error_message += "range:\n"
    error_message += gp.sprint_vars(lower, upper, fmt=gp.show_type(), indent=2)
    return process_error_message(error_message)
Ejemplo n.º 28
0
def valid_dict(var_value, required_keys=[], var_name=None):
    r"""
    The variable value is valid if it is a dictionary containing all of the required keys.

    Description of argument(s):
    var_value                       The value being validated.
    required_keys                   A list of keys which must be found in the dictionary for it to be
                                    considered valid.
    """

    error_message = ""
    missing_keys = list(set(required_keys) - set(var_value.keys()))
    if len(missing_keys) > 0:
        var_name = get_var_name(var_name)
        error_message += "The following dictionary is invalid because it is"
        error_message += " missing required keys:\n"
        error_message += gp.sprint_varx(var_name, var_value,
                                        gp.blank() | gp.show_type())
        error_message += "\n"
        error_message += gp.sprint_var(missing_keys, gp.show_type())
    return process_error_message(error_message)
Ejemplo n.º 29
0
def valid_program(var_value, var_name=None):
    r"""
    The variable value is valid if it contains the name of a program which can be located using the "which"
    command.

    Description of argument(s):
    var_value                       The value being validated.
    """

    error_message = ""
    rc, out_buf = gc.shell_cmd("which " + var_value, quiet=1, show_err=0,
                               ignore_err=1)
    if rc:
        var_name = get_var_name(var_name)
        error_message += "The following required program could not be found"
        error_message += " using the $PATH environment variable:\n"
        error_message += gp.sprint_varx(var_name, var_value, gp.blank())
        PATH = os.environ.get("PATH", "").split(":")
        error_message += "\n"
        error_message += gp.sprint_var(PATH)
    return process_error_message(error_message)
Ejemplo n.º 30
0
def svalid_path(var_value, var_name=""):
    r"""
    Return an empty string if var_value is either a valid file path or
    directory path.  Otherwise, return an error string.

    Description of arguments:
    var_value                       The value being validated.
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    error_message = ""
    if not (os.path.isfile(str(var_value)) or os.path.isdir(str(var_value))):
        error_message = "Invalid path (file or directory does not exist):\n" +\
            gp.sprint_varx(get_var_name(var_name), var_value)

    return error_message
Ejemplo n.º 31
0
def sprint_args(arg_obj,
                indent=0):
    r"""
    sprint_var all of the arguments found in arg_obj and return the result as
    a string.

    Description of arguments:
    arg_obj                         An argument object such as is returned by
                                    the argparse parse_args() method.
    indent                          The number of spaces to indent each line
                                    of output.
    """

    loc_col1_width = gp.col1_width + indent

    buffer = ""

    for key in arg_obj.__dict__:
        buffer += gp.sprint_varx(key, getattr(arg_obj, key), 0, indent,
                                 loc_col1_width)

    return buffer
Ejemplo n.º 32
0
def svalid_integer(var_value,
                   var_name=""):

    r"""
    Return an empty string if var_value is a valid integer.  Otherwise, return
    an error string.

    Description of arguments:
    var_value                       The value being validated.
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    success_message = ""
    error_message = ""
    try:
        if type(int(str(var_value), 0)) is int:
            return success_message
    except ValueError:
        pass

    # If we get to this point, the validation has failed.
    if var_name is "":
        stack_index = 3
        var_name = gp.get_arg_name(0, 1, stack_index)

    show_blanks = 1
    error_message += "Invalid integer value:\n" +\
                     gp.sprint_varx(var_name, var_value, show_blanks)

    return error_message
Ejemplo n.º 33
0
def check_state(match_state,
                invert=0,
                print_string="",
                openbmc_host="",
                openbmc_username="",
                openbmc_password="",
                os_host="",
                os_username="",
                os_password="",
                quiet=None):
    r"""
    Check that the Open BMC machine's composite state matches the specified
    state.  On success, this keyword returns the machine's composite state as a
    dictionary.

    Description of arguments:
    match_state       A dictionary whose key/value pairs are "state field"/
                      "state value".  The state value is interpreted as a
                      regular expression.  Example call from robot:
                      ${match_state}=  Create Dictionary  chassis=^On$
                      ...  bmc=^Ready$
                      ...  boot_progress=^OSStart$
                      ${state}=  Check State  &{match_state}
    invert            If this flag is set, this function will succeed if the
                      states do NOT match.
    print_string      This function will print this string to the console prior
                      to getting the state.
    openbmc_host      The DNS name or IP address of the BMC.
                      This defaults to global ${OPENBMC_HOST}.
    openbmc_username  The username to be used to login to the BMC.
                      This defaults to global ${OPENBMC_USERNAME}.
    openbmc_password  The password to be used to login to the BMC.
                      This defaults to global ${OPENBMC_PASSWORD}.
    os_host           The DNS name or IP address of the operating system.
                      This defaults to global ${OS_HOST}.
    os_username       The username to be used to login to the OS.
                      This defaults to global ${OS_USERNAME}.
    os_password       The password to be used to login to the OS.
                      This defaults to global ${OS_PASSWORD}.
    quiet             Indicates whether status details should be written to the
                      console.  Defaults to either global value of ${QUIET} or
                      to 1.
    """

    quiet = int(gp.get_var_value(quiet, 0))

    grp.rprint(print_string)

    req_states = match_state.keys()
    # Initialize state.
    state = get_state(openbmc_host=openbmc_host,
                      openbmc_username=openbmc_username,
                      openbmc_password=openbmc_password,
                      os_host=os_host,
                      os_username=os_username,
                      os_password=os_password,
                      req_states=req_states,
                      quiet=quiet)
    if not quiet:
        gp.print_var(state)

    match = compare_states(state, match_state)

    if invert and match:
        fail_msg = "The current state of the machine matches the match" +\
                   " state:\n" + gp.sprint_varx("state", state)
        BuiltIn().fail("\n" + gp.sprint_error(fail_msg))
    elif not invert and not match:
        fail_msg = "The current state of the machine does NOT match the" +\
                   " match state:\n" +\
                   gp.sprint_varx("state", state)
        BuiltIn().fail("\n" + gp.sprint_error(fail_msg))

    return state
Ejemplo n.º 34
0
def check_state(match_state,
                invert=0,
                print_string="",
                openbmc_host="",
                openbmc_username="",
                openbmc_password="",
                os_host="",
                os_username="",
                os_password="",
                quiet=None):
    r"""
    Check that the Open BMC machine's composite state matches the specified
    state.  On success, this keyword returns the machine's composite state as a
    dictionary.

    Description of argument(s):
    match_state       A dictionary whose key/value pairs are "state field"/
                      "state value".  The state value is interpreted as a
                      regular expression.  Example call from robot:
                      ${match_state}=  Create Dictionary  chassis=^On$
                      ...  bmc=^Ready$
                      ...  boot_progress=^OSStart$
                      ${state}=  Check State  &{match_state}
    invert            If this flag is set, this function will succeed if the
                      states do NOT match.
    print_string      This function will print this string to the console prior
                      to getting the state.
    openbmc_host      The DNS name or IP address of the BMC.
                      This defaults to global ${OPENBMC_HOST}.
    openbmc_username  The username to be used to login to the BMC.
                      This defaults to global ${OPENBMC_USERNAME}.
    openbmc_password  The password to be used to login to the BMC.
                      This defaults to global ${OPENBMC_PASSWORD}.
    os_host           The DNS name or IP address of the operating system.
                      This defaults to global ${OS_HOST}.
    os_username       The username to be used to login to the OS.
                      This defaults to global ${OS_USERNAME}.
    os_password       The password to be used to login to the OS.
                      This defaults to global ${OS_PASSWORD}.
    quiet             Indicates whether status details should be written to the
                      console.  Defaults to either global value of ${QUIET} or
                      to 1.
    """

    quiet = int(gp.get_var_value(quiet, 0))

    gp.gp_print(print_string)

    try:
        match_state = return_state_constant(match_state)
    except TypeError:
        pass

    req_states = list(match_state.keys())
    # Remove special-case match key from req_states.
    if expressions_key() in req_states:
        req_states.remove(expressions_key())
    # Initialize state.
    state = get_state(openbmc_host=openbmc_host,
                      openbmc_username=openbmc_username,
                      openbmc_password=openbmc_password,
                      os_host=os_host,
                      os_username=os_username,
                      os_password=os_password,
                      req_states=req_states,
                      quiet=quiet)
    if not quiet:
        gp.print_var(state)

    if exit_wait_early_message != "":
        # The exit_wait_early_message has been set by a signal handler so we
        # will exit "successfully".  It is incumbent upon the calling function
        # (e.g. wait_state) to check/clear this variable and to fail
        # appropriately.
        return state

    match = compare_states(state, match_state)

    if invert and match:
        fail_msg = "The current state of the machine matches the match" +\
                   " state:\n" + gp.sprint_varx("state", state)
        BuiltIn().fail("\n" + gp.sprint_error(fail_msg))
    elif not invert and not match:
        fail_msg = "The current state of the machine does NOT match the" +\
                   " match state:\n" +\
                   gp.sprint_varx("state", state)
        BuiltIn().fail("\n" + gp.sprint_error(fail_msg))

    return state
Ejemplo n.º 35
0
def svalid_value(var_value,
                 invalid_values=[],
                 valid_values=[],
                 var_name=""):

    r"""
    Return an empty string if var_value is a valid value.  Otherwise, return
    an error string.

    Description of arguments:
    var_value                       The value being validated.
    invalid_values                  A list of invalid values.  If var_value is
                                    equal to any of these, it is invalid.
                                    Note that if you specify anything for
                                    invalid_values (below), the valid_values
                                    list is not even processed.
    valid_values                    A list of invalid values.  var_value must
                                    be equal to one of these values to be
                                    considered valid.
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    success_message = ""
    error_message = ""
    stack_frame_ix = 3

    len_valid_values = len(valid_values)
    len_invalid_values = len(invalid_values)
    if len_valid_values > 0 and len_invalid_values > 0:
        error_message += "Programmer error - You must provide either an" +\
                         " invalid_values list or a valid_values" +\
                         " list but NOT both.\n" +\
                         gp.sprint_var(invalid_values) +\
                         gp.sprint_var(valid_values)
        return error_message

    show_blanks = 1
    if len_valid_values > 0:
        # Processing the valid_values list.
        if var_value in valid_values:
            return success_message
        if var_name == "":
            var_name = gp.get_arg_name(0, 1, stack_frame_ix)
        error_message += "The following variable has an invalid" +\
                         " value:\n" +\
                         gp.sprint_varx(var_name, var_value, show_blanks) +\
                         "\nIt must be one of the following values:\n" +\
                         gp.sprint_varx("valid_values", valid_values,
                                        show_blanks)
        return error_message

    if len_invalid_values == 0:
        # Assign default value.
        invalid_values = [""]

    # Assertion: We have an invalid_values list.  Processing it now.
    if var_value not in invalid_values:
        return success_message

    if var_name == "":
        var_name = gp.get_arg_name(0, 1, stack_frame_ix)
    error_message += "The following variable has an invalid value:\n" +\
                     gp.sprint_varx(var_name, var_value, show_blanks) +\
                     "\nIt must NOT be one of the following values:\n" +\
                     gp.sprint_varx("invalid_values", invalid_values,
                                    show_blanks)
    return error_message
def sprint_connection(connection,
                      indent=0):
    r"""
    sprint data from the connection object to a string and return it.

    connection                      A connection object which is created by
                                    the SSHlibrary open_connection() function.
    indent                          The number of characters to indent the
                                    output.
    """

    buffer = gp.sindent("", indent)
    buffer += "connection:\n"
    indent += 2
    buffer += gp.sprint_varx("index", connection.index, 0, indent)
    buffer += gp.sprint_varx("host", connection.host, 0, indent)
    buffer += gp.sprint_varx("alias", connection.alias, 0, indent)
    buffer += gp.sprint_varx("port", connection.port, 0, indent)
    buffer += gp.sprint_varx("timeout", connection.timeout, 0, indent)
    buffer += gp.sprint_varx("newline", connection.newline, 0, indent)
    buffer += gp.sprint_varx("prompt", connection.prompt, 0, indent)
    buffer += gp.sprint_varx("term_type", connection.term_type, 0, indent)
    buffer += gp.sprint_varx("width", connection.width, 0, indent)
    buffer += gp.sprint_varx("height", connection.height, 0, indent)
    buffer += gp.sprint_varx("path_separator", connection.path_separator, 0,
                             indent)
    buffer += gp.sprint_varx("encoding", connection.encoding, 0, indent)

    return buffer
Ejemplo n.º 37
0
def svalid_value(var_value,
                 invalid_values=[],
                 valid_values=[],
                 var_name=""):
    r"""
    Return an empty string if var_value is a valid value.  Otherwise, return
    an error string.

    Description of arguments:
    var_value                       The value being validated.
    invalid_values                  A list of invalid values.  If var_value is
                                    equal to any of these, it is invalid.
                                    Note that if you specify anything for
                                    invalid_values (below), the valid_values
                                    list is not even processed.  If you
                                    specify nothing for both invalid_values
                                    and valid_values, invalid_values will be
                                    set to a default value of [""].
    valid_values                    A list of invalid values.  var_value must
                                    be equal to one of these values to be
                                    considered valid.
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    success_message = ""
    error_message = ""

    # Validate this function's arguments.
    len_valid_values = len(valid_values)
    len_invalid_values = len(invalid_values)
    if len_valid_values > 0 and len_invalid_values > 0:
        error_message += "Programmer error - You must provide either an" +\
                         " invalid_values list or a valid_values" +\
                         " list but NOT both.\n" +\
                         gp.sprint_var(invalid_values) +\
                         gp.sprint_var(valid_values)
        return error_message

    show_blanks = 1
    if len_valid_values > 0:
        # Processing the valid_values list.
        if var_value in valid_values:
            return success_message
        error_message += "The following variable has an invalid" +\
                         " value:\n" +\
                         gp.sprint_varx(get_var_name(var_name), var_value,
                                        show_blanks) +\
                         "\nIt must be one of the following values:\n" +\
                         gp.sprint_varx("valid_values", valid_values,
                                        show_blanks)
        return error_message

    if len_invalid_values == 0:
        # Assign default value.
        invalid_values = [""]

    # Assertion: We have an invalid_values list.  Processing it now.
    if var_value not in invalid_values:
        return success_message

    error_message += "The following variable has an invalid value:\n" +\
                     gp.sprint_varx(get_var_name(var_name), var_value,
                                    show_blanks) +\
                     "\nIt must NOT be one of the following values:\n" +\
                     gp.sprint_varx("invalid_values", invalid_values,
                                    show_blanks)
    return error_message
Ejemplo n.º 38
0
def shell_cmd(command_string,
              quiet=None,
              print_output=None,
              show_err=1,
              test_mode=0,
              time_out=None,
              max_attempts=1,
              retry_sleep_time=5,
              allowed_shell_rcs=[0],
              ignore_err=None,
              return_stderr=0,
              fork=0):
    r"""
    Run the given command string in a shell and return a tuple consisting of
    the shell return code and the output.

    Description of argument(s):
    command_string                  The command string to be run in a shell
                                    (e.g. "ls /tmp").
    quiet                           If set to 0, this function will print
                                    "Issuing: <cmd string>" to stdout.  When
                                    the quiet argument is set to None, this
                                    function will assign a default value by
                                    searching upward in the stack for the
                                    quiet variable value.  If no such value is
                                    found, quiet is set to 0.
    print_output                    If this is set, this function will print
                                    the stdout/stderr generated by the shell
                                    command to stdout.
    show_err                        If show_err is set, this function will
                                    print a standardized error report if the
                                    shell command fails (i.e. if the shell
                                    command returns a shell_rc that is not in
                                    allowed_shell_rcs).  Note: Error text is
                                    only printed if ALL attempts to run the
                                    command_string fail.  In other words, if
                                    the command execution is ultimately
                                    successful, initial failures are hidden.
    test_mode                       If test_mode is set, this function will
                                    not actually run the command.  If
                                    print_output is also set, this function
                                    will print "(test_mode) Issuing: <cmd
                                    string>" to stdout.  A caller should call
                                    shell_cmd directly if they wish to have
                                    the command string run unconditionally.
                                    They should call the t_shell_cmd wrapper
                                    (defined below) if they wish to run the
                                    command string only if the prevailing
                                    test_mode variable is set to 0.
    time_out                        A time-out value expressed in seconds.  If
                                    the command string has not finished
                                    executing within <time_out> seconds, it
                                    will be halted and counted as an error.
    max_attempts                    The max number of attempts that should be
                                    made to run the command string.
    retry_sleep_time                The number of seconds to sleep between
                                    attempts.
    allowed_shell_rcs               A list of integers indicating which
                                    shell_rc values are not to be considered
                                    errors.
    ignore_err                      Ignore error means that a failure
                                    encountered by running the command string
                                    will not be raised as a python exception.
                                    When the ignore_err argument is set to
                                    None, this function will assign a default
                                    value by searching upward in the stack for
                                    the ignore_err variable value.  If no such
                                    value is found, ignore_err is set to 1.
    return_stderr                   If return_stderr is set, this function
                                    will process the stdout and stderr streams
                                    from the shell command separately.  In
                                    such a case, the tuple returned by this
                                    function will consist of three values
                                    rather than just two: rc, stdout, stderr.
    fork                            Run the command string asynchronously
                                    (i.e. don't wait for status of the child
                                    process and don't try to get
                                    stdout/stderr).
    """

    # Assign default values to some of the arguments to this function.
    quiet = int(gm.dft(quiet, gp.get_stack_var('quiet', 0)))
    print_output = int(gm.dft(print_output, not quiet))
    show_err = int(show_err)
    global_ignore_err = gp.get_var_value(ignore_err, 1)
    stack_ignore_err = gp.get_stack_var('ignore_err', global_ignore_err)
    ignore_err = int(gm.dft(ignore_err, gm.dft(stack_ignore_err, 1)))

    err_msg = gv.valid_value(command_string)
    if err_msg != "":
        raise ValueError(err_msg)

    if not quiet:
        gp.print_issuing(command_string, test_mode)

    if test_mode:
        if return_stderr:
            return 0, "", ""
        else:
            return 0, ""

    # Convert each list entry to a signed value.
    allowed_shell_rcs = fa.source_to_object(allowed_shell_rcs)
    allowed_shell_rcs = [gm.to_signed(x) for x in allowed_shell_rcs]

    if return_stderr:
        stderr = subprocess.PIPE
    else:
        stderr = subprocess.STDOUT

    shell_rc = 0
    out_buf = ""
    err_buf = ""
    # Write all output to func_history_stdout rather than directly to stdout.
    # This allows us to decide what to print after all attempts to run the
    # command string have been made.  func_history_stdout will contain the
    # complete stdout history from the current invocation of this function.
    func_history_stdout = ""
    for attempt_num in range(1, max_attempts + 1):
        sub_proc = subprocess.Popen(command_string,
                                    bufsize=1,
                                    shell=True,
                                    executable='/bin/bash',
                                    stdout=subprocess.PIPE,
                                    stderr=stderr)
        out_buf = ""
        err_buf = ""
        # Output from this loop iteration is written to func_stdout for later
        # processing.
        func_stdout = ""
        if fork:
            break
        command_timed_out = False
        if time_out is not None:
            # Designate a SIGALRM handling function and set alarm.
            signal.signal(signal.SIGALRM, shell_cmd_timed_out)
            signal.alarm(time_out)
        try:
            if return_stderr:
                for line in sub_proc.stderr:
                    try:
                        err_buf += line
                    except TypeError:
                        line = line.decode("utf-8")
                        err_buf += line
                    if not print_output:
                        continue
                    func_stdout += line
            for line in sub_proc.stdout:
                try:
                    out_buf += line
                except TypeError:
                    line = line.decode("utf-8")
                    out_buf += line
                if not print_output:
                    continue
                func_stdout += line
        except IOError:
            command_timed_out = True
        sub_proc.communicate()
        shell_rc = sub_proc.returncode
        # Restore the original SIGALRM handler and clear the alarm.
        signal.signal(signal.SIGALRM, original_sigalrm_handler)
        signal.alarm(0)
        if shell_rc in allowed_shell_rcs:
            break
        err_msg = "The prior shell command failed.\n"
        if quiet:
            err_msg += gp.sprint_var(command_string)
        if command_timed_out:
            err_msg += gp.sprint_var(command_timed_out)
            err_msg += gp.sprint_var(time_out)
            err_msg += gp.sprint_varx("child_pid", sub_proc.pid)
        err_msg += gp.sprint_var(attempt_num)
        err_msg += gp.sprint_var(shell_rc, gp.hexa())
        err_msg += gp.sprint_var(allowed_shell_rcs, gp.hexa())
        if not print_output:
            if return_stderr:
                err_msg += "err_buf:\n" + err_buf
            err_msg += "out_buf:\n" + out_buf
        if show_err:
            func_stdout += gp.sprint_error_report(err_msg)
        func_history_stdout += func_stdout
        if attempt_num < max_attempts:
            func_history_stdout += gp.sprint_issuing("time.sleep(" +
                                                     str(retry_sleep_time) +
                                                     ")")
            time.sleep(retry_sleep_time)

    if shell_rc not in allowed_shell_rcs:
        func_stdout = func_history_stdout

    gp.gp_print(func_stdout)

    if shell_rc not in allowed_shell_rcs:
        if not ignore_err:
            if robot_env:
                BuiltIn().fail(err_msg)
            else:
                raise ValueError("The prior shell command failed.\n")

    if return_stderr:
        return shell_rc, out_buf, err_buf
    else:
        return shell_rc, out_buf
Ejemplo n.º 39
0
def svalid_range(var_value,
                 valid_range=[],
                 var_name=""):
    r"""
    Return an empty string if var_value is within the range.  Otherwise,
    return an error string.

    Description of arguments:
    var_value                       The value being validated.  This value
                                    must be an integer.
    valid_range                     A list comprised of one or two elements
                                    which are the lower and upper ends of a
                                    range.  These values must be integers
                                    except where noted.  Valid specifications
                                    may be of the following forms: [lower,
                                    upper], [lower] or [None, upper].
    var_name                        The name of the variable whose value is
                                    passed in var_value.  This parameter is
                                    normally unnecessary as this function can
                                    figure out the var_name.  This is provided
                                    for Robot callers.  In this scenario, we
                                    are unable to get the variable name
                                    ourselves.
    """

    error_message = ""

    # Validate this function's parms:
    # First, ensure that the value is an integer.
    error_message = svalid_integer(var_value, var_name)
    if not error_message == "":
        return error_message
    var_value = int(var_value)

    len_valid_range = len(valid_range)
    if len_valid_range == 0 or len_valid_range > 2:
        error_message += "Programmer error - For the valid_range parameter," +\
                         " you must provide a list consisting of one or two" +\
                         " elements.\n" +\
                         gp.sprint_var(valid_range)
        return error_message

    if len_valid_range == 1 or valid_range[0] is not None:
        # Make sure lower valid_range value is an integer.
        error_message = svalid_integer(valid_range[0], "valid_range[0]")
        if not error_message == "":
            error_message = "Programmer error:\n" + error_message
            return error_message
    if valid_range[0] is not None:
        valid_range[0] = int(valid_range[0])
    if len_valid_range == 2:
        # Make sure upper valid_range value is an integer.
        error_message = svalid_integer(valid_range[1], "valid_range[1]")
        if not error_message == "":
            error_message = "Programmer error:\n" + error_message
            return error_message
        valid_range[1] = int(valid_range[1])
        if valid_range[0] is not None and valid_range[0] > valid_range[1]:
            error_message = "Programmer error - In the following range, the" +\
                            " lower limit is greater than the upper" +\
                            " limit:\n" + gp.sprint_varx("valid_range",
                                                         valid_range)
            return error_message

    if len_valid_range == 1:
        if var_value < valid_range[0]:
            error_message += "The following variable is not within the" +\
                             " expected range:\n" +\
                             gp.sprint_varx(get_var_name(var_name),
                                            var_value) +\
                             gp.sprint_varx("valid_range",
                                            str(valid_range[0]) + "..")
            return error_message
        return error_message

    if valid_range[0] is None:
        if var_value > valid_range[1]:
            error_message += "The following variable is not within the" +\
                             " expected range:\n" +\
                             gp.sprint_varx(get_var_name(var_name),
                                            var_value) +\
                             gp.sprint_varx("valid_range",
                                            ".." + str(valid_range[1]))
            return error_message

    if var_value < valid_range[0] or var_value > valid_range[1]:
        error_message += "The following variable is not within the expected" +\
                         " range:\n" +\
                         gp.sprint_varx(get_var_name(var_name), var_value) +\
                         gp.sprint_varx("valid_range",
                                        str(valid_range[0]) + ".."
                                        + str(valid_range[1]))
        return error_message

    return error_message