Ejemplo n.º 1
0
    def save_environment(self):
        environment = {}
        environment['id'] = 'Robot Framework'
        environment['name'] = socket.getfqdn()
        environment['url'] = 'http://' + socket.getfqdn() + ':8000'
        included_args = self.AllureProperties.get_property(
            'robot.cli.arguments.included')
        rf_args = sys.argv[1:]
        if included_args:
            rf_args = []
            for index, arg in enumerate(sys.argv):
                if arg in included_args:
                    rf_args.append(sys.argv[index])
                    if index < len(
                            sys.argv) and not sys.argv[index +
                                                       1].startswith('-'):
                        rf_args.append(sys.argv[index + 1])
        env_dict = (\
                    {'Robot Framework Full Version': get_full_version()},\
                    {'Robot Framework Version': get_version()},\
                    {'Interpreter': get_interpreter()},\
                    {'Python version': sys.version.split()[0]},\
                    {'Allure Adapter version': VERSION},\
                    {'Robot Framework CLI Arguments': rf_args},\
                    {'Robot Framework Hostname': socket.getfqdn()},\
                    {'Robot Framework Platform': sys.platform}\
                    )

        for key in env_dict:
            self.AllureImplc.environment.update(key)

        self.AllureImplc.logdir = self.AllureProperties.get_property(
            'allure.cli.logs.xml')
        self.AllureImplc.store_environment(environment)
Ejemplo n.º 2
0
class Xtimer(DutShell):
    """Interface to the a node with xtimer_cli firmware."""

    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
    ROBOT_LIBRARY_VERSION = get_version()

    FW_ID = 'xtimer_cli'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def is_connected_to_board(self):
        """Checks if board is connected."""
        return self.i2c_get_id()["data"] == [self.FW_ID]

    def xtimer_now(self):
        """Get current timer ticks."""
        return self.send_cmd('xtimer_now')

    def get_metadata(self):
        """Get the metadata of the firmware."""
        return self.send_cmd('get_metadata')

    def get_command_list(self):
        """List of all commands."""
        cmds = list()
        cmds.append(self.get_metadata)
        cmds.append(self.xtimer_now)
        return cmds
Ejemplo n.º 3
0
class mysqlLib(object):

    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()

    def mysqlName(self, a):
        print(a)
Ejemplo n.º 4
0
class PhilipAPI(Phil):
    """Robot framework wrapper for PHiLIP"""
    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
    ROBOT_LIBRARY_VERSION = get_version()

    def __init__(self, port, baudrate):
        super().__init__(port, baudrate)

    def setup_uart(self,
                   mode=0,
                   baudrate=115200,
                   databits=serial.EIGHTBITS,
                   parity=serial.PARITY_NONE,
                   stopbits=serial.STOPBITS_ONE,
                   rts=True):
        """Setup tester's UART."""
        ret = list()
        mode = int(mode)
        assert mode >= 0 and mode < 3, "Invalid mode setting for the if_type"
        ret.append(self.write_reg('uart.mode.if_type', mode))
        ret.append(self.write_reg('uart.baud', int(baudrate)))

        # setup UART control register
        if databits == serial.SEVENBITS:
            ret.append(self.write_reg('uart.mode.data_bits', 1))

        if parity == serial.PARITY_EVEN:
            ret.append(self.write_reg('uart.mode.parity', 1))
        elif parity == serial.PARITY_ODD:
            ret.append(self.write_reg('uart.mode.parity', 2))

        if stopbits == serial.STOPBITS_TWO:
            ret.append(self.write_reg('uart.mode.stop_bits', 1))
        # invert RTS level as it is a low active signal
        if not rts:
            ret.append(self.write_reg('uart.mode.rts', 1))

        ret.append(self.write_reg('uart.mode.init', 0))

        # apply changes
        ret.append(self.execute_changes())
        return ret

    def get_counters(self):
        """Get rx/tx counters."""
        ret = list()
        ret.append(self.read_reg('uart.rx_count'))
        ret.append(self.read_reg('uart.tx_count'))
        return ret

    def get_error_flags(self):
        """Get error flags."""
        ret = list()
        ret.append(self.read_reg('uart.status.pe'))
        ret.append(self.read_reg('uart.status.fe'))
        ret.append(self.read_reg('uart.status.nf'))
        ret.append(self.read_reg('uart.status.ore'))
        return ret
Ejemplo n.º 5
0
class XiaoFish(object):
    '''
    '''
    ROBOT_LIBRARY_SCOPE = 'TEST_SUITE'
    ROBOT_LIBRARY_VERSION = get_version()
    def __init__(self):
        ''''''
        self._pkt_streamlist_cmdstring = []
        self._pkt_kws = self._lib_kws = None
        self._pkt_class = rfbase.PacketBase()

    def get_keyword_names(self):
        return self._get_library_keywords() + self._get_pkt_keywords()

    def _get_library_keywords(self):
        if self._lib_kws is None:
            self._lib_kws = self._get_keywords(self, ['get_keyword_names'])
        return self._lib_kws

    def _get_keywords(self, source, excluded):
        return [name for name in dir(source)
                if self._is_keyword(name, source, excluded)]

    def _is_keyword(self, name, source, excluded):
        return (name not in excluded and
                not name.startswith('_') and
                name != 'get_keyword_names' and
                inspect.ismethod(getattr(source, name)))

    def _get_pkt_keywords(self):
        if self._pkt_kws is None:
            pkt = self._pkt_class
            excluded = ['get_packet_list','empty_packet_list','get_packet_list_ixiaapi']
            self._pkt_kws = self._get_keywords(pkt, excluded)
        return self._pkt_kws

    def __getattr__(self, name):
        if name not in self._get_pkt_keywords():
            raise AttributeError(name)
        # This makes it possible for Robot to create keyword
        # handlers when it imports the library.
        return getattr(self._pkt_class, name)

    def get_stream_from_pcapfile(self,filename):
        '''read pcap file and return bytes stream'''
        if not os.path.isfile(filename):
            logger.info('%s is not a file' % filename)
            raise AssertionError('%s is not file or path error' % filename)
        with open(filename,'rb') as handle:
            return handle.read()

    def build_stream(self):
        ''''''
        self._pkt_streamlist_cmdstring = self._pkt_class.get_packet_list()
        self._pkt_class.empty_packet_list()
        return self._pkt_streamlist_cmdstring
Ejemplo n.º 6
0
class ExcelLib:

    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()

    def Mul(self, a, b):
        logger.info("app/login")
        return int(a) * int(b)

    def Div(self, a, b):
        return float(a / b, 2)
Ejemplo n.º 7
0
class SearchKeywords(object):
    ROBOT_LIBRARY_VERSION = get_version()
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'

    def __init__(self):
        self.browser = None
        self.home_page = None
        self.search_results_page = None

        self.listener = RobotListener(
            'selenium.webdriver.remote.remote_connection')
        self.ROBOT_LIBRARY_LISTENER = self.listener

    def launch_browser(self,
                       name='firefox',
                       is_remote=False,
                       enable_screenshot=False):
        self.browser = Browser(name=name, is_remote=is_remote)

        if str(enable_screenshot).lower() not in ('false', 'no'):
            self.listener.enable_screenshot(self.browser)

    def close_browser(self):
        if self.browser:
            self.browser.close()

        self.listener.disable_screenshot()

    def i_am_on_home_page(self, url):
        self.home_page = BingHomePage(url)

    def i_search_with_keyword(self, keyword):
        self.search_results_page = \
            self.home_page.search_with_keyword(
                keyword
            )

    def i_get_the_first_search_record_containing_keyword(self, keyword):
        assert isinstance(
            self.search_results_page,
            SearchResultsPage), 'The search results page is displayed'

        bag_of_keywords = str.split(
            self.search_results_page.text_of_first_record.lower())

        if (bag_of_keywords[0] in keyword.lower()) or (bag_of_keywords[-1]
                                                       in keyword.lower()):
            logger.info('Succeed on searching keyword within bing.com',
                        # html=True
                        )
        else:
            logger.error('"{}" not in "{}"'.format(
                keyword, self.search_results_page.text_of_first_record),
                         html=True)
Ejemplo n.º 8
0
    def run_test_body(self, context, test):
        from robot import version

        IS_ROBOT_4_ONWARDS = not version.get_version().startswith("3.")
        if IS_ROBOT_4_ONWARDS:
            from robot.running.bodyrunner import BodyRunner  # noqa

            BodyRunner(context, templated=False).run(test.body)
        else:
            from robot.running.steprunner import StepRunner  # noqa

            StepRunner(context, False).run_steps(test.keywords.normal)
Ejemplo n.º 9
0
class PhilipAPI(LLMemMapIf):

    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
    ROBOT_LIBRARY_VERSION = get_version()

    def __init__(self, port, baudrate):
        super(PhilipAPI, self).__init__(PHILIP_MEM_MAP_PATH, 'serial', port,
                                        baudrate)

    def reset_dut(self):
        ret = list()
        ret.append(self.write_reg('sys.cr', 0xff))
        ret.append(self.execute_changes())
        sleep(1)
        ret.append(self.write_reg('sys.cr', 0x00))
        ret.append(self.execute_changes())
        sleep(1)
        return ret

    def setup_uart(self,
                   mode=0,
                   baudrate=115200,
                   parity=serial.PARITY_NONE,
                   stopbits=serial.STOPBITS_ONE,
                   rts=True):
        '''Setup tester's UART.'''
        ret = list()
        ret.append(self.write_reg('uart.mode', int(mode)))

        ret.append(self.write_reg('uart.baud', int(baudrate)))

        # setup UART control register
        ctrl = 0
        if parity == serial.PARITY_EVEN:
            ctrl = ctrl | 0x02
        elif parity == serial.PARITY_ODD:
            ctrl = ctrl | 0x04

        if stopbits == serial.STOPBITS_TWO:
            ctrl = ctrl | 0x01
        # invert RTS level as it is a low active signal
        if not rts:
            ctrl = ctrl | 0x08

        ret.append(self.write_reg('uart.ctrl', ctrl))

        # reset status register
        ret.append(self.write_reg('uart.status', 0x00))

        # apply changes
        ret.append(self.execute_changes())
        sleep(1)
        return ret
 def __init__(self, cfg='debug.rdb', *bps):
     from robot import version
     ROBOT_VERSION = version.get_version()
     if ROBOT_VERSION < '2.1':
         sys.__stderr__.write("Robot 2.1 is required for RDB(robot debug).\n")
         sys.exit(0)
     
     self.debuger = RobotDebuger(cfg)
     self.debuger.run()
     self.call_stack = []
     self.debugCtx = self.debuger.debugCtx
     self.logger = logging.getLogger("rbt.lis")
     for e in bps:
         self.debuger.add_breakpoint(e)
Ejemplo n.º 11
0
 def output_error_in_robot_log(self, e):
     import traceback
     from robot.output import LOGGER
     from robot import version
     ROBOT_VERSION = version.get_version()
     if ROBOT_VERSION >= '2.1':
         syslog = LOGGER
         from robot.output.loggerhelper import Message
         syslog.message(
             Message("%s:%s" % ('Import Keyword Error', e.message),
                     'ERROR'))
         syslog.message(Message(traceback.format_exc(), 'ERROR'))
     else:
         syslog = LOGGER
         syslog.error("*ERROR* %s:%s" % ('Import Keyword Error', e.message))
         syslog.error(traceback.format_exc())
