def list_sum(*argv, **kwargs):
    """
    Summarise items in provided list

    Arguments:
    - argv: list of item for summarise

    Options:
        - type: list item type (int if omitted)

        Note: All types provided by this lib supported

    Returns sum number in 'type' format

    """
    _type_name = kwargs.get('type', 'int')
    _type = type_factory(_type_name)
    _result: _type = 0
    try:
        for _list in argv:
            if isinstance(_list, (list, tuple)):
                _result += sum([_type(_item) for _item in _list])
            else:
                _number = _type(_list)
                _result += _number
    except (ValueError, IndexError) as e:
        raise FrameworkError(f"ROBOT_MATH.LIST_SUM: {e}")
    else:
        return _result
Beispiel #2
0
    def __init__(self, usage, name=None, version=None, arg_limits=None,
                 validator=None, env_options=None, auto_help=True,
                 auto_version=True, auto_pythonpath=True,
                 auto_argumentfile=True):
        """Available options and tool name are read from the usage.

        Tool name is got from the first row of the usage. It is either the
        whole row or anything before first ' -- '.
        """
        if not usage:
            raise FrameworkError('Usage cannot be empty')
        self.name = name or usage.splitlines()[0].split(' -- ')[0].strip()
        self.version = version or get_full_version()
        self._usage = usage
        self._arg_limit_validator = ArgLimitValidator(arg_limits)
        self._validator = validator
        self._auto_help = auto_help
        self._auto_version = auto_version
        self._auto_pythonpath = auto_pythonpath
        self._auto_argumentfile = auto_argumentfile
        self._env_options = env_options
        self._short_opts = ''
        self._long_opts = []
        self._multi_opts = []
        self._flag_opts = []
        self._short_to_long = {}
        self._expected_args = ()
        self._create_options(usage)
Beispiel #3
0
    def __init__(self, usage, name=None, version=None, arg_limits=None,
                 validator=None, env_options=None, auto_help=True,
                 auto_version=True, auto_pythonpath='DEPRECATED',
                 auto_argumentfile=True):
        """Available options and tool name are read from the usage.

        Tool name is got from the first row of the usage. It is either the
        whole row or anything before first ' -- '.
        """
        if not usage:
            raise FrameworkError('Usage cannot be empty')
        self.name = name or usage.splitlines()[0].split(' -- ')[0].strip()
        self.version = version or get_full_version()
        self._usage = usage
        self._arg_limit_validator = ArgLimitValidator(arg_limits)
        self._validator = validator
        self._auto_help = auto_help
        self._auto_version = auto_version
        # TODO: Change DeprecationWarning to more loud UserWarning in RF 5.1.
        if auto_pythonpath == 'DEPRECATED':
            auto_pythonpath = False
        else:
            warnings.warn("ArgumentParser option 'auto_pythonpath' is deprecated "
                          "since Robot Framework 5.0.", DeprecationWarning)
        self._auto_pythonpath = auto_pythonpath
        self._auto_argumentfile = auto_argumentfile
        self._env_options = env_options
        self._short_opts = ''
        self._long_opts = []
        self._multi_opts = []
        self._flag_opts = []
        self._short_to_long = {}
        self._expected_args = ()
        self._create_options(usage)
Beispiel #4
0
 def _import(self, import_setting):
     try:
         action = {'Library': self._import_library,
                   'Resource': self._import_resource,
                   'Variables': self._import_variables}[import_setting.type]
         action(import_setting, self.variables.current)
     except KeyError:
         raise FrameworkError("Invalid import setting: %s" % import_setting)
Beispiel #5
0
 def __setitem__(self, key, item):
     if not is_string(key) and not isinstance(key, tuple):
         raise FrameworkError('Invalid key for ImportCache')
     key = self._norm_path_key(key)
     if key not in self._keys:
         self._keys.append(key)
         self._items.append(item)
     else:
         self._items[self._keys.index(key)] = item
 def run(self, runnable, args=None, kwargs=None):
     if self.error:
         raise DataError(self.error)
     if not self.active:
         raise FrameworkError('Timeout is not active')
     timeout = self.time_left()
     if timeout <= 0:
         raise TimeoutError(self.get_message())
     executable = lambda: runnable(*(args or ()), **(kwargs or {}))
     return Timeout(timeout, self._timeout_error).execute(executable)
