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. = 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 when `importing` the library and using `Set Screenshot Directory` keyword during execution. It is also possible to save screenshots using an absolute path. """ 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 | """ 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 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)
from robotide.lib.robot.errors import DataError, Information from robotide.lib.robot.model import TagPatterns from robotide.lib.robot.output import LOGGER as ROBOT_LOGGER from robotide.lib.robot.output.loggerhelper import LEVELS as LOG_LEVELS from robotide.lib.robot.parsing.datarow import DataRow from robotide.lib.robot.parsing.model import ( TestCase, TestDataDirectory, ResourceFile, TestCaseFile, UserKeyword, Variable, Step, ForLoop, VariableTable, KeywordTable, TestCaseTable, TestCaseFileSettingTable) from robotide.lib.robot.parsing.populators import FromFilePopulator from robotide.lib.robot.parsing.settings import ( Library, Resource, Variables, Comment, _Import, Template, Fixture, Documentation, Timeout, Tags, Return) from robotide.lib.robot.parsing.tablepopulators import ( UserKeywordPopulator, TestCasePopulator) from robotide.lib.robot.parsing.txtreader import TxtReader from robotide.lib.robot.running import TestLibrary, EXECUTION_CONTEXTS from robotide.lib.robot.libraries import STDLIBS as STDLIB_NAMES from robotide.lib.robot.running.usererrorhandler import UserErrorHandler from robotide.lib.robot.running.arguments.embedded import EmbeddedArgumentParser from robotide.lib.robot.utils import normpath, NormalizedDict from robotide.lib.robot.variables import Variables as RobotVariables from robotide.lib.robot.variables import is_scalar_var, is_list_var, is_var, is_dict_var,\ VariableSplitter from robotide.lib.robot.variables.filesetter import VariableFileSetter from robotide.lib.robot.variables.tablesetter import VariableTableReader from robotide.lib.robot.version import get_version ROBOT_VERSION = get_version()
The library has following two limitations: - It is not compatible with IronPython. - It cannot be used with timeouts on Python. """ from robotide.lib.robot.version import get_version from robotide.lib.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=''):
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 an empty string or equal to ``FALSE``, ``NONE``, ``NO``, ``OFF`` or ``0``, case-insensitively. 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/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 | Considering string ``NONE`` false is new in Robot Framework 3.0.3 and considering also ``OFF`` and ``0`` false is new in Robot Framework 3.1. = 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/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. | """ _List._validate_list(self, list) 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. """ _List._validate_list(self, list) 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' | """ _List._validate_list(self, list) 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' | """ _List._validate_list(self, list) return len( self.get_matches(list, pattern, case_insensitive, whitespace_insensitive))
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 robotide.lib.robot.version import get_version from robotide.lib.robot.utils import IRONPYTHON, JYTHON, is_truthy if JYTHON: from .dialogs_jy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog, MultipleSelectionDialog elif IRONPYTHON: from .dialogs_ipy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog, MultipleSelectionDialog else: from .dialogs_py import MessageDialog, PassFailDialog, InputDialog, SelectionDialog, MultipleSelectionDialog __version__ = get_version() __all__ = ['execute_manual_step', 'get_value_from_user', 'get_selection_from_user', 'pause_execution', 'get_selections_from_user'] 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.
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_lowercase(self, string): """Converts string to lowercase. Examples: | ${str1} = | Convert To Lowercase | ABC | | ${str2} = | Convert To Lowercase | 1A2c3D | | Should Be Equal | ${str1} | abc | | Should Be Equal | ${str2} | 1a2c3d | New in Robot Framework 2.8.6. """ # Custom `lower` needed due to IronPython bug. See its code and # comments for more details. return lower(string) def convert_to_uppercase(self, string): """Converts string to uppercase. Examples: | ${str1} = | Convert To Uppercase | abc | | ${str2} = | Convert To Uppercase | 1a2C3d | | Should Be Equal | ${str1} | ABC | | Should Be Equal | ${str2} | 1A2C3D | New in Robot Framework 2.8.6. """ return string.upper() 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): """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`` or ``no``. If the value is not a string, its truth value is got directly in Python. 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`` or ``no``. If the value is not a string, its truth value is got directly in Python. 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`` or ``no``. If the value is not a string, its truth value is got directly in Python. 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 | 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 xrange(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 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. 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. The default error message can be overridden with the optional ``msg`` argument. New in Robot Framework 2.7.7. """ 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. The default error message can be overridden with the optional ``msg`` argument. New in Robot Framework 2.7.7. """ 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)
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 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. | | 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 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. = 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 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 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. This is not supported by Jython in general nor by Python versions prior to 2.7 on Windows. """ 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 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()