Ejemplo n.º 12
0
class Collections(_List, _Dictionary):

    """A test library providing keywords for handling lists and dictionaries.

    `Collections` is Robot Framework's standard library that provides a
    set of keywords for handling Python lists and dictionaries. This
    library has keywords, for example, for modifying and getting
    values from lists and dictionaries (e.g. `Append To List`, `Get
    From Dictionary`) and for verifying their contents (e.g. `Lists
    Should Be Equal`, `Dictionary Should Contain Value`).

    Following keywords from the BuiltIn library can also be used with
    lists and dictionaries:
    | *Keyword Name*               | *Applicable With* |
    | `Create List`                | lists |
    | `Get Length`                 | both  |
    | `Length Should Be`           | both  |
    | `Should Be Empty`            | both  |
    | `Should Not Be Empty`        | both  |
    | `Should Contain`             | lists |
    | `Should Not Contain`         | lists |
    | `Should Contain X Times`     | lists |
    | `Should Not Contain X Times` | lists |
    | `Get Count`                  | lists |

    All list keywords expect a scalar variable (e.g. ${list}) as an
    argument.  It is, however, possible to use list variables
    (e.g. @{list}) as scalars simply by replacing '@' with '$'.

    List keywords that do not alter the given list can also be used
    with tuples, and to some extend also with other iterables.
    `Convert To List` can be used to convert tuples and other iterables
    to lists.

    -------

    List related keywords use variables in format ${Lx} in their examples,
    which means a list with as many alphabetic characters as specified by 'x'.
    For example ${L1} means ['a'] and ${L3} means ['a', 'b', 'c'].

    Dictionary keywords use similar ${Dx} variables. For example ${D1} means
    {'a': 1} and ${D3} means {'a': 1, 'b': 2, 'c': 3}.

    --------
    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()
Ejemplo n.º 13
0
class TestData():
    """Interface to the node."""

    ROBOT_LIBRARY_SCOPE = "TEST"
    ROBOT_LIBRARY_VERSION = get_version()

    def get_empty(self):
        return ""

    def get_long_list(self):
        return [i for i in range(0, 500)]

    def get_long_dict(self):
        return {f"{str(i)}": i**2 for i in range(0, 500)}

    def get_long_string(self):
        return ''.join(random.choices("HEYDSLKJSDFLKJD", k=1000))
    def save_environment(self):
        environment = {}    
        environment['id'] = 'Robot Framework'
        environment['name'] = socket.getfqdn()
        environment['url']= 'http://'+socket.getfqdn()+':8000'
        
        env_dict = (\
                    {'Robot Framework Full Version': get_full_version()},\
                    {'Robot Framework Version': get_version()},\
                    {'Interpreter': get_interpreter()},\
                    {'Python version': sys.version.split()[0]},\
                    {'Allure Adapter version': VERSION},\
                    {'Robot Framework CLI Arguments': sys.argv[1:]},\
                    {'Robot Framework Hostname': socket.getfqdn()},\
                    {'Robot Framework Platform': sys.platform}\
                    )

        for key in env_dict:
            self.AllureImplc.environment.update(key)
        
        self.AllureImplc.logdir = self.AllureProperties.get_property('allure.cli.logs.xml')
        self.AllureImplc.store_environment(environment)
Ejemplo n.º 15
0
    def close(self): 

        environment = {}    
        environment['id'] = 'Robot Framework'
        environment['name'] = socket.getfqdn()
        environment['url']= 'http://'+socket.getfqdn()+':8000'
        
        env_dict = (\
                    {'Robot Framework Full Version': get_full_version()},\
                    {'Robot Framework Version': get_version()},\
                    {'Interpreter': get_interpreter()},\
                    {'Python version': sys.version.split()[0]},\
                    {'Allure Adapter version': VERSION},\
                    {'Robot Framework CLI Arguments': sys.argv[1:]},\
                    {'Robot Framework Hostname': socket.getfqdn()},\
                    {'Robot Framework Platform': sys.platform}\
                    )

        for key in env_dict:
            self.AllureImplc.environment.update(key)
        self.AllureImplc.store_environment(environment)        

        # store the Allure properties
        #
        with self.AllureImplc._attachfile('allure.properties') as f:

            li = self.AllureProperties
            lilen = int(len(self.AllureProperties))
            
            for i in range(lilen):
                if i < len(li):
                    key = list(li[i].keys())[0]
                    value = list(li[i].values())[0]
                    f.write(key+'='+value+'\n')
    
        f.close()
        return
Ejemplo n.º 16
0
class Psw(object):
    ROBOT_LIBRARY_SCOPE = 'TEST_SUITE'
    ROBOT_LIBRARY_VERSION = get_version()

    keywords = [
        'setup connect', '*IDN', 'APPLy', 'OUTPut', 'SYSTem', 'MEASure',
        'SOURce'
    ]

    def __init__(self, uart_port, baudrate=9600):
        self._conn = self._get_connection(uart_port, baudrate)

    #def open_connection(self,)

    def _get_connection(self, *args):
        """Can be overridden to use a custom connection."""
        self._conn = PswRun(*args)
        return self._conn

    def get_keyword_names(self):
        return Psw.keywords

    def __getattr__(self, name):
        return getattr(self._conn or self._get_connection(), name)
Ejemplo n.º 17
0
        if opt in ('-q','--quit'):
            verbosity = 0
        if opt in ('-v', '--verbose'):
            verbosity = 2
        if opt in ('-d', '--doc'):
            docs = 1
            verbosity = 2
    return docs, verbosity


def usage_exit(msg=None):
    print __doc__
    if msg is None:
        rc = 251
    else:
        print '\nError:', msg
        rc = 252
    sys.exit(rc)


if __name__ == '__main__':
    print "Testing with Robot version: %s" % get_version()
    docs, vrbst = parse_args(sys.argv[1:])
    tests = get_tests()
    suite = unittest.TestSuite(tests)
    runner = unittest.TextTestRunner(descriptions=docs, verbosity=vrbst)
    result = runner.run(suite)
    rc = len(result.failures) + len(result.errors)
    if rc > 250: rc = 250
    sys.exit(rc)
Ejemplo n.º 18
0
class Telnet:
    """A test library providing communication over Telnet connections.

    `Telnet` is Robot Framework's standard library that makes it possible to
    connect to Telnet servers and execute commands on the opened connections.

    == Table of contents ==

    - `Connections`
    - `Writing and reading`
    - `Configuration`
    - `Terminal emulation`
    - `Logging`
    - `Time string format`
    - `Importing`
    - `Shortcuts`
    - `Keywords`

    = Connections =

    The first step of using `Telnet` is opening a connection with `Open
    Connection` keyword. Typically the next step is logging in with `Login`
    keyword, and in the end the opened connection can be closed with `Close
    Connection`.

    It is possible to open multiple connections and switch the active one
    using `Switch Connection`. `Close All Connections` can be used to close
    all the connections, which is especially useful in suite teardowns to
    guarantee that all connections are always closed.

    = Writing and reading =

    After opening a connection and possibly logging in, commands can be
    executed or text written to the connection for other reasons using `Write`
    and `Write Bare` keywords. The main difference between these two is that
    the former adds a [#Configuration|configurable newline] after the text
    automatically.

    After writing something to the connection, the resulting output can be
    read using `Read`, `Read Until`, `Read Until Regexp`, and `Read Until
    Prompt` keywords. Which one to use depends on the context, but the latest
    one is often the most convenient.

    As a convenience when running a command, it is possible to use `Execute
    Command` that simply uses `Write` and `Read Until Prompt` internally.
    `Write Until Expected Output` is useful if you need to wait until writing
    something produces a desired output.

    Written and read text is automatically encoded/decoded using a
    [#Configuration|configured encoding].

    The ANSI escape codes, like cursor movement and color codes, are
    normally returned as part of the read operation. If an escape code occurs
    in middle of a search pattern it may also prevent finding the searched
    string. `Terminal emulation` can be used to process these
    escape codes as they would be if a real terminal would be in use.

    = Configuration =

    Many aspects related the connections can be easily configured either
    globally or per connection basis. Global configuration is done when
    [#Importing|library is imported], and these values can be overridden per
    connection by `Open Connection` or with setting specific keywords
    `Set Timeout`, `Set Newline`, `Set Prompt`, `Set Encoding`, and
    `Set Default Log Level`

    Values of `environ_user`, `window_size`, `terminal_emulation`, and
    `terminal_type` can not be changed after opening the connection.

    == Timeout ==

    Timeout defines how long is the maximum time to wait when reading
    output. It is used internally by `Read Until`, `Read Until Regexp`,
    `Read Until Prompt`, and `Login` keywords. The default value is 3 seconds.

    == Newline ==

    Newline defines which line separator `Write` keyword should use. The
    default value is `CRLF` that is typically used by Telnet connections.

    Newline can be given either in escaped format using '\\n' and '\\r' or
    with special 'LF' and 'CR' syntax.

    Examples:
    | `Set Newline` | \\n  |
    | `Set Newline` | CRLF |

    == Prompt ==

    Often the easiest way to read the output of a command is reading all
    the output until the next prompt with `Read Until Prompt`. It also makes
    it easier, and faster, to verify did `Login` succeed.

    Prompt can be specified either as a normal string or a regular expression.
    The latter is especially useful if the prompt changes as a result of
    the executed commands.

    == Encoding ==

    To ease handling text containing non-ASCII characters, all written text is
    encoded and read text decoded by default. The default encoding is UTF-8
    that works also with ASCII. Encoding can be disabled by using a special
    encoding value `NONE`. This is mainly useful if you need to get the bytes
    received from the connection as-is.

    Notice that when writing to the connection, only Unicode strings are
    encoded using the defined encoding. Byte strings are expected to be already
    encoded correctly. Notice also that normal text in test data is passed to
    the library as Unicode and you need to use variables to use bytes.

    It is also possible to configure the error handler to use if encoding or
    decoding characters fails. Accepted values are the same that encode/decode
    functions in Python strings accept. In practice the following values are
    the most useful:

    - `ignore`: ignore characters that cannot be encoded (default)
    - `strict`: fail if characters cannot be encoded
    - `replace`: replace characters that cannot be encoded with a replacement
      character

    Examples:
    | `Open Connection` | lolcathost | encoding=Latin1 | encoding_errors=strict |
    | `Set Encoding` | ISO-8859-15 |
    | `Set Encoding` | errors=ignore |

    Using UTF-8 encoding by default and being able to configure the encoding
    are new features in Robot Framework 2.7.6. In earlier versions only ASCII
    was supported and encoding errors were silently ignored. Robot Framework
    2.7.7 added a possibility to specify the error handler, changed the
    default behavior back to ignoring encoding errors, and added the
    possibility to disable encoding.

    == Default log level ==

    Default log level specifies the log level keywords use for `logging` unless
    they are given an explicit log level. The default value is `INFO`, and
    changing it, for example, to `DEBUG` can be a good idea if there is lot
    of unnecessary output that makes log files big.

    Configuring default log level in `importing` and with `Open Connection`
    are new features in Robot Framework 2.7.6. In earlier versions only
    `Set Default Log Level` could be used.

    == Terminal type ==

    By default the Telnet library does not negotiate any specific terminal type
    with the server. If a specific terminal type, for example `vt100`, is desired,
    the terminal type can be configured in `importing` and with
    `Open Connection`.

    New in Robot Framework 2.8.2.

    == Window size ==

    Window size for negotiation with the server can be configured when
    `importing` the library and with `Open Connection`.

    New in Robot Framework 2.8.2.

    == USER environment variable ==

    Telnet protocol allows the `USER` environment variable to be sent when
    connecting to the server. On some servers it may happen that there is no
    login prompt, and on those cases this configuration option will allow still
    to define the desired username. The option `environ_user` can be used in
    `importing` and with `Open Connection`.

    New in Robot Framework 2.8.2.

    = Terminal emulation =

    Starting from Robot Framework 2.8.2, Telnet library supports terminal
    emulation with [https://github.com/selectel/pyte|Pyte]. Terminal emulation
    will process the output in a virtual screen. This means that ANSI escape
    codes, like cursor movements, and also control characters, like
    carriage returns and backspaces, have the same effect on the result as they
    would have on a normal terminal screen. For example the sequence
    'acdc\\x1b[3Dbba' will result in output 'abba'.

    Terminal emulation is taken into use with option terminal_emulation=True,
    either in the library initialization, or as a option to `Open Connection`.

    As Pyte approximates vt-style terminal, you may also want to set the
    terminal type as `vt100`. We also recommend that you increase the window
    size, as the terminal emulation will break all lines that are longer than
    the window row length.

    When terminal emulation is used, the `newline` and `encoding` can not be
    changed anymore after opening the connection.

    As a prequisite for using terminal emulation you need to have [https://github.com/selectel/pyte|Pyte]
    installed. This is easiest done with [http://pip-installer.org|pip] by
    running `pip install pyte`.

    Examples:
    | `Open Connection` | lolcathost | terminal_emulation=True | terminal_type=vt100 | window_size=400x100 |

    = Logging =

    All keywords that read something log the output. These keywords take the
    log level to use as an optional argument, and if no log level is specified
    they use the [#Configuration|configured] default value.

    The valid log levels to use are `TRACE`, `DEBUG`, `INFO` (default), and
    `WARN`. Levels below `INFO` are not shown in log files by default whereas
    warnings are shown more prominently.

    The [http://docs.python.org/2/library/telnetlib.html|telnetlib module]
    used by this library has a custom logging system for logging content it
    sends and receives. Starting from Robot Framework 2.7.7, these low level
    log messages are forwarded to Robot's log file using `TRACE` level.

    = Time string format =

    Timeouts and other times used must be given as a time string using format
    in format like '15 seconds' or '1min 10s'. If the timeout is given as
    just a number, for example, '10' or '1.5', it is considered to be seconds.
    The time string format is described in more detail in an appendix of
    [http://code.google.com/p/robotframework/wiki/UserGuide|Robot Framework User Guide].
    """
    ROBOT_LIBRARY_SCOPE = 'TEST_SUITE'
    ROBOT_LIBRARY_VERSION = get_version()

    def __init__(self, timeout='3 seconds', newline='CRLF',
                 prompt=None, prompt_is_regexp=False,
                 encoding='UTF-8', encoding_errors='ignore',
                 default_log_level='INFO', window_size=None,
                 environ_user=None, terminal_emulation=False,
                 terminal_type=None):
        """Telnet library can be imported with optional configuration parameters.

        Configuration parameters are used as default values when new
        connections are opened with `Open Connection` keyword. They can also be
        overridden after opening the connection using the `Set Timeout`,
        `Set Newline`, `Set Prompt`, `Set Encoding`, and `Set Default Log Level`
        keywords. See these keywords as well as `Configuration` and
        `Terminal emulation` sections above for more information about these
        parameters and their possible values.

        Examples (use only one of these):

        | *Setting* | *Value* | *Value* | *Value* | *Value* | *Value* | *Comment* |
        | Library | Telnet |     |    |     |    | # default values                |
        | Library | Telnet | 0.5 |    |     |    | # set only timeout              |
        | Library | Telnet |     | LF |     |    | # set only newline              |
        | Library | Telnet | newline=LF | encoding=ISO-8859-1 | | | # set newline and encoding using named arguments |
        | Library | Telnet | 2.0 | LF |     |    | # set timeout and newline       |
        | Library | Telnet | 2.0 | CRLF | $ |    | # set also prompt               |
        | Library | Telnet | 2.0 | LF | (> |# ) | True | # set prompt as a regular expression |
        | Library | Telnet | terminal_emulation=True | terminal_type=vt100 | window_size=400x100 | | # use terminal emulation with defined window size and terminal type |
        """
        self._timeout = timeout or 3.0
        self._newline = newline or 'CRLF'
        self._prompt = (prompt, bool(prompt_is_regexp))
        self._encoding = encoding
        self._encoding_errors = encoding_errors
        self._default_log_level = default_log_level
        self._window_size = self._parse_window_size(window_size)
        self._environ_user = environ_user
        self._terminal_emulation = self._parse_terminal_emulation(terminal_emulation)
        self._terminal_type = terminal_type
        self._cache = utils.ConnectionCache()
        self._conn = None
        self._conn_kws = self._lib_kws = None

    def get_keyword_names(self):
        return self._get_library_keywords() + self._get_connection_keywords()

    def _get_library_keywords(self):
        if self._lib_kws is None:
            self._lib_kws = self._get_keywords(self, ['get_keyword_names'])
        return self._lib_kws

    def _get_keywords(self, source, excluded):
        return [name for name in dir(source)
                if self._is_keyword(name, source, excluded)]

    def _is_keyword(self, name, source, excluded):
        return (name not in excluded and
                not name.startswith('_') and
                name != 'get_keyword_names' and
                inspect.ismethod(getattr(source, name)))

    def _get_connection_keywords(self):
        if self._conn_kws is None:
            conn = self._get_connection()
            excluded = [name for name in dir(telnetlib.Telnet())
                        if name not in ['write', 'read', 'read_until']]
            self._conn_kws = self._get_keywords(conn, excluded)
        return self._conn_kws

    def __getattr__(self, name):
        if name not in self._get_connection_keywords():
            raise AttributeError(name)
        # If no connection is initialized, get attributes from a non-active
        # connection. This makes it possible for Robot to create keyword
        # handlers when it imports the library.
        return getattr(self._conn or self._get_connection(), name)

    def open_connection(self, host, alias=None, port=23, timeout=None,
                        newline=None, prompt=None, prompt_is_regexp=False,
                        encoding=None, encoding_errors=None,
                        default_log_level=None, window_size=None,
                        environ_user=None, terminal_emulation=False,
                        terminal_type=None):
        """Opens a new Telnet connection to the given host and port.

        The `timeout`, `newline`, `prompt`, `prompt_is_regexp`, `encoding`,
        `default_log_level`, `window_size`, `environ_user`,
        `terminal_emulation`, and `terminal_type` arguments get default values
        when the library is [#Importing|imported]. Setting them here overrides
        those values for the opened connection. See `Configuration` and
        `Terminal emulation` sections for more information.

        Possible already opened connections are cached and it is possible to
        switch back to them using `Switch Connection` keyword. It is possible
        to switch either using explicitly given `alias` or using index returned
        by this keyword. Indexing starts from 1 and is reset back to it by
        `Close All Connections` keyword.
        """
        timeout = timeout or self._timeout
        newline = newline or self._newline
        encoding = encoding or self._encoding
        encoding_errors = encoding_errors or self._encoding_errors
        default_log_level = default_log_level or self._default_log_level
        window_size = self._parse_window_size(window_size) or self._window_size
        environ_user = environ_user or self._environ_user
        terminal_emulation = self._get_terminal_emulation_with_default(terminal_emulation)
        terminal_type = terminal_type or self._terminal_type
        if not prompt:
            prompt, prompt_is_regexp = self._prompt
        logger.info('Opening connection to %s:%s with prompt: %s'
                    % (host, port, prompt))
        self._conn = self._get_connection(host, port, timeout, newline,
                                          prompt, prompt_is_regexp,
                                          encoding, encoding_errors,
                                          default_log_level, window_size,
                                          environ_user, terminal_emulation,
                                          terminal_type)
        return self._cache.register(self._conn, alias)

    def _get_terminal_emulation_with_default(self, terminal_emulation):
        if terminal_emulation is None or terminal_emulation == '':
            return self._terminal_emulation
        return self._parse_terminal_emulation(terminal_emulation)

    def _parse_terminal_emulation(self, terminal_emulation):
        if not terminal_emulation:
            return False
        if isinstance(terminal_emulation, basestring):
            return terminal_emulation.lower() == 'true'
        return bool(terminal_emulation)

    def _parse_window_size(self, window_size):
        if not window_size:
            return None
        try:
            cols, rows = window_size.split('x')
            cols, rows = (int(cols), int(rows))
        except:
            raise AssertionError("Invalid window size '%s'. Should be <rows>x<columns>" % window_size)
        return cols, rows

    def _get_connection(self, *args):
        """Can be overridden to use a custom connection."""
        return TelnetConnection(*args)

    def switch_connection(self, index_or_alias):
        """Switches between active connections using an index or an alias.

        Aliases can be given to `Open Connection` keyword which also always
        returns the connection index.

        This keyword returns the index of previous active connection.

        Example:
        | `Open Connection`   | myhost.net              |          |           |
        | `Login`             | john                    | secret   |           |
        | `Write`             | some command            |          |           |
        | `Open Connection`   | yourhost.com            | 2nd conn |           |
        | `Login`             | root                    | password |           |
        | `Write`             | another cmd             |          |           |
        | ${old index}=       | `Switch Connection`     | 1        | # index   |
        | `Write`             | something               |          |           |
        | `Switch Connection` | 2nd conn                |          | # alias   |
        | `Write`             | whatever                |          |           |
        | `Switch Connection` | ${old index}            | | # back to original |
        | [Teardown]          | `Close All Connections` |          |           |

        The example above expects that there were no other open
        connections when opening the first one, because it used index
        '1' when switching to the connection later. If you are not
        sure about that, you can store the index into a variable as
        shown below.

        | ${index} =          | `Open Connection` | myhost.net |
        | `Do Something`      |                   |            |
        | `Switch Connection` | ${index}          |            |
        """
        old_index = self._cache.current_index
        self._conn = self._cache.switch(index_or_alias)
        return old_index

    def close_all_connections(self):
        """Closes all open connections and empties the connection cache.

        If multiple connections are opened, this keyword should be used in
        a test or suite teardown to make sure that all connections are closed.
        It is not an error is some of the connections have already been closed
        by `Close Connection`.

        After this keyword, new indexes returned by `Open Connection`
        keyword are reset to 1.
        """
        self._conn = self._cache.close_all()
Ejemplo n.º 19
0
            verbosity = 0
        if opt in ("-v", "--verbose"):
            verbosity = 2
        if opt in ("-d", "--doc"):
            docs = 1
            verbosity = 2
    return docs, verbosity


def usage_exit(msg=None):
    print __doc__
    if msg is None:
        rc = 251
    else:
        print "\nError:", msg
        rc = 252
    sys.exit(rc)


if __name__ == "__main__":
    print "Testing with Robot version: %s" % get_version()
    docs, vrbst = parse_args(sys.argv[1:])
    tests = get_tests()
    suite = unittest.TestSuite(tests)
    runner = unittest.TextTestRunner(descriptions=docs, verbosity=vrbst)
    result = runner.run(suite)
    rc = len(result.failures) + len(result.errors)
    if rc > 250:
        rc = 250
    sys.exit(rc)
Ejemplo n.º 20
0
The command line entry points provided by the framework are exposed for
programmatic usage as follows:

  * :func:`~robot.run.run`: Function to run tests.
  * :func:`~robot.run.run_cli`: Function to run tests
    with command line argument processing.
  * :func:`~robot.rebot.rebot`: Function to post-process outputs.
  * :func:`~robot.rebot.rebot_cli`: Function to post-process outputs
    with command line argument processing.
  * :mod:`~robot.libdoc`: Module for library documentation generation.
  * :mod:`~robot.testdoc`: Module for test case documentation generation.
  * :mod:`~robot.tidy`: Module for test data clean-up and format change.

All the functions above can be imported like ``from robot import run``.
Functions and classes provided by the modules need to be imported like
``from robot.libdoc import libdoc_cli``.

The functions and modules listed above are considered stable. Other modules in
this package are for for internal usage and may change without prior notice.

.. tip:: More public APIs are exposed by the :mod:`robot.api` package.
"""

from robot.rebot import rebot, rebot_cli
from robot.run import run, run_cli
from robot.version import get_version


__all__ = ['run', 'run_cli', 'rebot', 'rebot_cli']
__version__ = get_version()
Ejemplo n.º 21
0
class Process(object):
    """Robot Framework test library for running processes.

    This library utilizes Python's
    [http://docs.python.org/2/library/subprocess.html|subprocess]
    module and its
    [http://docs.python.org/2/library/subprocess.html#subprocess.Popen|Popen]
    class.

    The library has following main usages:

    - Running processes in system and waiting for their completion using
      `Run Process` keyword.
    - Starting processes on background using `Start Process`.
    - Waiting started process to complete using `Wait For Process` or
      stopping them with `Terminate Process` or `Terminate All Processes`.

    This library is new in Robot Framework 2.8.

    == Table of contents ==

    - `Specifying command and arguments`
    - `Process configuration`
    - `Active process`
    - `Result object`
    - `Boolean arguments`
    - `Using with OperatingSystem library`
    - `Example`
    - `Shortcuts`
    - `Keywords`

    = Specifying command and arguments =

    Both `Run Process` and `Start Process` accept the command to execute
    and all arguments passed to it as separate arguments. This is convenient
    to use and also allows these keywords to automatically escape possible
    spaces and other special characters in the command or arguments.

    When `running processes in shell`, it is also possible to give the
    whole command to execute as a single string. The command can then
    contain multiple commands, for example, connected with pipes. When
    using this approach the caller is responsible on escaping.

    Examples:
    | `Run Process` | ${progdir}${/}prog.py        | first arg | second         |
    | `Run Process` | script1.sh arg && script2.sh | shell=yes | cwd=${progdir} |

    Starting from Robot Framework 2.8.6, possible non-string arguments are
    converted to strings automatically.

    = Process configuration =

    `Run Process` and `Start Process` keywords can be configured using
    optional `**configuration` keyword arguments. Configuration arguments
    must be given after other arguments passed to these keywords and must
    use syntax like `name=value`. Available configuration arguments are
    listed below and discussed further in sections afterwards.

    |  = Name =  |                  = Explanation =                      |
    | shell      | Specifies whether to run the command in shell or not  |
    | cwd        | Specifies the working directory.                      |
    | env        | Specifies environment variables given to the process. |
    | env:<name> | Overrides the named environment variable(s) only.     |
    | stdout     | Path of a file where to write standard output.        |
    | stderr     | Path of a file where to write standard error.         |
    | alias      | Alias given to the process.                           |

    Note that because `**configuration` is passed using `name=value` syntax,
    possible equal signs in other arguments passed to `Run Process` and
    `Start Process` must be escaped with a backslash like `name\\=value`.
    See `Run Process` for an example.

    == Running processes in shell ==

    The `shell` argument specifies whether to run the process in a shell or
    not. By default shell is not used, which means that shell specific
    commands, like `copy` and `dir` on Windows, are not available.

    Giving the `shell` argument any non-false value, such as `shell=True`,
    changes the program to be executed in a shell. It allows using the shell
    capabilities, but can also make the process invocation operating system
    dependent.

    When using a shell it is possible to give the whole command to execute
    as a single string. See `Specifying command and arguments` section for
    examples and more details in general.

    == Current working directory ==

    By default the child process will be executed in the same directory
    as the parent process, the process running tests, is executed. This
    can be changed by giving an alternative location using the `cwd` argument.
    Forward slashes in the given path are automatically converted to
    backslashes on Windows.

    `Standard output and error streams`, when redirected to files,
    are also relative to the current working directory possibly set using
    the `cwd` argument.

    Example:
    | `Run Process` | prog.exe | cwd=${ROOT}/directory | stdout=stdout.txt |

    == Environment variables ==

    By default the child process will get a copy of the parent process's
    environment variables. The `env` argument can be used to give the
    child a custom environment as a Python dictionary. If there is a need
    to specify only certain environment variable, it is possible to use the
    `env:<name>=<value>` format to set or override only that named variables.
    It is also possible to use these two approaches together.

    Examples:
    | `Run Process` | program | env=${environ} |
    | `Run Process` | program | env:http_proxy=10.144.1.10:8080 | env:PATH=%{PATH}${:}${PROGDIR} |
    | `Run Process` | program | env=${environ} | env:EXTRA=value |

    == Standard output and error streams ==

    By default processes are run so that their standard output and standard
    error streams are kept in the memory. This works fine normally,
    but if there is a lot of output, the output buffers may get full and
    the program can hang. Additionally on Jython, everything written to
    these in-memory buffers can be lost if the process is terminated.

    To avoid the above mentioned problems, it is possible to use `stdout`
    and `stderr` arguments to specify files on the file system where to
    redirect the outputs. This can also be useful if other processes or
    other keywords need to read or manipulate the outputs somehow.

    Given `stdout` and `stderr` paths are relative to the `current working
    directory`. Forward slashes in the given paths are automatically converted
    to backslashes on Windows.

    As a special feature, it is possible to redirect the standard error to
    the standard output by using `stderr=STDOUT`.

    Regardless are outputs redirected to files or not, they are accessible
    through the `result object` returned when the process ends.

    Examples:
    | ${result} = | `Run Process` | program | stdout=${TEMPDIR}/stdout.txt | stderr=${TEMPDIR}/stderr.txt |
    | `Log Many`  | stdout: ${result.stdout} | stderr: ${result.stderr} |
    | ${result} = | `Run Process` | program | stderr=STDOUT |
    | `Log`       | all output: ${result.stdout} |

    Note that the created output files are not automatically removed after
    the test run. The user is responsible to remove them if needed.

    == Alias ==

    A custom name given to the process that can be used when selecting the
    `active process`.

    Examples:
    | `Start Process` | program | alias=example |
    | `Run Process`   | python  | -c | print 'hello' | alias=hello |

    = Active process =

    The test library keeps record which of the started processes is currently
    active. By default it is latest process started with `Start Process`,
    but `Switch Process` can be used to select a different one. Using
    `Run Process` does not affect the active process.

    The keywords that operate on started processes will use the active process
    by default, but it is possible to explicitly select a different process
    using the `handle` argument. The handle can be the identifier returned by
    `Start Process` or an `alias` explicitly given to `Start Process` or
    `Run Process`.

    = Result object =

    `Run Process`, `Wait For Process` and `Terminate Process` keywords return a
    result object that contains information about the process execution as its
    attributes. The same result object, or some of its attributes, can also
    be get using `Get Process Result` keyword. Attributes available in the
    object are documented in the table below.

    | = Attribute = |             = Explanation =               |
    | rc            | Return code of the process as an integer. |
    | stdout        | Contents of the standard output stream.   |
    | stderr        | Contents of the standard error stream.    |
    | stdout_path   | Path where stdout was redirected or `None` if not redirected. |
    | stderr_path   | Path where stderr was redirected or `None` if not redirected. |

    Example:
    | ${result} =            | `Run Process`         | program               |
    | `Should Be Equal As Integers` | ${result.rc}   | 0                     |
    | `Should Match`         | ${result.stdout}      | Some t?xt*            |
    | `Should Be Empty`      | ${result.stderr}      |                       |
    | ${stdout} =            | `Get File`            | ${result.stdout_path} |
    | `Should Be Equal`      | ${stdout}             | ${result.stdout}      |
    | `File Should Be Empty` | ${result.stderr_path} |                       |

    = Boolean arguments =

    Some keywords accept arguments that are handled as Boolean values.
    If such an argument is given as a string, it is considered false if it
    is either empty or case-insensitively equal to `false`. Other strings
    are considered true regardless what they contain, and other argument
    types are tested using same
    [http://docs.python.org/2/library/stdtypes.html#truth-value-testing|rules
    as in Python].

    True examples:
    | `Terminate Process` | kill=True     | # Strings are generally true.    |
    | `Terminate Process` | kill=yes      | # Same as above.                 |
    | `Terminate Process` | kill=${TRUE}  | # Python `True` is true.         |
    | `Terminate Process` | kill=${42}    | # Numbers other than 0 are true. |

    False examples:
    | `Terminate Process` | kill=False    | # String `False` is false.       |
    | `Terminate Process` | kill=${EMPTY} | # Empty string is false.         |
    | `Terminate Process` | kill=${FALSE} | # Python `False` is false.       |
    | `Terminate Process` | kill=${0}     | # Number 0 is false.             |

    Note that prior to Robot Framework 2.8 all non-empty strings, including
    `false`, were considered true.

    = Using with OperatingSystem library =

    The OperatingSystem library also contains keywords for running processes.
    They are not as flexible as the keywords provided by this library, and
    thus not recommended to be used anymore. They may eventually even be
    deprecated.

    There is a name collision because both of these libraries have
    `Start Process` and `Switch Process` keywords. This is handled so that
    if both libraries are imported, the keywords in the Process library are
    used by default. If there is a need to use the OperatingSystem variants,
    it is possible to use `OperatingSystem.Start Process` syntax or use
    the `BuiltIn` keyword `Set Library Search Order` to change the priority.

    Other keywords in the OperatingSystem library can be used freely with
    keywords in the Process library.

    = Example =

    | ***** Settings *****
    | Library    Process
    | Suite Teardown    `Terminate All Processes`    kill=True
    |
    | ***** Test Cases *****
    | Example
    |     `Start Process`    program    arg1   arg2    alias=First
    |     ${handle} =    `Start Process`    command.sh arg | command2.sh   shell=True    cwd=/path
    |     ${result} =    `Run Process`    ${CURDIR}/script.py
    |     `Should Not Contain`    ${result.stdout}    FAIL
    |     `Terminate Process`    ${handle}
    |     ${result} =    `Wait For Process`    First
    |     `Should Be Equal As Integers`   ${result.rc}    0
    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()
    TERMINATE_TIMEOUT = 30
    KILL_TIMEOUT = 10

    def __init__(self):
        self._processes = ConnectionCache('No active process.')
        self._results = {}

    def run_process(self, command, *arguments, **configuration):
        """Runs a process and waits for it to complete.

        `command` and `*arguments` specify the command to execute and arguments
        passed to it. See `Specifying command and arguments` for more details.

        `**configuration` contains additional configuration related to starting
        processes and waiting for them to finish. See `Process configuration`
        for more details about configuration related to starting processes.
        Configuration related to waiting for processes consists of `timeout`
        and `on_timeout` arguments that have same semantics as with `Wait
        For Process` keyword. By default there is no timeout, and if timeout
        is defined the default action on timeout is `terminate`.

        Returns a `result object` containing information about the execution.

        Note that possible equal signs in `*arguments` must be escaped
        with a backslash (e.g. `name\\=value`) to avoid them to be passed in
        as `**configuration`.

        Examples:
        | ${result} = | Run Process | python | -c | print 'Hello, world!' |
        | Should Be Equal | ${result.stdout} | Hello, world! |
        | ${result} = | Run Process | ${command} | stderr=STDOUT | timeout=10s |
        | ${result} = | Run Process | ${command} | timeout=1min | on_timeout=continue |
        | ${result} = | Run Process | java -Dname\\=value Example | shell=True | cwd=${EXAMPLE} |

        This command does not change the `active process`.
        `timeout` and `on_timeout` arguments are new in Robot Framework 2.8.4.
        """
        current = self._processes.current
        timeout = configuration.pop('timeout', None)
        on_timeout = configuration.pop('on_timeout', 'terminate')
        try:
            handle = self.start_process(command, *arguments, **configuration)
            return self.wait_for_process(handle, timeout, on_timeout)
        finally:
            self._processes.current = current

    def start_process(self, command, *arguments, **configuration):
        """Starts a new process on background.

        See `Specifying command and arguments` and `Process configuration`
        for more information about the arguments, and `Run Process` keyword
        for related examples.

        Makes the started process new `active process`. Returns an identifier
        that can be used as a handle to active the started process if needed.

        Starting from Robot Framework 2.8.5, processes are started so that
        they create a new process group. This allows sending signals to and
        terminating also possible child processes.
        """
        config = ProcessConfig(**configuration)
        executable_command = self._cmd(command, arguments, config.shell)
        logger.info('Starting process:\n%s' % executable_command)
        logger.debug('Process configuration:\n%s' % config)
        process = subprocess.Popen(executable_command, **config.full_config)
        self._results[process] = ExecutionResult(process, config.stdout_stream,
                                                 config.stderr_stream)
        return self._processes.register(process, alias=config.alias)

    def _cmd(self, command, args, use_shell):
        command = [encode_to_system(item) for item in [command] + list(args)]
        if not use_shell:
            return command
        if args:
            return subprocess.list2cmdline(command)
        return command[0]

    def is_process_running(self, handle=None):
        """Checks is the process running or not.

        If `handle` is not given, uses the current `active process`.

        Returns `True` if the process is still running and `False` otherwise.
        """
        return self._processes[handle].poll() is None

    def process_should_be_running(self,
                                  handle=None,
                                  error_message='Process is not running.'):
        """Verifies that the process is running.

        If `handle` is not given, uses the current `active process`.

        Fails if the process has stopped.
        """
        if not self.is_process_running(handle):
            raise AssertionError(error_message)

    def process_should_be_stopped(self,
                                  handle=None,
                                  error_message='Process is running.'):
        """Verifies that the process is not running.

        If `handle` is not given, uses the current `active process`.

        Fails if the process is still running.
        """
        if self.is_process_running(handle):
            raise AssertionError(error_message)

    def wait_for_process(self,
                         handle=None,
                         timeout=None,
                         on_timeout='continue'):
        """Waits for the process to complete or to reach the given timeout.

        The process to wait for must have been started earlier with
        `Start Process`. If `handle` is not given, uses the current
        `active process`.

        `timeout` defines the maximum time to wait for the process. It is
        interpreted according to Robot Framework User Guide Appendix
        `Time Format`, for example, '42', '42 s', or '1 minute 30 seconds'.

        `on_timeout` defines what to do if the timeout occurs. Possible values
        and corresponding actions are explained in the table below. Notice
        that reaching the timeout never fails the test.

        |  = Value =  |               = Action =               |
        | `continue`  | The process is left running (default). |
        | `terminate` | The process is gracefully terminated.  |
        | `kill`      | The process is forcefully stopped.     |

        See `Terminate Process` keyword for more details how processes are
        terminated and killed.

        If the process ends before the timeout or it is terminated or killed,
        this keyword returns a `result object` containing information about
        the execution. If the process is left running, Python `None` is
        returned instead.

        Examples:
        | # Process ends cleanly      |                  |                  |
        | ${result} =                 | Wait For Process | example          |
        | Process Should Be Stopped   | example          |                  |
        | Should Be Equal As Integers | ${result.rc}     | 0                |
        | # Process does not end      |                  |                  |
        | ${result} =                 | Wait For Process | timeout=42 secs  |
        | Process Should Be Running   |                  |                  |
        | Should Be Equal             | ${result}        | ${NONE}          |
        | # Kill non-ending process   |                  |                  |
        | ${result} =                 | Wait For Process | timeout=1min 30s | on_timeout=kill |
        | Process Should Be Stopped   |                  |                  |
        | Should Be Equal As Integers | ${result.rc}     | -9               |

        `timeout` and `on_timeout` are new in Robot Framework 2.8.2.
        """
        process = self._processes[handle]
        logger.info('Waiting for process to complete.')
        if timeout:
            timeout = timestr_to_secs(timeout)
            if not self._process_is_stopped(process, timeout):
                logger.info('Process did not complete in %s.' %
                            secs_to_timestr(timeout))
                return self._manage_process_timeout(handle, on_timeout.lower())
        return self._wait(process)

    def _manage_process_timeout(self, handle, on_timeout):
        if on_timeout == 'terminate':
            return self.terminate_process(handle)
        elif on_timeout == 'kill':
            return self.terminate_process(handle, kill=True)
        else:
            logger.info('Leaving process intact.')
            return None

    def _wait(self, process):
        result = self._results[process]
        result.rc = process.wait() or 0
        result.close_streams()
        logger.info('Process completed.')
        return result

    def terminate_process(self, handle=None, kill=False):
        """Stops the process gracefully or forcefully.

        If `handle` is not given, uses the current `active process`.

        Waits for the process to stop after terminating it. Returns
        a `result object` containing information about the execution
        similarly as `Wait For Process`.

        On Unix-like machines, by default, first tries to terminate the process
        group gracefully, but forcefully kills it if it does not stop in 30
        seconds. Kills the process group immediately if the `kill` argument is
        given any value considered true. See `Boolean arguments` section for
        more details about true and false values.

        Termination is done using `TERM (15)` signal and killing using
        `KILL (9)`. Use `Send Signal To Process` instead if you just want to
        send either of these signals without waiting for the process to stop.

        On Windows, by default, sends `CTRL_BREAK_EVENT` signal to the process
        group. If that does not stop the process in 30 seconds, or `kill`
        argument is given a true value, uses Win32 API function
        `TerminateProcess()` to kill the process forcefully. Note that
        `TerminateProcess()` does not kill possible child processes.

        | ${result} =                 | Terminate Process |     |
        | Should Be Equal As Integers | ${result.rc}      | -15 | # On Unixes |
        | Terminate Process           | myproc            | kill=true |

        *NOTE:* Stopping processes requires the
        [http://docs.python.org/2/library/subprocess.html|subprocess]
        module to have working `terminate` and `kill` functions. They were
        added in Python 2.6 and are thus missing from earlier versions.

        With Jython termination is supported starting from Jython 2.7 beta 3
        with some limitations. One problem is that everything written to the
        `standard output and error streams` before termination can be lost
        unless custom streams are used. A bigger problem is that at least
        beta 3 does not support killing the process

        Automatically killing the process if termination fails as well as
        returning a result object are new features in Robot Framework 2.8.2.
        Terminating also possible child processes, including using
        `CTRL_BREAK_EVENT` on Windows, is new in Robot Framework 2.8.5.
        """
        process = self._processes[handle]
        if not hasattr(process, 'terminate'):
            raise RuntimeError('Terminating processes is not supported '
                               'by this Python version.')
        terminator = self._kill if is_true(kill) else self._terminate
        try:
            terminator(process)
        except OSError:
            if not self._process_is_stopped(process, self.KILL_TIMEOUT):
                raise
            logger.debug('Ignored OSError because process was stopped.')
        return self._wait(process)

    def _kill(self, process):
        logger.info('Forcefully killing process.')
        if hasattr(os, 'killpg'):
            os.killpg(process.pid, signal_module.SIGKILL)
        else:
            process.kill()
        if not self._process_is_stopped(process, self.KILL_TIMEOUT):
            raise RuntimeError('Failed to kill process.')

    def _terminate(self, process):
        logger.info('Gracefully terminating process.')
        # Sends signal to the whole process group both on POSIX and on Windows
        # if supported by the interpreter.
        if hasattr(os, 'killpg'):
            os.killpg(process.pid, signal_module.SIGTERM)
        elif hasattr(signal_module, 'CTRL_BREAK_EVENT'):
            if sys.platform == 'cli':
                # https://ironpython.codeplex.com/workitem/35020
                ctypes.windll.kernel32.GenerateConsoleCtrlEvent(
                    signal_module.CTRL_BREAK_EVENT, process.pid)
            else:
                process.send_signal(signal_module.CTRL_BREAK_EVENT)
        else:
            process.terminate()
        if not self._process_is_stopped(process, self.TERMINATE_TIMEOUT):
            logger.info('Graceful termination failed.')
            self._kill(process)

    def terminate_all_processes(self, kill=False):
        """Terminates all still running processes started by this library.

        This keyword can be used in suite teardown or elsewhere to make
        sure that all processes are stopped,

        By default tries to terminate processes gracefully, but can be
        configured to forcefully kill them immediately. See `Terminate Process`
        that this keyword uses internally for more details.
        """
        for handle in range(1, len(self._processes) + 1):
            if self.is_process_running(handle):
                self.terminate_process(handle, kill=kill)
        self.__init__()

    def send_signal_to_process(self, signal, handle=None, group=False):
        """Sends the given `signal` to the specified process.

        If `handle` is not given, uses the current `active process`.

        Signal can be specified either as an integer, or anything that can
        be converted to an integer, or as a signal name. In the latter case it
        is possible to give the name both with or without a `SIG` prefix,
        but names are case-sensitive. For example, all the examples below
        send signal `INT (2)`:

        | Send Signal To Process | 2      |        | # Send to active process |
        | Send Signal To Process | INT    |        |                          |
        | Send Signal To Process | SIGINT | myproc | # Send to named process  |

        What signals are supported depends on the system. For a list of
        existing signals on your system, see the Unix man pages related to
        signal handling (typically `man signal` or `man 7 signal`).

        By default sends the signal only to the parent process, not to possible
        child processes started by it. Notice that when `running processes in
        shell`, the shell is the parent process and it depends on the system
        does the shell propagate the signal to the actual started process.
        To send the signal to the whole process group, `group` argument can
        be set to any true value:

        | Send Signal To Process | TERM  | group=yes |

        If you are stopping a process, it is often easier and safer to use
        `Terminate Process` keyword instead.

        *NOTE:* Sending signals requires the
        [http://docs.python.org/2/library/subprocess.html|subprocess]
        module to have working `send_signal` function. It was added
        in Python 2.6 and are thus missing from earlier versions.
        How well it will work with forthcoming Jython 2.7 is unknown.

        New in Robot Framework 2.8.2. Support for `group` argument is new
        in Robot Framework 2.8.5.
        """
        if os.sep == '\\':
            raise RuntimeError('This keyword does not work on Windows.')
        process = self._processes[handle]
        signum = self._get_signal_number(signal)
        logger.info('Sending signal %s (%d).' % (signal, signum))
        if is_true(group) and hasattr(os, 'killpg'):
            os.killpg(process.pid, signum)
        elif hasattr(process, 'send_signal'):
            process.send_signal(signum)
        else:
            raise RuntimeError('Sending signals is not supported '
                               'by this Python version.')

    def _get_signal_number(self, int_or_name):
        try:
            return int(int_or_name)
        except ValueError:
            return self._convert_signal_name_to_number(int_or_name)

    def _convert_signal_name_to_number(self, name):
        try:
            return getattr(signal_module,
                           name if name.startswith('SIG') else 'SIG' + name)
        except AttributeError:
            raise RuntimeError("Unsupported signal '%s'." % name)

    def get_process_id(self, handle=None):
        """Returns the process ID (pid) of the process.

        If `handle` is not given, uses the current `active process`.

        Returns the pid assigned by the operating system as an integer.
        Note that with Jython, at least with the 2.5 version, the returned
        pid seems to always be `None`.

        The pid is not the same as the identifier returned by
        `Start Process` that is used internally by this library.
        """
        return self._processes[handle].pid

    def get_process_object(self, handle=None):
        """Return the underlying `subprocess.Popen`  object.

        If `handle` is not given, uses the current `active process`.
        """
        return self._processes[handle]

    def get_process_result(self,
                           handle=None,
                           rc=False,
                           stdout=False,
                           stderr=False,
                           stdout_path=False,
                           stderr_path=False):
        """Returns the specified `result object` or some of its attributes.

        The given `handle` specifies the process whose results should be
        returned. If no `handle` is given, results of the current `active
        process` are returned. In either case, the process must have been
        finishes before this keyword can be used. In practice this means
        that processes started with `Start Process` must be finished either
        with `Wait For Process` or `Terminate Process` before using this
        keyword.

        If no other arguments than the optional `handle` are given, a whole
        `result object` is returned. If one or more of the other arguments
        are given any true value, only the specified attributes of the
        `result object` are returned. These attributes are always returned
        in the same order as arguments are specified in the keyword signature.
        See `Boolean arguments` section for more details about true and false
        values.

        Examples:
        | Run Process           | python             | -c            | print 'Hello, world!' | alias=myproc |
        | # Get result object   |                    |               |
        | ${result} =           | Get Process Result | myproc        |
        | Should Be Equal       | ${result.rc}       | ${0}          |
        | Should Be Equal       | ${result.stdout}   | Hello, world! |
        | Should Be Empty       | ${result.stderr}   |               |
        | # Get one attribute   |                    |               |
        | ${stdout} =           | Get Process Result | myproc        | stdout=true |
        | Should Be Equal       | ${stdout}          | Hello, world! |
        | # Multiple attributes |                    |               |
        | ${stdout}             | ${stderr} =        | Get Process Result |  myproc | stdout=yes | stderr=yes |
        | Should Be Equal       | ${stdout}          | Hello, world! |
        | Should Be Empty       | ${stderr}          |               |

        Although getting results of a previously executed process can be handy
        in general, the main use case for this keyword is returning results
        over the remote library interface. The remote interface does not
        support returning the whole result object, but individual attributes
        can be returned without problems.

        New in Robot Framework 2.8.2.
        """
        result = self._results[self._processes[handle]]
        if result.rc is None:
            raise RuntimeError('Getting results of unfinished processes '
                               'is not supported.')
        attributes = self._get_result_attributes(result, rc, stdout, stderr,
                                                 stdout_path, stderr_path)
        if not attributes:
            return result
        elif len(attributes) == 1:
            return attributes[0]
        return attributes

    def _get_result_attributes(self, result, *includes):
        attributes = (result.rc, result.stdout, result.stderr,
                      result.stdout_path, result.stderr_path)
        includes = (is_true(incl) for incl in includes)
        return tuple(attr for attr, incl in zip(attributes, includes) if incl)

    def switch_process(self, handle):
        """Makes the specified process the current `active process`.

        The handle can be an identifier returned by `Start Process` or
        the `alias` given to it explicitly.

        Example:
        | Start Process  | prog1    | alias=process1 |
        | Start Process  | prog2    | alias=process2 |
        | # currently active process is process2 |
        | Switch Process | process1 |
        | # now active process is process1 |
        """
        self._processes.switch(handle)

    def _process_is_stopped(self, process, timeout):
        max_time = time.time() + timeout
        while time.time() <= max_time:
            if process.poll() is not None:
                return True
            time.sleep(0.1)
        return False
Ejemplo n.º 22
0
# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Robot Framework'
copyright = u'2012, Nokia Siemens Networks'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = VERSION
# The full version, including alpha/beta/rc tags.
release = get_version()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
Ejemplo n.º 23
0
class Collections(_List, _Dictionary):
    """A test library providing keywords for handling lists and dictionaries.

    ``Collections`` is Robot Framework's standard library that provides a
    set of keywords for handling Python lists and dictionaries. This
    library has keywords, for example, for modifying and getting
    values from lists and dictionaries (e.g. `Append To List`, `Get
    From Dictionary`) and for verifying their contents (e.g. `Lists
    Should Be Equal`, `Dictionary Should Contain Value`).

    Following keywords from the BuiltIn library can also be used with
    lists and dictionaries:
    | = Keyword Name =             | = Applicable With = | = Comment = |
    | `Create List`                | lists |
    | `Create Dictionary`          | dicts | Was in Collections until RF 2.9. |
    | `Get Length`                 | both  |
    | `Length Should Be`           | both  |
    | `Should Be Empty`            | both  |
    | `Should Not Be Empty`        | both  |
    | `Should Contain`             | both  |
    | `Should Not Contain`         | both  |
    | `Should Contain X Times`     | lists |
    | `Should Not Contain X Times` | lists |
    | `Get Count`                  | lists |

    List keywords that do not alter the given list can also be used
    with tuples, and to some extend also with other iterables.
    `Convert To List` can be used to convert tuples and other iterables
    to lists.

    -------

    List related keywords use variables in format ``${Lx}`` in their examples.
    They mean lists with as many alphabetic characters as specified by ``x``.
    For example, ``${L1}`` means ``['a']`` and ``${L3}`` means
    ``['a', 'b', 'c']``.

    Dictionary keywords use similar ``${Dx}`` variables. For example, ``${D1}``
    means ``{'a': 1}`` and ``${D3}`` means ``{'a': 1, 'b': 2, 'c': 3}``.

    --------
    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()

    def should_contain_match(self,
                             list,
                             pattern,
                             msg=None,
                             case_insensitive=False,
                             whitespace_insensitive=False):
        """Fails if ``pattern`` is not found in ``list``.

        See `List Should Contain Value` for an explanation of ``msg``.

        By default, pattern matching is similar to matching files in a shell
        and is case-sensitive and whitespace-sensitive. In the pattern syntax,
        ``*`` matches to anything and ``?`` matches to any single character. You
        can also prepend ``glob=`` to your pattern to explicitly use this pattern
        matching behavior.

        If you prepend ``regexp=`` to your pattern, your pattern will be used
        according to the Python
        [http://docs.python.org/2/library/re.html|re module] regular expression
        syntax. Important note: Backslashes are an escape character, and must
        be escaped with another backslash (e.g. ``regexp=\\\\d{6}`` to search for
        ``\\d{6}``). See `BuiltIn.Should Match Regexp` for more details.

        If ``case_insensitive`` is True, the pattern matching will ignore case.

        If ``whitespace_insensitive`` is True, the pattern matching will ignore
        whitespace.

        Non-string values in lists are ignored when matching patterns.

        The given list is never altered by this keyword.

        See also ``Should Not Contain Match``.

        Examples:
        | Should Contain Match | ${list} | a* | # List should contain any string beginning with 'a' |
        | Should Contain Match | ${list} | regexp=a.* | # List should contain any string beginning with 'a' (regexp version) |
        | Should Contain Match | ${list} | regexp=\\\\d{6} | # List should contain any string which contains six decimal digits |
        | Should Contain Match | ${list} | a* | case_insensitive=${True} | # List should contain any string beginning with 'a' or 'A' |
        | Should Contain Match | ${list} | ab* | whitespace_insensitive=${True} | # List should contain any string beginning with 'ab' or 'a b' or any other combination of whitespace |
        | Should Contain Match | ${list} | ab* | whitespace_insensitive=${True} | case_insensitive=${True} | # List should contain any string beginning with 'ab' or 'a b' or 'AB' or 'A B' or any other combination of whitespace and upper/lower case 'a' and 'b' |

        New in Robot Framework 2.8.6.
        """
        default = "%s does not contain match for pattern '%s'." % (
            seq2str2(list), pattern)
        _verify_condition(
            _get_matches_in_iterable(list, pattern, case_insensitive,
                                     whitespace_insensitive), default, msg)

    def should_not_contain_match(self,
                                 list,
                                 pattern,
                                 msg=None,
                                 case_insensitive=False,
                                 whitespace_insensitive=False):
        """Fails if ``pattern`` is found in ``list``.

        See `List Should Contain Value` for an explanation of ``msg``.

        See `Should Contain Match` for usage details and examples.

        New in Robot Framework 2.8.6.
        """
        default = "%s contains match for pattern '%s'." % (seq2str2(list),
                                                           pattern)
        _verify_condition(
            not _get_matches_in_iterable(list, pattern, case_insensitive,
                                         whitespace_insensitive), default, msg)

    def get_matches(self,
                    list,
                    pattern,
                    case_insensitive=False,
                    whitespace_insensitive=False):
        """Returns a list of matches to ``pattern`` in ``list``.

        For more information on ``pattern``, ``case_insensitive``, and
        ``whitespace_insensitive``, see `Should Contain Match`.

        Examples:
        | ${matches}= | Get Matches | ${list} | a* | # ${matches} will contain any string beginning with 'a' |
        | ${matches}= | Get Matches | ${list} | regexp=a.* | # ${matches} will contain any string beginning with 'a' (regexp version) |
        | ${matches}= | Get Matches | ${list} | a* | case_insensitive=${True} | # ${matches} will contain any string beginning with 'a' or 'A' |

        New in Robot Framework 2.8.6.
        """
        return _get_matches_in_iterable(list, pattern, case_insensitive,
                                        whitespace_insensitive)

    def get_match_count(self,
                        list,
                        pattern,
                        case_insensitive=False,
                        whitespace_insensitive=False):
        """Returns the count of matches to ``pattern`` in ``list``.

        For more information on ``pattern``, ``case_insensitive``, and
        ``whitespace_insensitive``, see `Should Contain Match`.

        Examples:
        | ${count}= | Get Match Count | ${list} | a* | # ${count} will be the count of strings beginning with 'a' |
        | ${count}= | Get Match Count | ${list} | regexp=a.* | # ${matches} will be the count of strings beginning with 'a' (regexp version) |
        | ${count}= | Get Match Count | ${list} | a* | case_insensitive=${True} | # ${matches} will be the count of strings beginning with 'a' or 'A' |

        New in Robot Framework 2.8.6.
        """
        return len(
            self.get_matches(list, pattern, case_insensitive,
                             whitespace_insensitive))
Ejemplo n.º 24
0
# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Robot Framework'
copyright = u'2008-2015 Nokia Solutions and Networks'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = get_version(naked=True)
# The full version, including alpha/beta/rc tags.
release = get_version()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
Ejemplo n.º 25
0
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import robot.parsing.populators
robot.parsing.populators.PROCESS_CURDIR = False

from robot.version import get_version
from robot.utils import normpath, NormalizedDict
try: # Robot 2.8+
    from robot.running.usererrorhandler import UserErrorHandler
except ImportError:
    from robot.common.handlers import UserErrorHandler
from robot.parsing import TestCaseFile, ResourceFile, TestDataDirectory
from robot.parsing.model import TestCase, UserKeyword
from robot.parsing.datarow import DataRow
from robot.parsing.model import Variable
from robot.running import TestLibrary
from robot.output import LOGGER as ROBOT_LOGGER
from robot.variables import Variables as RobotVariables
from robot.variables import is_scalar_var, is_list_var, is_var, VariableSplitter


ROBOT_VERSION = get_version()
Ejemplo n.º 26
0
class String(object):
    """A test library for string manipulation and verification.

    ``String`` is Robot Framework's standard library for manipulating
    strings (e.g. `Replace String Using Regexp`, `Split To Lines`) and
    verifying their contents (e.g. `Should Be String`).

    Following keywords from ``BuiltIn`` library can also be used with strings:

    - `Catenate`
    - `Get Length`
    - `Length Should Be`
    - `Should (Not) Be Empty`
    - `Should (Not) Be Equal (As Strings/Integers/Numbers)`
    - `Should (Not) Match (Regexp)`
    - `Should (Not) Contain`
    - `Should (Not) Start With`
    - `Should (Not) End With`
    - `Convert To String`
    - `Convert To Bytes`
    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()

    def convert_to_lower_case(self, string):
        """Converts string to lower case.

        Uses Python's standard
        [https://docs.python.org/library/stdtypes.html#str.lower|lower()]
        method.

        Examples:
        | ${str1} = | Convert To Lower Case | ABC |
        | ${str2} = | Convert To Lower Case | 1A2c3D |
        | Should Be Equal | ${str1} | abc |
        | Should Be Equal | ${str2} | 1a2c3d |
        """
        # Custom `lower` needed due to IronPython bug. See its code and
        # comments for more details.
        return lower(string)

    def convert_to_upper_case(self, string):
        """Converts string to upper case.

        Uses Python's standard
        [https://docs.python.org/library/stdtypes.html#str.upper|upper()]
        method.

        Examples:
        | ${str1} = | Convert To Upper Case | abc |
        | ${str2} = | Convert To Upper Case | 1a2C3d |
        | Should Be Equal | ${str1} | ABC |
        | Should Be Equal | ${str2} | 1A2C3D |
        """
        return string.upper()

    @keyword(types=None)
    def convert_to_title_case(self, string, exclude=None):
        """Converts string to title case.

        Uses the following algorithm:

        - Split the string to words from whitespace characters (spaces,
          newlines, etc.).
        - Exclude words that are not all lower case. This preserves,
          for example, "OK" and "iPhone".
        - Exclude also words listed in the optional ``exclude`` argument.
        - Title case the first alphabetical character of each word that has
          not been excluded.
        - Join all words together so that original whitespace is preserved.

        Explicitly excluded words can be given as a list or as a string with
        words separated by a comma and an optional space. Excluded words are
        actually considered to be regular expression patterns, so it is
        possible to use something like "example[.!?]?" to match the word
        "example" on it own and also if followed by ".", "!" or "?".
        See `BuiltIn.Should Match Regexp` for more information about Python
        regular expression syntax in general and how to use it in Robot
        Framework test data in particular.

        Examples:
        | ${str1} = | Convert To Title Case | hello, world!     |
        | ${str2} = | Convert To Title Case | it's an OK iPhone | exclude=a, an, the |
        | ${str3} = | Convert To Title Case | distance is 1 km. | exclude=is, km.? |
        | Should Be Equal | ${str1} | Hello, World! |
        | Should Be Equal | ${str2} | It's an OK iPhone |
        | Should Be Equal | ${str3} | Distance is 1 km. |

        The reason this keyword does not use Python's standard
        [https://docs.python.org/library/stdtypes.html#str.title|title()]
        method is that it can yield undesired results, for example, if
        strings contain upper case letters or special characters like
        apostrophes. It would, for example, convert "it's an OK iPhone"
        to "It'S An Ok Iphone".

        New in Robot Framework 3.2.
        """
        if is_string(exclude):
            exclude = [e.strip() for e in exclude.split(',')]
        elif not exclude:
            exclude = []
        exclude = [re.compile('^%s$' % e) for e in exclude]

        def title(word):
            if any(e.match(word) for e in exclude) or not word.islower():
                return word
            for index, char in enumerate(word):
                if char.isalpha():
                    return word[:index] + word[index].title() + word[index +
                                                                     1:]
            return word

        tokens = re.split(r'(\s+)', string, flags=re.UNICODE)
        return ''.join(title(token) for token in tokens)

    def encode_string_to_bytes(self, string, encoding, errors='strict'):
        """Encodes the given Unicode ``string`` to bytes using the given ``encoding``.

        ``errors`` argument controls what to do if encoding some characters fails.
        All values accepted by ``encode`` method in Python are valid, but in
        practice the following values are most useful:

        - ``strict``: fail if characters cannot be encoded (default)
        - ``ignore``: ignore characters that cannot be encoded
        - ``replace``: replace characters that cannot be encoded with
          a replacement character

        Examples:
        | ${bytes} = | Encode String To Bytes | ${string} | UTF-8 |
        | ${bytes} = | Encode String To Bytes | ${string} | ASCII | errors=ignore |

        Use `Convert To Bytes` in ``BuiltIn`` if you want to create bytes based
        on character or integer sequences. Use `Decode Bytes To String` if you
        need to convert byte strings to Unicode strings and `Convert To String`
        in ``BuiltIn`` if you need to convert arbitrary objects to Unicode.
        """
        return bytes(string.encode(encoding, errors))

    def decode_bytes_to_string(self, bytes, encoding, errors='strict'):
        """Decodes the given ``bytes`` to a Unicode string using the given ``encoding``.

        ``errors`` argument controls what to do if decoding some bytes fails.
        All values accepted by ``decode`` method in Python are valid, but in
        practice the following values are most useful:

        - ``strict``: fail if characters cannot be decoded (default)
        - ``ignore``: ignore characters that cannot be decoded
        - ``replace``: replace characters that cannot be decoded with
          a replacement character

        Examples:
        | ${string} = | Decode Bytes To String | ${bytes} | UTF-8 |
        | ${string} = | Decode Bytes To String | ${bytes} | ASCII | errors=ignore |

        Use `Encode String To Bytes` if you need to convert Unicode strings to
        byte strings, and `Convert To String` in ``BuiltIn`` if you need to
        convert arbitrary objects to Unicode strings.
        """
        if PY3 and is_unicode(bytes):
            raise TypeError('Can not decode strings on Python 3.')
        return bytes.decode(encoding, errors)

    def format_string(self, template, *positional, **named):
        """Formats a ``template`` using the given ``positional`` and ``named`` arguments.

        The template can be either be a string or an absolute path to
        an existing file. In the latter case the file is read and its contents
        are used as the template. If the template file contains non-ASCII
        characters, it must be encoded using UTF-8.

        The template is formatted using Python's
        [https://docs.python.org/library/string.html#format-string-syntax|format
        string syntax]. Placeholders are marked using ``{}`` with possible
        field name and format specification inside. Literal curly braces
        can be inserted by doubling them like `{{` and `}}`.

        Examples:
        | ${to} = | Format String | To: {} <{}>                    | ${user}      | ${email} |
        | ${to} = | Format String | To: {name} <{email}>           | name=${name} | email=${email} |
        | ${to} = | Format String | To: {user.name} <{user.email}> | user=${user} |
        | ${xx} = | Format String | {:*^30}                        | centered     |
        | ${yy} = | Format String | {0:{width}{base}}              | ${42}        | base=X | width=10 |
        | ${zz} = | Format String | ${CURDIR}/template.txt         | positional   | named=value |

        New in Robot Framework 3.1.
        """
        if os.path.isabs(template) and os.path.isfile(template):
            template = template.replace('/', os.sep)
            logger.info('Reading template from file <a href="%s">%s</a>.' %
                        (template, template),
                        html=True)
            with FileReader(template) as reader:
                template = reader.read()
        return template.format(*positional, **named)

    def get_line_count(self, string):
        """Returns and logs the number of lines in the given string."""
        count = len(string.splitlines())
        logger.info('%d lines' % count)
        return count

    def split_to_lines(self, string, start=0, end=None):
        """Splits the given string to lines.

        It is possible to get only a selection of lines from ``start``
        to ``end`` so that ``start`` index is inclusive and ``end`` is
        exclusive. Line numbering starts from 0, and it is possible to
        use negative indices to refer to lines from the end.

        Lines are returned without the newlines. The number of
        returned lines is automatically logged.

        Examples:
        | @{lines} =        | Split To Lines | ${manylines} |    |    |
        | @{ignore first} = | Split To Lines | ${manylines} | 1  |    |
        | @{ignore last} =  | Split To Lines | ${manylines} |    | -1 |
        | @{5th to 10th} =  | Split To Lines | ${manylines} | 4  | 10 |
        | @{first two} =    | Split To Lines | ${manylines} |    | 1  |
        | @{last two} =     | Split To Lines | ${manylines} | -2 |    |

        Use `Get Line` if you only need to get a single line.
        """
        start = self._convert_to_index(start, 'start')
        end = self._convert_to_index(end, 'end')
        lines = string.splitlines()[start:end]
        logger.info('%d lines returned' % len(lines))
        return lines

    def get_line(self, string, line_number):
        """Returns the specified line from the given ``string``.

        Line numbering starts from 0 and it is possible to use
        negative indices to refer to lines from the end. The line is
        returned without the newline character.

        Examples:
        | ${first} =    | Get Line | ${string} | 0  |
        | ${2nd last} = | Get Line | ${string} | -2 |

        Use `Split To Lines` if all lines are needed.
        """
        line_number = self._convert_to_integer(line_number, 'line_number')
        return string.splitlines()[line_number]

    def get_lines_containing_string(self,
                                    string,
                                    pattern,
                                    case_insensitive=False):
        """Returns lines of the given ``string`` that contain the ``pattern``.

        The ``pattern`` is always considered to be a normal string, not a glob
        or regexp pattern. A line matches if the ``pattern`` is found anywhere
        on it.

        The match is case-sensitive by default, but giving ``case_insensitive``
        a true value makes it case-insensitive. The value is considered true
        if it is a non-empty string that is not equal to ``false``, ``none`` or
        ``no``. If the value is not a string, its truth value is got directly
        in Python. Considering ``none`` false is new in RF 3.0.3.

        Lines are returned as one string catenated back together with
        newlines. Possible trailing newline is never returned. The
        number of matching lines is automatically logged.

        Examples:
        | ${lines} = | Get Lines Containing String | ${result} | An example |
        | ${ret} =   | Get Lines Containing String | ${ret} | FAIL | case-insensitive |

        See `Get Lines Matching Pattern` and `Get Lines Matching Regexp`
        if you need more complex pattern matching.
        """
        if is_truthy(case_insensitive):
            pattern = pattern.lower()
            contains = lambda line: pattern in line.lower()
        else:
            contains = lambda line: pattern in line
        return self._get_matching_lines(string, contains)

    def get_lines_matching_pattern(self,
                                   string,
                                   pattern,
                                   case_insensitive=False):
        """Returns lines of the given ``string`` that match the ``pattern``.

        The ``pattern`` is a _glob pattern_ where:
        | ``*``        | matches everything |
        | ``?``        | matches any single character |
        | ``[chars]``  | matches any character inside square brackets (e.g. ``[abc]`` matches either ``a``, ``b`` or ``c``) |
        | ``[!chars]`` | matches any character not inside square brackets |

        A line matches only if it matches the ``pattern`` fully.

        The match is case-sensitive by default, but giving ``case_insensitive``
        a true value makes it case-insensitive. The value is considered true
        if it is a non-empty string that is not equal to ``false``, ``none`` or
        ``no``. If the value is not a string, its truth value is got directly
        in Python. Considering ``none`` false is new in RF 3.0.3.

        Lines are returned as one string catenated back together with
        newlines. Possible trailing newline is never returned. The
        number of matching lines is automatically logged.

        Examples:
        | ${lines} = | Get Lines Matching Pattern | ${result} | Wild???? example |
        | ${ret} = | Get Lines Matching Pattern | ${ret} | FAIL: * | case_insensitive=true |

        See `Get Lines Matching Regexp` if you need more complex
        patterns and `Get Lines Containing String` if searching
        literal strings is enough.
        """
        if is_truthy(case_insensitive):
            pattern = pattern.lower()
            matches = lambda line: fnmatchcase(line.lower(), pattern)
        else:
            matches = lambda line: fnmatchcase(line, pattern)
        return self._get_matching_lines(string, matches)

    def get_lines_matching_regexp(self, string, pattern, partial_match=False):
        """Returns lines of the given ``string`` that match the regexp ``pattern``.

        See `BuiltIn.Should Match Regexp` for more information about
        Python regular expression syntax in general and how to use it
        in Robot Framework test data in particular.

        By default lines match only if they match the pattern fully, but
        partial matching can be enabled by giving the ``partial_match``
        argument a true value. The value is considered true
        if it is a non-empty string that is not equal to ``false``, ``none`` or
        ``no``. If the value is not a string, its truth value is got directly
        in Python. Considering ``none`` false is new in RF 3.0.3.

        If the pattern is empty, it matches only empty lines by default.
        When partial matching is enabled, empty pattern matches all lines.

        Notice that to make the match case-insensitive, you need to prefix
        the pattern with case-insensitive flag ``(?i)``.

        Lines are returned as one string concatenated back together with
        newlines. Possible trailing newline is never returned. The
        number of matching lines is automatically logged.

        Examples:
        | ${lines} = | Get Lines Matching Regexp | ${result} | Reg\\\\w{3} example |
        | ${lines} = | Get Lines Matching Regexp | ${result} | Reg\\\\w{3} example | partial_match=true |
        | ${ret} =   | Get Lines Matching Regexp | ${ret}    | (?i)FAIL: .* |

        See `Get Lines Matching Pattern` and `Get Lines Containing
        String` if you do not need full regular expression powers (and
        complexity).

        ``partial_match`` argument is new in Robot Framework 2.9. In earlier
         versions exact match was always required.
        """
        if not is_truthy(partial_match):
            pattern = '^%s$' % pattern
        return self._get_matching_lines(string, re.compile(pattern).search)

    def _get_matching_lines(self, string, matches):
        lines = string.splitlines()
        matching = [line for line in lines if matches(line)]
        logger.info('%d out of %d lines matched' % (len(matching), len(lines)))
        return '\n'.join(matching)

    def get_regexp_matches(self, string, pattern, *groups):
        """Returns a list of all non-overlapping matches in the given string.

        ``string`` is the string to find matches from and ``pattern`` is the
        regular expression. See `BuiltIn.Should Match Regexp` for more
        information about Python regular expression syntax in general and how
        to use it in Robot Framework test data in particular.

        If no groups are used, the returned list contains full matches. If one
        group is used, the list contains only contents of that group. If
        multiple groups are used, the list contains tuples that contain
        individual group contents. All groups can be given as indexes (starting
        from 1) and named groups also as names.

        Examples:
        | ${no match} =    | Get Regexp Matches | the string | xxx     |
        | ${matches} =     | Get Regexp Matches | the string | t..     |
        | ${one group} =   | Get Regexp Matches | the string | t(..)   | 1 |
        | ${named group} = | Get Regexp Matches | the string | t(?P<name>..) | name |
        | ${two groups} =  | Get Regexp Matches | the string | t(.)(.) | 1 | 2 |
        =>
        | ${no match} = []
        | ${matches} = ['the', 'tri']
        | ${one group} = ['he', 'ri']
        | ${named group} = ['he', 'ri']
        | ${two groups} = [('h', 'e'), ('r', 'i')]

        New in Robot Framework 2.9.
        """
        regexp = re.compile(pattern)
        groups = [self._parse_group(g) for g in groups]
        return [m.group(*groups) for m in regexp.finditer(string)]

    def _parse_group(self, group):
        try:
            return int(group)
        except ValueError:
            return group

    def replace_string(self, string, search_for, replace_with, count=-1):
        """Replaces ``search_for`` in the given ``string`` with ``replace_with``.

        ``search_for`` is used as a literal string. See `Replace String
        Using Regexp` if more powerful pattern matching is needed.
        If you need to just remove a string see `Remove String`.

        If the optional argument ``count`` is given, only that many
        occurrences from left are replaced. Negative ``count`` means
        that all occurrences are replaced (default behaviour) and zero
        means that nothing is done.

        A modified version of the string is returned and the original
        string is not altered.

        Examples:
        | ${str} =        | Replace String | Hello, world!  | world | tellus   |
        | Should Be Equal | ${str}         | Hello, tellus! |       |          |
        | ${str} =        | Replace String | Hello, world!  | l     | ${EMPTY} | count=1 |
        | Should Be Equal | ${str}         | Helo, world!   |       |          |
        """
        count = self._convert_to_integer(count, 'count')
        return string.replace(search_for, replace_with, count)

    def replace_string_using_regexp(self,
                                    string,
                                    pattern,
                                    replace_with,
                                    count=-1):
        """Replaces ``pattern`` in the given ``string`` with ``replace_with``.

        This keyword is otherwise identical to `Replace String`, but
        the ``pattern`` to search for is considered to be a regular
        expression.  See `BuiltIn.Should Match Regexp` for more
        information about Python regular expression syntax in general
        and how to use it in Robot Framework test data in particular.

        If you need to just remove a string see `Remove String Using Regexp`.

        Examples:
        | ${str} = | Replace String Using Regexp | ${str} | 20\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d | <DATE> |
        | ${str} = | Replace String Using Regexp | ${str} | (Hello|Hi) | ${EMPTY} | count=1 |
        """
        count = self._convert_to_integer(count, 'count')
        # re.sub handles 0 and negative counts differently than string.replace
        if count == 0:
            return string
        return re.sub(pattern, replace_with, string, max(count, 0))

    def remove_string(self, string, *removables):
        """Removes all ``removables`` from the given ``string``.

        ``removables`` are used as literal strings. Each removable will be
        matched to a temporary string from which preceding removables have
        been already removed. See second example below.

        Use `Remove String Using Regexp` if more powerful pattern matching is
        needed. If only a certain number of matches should be removed,
        `Replace String` or `Replace String Using Regexp` can be used.

        A modified version of the string is returned and the original
        string is not altered.

        Examples:
        | ${str} =        | Remove String | Robot Framework | work   |
        | Should Be Equal | ${str}        | Robot Frame     |
        | ${str} =        | Remove String | Robot Framework | o | bt |
        | Should Be Equal | ${str}        | R Framewrk      |
        """
        for removable in removables:
            string = self.replace_string(string, removable, '')
        return string

    def remove_string_using_regexp(self, string, *patterns):
        """Removes ``patterns`` from the given ``string``.

        This keyword is otherwise identical to `Remove String`, but
        the ``patterns`` to search for are considered to be a regular
        expression. See `Replace String Using Regexp` for more information
        about the regular expression syntax. That keyword can also be
        used if there is a need to remove only a certain number of
        occurrences.
        """
        for pattern in patterns:
            string = self.replace_string_using_regexp(string, pattern, '')
        return string

    @keyword(types=None)
    def split_string(self, string, separator=None, max_split=-1):
        """Splits the ``string`` using ``separator`` as a delimiter string.

        If a ``separator`` is not given, any whitespace string is a
        separator. In that case also possible consecutive whitespace
        as well as leading and trailing whitespace is ignored.

        Split words are returned as a list. If the optional
        ``max_split`` is given, at most ``max_split`` splits are done, and
        the returned list will have maximum ``max_split + 1`` elements.

        Examples:
        | @{words} =         | Split String | ${string} |
        | @{words} =         | Split String | ${string} | ,${SPACE} |
        | ${pre} | ${post} = | Split String | ${string} | ::    | 1 |

        See `Split String From Right` if you want to start splitting
        from right, and `Fetch From Left` and `Fetch From Right` if
        you only want to get first/last part of the string.
        """
        if separator == '':
            separator = None
        max_split = self._convert_to_integer(max_split, 'max_split')
        return string.split(separator, max_split)

    @keyword(types=None)
    def split_string_from_right(self, string, separator=None, max_split=-1):
        """Splits the ``string`` using ``separator`` starting from right.

        Same as `Split String`, but splitting is started from right. This has
        an effect only when ``max_split`` is given.

        Examples:
        | ${first} | ${rest} = | Split String            | ${string} | - | 1 |
        | ${rest}  | ${last} = | Split String From Right | ${string} | - | 1 |
        """
        if separator == '':
            separator = None
        max_split = self._convert_to_integer(max_split, 'max_split')
        return string.rsplit(separator, max_split)

    def split_string_to_characters(self, string):
        """Splits the given ``string`` to characters.

        Example:
        | @{characters} = | Split String To Characters | ${string} |
        """
        return list(string)

    def fetch_from_left(self, string, marker):
        """Returns contents of the ``string`` before the first occurrence of ``marker``.

        If the ``marker`` is not found, whole string is returned.

        See also `Fetch From Right`, `Split String` and `Split String
        From Right`.
        """
        return string.split(marker)[0]

    def fetch_from_right(self, string, marker):
        """Returns contents of the ``string`` after the last occurrence of ``marker``.

        If the ``marker`` is not found, whole string is returned.

        See also `Fetch From Left`, `Split String` and `Split String
        From Right`.
        """
        return string.split(marker)[-1]

    def generate_random_string(self, length=8, chars='[LETTERS][NUMBERS]'):
        """Generates a string with a desired ``length`` from the given ``chars``.

        The population sequence ``chars`` contains the characters to use
        when generating the random string. It can contain any
        characters, and it is possible to use special markers
        explained in the table below:

        |  = Marker =   |               = Explanation =                   |
        | ``[LOWER]``   | Lowercase ASCII characters from ``a`` to ``z``. |
        | ``[UPPER]``   | Uppercase ASCII characters from ``A`` to ``Z``. |
        | ``[LETTERS]`` | Lowercase and uppercase ASCII characters.       |
        | ``[NUMBERS]`` | Numbers from 0 to 9.                            |

        Examples:
        | ${ret} = | Generate Random String |
        | ${low} = | Generate Random String | 12 | [LOWER]         |
        | ${bin} = | Generate Random String | 8  | 01              |
        | ${hex} = | Generate Random String | 4  | [NUMBERS]abcdef |
        """
        if length == '':
            length = 8
        length = self._convert_to_integer(length, 'length')
        for name, value in [('[LOWER]', ascii_lowercase),
                            ('[UPPER]', ascii_uppercase),
                            ('[LETTERS]', ascii_lowercase + ascii_uppercase),
                            ('[NUMBERS]', digits)]:
            chars = chars.replace(name, value)
        maxi = len(chars) - 1
        return ''.join(chars[randint(0, maxi)] for _ in range(length))

    def get_substring(self, string, start, end=None):
        """Returns a substring from ``start`` index to ``end`` index.

        The ``start`` index is inclusive and ``end`` is exclusive.
        Indexing starts from 0, and it is possible to use
        negative indices to refer to characters from the end.

        Examples:
        | ${ignore first} = | Get Substring | ${string} | 1  |    |
        | ${ignore last} =  | Get Substring | ${string} |    | -1 |
        | ${5th to 10th} =  | Get Substring | ${string} | 4  | 10 |
        | ${first two} =    | Get Substring | ${string} |    | 1  |
        | ${last two} =     | Get Substring | ${string} | -2 |    |
        """
        start = self._convert_to_index(start, 'start')
        end = self._convert_to_index(end, 'end')
        return string[start:end]

    @keyword(types=None)
    def strip_string(self, string, mode='both', characters=None):
        """Remove leading and/or trailing whitespaces from the given string.

        ``mode`` is either ``left`` to remove leading characters, ``right`` to
        remove trailing characters, ``both`` (default) to remove the
        characters from both sides of the string or ``none`` to return the
        unmodified string.

        If the optional ``characters`` is given, it must be a string and the
        characters in the string will be stripped in the string. Please note,
        that this is not a substring to be removed but a list of characters,
        see the example below.

        Examples:
        | ${stripped}=  | Strip String | ${SPACE}Hello${SPACE} | |
        | Should Be Equal | ${stripped} | Hello | |
        | ${stripped}=  | Strip String | ${SPACE}Hello${SPACE} | mode=left |
        | Should Be Equal | ${stripped} | Hello${SPACE} | |
        | ${stripped}=  | Strip String | aabaHelloeee | characters=abe |
        | Should Be Equal | ${stripped} | Hello | |

        New in Robot Framework 3.0.
        """
        try:
            method = {
                'BOTH': string.strip,
                'LEFT': string.lstrip,
                'RIGHT': string.rstrip,
                'NONE': lambda characters: string
            }[mode.upper()]
        except KeyError:
            raise ValueError("Invalid mode '%s'." % mode)
        return method(characters)

    def should_be_string(self, item, msg=None):
        """Fails if the given ``item`` is not a string.

        With Python 2, except with IronPython, this keyword passes regardless
        is the ``item`` a Unicode string or a byte string. Use `Should Be
        Unicode String` or `Should Be Byte String` if you want to restrict
        the string type. Notice that with Python 2, except with IronPython,
        ``'string'`` creates a byte string and ``u'unicode'`` must be used to
        create a Unicode string.

        With Python 3 and IronPython, this keyword passes if the string is
        a Unicode string but fails if it is bytes. Notice that with both
        Python 3 and IronPython, ``'string'`` creates a Unicode string, and
        ``b'bytes'`` must be used to create a byte string.

        The default error message can be overridden with the optional
        ``msg`` argument.
        """
        if not is_string(item):
            self._fail(msg, "'%s' is not a string.", item)

    def should_not_be_string(self, item, msg=None):
        """Fails if the given ``item`` is a string.

        See `Should Be String` for more details about Unicode strings and byte
        strings.

        The default error message can be overridden with the optional
        ``msg`` argument.
        """
        if is_string(item):
            self._fail(msg, "'%s' is a string.", item)

    def should_be_unicode_string(self, item, msg=None):
        """Fails if the given ``item`` is not a Unicode string.

        Use `Should Be Byte String` if you want to verify the ``item`` is a
        byte string, or `Should Be String` if both Unicode and byte strings
        are fine. See `Should Be String` for more details about Unicode
        strings and byte strings.

        The default error message can be overridden with the optional
        ``msg`` argument.
        """
        if not is_unicode(item):
            self._fail(msg, "'%s' is not a Unicode string.", item)

    def should_be_byte_string(self, item, msg=None):
        """Fails if the given ``item`` is not a byte string.

        Use `Should Be Unicode String` if you want to verify the ``item`` is a
        Unicode string, or `Should Be String` if both Unicode and byte strings
        are fine. See `Should Be String` for more details about Unicode strings
        and byte strings.

        The default error message can be overridden with the optional
        ``msg`` argument.
        """
        if not is_bytes(item):
            self._fail(msg, "'%s' is not a byte string.", item)

    def should_be_lowercase(self, string, msg=None):
        """Fails if the given ``string`` is not in lowercase.

        For example, ``'string'`` and ``'with specials!'`` would pass, and
        ``'String'``, ``''`` and ``' '`` would fail.

        The default error message can be overridden with the optional
        ``msg`` argument.

        See also `Should Be Uppercase` and `Should Be Titlecase`.
        """
        if not string.islower():
            self._fail(msg, "'%s' is not lowercase.", string)

    def should_be_uppercase(self, string, msg=None):
        """Fails if the given ``string`` is not in uppercase.

        For example, ``'STRING'`` and ``'WITH SPECIALS!'`` would pass, and
        ``'String'``, ``''`` and ``' '`` would fail.

        The default error message can be overridden with the optional
        ``msg`` argument.

        See also `Should Be Titlecase` and `Should Be Lowercase`.
        """
        if not string.isupper():
            self._fail(msg, "'%s' is not uppercase.", string)

    def should_be_titlecase(self, string, msg=None):
        """Fails if given ``string`` is not title.

        ``string`` is a titlecased string if there is at least one
        character in it, uppercase characters only follow uncased
        characters and lowercase characters only cased ones.

        For example, ``'This Is Title'`` would pass, and ``'Word In UPPER'``,
        ``'Word In lower'``, ``''`` and ``' '`` would fail.

        The default error message can be overridden with the optional
        ``msg`` argument.

        See also `Should Be Uppercase` and `Should Be Lowercase`.
        """
        if not string.istitle():
            self._fail(msg, "'%s' is not titlecase.", string)

    def _convert_to_index(self, value, name):
        if value == '':
            return 0
        if value is None:
            return None
        return self._convert_to_integer(value, name)

    def _convert_to_integer(self, value, name):
        try:
            return int(value)
        except ValueError:
            raise ValueError(
                "Cannot convert '%s' argument '%s' to an integer." %
                (name, value))

    def _fail(self, message, default_template, *items):
        if not message:
            message = default_template % tuple(unic(item) for item in items)
        raise AssertionError(message)
Ejemplo n.º 27
0
class Screenshot(object):
    """Test library for taking screenshots on the machine where tests are run.

    Notice that successfully taking screenshots requires tests to be run with
    a physical or virtual display.

    *Using with Python*

    With Python you need to have one of the following modules installed to be
    able to use this library. The first module that is found will be used.

    - wxPython :: http://wxpython.org :: Required also by RIDE so many Robot
      Framework users already have this module installed.
    - PyGTK :: http://pygtk.org :: This module is available by default on most
      Linux distributions.
    - Python Imaging Library (PIL) :: http://www.pythonware.com/products/pil ::
      This module can take screenshots only on Windows.

    Python support was added in Robot Framework 2.5.5.

    *Using with Jython and IronPython*

    With Jython and IronPython this library uses APIs provided by JVM and .NET
    platforms, respectively. These APIs are always available and thus no
    external modules are needed.

    IronPython support was added in Robot Framework 2.7.5.

    *Where screenshots are saved*

    By default screenshots are saved into the same directory where the Robot
    Framework log file is written. If no log is created, screenshots are saved
    into the directory where the XML output file is written.

    It is possible to specify a custom location for screenshots using
   `screenshot_directory` argument in `importing` and `Set Screenshot Directory`
    keyword during execution. It is also possible to save screenshots using
    an absolute path.

    Note that prior to Robot Framework 2.5.5 the default screenshot location
    was system's temporary directory.

    *Changes in Robot Framework 2.5.5 and Robot Framework 2.6*

    This library was heavily enhanced in Robot Framework 2.5.5 release. The
    changes are listed below and explained more thoroughly in affected places.

    - The support for using this library on Python (see above) was added.
    - The default location where screenshots are saved was changed (see above).
    - New `Take Screenshot` and `Take Screenshot Without Embedding` keywords
      were added. These keywords should be used for taking screenshots in
      the future. Other screenshot taking keywords will be deprecated and
      removed later.
    - `log_file_directory` argument was deprecated everywhere it was used.

    In Robot Framework 2.6, following additional changes were made:

    - `log_file_directory` argument was removed altogether.
    - `Set Screenshot Directories` keyword was removed.
    - `Save Screenshot`, `Save Screenshot To` and `Log Screenshot`
      keywords were deprecated. They will be removed in Robot Framework 2.8.
    """

    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
    ROBOT_LIBRARY_VERSION = get_version()

    def __init__(self, screenshot_directory=None):
        """Configure where screenshots are saved.

        If `screenshot_directory` is not given, screenshots are saved into
        same directory as the log file. The directory can also be set using
        `Set Screenshot Directory` keyword.

        Examples (use only one of these):

        | *Setting* | *Value*  | *Value*    | *Value* |
        | Library | Screenshot |            | # Default location |
        | Library | Screenshot | ${TEMPDIR} | # System temp (this was default prior to 2.5.5) |
        """
        self._given_screenshot_dir = self._norm_path(screenshot_directory)
        self._screenshot_taker = ScreenshotTaker()

    def _norm_path(self, path):
        if not path:
            return path
        return os.path.normpath(path.replace('/', os.sep))

    @property
    def _screenshot_dir(self):
        return self._given_screenshot_dir or self._log_dir

    @property
    def _log_dir(self):
        variables = BuiltIn().get_variables()
        outdir = variables['${OUTPUTDIR}']
        log = variables['${LOGFILE}']
        log = os.path.dirname(log) if log != 'NONE' else '.'
        return self._norm_path(os.path.join(outdir, log))

    def set_screenshot_directory(self, path):
        """Sets the directory where screenshots are saved.

        It is possible to use `/` as a path separator in all operating systems.
        Path to the old directory is returned.

        The directory can also be set in `importing`.
        """
        path = self._norm_path(path)
        if not os.path.isdir(path):
            raise RuntimeError("Directory '%s' does not exist." % path)
        old = self._screenshot_dir
        self._given_screenshot_dir = path
        return old

    def save_screenshot_to(self, path):
        """*DEPRECATED* Use `Take Screenshot` or `Take Screenshot Without Embedding` instead."""
        path = self._screenshot_to_file(path)
        self._link_screenshot(path)
        return path

    def save_screenshot(self, basename="screenshot", directory=None):
        """*DEPRECATED* Use `Take Screenshot` or `Take Screenshot Without Embedding` instead."""
        path = self._save_screenshot(basename, directory)
        self._link_screenshot(path)
        return path

    def log_screenshot(self,
                       basename='screenshot',
                       directory=None,
                       width='100%'):
        """*DEPRECATED* Use `Take Screenshot` or `Take Screenshot Without Embedding` instead."""
        path = self._save_screenshot(basename, directory)
        self._embed_screenshot(path, width)
        return path

    def take_screenshot(self, name="screenshot", width="800px"):
        """Takes a screenshot in JPEG format and embeds it into the log file.

        Name of the file where the screenshot is stored is derived from the
        given `name`. If the `name` ends with extension `.jpg` or `.jpeg`,
        the screenshot will be stored with that exact name. Otherwise a unique
        name is created by adding an underscore, a running index and
        an extension to the `name`.

        The name will be interpreted to be relative to the directory where
        the log file is written. It is also possible to use absolute paths.
        Using `/` as a path separator works in all operating systems.

        `width` specifies the size of the screenshot in the log file.

        Examples: (LOGDIR is determined automatically by the library)
        | Take Screenshot |                  |     | # LOGDIR/screenshot_1.jpg (index automatically incremented) |
        | Take Screenshot | mypic            |     | # LOGDIR/mypic_1.jpg (index automatically incremented) |
        | Take Screenshot | ${TEMPDIR}/mypic |     | # /tmp/mypic_1.jpg (index automatically incremented) |
        | Take Screenshot | pic.jpg          |     | # LOGDIR/pic.jpg (always uses this file) |
        | Take Screenshot | images/login.jpg | 80% | # Specify both name and width. |
        | Take Screenshot | width=550px      |     | # Specify only width. |

        The path where the screenshot is saved is returned.
        """
        path = self._save_screenshot(name)
        self._embed_screenshot(path, width)
        return path

    def take_screenshot_without_embedding(self, name="screenshot"):
        """Takes a screenshot and links it from the log file.

        This keyword is otherwise identical to `Take Screenshot` but the saved
        screenshot is not embedded into the log file. The screenshot is linked
        so it is nevertheless easily available.
        """
        path = self._save_screenshot(name)
        self._link_screenshot(path)
        return path

    def _save_screenshot(self, basename, directory=None):
        path = self._get_screenshot_path(basename, directory)
        return self._screenshot_to_file(path)

    def _screenshot_to_file(self, path):
        path = self._validate_screenshot_path(path)
        logger.debug('Using %s modules for taking screenshot.' %
                     self._screenshot_taker.module)
        try:
            self._screenshot_taker(path)
        except:
            logger.warn(
                'Taking screenshot failed: %s\n'
                'Make sure tests are run with a physical or virtual display.' %
                utils.get_error_message())
        return path

    def _validate_screenshot_path(self, path):
        path = utils.abspath(self._norm_path(path))
        if not os.path.exists(os.path.dirname(path)):
            raise RuntimeError("Directory '%s' where to save the screenshot "
                               "does not exist" % os.path.dirname(path))
        return path

    def _get_screenshot_path(self, basename, directory):
        directory = self._norm_path(
            directory) if directory else self._screenshot_dir
        if basename.lower().endswith(('.jpg', '.jpeg')):
            return os.path.join(directory, basename)
        index = 0
        while True:
            index += 1
            path = os.path.join(directory, "%s_%d.jpg" % (basename, index))
            if not os.path.exists(path):
                return path

    def _embed_screenshot(self, path, width):
        link = utils.get_link_path(path, self._log_dir)
        logger.info('<a href="%s"><img src="%s" width="%s"></a>' %
                    (link, link, width),
                    html=True)

    def _link_screenshot(self, path):
        link = utils.get_link_path(path, self._log_dir)
        logger.info("Screenshot saved to '<a href=\"%s\">%s</a>'." %
                    (link, path),
                    html=True)
Ejemplo n.º 28
0
class String(object):
    """A test library for string manipulation and verification.

    `String` is Robot Framework's standard library for manipulating
    strings (e.g. `Replace String Using Regexp`, `Split To Lines`) and
    verifying their contents (e.g. `Should Be String`).

    Following keywords from `BuiltIn` library can also be used with strings:

    - `Catenate`
    - `Get Length`
    - `Length Should Be`
    - `Should (Not) Be Empty`
    - `Should (Not) Be Equal (As Strings/Integers/Numbers)`
    - `Should (Not) Match (Regexp)`
    - `Should (Not) Contain`
    - `Should (Not) Start With`
    - `Should (Not) End With`
    - `Convert To String`
    - `Convert To Bytes`
    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()

    def encode_string_to_bytes(self, string, encoding, errors='strict'):
        """Encodes the given Unicode `string` to bytes using the given `encoding`.

        `errors` argument controls what to do if encoding some characters fails.
        All values accepted by `encode` method in Python are valid, but in
        practice the following values are most useful:

        - `strict`: fail if characters cannot be encoded (default)
        - `ignore`: ignore characters that cannot be encoded
        - `replace`: replace characters that cannot be encoded with
          a replacement character

        Examples:
        | ${bytes} = | Encode String To Bytes | ${string} | UTF-8 |
        | ${bytes} = | Encode String To Bytes | ${string} | ASCII | errors=ignore |

        Use `Convert To Bytes` in `BuiltIn` if you want to create bytes based
        on character or integer sequences. Use `Decode Bytes To String` if you
        need to convert byte strings to Unicode strings and `Convert To String`
        in `BuiltIn` if you need to convert arbitrary objects to Unicode.

        New in Robot Framework 2.7.7.
        """
        return string.encode(encoding, errors)

    def decode_bytes_to_string(self, bytes, encoding, errors='strict'):
        """Decodes the given `bytes` to a Unicode string using the given `encoding`.

        `errors` argument controls what to do if decoding some bytes fails.
        All values accepted by `decode` method in Python are valid, but in
        practice the following values are most useful:

        - `strict`: fail if characters cannot be decoded (default)
        - `ignore`: ignore characters that cannot be decoded
        - `replace`: replace characters that cannot be decoded with
          a replacement character

        Examples:
        | ${string} = | Decode Bytes To String | ${bytes} | UTF-8 |
        | ${string} = | Decode Bytes To String | ${bytes} | ASCII | errors=ignore |

        Use `Encode String To Bytes` if you need to convert Unicode strings to
        byte strings, and `Convert To String` in `BuiltIn` if you need to
        convert arbitrary objects to Unicode strings.

        New in Robot Framework 2.7.7.
        """
        return bytes.decode(encoding, errors)

    def get_line_count(self, string):
        """Returns and logs the number of lines in the given `string`."""
        count = len(string.splitlines())
        logger.info('%d lines' % count)
        return count

    def split_to_lines(self, string, start=0, end=None):
        """Converts the `string` into a list of lines.

        It is possible to get only a selection of lines from `start`
        to `end` so that `start` index is inclusive and `end` is
        exclusive. Line numbering starts from 0, and it is possible to
        use negative indices to refer to lines from the end.

        Lines are returned without the newlines. The number of
        returned lines is automatically logged.

        Examples:
        | @{lines} =        | Split To Lines | ${manylines} |    |    |
        | @{ignore first} = | Split To Lines | ${manylines} | 1  |    |
        | @{ignore last} =  | Split To Lines | ${manylines} |    | -1 |
        | @{5th to 10th} =  | Split To Lines | ${manylines} | 4  | 10 |
        | @{first two} =    | Split To Lines | ${manylines} |    | 1  |
        | @{last two} =     | Split To Lines | ${manylines} | -2 |    |

        Use `Get Line` if you only need to get a single line.
        """
        start = self._convert_to_index(start, 'start')
        end = self._convert_to_index(end, 'end')
        lines = string.splitlines()[start:end]
        logger.info('%d lines returned' % len(lines))
        return lines

    def get_line(self, string, line_number):
        """Returns the specified line from the given `string`.

        Line numbering starts from 0 and it is possible to use
        negative indices to refer to lines from the end. The line is
        returned without the newline character.

        Examples:
        | ${first} =    | Get Line | ${string} | 0  |
        | ${2nd last} = | Get Line | ${string} | -2 |
        """
        line_number = self._convert_to_integer(line_number, 'line_number')
        return string.splitlines()[line_number]

    def get_lines_containing_string(self,
                                    string,
                                    pattern,
                                    case_insensitive=False):
        """Returns lines of the given `string` that contain the `pattern`.

        The `pattern` is always considered to be a normal string and a
        line matches if the `pattern` is found anywhere in it. By
        default the match is case-sensitive, but setting
        `case_insensitive` to any value makes it case-insensitive.

        Lines are returned as one string catenated back together with
        newlines. Possible trailing newline is never returned. The
        number of matching lines is automatically logged.

        Examples:
        | ${lines} = | Get Lines Containing String | ${result} | An example |
        | ${ret} =   | Get Lines Containing String | ${ret} | FAIL | case-insensitive |

        See `Get Lines Matching Pattern` and `Get Lines Matching Regexp`
        if you need more complex pattern matching.
        """
        if case_insensitive:
            pattern = pattern.lower()
            contains = lambda line: pattern in line.lower()
        else:
            contains = lambda line: pattern in line
        return self._get_matching_lines(string, contains)

    def get_lines_matching_pattern(self,
                                   string,
                                   pattern,
                                   case_insensitive=False):
        """Returns lines of the given `string` that match the `pattern`.

        The `pattern` is a _glob pattern_ where:
        | *        | matches everything |
        | ?        | matches any single character |
        | [chars]  | matches any character inside square brackets (e.g. '[abc]' matches either 'a', 'b' or 'c') |
        | [!chars] | matches any character not inside square brackets |

        A line matches only if it matches the `pattern` fully.  By
        default the match is case-sensitive, but setting
        `case_insensitive` to any value makes it case-insensitive.

        Lines are returned as one string catenated back together with
        newlines. Possible trailing newline is never returned. The
        number of matching lines is automatically logged.

        Examples:
        | ${lines} = | Get Lines Matching Pattern | ${result} | Wild???? example |
        | ${ret} = | Get Lines Matching Pattern | ${ret} | FAIL: * | case-insensitive |

        See `Get Lines Matching Regexp` if you need more complex
        patterns and `Get Lines Containing String` if searching
        literal strings is enough.
        """
        if case_insensitive:
            pattern = pattern.lower()
            matches = lambda line: fnmatchcase(line.lower(), pattern)
        else:
            matches = lambda line: fnmatchcase(line, pattern)
        return self._get_matching_lines(string, matches)

    def get_lines_matching_regexp(self, string, pattern):
        """Returns lines of the given `string` that match the regexp `pattern`.

        See `BuiltIn.Should Match Regexp` for more information about
        Python regular expression syntax in general and how to use it
        in Robot Framework test data in particular. A line matches
        only if it matches the `pattern` fully. Notice that to make
        the match case-insensitive, you need to embed case-insensitive
        flag into the pattern.

        Lines are returned as one string catenated back together with
        newlines. Possible trailing newline is never returned. The
        number of matching lines is automatically logged.

        Examples:
        | ${lines} = | Get Lines Matching Regexp | ${result} | Reg\\\\w{3} example |
        | ${ret} = | Get Lines Matching Regexp | ${ret} | (?i)FAIL: .* |

        See `Get Lines Matching Pattern` and `Get Lines Containing
        String` if you do not need full regular expression powers (and
        complexity).
        """
        regexp = re.compile('^%s$' % pattern)
        return self._get_matching_lines(string, regexp.match)

    def _get_matching_lines(self, string, matches):
        lines = string.splitlines()
        matching = [line for line in lines if matches(line)]
        logger.info('%d out of %d lines matched' % (len(matching), len(lines)))
        return '\n'.join(matching)

    def replace_string(self, string, search_for, replace_with, count=-1):
        """Replaces `search_for` in the given `string` with `replace_with`.

        `search_for` is used as a literal string. See `Replace String
        Using Regexp` if more powerful pattern matching is needed.
        If you need to just remove a string see `Remove String`.

        If the optional argument `count` is given, only that many
        occurrences from left are replaced. Negative `count` means
        that all occurrences are replaced (default behaviour) and zero
        means that nothing is done.

        A modified version of the string is returned and the original
        string is not altered.

        Examples:
        | ${str} =        | Replace String | Hello, world!  | world | tellus   |
        | Should Be Equal | ${str}         | Hello, tellus! |       |          |
        | ${str} =        | Replace String | Hello, world!  | l     | ${EMPTY} | count=1 |
        | Should Be Equal | ${str}         | Helo, world!   |       |          |
        """
        count = self._convert_to_integer(count, 'count')
        return string.replace(search_for, replace_with, count)

    def replace_string_using_regexp(self,
                                    string,
                                    pattern,
                                    replace_with,
                                    count=-1):
        """Replaces `pattern` in the given `string` with `replace_with`.

        This keyword is otherwise identical to `Replace String`, but
        the `pattern` to search for is considered to be a regular
        expression.  See `BuiltIn.Should Match Regexp` for more
        information about Python regular expression syntax in general
        and how to use it in Robot Framework test data in particular.

        If you need to just remove a string see `Remove String Using Regexp`.

        Examples:
        | ${str} = | Replace String Using Regexp | ${str} | 20\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d | <DATE> |
        | ${str} = | Replace String Using Regexp | ${str} | (Hello|Hi) | ${EMPTY} | count=1 |
        """
        count = self._convert_to_integer(count, 'count')
        # re.sub handles 0 and negative counts differently than string.replace
        if count == 0:
            return string
        return re.sub(pattern, replace_with, string, max(count, 0))

    def remove_string(self, string, *removables):
        """Removes all `removables` from the given `string`.

        `removables` are used as literal strings. Each removable will be
        matched to a temporary string from which preceding removables have
        been already removed. See second example below.

        Use `Remove String Using Regexp` if more powerful pattern matching is
        needed. If only a certain number of matches should be removed,
        `Replace String` or `Replace String Using Regexp` can be used.

        A modified version of the string is returned and the original
        string is not altered.

        Examples:
        | ${str} =        | Remove String | Robot Framework | work   |
        | Should Be Equal | ${str}        | Robot Frame     |
        | ${str} =        | Remove String | Robot Framework | o | bt |
        | Should Be Equal | ${str}        | R Framewrk      |

        New in Robot Framework 2.8.2.
        """
        for removable in removables:
            string = self.replace_string(string, removable, '')
        return string

    def remove_string_using_regexp(self, string, *patterns):
        """Removes `patterns` from the given `string`.

        This keyword is otherwise identical to `Remove String`, but
        the `patterns` to search for are considered to be a regular
        expression. See `Replace String Using Regexp` for more information
        about the regular expression syntax. That keyword can also be
        used if there is a need to remove only a certain number of
        occurrences.

        New in Robot Framework 2.8.2.
        """
        for pattern in patterns:
            string = self.replace_string_using_regexp(string, pattern, '')
        return string

    def split_string(self, string, separator=None, max_split=-1):
        """Splits the `string` using `separator` as a delimiter string.

        If a `separator` is not given, any whitespace string is a
        separator. In that case also possible consecutive whitespace
        as well as leading and trailing whitespace is ignored.

        Split words are returned as a list. If the optional
        `max_split` is given, at most `max_split` splits are done, and
        the returned list will have maximum `max_split + 1` elements.

        Examples:
        | @{words} =         | Split String | ${string} |
        | @{words} =         | Split String | ${string} | ,${SPACE} |
        | ${pre} | ${post} = | Split String | ${string} | ::    | 1 |

        See `Split String From Right` if you want to start splitting
        from right, and `Fetch From Left` and `Fetch From Right` if
        you only want to get first/last part of the string.
        """
        if separator == '':
            separator = None
        max_split = self._convert_to_integer(max_split, 'max_split')
        return string.split(separator, max_split)

    def split_string_from_right(self, string, separator=None, max_split=-1):
        """Splits the `string` using `separator` starting from right.

        Same as `Split String`, but splitting is started from right. This has
        an effect only when `max_split` is given.

        Examples:
        | ${first} | ${rest} = | Split String            | ${string} | - | 1 |
        | ${rest}  | ${last} = | Split String From Right | ${string} | - | 1 |
        """
        if separator == '':
            separator = None
        max_split = self._convert_to_integer(max_split, 'max_split')
        return string.rsplit(separator, max_split)

    def split_string_to_characters(self, string):
        """Splits the given `string` to characters.

        Example:
        | @{characters} = | Split String To Characters | ${string} |

        New in Robot Framework 2.7.
        """
        return list(string)

    def fetch_from_left(self, string, marker):
        """Returns contents of the `string` before the first occurrence of `marker`.

        If the `marker` is not found, whole string is returned.

        See also `Fetch From Right`, `Split String` and `Split String
        From Right`.
        """
        return string.split(marker)[0]

    def fetch_from_right(self, string, marker):
        """Returns contents of the `string` after the last occurrence of `marker`.

        If the `marker` is not found, whole string is returned.

        See also `Fetch From Left`, `Split String` and `Split String
        From Right`.
        """
        return string.split(marker)[-1]

    def generate_random_string(self, length=8, chars='[LETTERS][NUMBERS]'):
        """Generates a string with a desired `length` from the given `chars`.

        The population sequence `chars` contains the characters to use
        when generating the random string. It can contain any
        characters, and it is possible to use special markers
        explained in the table below:

        | = Marker =  |              = Explanation =                |
        | _[LOWER]_   | Lowercase ASCII characters from 'a' to 'z'. |
        | _[UPPER]_   | Uppercase ASCII characters from 'A' to 'Z'. |
        | _[LETTERS]_ | Lowercase and uppercase ASCII characters.   |
        | _[NUMBERS]_ | Numbers from 0 to 9. |

        Examples:
        | ${ret} = | Generate Random String |
        | ${low} = | Generate Random String | 12 | [LOWER]         |
        | ${bin} = | Generate Random String | 8  | 01              |
        | ${hex} = | Generate Random String | 4  | [NUMBERS]abcdef |
        """
        if length == '':
            length = 8
        length = self._convert_to_integer(length, 'length')
        for name, value in [('[LOWER]', ascii_lowercase),
                            ('[UPPER]', ascii_uppercase),
                            ('[LETTERS]', ascii_lowercase + ascii_uppercase),
                            ('[NUMBERS]', digits)]:
            chars = chars.replace(name, value)
        maxi = len(chars) - 1
        return ''.join(chars[randint(0, maxi)] for _ in range(length))

    def get_substring(self, string, start, end=None):
        """Returns a substring from `start` index to `end` index.

        The `start` index is inclusive and `end` is exclusive.
        Indexing starts from 0, and it is possible to use
        negative indices to refer to characters from the end.

        Examples:
        | ${ignore first} = | Get Substring | ${string} | 1  |    |
        | ${ignore last} =  | Get Substring | ${string} |    | -1 |
        | ${5th to 10th} =  | Get Substring | ${string} | 4  | 10 |
        | ${first two} =    | Get Substring | ${string} |    | 1  |
        | ${last two} =     | Get Substring | ${string} | -2 |    |
        """
        start = self._convert_to_index(start, 'start')
        end = self._convert_to_index(end, 'end')
        return string[start:end]

    def should_be_string(self, item, msg=None):
        """Fails if the given `item` is not a string.

        This keyword passes regardless is the `item` is a Unicode string or
        a byte string. Use `Should Be Unicode String` or `Should Be Byte
        String` if you want to restrict the string type.

        The default error message can be overridden with the optional
        `msg` argument.
        """
        if not isinstance(item, string_types):
            self._fail(msg, "'%s' is not a string.", item)

    def should_not_be_string(self, item, msg=None):
        """Fails if the given `item` is a string.

        The default error message can be overridden with the optional
        `msg` argument.
        """
        if isinstance(item, string_types):
            self._fail(msg, "'%s' is a string.", item)

    def should_be_unicode_string(self, item, msg=None):
        """Fails if the given `item` is not a Unicode string.

        Use `Should Be Byte String` if you want to verify the `item` is a
        byte string, or `Should Be String` if both Unicode and byte strings
        are fine.

        The default error message can be overridden with the optional
        `msg` argument.

        New in Robot Framework 2.7.7.
        """
        if not isinstance(item, unicode):
            self._fail(msg, "'%s' is not a Unicode string.", item)

    def should_be_byte_string(self, item, msg=None):
        """Fails if the given `item` is not a byte string.

        Use `Should Be Unicode String` if you want to verify the `item` is a
        Unicode string, or `Should Be String` if both Unicode and byte strings
        are fine.

        The default error message can be overridden with the optional
        `msg` argument.

        New in Robot Framework 2.7.7.
        """
        # Python 2.7 also has 'bytes' (alias for 'str')
        if not isinstance(item, bytes):
            self._fail(msg, "'%s' is not a byte string.", item)

    def should_be_lowercase(self, string, msg=None):
        """Fails if the given `string` is not in lowercase.

        For example 'string' and 'with specials!' would pass, and 'String', ''
        and ' ' would fail.

        The default error message can be overridden with the optional
        `msg` argument.

        See also `Should Be Uppercase` and `Should Be Titlecase`.
        All these keywords were added in Robot Framework 2.1.2.
        """
        if not string.islower():
            self._fail(msg, "'%s' is not lowercase.", string)

    def should_be_uppercase(self, string, msg=None):
        """Fails if the given `string` is not in uppercase.

        For example 'STRING' and 'WITH SPECIALS!' would pass, and 'String', ''
        and ' ' would fail.

        The default error message can be overridden with the optional
        `msg` argument.

        See also `Should Be Titlecase` and `Should Be Lowercase`.
        All these keywords were added in Robot Framework 2.1.2.
        """
        if not string.isupper():
            self._fail(msg, "'%s' is not uppercase.", string)

    def should_be_titlecase(self, string, msg=None):
        """Fails if given `string` is not title.

        `string` is a titlecased string if there is at least one
        character in it, uppercase characters only follow uncased
        characters and lowercase characters only cased ones.

        For example 'This Is Title' would pass, and 'Word In UPPER',
        'Word In lower', '' and ' ' would fail.

        The default error message can be overridden with the optional
        `msg` argument.

        See also `Should Be Uppercase` and `Should Be Lowercase`.
        All theses keyword were added in Robot Framework 2.1.2.
        """
        if not string.istitle():
            self._fail(msg, "'%s' is not titlecase.", string)

    def _convert_to_index(self, value, name):
        if value == '':
            return 0
        if value is None:
            return None
        return self._convert_to_integer(value, name)

    def _convert_to_integer(self, value, name):
        try:
            return int(value)
        except ValueError:
            raise ValueError(
                "Cannot convert '%s' argument '%s' to an integer." %
                (name, value))

    def _fail(self, message, default_template, *items):
        if not message:
            message = default_template % tuple(unic(item) for item in items)
        raise AssertionError(message)
Ejemplo n.º 29
0
class Screenshot:
    """A test library for taking full-screen screenshots of the desktop.

    `Screenshot` is Robot Framework's standard library that provides
    keywords to capture and store screenshots of the whole desktop.
    This library is implemented with Java AWT APIs, so it can be used
    only when running Robot Framework on Jython.
    """

    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
    ROBOT_LIBRARY_VERSION = get_version()

    def __init__(self, default_directory=None, log_file_directory=None):
        """Screenshot library can be imported with optional arguments.

        If the `default_directory` is provided, all the screenshots are saved
        into that directory by default. Otherwise the default location is the
        system temporary directory.

        `log_file_directory` is used to create relative paths when screenshots
        are logged. By default the paths to images in the log file are absolute.

        Examples (use only one of these):

        | *Setting* | *Value*  | *Value* | *Value* |
        | Library | Screenshot |         |         |
        | Library | Screenshot | ${CURDIR}/images | |
        | Library | Screenshot | ${OUTPUTDIR} | ${OUTPUTDIR} |

        It is also possible to set these directories using `Set Screenshot
        Directories` keyword.
        """
        self.set_screenshot_directories(default_directory, log_file_directory)

    def set_screenshot_directories(self,
                                   default_directory=None,
                                   log_file_directory=None):
        """Used to set `default_directory` and `log_file_directory`.

        See the `library importing` for details.
        """
        if not default_directory:
            self._default_dir = tempfile.gettempdir()
        else:
            self._default_dir = os.path.normpath(
                default_directory.replace('/', os.sep))
        if not log_file_directory:
            self._log_file_dir = None
        else:
            self._log_file_dir = os.path.normpath(
                log_file_directory.replace('/', os.sep))

    def save_screenshot_to(self, path):
        """Saves a screenshot to the specified file.

        The directory holding the file must exist or an exception is raised.
        """
        path = os.path.abspath(path.replace('/', os.sep))
        if not os.path.exists(os.path.dirname(path)):
            raise RuntimeError(
                "Directory '%s' where to save the screenshot does "
                "not exist" % os.path.dirname(path))
        screensize = Toolkit.getDefaultToolkit().getScreenSize()
        rectangle = Rectangle(0, 0, screensize.width, screensize.height)
        image = Robot().createScreenCapture(rectangle)
        ImageIO.write(image, "jpg", File(path))
        print "Screenshot saved to '%s'" % path
        return path

    def save_screenshot(self, basename="screenshot", directory=None):
        """Saves a screenshot with a generated unique name.

        The unique name is derived based on the provided `basename` and
        `directory` passed in as optional arguments. If a `directory`
        is provided, the screenshot is saved under that directory.
        Otherwise, the `default_directory` set during the library
        import or by the keyword `Set Screenshot Directories` is used.
        If a `basename` for the screenshot file is provided, a unique
        filename is determined by appending an underscore and a running
        counter. Otherwise, the `basename` defaults to 'screenshot'.

        The path where the screenshot is saved is returned.

        Examples:
        | Save Screenshot | mypic | /home/user | # (1) |
        | Save Screenshot | mypic |            | # (2) |
        | Save Screenshot |       |            | # (3) |
        =>
        1. /home/user/mypic_1.jpg, /home/user/mypic_2.jpg, ...
        2. /tmp/mypic_1.jpg, /tmp/mypic_2.jpg, ...
        3. /tmp/screenshot_1.jpg, /tmp/screenshot_2.jpg, ...
        """
        if directory is None:
            directory = self._default_dir
        else:
            directory = directory.replace('/', os.sep)
        index = 0
        while True:
            index += 1
            path = os.path.join(directory, "%s_%d.jpg" % (basename, index))
            if not os.path.exists(path):
                break
        return self.save_screenshot_to(path)

    def log_screenshot(self,
                       basename="screenshot",
                       directory=None,
                       log_file_directory=None,
                       width="100%"):
        """Takes a screenshot and logs it to Robot Framework's log file.

        Saves the files as defined in the keyword `Save Screenshot` and creates
        a picture to Robot Framework's log. `directory` defines the directory
        where the screenshots are saved. By default, its value is
        `default_directory`, which is set at the library import or with the
        keyword `Set Screenshot Directories`. `log_file_directory` is used to
        create relative paths to the pictures. This allows moving the log and
        pictures to different machines and having still working pictures. If
        `log_file_directory` is not given or set (in the same way as
        `default_directory` is set), the paths are absolute.

        The path where the screenshot is saved is returned.
        """
        path = self.save_screenshot(basename, directory)
        if log_file_directory is None:
            log_file_directory = self._log_file_dir
        if log_file_directory is not None:
            link = utils.get_link_path(path, log_file_directory)
        else:
            link = 'file:///' + path.replace('\\', '/')
        print '*HTML* <a href="%s"><img src="%s" width="%s" /></a>' \
              % (link, link, width)
        return path
Ejemplo n.º 30
0
from datetime import datetime
from robot import run
import os
from robot.libraries.BuiltIn import BuiltIn
from . import models as m
from multiprocessing import Pool
import multiprocessing
from operator import itemgetter
from .constants import AppConfig
from .util import RobotLogger
from robot.version import get_version

AppConfig.ROBOT_VERSION = get_version()
if AppConfig.ROBOT_VERSION < '3.2.2':
    from robot.api import TestData, ResourceFile, TestCaseFile
else:
    from robot.api import TestSuiteBuilder, get_model, get_resource_model


def run_task(task):
    # print('worker_started:', multiprocessing.current_process().name, multiprocessing.current_process().pid)
    logger = RobotLogger(__name__).logger
    logger.debug("In Run task")
    logger.debug('BatchID:%s', task.get('Batch_ID'))
    logger.debug('RUN_ID:%s', task.get('RUN_ID'))
    logger.debug('Test Name:%s', task.get('ScriptName'))
    logger.debug('Test Source:%s', task.get('Source'))
    variable_list = []
    logger.debug('Test Type:%s', task.get('TestType'))
    logger.debug('Starting Test Name:%s', task.get('ScriptName'))
Ejemplo n.º 31
0
class Process(object):
    """Robot Framework test library for running processes.

    This library utilizes Python's
    [http://docs.python.org/2/library/subprocess.html|subprocess]
    module and its
    [http://docs.python.org/2/library/subprocess.html#subprocess.Popen|Popen]
    class.

    The library has following main usages:

    - Running processes in system and waiting for their completion using
      `Run Process` keyword.
    - Starting processes on background using `Start Process`.
    - Waiting started process to complete using `Wait For Process` or
      stopping them with `Terminate Process` or `Terminate All Processes`.

    This library is new in Robot Framework 2.8.

    == Table of contents ==

    - `Specifying command and arguments`
    - `Process configuration`
    - `Active process`
    - `Result object`
    - `Boolean arguments`
    - `Example`
    - `Shortcuts`
    - `Keywords`

    = Specifying command and arguments =

    Both `Run Process` and `Start Process` accept the command to execute and
    all arguments passed to the command as separate arguments. This makes usage
    convenient and also allows these keywords to automatically escape possible
    spaces and other special characters in commands and arguments. Notice that
    if a command accepts options that themselves accept values, these options
    and their values must be given as separate arguments.

    When `running processes in shell`, it is also possible to give the whole
    command to execute as a single string. The command can then contain
    multiple commands to be run together. When using this approach, the caller
    is responsible on escaping.

    Examples:
    | `Run Process` | ${tools}${/}prog.py | argument | second arg with spaces |
    | `Run Process` | java | -jar | ${jars}${/}example.jar | --option | value |
    | `Run Process` | prog.py "one arg" && tool.sh | shell=yes | cwd=${tools} |

    Starting from Robot Framework 2.8.6, possible non-string arguments are
    converted to strings automatically.

    = Process configuration =

    `Run Process` and `Start Process` keywords can be configured using
    optional ``**configuration`` keyword arguments. Configuration arguments
    must be given after other arguments passed to these keywords and must
    use syntax like ``name=value``. Available configuration arguments are
    listed below and discussed further in sections afterwards.

    |  = Name =  |                  = Explanation =                      |
    | shell      | Specifies whether to run the command in shell or not. |
    | cwd        | Specifies the working directory.                      |
    | env        | Specifies environment variables given to the process. |
    | env:<name> | Overrides the named environment variable(s) only.     |
    | stdout     | Path of a file where to write standard output.        |
    | stderr     | Path of a file where to write standard error.         |
    | output_encoding | Encoding to use when reading command outputs.    |
    | alias      | Alias given to the process.                           |

    Note that because ``**configuration`` is passed using ``name=value`` syntax,
    possible equal signs in other arguments passed to `Run Process` and
    `Start Process` must be escaped with a backslash like ``name\\=value``.
    See `Run Process` for an example.

    == Running processes in shell ==

    The ``shell`` argument specifies whether to run the process in a shell or
    not. By default shell is not used, which means that shell specific commands,
    like ``copy`` and ``dir`` on Windows, are not available. You can, however,
    run shell scripts and batch files without using a shell.

    Giving the ``shell`` argument any non-false value, such as ``shell=True``,
    changes the program to be executed in a shell. It allows using the shell
    capabilities, but can also make the process invocation operating system
    dependent. Having a shell between the actually started process and this
    library can also interfere communication with the process such as stopping
    it and reading its outputs. Because of these problems, it is recommended
    to use the shell only when absolutely necessary.

    When using a shell it is possible to give the whole command to execute
    as a single string. See `Specifying command and arguments` section for
    examples and more details in general.

    == Current working directory ==

    By default the child process will be executed in the same directory
    as the parent process, the process running tests, is executed. This
    can be changed by giving an alternative location using the ``cwd`` argument.
    Forward slashes in the given path are automatically converted to
    backslashes on Windows.

    `Standard output and error streams`, when redirected to files,
    are also relative to the current working directory possibly set using
    the ``cwd`` argument.

    Example:
    | `Run Process` | prog.exe | cwd=${ROOT}/directory | stdout=stdout.txt |

    == Environment variables ==

    By default the child process will get a copy of the parent process's
    environment variables. The ``env`` argument can be used to give the
    child a custom environment as a Python dictionary. If there is a need
    to specify only certain environment variable, it is possible to use the
    ``env:<name>=<value>`` format to set or override only that named variables.
    It is also possible to use these two approaches together.

    Examples:
    | `Run Process` | program | env=${environ} |
    | `Run Process` | program | env:http_proxy=10.144.1.10:8080 | env:PATH=%{PATH}${:}${PROGDIR} |
    | `Run Process` | program | env=${environ} | env:EXTRA=value |

    == Standard output and error streams ==

    By default processes are run so that their standard output and standard
    error streams are kept in the memory. This works fine normally,
    but if there is a lot of output, the output buffers may get full and
    the program can hang. Additionally on Jython, everything written to
    these in-memory buffers can be lost if the process is terminated.

    To avoid the above mentioned problems, it is possible to use ``stdout``
    and ``stderr`` arguments to specify files on the file system where to
    redirect the outputs. This can also be useful if other processes or
    other keywords need to read or manipulate the outputs somehow.

    Given ``stdout`` and ``stderr`` paths are relative to the `current working
    directory`. Forward slashes in the given paths are automatically converted
    to backslashes on Windows.

    As a special feature, it is possible to redirect the standard error to
    the standard output by using ``stderr=STDOUT``.

    Regardless are outputs redirected to files or not, they are accessible
    through the `result object` returned when the process ends. Commands are
    expected to write outputs using the console encoding, but `output encoding`
    can be configured using the ``output_encoding`` argument if needed.

    Examples:
    | ${result} = | `Run Process` | program | stdout=${TEMPDIR}/stdout.txt | stderr=${TEMPDIR}/stderr.txt |
    | `Log Many`  | stdout: ${result.stdout} | stderr: ${result.stderr} |
    | ${result} = | `Run Process` | program | stderr=STDOUT |
    | `Log`       | all output: ${result.stdout} |

    Note that the created output files are not automatically removed after
    the test run. The user is responsible to remove them if needed.

    == Output encoding ==

    Executed commands are, by default, expected to write outputs to the
    `standard output and error streams` using the encoding used by the
    system console. If the command uses some other encoding, that can be
    configured using the ``output_encoding`` argument. This is especially
    useful on Windows where the console uses a different encoding than rest
    of the system, and many commands use the general system encoding instead
    of the console encoding.

    The value used with the ``output_encoding`` argument must be a valid
    encoding and must match the encoding actually used by the command. As a
    convenience, it is possible to use strings ``CONSOLE`` and ``SYSTEM``
    to specify that the console or system encoding is used, respectively.
    If produced outputs use different encoding then configured, values got
    through the `result object` will be invalid.

    Examples:
    | `Start Process` | program | output_encoding=UTF-8 |
    | `Run Process`   | program | stdout=${path} | output_encoding=SYSTEM |

    The support to set output encoding is new in Robot Framework 3.0.

    == Alias ==

    A custom name given to the process that can be used when selecting the
    `active process`.

    Examples:
    | `Start Process` | program | alias=example |
    | `Run Process`   | python  | -c | print 'hello' | alias=hello |

    = Active process =

    The test library keeps record which of the started processes is currently
    active. By default it is latest process started with `Start Process`,
    but `Switch Process` can be used to select a different one. Using
    `Run Process` does not affect the active process.

    The keywords that operate on started processes will use the active process
    by default, but it is possible to explicitly select a different process
    using the ``handle`` argument. The handle can be the identifier returned by
    `Start Process` or an ``alias`` explicitly given to `Start Process` or
    `Run Process`.

    = Result object =

    `Run Process`, `Wait For Process` and `Terminate Process` keywords return a
    result object that contains information about the process execution as its
    attributes. The same result object, or some of its attributes, can also
    be get using `Get Process Result` keyword. Attributes available in the
    object are documented in the table below.

    | = Attribute = |             = Explanation =               |
    | rc            | Return code of the process as an integer. |
    | stdout        | Contents of the standard output stream.   |
    | stderr        | Contents of the standard error stream.    |
    | stdout_path   | Path where stdout was redirected or ``None`` if not redirected. |
    | stderr_path   | Path where stderr was redirected or ``None`` if not redirected. |

    Example:
    | ${result} =            | `Run Process`         | program               |
    | `Should Be Equal As Integers` | ${result.rc}   | 0                     |
    | `Should Match`         | ${result.stdout}      | Some t?xt*            |
    | `Should Be Empty`      | ${result.stderr}      |                       |
    | ${stdout} =            | `Get File`            | ${result.stdout_path} |
    | `Should Be Equal`      | ${stdout}             | ${result.stdout}      |
    | `File Should Be Empty` | ${result.stderr_path} |                       |

    = Boolean arguments =

    Some keywords accept arguments that are handled as Boolean values true or
    false. If such an argument is given as a string, it is considered false if
    it is either empty or case-insensitively equal to ``false`` or ``no``.
    Other strings are considered true regardless their value, and other
    argument types are tested using same
    [http://docs.python.org/2/library/stdtypes.html#truth-value-testing|rules
    as in Python].

    True examples:
    | `Terminate Process` | kill=True     | # Strings are generally true.    |
    | `Terminate Process` | kill=yes      | # Same as the above.             |
    | `Terminate Process` | kill=${TRUE}  | # Python ``True`` is true.       |
    | `Terminate Process` | kill=${42}    | # Numbers other than 0 are true. |

    False examples:
    | `Terminate Process` | kill=False    | # String ``false`` is false.   |
    | `Terminate Process` | kill=no       | # Also string ``no`` is false. |
    | `Terminate Process` | kill=${EMPTY} | # Empty string is false.       |
    | `Terminate Process` | kill=${FALSE} | # Python ``False`` is false.   |

    Note that prior to Robot Framework 2.8 all non-empty strings, including
    ``false``, were considered true. Additionally, ``no`` is considered false
    only in Robot Framework 2.9 and newer.

    = Example =

    | ***** Settings *****
    | Library           Process
    | Suite Teardown    `Terminate All Processes`    kill=True
    |
    | ***** Test Cases *****
    | Example
    |     `Start Process`    program    arg1    arg2    alias=First
    |     ${handle} =    `Start Process`    command.sh arg | command2.sh    shell=True    cwd=/path
    |     ${result} =    `Run Process`    ${CURDIR}/script.py
    |     `Should Not Contain`    ${result.stdout}    FAIL
    |     `Terminate Process`    ${handle}
    |     ${result} =    `Wait For Process`    First
    |     `Should Be Equal As Integers`    ${result.rc}    0
    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()
    TERMINATE_TIMEOUT = 30
    KILL_TIMEOUT = 10

    def __init__(self):
        self._processes = ConnectionCache('No active process.')
        self._results = {}

    def run_process(self, command, *arguments, **configuration):
        """Runs a process and waits for it to complete.

        ``command`` and ``*arguments`` specify the command to execute and
        arguments passed to it. See `Specifying command and arguments` for
        more details.

        ``**configuration`` contains additional configuration related to
        starting processes and waiting for them to finish. See `Process
        configuration` for more details about configuration related to starting
        processes. Configuration related to waiting for processes consists of
        ``timeout`` and ``on_timeout`` arguments that have same semantics as
        with `Wait For Process` keyword. By default there is no timeout, and
        if timeout is defined the default action on timeout is ``terminate``.

        Returns a `result object` containing information about the execution.

        Note that possible equal signs in ``*arguments`` must be escaped
        with a backslash (e.g. ``name\\=value``) to avoid them to be passed in
        as ``**configuration``.

        Examples:
        | ${result} = | Run Process | python | -c | print 'Hello, world!' |
        | Should Be Equal | ${result.stdout} | Hello, world! |
        | ${result} = | Run Process | ${command} | stderr=STDOUT | timeout=10s |
        | ${result} = | Run Process | ${command} | timeout=1min | on_timeout=continue |
        | ${result} = | Run Process | java -Dname\\=value Example | shell=True | cwd=${EXAMPLE} |

        This keyword does not change the `active process`.

        ``timeout`` and ``on_timeout`` arguments are new in Robot Framework
        2.8.4.
        """
        current = self._processes.current
        timeout = configuration.pop('timeout', None)
        on_timeout = configuration.pop('on_timeout', 'terminate')
        try:
            handle = self.start_process(command, *arguments, **configuration)
            return self.wait_for_process(handle, timeout, on_timeout)
        finally:
            self._processes.current = current

    def start_process(self, command, *arguments, **configuration):
        """Starts a new process on background.

        See `Specifying command and arguments` and `Process configuration`
        for more information about the arguments, and `Run Process` keyword
        for related examples.

        Makes the started process new `active process`. Returns an identifier
        that can be used as a handle to activate the started process if needed.

        Starting from Robot Framework 2.8.5, processes are started so that
        they create a new process group. This allows sending signals to and
        terminating also possible child processes. This is not supported by
        Jython in general nor by Python versions prior to 2.7 on Windows.
        """
        conf = ProcessConfiguration(**configuration)
        command = conf.get_command(command, list(arguments))
        self._log_start(command, conf)
        process = subprocess.Popen(command, **conf.popen_config)
        self._results[process] = ExecutionResult(process, **conf.result_config)
        return self._processes.register(process, alias=conf.alias)

    def _log_start(self, command, config):
        if is_list_like(command):
            command = self.join_command_line(command)
        logger.info(u'Starting process:\n%s' % system_decode(command))
        logger.debug(u'Process configuration:\n%s' % config)

    def is_process_running(self, handle=None):
        """Checks is the process running or not.

        If ``handle`` is not given, uses the current `active process`.

        Returns ``True`` if the process is still running and ``False`` otherwise.
        """
        return self._processes[handle].poll() is None

    def process_should_be_running(self,
                                  handle=None,
                                  error_message='Process is not running.'):
        """Verifies that the process is running.

        If ``handle`` is not given, uses the current `active process`.

        Fails if the process has stopped.
        """
        if not self.is_process_running(handle):
            raise AssertionError(error_message)

    def process_should_be_stopped(self,
                                  handle=None,
                                  error_message='Process is running.'):
        """Verifies that the process is not running.

        If ``handle`` is not given, uses the current `active process`.

        Fails if the process is still running.
        """
        if self.is_process_running(handle):
            raise AssertionError(error_message)

    def wait_for_process(self,
                         handle=None,
                         timeout=None,
                         on_timeout='continue'):
        """Waits for the process to complete or to reach the given timeout.

        The process to wait for must have been started earlier with
        `Start Process`. If ``handle`` is not given, uses the current
        `active process`.

        ``timeout`` defines the maximum time to wait for the process. It can be
        given in
        [http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#time-format|
        various time formats] supported by Robot Framework, for example, ``42``,
        ``42 s``, or ``1 minute 30 seconds``.

        ``on_timeout`` defines what to do if the timeout occurs. Possible values
        and corresponding actions are explained in the table below. Notice
        that reaching the timeout never fails the test.

        | = Value = |               = Action =               |
        | continue  | The process is left running (default). |
        | terminate | The process is gracefully terminated.  |
        | kill      | The process is forcefully stopped.     |

        See `Terminate Process` keyword for more details how processes are
        terminated and killed.

        If the process ends before the timeout or it is terminated or killed,
        this keyword returns a `result object` containing information about
        the execution. If the process is left running, Python ``None`` is
        returned instead.

        Examples:
        | # Process ends cleanly      |                  |                  |
        | ${result} =                 | Wait For Process | example          |
        | Process Should Be Stopped   | example          |                  |
        | Should Be Equal As Integers | ${result.rc}     | 0                |
        | # Process does not end      |                  |                  |
        | ${result} =                 | Wait For Process | timeout=42 secs  |
        | Process Should Be Running   |                  |                  |
        | Should Be Equal             | ${result}        | ${NONE}          |
        | # Kill non-ending process   |                  |                  |
        | ${result} =                 | Wait For Process | timeout=1min 30s | on_timeout=kill |
        | Process Should Be Stopped   |                  |                  |
        | Should Be Equal As Integers | ${result.rc}     | -9               |

        ``timeout`` and ``on_timeout`` are new in Robot Framework 2.8.2.
        """
        process = self._processes[handle]
        logger.info('Waiting for process to complete.')
        if timeout:
            timeout = timestr_to_secs(timeout)
            if not self._process_is_stopped(process, timeout):
                logger.info('Process did not complete in %s.' %
                            secs_to_timestr(timeout))
                return self._manage_process_timeout(handle, on_timeout.lower())
        return self._wait(process)

    def _manage_process_timeout(self, handle, on_timeout):
        if on_timeout == 'terminate':
            return self.terminate_process(handle)
        elif on_timeout == 'kill':
            return self.terminate_process(handle, kill=True)
        else:
            logger.info('Leaving process intact.')
            return None

    def _wait(self, process):
        result = self._results[process]
        result.rc = process.wait() or 0
        result.close_streams()
        logger.info('Process completed.')
        return result

    def terminate_process(self, handle=None, kill=False):
        """Stops the process gracefully or forcefully.

        If ``handle`` is not given, uses the current `active process`.

        By default first tries to stop the process gracefully. If the process
        does not stop in 30 seconds, or ``kill`` argument is given a true value,
        (see `Boolean arguments`) kills the process forcefully. Stops also all
        the child processes of the originally started process.

        Waits for the process to stop after terminating it. Returns a `result
        object` containing information about the execution similarly as `Wait
        For Process`.

        On Unix-like machines graceful termination is done using ``TERM (15)``
        signal and killing using ``KILL (9)``. Use `Send Signal To Process`
        instead if you just want to send either of these signals without
        waiting for the process to stop.

        On Windows graceful termination is done using ``CTRL_BREAK_EVENT``
        event and killing using Win32 API function ``TerminateProcess()``.

        Examples:
        | ${result} =                 | Terminate Process |     |
        | Should Be Equal As Integers | ${result.rc}      | -15 | # On Unixes |
        | Terminate Process           | myproc            | kill=true |

        Limitations:
        - Graceful termination is not supported on Windows by Jython nor by
          Python versions prior to 2.7. Process is killed instead.
        - Stopping the whole process group is not supported by Jython at all
          nor by Python versions prior to 2.7 on Windows.
        - On Windows forceful kill only stops the main process, not possible
          child processes.

        Automatically killing the process if termination fails as well as
        returning a result object are new features in Robot Framework 2.8.2.
        Terminating also possible child processes, including using
        ``CTRL_BREAK_EVENT`` on Windows, is new in Robot Framework 2.8.5.
        """
        process = self._processes[handle]
        if not hasattr(process, 'terminate'):
            raise RuntimeError('Terminating processes is not supported '
                               'by this Python version.')
        terminator = self._kill if is_truthy(kill) else self._terminate
        try:
            terminator(process)
        except OSError:
            if not self._process_is_stopped(process, self.KILL_TIMEOUT):
                raise
            logger.debug('Ignored OSError because process was stopped.')
        return self._wait(process)

    def _kill(self, process):
        logger.info('Forcefully killing process.')
        if hasattr(os, 'killpg'):
            os.killpg(process.pid, signal_module.SIGKILL)
        else:
            process.kill()
        if not self._process_is_stopped(process, self.KILL_TIMEOUT):
            raise RuntimeError('Failed to kill process.')

    def _terminate(self, process):
        logger.info('Gracefully terminating process.')
        # Sends signal to the whole process group both on POSIX and on Windows
        # if supported by the interpreter.
        if hasattr(os, 'killpg'):
            os.killpg(process.pid, signal_module.SIGTERM)
        elif hasattr(signal_module, 'CTRL_BREAK_EVENT'):
            if IRONPYTHON:
                # https://ironpython.codeplex.com/workitem/35020
                ctypes.windll.kernel32.GenerateConsoleCtrlEvent(
                    signal_module.CTRL_BREAK_EVENT, process.pid)
            else:
                process.send_signal(signal_module.CTRL_BREAK_EVENT)
        else:
            process.terminate()
        if not self._process_is_stopped(process, self.TERMINATE_TIMEOUT):
            logger.info('Graceful termination failed.')
            self._kill(process)

    def terminate_all_processes(self, kill=False):
        """Terminates all still running processes started by this library.

        This keyword can be used in suite teardown or elsewhere to make
        sure that all processes are stopped,

        By default tries to terminate processes gracefully, but can be
        configured to forcefully kill them immediately. See `Terminate Process`
        that this keyword uses internally for more details.
        """
        for handle in range(1, len(self._processes) + 1):
            if self.is_process_running(handle):
                self.terminate_process(handle, kill=kill)
        self.__init__()

    def send_signal_to_process(self, signal, handle=None, group=False):
        """Sends the given ``signal`` to the specified process.

        If ``handle`` is not given, uses the current `active process`.

        Signal can be specified either as an integer as a signal name. In the
        latter case it is possible to give the name both with or without ``SIG``
        prefix, but names are case-sensitive. For example, all the examples
        below send signal ``INT (2)``:

        | Send Signal To Process | 2      |        | # Send to active process |
        | Send Signal To Process | INT    |        |                          |
        | Send Signal To Process | SIGINT | myproc | # Send to named process  |

        This keyword is only supported on Unix-like machines, not on Windows.
        What signals are supported depends on the system. For a list of
        existing signals on your system, see the Unix man pages related to
        signal handling (typically ``man signal`` or ``man 7 signal``).

        By default sends the signal only to the parent process, not to possible
        child processes started by it. Notice that when `running processes in
        shell`, the shell is the parent process and it depends on the system
        does the shell propagate the signal to the actual started process.

        To send the signal to the whole process group, ``group`` argument can
        be set to any true value (see `Boolean arguments`). This is not
        supported by Jython, however.

        New in Robot Framework 2.8.2. Support for ``group`` argument is new
        in Robot Framework 2.8.5.
        """
        if os.sep == '\\':
            raise RuntimeError('This keyword does not work on Windows.')
        process = self._processes[handle]
        signum = self._get_signal_number(signal)
        logger.info('Sending signal %s (%d).' % (signal, signum))
        if is_truthy(group) and hasattr(os, 'killpg'):
            os.killpg(process.pid, signum)
        elif hasattr(process, 'send_signal'):
            process.send_signal(signum)
        else:
            raise RuntimeError('Sending signals is not supported '
                               'by this Python version.')

    def _get_signal_number(self, int_or_name):
        try:
            return int(int_or_name)
        except ValueError:
            return self._convert_signal_name_to_number(int_or_name)

    def _convert_signal_name_to_number(self, name):
        try:
            return getattr(signal_module,
                           name if name.startswith('SIG') else 'SIG' + name)
        except AttributeError:
            raise RuntimeError("Unsupported signal '%s'." % name)

    def get_process_id(self, handle=None):
        """Returns the process ID (pid) of the process as an integer.

        If ``handle`` is not given, uses the current `active process`.

        Notice that the pid is not the same as the handle returned by
        `Start Process` that is used internally by this library.
        """
        return self._processes[handle].pid

    def get_process_object(self, handle=None):
        """Return the underlying ``subprocess.Popen`` object.

        If ``handle`` is not given, uses the current `active process`.
        """
        return self._processes[handle]

    def get_process_result(self,
                           handle=None,
                           rc=False,
                           stdout=False,
                           stderr=False,
                           stdout_path=False,
                           stderr_path=False):
        """Returns the specified `result object` or some of its attributes.

        The given ``handle`` specifies the process whose results should be
        returned. If no ``handle`` is given, results of the current `active
        process` are returned. In either case, the process must have been
        finishes before this keyword can be used. In practice this means
        that processes started with `Start Process` must be finished either
        with `Wait For Process` or `Terminate Process` before using this
        keyword.

        If no other arguments than the optional ``handle`` are given, a whole
        `result object` is returned. If one or more of the other arguments
        are given any true value, only the specified attributes of the
        `result object` are returned. These attributes are always returned
        in the same order as arguments are specified in the keyword signature.
        See `Boolean arguments` section for more details about true and false
        values.

        Examples:
        | Run Process           | python             | -c            | print 'Hello, world!' | alias=myproc |
        | # Get result object   |                    |               |
        | ${result} =           | Get Process Result | myproc        |
        | Should Be Equal       | ${result.rc}       | ${0}          |
        | Should Be Equal       | ${result.stdout}   | Hello, world! |
        | Should Be Empty       | ${result.stderr}   |               |
        | # Get one attribute   |                    |               |
        | ${stdout} =           | Get Process Result | myproc        | stdout=true |
        | Should Be Equal       | ${stdout}          | Hello, world! |
        | # Multiple attributes |                    |               |
        | ${stdout}             | ${stderr} =        | Get Process Result |  myproc | stdout=yes | stderr=yes |
        | Should Be Equal       | ${stdout}          | Hello, world! |
        | Should Be Empty       | ${stderr}          |               |

        Although getting results of a previously executed process can be handy
        in general, the main use case for this keyword is returning results
        over the remote library interface. The remote interface does not
        support returning the whole result object, but individual attributes
        can be returned without problems.

        New in Robot Framework 2.8.2.
        """
        result = self._results[self._processes[handle]]
        if result.rc is None:
            raise RuntimeError('Getting results of unfinished processes '
                               'is not supported.')
        attributes = self._get_result_attributes(result, rc, stdout, stderr,
                                                 stdout_path, stderr_path)
        if not attributes:
            return result
        elif len(attributes) == 1:
            return attributes[0]
        return attributes

    def _get_result_attributes(self, result, *includes):
        attributes = (result.rc, result.stdout, result.stderr,
                      result.stdout_path, result.stderr_path)
        includes = (is_truthy(incl) for incl in includes)
        return tuple(attr for attr, incl in zip(attributes, includes) if incl)

    def switch_process(self, handle):
        """Makes the specified process the current `active process`.

        The handle can be an identifier returned by `Start Process` or
        the ``alias`` given to it explicitly.

        Example:
        | Start Process  | prog1    | alias=process1 |
        | Start Process  | prog2    | alias=process2 |
        | # currently active process is process2 |
        | Switch Process | process1 |
        | # now active process is process1 |
        """
        self._processes.switch(handle)

    def _process_is_stopped(self, process, timeout):
        stopped = lambda: process.poll() is not None
        max_time = time.time() + timeout
        while time.time() <= max_time and not stopped():
            time.sleep(min(0.1, timeout))
        return stopped()

    def split_command_line(self, args, escaping=False):
        """Splits command line string into a list of arguments.

        String is split from spaces, but argument surrounded in quotes may
        contain spaces in them. If ``escaping`` is given a true value, then
        backslash is treated as an escape character. It can escape unquoted
        spaces, quotes inside quotes, and so on, but it also requires using
        double backslashes when using Windows paths.

        Examples:
        | @{cmd} = | Split Command Line | --option "value with spaces" |
        | Should Be True | $cmd == ['--option', 'value with spaces'] |

        New in Robot Framework 2.9.2.
        """
        return cmdline2list(args, escaping=escaping)

    def join_command_line(self, *args):
        """Joins arguments into one command line string.

        In resulting command line string arguments are delimited with a space,
        arguments containing spaces are surrounded with quotes, and possible
        quotes are escaped with a backslash.

        If this keyword is given only one argument and that is a list like
        object, then the values of that list are joined instead.

        Example:
        | ${cmd} = | Join Command Line | --option | value with spaces |
        | Should Be Equal | ${cmd} | --option "value with spaces" |

        New in Robot Framework 2.9.2.
        """
        if len(args) == 1 and is_list_like(args[0]):
            args = args[0]
        return subprocess.list2cmdline(args)
Ejemplo n.º 32
0
#  limitations under the License.

import sys

try:
    from robot.common import UserErrorHandler
    from robot.common.model import BaseTestSuite
    from robot.running import TestSuite
    from robot.running.model import RunnableTestSuite, RunnableTestCase
    from robot.conf import RobotSettings
    from robot.running.namespace import Namespace
    from robot.utils import (ArgumentParser, get_timestamp, normalize,
                            elapsed_time_to_string, eq, normalize_tags,
                            unescape, get_elapsed_time)
    from robot import version
    ROBOT_VERSION = version.get_version()
    from robot.errors import DataError, Information
    from robot.output.logger import LOGGER
    LOGGER.disable_automatic_console_logger()
except ImportError, error:
    print """All needed Robot modules could not be imported.
Check your Robot installation."""
    print "Error was: %s" % (error)
    raise error


def XmlTestSuite(suite):
    if ROBOT_VERSION < '2.7':
        from robot.output import TestSuite
        return TestSuite(suite)
    from robot.result import ExecutionResult
Ejemplo n.º 33
0
class Collections(_List, _Dictionary):
    """A test library providing keywords for handling lists and dictionaries.

    ``Collections`` is Robot Framework's standard library that provides a
    set of keywords for handling Python lists and dictionaries. This
    library has keywords, for example, for modifying and getting
    values from lists and dictionaries (e.g. `Append To List`, `Get
    From Dictionary`) and for verifying their contents (e.g. `Lists
    Should Be Equal`, `Dictionary Should Contain Value`).

    = Related keywords in BuiltIn =

    Following keywords in the BuiltIn library can also be used with
    lists and dictionaries:

    | = Keyword Name =             | = Applicable With = | = Comment = |
    | `Create List`                | lists |
    | `Create Dictionary`          | dicts | Was in Collections until RF 2.9. |
    | `Get Length`                 | both  |
    | `Length Should Be`           | both  |
    | `Should Be Empty`            | both  |
    | `Should Not Be Empty`        | both  |
    | `Should Contain`             | both  |
    | `Should Not Contain`         | both  |
    | `Should Contain X Times`     | lists |
    | `Should Not Contain X Times` | lists |
    | `Get Count`                  | lists |

    = Using with list-like and dictionary-like objects =

    List keywords that do not alter the given list can also be used
    with tuples, and to some extend also with other iterables.
    `Convert To List` can be used to convert tuples and other iterables
    to Python ``list`` objects.

    Similarly dictionary keywords can, for most parts, be used with other
    mappings. `Convert To Dictionary` can be used if real Python ``dict``
    objects are needed.

    = Boolean arguments =

    Some keywords accept arguments that are handled as Boolean values true or
    false. If such an argument is given as a string, it is considered false if
    it is either an empty string or case-insensitively equal to ``false``,
    ``none`` or ``no``. Keywords verifying something that allow dropping actual
    and expected values from the possible error message also consider string
    ``no values`` to be false. Other strings are considered true regardless
    their value, and other argument types are tested using the same
    [http://docs.python.org/3/library/stdtypes.html#truth|rules as in Python].

    True examples:
    | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=True    | # Strings are generally true.    |
    | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=yes     | # Same as the above.             |
    | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=${TRUE} | # Python ``True`` is true.       |
    | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=${42}   | # Numbers other than 0 are true. |

    False examples:
    | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=False    | # String ``false`` is false.   |
    | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=no       | # Also string ``no`` is false. |
    | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=${EMPTY} | # Empty string is false.       |
    | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=${FALSE} | # Python ``False`` is false.   |
    | `Lists Should Be Equal` | ${x}   | ${y} | Custom error | values=no values | # ``no values`` works with ``values`` argument |

    Note that prior to Robot Framework 2.9 some keywords considered all
    non-empty strings, including ``False``, to be true.
    Considering ``none`` false is new in Robot Framework 3.0.3.

    = Data in examples =

    List related keywords use variables in format ``${Lx}`` in their examples.
    They mean lists with as many alphabetic characters as specified by ``x``.
    For example, ``${L1}`` means ``['a']`` and ``${L3}`` means
    ``['a', 'b', 'c']``.

    Dictionary keywords use similar ``${Dx}`` variables. For example, ``${D1}``
    means ``{'a': 1}`` and ``${D3}`` means ``{'a': 1, 'b': 2, 'c': 3}``.
    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()

    def should_contain_match(self,
                             list,
                             pattern,
                             msg=None,
                             case_insensitive=False,
                             whitespace_insensitive=False):
        """Fails if ``pattern`` is not found in ``list``.

        See `List Should Contain Value` for an explanation of ``msg``.

        By default, pattern matching is similar to matching files in a shell
        and is case-sensitive and whitespace-sensitive. In the pattern syntax,
        ``*`` matches to anything and ``?`` matches to any single character. You
        can also prepend ``glob=`` to your pattern to explicitly use this pattern
        matching behavior.

        If you prepend ``regexp=`` to your pattern, your pattern will be used
        according to the Python
        [http://docs.python.org/3/library/re.html|re module] regular expression
        syntax. Important note: Backslashes are an escape character, and must
        be escaped with another backslash (e.g. ``regexp=\\\\d{6}`` to search for
        ``\\d{6}``). See `BuiltIn.Should Match Regexp` for more details.

        If ``case_insensitive`` is given a true value (see `Boolean arguments`),
        the pattern matching will ignore case.

        If ``whitespace_insensitive`` is given a true value (see `Boolean
        arguments`), the pattern matching will ignore whitespace.

        Non-string values in lists are ignored when matching patterns.

        The given list is never altered by this keyword.

        See also ``Should Not Contain Match``.

        Examples:
        | Should Contain Match | ${list} | a*              | | | # Match strings beginning with 'a'. |
        | Should Contain Match | ${list} | regexp=a.*      | | | # Same as the above but with regexp. |
        | Should Contain Match | ${list} | regexp=\\\\d{6} | | | # Match strings containing six digits. |
        | Should Contain Match | ${list} | a*  | case_insensitive=True       | | # Match strings beginning with 'a' or 'A'. |
        | Should Contain Match | ${list} | ab* | whitespace_insensitive=yes  | | # Match strings beginning with 'ab' with possible whitespace ignored. |
        | Should Contain Match | ${list} | ab* | whitespace_insensitive=true | case_insensitive=true | # Same as the above but also ignore case. |

        New in Robot Framework 2.8.6.
        """
        matches = _get_matches_in_iterable(list, pattern, case_insensitive,
                                           whitespace_insensitive)
        default = "%s does not contain match for pattern '%s'." \
                  % (seq2str2(list), pattern)
        _verify_condition(matches, default, msg)

    def should_not_contain_match(self,
                                 list,
                                 pattern,
                                 msg=None,
                                 case_insensitive=False,
                                 whitespace_insensitive=False):
        """Fails if ``pattern`` is found in ``list``.

        Exact opposite of `Should Contain Match` keyword. See that keyword
        for information about arguments and usage in general.

        New in Robot Framework 2.8.6.
        """
        matches = _get_matches_in_iterable(list, pattern, case_insensitive,
                                           whitespace_insensitive)
        default = "%s contains match for pattern '%s'." \
                  % (seq2str2(list), pattern)
        _verify_condition(not matches, default, msg)

    def get_matches(self,
                    list,
                    pattern,
                    case_insensitive=False,
                    whitespace_insensitive=False):
        """Returns a list of matches to ``pattern`` in ``list``.

        For more information on ``pattern``, ``case_insensitive``, and
        ``whitespace_insensitive``, see `Should Contain Match`.

        Examples:
        | ${matches}= | Get Matches | ${list} | a* | # ${matches} will contain any string beginning with 'a' |
        | ${matches}= | Get Matches | ${list} | regexp=a.* | # ${matches} will contain any string beginning with 'a' (regexp version) |
        | ${matches}= | Get Matches | ${list} | a* | case_insensitive=${True} | # ${matches} will contain any string beginning with 'a' or 'A' |

        New in Robot Framework 2.8.6.
        """
        return _get_matches_in_iterable(list, pattern, case_insensitive,
                                        whitespace_insensitive)

    def get_match_count(self,
                        list,
                        pattern,
                        case_insensitive=False,
                        whitespace_insensitive=False):
        """Returns the count of matches to ``pattern`` in ``list``.

        For more information on ``pattern``, ``case_insensitive``, and
        ``whitespace_insensitive``, see `Should Contain Match`.

        Examples:
        | ${count}= | Get Match Count | ${list} | a* | # ${count} will be the count of strings beginning with 'a' |
        | ${count}= | Get Match Count | ${list} | regexp=a.* | # ${matches} will be the count of strings beginning with 'a' (regexp version) |
        | ${count}= | Get Match Count | ${list} | a* | case_insensitive=${True} | # ${matches} will be the count of strings beginning with 'a' or 'A' |

        New in Robot Framework 2.8.6.
        """
        return len(
            self.get_matches(list, pattern, case_insensitive,
                             whitespace_insensitive))
Ejemplo n.º 34
0
class Process(object):
    """Robot Framework test library for running processes.

    This library utilizes Python's
    [http://docs.python.org/2.7/library/subprocess.html|subprocess]
    module and its
    [http://docs.python.org/2.7/library/subprocess.html#subprocess.Popen|Popen]
    class.

    The library has following main usages:

    - Running processes in system and waiting for their completion using
      `Run Process` keyword.
    - Starting processes on background using `Start Process`.
    - Waiting started process to complete using `Wait For Process` or
      stopping them with `Terminate Process` or `Terminate All Processes`.

    This library is new in Robot Framework 2.8.

    == Table of contents ==

    - `Specifying command and arguments`
    - `Process configuration`
    - `Active process`
    - `Stopping processes`
    - `Result object`
    - `Using with OperatingSystem library`
    - `Example`

    = Specifying command and arguments =

    Both `Run Process` and `Start Process` accept the command to execute
    and all arguments passed to it as separate arguments. This is convenient
    to use and also allows these keywords to automatically escape possible
    spaces and other special characters in the command or arguments.

    When `running processes in shell`, it is also possible to give the
    whole command to execute as a single string. The command can then
    contain multiple commands, for example, connected with pipes. When
    using this approach the caller is responsible on escaping.

    Examples:
    | `Run Process` | ${progdir}${/}prog.py        | first arg | second         |
    | `Run Process` | script1.sh arg && script2.sh | shell=yes | cwd=${progdir} |

    = Process configuration =

    `Run Process` and `Start Process` keywords can be configured using
    optional `**configuration` keyword arguments. Available configuration
    arguments are listed below and discussed further in sections afterwards.

    | *Name*     | *Explanation*                                         |
    | shell      | Specifies whether to run the command in shell or not  |
    | cwd        | Specifies the working directory.                      |
    | env        | Specifies environment variables given to the process. |
    | env:<name> | Overrides the named environment variable(s) only.     |
    | stdout     | Path of a file where to write standard output.        |
    | stderr     | Path of a file where to write standard error.         |
    | alias      | Alias given to the process.                           |

    Configuration must be given after other arguments passed to these keywords
    and must use syntax `name=value`.

    == Running processes in shell ==

    The `shell` argument specifies whether to run the process in a shell or
    not. By default shell is not used, which means that shell specific
    commands, like `copy` and `dir` on Windows, are not available.

    Giving the `shell` argument any non-false value, such as `shell=True`,
    changes the program to be executed in a shell. It allows using the shell
    capabilities, but can also make the process invocation operating system
    dependent.

    When using a shell it is possible to give the whole command to execute
    as a single string. See `Specifying command and arguments` section for
    more details.

    == Current working directory ==

    By default the child process will be executed in the same directory
    as the parent process, the process running tests, is executed. This
    can be changed by giving an alternative location using the `cwd` argument.
    Forward slashes in the given path are automatically converted to
    backslashes on Windows.

    `Standard output and error streams`, when redirected to files,
    are also relative to the current working directory possibly set using
    the `cwd` argument.

    Example:
    | `Run Process` | prog.exe | cwd=${ROOT}/directory | stdout=stdout.txt |

    == Environment variables ==

    By default the child process will get a copy of the parent process's
    environment variables. The `env` argument can be used to give the
    child a custom environment as a Python dictionary. If there is a need
    to specify only certain environment variable, it is possible to use the
    `env:<name>` format to set or override only that named variables. It is
    also possible to use these two approaches together.

    Examples:
    | `Run Process` | program | env=${environ} |
    | `Run Process` | program | env:PATH=%{PATH}${:}${PROGRAM DIR} |
    | `Run Process` | program | env=${environ} | env:EXTRA=value   |

    == Standard output and error streams ==

    By default processes are run so that their standard output and standard
    error streams are kept in the memory. This works fine normally,
    but if there is a lot of output, the output buffers may get full and
    the program could hang.

    To avoid output buffers getting full, it is possible to use `stdout`
    and `stderr` arguments to specify files on the file system where to
    redirect the outputs. This can also be useful if other processes or
    other keywords need to read or manipulate the outputs somehow.

    Given `stdout` and `stderr` paths are relative to the `current working
    directory`. Forward slashes in the given paths are automatically converted
    to backslashes on Windows.

    As a special feature, it is possible to redirect the standard error to
    the standard output by using `stderr=STDOUT`.

    Regardless are outputs redirected to files or not, they are accessible
    through the `result object` returned when the process ends.

    Examples:
    | ${result} = | `Run Process` | program | stdout=${TEMPDIR}/stdout.txt | stderr=${TEMPDIR}/stderr.txt |
    | `Log Many`  | stdout: ${result.stdout} | stderr: ${result.stderr} |
    | ${result} = | `Run Process` | program | stderr=STDOUT |
    | `Log`       | all output: ${result.stdout} |

    *Note:* The created output files are not automatically removed after
    the test run. The user is responsible to remove them if needed.

    == Alias ==

    A custom name given to the process that can be used when selecting the
    `active process`.

    Example:
    | `Start Process` | program | alias=example |

    = Active process =

    The test library keeps record which of the started processes is currently
    active. By default it is latest process started with `Start Process`,
    but `Switch Process` can be used to select a different one.

    The keywords that operate on started processes will use the active process
    by default, but it is possible to explicitly select a different process
    using the `handle` argument. The handle can be the identifier returned by
    `Start Process` or an explicitly given `alias`.

    = Stopping processes =

    Started processed can be stopped using `Terminate Process` and
    `Terminate All Processes`. The former is used for stopping a selected
    process, and the latter to make sure all processes are stopped, for
    example, in a suite teardown.

    Both keywords use `subprocess`
    [http://docs.python.org/2.7/library/subprocess.html#subprocess.Popen.terminate|terminate()]
    method by default, but can be configured to use
    [http://docs.python.org/2.7/library/subprocess.html#subprocess.Popen.kill|kill()]
    instead.

    Because both `terminate()` and `kill()` methods were added to `subprocess`
    in Python 2.6, stopping processes does not work with Python or Jython 2.5.
    Unfortunately at least beta releases of Jython 2.7
    [http://bugs.jython.org/issue1898|do not seem to support it either].

    Examples:
    | `Terminate Process` | kill=True |
    | `Terminate All Processes` |

    = Result object =

    `Run Process` and `Wait For Process` keywords return a result object
    that contains information about the process execution as its attibutes.
    What is available is documented in the table below.

    | *Attribute* | *Explanation*                             |
    | rc          | Return code of the process as an integer. |
    | stdout      | Contents of the standard output stream.   |
    | stderr      | Contents of the standard error stream.    |
    | stdout_path | Path where stdout was redirected or `None` if not redirected. |
    | stderr_path | Path where stderr was redirected or `None` if not redirected. |

    Example:
    | ${result} =            | `Run Process`         | program               |
    | `Should Be Equal As Integers` | ${result.rc}   |                       |
    | `Should Match`         | ${result.stdout}      | Some t?xt*            |
    | `Should Be Empty`      | ${result.stderr}      |                       |
    | ${stdout} =            | `Get File`            | ${result.stdout_path} |
    | `File Should Be Empty` | ${result.stderr_path} |                       |
    | `Should Be Equal`      | ${result.stdout}      | ${stdout}             |

    = Using with OperatingSystem library =

    The OperatingSystem library also contains keywords for running processes.
    They are not as flexible as the keywords provided by this library, and
    thus not recommended to be used anymore. They may eventually even be
    deprecated.

    There is a name collision because both of these libraries have
    `Start Process` and `Switch Process` keywords. This is handled so that
    if both libraries are imported, the keywords in the Process library are
    used by default. If there is a need to use the OperatingSystem variants,
    it is possible to use `OperatingSystem.Start Process` syntax or use
    the `BuiltIn` keyword `Set Library Search Order` to change the priority.

    Other keywords in the OperatingSystem library can be used freely with
    keywords in the Process library.

    = Example =

    | ***** Settings *****
    | Library    Process
    | Suite Teardown    `Terminate All Processes`    kill=True
    |
    | ***** Test Cases *****
    | Example
    |     `Start Process`    program    arg1   arg2    alias=First
    |     ${handle} =    `Start Process`    command.sh arg | command2.sh   shell=True    cwd=/path
    |     ${result} =    `Run Process`    ${CURDIR}/script.py
    |     `Should Not Contain`    ${result.stdout}    FAIL
    |     `Terminate Process`    ${handle}
    |     ${result} =    `Wait For Process`    First
    |     `Should Be Equal As Integers`   ${result.rc}    0
    """
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_VERSION = get_version()

    def __init__(self):
        self._processes = ConnectionCache('No active process.')
        self._results = {}

    def run_process(self, command, *arguments, **configuration):
        """Runs a process and waits for it to complete.

        See `Specifying command and arguments` and `Process configuration`
        for more information about the arguments.

        Returns a `result object` containing information about the execution.

        This command does not change the `active process`.
        """
        current = self._processes.current
        try:
            handle = self.start_process(command, *arguments, **configuration)
            return self.wait_for_process(handle)
        finally:
            self._processes.current = current

    def start_process(self, command, *arguments, **configuration):
        """Starts a new process on background.

        See `Specifying command and arguments` and `Process configuration`
        for more information about the arguments.

        Makes the started process new `active process`. Returns an identifier
        that can be used as a handle to active the started process if needed.
        """
        config = ProcessConfig(**configuration)
        executable_command = self._cmd(arguments, command, config.shell)
        logger.info('Starting process:\n%s' % executable_command)
        logger.debug('Process configuration:\n%s' % config)
        process = subprocess.Popen(executable_command,
                                   stdout=config.stdout_stream,
                                   stderr=config.stderr_stream,
                                   stdin=subprocess.PIPE,
                                   shell=config.shell,
                                   cwd=config.cwd,
                                   env=config.env,
                                   universal_newlines=True)
        self._results[process] = ExecutionResult(process,
                                                 config.stdout_stream,
                                                 config.stderr_stream)
        return self._processes.register(process, alias=config.alias)

    def _cmd(self, args, command, use_shell):
        command = [encode_to_system(item) for item in [command] + list(args)]
        if not use_shell:
            return command
        if args:
            return subprocess.list2cmdline(command)
        return command[0]

    def is_process_running(self, handle=None):
        """Checks is the process running or not.

        If `handle` is not given, uses the current `active process`.

        Returns `True` if the process is still running and `False` otherwise.
        """
        return self._processes[handle].poll() is None

    def process_should_be_running(self, handle=None,
                                  error_message='Process is not running.'):
        """Verifies that the process is running.

        If `handle` is not given, uses the current `active process`.

        Fails if the process has stopped.
        """
        if not self.is_process_running(handle):
            raise AssertionError(error_message)

    def process_should_be_stopped(self, handle=None,
                                  error_message='Process is running.'):
        """Verifies that the process is not running.

        If `handle` is not given, uses the current `active process`.

        Fails if the process is still running.
        """
        if self.is_process_running(handle):
            raise AssertionError(error_message)

    def wait_for_process(self, handle=None):
        """Waits for the process to complete.

        If `handle` is not given, uses the current `active process`.

        Returns a `result object` containing information about the execution.
        """
        process = self._processes[handle]
        result = self._results[process]
        logger.info('Waiting for process to complete.')
        result.rc = process.wait() or 0
        logger.info('Process completed.')
        return result

    def terminate_process(self, handle=None, kill=False):
        """Terminates the process.

        If `handle` is not given, uses the current `active process`.

        See `Stopping process` for more details.
        """
        process = self._processes[handle]
        try:
            terminator = process.kill if kill else process.terminate
        except AttributeError:
            raise RuntimeError('Terminating processes is not supported '
                               'by this interpreter version.')
        logger.info('Killing process.' if kill else 'Terminating process.')
        try:
            terminator()
        except OSError:
            if process.poll() is None:
                raise
            logger.debug('Ignored OSError because process was stopped.')

    def terminate_all_processes(self, kill=True):
        """Terminates all still running processes started by this library.

        See `Stopping processes` for more details.
        """
        for handle in range(1, len(self._processes) + 1):
            if self.is_process_running(handle):
                self.terminate_process(handle, kill=kill)
        self.__init__()

    def get_process_id(self, handle=None):
        """Returns the process ID (pid) of the process.

        If `handle` is not given, uses the current `active process`.

        Returns the pid assigned by the operating system as an integer.
        Note that with Jython, at least with the 2.5 version, the returned
        pid seems to always be `None`.

        The pid is not the same as the identifier returned by
        `Start Process` that is used internally by this library.
        """
        return self._processes[handle].pid

    def get_process_object(self, handle=None):
        """Return the underlying `subprocess.Popen`  object.

        If `handle` is not given, uses the current `active process`.
        """
        return self._processes[handle]

    def switch_process(self, handle):
        """Makes the specified process the current `active process`.

        The handle can be an identifier returned by `Start Process` or
        the `alias` given to it explicitly.

        Example:
        | `Start Process` | prog1 | alias=process1 |
        | `Start Process` | prog2 | alias=process2 |
        | # currently active process is process2 |
        | `Switch Process` | process1 |
        | # now active process is process 1 |
        """
        self._processes.switch(handle)
Ejemplo n.º 35
0
The library has a known limitation that it cannot be used with timeouts
on Python. Support for IronPython was added in Robot Framework 2.9.2.
"""

from robot.version import get_version
from robot.utils import IRONPYTHON, JYTHON, is_truthy

if JYTHON:
    from .dialogs_jy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog
elif IRONPYTHON:
    from .dialogs_ipy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog
else:
    from .dialogs_py import MessageDialog, PassFailDialog, InputDialog, SelectionDialog


__version__ = get_version()
__all__ = ["execute_manual_step", "get_value_from_user", "get_selection_from_user", "pause_execution"]


def pause_execution(message="Test execution paused. Press OK to continue."):
    """Pauses test execution until user clicks ``Ok`` button.

    ``message`` is the message shown in the dialog.
    """
    MessageDialog(message).show()


def execute_manual_step(message, default_error=""):
    """Pauses test execution until user sets the keyword status.

    User can press either ``PASS`` or ``FAIL`` button. In the latter case execution
Ejemplo n.º 36
0
# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Robot Framework'
copyright = u'2008-2014, Nokia Solutions and Networks'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = VERSION
# The full version, including alpha/beta/rc tags.
release = get_version()

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']