Beispiel #7
0
 def _get_output_extension(self, extension, file_type):
     if extension:
         return extension
     if file_type in ['Output', 'XUnit']:
         return '.xml'
     if file_type in ['Log', 'Report']:
         return '.html'
     if file_type == 'DebugFile':
         return '.txt'
     raise FrameworkError(f"Invalid output file type '{file_type}'.")
Beispiel #8
0
 def _get_output_extension(self, ext, type_):
     if ext != '':
         return ext
     if type_ in ['Output', 'XUnit']:
         return '.xml'
     if type_ in ['Log', 'Report']:
         return '.html'
     if type_ == 'DebugFile':
         return '.txt'
     raise FrameworkError("Invalid output file type: %s" % type_)
 def _unescape_opts_and_args(self, opts, args):
     try:
         escape_strings = opts['escape']
     except KeyError:
         raise FrameworkError("No 'escape' in options")
     escapes = self._get_escapes(escape_strings)
     for name, value in opts.items():
         if name != 'escape':
             opts[name] = self._unescape(value, escapes)
     return opts, [self._unescape(arg, escapes) for arg in args]
Beispiel #10
0
 def _unescape_opts_and_args(self, opts, args, escape_opt):
     try:
         escape_strings = opts[escape_opt]
     except KeyError:
         raise FrameworkError("No escape option '%s' in given options")
     escapes = self._get_escapes(escape_strings)
     for name, value in opts.items():
         if name != escape_opt:
             opts[name] = self._unescape(value, escapes)
     args = [self._unescape(arg, escapes) for arg in args]
     return opts, args
Beispiel #11
0
 def run(self, runnable, args=None, kwargs=None):
     if self.error:
         raise DataError(self.error)
     if not self.active:
         raise FrameworkError('Timeout is not active')
     timeout = self.time_left()
     error = TimeoutError(self._timeout_error,
                          test_timeout=isinstance(self, TestTimeout))
     if timeout <= 0:
         raise error
     executable = lambda: runnable(*(args or ()), **(kwargs or {}))
     return Timeout(timeout, error).execute(executable)
Beispiel #12
0
 def _check_args(self, args):
     if not self._arg_limits:
         raise FrameworkError('No argument information specified.')
     minargs, maxargs = self._arg_limits
     if minargs <= len(args) <= maxargs:
         return
     minend = plural_or_not(minargs)
     if minargs == maxargs:
         exptxt = "%d argument%s" % (minargs, minend)
     elif maxargs != sys.maxint:
         exptxt = "%d to %d arguments" % (minargs, maxargs)
     else:
         exptxt = "at least %d argument%s" % (minargs, minend)
     raise DataError("Expected %s, got %d." % (exptxt, len(args)))
 def _unescape_opts_and_args(self, opts, args):
     from robot.output import LOGGER
     with LOGGER.cache_only:
         LOGGER.warn("Option '--escape' is deprecated. Use console escape "
                     "mechanism instead.")
     try:
         escape_strings = opts['escape']
     except KeyError:
         raise FrameworkError("No 'escape' in options")
     escapes = self._get_escapes(escape_strings)
     for name, value in opts.items():
         if name != 'escape':
             opts[name] = self._unescape(value, escapes)
     return opts, [self._unescape(arg, escapes) for arg in args]
Beispiel #14
0
 def run(self, runnable, args=None, kwargs=None):
     if self.error:
         raise DataError(self.error)
     if not self.active:
         raise FrameworkError('Timeout is not active')
     timeout = self.time_left()
     if timeout <= 0:
         raise TimeoutError(self.get_message())
     runner = ThreadedRunner(runnable, args, kwargs)
     if runner.run_in_thread(timeout):
         return runner.get_result()
     try:
         runner.stop_thread()
     except:
         raise TimeoutError('Stopping keyword after %s failed: %s' %
                            (self.type.lower(), utils.get_error_message()))
     raise TimeoutError(self._get_timeout_error())
