robot.utils package¶
Various generic utility functions and classes.
Utilities are mainly for internal usage, but external libraries and tools may find some of them useful. Utilities are generally stable, but absolute backwards compatibility between major versions is not guaranteed.
All utilities are exposed via the robot.utils
package, and should be
used either like:
from robot import utils
assert utils.Matcher('H?llo').match('Hillo')
or:
from robot.utils import Matcher
assert Matcher('H?llo').match('Hillo')
Submodules¶
robot.utils.application module¶
-
class
robot.utils.application.
Application
(usage, name=None, version=None, arg_limits=None, env_options=None, logger=None, **auto_options)[source]¶ Bases:
object
-
parse_arguments
(cli_args)[source]¶ Public interface for parsing command line arguments.
Parameters: cli_args – Command line arguments as a list Returns: options (dict), arguments (list) Raises: Information
when –help or –version usedRaises: DataError
when parsing fails
-
robot.utils.argumentparser module¶
-
class
robot.utils.argumentparser.
ArgumentParser
(usage, name=None, version=None, arg_limits=None, validator=None, env_options=None, auto_help=True, auto_version=True, auto_pythonpath=True, auto_argumentfile=True)[source]¶ Bases:
object
Available options and tool name are read from the usage.
Tool name is got from the first row of the usage. It is either the whole row or anything before first ‘ – ‘.
-
parse_args
(args)[source]¶ Parse given arguments and return options and positional arguments.
Arguments must be given as a list and are typically sys.argv[1:].
Options are returned as a dictionary where long options are keys. Value is a string for those options that can be given only one time (if they are given multiple times the last value is used) or None if the option is not used at all. Value for options that can be given multiple times (denoted with ‘*’ in the usage) is a list which contains all the given values and is empty if options are not used. Options not taken arguments have value False when they are not set and True otherwise.
Positional arguments are returned as a list in the order they are given.
If ‘check_args’ is True, this method will automatically check that correct number of arguments, as parsed from the usage line, are given. If the last argument in the usage line ends with the character ‘s’, the maximum number of arguments is infinite.
Possible errors in processing arguments are reported using DataError.
Some options have a special meaning and are handled automatically if defined in the usage and given from the command line:
–argumentfile can be used to automatically read arguments from a specified file. When –argumentfile is used, the parser always allows using it multiple times. Adding ‘*’ to denote that is thus recommend. A special value ‘stdin’ can be used to read arguments from stdin instead of a file.
–pythonpath can be used to add extra path(s) to sys.path.
–help and –version automatically generate help and version messages. Version is generated based on the tool name and version – see __init__ for information how to set them. Help contains the whole usage given to __init__. Possible <VERSION> text in the usage is replaced with the given version. Both help and version are wrapped to Information exception.
-
robot.utils.asserts module¶
Convenience functions for testing both in unit and higher levels.
- Benefits:
- Integrates 100% with unittest (see example below)
- Can be easily used without unittest (using unittest.TestCase when you only need convenient asserts is not so nice)
- Saved typing and shorter lines because no need to have ‘self.’ before asserts. These are static functions after all so that is OK.
- All ‘equals’ methods (by default) report given values even if optional message given. This behavior can be controlled with the optional values argument.
- Drawbacks:
- unittest is not able to filter as much non-interesting traceback away as with its own methods because AssertionErrors occur outside.
Most of the functions are copied more or less directly from unittest.TestCase which comes with the following license. Further information about unittest in general can be found from http://pyunit.sourceforge.net/. This module can be used freely in same terms as unittest.
unittest license:
Copyright (c) 1999-2003 Steve Purcell
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.
IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Examples:
import unittest
from robot.utils.asserts import assert_equal
class MyTests(unittest.TestCase):
def test_old_style(self):
self.assertEqual(1, 2, 'my msg')
def test_new_style(self):
assert_equal(1, 2, 'my msg')
Example output:
FF
======================================================================
FAIL: test_old_style (example.MyTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "example.py", line 7, in test_old_style
self.assertEqual(1, 2, 'my msg')
AssertionError: my msg
======================================================================
FAIL: test_new_style (example.MyTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "example.py", line 10, in test_new_style
assert_equal(1, 2, 'my msg')
File "/path/to/robot/utils/asserts.py", line 181, in assert_equal
_report_inequality_failure(first, second, msg, values, '!=')
File "/path/to/robot/utils/asserts.py", line 229, in _report_inequality_failure
raise AssertionError(msg)
AssertionError: my msg: 1 != 2
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=2)
-
robot.utils.asserts.
assert_true
(expr, msg=None)[source]¶ Fail the test unless the expression is True.
-
robot.utils.asserts.
assert_not_none
(obj, msg=None, values=True)[source]¶ Fail the test if given object is None.
-
robot.utils.asserts.
assert_none
(obj, msg=None, values=True)[source]¶ Fail the test if given object is not None.
-
robot.utils.asserts.
assert_raises
(exc_class, callable_obj, *args, **kwargs)[source]¶ Fail unless an exception of class exc_class is thrown by callable_obj.
callable_obj is invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.
If a correct exception is raised, the exception instance is returned by this method.
-
robot.utils.asserts.
assert_raises_with_msg
(exc_class, expected_msg, callable_obj, *args, **kwargs)[source]¶ Similar to fail_unless_raises but also checks the exception message.
-
robot.utils.asserts.
assert_equal
(first, second, msg=None, values=True, formatter=None)[source]¶ Fail if given objects are unequal as determined by the ‘==’ operator.
-
robot.utils.asserts.
assert_not_equal
(first, second, msg=None, values=True, formatter=None)[source]¶ Fail if given objects are equal as determined by the ‘==’ operator.
-
robot.utils.asserts.
assert_almost_equal
(first, second, places=7, msg=None, values=True)[source]¶ Fail if the two objects are unequal after rounded to given places.
inequality is determined by object’s difference rounded to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).
-
robot.utils.asserts.
assert_not_almost_equal
(first, second, places=7, msg=None, values=True)[source]¶ Fail if the two objects are unequal after rounded to given places.
Equality is determined by object’s difference rounded to to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).
robot.utils.charwidth module¶
A module to handle different character widths on the console.
Some East Asian characters have width of two on console, and combining characters themselves take no extra space.
See issue 604 [1] for more details about East Asian characters. The issue also contains generate_wild_chars.py script that was originally used to create _EAST_ASIAN_WILD_CHARS mapping. An updated version of the script is attached to issue 1096. Big thanks for xieyanbo for the script and the original patch.
Note that Python’s unicodedata module is not used here because importing it takes several seconds on Jython.
[1] https://github.com/robotframework/robotframework/issues/604 [2] https://github.com/robotframework/robotframework/issues/1096
robot.utils.compat module¶
robot.utils.connectioncache module¶
-
class
robot.utils.connectioncache.
ConnectionCache
(no_current_msg='No open connection.')[source]¶ Bases:
object
Cache for test libs to use with concurrent connections, processes, etc.
The cache stores the registered connections (or other objects) and allows switching between them using generated indices or user given aliases. This is useful with any test library where there’s need for multiple concurrent connections, processes, etc.
This class can, and is, used also outside the core framework by SSHLibrary, Selenium(2)Library, etc. Backwards compatibility is thus important when doing changes.
-
current
= None¶ Current active connection.
-
current_index
¶
-
register
(connection, alias=None)[source]¶ Registers given connection with optional alias and returns its index.
Given connection is set to be the
current
connection.If alias is given, it must be a string. Aliases are case and space insensitive.
The index of the first connection after initialization, and after
close_all()
orempty_cache()
, is 1, second is 2, etc.
-
switch
(alias_or_index)[source]¶ Switches to the connection specified by the given alias or index.
Updates
current
and also returns its new value.Alias is whatever was given to
register()
method and indices are returned by it. Index can be given either as an integer or as a string that can be converted to an integer. Raises an error if no connection with the given index or alias found.
-
get_connection
(alias_or_index=None)[source]¶ Get the connection specified by the given alias or index..
If
alias_or_index
isNone
, returns the current connection if it is active, or raises an error if it is not.Alias is whatever was given to
register()
method and indices are returned by it. Index can be given either as an integer or as a string that can be converted to an integer. Raises an error if no connection with the given index or alias found.
-
close_all
(closer_method='close')[source]¶ Closes connections using given closer method and empties cache.
If simply calling the closer method is not adequate for closing connections, clients should close connections themselves and use
empty_cache()
afterwards.
-
robot.utils.dotdict module¶
-
class
robot.utils.dotdict.
DotDict
(*args, **kwds)[source]¶ Bases:
collections.OrderedDict
-
clear
() → None. Remove all items from od.¶
-
copy
() → a shallow copy of od¶
-
classmethod
fromkeys
(S[, v]) → New ordered dictionary with keys from S.¶ If not specified, the value defaults to None.
-
get
(k[, d]) → D[k] if k in D, else d. d defaults to None.¶
-
has_key
(k) → True if D has a key k, else False¶
-
items
() → list of (key, value) pairs in od¶
-
iteritems
()¶ od.iteritems -> an iterator over the (key, value) pairs in od
-
iterkeys
() → an iterator over the keys in od¶
-
itervalues
()¶ od.itervalues -> an iterator over the values in od
-
keys
() → list of keys in od¶
-
pop
(k[, d]) → v, remove specified key and return the corresponding¶ value. If key is not found, d is returned if given, otherwise KeyError is raised.
-
popitem
() → (k, v), return and remove a (key, value) pair.¶ Pairs are returned in LIFO order if last is true or FIFO order if false.
-
setdefault
(k[, d]) → od.get(k,d), also set od[k]=d if k not in od¶
-
update
([E, ]**F) → None. Update D from mapping/iterable E and F.¶ If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
-
values
() → list of values in od¶
-
viewitems
() → a set-like object providing a view on od's items¶
-
viewkeys
() → a set-like object providing a view on od's keys¶
-
viewvalues
() → an object providing a view on od's values¶
-
robot.utils.encoding module¶
-
robot.utils.encoding.
console_decode
(string, encoding='UTF-8', force=False)[source]¶ Decodes bytes from console encoding to Unicode.
By default uses the system console encoding, but that can be configured using the encoding argument. In addition to the normal encodings, it is possible to use case-insensitive values CONSOLE and SYSTEM to use the system console and system encoding, respectively.
By default returns Unicode strings as-is. The force argument can be used on IronPython where all strings are unicode and caller knows decoding is needed.
-
robot.utils.encoding.
console_encode
(string, encoding=None, errors='replace', stream=<open file '<stdout>', mode 'w'>, force=False)[source]¶ Encodes Unicode to bytes in console or system encoding.
If encoding is not given, determines it based on the given stream and system configuration. In addition to the normal encodings, it is possible to use case-insensitive values CONSOLE and SYSTEM to use the system console and system encoding, respectively.
On Python 3 and IronPython returns Unicode unless force is True in which case returns bytes. Otherwise always returns bytes.
robot.utils.encodingsniffer module¶
robot.utils.error module¶
-
robot.utils.error.
get_error_message
()[source]¶ Returns error message of the last occurred exception.
This method handles also exceptions containing unicode messages. Thus it MUST be used to get messages from all exceptions originating outside the framework.
-
robot.utils.error.
get_error_details
(exclude_robot_traces=True)[source]¶ Returns error message and details of the last occurred exception.
-
robot.utils.error.
ErrorDetails
(exc_info=None, exclude_robot_traces=True)[source]¶ This factory returns an object that wraps the last occurred exception
It has attributes message, traceback and error, where message contains type and message of the original error, traceback contains the traceback/stack trace and error contains the original error instance.
robot.utils.escaping module¶
robot.utils.etreewrapper module¶
robot.utils.filereader module¶
-
class
robot.utils.filereader.
FileReader
(source, accept_text=False)[source]¶ Bases:
object
Utility to ease reading different kind of files.
Supports different sources where to read the data:
- The source can be a path to a file, either as a string or as a
pathlib.Path
instance in Python 3. The file itself must be UTF-8 encoded. - Alternatively the source can be an already opened file object, including a StringIO or BytesIO object. The file can contain either Unicode text or UTF-8 encoded bytes.
- The third options is giving the source as Unicode text directly.
This requires setting
accept_text=True
when creating the reader.
In all cases bytes are automatically decoded to Unicode and possible BOM removed.
- The source can be a path to a file, either as a string or as a
robot.utils.frange module¶
robot.utils.htmlformatters module¶
-
class
robot.utils.htmlformatters.
LineFormatter
[source]¶ Bases:
object
-
handles
(line)¶
-
newline
= '\n'¶
-
-
class
robot.utils.htmlformatters.
RulerFormatter
[source]¶ Bases:
robot.utils.htmlformatters._SingleLineFormatter
-
match
()¶ match(string[, pos[, endpos]]) –> match object or None. Matches zero or more characters at the beginning of the string
-
add
(line)¶
-
end
()¶
-
format
(lines)¶
-
handles
(line)¶
-
-
class
robot.utils.htmlformatters.
HeaderFormatter
[source]¶ Bases:
robot.utils.htmlformatters._SingleLineFormatter
-
match
()¶ match(string[, pos[, endpos]]) –> match object or None. Matches zero or more characters at the beginning of the string
-
add
(line)¶
-
end
()¶
-
format
(lines)¶
-
handles
(line)¶
-
-
class
robot.utils.htmlformatters.
ParagraphFormatter
(other_formatters)[source]¶ Bases:
robot.utils.htmlformatters._Formatter
-
add
(line)¶
-
end
()¶
-
handles
(line)¶
-
-
class
robot.utils.htmlformatters.
TableFormatter
[source]¶ Bases:
robot.utils.htmlformatters._Formatter
-
add
(line)¶
-
end
()¶
-
handles
(line)¶
-
robot.utils.importer module¶
-
robot.utils.importer.
invalidate_import_caches
()¶
-
class
robot.utils.importer.
Importer
(type=None, logger=None)[source]¶ Bases:
object
Utility that can import modules and classes based on names and paths.
Imported classes can optionally be instantiated automatically.
Parameters: - type – Type of the thing being imported. Used in error and log messages.
- logger – Logger to be notified about successful imports and other events.
Currently only needs the
info
method, but other level specific methods may be needed in the future. If not given, logging is disabled.
-
import_class_or_module
(name_or_path, instantiate_with_args=None, return_source=False)[source]¶ Imports Python class/module or Java class based on the given name or path.
Parameters: - name_or_path – Name or path of the module or class to import.
- instantiate_with_args – When arguments are given, imported classes are automatically initialized using them.
- return_source – When true, returns a tuple containing the imported module or class and a path to it. By default returns only the imported module or class.
The class or module to import can be specified either as a name, in which case it must be in the module search path, or as a path to the file or directory implementing the module. See
import_class_or_module_by_path()
for more information about importing classes and modules by path.Classes can be imported from the module search path using name like
modulename.ClassName
. If the class name and module name are same, using justCommonName
is enough. When importing a class by a path, the class name and the module name must match.Optional arguments to use when creating an instance are given as a list. Starting from Robot Framework 4.0, both positional and named arguments are supported (e.g.
['positional', 'name=value']
) and arguments are converted automatically based on type hints and default values.If arguments needed when creating an instance are initially embedded into the name or path like
Example:arg1:arg2
, separatesplit_args_from_name_or_path()
function can be used to split them before calling this method.
-
import_class_or_module_by_path
(path, instantiate_with_args=None)[source]¶ Import a Python module or Java class using a file system path.
Parameters: - path – Path to the module or class to import.
- instantiate_with_args – When arguments are given, imported classes are automatically initialized using them.
When importing a Python file, the path must end with
.py
and the actual file must also exist. When importing Java classes, the path must end with.java
or.class
. The Java class file must exist in both cases and in the former case also the source file must exist.Use
import_class_or_module()
to support importing also using name, not only path. See the documentation of that function for more information about creating instances automatically.
robot.utils.markuputils module¶
robot.utils.markupwriters module¶
-
class
robot.utils.markupwriters.
HtmlWriter
(output, write_empty=True, usage=None)[source]¶ Bases:
robot.utils.markupwriters._MarkupWriter
Parameters: - output – Either an opened, file like object, or a path to the
desired output file. In the latter case, the file is created
and clients should use
close()
method to close it. - write_empty – Whether to write empty elements and attributes.
-
close
()¶ Closes the underlying output file.
-
content
(content=None, escape=True, newline=False)¶
-
element
(name, content=None, attrs=None, escape=True, newline=True)¶
-
end
(name, newline=True)¶
-
start
(name, attrs=None, newline=True)¶
- output – Either an opened, file like object, or a path to the
desired output file. In the latter case, the file is created
and clients should use
-
class
robot.utils.markupwriters.
XmlWriter
(output, write_empty=True, usage=None)[source]¶ Bases:
robot.utils.markupwriters._MarkupWriter
Parameters: - output – Either an opened, file like object, or a path to the
desired output file. In the latter case, the file is created
and clients should use
close()
method to close it. - write_empty – Whether to write empty elements and attributes.
-
close
()¶ Closes the underlying output file.
-
content
(content=None, escape=True, newline=False)¶
-
end
(name, newline=True)¶
-
start
(name, attrs=None, newline=True)¶
- output – Either an opened, file like object, or a path to the
desired output file. In the latter case, the file is created
and clients should use
robot.utils.match module¶
robot.utils.misc module¶
-
robot.utils.misc.
roundup
(number, ndigits=0, return_type=None)[source]¶ Rounds number to the given number of digits.
Numbers equally close to a certain precision are always rounded away from zero. By default return value is float when
ndigits
is positive and int otherwise, but that can be controlled withreturn_type
.With the built-in
round()
rounding equally close numbers as well as the return type depends on the Python version.
-
robot.utils.misc.
printable_name
(string, code_style=False)[source]¶ Generates and returns printable name from the given string.
Examples: ‘simple’ -> ‘Simple’ ‘name with spaces’ -> ‘Name With Spaces’ ‘more spaces’ -> ‘More Spaces’ ‘Cases AND spaces’ -> ‘Cases AND Spaces’ ‘’ -> ‘’
If ‘code_style’ is True:
‘mixedCAPSCamel’ -> ‘Mixed CAPS Camel’ ‘camelCaseName’ -> ‘Camel Case Name’ ‘under_score_name’ -> ‘Under Score Name’ ‘under_and space’ -> ‘Under And Space’ ‘miXed_CAPS_nAMe’ -> ‘MiXed CAPS NAMe’ ‘’ -> ‘’
robot.utils.normalizing module¶
-
robot.utils.normalizing.
normalize
(string, ignore=(), caseless=True, spaceless=True)[source]¶ Normalizes given string according to given spec.
By default string is turned to lower case and all whitespace is removed. Additional characters can be removed by giving them in
ignore
list.
-
class
robot.utils.normalizing.
NormalizedDict
(initial=None, ignore=(), caseless=True, spaceless=True)[source]¶ Bases:
_abcoll.MutableMapping
Custom dictionary implementation automatically normalizing keys.
Initialized with possible initial value and normalizing spec.
Initial values can be either a dictionary or an iterable of name/value pairs. In the latter case items are added in the given order.
Normalizing spec has exact same semantics as with the
normalize()
function.-
get
(k[, d]) → D[k] if k in D, else d. d defaults to None.¶
-
items
() → list of D's (key, value) pairs, as 2-tuples¶
-
iteritems
() → an iterator over the (key, value) items of D¶
-
iterkeys
() → an iterator over the keys of D¶
-
itervalues
() → an iterator over the values of D¶
-
keys
() → list of D's keys¶
-
pop
(k[, d]) → v, remove specified key and return the corresponding value.¶ If key is not found, d is returned if given, otherwise KeyError is raised.
-
popitem
() → (k, v), remove and return some (key, value) pair¶ as a 2-tuple; but raise KeyError if D is empty.
-
setdefault
(k[, d]) → D.get(k,d), also set D[k]=d if k not in D¶
-
update
([E, ]**F) → None. Update D from mapping/iterable E and F.¶ If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
-
values
() → list of D's values¶
-