def packet_operation(expression_str, deviation_str=None, reason=None):
    """
    Provide logical and mathematical operation with packet

    - expression_str: operand1 operation operand2

    | Example | Comments |
    | 1M * 2 | Multiple Packet size 2M |
    | 1M + 10K | Return packet size 1.01M |
    | 1M + 10% | Return packet size 1.1M |

    Options:
    - deviation: add on for comparison verifications (eq, ,gt, lt, ge, le)

    Equality Examples:

    | Operand1  Operation  Operand2 | Deviation   | Result    | Comments  |
    | 10M  == 12M                   | 25%       | TRUE      | (10M - 25%) < 12M < (10M + 25%)   |
    | 10M  == 12M                   | 0.25       | TRUE      | (10M - 25%) < 12M < (10M + 25%)   |
    | 10M  == 12M                   | -25%       | FALSE      | (10M - 25%) < 12M < 10M   |
    | 10M  == 12M                   | +25%      | TRUE      | 10M < 12M < (10M + 25%)   |

    - reason: Custom fail reason

    return: TRUE/FALSE for logical operation and value for math operation
    """
    try:

        logger.trace(
            f"{expression_str}{', ' + deviation_str  if deviation_str else ''}"
        )
        _deviation = format_factory(deviation_str,
                                    Percent) if deviation_str else None
        operand1, operation, operand2 = _parse_line(expression_str, DataPacket,
                                                    Percent)
        result = _type_evaluation(operand1=operand1,
                                  operand2=operand2,
                                  operation=operation,
                                  deviation=_deviation,
                                  special_eq=packet_eq)
        assert result is not False, f"{operand1} {operation.__name__} {operand2} False" if reason is None else reason
        return result
    except AssertionError as e:
        raise e
    except Exception as e:
        raise FrameworkError(e)
def time_operation(expression_str, deviation_str=None, reason=None):
    """
        RF_MATH_OPERATION

        - expression: operand1 operation operand2

        | Example | Comments |
        | 1h * 3 | Return 3h |
        | 1h + 10% | Return 1h 6m |

    - deviation: add on for comparison verifications (eq, ,gt, lt, ge, le)

        Equality Examples:
            | Operand1  | Operand2  | Percent   | Result    | Comments  |
            | 10m       | 12m       | 25%       | TRUE      | 10m - 25% < 12m < 10m + 25%   |
            | 10m       | 12m       | -25%       | FALSE      | 10m - 25% < 12m < 10m   |
            | 10m       | 12m       | +25%       | TRUE      | 10m < 12m < 10m + 25%   |

    - reason: Custom fail reason

        return: TRUE/FALSE for logical operation and value for math operation
        """
    try:
        logger.trace(
            f"{expression_str}{', ' + deviation_str if deviation_str else ''}")
        _deviation = format_factory(deviation_str,
                                    Percent) if deviation_str else None
        operand1, operation, operand2 = _parse_line(expression_str, float,
                                                    TimeInterval, Percent)
        result = _type_evaluation(operand1=operand1,
                                  operand2=operand2,
                                  operation=operation,
                                  deviation=_deviation,
                                  special_eq=robot_time_eq)
        assert result is not False, f"{operand1} {operation.__name__} {operand2} False" if reason is None else reason
        return result
    except AssertionError as e:
        raise e
    except Exception as e:
        raise FrameworkError(e)
Beispiel #17
0
    def __init__(self, usage, version=None, arg_limits=None):
        """Available options and tool name are read from the usage.

        Tool name is got from the first row of the usage. It is either the
        whole row or anything before first ' -- '.

        See for example 'runner.py' and 'rebot.py' for examples.
        """
        if not usage:
            raise FrameworkError('Usage cannot be empty')
        self._usage = usage
        self._name = usage.splitlines()[0].split(' -- ')[0].strip()
        self._version = version
        self._arg_limits = arg_limits
        self._short_opts = ''
        self._long_opts = []
        self._multi_opts = []
        self._toggle_opts = []
        self._names = []
        self._short_to_long = {}
        self._expected_args = ()
        self._parse_usage(usage)
Beispiel #18
0
 def _raise_option_multiple_times_in_usage(self, opt):
     raise FrameworkError("Option '%s' multiple times in usage" % opt)
Beispiel #19
0
 def _raise_version(self):
     if not self._version:
         raise FrameworkError('Version not set')
     raise Information('%s %s' % (self._name, self._version))