code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1
value |
|---|---|---|---|---|---|
from robotide.lib.robot.errors import DataError
from robotide.lib.robot.model import SuiteVisitor
from robotide.lib.robot.utils import html_escape
class Merger(SuiteVisitor):
def __init__(self, result):
self.result = result
self.current = None
def merge(self, merged):
self.result.set_execution_mode(merged)
merged.suite.visit(self)
self.result.errors.add(merged.errors)
def start_suite(self, suite):
try:
self.current = self._find_suite(self.current, suite.name)
except IndexError:
suite.message = self._create_add_message(suite, test=False)
self.current.suites.append(suite)
return False
def _find_suite(self, parent, name):
if not parent:
suite = self._find_root(name)
else:
suite = self._find(parent.suites, name)
suite.starttime = suite.endtime = None
return suite
def _find_root(self, name):
root = self.result.suite
if root.name != name:
raise DataError("Cannot merge outputs containing different root "
"suites. Original suite is '%s' and merged is "
"'%s'." % (root.name, name))
return root
def _find(self, items, name):
for item in items:
if item.name == name:
return item
raise IndexError
def end_suite(self, suite):
self.current = self.current.parent
def visit_test(self, test):
try:
old = self._find(self.current.tests, test.name)
except IndexError:
test.message = self._create_add_message(test)
self.current.tests.append(test)
else:
test.message = self._create_merge_message(test, old)
index = self.current.tests.index(old)
self.current.tests[index] = test
def _create_add_message(self, item, test=True):
prefix = ('*HTML* %s added from merged output.'
% ('Test' if test else 'Suite'))
if not item.message:
return prefix
return ''.join([prefix, '<hr>', self._html_escape(item.message)])
def _html_escape(self, message):
if message.startswith('*HTML*'):
return message[6:].lstrip()
else:
return html_escape(message)
def _create_merge_message(self, new, old):
return ''.join([
'*HTML* Re-executed test has been merged.<hr>',
'New status: %s<br>' % self._format_status(new.status),
'New message: %s<hr>' % self._html_escape(new.message),
'Old status: %s<br>' % self._format_status(old.status),
'Old message: %s' % self._html_escape(old.message)
])
def _format_status(self, status):
return '<span class="%s">%s</span>' % (status.lower(), status) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/result/merger.py | 0.505615 | 0.195172 | merger.py | pypi |
from inspect import cleandoc
from java.nio.charset import StandardCharsets
from java.util import Locale
from javax.lang.model.element.Modifier import PUBLIC
from javax.lang.model.util import ElementFilter
from javax.lang.model.type import TypeKind
from javax.tools import DocumentationTool, ToolProvider
from robotide.lib.robot.utils import normalize, printable_name, split_tags_from_doc
from .model import LibraryDoc, KeywordDoc
class JavaDocBuilder(object):
def build(self, path):
qualified_name, type_element, fields, constructors, methods, elements \
= self._get_documentation_data(path)
libdoc = LibraryDoc(name=qualified_name,
doc=self._get_doc(elements, type_element),
version=self._get_version(fields),
scope=self._get_scope(fields),
named_args=False,
doc_format=self._get_doc_format(fields))
libdoc.inits = self._initializers(elements, constructors)
libdoc.keywords = self._keywords(elements, methods)
return libdoc
def _get_doc(self, elements, element):
doc = elements.getDocComment(element)
return cleandoc(doc or '').rstrip()
def _get_version(self, fields):
return self._get_attr(fields, 'VERSION')
def _get_scope(self, fields):
scope = self._get_attr(fields, 'SCOPE', upper=True)
return {'TESTSUITE': 'test suite',
'GLOBAL': 'global'}.get(scope, 'test suite')
def _get_doc_format(self, fields):
return self._get_attr(fields, 'DOC_FORMAT', upper=True)
def _get_attr(self, fields, name, upper=False):
name = 'ROBOT_LIBRARY_' + name
for field in fields:
if field.getSimpleName().toString() == name:
value = field.getConstantValue()
if upper:
value = normalize(value, ignore='_').upper()
return value
return ''
def _initializers(self, elements, constructors):
inits = [self._keyword_doc(elements, constructor)
for constructor in constructors]
if len(inits) == 1 and not inits[0].args:
return []
return inits
def _keywords(self, elements, methods):
return [self._keyword_doc(elements, method) for method in methods]
def _keyword_doc(self, elements, method):
doc, tags = split_tags_from_doc(self._get_doc(elements, method))
return KeywordDoc(
name=printable_name(method.getSimpleName().toString(),
code_style=True),
args=self._get_keyword_arguments(method),
doc=doc,
tags=tags
)
def _get_keyword_arguments(self, method):
params = method.getParameters()
if not params:
return []
names = [param.getSimpleName().toString() for param in params]
if self._is_varargs(params[-1]):
names[-1] = '*' + names[-1]
elif self._is_kwargs(params[-1]):
names[-1] = '**' + names[-1]
if len(params) > 1 and self._is_varargs(params[-2]):
names[-2] = '*' + names[-2]
return names
def _is_varargs(self, param):
param_type = param.asType()
return (param_type.toString().startswith('java.util.List') or
(param_type.getKind() == TypeKind.ARRAY and
param_type.getComponentType().getKind() != TypeKind.ARRAY))
def _is_kwargs(self, param):
return param.asType().toString().startswith('java.util.Map')
def _get_documentation_data(self, path):
doc_tool = ToolProvider.getSystemDocumentationTool()
file_manager = DocumentationTool.getStandardFileManager(
doc_tool, None, Locale.US, StandardCharsets.UTF_8)
compiler = ToolProvider.getSystemJavaCompiler()
source = file_manager.getJavaFileObjectsFromStrings([path])
task = compiler.getTask(None, None, None, None, None, source)
type_element = task.analyze().iterator().next()
elements = task.getElements()
members = elements.getAllMembers(type_element)
qf_name = type_element.getQualifiedName().toString()
fields = [f for f in ElementFilter.fieldsIn(members)
if PUBLIC in f.getModifiers()]
constructors = [c for c in ElementFilter.constructorsIn(members)
if PUBLIC in c.getModifiers()]
methods = [m for m in ElementFilter.methodsIn(members)
if m.getEnclosingElement() is type_element and
PUBLIC in m.getModifiers()]
return qf_name, type_element, fields, constructors, methods, elements | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libdocpkg/java9builder.py | 0.600657 | 0.219965 | java9builder.py | pypi |
from inspect import cleandoc
from robotide.lib.robot.errors import DataError
from robotide.lib.robot.utils import (JAVA_VERSION, normalize, split_tags_from_doc,
printable_name)
from .model import LibraryDoc, KeywordDoc
class JavaDocBuilder(object):
def build(self, path):
doc = ClassDoc(path)
libdoc = LibraryDoc(name=doc.qualifiedName(),
doc=self._get_doc(doc),
version=self._get_version(doc),
scope=self._get_scope(doc),
named_args=False,
doc_format=self._get_doc_format(doc))
libdoc.inits = self._initializers(doc)
libdoc.keywords = self._keywords(doc)
return libdoc
def _get_doc(self, doc):
text = doc.getRawCommentText()
return cleandoc(text).rstrip()
def _get_version(self, doc):
return self._get_attr(doc, 'VERSION')
def _get_scope(self, doc):
scope = self._get_attr(doc, 'SCOPE', upper=True)
return {'TESTSUITE': 'test suite',
'GLOBAL': 'global'}.get(scope, 'test suite')
def _get_doc_format(self, doc):
return self._get_attr(doc, 'DOC_FORMAT', upper=True)
def _get_attr(self, doc, name, upper=False):
name = 'ROBOT_LIBRARY_' + name
for field in doc.fields():
if field.name() == name and field.isPublic():
value = field.constantValue()
if upper:
value = normalize(value, ignore='_').upper()
return value
return ''
def _initializers(self, doc):
inits = [self._keyword_doc(init) for init in doc.constructors()]
if len(inits) == 1 and not inits[0].args:
return []
return inits
def _keywords(self, doc):
return [self._keyword_doc(m) for m in doc.methods()]
def _keyword_doc(self, method):
doc, tags = split_tags_from_doc(self._get_doc(method))
return KeywordDoc(
name=printable_name(method.name(), code_style=True),
args=self._get_keyword_arguments(method),
doc=doc,
tags=tags
)
def _get_keyword_arguments(self, method):
params = method.parameters()
if not params:
return []
names = [p.name() for p in params]
if self._is_varargs(params[-1]):
names[-1] = '*' + names[-1]
elif self._is_kwargs(params[-1]):
names[-1] = '**' + names[-1]
if len(params) > 1 and self._is_varargs(params[-2]):
names[-2] = '*' + names[-2]
return names
def _is_varargs(self, param):
return (param.typeName().startswith('java.util.List')
or param.type().dimension() == '[]')
def _is_kwargs(self, param):
return param.typeName().startswith('java.util.Map')
def ClassDoc(path):
"""Process the given Java source file and return ClassDoc instance.
Processing is done using com.sun.tools.javadoc APIs. Returned object
implements com.sun.javadoc.ClassDoc interface:
http://docs.oracle.com/javase/7/docs/jdk/api/javadoc/doclet/
"""
try:
from com.sun.tools.javadoc import JavadocTool, Messager, ModifierFilter
from com.sun.tools.javac.util import List, Context
from com.sun.tools.javac.code.Flags import PUBLIC
except ImportError:
raise DataError("Creating documentation from Java source files "
"requires 'tools.jar' to be in CLASSPATH.")
context = Context()
Messager.preRegister(context, 'libdoc')
jdoctool = JavadocTool.make0(context)
filter = ModifierFilter(PUBLIC)
java_names = List.of(path)
if JAVA_VERSION < (1, 8): # API changed in Java 8
root = jdoctool.getRootDocImpl('en', 'utf-8', filter, java_names,
List.nil(), False, List.nil(),
List.nil(), False, False, True)
else:
root = jdoctool.getRootDocImpl('en', 'utf-8', filter, java_names,
List.nil(), List.nil(), False, List.nil(),
List.nil(), False, False, True)
return root.classes()[0] | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libdocpkg/javabuilder.py | 0.579995 | 0.186317 | javabuilder.py | pypi |
import fnmatch
import glob
import io
import os
import shutil
import sys
import tempfile
import time
from robotide.lib.robot.version import get_version
from robotide.lib.robot.api import logger
from robotide.lib.robot.utils import (abspath, ConnectionCache, console_decode, del_env_var,
get_env_var, get_env_vars, get_time, is_truthy,
is_unicode, normpath, parse_time, plural_or_not,
secs_to_timestamp, secs_to_timestr, seq2str,
set_env_var, timestr_to_secs, unic, CONSOLE_ENCODING,
IRONPYTHON, JYTHON, PY2, PY3, SYSTEM_ENCODING, WINDOWS)
__version__ = get_version()
PROCESSES = ConnectionCache('No active processes.')
class OperatingSystem(object):
"""A test library providing keywords for OS related tasks.
``OperatingSystem`` is Robot Framework's standard library that
enables various operating system related tasks to be performed in
the system where Robot Framework is running. It can, among other
things, execute commands (e.g. `Run`), create and remove files and
directories (e.g. `Create File`, `Remove Directory`), check
whether files or directories exists or contain something
(e.g. `File Should Exist`, `Directory Should Be Empty`) and
manipulate environment variables (e.g. `Set Environment Variable`).
== Table of contents ==
- `Path separators`
- `Pattern matching`
- `Tilde expansion`
- `Boolean arguments`
- `Example`
- `Shortcuts`
- `Keywords`
= Path separators =
Because Robot Framework uses the backslash (``\\``) as an escape character
in the test data, using a literal backslash requires duplicating it like
in ``c:\\\\path\\\\file.txt``. That can be inconvenient especially with
longer Windows paths, and thus all keywords expecting paths as arguments
convert forward slashes to backslashes automatically on Windows. This also
means that paths like ``${CURDIR}/path/file.txt`` are operating system
independent.
Notice that the automatic path separator conversion does not work if
the path is only a part of an argument like with `Run` and `Start Process`
keywords. In these cases the built-in variable ``${/}`` that contains
``\\`` or ``/``, depending on the operating system, can be used instead.
= Pattern matching =
Some keywords allow their arguments to be specified as
[http://en.wikipedia.org/wiki/Glob_(programming)|glob patterns] where:
| ``*`` | matches any string, even an empty string |
| ``?`` | matches any single character |
| ``[chars]`` | matches one character in the bracket |
| ``[!chars]`` | matches one character not in the bracket |
| ``[a-z]`` | matches one character from the range in the bracket |
| ``[!a-z]`` | matches one character not from the range in the bracket |
Unless otherwise noted, matching is case-insensitive on
case-insensitive operating systems such as Windows.
Starting from Robot Framework 2.9.1, globbing is not done if the given path
matches an existing file even if it would contain a glob pattern.
= Tilde expansion =
Paths beginning with ``~`` or ``~username`` are expanded to the current or
specified user's home directory, respectively. The resulting path is
operating system dependent, but typically e.g. ``~/robot`` is expanded to
``C:\\Users\\<user>\\robot`` on Windows and ``/home/<user>/robot`` on
Unixes.
The ``~username`` form does not work on Jython.
= 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. 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:
| `Remove Directory` | ${path} | recursive=True | # Strings are generally true. |
| `Remove Directory` | ${path} | recursive=yes | # Same as the above. |
| `Remove Directory` | ${path} | recursive=${TRUE} | # Python ``True`` is true. |
| `Remove Directory` | ${path} | recursive=${42} | # Numbers other than 0 are true. |
False examples:
| `Remove Directory` | ${path} | recursive=False | # String ``false`` is false. |
| `Remove Directory` | ${path} | recursive=no | # Also string ``no`` is false. |
| `Remove Directory` | ${path} | recursive=${EMPTY} | # Empty string is false. |
| `Remove Directory` | ${path} | recursive=${FALSE} | # Python ``False`` is false. |
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.
= Example =
| =Setting= | =Value= |
| Library | OperatingSystem |
| =Variable= | =Value= |
| ${PATH} | ${CURDIR}/example.txt |
| =Test Case= | =Action= | =Argument= | =Argument= |
| Example | Create File | ${PATH} | Some text |
| | File Should Exist | ${PATH} | |
| | Copy File | ${PATH} | ~/file.txt |
| | ${output} = | Run | ${TEMPDIR}${/}script.py arg |
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = __version__
def run(self, command):
"""Runs the given command in the system and returns the output.
The execution status of the command *is not checked* by this
keyword, and it must be done separately based on the returned
output. If the execution return code is needed, either `Run
And Return RC` or `Run And Return RC And Output` can be used.
The standard error stream is automatically redirected to the standard
output stream by adding ``2>&1`` after the executed command. This
automatic redirection is done only when the executed command does not
contain additional output redirections. You can thus freely forward
the standard error somewhere else, for example, like
``my_command 2>stderr.txt``.
The returned output contains everything written into the standard
output or error streams by the command (unless either of them
is redirected explicitly). Many commands add an extra newline
(``\\n``) after the output to make it easier to read in the
console. To ease processing the returned output, this possible
trailing newline is stripped by this keyword.
Examples:
| ${output} = | Run | ls -lhF /tmp |
| Log | ${output} |
| ${result} = | Run | ${CURDIR}${/}tester.py arg1 arg2 |
| Should Not Contain | ${result} | FAIL |
| ${stdout} = | Run | /opt/script.sh 2>/tmp/stderr.txt |
| Should Be Equal | ${stdout} | TEST PASSED |
| File Should Be Empty | /tmp/stderr.txt |
*TIP:* `Run Process` keyword provided by the
[http://robotframework.org/robotframework/latest/libraries/Process.html|
Process library] supports better process configuration and is generally
recommended as a replacement for this keyword.
"""
return self._run(command)[1]
def run_and_return_rc(self, command):
"""Runs the given command in the system and returns the return code.
The return code (RC) is returned as a positive integer in
range from 0 to 255 as returned by the executed command. On
some operating systems (notable Windows) original return codes
can be something else, but this keyword always maps them to
the 0-255 range. Since the RC is an integer, it must be
checked e.g. with the keyword `Should Be Equal As Integers`
instead of `Should Be Equal` (both are built-in keywords).
Examples:
| ${rc} = | Run and Return RC | ${CURDIR}${/}script.py arg |
| Should Be Equal As Integers | ${rc} | 0 |
| ${rc} = | Run and Return RC | /path/to/example.rb arg1 arg2 |
| Should Be True | 0 < ${rc} < 42 |
See `Run` and `Run And Return RC And Output` if you need to get the
output of the executed command.
*TIP:* `Run Process` keyword provided by the
[http://robotframework.org/robotframework/latest/libraries/Process.html|
Process library] supports better process configuration and is generally
recommended as a replacement for this keyword.
"""
return self._run(command)[0]
def run_and_return_rc_and_output(self, command):
"""Runs the given command in the system and returns the RC and output.
The return code (RC) is returned similarly as with `Run And Return RC`
and the output similarly as with `Run`.
Examples:
| ${rc} | ${output} = | Run and Return RC and Output | ${CURDIR}${/}mytool |
| Should Be Equal As Integers | ${rc} | 0 |
| Should Not Contain | ${output} | FAIL |
| ${rc} | ${stdout} = | Run and Return RC and Output | /opt/script.sh 2>/tmp/stderr.txt |
| Should Be True | ${rc} > 42 |
| Should Be Equal | ${stdout} | TEST PASSED |
| File Should Be Empty | /tmp/stderr.txt |
*TIP:* `Run Process` keyword provided by the
[http://robotframework.org/robotframework/latest/libraries/Process.html|
Process library] supports better process configuration and is generally
recommended as a replacement for this keyword.
"""
return self._run(command)
def _run(self, command):
process = _Process(command)
self._info("Running command '%s'." % process)
stdout = process.read()
rc = process.close()
return rc, stdout
def get_file(self, path, encoding='UTF-8', encoding_errors='strict'):
"""Returns the contents of a specified file.
This keyword reads the specified file and returns the contents.
Line breaks in content are converted to platform independent form.
See also `Get Binary File`.
``encoding`` defines the encoding of the file. The default value is
``UTF-8``, which means that UTF-8 and ASCII encoded files are read
correctly. In addition to the encodings supported by the underlying
Python implementation, the following special encoding values can be
used:
- ``SYSTEM``: Use the default system encoding.
- ``CONSOLE``: Use the console encoding. Outside Windows this is same
as the system encoding.
``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.
Support for ``SYSTEM`` and ``CONSOLE`` encodings in Robot Framework 3.0.
"""
path = self._absnorm(path)
self._link("Getting file '%s'.", path)
encoding = self._map_encoding(encoding)
if IRONPYTHON:
# https://github.com/IronLanguages/main/issues/1233
with open(path) as f:
content = f.read().decode(encoding, encoding_errors)
else:
with io.open(path, encoding=encoding, errors=encoding_errors,
newline='') as f:
content = f.read()
return content.replace('\r\n', '\n')
def _map_encoding(self, encoding):
# Python 3 opens files in native system encoding by default.
if PY3 and encoding.upper() == 'SYSTEM':
return None
return {'SYSTEM': SYSTEM_ENCODING,
'CONSOLE': CONSOLE_ENCODING}.get(encoding.upper(), encoding)
def get_binary_file(self, path):
"""Returns the contents of a specified file.
This keyword reads the specified file and returns the contents as is.
See also `Get File`.
"""
path = self._absnorm(path)
self._link("Getting file '%s'.", path)
with open(path, 'rb') as f:
return bytes(f.read())
def grep_file(self, path, pattern, encoding='UTF-8', encoding_errors='strict'):
"""Returns the lines of the specified file that match the ``pattern``.
This keyword reads a file from the file system using the defined
``path``, ``encoding`` and ``encoding_errors`` similarly as `Get File`.
A difference is that only the lines that match the given ``pattern`` are
returned. Lines are returned as a single string catenated back together
with newlines and the number of matched lines is automatically logged.
Possible trailing newline is never returned.
A line matches if it contains the ``pattern`` anywhere in it and
it *does not need to match the pattern fully*. The pattern
matching syntax is explained in `introduction`, and in this
case matching is case-sensitive.
Examples:
| ${errors} = | Grep File | /var/log/myapp.log | ERROR |
| ${ret} = | Grep File | ${CURDIR}/file.txt | [Ww]ildc??d ex*ple |
If more complex pattern matching is needed, it is possible to use
`Get File` in combination with String library keywords like `Get
Lines Matching Regexp`.
"""
pattern = '*%s*' % pattern
path = self._absnorm(path)
lines = []
total_lines = 0
self._link("Reading file '%s'.", path)
with io.open(path, encoding=encoding, errors=encoding_errors) as f:
for line in f.readlines():
total_lines += 1
line = line.rstrip('\r\n')
if fnmatch.fnmatchcase(line, pattern):
lines.append(line)
self._info('%d out of %d lines matched' % (len(lines), total_lines))
return '\n'.join(lines)
def log_file(self, path, encoding='UTF-8', encoding_errors='strict'):
"""Wrapper for `Get File` that also logs the returned file.
The file is logged with the INFO level. If you want something else,
just use `Get File` and the built-in keyword `Log` with the desired
level.
See `Get File` for more information about ``encoding`` and
``encoding_errors`` arguments.
"""
content = self.get_file(path, encoding, encoding_errors)
self._info(content)
return content
# File and directory existence
def should_exist(self, path, msg=None):
"""Fails unless the given path (file or directory) exists.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
if not self._glob(path):
self._fail(msg, "Path '%s' does not exist." % path)
self._link("Path '%s' exists.", path)
def should_not_exist(self, path, msg=None):
"""Fails if the given path (file or directory) exists.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
matches = self._glob(path)
if matches:
self._fail(msg, self._get_matches_error('Path', path, matches))
self._link("Path '%s' does not exist.", path)
def _glob(self, path):
return glob.glob(path) if not os.path.exists(path) else [path]
def _get_matches_error(self, what, path, matches):
if not self._is_glob_path(path):
return "%s '%s' exists." % (what, path)
return "%s '%s' matches %s." % (what, path, seq2str(sorted(matches)))
def _is_glob_path(self, path):
return '*' in path or '?' in path or ('[' in path and ']' in path)
def file_should_exist(self, path, msg=None):
"""Fails unless the given ``path`` points to an existing file.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
matches = [p for p in self._glob(path) if os.path.isfile(p)]
if not matches:
self._fail(msg, "File '%s' does not exist." % path)
self._link("File '%s' exists.", path)
def file_should_not_exist(self, path, msg=None):
"""Fails if the given path points to an existing file.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
matches = [p for p in self._glob(path) if os.path.isfile(p)]
if matches:
self._fail(msg, self._get_matches_error('File', path, matches))
self._link("File '%s' does not exist.", path)
def directory_should_exist(self, path, msg=None):
"""Fails unless the given path points to an existing directory.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
matches = [p for p in self._glob(path) if os.path.isdir(p)]
if not matches:
self._fail(msg, "Directory '%s' does not exist." % path)
self._link("Directory '%s' exists.", path)
def directory_should_not_exist(self, path, msg=None):
"""Fails if the given path points to an existing file.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
matches = [p for p in self._glob(path) if os.path.isdir(p)]
if matches:
self._fail(msg, self._get_matches_error('Directory', path, matches))
self._link("Directory '%s' does not exist.", path)
# Waiting file/dir to appear/disappear
def wait_until_removed(self, path, timeout='1 minute'):
"""Waits until the given file or directory is removed.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
If the path is a pattern, the keyword waits until all matching
items are removed.
The optional ``timeout`` can be used to control the maximum time of
waiting. The timeout is given as a timeout string, e.g. in a format
``15 seconds``, ``1min 10s`` or just ``10``. The time string format is
described in an appendix of Robot Framework User Guide.
If the timeout is negative, the keyword is never timed-out. The keyword
returns immediately, if the path does not exist in the first place.
"""
path = self._absnorm(path)
timeout = timestr_to_secs(timeout)
maxtime = time.time() + timeout
while self._glob(path):
if timeout >= 0 and time.time() > maxtime:
self._fail("'%s' was not removed in %s."
% (path, secs_to_timestr(timeout)))
time.sleep(0.1)
self._link("'%s' was removed.", path)
def wait_until_created(self, path, timeout='1 minute'):
"""Waits until the given file or directory is created.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
If the path is a pattern, the keyword returns when an item matching
it is created.
The optional ``timeout`` can be used to control the maximum time of
waiting. The timeout is given as a timeout string, e.g. in a format
``15 seconds``, ``1min 10s`` or just ``10``. The time string format is
described in an appendix of Robot Framework User Guide.
If the timeout is negative, the keyword is never timed-out. The keyword
returns immediately, if the path already exists.
"""
path = self._absnorm(path)
timeout = timestr_to_secs(timeout)
maxtime = time.time() + timeout
while not self._glob(path):
if timeout >= 0 and time.time() > maxtime:
self._fail("'%s' was not created in %s."
% (path, secs_to_timestr(timeout)))
time.sleep(0.1)
self._link("'%s' was created.", path)
# Dir/file empty
def directory_should_be_empty(self, path, msg=None):
"""Fails unless the specified directory is empty.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
items = self._list_dir(path)
if items:
self._fail(msg, "Directory '%s' is not empty. Contents: %s."
% (path, seq2str(items, lastsep=', ')))
self._link("Directory '%s' is empty.", path)
def directory_should_not_be_empty(self, path, msg=None):
"""Fails if the specified directory is empty.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
items = self._list_dir(path)
if not items:
self._fail(msg, "Directory '%s' is empty." % path)
self._link("Directory '%%s' contains %d item%s."
% (len(items), plural_or_not(items)), path)
def file_should_be_empty(self, path, msg=None):
"""Fails unless the specified file is empty.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
if not os.path.isfile(path):
self._error("File '%s' does not exist." % path)
size = os.stat(path).st_size
if size > 0:
self._fail(msg,
"File '%s' is not empty. Size: %d bytes." % (path, size))
self._link("File '%s' is empty.", path)
def file_should_not_be_empty(self, path, msg=None):
"""Fails if the specified directory is empty.
The default error message can be overridden with the ``msg`` argument.
"""
path = self._absnorm(path)
if not os.path.isfile(path):
self._error("File '%s' does not exist." % path)
size = os.stat(path).st_size
if size == 0:
self._fail(msg, "File '%s' is empty." % path)
self._link("File '%%s' contains %d bytes." % size, path)
# Creating and removing files and directory
def create_file(self, path, content='', encoding='UTF-8'):
"""Creates a file with the given content and encoding.
If the directory where the file is created does not exist, it is
automatically created along with possible missing intermediate
directories. Possible existing file is overwritten.
On Windows newline characters (``\\n``) in content are automatically
converted to Windows native newline sequence (``\\r\\n``).
See `Get File` for more information about possible ``encoding`` values,
including special values ``SYSTEM`` and ``CONSOLE``.
Examples:
| Create File | ${dir}/example.txt | Hello, world! | |
| Create File | ${path} | Hyv\\xe4 esimerkki | Latin-1 |
| Create File | /tmp/foo.txt | 3\\nlines\\nhere\\n | SYSTEM |
Use `Append To File` if you want to append to an existing file
and `Create Binary File` if you need to write bytes without encoding.
`File Should Not Exist` can be used to avoid overwriting existing
files.
The support for ``SYSTEM`` and ``CONSOLE`` encodings is new in Robot
Framework 3.0. Automatically converting ``\\n`` to ``\\r\\n`` on
Windows is new in Robot Framework 3.1.
"""
path = self._write_to_file(path, content, encoding)
self._link("Created file '%s'.", path)
def _write_to_file(self, path, content, encoding=None, mode='w'):
path = self._absnorm(path)
parent = os.path.dirname(path)
if not os.path.exists(parent):
os.makedirs(parent)
# io.open() only accepts Unicode, not byte-strings, in text mode.
# We expect possible byte-strings to be all ASCII.
if PY2 and isinstance(content, str) and 'b' not in mode:
content = unicode(content)
if encoding:
encoding = self._map_encoding(encoding)
with io.open(path, mode, encoding=encoding) as f:
f.write(content)
return path
def create_binary_file(self, path, content):
"""Creates a binary file with the given content.
If content is given as a Unicode string, it is first converted to bytes
character by character. All characters with ordinal below 256 can be
used and are converted to bytes with same values. Using characters
with higher ordinal is an error.
Byte strings, and possible other types, are written to the file as is.
If the directory for the file does not exist, it is created, along
with missing intermediate directories.
Examples:
| Create Binary File | ${dir}/example.png | ${image content} |
| Create Binary File | ${path} | \\x01\\x00\\xe4\\x00 |
Use `Create File` if you want to create a text file using a certain
encoding. `File Should Not Exist` can be used to avoid overwriting
existing files.
"""
if is_unicode(content):
content = bytes(bytearray(ord(c) for c in content))
path = self._write_to_file(path, content, mode='wb')
self._link("Created binary file '%s'.", path)
def append_to_file(self, path, content, encoding='UTF-8'):
"""Appends the given content to the specified file.
If the file exists, the given text is written to its end. If the file
does not exist, it is created.
Other than not overwriting possible existing files, this keyword works
exactly like `Create File`. See its documentation for more details
about the usage.
Note that special encodings ``SYSTEM`` and ``CONSOLE`` only work
with this keyword starting from Robot Framework 3.1.2.
"""
path = self._write_to_file(path, content, encoding, mode='a')
self._link("Appended to file '%s'.", path)
def remove_file(self, path):
"""Removes a file with the given path.
Passes if the file does not exist, but fails if the path does
not point to a regular file (e.g. it points to a directory).
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
If the path is a pattern, all files matching it are removed.
"""
path = self._absnorm(path)
matches = self._glob(path)
if not matches:
self._link("File '%s' does not exist.", path)
for match in matches:
if not os.path.isfile(match):
self._error("Path '%s' is not a file." % match)
os.remove(match)
self._link("Removed file '%s'.", match)
def remove_files(self, *paths):
"""Uses `Remove File` to remove multiple files one-by-one.
Example:
| Remove Files | ${TEMPDIR}${/}foo.txt | ${TEMPDIR}${/}bar.txt | ${TEMPDIR}${/}zap.txt |
"""
for path in paths:
self.remove_file(path)
def empty_directory(self, path):
"""Deletes all the content from the given directory.
Deletes both files and sub-directories, but the specified directory
itself if not removed. Use `Remove Directory` if you want to remove
the whole directory.
"""
path = self._absnorm(path)
for item in self._list_dir(path, absolute=True):
if os.path.isdir(item):
shutil.rmtree(item)
else:
os.remove(item)
self._link("Emptied directory '%s'.", path)
def create_directory(self, path):
"""Creates the specified directory.
Also possible intermediate directories are created. Passes if the
directory already exists, but fails if the path exists and is not
a directory.
"""
path = self._absnorm(path)
if os.path.isdir(path):
self._link("Directory '%s' already exists.", path )
elif os.path.exists(path):
self._error("Path '%s' is not a directory." % path)
else:
os.makedirs(path)
self._link("Created directory '%s'.", path)
def remove_directory(self, path, recursive=False):
"""Removes the directory pointed to by the given ``path``.
If the second argument ``recursive`` is given a true value (see
`Boolean arguments`), the directory is removed recursively. Otherwise
removing fails if the directory is not empty.
If the directory pointed to by the ``path`` does not exist, the keyword
passes, but it fails, if the ``path`` points to a file.
"""
path = self._absnorm(path)
if not os.path.exists(path):
self._link("Directory '%s' does not exist.", path)
elif not os.path.isdir(path):
self._error("Path '%s' is not a directory." % path)
else:
if is_truthy(recursive):
shutil.rmtree(path)
else:
self.directory_should_be_empty(
path, "Directory '%s' is not empty." % path)
os.rmdir(path)
self._link("Removed directory '%s'.", path)
# Moving and copying files and directories
def copy_file(self, source, destination):
"""Copies the source file into the destination.
Source must be a path to an existing file or a glob pattern (see
`Pattern matching`) that matches exactly one file. How the
destination is interpreted is explained below.
1) If the destination is an existing file, the source file is copied
over it.
2) If the destination is an existing directory, the source file is
copied into it. A possible file with the same name as the source is
overwritten.
3) If the destination does not exist and it ends with a path
separator (``/`` or ``\\``), it is considered a directory. That
directory is created and a source file copied into it.
Possible missing intermediate directories are also created.
4) If the destination does not exist and it does not end with a path
separator, it is considered a file. If the path to the file does not
exist, it is created.
The resulting destination path is returned since Robot Framework 2.9.2.
See also `Copy Files`, `Move File`, and `Move Files`.
"""
source, destination = \
self._prepare_copy_and_move_file(source, destination)
if not self._are_source_and_destination_same_file(source, destination):
source, destination = self._atomic_copy(source, destination)
self._link("Copied file from '%s' to '%s'.", source, destination)
return destination
def _prepare_copy_and_move_file(self, source, destination):
source = self._normalize_copy_and_move_source(source)
destination = self._normalize_copy_and_move_destination(destination)
if os.path.isdir(destination):
destination = os.path.join(destination, os.path.basename(source))
return source, destination
def _normalize_copy_and_move_source(self, source):
source = self._absnorm(source)
sources = self._glob(source)
if len(sources) > 1:
self._error("Multiple matches with source pattern '%s'." % source)
if sources:
source = sources[0]
if not os.path.exists(source):
self._error("Source file '%s' does not exist." % source)
if not os.path.isfile(source):
self._error("Source file '%s' is not a regular file." % source)
return source
def _normalize_copy_and_move_destination(self, destination):
is_dir = os.path.isdir(destination) or destination.endswith(('/', '\\'))
destination = self._absnorm(destination)
directory = destination if is_dir else os.path.dirname(destination)
self._ensure_destination_directory_exists(directory)
return destination
def _ensure_destination_directory_exists(self, path):
if not os.path.exists(path):
os.makedirs(path)
elif not os.path.isdir(path):
self._error("Destination '%s' exists and is not a directory." % path)
def _are_source_and_destination_same_file(self, source, destination):
if self._force_normalize(source) == self._force_normalize(destination):
self._link("Source '%s' and destination '%s' point to the same "
"file.", source, destination)
return True
return False
def _force_normalize(self, path):
# TODO: Should normalize_path also support link normalization?
# TODO: Should we handle dos paths like 'exampl~1.txt'?
return os.path.realpath(normpath(path, case_normalize=True))
def _atomic_copy(self, source, destination):
"""Copy file atomically (or at least try to).
This method tries to ensure that a file copy operation will not fail
if the destination file is removed during copy operation. The problem
is that copying a file is typically not an atomic operation.
Luckily moving files is atomic in almost every platform, assuming files
are on the same filesystem, and we can use that as a workaround:
- First move the source to a temporary directory that is ensured to
be on the same filesystem as the destination.
- Move the temporary file over the real destination.
See also https://github.com/robotframework/robotframework/issues/1502
"""
temp_directory = tempfile.mkdtemp(dir=os.path.dirname(destination))
temp_file = os.path.join(temp_directory, os.path.basename(source))
try:
shutil.copy(source, temp_file)
if os.path.exists(destination):
os.remove(destination)
shutil.move(temp_file, destination)
finally:
shutil.rmtree(temp_directory)
return source, destination
def move_file(self, source, destination):
"""Moves the source file into the destination.
Arguments have exactly same semantics as with `Copy File` keyword.
Destination file path is returned since Robot Framework 2.9.2.
If the source and destination are on the same filesystem, rename
operation is used. Otherwise file is copied to the destination
filesystem and then removed from the original filesystem.
See also `Move Files`, `Copy File`, and `Copy Files`.
"""
source, destination = \
self._prepare_copy_and_move_file(source, destination)
if not self._are_source_and_destination_same_file(destination, source):
shutil.move(source, destination)
self._link("Moved file from '%s' to '%s'.", source, destination)
return destination
def copy_files(self, *sources_and_destination):
"""Copies specified files to the target directory.
Source files can be given as exact paths and as glob patterns (see
`Pattern matching`). At least one source must be given, but it is
not an error if it is a pattern that does not match anything.
Last argument must be the destination directory. If the destination
does not exist, it will be created.
Examples:
| Copy Files | ${dir}/file1.txt | ${dir}/file2.txt | ${dir2} |
| Copy Files | ${dir}/file-*.txt | ${dir2} | |
See also `Copy File`, `Move File`, and `Move Files`.
"""
sources, destination \
= self._prepare_copy_and_move_files(sources_and_destination)
for source in sources:
self.copy_file(source, destination)
def _prepare_copy_and_move_files(self, items):
if len(items) < 2:
self._error('Must contain destination and at least one source.')
sources = self._glob_files(items[:-1])
destination = self._absnorm(items[-1])
self._ensure_destination_directory_exists(destination)
return sources, destination
def _glob_files(self, patterns):
files = []
for pattern in patterns:
files.extend(self._glob(self._absnorm(pattern)))
return files
def move_files(self, *sources_and_destination):
"""Moves specified files to the target directory.
Arguments have exactly same semantics as with `Copy Files` keyword.
See also `Move File`, `Copy File`, and `Copy Files`.
"""
sources, destination \
= self._prepare_copy_and_move_files(sources_and_destination)
for source in sources:
self.move_file(source, destination)
def copy_directory(self, source, destination):
"""Copies the source directory into the destination.
If the destination exists, the source is copied under it. Otherwise
the destination directory and the possible missing intermediate
directories are created.
"""
source, destination \
= self._prepare_copy_and_move_directory(source, destination)
try:
shutil.copytree(source, destination)
except shutil.Error:
# https://github.com/robotframework/robotframework/issues/2321
if not (WINDOWS and JYTHON):
raise
self._link("Copied directory from '%s' to '%s'.", source, destination)
def _prepare_copy_and_move_directory(self, source, destination):
source = self._absnorm(source)
destination = self._absnorm(destination)
if not os.path.exists(source):
self._error("Source '%s' does not exist." % source)
if not os.path.isdir(source):
self._error("Source '%s' is not a directory." % source)
if os.path.exists(destination) and not os.path.isdir(destination):
self._error("Destination '%s' is not a directory." % destination)
if os.path.exists(destination):
base = os.path.basename(source)
destination = os.path.join(destination, base)
else:
parent = os.path.dirname(destination)
if not os.path.exists(parent):
os.makedirs(parent)
return source, destination
def move_directory(self, source, destination):
"""Moves the source directory into a destination.
Uses `Copy Directory` keyword internally, and ``source`` and
``destination`` arguments have exactly same semantics as with
that keyword.
"""
source, destination \
= self._prepare_copy_and_move_directory(source, destination)
shutil.move(source, destination)
self._link("Moved directory from '%s' to '%s'.", source, destination)
# Environment Variables
def get_environment_variable(self, name, default=None):
"""Returns the value of an environment variable with the given name.
If no such environment variable is set, returns the default value, if
given. Otherwise fails the test case.
Returned variables are automatically decoded to Unicode using
the system encoding.
Note that you can also access environment variables directly using
the variable syntax ``%{ENV_VAR_NAME}``.
"""
value = get_env_var(name, default)
if value is None:
self._error("Environment variable '%s' does not exist." % name)
return value
def set_environment_variable(self, name, value):
"""Sets an environment variable to a specified value.
Values are converted to strings automatically. Set variables are
automatically encoded using the system encoding.
"""
set_env_var(name, value)
self._info("Environment variable '%s' set to value '%s'."
% (name, value))
def append_to_environment_variable(self, name, *values, **config):
"""Appends given ``values`` to environment variable ``name``.
If the environment variable already exists, values are added after it,
and otherwise a new environment variable is created.
Values are, by default, joined together using the operating system
path separator (``;`` on Windows, ``:`` elsewhere). This can be changed
by giving a separator after the values like ``separator=value``. No
other configuration parameters are accepted.
Examples (assuming ``NAME`` and ``NAME2`` do not exist initially):
| Append To Environment Variable | NAME | first | |
| Should Be Equal | %{NAME} | first | |
| Append To Environment Variable | NAME | second | third |
| Should Be Equal | %{NAME} | first${:}second${:}third |
| Append To Environment Variable | NAME2 | first | separator=- |
| Should Be Equal | %{NAME2} | first | |
| Append To Environment Variable | NAME2 | second | separator=- |
| Should Be Equal | %{NAME2} | first-second |
"""
sentinel = object()
initial = self.get_environment_variable(name, sentinel)
if initial is not sentinel:
values = (initial,) + values
separator = config.pop('separator', os.pathsep)
if config:
config = ['='.join(i) for i in sorted(config.items())]
self._error('Configuration %s not accepted.'
% seq2str(config, lastsep=' or '))
self.set_environment_variable(name, separator.join(values))
def remove_environment_variable(self, *names):
"""Deletes the specified environment variable.
Does nothing if the environment variable is not set.
It is possible to remove multiple variables by passing them to this
keyword as separate arguments.
"""
for name in names:
value = del_env_var(name)
if value:
self._info("Environment variable '%s' deleted." % name)
else:
self._info("Environment variable '%s' does not exist." % name)
def environment_variable_should_be_set(self, name, msg=None):
"""Fails if the specified environment variable is not set.
The default error message can be overridden with the ``msg`` argument.
"""
value = get_env_var(name)
if not value:
self._fail(msg, "Environment variable '%s' is not set." % name)
self._info("Environment variable '%s' is set to '%s'." % (name, value))
def environment_variable_should_not_be_set(self, name, msg=None):
"""Fails if the specified environment variable is set.
The default error message can be overridden with the ``msg`` argument.
"""
value = get_env_var(name)
if value:
self._fail(msg, "Environment variable '%s' is set to '%s'."
% (name, value))
self._info("Environment variable '%s' is not set." % name)
def get_environment_variables(self):
"""Returns currently available environment variables as a dictionary.
Both keys and values are decoded to Unicode using the system encoding.
Altering the returned dictionary has no effect on the actual environment
variables.
"""
return get_env_vars()
def log_environment_variables(self, level='INFO'):
"""Logs all environment variables using the given log level.
Environment variables are also returned the same way as with
`Get Environment Variables` keyword.
"""
variables = get_env_vars()
for name in sorted(variables, key=lambda item: item.lower()):
self._log('%s = %s' % (name, variables[name]), level)
return variables
# Path
def join_path(self, base, *parts):
"""Joins the given path part(s) to the given base path.
The path separator (``/`` or ``\\``) is inserted when needed and
the possible absolute paths handled as expected. The resulted
path is also normalized.
Examples:
| ${path} = | Join Path | my | path |
| ${p2} = | Join Path | my/ | path/ |
| ${p3} = | Join Path | my | path | my | file.txt |
| ${p4} = | Join Path | my | /path |
| ${p5} = | Join Path | /my/path/ | .. | path2 |
=>
- ${path} = 'my/path'
- ${p2} = 'my/path'
- ${p3} = 'my/path/my/file.txt'
- ${p4} = '/path'
- ${p5} = '/my/path2'
"""
base = base.replace('/', os.sep)
parts = [p.replace('/', os.sep) for p in parts]
return self.normalize_path(os.path.join(base, *parts))
def join_paths(self, base, *paths):
"""Joins given paths with base and returns resulted paths.
See `Join Path` for more information.
Examples:
| @{p1} = | Join Paths | base | example | other | |
| @{p2} = | Join Paths | /my/base | /example | other | |
| @{p3} = | Join Paths | my/base | example/path/ | other | one/more |
=>
- @{p1} = ['base/example', 'base/other']
- @{p2} = ['/example', '/my/base/other']
- @{p3} = ['my/base/example/path', 'my/base/other', 'my/base/one/more']
"""
return [self.join_path(base, path) for path in paths]
def normalize_path(self, path, case_normalize=False):
"""Normalizes the given path.
- Collapses redundant separators and up-level references.
- Converts ``/`` to ``\\`` on Windows.
- Replaces initial ``~`` or ``~user`` by that user's home directory.
The latter is not supported on Jython.
- If ``case_normalize`` is given a true value (see `Boolean arguments`)
on Windows, converts the path to all lowercase. New in Robot
Framework 3.1.
Examples:
| ${path1} = | Normalize Path | abc/ |
| ${path2} = | Normalize Path | abc/../def |
| ${path3} = | Normalize Path | abc/./def//ghi |
| ${path4} = | Normalize Path | ~robot/stuff |
=>
- ${path1} = 'abc'
- ${path2} = 'def'
- ${path3} = 'abc/def/ghi'
- ${path4} = '/home/robot/stuff'
On Windows result would use ``\\`` instead of ``/`` and home directory
would be different.
"""
path = os.path.normpath(os.path.expanduser(path.replace('/', os.sep)))
# os.path.normcase doesn't normalize on OSX which also, by default,
# has case-insensitive file system. Our robot.utils.normpath would
# do that, but it's not certain would that, or other things that the
# utility do, desirable.
if case_normalize:
path = os.path.normcase(path)
return path or '.'
def split_path(self, path):
"""Splits the given path from the last path separator (``/`` or ``\\``).
The given path is first normalized (e.g. a possible trailing
path separator is removed, special directories ``..`` and ``.``
removed). The parts that are split are returned as separate
components.
Examples:
| ${path1} | ${dir} = | Split Path | abc/def |
| ${path2} | ${file} = | Split Path | abc/def/ghi.txt |
| ${path3} | ${d2} = | Split Path | abc/../def/ghi/ |
=>
- ${path1} = 'abc' & ${dir} = 'def'
- ${path2} = 'abc/def' & ${file} = 'ghi.txt'
- ${path3} = 'def' & ${d2} = 'ghi'
"""
return os.path.split(self.normalize_path(path))
def split_extension(self, path):
"""Splits the extension from the given path.
The given path is first normalized (e.g. possible trailing
path separators removed, special directories ``..`` and ``.``
removed). The base path and extension are returned as separate
components so that the dot used as an extension separator is
removed. If the path contains no extension, an empty string is
returned for it. Possible leading and trailing dots in the file
name are never considered to be extension separators.
Examples:
| ${path} | ${ext} = | Split Extension | file.extension |
| ${p2} | ${e2} = | Split Extension | path/file.ext |
| ${p3} | ${e3} = | Split Extension | path/file |
| ${p4} | ${e4} = | Split Extension | p1/../p2/file.ext |
| ${p5} | ${e5} = | Split Extension | path/.file.ext |
| ${p6} | ${e6} = | Split Extension | path/.file |
=>
- ${path} = 'file' & ${ext} = 'extension'
- ${p2} = 'path/file' & ${e2} = 'ext'
- ${p3} = 'path/file' & ${e3} = ''
- ${p4} = 'p2/file' & ${e4} = 'ext'
- ${p5} = 'path/.file' & ${e5} = 'ext'
- ${p6} = 'path/.file' & ${e6} = ''
"""
path = self.normalize_path(path)
basename = os.path.basename(path)
if basename.startswith('.' * basename.count('.')):
return path, ''
if path.endswith('.'):
path2 = path.rstrip('.')
trailing_dots = '.' * (len(path) - len(path2))
path = path2
else:
trailing_dots = ''
basepath, extension = os.path.splitext(path)
if extension.startswith('.'):
extension = extension[1:]
if extension:
extension += trailing_dots
else:
basepath += trailing_dots
return basepath, extension
# Misc
def get_modified_time(self, path, format='timestamp'):
"""Returns the last modification time of a file or directory.
How time is returned is determined based on the given ``format``
string as follows. Note that all checks are case-insensitive.
Returned time is also automatically logged.
1) If ``format`` contains the word ``epoch``, the time is returned
in seconds after the UNIX epoch. The return value is always
an integer.
2) If ``format`` contains any of the words ``year``, ``month``,
``day``, ``hour``, ``min`` or ``sec``, only the selected parts are
returned. The order of the returned parts is always the one
in the previous sentence and the order of the words in
``format`` is not significant. The parts are returned as
zero-padded strings (e.g. May -> ``05``).
3) Otherwise, and by default, the time is returned as a
timestamp string in the format ``2006-02-24 15:08:31``.
Examples (when the modified time of ``${CURDIR}`` is
2006-03-29 15:06:21):
| ${time} = | Get Modified Time | ${CURDIR} |
| ${secs} = | Get Modified Time | ${CURDIR} | epoch |
| ${year} = | Get Modified Time | ${CURDIR} | return year |
| ${y} | ${d} = | Get Modified Time | ${CURDIR} | year,day |
| @{time} = | Get Modified Time | ${CURDIR} | year,month,day,hour,min,sec |
=>
- ${time} = '2006-03-29 15:06:21'
- ${secs} = 1143637581
- ${year} = '2006'
- ${y} = '2006' & ${d} = '29'
- @{time} = ['2006', '03', '29', '15', '06', '21']
"""
path = self._absnorm(path)
if not os.path.exists(path):
self._error("Path '%s' does not exist." % path)
mtime = get_time(format, os.stat(path).st_mtime)
self._link("Last modified time of '%%s' is %s." % mtime, path)
return mtime
def set_modified_time(self, path, mtime):
"""Sets the file modification and access times.
Changes the modification and access times of the given file to
the value determined by ``mtime``. The time can be given in
different formats described below. Note that all checks
involving strings are case-insensitive. Modified time can only
be set to regular files.
1) If ``mtime`` is a number, or a string that can be converted
to a number, it is interpreted as seconds since the UNIX
epoch (1970-01-01 00:00:00 UTC). This documentation was
originally written about 1177654467 seconds after the epoch.
2) If ``mtime`` is a timestamp, that time will be used. Valid
timestamp formats are ``YYYY-MM-DD hh:mm:ss`` and
``YYYYMMDD hhmmss``.
3) If ``mtime`` is equal to ``NOW``, the current local time is used.
4) If ``mtime`` is equal to ``UTC``, the current time in
[http://en.wikipedia.org/wiki/Coordinated_Universal_Time|UTC]
is used.
5) If ``mtime`` is in the format like ``NOW - 1 day`` or ``UTC + 1
hour 30 min``, the current local/UTC time plus/minus the time
specified with the time string is used. The time string format
is described in an appendix of Robot Framework User Guide.
Examples:
| Set Modified Time | /path/file | 1177654467 | # Time given as epoch seconds |
| Set Modified Time | /path/file | 2007-04-27 9:14:27 | # Time given as a timestamp |
| Set Modified Time | /path/file | NOW | # The local time of execution |
| Set Modified Time | /path/file | NOW - 1 day | # 1 day subtracted from the local time |
| Set Modified Time | /path/file | UTC + 1h 2min 3s | # 1h 2min 3s added to the UTC time |
"""
mtime = parse_time(mtime)
path = self._absnorm(path)
if not os.path.exists(path):
self._error("File '%s' does not exist." % path)
if not os.path.isfile(path):
self._error("Path '%s' is not a regular file." % path)
os.utime(path, (mtime, mtime))
time.sleep(0.1) # Give os some time to really set these times
tstamp = secs_to_timestamp(mtime, seps=('-', ' ', ':'))
self._link("Set modified time of '%%s' to %s." % tstamp, path)
def get_file_size(self, path):
"""Returns and logs file size as an integer in bytes."""
path = self._absnorm(path)
if not os.path.isfile(path):
self._error("File '%s' does not exist." % path)
size = os.stat(path).st_size
plural = plural_or_not(size)
self._link("Size of file '%%s' is %d byte%s." % (size, plural), path)
return size
def list_directory(self, path, pattern=None, absolute=False):
"""Returns and logs items in a directory, optionally filtered with ``pattern``.
File and directory names are returned in case-sensitive alphabetical
order, e.g. ``['A Name', 'Second', 'a lower case name', 'one more']``.
Implicit directories ``.`` and ``..`` are not returned. The returned
items are automatically logged.
File and directory names are returned relative to the given path
(e.g. ``'file.txt'``) by default. If you want them be returned in
absolute format (e.g. ``'/home/robot/file.txt'``), give the ``absolute``
argument a true value (see `Boolean arguments`).
If ``pattern`` is given, only items matching it are returned. The pattern
matching syntax is explained in `introduction`, and in this case
matching is case-sensitive.
Examples (using also other `List Directory` variants):
| @{items} = | List Directory | ${TEMPDIR} |
| @{files} = | List Files In Directory | /tmp | *.txt | absolute |
| ${count} = | Count Files In Directory | ${CURDIR} | ??? |
"""
items = self._list_dir(path, pattern, absolute)
self._info('%d item%s:\n%s' % (len(items), plural_or_not(items),
'\n'.join(items)))
return items
def list_files_in_directory(self, path, pattern=None, absolute=False):
"""Wrapper for `List Directory` that returns only files."""
files = self._list_files_in_dir(path, pattern, absolute)
self._info('%d file%s:\n%s' % (len(files), plural_or_not(files),
'\n'.join(files)))
return files
def list_directories_in_directory(self, path, pattern=None, absolute=False):
"""Wrapper for `List Directory` that returns only directories."""
dirs = self._list_dirs_in_dir(path, pattern, absolute)
self._info('%d director%s:\n%s' % (len(dirs),
'y' if len(dirs) == 1 else 'ies',
'\n'.join(dirs)))
return dirs
def count_items_in_directory(self, path, pattern=None):
"""Returns and logs the number of all items in the given directory.
The argument ``pattern`` has the same semantics as with `List Directory`
keyword. The count is returned as an integer, so it must be checked e.g.
with the built-in keyword `Should Be Equal As Integers`.
"""
count = len(self._list_dir(path, pattern))
self._info("%s item%s." % (count, plural_or_not(count)))
return count
def count_files_in_directory(self, path, pattern=None):
"""Wrapper for `Count Items In Directory` returning only file count."""
count = len(self._list_files_in_dir(path, pattern))
self._info("%s file%s." % (count, plural_or_not(count)))
return count
def count_directories_in_directory(self, path, pattern=None):
"""Wrapper for `Count Items In Directory` returning only directory count."""
count = len(self._list_dirs_in_dir(path, pattern))
self._info("%s director%s." % (count, 'y' if count == 1 else 'ies'))
return count
def _list_dir(self, path, pattern=None, absolute=False):
path = self._absnorm(path)
self._link("Listing contents of directory '%s'.", path)
if not os.path.isdir(path):
self._error("Directory '%s' does not exist." % path)
# result is already unicode but unic also handles NFC normalization
items = sorted(unic(item) for item in os.listdir(path))
if pattern:
items = [i for i in items if fnmatch.fnmatchcase(i, pattern)]
if is_truthy(absolute):
path = os.path.normpath(path)
items = [os.path.join(path, item) for item in items]
return items
def _list_files_in_dir(self, path, pattern=None, absolute=False):
return [item for item in self._list_dir(path, pattern, absolute)
if os.path.isfile(os.path.join(path, item))]
def _list_dirs_in_dir(self, path, pattern=None, absolute=False):
return [item for item in self._list_dir(path, pattern, absolute)
if os.path.isdir(os.path.join(path, item))]
def touch(self, path):
"""Emulates the UNIX touch command.
Creates a file, if it does not exist. Otherwise changes its access and
modification times to the current time.
Fails if used with the directories or the parent directory of the given
file does not exist.
"""
path = self._absnorm(path)
if os.path.isdir(path):
self._error("Cannot touch '%s' because it is a directory." % path)
if not os.path.exists(os.path.dirname(path)):
self._error("Cannot touch '%s' because its parent directory does "
"not exist." % path)
if os.path.exists(path):
mtime = round(time.time())
os.utime(path, (mtime, mtime))
self._link("Touched existing file '%s'.", path)
else:
open(path, 'w').close()
self._link("Touched new file '%s'.", path)
def _absnorm(self, path):
path = self.normalize_path(path)
try:
return abspath(path)
except ValueError: # http://ironpython.codeplex.com/workitem/29489
return path
def _fail(self, *messages):
raise AssertionError(next(msg for msg in messages if msg))
def _error(self, msg):
raise RuntimeError(msg)
def _info(self, msg):
self._log(msg, 'INFO')
def _link(self, msg, *paths):
paths = tuple('<a href="file://%s">%s</a>' % (p, p) for p in paths)
self._log(msg % paths, 'HTML')
def _warn(self, msg):
self._log(msg, 'WARN')
def _log(self, msg, level):
logger.write(msg, level)
class _Process:
def __init__(self, command):
self._command = self._process_command(command)
self._process = os.popen(self._command)
def __str__(self):
return self._command
def read(self):
return self._process_output(self._process.read())
def close(self):
try:
rc = self._process.close()
except IOError: # Has occurred sometimes in Windows
return 255
if rc is None:
return 0
# In Windows (Python and Jython) return code is value returned by
# command (can be almost anything)
# In other OS:
# In Jython return code can be between '-255' - '255'
# In Python return code must be converted with 'rc >> 8' and it is
# between 0-255 after conversion
if WINDOWS or JYTHON:
return rc % 256
return rc >> 8
def _process_command(self, command):
if '>' not in command:
if command.endswith('&'):
command = command[:-1] + ' 2>&1 &'
else:
command += ' 2>&1'
return self._encode_to_file_system(command)
def _encode_to_file_system(self, string):
enc = sys.getfilesystemencoding() if PY2 else None
return string.encode(enc) if enc else string
def _process_output(self, output):
if '\r\n' in output:
output = output.replace('\r\n', '\n')
if output.endswith('\n'):
output = output[:-1]
return console_decode(output, force=True) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libraries/OperatingSystem.py | 0.677581 | 0.382343 | OperatingSystem.py | pypi |
from __future__ import print_function
import os
import subprocess
import sys
if sys.platform.startswith('java'):
from java.awt import Toolkit, Robot, Rectangle
from javax.imageio import ImageIO
from java.io import File
elif sys.platform == 'cli':
import clr
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')
from System.Drawing import Bitmap, Graphics, Imaging
from System.Windows.Forms import Screen
else:
try:
import wx
except ImportError:
wx = None
try:
from gtk import gdk
except ImportError:
gdk = None
try:
from PIL import ImageGrab # apparently available only on Windows
except ImportError:
ImageGrab = None
from robotide.lib.robot.api import logger
from robotide.lib.robot.libraries.BuiltIn import BuiltIn
from robotide.lib.robot.version import get_version
from robotide.lib.robot.utils import abspath, get_error_message, get_link_path, py2to3
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 =
How screenshots are taken when using Python depends on the operating
system. On OSX screenshots are taken using the built-in ``screencapture``
utility. On other operating systems you need to have one of the following
tools or Python modules installed. You can specify the tool/module to use
when `importing` the library. If no tool or module is specified, the first
one 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.
- Pillow :: http://python-pillow.github.io ::
Only works on Windows. Also the original PIL package is supported.
- Scrot :: http://en.wikipedia.org/wiki/Scrot :: Not used on Windows.
Install with ``apt-get install scrot`` or similar.
Using ``screencapture`` on OSX and specifying explicit screenshot module
are new in Robot Framework 2.9.2. The support for using ``scrot`` is new
in Robot Framework 3.0.
= 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.
= 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, screenshot_module=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.
``screenshot_module`` specifies the module or tool to use when using
this library on Python outside OSX. Possible values are ``wxPython``,
``PyGTK``, ``PIL`` and ``scrot``, case-insensitively. If no value is
given, the first module/tool found is used in that order. See `Using
with Python` for more information.
Examples (use only one of these):
| =Setting= | =Value= | =Value= |
| Library | Screenshot | |
| Library | Screenshot | ${TEMPDIR} |
| Library | Screenshot | screenshot_module=PyGTK |
Specifying explicit screenshot module is new in Robot Framework 2.9.2.
"""
self._given_screenshot_dir = self._norm_path(screenshot_directory)
self._screenshot_taker = ScreenshotTaker(screenshot_module)
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 module/tool 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.' % get_error_message())
return path
def _validate_screenshot_path(self, path):
path = 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 = 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 = get_link_path(path, self._log_dir)
logger.info("Screenshot saved to '<a href=\"%s\">%s</a>'."
% (link, path), html=True)
@py2to3
class ScreenshotTaker(object):
def __init__(self, module_name=None):
self._screenshot = self._get_screenshot_taker(module_name)
self.module = self._screenshot.__name__.split('_')[1]
self._wx_app_reference = None
def __call__(self, path):
self._screenshot(path)
def __nonzero__(self):
return self.module != 'no'
def test(self, path=None):
if not self:
print("Cannot take screenshots.")
return False
print("Using '%s' to take screenshot." % self.module)
if not path:
print("Not taking test screenshot.")
return True
print("Taking test screenshot to '%s'." % path)
try:
self(path)
except:
print("Failed: %s" % get_error_message())
return False
else:
print("Success!")
return True
def _get_screenshot_taker(self, module_name=None):
if sys.platform.startswith('java'):
return self._java_screenshot
if sys.platform == 'cli':
return self._cli_screenshot
if sys.platform == 'darwin':
return self._osx_screenshot
if module_name:
return self._get_named_screenshot_taker(module_name.lower())
return self._get_default_screenshot_taker()
def _get_named_screenshot_taker(self, name):
screenshot_takers = {'wxpython': (wx, self._wx_screenshot),
'pygtk': (gdk, self._gtk_screenshot),
'pil': (ImageGrab, self._pil_screenshot),
'scrot': (self._scrot, self._scrot_screenshot)}
if name not in screenshot_takers:
raise RuntimeError("Invalid screenshot module or tool '%s'." % name)
supported, screenshot_taker = screenshot_takers[name]
if not supported:
raise RuntimeError("Screenshot module or tool '%s' not installed."
% name)
return screenshot_taker
def _get_default_screenshot_taker(self):
for module, screenshot_taker in [(wx, self._wx_screenshot),
(gdk, self._gtk_screenshot),
(ImageGrab, self._pil_screenshot),
(self._scrot, self._scrot_screenshot),
(True, self._no_screenshot)]:
if module:
return screenshot_taker
def _java_screenshot(self, path):
size = Toolkit.getDefaultToolkit().getScreenSize()
rectangle = Rectangle(0, 0, size.width, size.height)
image = Robot().createScreenCapture(rectangle)
ImageIO.write(image, 'jpg', File(path))
def _cli_screenshot(self, path):
bmp = Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height)
graphics = Graphics.FromImage(bmp)
try:
graphics.CopyFromScreen(0, 0, 0, 0, bmp.Size)
finally:
graphics.Dispose()
bmp.Save(path, Imaging.ImageFormat.Jpeg)
def _osx_screenshot(self, path):
if self._call('screencapture', '-t', 'jpg', path) != 0:
raise RuntimeError("Using 'screencapture' failed.")
def _call(self, *command):
try:
return subprocess.call(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
except OSError:
return -1
@property
def _scrot(self):
return os.sep == '/' and self._call('scrot', '--version') == 0
def _scrot_screenshot(self, path):
if not path.endswith(('.jpg', '.jpeg')):
raise RuntimeError("Scrot requires extension to be '.jpg' or "
"'.jpeg', got '%s'." % os.path.splitext(path)[1])
if self._call('scrot', '--silent', path) != 0:
raise RuntimeError("Using 'scrot' failed.")
def _wx_screenshot(self, path):
if not self._wx_app_reference:
self._wx_app_reference = wx.App(False)
context = wx.ScreenDC()
width, height = context.GetSize()
if wx.__version__ >= '4':
bitmap = wx.Bitmap(width, height, -1)
else:
bitmap = wx.EmptyBitmap(width, height, -1)
memory = wx.MemoryDC()
memory.SelectObject(bitmap)
memory.Blit(0, 0, width, height, context, -1, -1)
memory.SelectObject(wx.NullBitmap)
bitmap.SaveFile(path, wx.BITMAP_TYPE_JPEG)
def _gtk_screenshot(self, path):
window = gdk.get_default_root_window()
if not window:
raise RuntimeError('Taking screenshot failed.')
width, height = window.get_size()
pb = gdk.Pixbuf(gdk.COLORSPACE_RGB, False, 8, width, height)
pb = pb.get_from_drawable(window, window.get_colormap(),
0, 0, 0, 0, width, height)
if not pb:
raise RuntimeError('Taking screenshot failed.')
pb.save(path, 'jpeg')
def _pil_screenshot(self, path):
ImageGrab.grab().save(path, 'JPEG')
def _no_screenshot(self, path):
raise RuntimeError('Taking screenshots is not supported on this platform '
'by default. See library documentation for details.')
if __name__ == "__main__":
if len(sys.argv) not in [2, 3]:
sys.exit("Usage: %s <path>|test [wx|pygtk|pil|scrot]"
% os.path.basename(sys.argv[0]))
path = sys.argv[1] if sys.argv[1] != 'test' else None
module = sys.argv[2] if len(sys.argv) > 2 else None
ScreenshotTaker(module).test(path) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libraries/Screenshot.py | 0.680348 | 0.244222 | Screenshot.py | pypi |
import copy
from robotide.lib.robot.api import logger
from robotide.lib.robot.utils import (is_dict_like, is_list_like, is_number, is_string, is_truthy, plural_or_not,
seq2str, seq2str2, type_name, unic, Matcher)
from robotide.lib.robot.utils.asserts import assert_equal
from robotide.lib.robot.version import get_version
class NotSet(object):
def __repr__(self):
return ""
NOT_SET = NotSet()
class _List(object):
def convert_to_list(self, item):
"""Converts the given ``item`` to a Python ``list`` type.
Mainly useful for converting tuples and other iterable to lists.
Use `Create List` from the BuiltIn library for constructing new lists.
"""
return list(item)
def append_to_list(self, list_, *values):
"""Adds ``values`` to the end of ``list``.
Example:
| Append To List | ${L1} | xxx | | |
| Append To List | ${L2} | x | y | z |
=>
| ${L1} = ['a', 'xxx']
| ${L2} = ['a', 'b', 'x', 'y', 'z']
"""
self._validate_list(list_)
for value in values:
list_.append(value)
def insert_into_list(self, list_, index, value):
"""Inserts ``value`` into ``list`` to the position specified with ``index``.
Index ``0`` adds the value into the first position, ``1`` to the second,
and so on. Inserting from right works with negative indices so that
``-1`` is the second last position, ``-2`` third last, and so on. Use
`Append To List` to add items to the end of the list.
If the absolute value of the index is greater than
the length of the list, the value is added at the end
(positive index) or the beginning (negative index). An index
can be given either as an integer or a string that can be
converted to an integer.
Example:
| Insert Into List | ${L1} | 0 | xxx |
| Insert Into List | ${L2} | ${-1} | xxx |
=>
| ${L1} = ['xxx', 'a']
| ${L2} = ['a', 'xxx', 'b']
"""
self._validate_list(list_)
list_.insert(self._index_to_int(index), value)
def combine_lists(self, *lists):
"""Combines the given ``lists`` together and returns the result.
The given lists are not altered by this keyword.
Example:
| ${x} = | Combine List | ${L1} | ${L2} | |
| ${y} = | Combine List | ${L1} | ${L2} | ${L1} |
=>
| ${x} = ['a', 'a', 'b']
| ${y} = ['a', 'a', 'b', 'a']
| ${L1} and ${L2} are not changed.
"""
self._validate_lists(*lists)
ret = []
for item in lists:
ret.extend(item)
return ret
def set_list_value(self, list_, index, value):
"""Sets the value of ``list`` specified by ``index`` to the given ``value``.
Index ``0`` means the first position, ``1`` the second and so on.
Similarly, ``-1`` is the last position, ``-2`` second last, and so on.
Using an index that does not exist on the list causes an error.
The index can be either an integer or a string that can be converted to
an integer.
Example:
| Set List Value | ${L3} | 1 | xxx |
| Set List Value | ${L3} | -1 | yyy |
=>
| ${L3} = ['a', 'xxx', 'yyy']
"""
self._validate_list(list_)
try:
list_[self._index_to_int(index)] = value
except IndexError:
self._index_error(list_, index)
def remove_values_from_list(self, list_, *values):
"""Removes all occurrences of given ``values`` from ``list``.
It is not an error if a value does not exist in the list at all.
Example:
| Remove Values From List | ${L4} | a | c | e | f |
=>
| ${L4} = ['b', 'd']
"""
self._validate_list(list_)
for value in values:
while value in list_:
list_.remove(value)
def remove_from_list(self, list_, index):
"""Removes and returns the value specified with an ``index`` from ``list``.
Index ``0`` means the first position, ``1`` the second and so on.
Similarly, ``-1`` is the last position, ``-2`` the second last, and so on.
Using an index that does not exist on the list causes an error.
The index can be either an integer or a string that can be converted
to an integer.
Example:
| ${x} = | Remove From List | ${L2} | 0 |
=>
| ${x} = 'a'
| ${L2} = ['b']
"""
self._validate_list(list_)
try:
return list_.pop(self._index_to_int(index))
except IndexError:
self._index_error(list_, index)
def remove_duplicates(self, list_):
"""Returns a list without duplicates based on the given ``list``.
Creates and returns a new list that contains all items in the given
list so that one item can appear only once. Order of the items in
the new list is the same as in the original except for missing
duplicates. Number of the removed duplicates is logged.
"""
self._validate_list(list_)
ret = []
for item in list_:
if item not in ret:
ret.append(item)
removed = len(list_) - len(ret)
logger.info('%d duplicate%s removed.' % (removed, plural_or_not(removed)))
return ret
def get_from_list(self, list_, index):
"""Returns the value specified with an ``index`` from ``list``.
The given list is never altered by this keyword.
Index ``0`` means the first position, ``1`` the second, and so on.
Similarly, ``-1`` is the last position, ``-2`` the second last, and so on.
Using an index that does not exist on the list causes an error.
The index can be either an integer or a string that can be converted
to an integer.
Examples (including Python equivalents in comments):
| ${x} = | Get From List | ${L5} | 0 | # L5[0] |
| ${y} = | Get From List | ${L5} | -2 | # L5[-2] |
=>
| ${x} = 'a'
| ${y} = 'd'
| ${L5} is not changed
"""
self._validate_list(list_)
try:
return list_[self._index_to_int(index)]
except IndexError:
self._index_error(list_, index)
def get_slice_from_list(self, list_, start=0, end=None):
"""Returns a slice of the given list between ``start`` and ``end`` indexes.
The given list is never altered by this keyword.
If both ``start`` and ``end`` are given, a sublist containing values
from ``start`` to ``end`` is returned. This is the same as
``list[start:end]`` in Python. To get all items from the beginning,
use 0 as the start value, and to get all items until and including
the end, use ``None`` (default) as the end value.
Using ``start`` or ``end`` not found on the list is the same as using
the largest (or smallest) available index.
Examples (incl. Python equivalents in comments):
| ${x} = | Get Slice From List | ${L5} | 2 | 4 | # L5[2:4] |
| ${y} = | Get Slice From List | ${L5} | 1 | | # L5[1:None] |
| ${z} = | Get Slice From List | ${L5} | | -2 | # L5[0:-2] |
=>
| ${x} = ['c', 'd']
| ${y} = ['b', 'c', 'd', 'e']
| ${z} = ['a', 'b', 'c']
| ${L5} is not changed
"""
self._validate_list(list_)
start = self._index_to_int(start, True)
if end is not None:
end = self._index_to_int(end)
return list_[start:end]
def count_values_in_list(self, list_, value, start=0, end=None):
"""Returns the number of occurrences of the given ``value`` in ``list``.
The search can be narrowed to the selected sublist by the ``start`` and
``end`` indexes having the same semantics as with `Get Slice From List`
keyword. The given list is never altered by this keyword.
Example:
| ${x} = | Count Values In List | ${L3} | b |
=>
| ${x} = 1
| ${L3} is not changed
"""
self._validate_list(list_)
return self.get_slice_from_list(list_, start, end).count(value)
def get_index_from_list(self, list_, value, start=0, end=None):
"""Returns the index of the first occurrence of the ``value`` on the list.
The search can be narrowed to the selected sublist by the ``start`` and
``end`` indexes having the same semantics as with `Get Slice From List`
keyword. In case the value is not found, -1 is returned. The given list
is never altered by this keyword.
Example:
| ${x} = | Get Index From List | ${L5} | d |
=>
| ${x} = 3
| ${L5} is not changed
"""
self._validate_list(list_)
if start == '':
start = 0
list_ = self.get_slice_from_list(list_, start, end)
try:
return int(start) + list_.index(value)
except ValueError:
return -1
def copy_list(self, list_, deepcopy=False):
"""Returns a copy of the given list.
If the optional ``deepcopy`` is given a true value, the returned
list is a deep copy. New option in Robot Framework 3.1.2.
The given list is never altered by this keyword.
"""
self._validate_list(list_)
if deepcopy:
return copy.deepcopy(list_)
return list_[:]
def reverse_list(self, list_):
"""Reverses the given list in place.
Note that the given list is changed and nothing is returned. Use
`Copy List` first, if you need to keep also the original order.
| Reverse List | ${L3} |
=>
| ${L3} = ['c', 'b', 'a']
"""
self._validate_list(list_)
list_.reverse()
def sort_list(self, list_):
"""Sorts the given list in place.
Sorting fails if items in the list are not comparable with each others.
On Python 2 most objects are comparable, but on Python 3 comparing,
for example, strings with numbers is not possible.
Note that the given list is changed and nothing is returned. Use
`Copy List` first, if you need to keep also the original order.
"""
self._validate_list(list_)
list_.sort()
def list_should_contain_value(self, list_, value, msg=None):
"""Fails if the ``value`` is not found from ``list``.
Use the ``msg`` argument to override the default error message.
"""
self._validate_list(list_)
default = "%s does not contain value '%s'." % (seq2str2(list_), value)
_verify_condition(value in list_, default, msg)
def list_should_not_contain_value(self, list_, value, msg=None):
"""Fails if the ``value`` is found from ``list``.
Use the ``msg`` argument to override the default error message.
"""
self._validate_list(list_)
default = "%s contains value '%s'." % (seq2str2(list_), value)
_verify_condition(value not in list_, default, msg)
def list_should_not_contain_duplicates(self, list_, msg=None):
"""Fails if any element in the ``list`` is found from it more than once.
The default error message lists all the elements that were found
from the ``list`` multiple times, but it can be overridden by giving
a custom ``msg``. All multiple times found items and their counts are
also logged.
This keyword works with all iterables that can be converted to a list.
The original iterable is never altered.
"""
self._validate_list(list_)
if not isinstance(list_, list):
list_ = list(list_)
dupes = []
for item in list_:
if item not in dupes:
count = list_.count(item)
if count > 1:
logger.info("'%s' found %d times." % (item, count))
dupes.append(item)
if dupes:
raise AssertionError(msg or
'%s found multiple times.' % seq2str(dupes))
def lists_should_be_equal(self, list1, list2, msg=None, values=True,
names=None):
"""Fails if given lists are unequal.
The keyword first verifies that the lists have equal lengths, and then
it checks are all their values equal. Possible differences between the
values are listed in the default error message like ``Index 4: ABC !=
Abc``. The types of the lists do not need to be the same. For example,
Python tuple and list with same content are considered equal.
The error message can be configured using ``msg`` and ``values``
arguments:
- If ``msg`` is not given, the default error message is used.
- If ``msg`` is given and ``values`` gets a value considered true
(see `Boolean arguments`), the error message starts with the given
``msg`` followed by a newline and the default message.
- If ``msg`` is given and ``values`` is not given a true value,
the error message is just the given ``msg``.
Optional ``names`` argument can be used for naming the indices shown in
the default error message. It can either be a list of names matching
the indices in the lists or a dictionary where keys are indices that
need to be named. It is not necessary to name all of the indices. When
using a dictionary, keys can be either integers or strings that can be
converted to integers.
Examples:
| ${names} = | Create List | First Name | Family Name | Email |
| Lists Should Be Equal | ${people1} | ${people2} | names=${names} |
| ${names} = | Create Dictionary | 0=First Name | 2=Email |
| Lists Should Be Equal | ${people1} | ${people2} | names=${names} |
If the items in index 2 would differ in the above examples, the error
message would contain a row like ``Index 2 (email): name@foo.com !=
name@bar.com``.
"""
self._validate_lists(list1, list2)
len1 = len(list1)
len2 = len(list2)
default = 'Lengths are different: %d != %d' % (len1, len2)
_verify_condition(len1 == len2, default, msg, values)
names = self._get_list_index_name_mapping(names, len1)
diffs = list(self._yield_list_diffs(list1, list2, names))
default = 'Lists are different:\n' + '\n'.join(diffs)
_verify_condition(diffs == [], default, msg, values)
def _get_list_index_name_mapping(self, names, list_length):
if not names:
return {}
if is_dict_like(names):
return dict((int(index), names[index]) for index in names)
return dict(zip(range(list_length), names))
def _yield_list_diffs(self, list1, list2, names):
for index, (item1, item2) in enumerate(zip(list1, list2)):
name = ' (%s)' % names[index] if index in names else ''
try:
assert_equal(item1, item2, msg='Index %d%s' % (index, name))
except AssertionError as err:
yield unic(err)
def list_should_contain_sub_list(self, list1, list2, msg=None, values=True):
"""Fails if not all of the elements in ``list2`` are found in ``list1``.
The order of values and the number of values are not taken into
account.
See `Lists Should Be Equal` for more information about configuring
the error message with ``msg`` and ``values`` arguments.
"""
self._validate_lists(list1, list2)
diffs = ', '.join(unic(item) for item in list2 if item not in list1)
default = 'Following values were not found from first list: ' + diffs
_verify_condition(not diffs, default, msg, values)
def log_list(self, list_, level='INFO'):
"""Logs the length and contents of the ``list`` using given ``level``.
Valid levels are TRACE, DEBUG, INFO (default), and WARN.
If you only want to the length, use keyword `Get Length` from
the BuiltIn library.
"""
self._validate_list(list_)
logger.write('\n'.join(self._log_list(list_)), level)
def _log_list(self, list_):
if not list_:
yield 'List is empty.'
elif len(list_) == 1:
yield 'List has one item:\n%s' % list_[0]
else:
yield 'List length is %d and it contains following items:' % len(list_)
for index, item in enumerate(list_):
yield '%s: %s' % (index, item)
def _index_to_int(self, index, empty_to_zero=False):
if empty_to_zero and not index:
return 0
try:
return int(index)
except ValueError:
raise ValueError("Cannot convert index '%s' to an integer." % index)
def _index_error(self, list_, index):
raise IndexError('Given index %s is out of the range 0-%d.'
% (index, len(list_)-1))
def _validate_list(self, list_, position=1):
if not is_list_like(list_):
raise TypeError("Expected argument %d to be a list or list-like, "
"got %s instead." % (position, type_name(list_)))
def _validate_lists(self, *lists):
for index, item in enumerate(lists, start=1):
self._validate_list(item, index)
class _Dictionary(object):
def convert_to_dictionary(self, item):
"""Converts the given ``item`` to a Python ``dict`` type.
Mainly useful for converting other mappings to normal dictionaries.
This includes converting Robot Framework's own ``DotDict`` instances
that it uses if variables are created using the ``&{var}`` syntax.
Use `Create Dictionary` from the BuiltIn library for constructing new
dictionaries.
New in Robot Framework 2.9.
"""
return dict(item)
def set_to_dictionary(self, dictionary, *key_value_pairs, **items):
"""Adds the given ``key_value_pairs`` and ``items`` to the ``dictionary``.
Giving items as ``key_value_pairs`` means giving keys and values
as separate arguments:
| Set To Dictionary | ${D1} | key | value | second | ${2} |
=>
| ${D1} = {'a': 1, 'key': 'value', 'second': 2}
| Set To Dictionary | ${D1} | key=value | second=${2} |
The latter syntax is typically more convenient to use, but it has
a limitation that keys must be strings.
If given keys already exist in the dictionary, their values are updated.
"""
self._validate_dictionary(dictionary)
if len(key_value_pairs) % 2 != 0:
raise ValueError("Adding data to a dictionary failed. There "
"should be even number of key-value-pairs.")
for i in range(0, len(key_value_pairs), 2):
dictionary[key_value_pairs[i]] = key_value_pairs[i+1]
dictionary.update(items)
return dictionary
def remove_from_dictionary(self, dictionary, *keys):
"""Removes the given ``keys`` from the ``dictionary``.
If the given ``key`` cannot be found from the ``dictionary``, it
is ignored.
Example:
| Remove From Dictionary | ${D3} | b | x | y |
=>
| ${D3} = {'a': 1, 'c': 3}
"""
self._validate_dictionary(dictionary)
for key in keys:
if key in dictionary:
value = dictionary.pop(key)
logger.info("Removed item with key '%s' and value '%s'." % (key, value))
else:
logger.info("Key '%s' not found." % key)
def pop_from_dictionary(self, dictionary, key, default=NOT_SET):
"""Pops the given ``key`` from the ``dictionary`` and returns its value.
By default the keyword fails if the given ``key`` cannot be found from
the ``dictionary``. If optional ``default`` value is given, it will be
returned instead of failing.
Example:
| ${val}= | Pop From Dictionary | ${D3} | b |
=>
| ${val} = 2
| ${D3} = {'a': 1, 'c': 3}
New in Robot Framework 2.9.2.
"""
self._validate_dictionary(dictionary)
if default is NOT_SET:
self.dictionary_should_contain_key(dictionary, key)
return dictionary.pop(key)
return dictionary.pop(key, default)
def keep_in_dictionary(self, dictionary, *keys):
"""Keeps the given ``keys`` in the ``dictionary`` and removes all other.
If the given ``key`` cannot be found from the ``dictionary``, it
is ignored.
Example:
| Keep In Dictionary | ${D5} | b | x | d |
=>
| ${D5} = {'b': 2, 'd': 4}
"""
self._validate_dictionary(dictionary)
remove_keys = [k for k in dictionary if k not in keys]
self.remove_from_dictionary(dictionary, *remove_keys)
def copy_dictionary(self, dictionary, deepcopy=False):
"""Returns a copy of the given dictionary.
The ``deepcopy`` argument controls should the returned dictionary be
a [https://docs.python.org/library/copy.html|shallow or deep copy].
By default returns a shallow copy, but that can be changed by giving
``deepcopy`` a true value (see `Boolean arguments`). This is a new
option in Robot Framework 3.1.2. Earlier versions always returned
shallow copies.
The given dictionary is never altered by this keyword.
"""
self._validate_dictionary(dictionary)
if deepcopy:
return copy.deepcopy(dictionary)
return dictionary.copy()
def get_dictionary_keys(self, dictionary, sort_keys=True):
"""Returns keys of the given ``dictionary`` as a list.
By default keys are returned in sorted order (assuming they are
sortable), but they can be returned in the original order by giving
``sort_keys`` a false value (see `Boolean arguments`). Notice that
with Python 3.5 and earlier dictionary order is undefined unless using
ordered dictionaries.
The given ``dictionary`` is never altered by this keyword.
Example:
| ${sorted} = | Get Dictionary Keys | ${D3} |
| ${unsorted} = | Get Dictionary Keys | ${D3} | sort_keys=False |
=>
| ${sorted} = ['a', 'b', 'c']
| ${unsorted} = ['b', 'a', 'c'] # Order depends on Python version.
``sort_keys`` is a new option in Robot Framework 3.1.2. Earlier keys
were always sorted.
"""
self._validate_dictionary(dictionary)
keys = dictionary.keys()
if sort_keys:
try:
return sorted(keys)
except TypeError:
pass
return list(keys)
def get_dictionary_values(self, dictionary, sort_keys=True):
"""Returns values of the given ``dictionary`` as a list.
Uses `Get Dictionary Keys` to get keys and then returns corresponding
values. By default keys are sorted and values returned in that order,
but this can be changed by giving ``sort_keys`` a false value (see
`Boolean arguments`). Notice that with Python 3.5 and earlier
dictionary order is undefined unless using ordered dictionaries.
The given ``dictionary`` is never altered by this keyword.
Example:
| ${sorted} = | Get Dictionary Values | ${D3} |
| ${unsorted} = | Get Dictionary Values | ${D3} | sort_keys=False |
=>
| ${sorted} = [1, 2, 3]
| ${unsorted} = [2, 1, 3] # Order depends on Python version.
``sort_keys`` is a new option in Robot Framework 3.1.2. Earlier values
were always sorted based on keys.
"""
self._validate_dictionary(dictionary)
keys = self.get_dictionary_keys(dictionary, sort_keys=sort_keys)
return [dictionary[k] for k in keys]
def get_dictionary_items(self, dictionary, sort_keys=True):
"""Returns items of the given ``dictionary`` as a list.
Uses `Get Dictionary Keys` to get keys and then returns corresponding
items. By default keys are sorted and items returned in that order,
but this can be changed by giving ``sort_keys`` a false value (see
`Boolean arguments`). Notice that with Python 3.5 and earlier
dictionary order is undefined unless using ordered dictionaries.
Items are returned as a flat list so that first item is a key,
second item is a corresponding value, third item is the second key,
and so on.
The given ``dictionary`` is never altered by this keyword.
Example:
| ${sorted} = | Get Dictionary Items | ${D3} |
| ${unsorted} = | Get Dictionary Items | ${D3} | sort_keys=False |
=>
| ${sorted} = ['a', 1, 'b', 2, 'c', 3]
| ${unsorted} = ['b', 2, 'a', 1, 'c', 3] # Order depends on Python version.
``sort_keys`` is a new option in Robot Framework 3.1.2. Earlier items
were always sorted based on keys.
"""
self._validate_dictionary(dictionary)
keys = self.get_dictionary_keys(dictionary, sort_keys=sort_keys)
return [i for key in keys for i in (key, dictionary[key])]
def get_from_dictionary(self, dictionary, key):
"""Returns a value from the given ``dictionary`` based on the given ``key``.
If the given ``key`` cannot be found from the ``dictionary``, this
keyword fails.
The given dictionary is never altered by this keyword.
Example:
| ${value} = | Get From Dictionary | ${D3} | b |
=>
| ${value} = 2
"""
self._validate_dictionary(dictionary)
try:
return dictionary[key]
except KeyError:
raise RuntimeError("Dictionary does not contain key '%s'." % key)
def dictionary_should_contain_key(self, dictionary, key, msg=None):
"""Fails if ``key`` is not found from ``dictionary``.
Use the ``msg`` argument to override the default error message.
"""
self._validate_dictionary(dictionary)
default = "Dictionary does not contain key '%s'." % key
_verify_condition(key in dictionary, default, msg)
def dictionary_should_not_contain_key(self, dictionary, key, msg=None):
"""Fails if ``key`` is found from ``dictionary``.
Use the ``msg`` argument to override the default error message.
"""
self._validate_dictionary(dictionary)
default = "Dictionary contains key '%s'." % key
_verify_condition(key not in dictionary, default, msg)
def dictionary_should_contain_item(self, dictionary, key, value, msg=None):
"""An item of ``key`` / ``value`` must be found in a ``dictionary``.
Value is converted to unicode for comparison.
Use the ``msg`` argument to override the default error message.
"""
self._validate_dictionary(dictionary)
self.dictionary_should_contain_key(dictionary, key, msg)
actual, expected = unic(dictionary[key]), unic(value)
default = "Value of dictionary key '%s' does not match: %s != %s" % (key, actual, expected)
_verify_condition(actual == expected, default, msg)
def dictionary_should_contain_value(self, dictionary, value, msg=None):
"""Fails if ``value`` is not found from ``dictionary``.
Use the ``msg`` argument to override the default error message.
"""
self._validate_dictionary(dictionary)
default = "Dictionary does not contain value '%s'." % value
_verify_condition(value in dictionary.values(), default, msg)
def dictionary_should_not_contain_value(self, dictionary, value, msg=None):
"""Fails if ``value`` is found from ``dictionary``.
Use the ``msg`` argument to override the default error message.
"""
self._validate_dictionary(dictionary)
default = "Dictionary contains value '%s'." % value
_verify_condition(not value in dictionary.values(), default, msg)
def dictionaries_should_be_equal(self, dict1, dict2, msg=None, values=True):
"""Fails if the given dictionaries are not equal.
First the equality of dictionaries' keys is checked and after that all
the key value pairs. If there are differences between the values, those
are listed in the error message. The types of the dictionaries do not
need to be same.
See `Lists Should Be Equal` for more information about configuring
the error message with ``msg`` and ``values`` arguments.
"""
self._validate_dictionary(dict1)
self._validate_dictionary(dict2, 2)
keys = self._keys_should_be_equal(dict1, dict2, msg, values)
self._key_values_should_be_equal(keys, dict1, dict2, msg, values)
def dictionary_should_contain_sub_dictionary(self, dict1, dict2, msg=None,
values=True):
"""Fails unless all items in ``dict2`` are found from ``dict1``.
See `Lists Should Be Equal` for more information about configuring
the error message with ``msg`` and ``values`` arguments.
"""
self._validate_dictionary(dict1)
self._validate_dictionary(dict2, 2)
keys = self.get_dictionary_keys(dict2)
diffs = [unic(k) for k in keys if k not in dict1]
default = "Following keys missing from first dictionary: %s" \
% ', '.join(diffs)
_verify_condition(not diffs, default, msg, values)
self._key_values_should_be_equal(keys, dict1, dict2, msg, values)
def log_dictionary(self, dictionary, level='INFO'):
"""Logs the size and contents of the ``dictionary`` using given ``level``.
Valid levels are TRACE, DEBUG, INFO (default), and WARN.
If you only want to log the size, use keyword `Get Length` from
the BuiltIn library.
"""
self._validate_dictionary(dictionary)
logger.write('\n'.join(self._log_dictionary(dictionary)), level)
def _log_dictionary(self, dictionary):
if not dictionary:
yield 'Dictionary is empty.'
elif len(dictionary) == 1:
yield 'Dictionary has one item:'
else:
yield 'Dictionary size is %d and it contains following items:' % len(dictionary)
for key in self.get_dictionary_keys(dictionary):
yield '%s: %s' % (key, dictionary[key])
def _keys_should_be_equal(self, dict1, dict2, msg, values):
keys1 = self.get_dictionary_keys(dict1)
keys2 = self.get_dictionary_keys(dict2)
miss1 = [unic(k) for k in keys2 if k not in dict1]
miss2 = [unic(k) for k in keys1 if k not in dict2]
error = []
if miss1:
error += ['Following keys missing from first dictionary: %s'
% ', '.join(miss1)]
if miss2:
error += ['Following keys missing from second dictionary: %s'
% ', '.join(miss2)]
_verify_condition(not error, '\n'.join(error), msg, values)
return keys1
def _key_values_should_be_equal(self, keys, dict1, dict2, msg, values):
diffs = list(self._yield_dict_diffs(keys, dict1, dict2))
default = 'Following keys have different values:\n' + '\n'.join(diffs)
_verify_condition(not diffs, default, msg, values)
def _yield_dict_diffs(self, keys, dict1, dict2):
for key in keys:
try:
assert_equal(dict1[key], dict2[key], msg='Key %s' % (key,))
except AssertionError as err:
yield unic(err)
def _validate_dictionary(self, dictionary, position=1):
if is_string(dictionary) or is_number(dictionary):
raise TypeError("Expected argument %d to be a dictionary or dictionary-like, "
"got %s instead." % (position, type_name(dictionary)))
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``.
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.
Use the ``msg`` argument to override the default error message.
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))
def _verify_condition(condition, default_msg, msg, values=False):
if condition:
return
if not msg:
msg = default_msg
elif is_truthy(values) and str(values).upper() != 'NO VALUES':
msg += '\n' + default_msg
raise AssertionError(msg)
def _get_matches_in_iterable(iterable, pattern, case_insensitive=False,
whitespace_insensitive=False):
if not is_string(pattern):
raise TypeError("Pattern must be string, got '%s'." % type_name(pattern))
regexp = False
if pattern.startswith('regexp='):
pattern = pattern[7:]
regexp = True
elif pattern.startswith('glob='):
pattern = pattern[5:]
matcher = Matcher(pattern,
caseless=is_truthy(case_insensitive),
spaceless=is_truthy(whitespace_insensitive),
regexp=regexp)
return [string for string in iterable
if is_string(string) and matcher.match(string)] | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libraries/Collections.py | 0.781164 | 0.594728 | Collections.py | pypi |
from __future__ import absolute_import
from datetime import datetime, timedelta
import time
import re
from robotide.lib.robot.version import get_version
from robotide.lib.robot.utils import (elapsed_time_to_string, is_falsy, is_number, is_string, roundup, secs_to_timestr,
timestr_to_secs, type_name, IRONPYTHON)
__version__ = get_version()
__all__ = ['convert_time', 'convert_date', 'subtract_date_from_date',
'subtract_time_from_date', 'subtract_time_from_time',
'add_time_to_time', 'add_time_to_date', 'get_current_date']
def get_current_date(time_zone='local', increment=0,
result_format='timestamp', exclude_millis=False):
"""Returns current local or UTC time with an optional increment.
Arguments:
- ``time_zone:`` Get the current time on this time zone. Currently only
``local`` (default) and ``UTC`` are supported.
- ``increment:`` Optional time increment to add to the returned date in
one of the supported `time formats`. Can be negative.
- ``result_format:`` Format of the returned date (see `date formats`).
- ``exclude_millis:`` When set to any true value, rounds and drops
milliseconds as explained in `millisecond handling`.
Examples:
| ${date} = | Get Current Date |
| Should Be Equal | ${date} | 2014-06-12 20:00:58.946 |
| ${date} = | Get Current Date | UTC |
| Should Be Equal | ${date} | 2014-06-12 17:00:58.946 |
| ${date} = | Get Current Date | increment=02:30:00 |
| Should Be Equal | ${date} | 2014-06-12 22:30:58.946 |
| ${date} = | Get Current Date | UTC | - 5 hours |
| Should Be Equal | ${date} | 2014-06-12 12:00:58.946 |
| ${date} = | Get Current Date | result_format=datetime |
| Should Be Equal | ${date.year} | ${2014} |
| Should Be Equal | ${date.month} | ${6} |
"""
if time_zone.upper() == 'LOCAL':
dt = datetime.now()
elif time_zone.upper() == 'UTC':
dt = datetime.utcnow()
else:
raise ValueError("Unsupported timezone '%s'." % time_zone)
date = Date(dt) + Time(increment)
return date.convert(result_format, millis=is_falsy(exclude_millis))
def convert_date(date, result_format='timestamp', exclude_millis=False,
date_format=None):
"""Converts between supported `date formats`.
Arguments:
- ``date:`` Date in one of the supported `date formats`.
- ``result_format:`` Format of the returned date.
- ``exclude_millis:`` When set to any true value, rounds and drops
milliseconds as explained in `millisecond handling`.
- ``date_format:`` Specifies possible `custom timestamp` format.
Examples:
| ${date} = | Convert Date | 20140528 12:05:03.111 |
| Should Be Equal | ${date} | 2014-05-28 12:05:03.111 |
| ${date} = | Convert Date | ${date} | epoch |
| Should Be Equal | ${date} | ${1401267903.111} |
| ${date} = | Convert Date | 5.28.2014 12:05 | exclude_millis=yes | date_format=%m.%d.%Y %H:%M |
| Should Be Equal | ${date} | 2014-05-28 12:05:00 |
"""
return Date(date, date_format).convert(result_format,
millis=is_falsy(exclude_millis))
def convert_time(ltime, result_format='number', exclude_millis=False):
"""Converts between supported `time formats`.
Arguments:
- ``time:`` Time in one of the supported `time formats`.
- ``result_format:`` Format of the returned time.
- ``exclude_millis:`` When set to any true value, rounds and drops
milliseconds as explained in `millisecond handling`.
Examples:
| ${time} = | Convert Time | 10 seconds |
| Should Be Equal | ${time} | ${10} |
| ${time} = | Convert Time | 1:00:01 | verbose |
| Should Be Equal | ${time} | 1 hour 1 second |
| ${time} = | Convert Time | ${3661.5} | timer | exclude_milles=yes |
| Should Be Equal | ${time} | 01:01:02 |
"""
return Time(ltime).convert(result_format, millis=is_falsy(exclude_millis))
def subtract_date_from_date(date1, date2, result_format='number',
exclude_millis=False, date1_format=None,
date2_format=None):
"""Subtracts date from another date and returns time between.
Arguments:
- ``date1:`` Date to subtract another date from in one of the
supported `date formats`.
- ``date2:`` Date that is subtracted in one of the supported
`date formats`.
- ``result_format:`` Format of the returned time (see `time formats`).
- ``exclude_millis:`` When set to any true value, rounds and drops
milliseconds as explained in `millisecond handling`.
- ``date1_format:`` Possible `custom timestamp` format of ``date1``.
- ``date2_format:`` Possible `custom timestamp` format of ``date2``.
Examples:
| ${time} = | Subtract Date From Date | 2014-05-28 12:05:52 | 2014-05-28 12:05:10 |
| Should Be Equal | ${time} | ${42} |
| ${time} = | Subtract Date From Date | 2014-05-28 12:05:52 | 2014-05-27 12:05:10 | verbose |
| Should Be Equal | ${time} | 1 day 42 seconds |
"""
ltime = Date(date1, date1_format) - Date(date2, date2_format)
return ltime.convert(result_format, millis=is_falsy(exclude_millis))
def add_time_to_date(date, ltime, result_format='timestamp',
exclude_millis=False, date_format=None):
"""Adds time to date and returns the resulting date.
Arguments:
- ``date:`` Date to add time to in one of the supported
`date formats`.
- ``time:`` Time that is added in one of the supported
`time formats`.
- ``result_format:`` Format of the returned date.
- ``exclude_millis:`` When set to any true value, rounds and drops
milliseconds as explained in `millisecond handling`.
- ``date_format:`` Possible `custom timestamp` format of ``date``.
Examples:
| ${date} = | Add Time To Date | 2014-05-28 12:05:03.111 | 7 days |
| Should Be Equal | ${date} | 2014-06-04 12:05:03.111 | |
| ${date} = | Add Time To Date | 2014-05-28 12:05:03.111 | 01:02:03:004 |
| Should Be Equal | ${date} | 2014-05-28 13:07:06.115 |
"""
date = Date(date, date_format) + Time(ltime)
return date.convert(result_format, millis=is_falsy(exclude_millis))
def subtract_time_from_date(date, ltime, result_format='timestamp',
exclude_millis=False, date_format=None):
"""Subtracts time from date and returns the resulting date.
Arguments:
- ``date:`` Date to subtract time from in one of the supported
`date formats`.
- ``time:`` Time that is subtracted in one of the supported
`time formats`.
- ``result_format:`` Format of the returned date.
- ``exclude_millis:`` When set to any true value, rounds and drops
milliseconds as explained in `millisecond handling`.
- ``date_format:`` Possible `custom timestamp` format of ``date``.
Examples:
| ${date} = | Subtract Time From Date | 2014-06-04 12:05:03.111 | 7 days |
| Should Be Equal | ${date} | 2014-05-28 12:05:03.111 |
| ${date} = | Subtract Time From Date | 2014-05-28 13:07:06.115 | 01:02:03:004 |
| Should Be Equal | ${date} | 2014-05-28 12:05:03.111 |
"""
date = Date(date, date_format) - Time(ltime)
return date.convert(result_format, millis=is_falsy(exclude_millis))
def add_time_to_time(time1, time2, result_format='number',
exclude_millis=False):
"""Adds time to another time and returns the resulting time.
Arguments:
- ``time1:`` First time in one of the supported `time formats`.
- ``time2:`` Second time in one of the supported `time formats`.
- ``result_format:`` Format of the returned time.
- ``exclude_millis:`` When set to any true value, rounds and drops
milliseconds as explained in `millisecond handling`.
Examples:
| ${time} = | Add Time To Time | 1 minute | 42 |
| Should Be Equal | ${time} | ${102} |
| ${time} = | Add Time To Time | 3 hours 5 minutes | 01:02:03 | timer | exclude_millis=yes |
| Should Be Equal | ${time} | 04:07:03 |
"""
ltime = Time(time1) + Time(time2)
return ltime.convert(result_format, millis=is_falsy(exclude_millis))
def subtract_time_from_time(time1, time2, result_format='number',
exclude_millis=False):
"""Subtracts time from another time and returns the resulting time.
Arguments:
- ``time1:`` Time to subtract another time from in one of
the supported `time formats`.
- ``time2:`` Time to subtract in one of the supported `time formats`.
- ``result_format:`` Format of the returned time.
- ``exclude_millis:`` When set to any true value, rounds and drops
milliseconds as explained in `millisecond handling`.
Examples:
| ${time} = | Subtract Time From Time | 00:02:30 | 100 |
| Should Be Equal | ${time} | ${50} |
| ${time} = | Subtract Time From Time | ${time} | 1 minute | compact |
| Should Be Equal | ${time} | - 10s |
"""
ltime = Time(time1) - Time(time2)
return ltime.convert(result_format, millis=is_falsy(exclude_millis))
class Date(object):
def __init__(self, date, input_format=None):
self.datetime = self._convert_to_datetime(date, input_format)
@property
def seconds(self):
# Mainly for backwards compatibility with RF 2.9.1 and earlier.
return self._convert_to_epoch(self.datetime)
def _convert_to_datetime(self, date, input_format):
if isinstance(date, datetime):
return date
if is_number(date):
return self._seconds_to_datetime(date)
if is_string(date):
return self._string_to_datetime(date, input_format)
raise ValueError("Unsupported input '%s'." % date)
@staticmethod
def _seconds_to_datetime(secs):
# Workaround microsecond rounding errors with IronPython:
# https://github.com/IronLanguages/main/issues/1170
# Also Jython had similar problems, but they seem to be fixed in 2.7.
dt = datetime.fromtimestamp(secs)
return dt.replace(microsecond=roundup(secs % 1 * 1e6))
def _string_to_datetime(self, ts, input_format):
if not input_format:
ts = self._normalize_timestamp(ts)
input_format = '%Y-%m-%d %H:%M:%S.%f'
if self._need_to_handle_f_directive(input_format):
return self._handle_un_supported_f_directive(ts, input_format)
return datetime.strptime(ts, input_format)
@staticmethod
def _normalize_timestamp(date):
ts = ''.join(d for d in date if d.isdigit())
if not (8 <= len(ts) <= 20):
raise ValueError("Invalid timestamp '%s'." % date)
ts = ts.ljust(20, '0')
return '%s-%s-%s %s:%s:%s.%s' % (ts[:4], ts[4:6], ts[6:8], ts[8:10],
ts[10:12], ts[12:14], ts[14:])
@staticmethod
def _need_to_handle_f_directive(lformat):
# https://github.com/IronLanguages/main/issues/1169
return IRONPYTHON and '%f' in lformat
def _handle_un_supported_f_directive(self, ts, input_format):
input_format = self._remove_f_from_format(input_format)
match = re.search(r"\d+$", ts)
if not match:
raise ValueError("time data '%s' does not match format '%s%%f'."
% (ts, input_format))
end_digits = match.group(0)
micro = int(end_digits.ljust(6, '0'))
dt = datetime.strptime(ts[:-len(end_digits)], input_format)
return dt.replace(microsecond=micro)
@staticmethod
def _remove_f_from_format(lformat):
if not lformat.endswith('%f'):
raise ValueError('%f directive is supported only at the end of '
'the format string on this Python interpreter.')
return lformat[:-2]
def convert(self, lformat, millis=True):
dt = self.datetime
if not millis:
secs = 1 if dt.microsecond >= 5e5 else 0
dt = dt.replace(microsecond=0) + timedelta(seconds=secs)
if '%' in lformat:
return self._convert_to_custom_timestamp(dt, lformat)
lformat = lformat.lower()
if lformat == 'timestamp':
return self._convert_to_timestamp(dt, millis)
if lformat == 'datetime':
return dt
if lformat == 'epoch':
return self._convert_to_epoch(dt)
raise ValueError("Unknown format '%s'." % lformat)
def _convert_to_custom_timestamp(self, dt, lformat):
if not self._need_to_handle_f_directive(lformat):
return dt.strftime(lformat)
lformat = self._remove_f_from_format(lformat)
return dt.strftime(lformat) + '%06d' % dt.microsecond
@staticmethod
def _convert_to_timestamp(dt, millis=True):
if not millis:
return dt.strftime('%Y-%m-%d %H:%M:%S')
ms = roundup(dt.microsecond / 1000.0)
if ms == 1000:
dt += timedelta(seconds=1)
ms = 0
return dt.strftime('%Y-%m-%d %H:%M:%S') + '.%03d' % ms
@staticmethod
def _convert_to_epoch(dt):
return time.mktime(dt.timetuple()) + dt.microsecond / 1e6
def __add__(self, other):
if isinstance(other, Time):
return Date(self.datetime + other.timedelta)
raise TypeError('Can only add Time to Date, got %s.' % type_name(other))
def __sub__(self, other):
if isinstance(other, Date):
return Time(self.datetime - other.datetime)
if isinstance(other, Time):
return Date(self.datetime - other.timedelta)
raise TypeError('Can only subtract Date or Time from Date, got %s.'
% type_name(other))
class Time(object):
def __init__(self, ltime):
self.seconds = float(self._convert_time_to_seconds(ltime))
@staticmethod
def _convert_time_to_seconds(ltime):
if isinstance(ltime, timedelta):
return ltime.total_seconds()
return timestr_to_secs(time, round_to=None)
@property
def timedelta(self):
return timedelta(seconds=self.seconds)
def convert(self, lformat, millis=True):
try:
result_converter = getattr(self, '_convert_to_%s' % lformat.lower())
except AttributeError:
raise ValueError("Unknown format '%s'." % lformat)
seconds = self.seconds if millis else float(roundup(self.seconds))
return result_converter(seconds, millis)
@staticmethod
def _convert_to_number(seconds, millis=True):
_ = millis
return seconds
@staticmethod
def _convert_to_verbose(seconds, millis=True):
_ = millis
return secs_to_timestr(seconds)
@staticmethod
def _convert_to_compact(seconds, millis=True):
_ = millis
return secs_to_timestr(seconds, compact=True)
@staticmethod
def _convert_to_timer(seconds, millis=True):
return elapsed_time_to_string(seconds * 1000, include_millis=millis)
@staticmethod
def _convert_to_timedelta(seconds, millis=True):
_ = millis
return timedelta(seconds=seconds)
def __add__(self, other):
if isinstance(other, Time):
return Time(self.seconds + other.seconds)
raise TypeError('Can only add Time to Time, got %s.' % type_name(other))
def __sub__(self, other):
if isinstance(other, Time):
return Time(self.seconds - other.seconds)
raise TypeError('Can only subtract Time from Time, got %s.'
% type_name(other)) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libraries/DateTime.py | 0.90722 | 0.354824 | DateTime.py | pypi |
from contextlib import contextmanager
import inspect
import re
import socket
import struct
import telnetlib
import time
try:
import pyte
except ImportError:
pyte = None
from robotide.lib.robot.api import logger
from robotide.lib.robot.api.deco import keyword
from robotide.lib.robot.utils import (ConnectionCache, is_bytes, is_string, is_truthy,
is_unicode, secs_to_timestr, seq2str, timestr_to_secs)
from robotide.lib.robot.version import get_version
class Telnet(object):
"""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`
- `Boolean arguments`
- `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`,
`Set Default Log Level` and `Set Telnetlib 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.
== Connection Timeout ==
Connection Timeout defines how long is the maximum time to wait when
opening the telnet connection. It is used internally by `Open Connection`.
The default value is the system global default timeout.
New in Robot Framework 2.9.2.
== 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. Prompt can be set to be a regular expression
by giving ``prompt_is_regexp`` argument a true value (see `Boolean
arguments`).
Examples:
| `Open Connection` | lolcathost | prompt=$ |
| `Set Prompt` | (> |# ) | prompt_is_regexp=true |
== 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 |
== 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.
== 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`.
== Window size ==
Window size for negotiation with the server can be configured when
`importing` the library and with `Open Connection`.
== 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`.
= Terminal emulation =
Telnet library supports terminal
emulation with [http://pyte.readthedocs.io|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 by giving ``terminal_emulation``
argument a true value (see `Boolean arguments`) either in the library
initialization or with `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.
Examples:
| `Open Connection` | lolcathost | terminal_emulation=True | terminal_type=vt100 | window_size=400x100 |
As a prerequisite for using terminal emulation, you need to have Pyte
installed. Due to backwards incompatible changes in Pyte, different
Robot Framework versions support different Pyte versions:
- Pyte 0.6 and newer are supported by Robot Framework 3.0.3.
Latest Pyte version can be installed (or upgraded) with
``pip install --upgrade pyte``.
- Pyte 0.5.2 and older are supported by Robot Framework 3.0.2 and earlier.
Pyte 0.5.2 can be installed with ``pip install pyte==0.5.2``.
= 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/library/telnetlib.html|telnetlib module]
used by this library has a custom logging system for logging content it
sends and receives. By default these messages are written using ``TRACE``
level, but the level is configurable with the ``telnetlib_log_level``
option either in the library initialization, to the `Open Connection`
or by using the `Set Telnetlib Log Level` keyword to the active
connection. Special level ``NONE`` con be used to disable the logging
altogether.
= Time string format =
Timeouts and other times used must be given as a time string using 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://robotframework.org/robotframework/#user-guide|Robot Framework User Guide].
= 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. 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:
| `Open Connection` | lolcathost | terminal_emulation=True | # Strings are generally true. |
| `Open Connection` | lolcathost | terminal_emulation=yes | # Same as the above. |
| `Open Connection` | lolcathost | terminal_emulation=${TRUE} | # Python ``True`` is true. |
| `Open Connection` | lolcathost | terminal_emulation=${42} | # Numbers other than 0 are true. |
False examples:
| `Open Connection` | lolcathost | terminal_emulation=False | # String ``false`` is false. |
| `Open Connection` | lolcathost | terminal_emulation=no | # Also string ``no`` is false. |
| `Open Connection` | lolcathost | terminal_emulation=${EMPTY} | # Empty string is false. |
| `Open Connection` | lolcathost | terminal_emulation=${FALSE} | # Python ``False`` is false. |
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.
"""
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, telnetlib_log_level='TRACE',
connection_timeout=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 ...` `keywords`.
See these keywords as well as `Configuration`, `Terminal emulation` and
`Logging` sections above for more information about these parameters
and their possible values.
See `Time string format` and `Boolean arguments` sections for
information about using arguments accepting times and Boolean values,
respectively.
Examples (use only one of these):
| = Setting = | = Value = | = Value = | = Value = | = Value = | = Comment = |
| Library | Telnet | | | | # default values |
| Library | Telnet | 5 seconds | | | # set only timeout |
| Library | Telnet | newline=LF | encoding=ISO-8859-1 | | # set newline and encoding using named arguments |
| Library | Telnet | prompt=$ | | | # set prompt |
| Library | Telnet | prompt=(> |# ) | prompt_is_regexp=yes | | # 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 |
| Library | Telnet | telnetlib_log_level=NONE | | | # disable logging messages from the underlying telnetlib |
"""
self._timeout = timeout or 3.0
self._set_connection_timeout(connection_timeout)
self._newline = newline or 'CRLF'
self._prompt = (prompt, prompt_is_regexp)
self._encoding = encoding
self._encoding_errors = encoding_errors
self._default_log_level = default_log_level
self._window_size = window_size
self._environ_user = environ_user
self._terminal_emulation = terminal_emulation
self._terminal_type = terminal_type
self._telnetlib_log_level = telnetlib_log_level
self._cache = 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)
@keyword(types=None)
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=None,
terminal_type=None, telnetlib_log_level=None,
connection_timeout=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``, ``terminal_type`` and ``telnetlib_log_level``
arguments get default values when the library is [#Importing|imported].
Setting them here overrides those values for the opened connection.
See `Configuration`, `Terminal emulation` and `Logging` sections for
more information about these parameters and their possible values.
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
connection_timeout = (timestr_to_secs(connection_timeout)
if connection_timeout
else self._connection_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
if terminal_emulation is None:
terminal_emulation = self._terminal_emulation
terminal_type = terminal_type or self._terminal_type
telnetlib_log_level = telnetlib_log_level or self._telnetlib_log_level
if not prompt:
prompt, prompt_is_regexp = self._prompt
logger.info('Opening connection to %s:%s with prompt: %s%s'
% (host, port, prompt, ' (regexp)' if prompt_is_regexp else ''))
self._conn = self._get_connection(host, port, timeout, newline,
prompt, is_truthy(prompt_is_regexp),
encoding, encoding_errors,
default_log_level,
window_size,
environ_user,
is_truthy(terminal_emulation),
terminal_type,
telnetlib_log_level,
connection_timeout)
return self._cache.register(self._conn, alias)
def _parse_window_size(self, window_size):
if not window_size:
return None
try:
cols, rows = window_size.split('x', 1)
return int(cols), int(rows)
except ValueError:
raise ValueError("Invalid window size '%s'. Should be "
"<rows>x<columns>." % window_size)
def _get_connection(self, *args):
"""Can be overridden to use a custom connection."""
return TelnetConnection(*args)
def _set_connection_timeout(self, connection_timeout):
self._connection_timeout = connection_timeout
if self._connection_timeout:
self._connection_timeout = timestr_to_secs(connection_timeout)
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()
class TelnetConnection(telnetlib.Telnet):
NEW_ENVIRON_IS = b'\x00'
NEW_ENVIRON_VAR = b'\x00'
NEW_ENVIRON_VALUE = b'\x01'
INTERNAL_UPDATE_FREQUENCY = 0.03
def __init__(self, host=None, port=23, timeout=3.0, 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,
telnetlib_log_level='TRACE', connection_timeout=None):
if connection_timeout is None:
telnetlib.Telnet.__init__(self, host, int(port) if port else 23)
else:
telnetlib.Telnet.__init__(self, host, int(port) if port else 23,
connection_timeout)
self._set_timeout(timeout)
self._set_newline(newline)
self._set_prompt(prompt, prompt_is_regexp)
self._set_encoding(encoding, encoding_errors)
self._set_default_log_level(default_log_level)
self._window_size = window_size
self._environ_user = self._encode(environ_user) if environ_user else None
self._terminal_emulator = self._check_terminal_emulation(terminal_emulation)
self._terminal_type = self._encode(terminal_type) if terminal_type else None
self.set_option_negotiation_callback(self._negotiate_options)
self._set_telnetlib_log_level(telnetlib_log_level)
self._opt_responses = list()
def set_timeout(self, timeout):
"""Sets the timeout used for waiting output in the current connection.
Read operations that expect some output to appear (`Read Until`, `Read
Until Regexp`, `Read Until Prompt`, `Login`) use this timeout and fail
if the expected output does not appear before this timeout expires.
The ``timeout`` must be given in `time string format`. The old timeout
is returned and can be used to restore the timeout later.
Example:
| ${old} = | `Set Timeout` | 2 minute 30 seconds |
| `Do Something` |
| `Set Timeout` | ${old} |
See `Configuration` section for more information about global and
connection specific configuration.
"""
self._verify_connection()
old = self._timeout
self._set_timeout(timeout)
return secs_to_timestr(old)
def _set_timeout(self, timeout):
self._timeout = timestr_to_secs(timeout)
def set_newline(self, newline):
"""Sets the newline used by `Write` keyword in the current connection.
The old newline is returned and can be used to restore the newline later.
See `Set Timeout` for a similar example.
If terminal emulation is used, the newline can not be changed on an open
connection.
See `Configuration` section for more information about global and
connection specific configuration.
"""
self._verify_connection()
if self._terminal_emulator:
raise AssertionError("Newline can not be changed when terminal emulation is used.")
old = self._newline
self._set_newline(newline)
return old
def _set_newline(self, newline):
newline = str(newline).upper()
self._newline = newline.replace('LF', '\n').replace('CR', '\r')
def set_prompt(self, prompt, prompt_is_regexp=False):
"""Sets the prompt used by `Read Until Prompt` and `Login` in the current connection.
If ``prompt_is_regexp`` is given a true value (see `Boolean arguments`),
the given ``prompt`` is considered to be a regular expression.
The old prompt is returned and can be used to restore the prompt later.
Example:
| ${prompt} | ${regexp} = | `Set Prompt` | $ |
| `Do Something` |
| `Set Prompt` | ${prompt} | ${regexp} |
See the documentation of
[http://docs.python.org/library/re.html|Python re module]
for more information about the supported regular expression syntax.
Notice that possible backslashes need to be escaped in Robot Framework
test data.
See `Configuration` section for more information about global and
connection specific configuration.
"""
self._verify_connection()
old = self._prompt
self._set_prompt(prompt, prompt_is_regexp)
if old[1]:
return old[0].pattern, True
return old
def _set_prompt(self, prompt, prompt_is_regexp):
if is_truthy(prompt_is_regexp):
self._prompt = (re.compile(prompt), True)
else:
self._prompt = (prompt, False)
def _prompt_is_set(self):
return self._prompt[0] is not None
@keyword(types=None)
def set_encoding(self, encoding=None, errors=None):
"""Sets the encoding to use for `writing and reading` in the current connection.
The given ``encoding`` specifies the encoding to use when written/read
text is encoded/decoded, and ``errors`` specifies the error handler to
use if encoding/decoding fails. Either of these can be omitted and in
that case the old value is not affected. Use string ``NONE`` to disable
encoding altogether.
See `Configuration` section for more information about encoding and
error handlers, as well as global and connection specific configuration
in general.
The old values are returned and can be used to restore the encoding
and the error handler later. See `Set Prompt` for a similar example.
If terminal emulation is used, the encoding can not be changed on an open
connection.
"""
self._verify_connection()
if self._terminal_emulator:
raise AssertionError("Encoding can not be changed when terminal emulation is used.")
old = self._encoding
self._set_encoding(encoding or old[0], errors or old[1])
return old
def _set_encoding(self, encoding, errors):
self._encoding = (encoding.upper(), errors)
def _encode(self, text):
if is_bytes(text):
return text
if self._encoding[0] == 'NONE':
return text.encode('ASCII')
return text.encode(*self._encoding)
def _decode(self, bytes):
if self._encoding[0] == 'NONE':
return bytes
return bytes.decode(*self._encoding)
def set_telnetlib_log_level(self, level):
"""Sets the log level used for `logging` in the underlying ``telnetlib``.
Note that ``telnetlib`` can be very noisy thus using the level ``NONE``
can shutdown the messages generated by this library.
"""
self._verify_connection()
old = self._telnetlib_log_level
self._set_telnetlib_log_level(level)
return old
def _set_telnetlib_log_level(self, level):
if level.upper() == 'NONE':
self._telnetlib_log_level = 'NONE'
elif self._is_valid_log_level(level) is False:
raise AssertionError("Invalid log level '%s'" % level)
self._telnetlib_log_level = level.upper()
def set_default_log_level(self, level):
"""Sets the default log level used for `logging` in the current connection.
The old default log level is returned and can be used to restore the
log level later.
See `Configuration` section for more information about global and
connection specific configuration.
"""
self._verify_connection()
old = self._default_log_level
self._set_default_log_level(level)
return old
def _set_default_log_level(self, level):
if level is None or not self._is_valid_log_level(level):
raise AssertionError("Invalid log level '%s'" % level)
self._default_log_level = level.upper()
def _is_valid_log_level(self, level):
if level is None:
return True
if not is_string(level):
return False
return level.upper() in ('TRACE', 'DEBUG', 'INFO', 'WARN')
def close_connection(self, loglevel=None):
"""Closes the current Telnet connection.
Remaining output in the connection is read, logged, and returned.
It is not an error to close an already closed connection.
Use `Close All Connections` if you want to make sure all opened
connections are closed.
See `Logging` section for more information about log levels.
"""
if self.sock:
self.sock.shutdown(socket.SHUT_RDWR)
self.close()
output = self._decode(self.read_all())
self._log(output, loglevel)
return output
def login(self, username, password, login_prompt='login: ',
password_prompt='Password: ', login_timeout='1 second',
login_incorrect='Login incorrect'):
"""Logs in to the Telnet server with the given user information.
This keyword reads from the connection until the ``login_prompt`` is
encountered and then types the given ``username``. Then it reads until
the ``password_prompt`` and types the given ``password``. In both cases
a newline is appended automatically and the connection specific
timeout used when waiting for outputs.
How logging status is verified depends on whether a prompt is set for
this connection or not:
1) If the prompt is set, this keyword reads the output until the prompt
is found using the normal timeout. If no prompt is found, login is
considered failed and also this keyword fails. Note that in this case
both ``login_timeout`` and ``login_incorrect`` arguments are ignored.
2) If the prompt is not set, this keywords sleeps until ``login_timeout``
and then reads all the output available on the connection. If the
output contains ``login_incorrect`` text, login is considered failed
and also this keyword fails.
See `Configuration` section for more information about setting
newline, timeout, and prompt.
"""
output = self._submit_credentials(username, password, login_prompt,
password_prompt)
if self._prompt_is_set():
success, output2 = self._read_until_prompt()
else:
success, output2 = self._verify_login_without_prompt(
login_timeout, login_incorrect)
output += output2
self._log(output)
if not success:
raise AssertionError('Login incorrect')
return output
def _submit_credentials(self, username, password, login_prompt, password_prompt):
# Using write_bare here instead of write because don't want to wait for
# newline: https://github.com/robotframework/robotframework/issues/1371
output = self.read_until(login_prompt, 'TRACE')
self.write_bare(username + self._newline)
output += self.read_until(password_prompt, 'TRACE')
self.write_bare(password + self._newline)
return output
def _verify_login_without_prompt(self, delay, incorrect):
time.sleep(timestr_to_secs(delay))
output = self.read('TRACE')
success = incorrect not in output
return success, output
def write(self, text, loglevel=None):
"""Writes the given text plus a newline into the connection.
The newline character sequence to use can be [#Configuration|configured]
both globally and per connection basis. The default value is ``CRLF``.
This keyword consumes the written text, until the added newline, from
the output and logs and returns it. The given text itself must not
contain newlines. Use `Write Bare` instead if either of these features
causes a problem.
*Note:* This keyword does not return the possible output of the executed
command. To get the output, one of the `Read ...` `keywords` must be
used. See `Writing and reading` section for more details.
See `Logging` section for more information about log levels.
"""
newline = self._get_newline_for(text)
if newline in text:
raise RuntimeError("'Write' keyword cannot be used with strings "
"containing newlines. Use 'Write Bare' instead.")
self.write_bare(text + newline)
# Can't read until 'text' because long lines are cut strangely in the output
return self.read_until(self._newline, loglevel)
def _get_newline_for(self, text):
if is_bytes(text):
return self._encode(self._newline)
return self._newline
def write_bare(self, text):
"""Writes the given text, and nothing else, into the connection.
This keyword does not append a newline nor consume the written text.
Use `Write` if these features are needed.
"""
self._verify_connection()
telnetlib.Telnet.write(self, self._encode(text))
def write_until_expected_output(self, text, expected, timeout,
retry_interval, loglevel=None):
"""Writes the given ``text`` repeatedly, until ``expected`` appears in the output.
``text`` is written without appending a newline and it is consumed from
the output before trying to find ``expected``. If ``expected`` does not
appear in the output within ``timeout``, this keyword fails.
``retry_interval`` defines the time to wait ``expected`` to appear before
writing the ``text`` again. Consuming the written ``text`` is subject to
the normal [#Configuration|configured timeout].
Both ``timeout`` and ``retry_interval`` must be given in `time string
format`. See `Logging` section for more information about log levels.
Example:
| Write Until Expected Output | ps -ef| grep myprocess\\r\\n | myprocess |
| ... | 5 s | 0.5 s |
The above example writes command ``ps -ef | grep myprocess\\r\\n`` until
``myprocess`` appears in the output. The command is written every 0.5
seconds and the keyword fails if ``myprocess`` does not appear in
the output in 5 seconds.
"""
timeout = timestr_to_secs(timeout)
retry_interval = timestr_to_secs(retry_interval)
maxtime = time.time() + timeout
while time.time() < maxtime:
self.write_bare(text)
self.read_until(text, loglevel)
try:
with self._custom_timeout(retry_interval):
return self.read_until(expected, loglevel)
except AssertionError:
pass
raise NoMatchError(expected, timeout)
def write_control_character(self, character):
"""Writes the given control character into the connection.
The control character is prepended with an IAC (interpret as command)
character.
The following control character names are supported: BRK, IP, AO, AYT,
EC, EL, NOP. Additionally, you can use arbitrary numbers to send any
control character.
Example:
| Write Control Character | BRK | # Send Break command |
| Write Control Character | 241 | # Send No operation command |
"""
self._verify_connection()
self.sock.sendall(telnetlib.IAC + self._get_control_character(character))
def _get_control_character(self, int_or_name):
try:
ordinal = int(int_or_name)
return bytes(bytearray([ordinal]))
except ValueError:
return self._convert_control_code_name_to_character(int_or_name)
def _convert_control_code_name_to_character(self, name):
code_names = {
'BRK' : telnetlib.BRK,
'IP' : telnetlib.IP,
'AO' : telnetlib.AO,
'AYT' : telnetlib.AYT,
'EC' : telnetlib.EC,
'EL' : telnetlib.EL,
'NOP' : telnetlib.NOP
}
try:
return code_names[name]
except KeyError:
raise RuntimeError("Unsupported control character '%s'." % name)
def read(self, loglevel=None):
"""Reads everything that is currently available in the output.
Read output is both returned and logged. See `Logging` section for more
information about log levels.
"""
self._verify_connection()
output = self._decode(self.read_very_eager())
if self._terminal_emulator:
self._terminal_emulator.feed(output)
output = self._terminal_emulator.read()
self._log(output, loglevel)
return output
def read_until(self, expected, loglevel=None):
"""Reads output until ``expected`` text is encountered.
Text up to and including the match is returned and logged. If no match
is found, this keyword fails. How much to wait for the output depends
on the [#Configuration|configured timeout].
See `Logging` section for more information about log levels. Use
`Read Until Regexp` if more complex matching is needed.
"""
success, output = self._read_until(expected)
self._log(output, loglevel)
if not success:
raise NoMatchError(expected, self._timeout, output)
return output
def _read_until(self, expected):
self._verify_connection()
if self._terminal_emulator:
return self._terminal_read_until(expected)
expected = self._encode(expected)
output = telnetlib.Telnet.read_until(self, expected, self._timeout)
return output.endswith(expected), self._decode(output)
@property
def _terminal_frequency(self):
return min(self.INTERNAL_UPDATE_FREQUENCY, self._timeout)
def _terminal_read_until(self, expected):
max_time = time.time() + self._timeout
output = self._terminal_emulator.read_until(expected)
if output:
return True, output
while time.time() < max_time:
output = telnetlib.Telnet.read_until(self, self._encode(expected),
self._terminal_frequency)
self._terminal_emulator.feed(self._decode(output))
output = self._terminal_emulator.read_until(expected)
if output:
return True, output
return False, self._terminal_emulator.read()
def _read_until_regexp(self, *expected):
self._verify_connection()
if self._terminal_emulator:
return self._terminal_read_until_regexp(expected)
expected = [self._encode(exp) if is_unicode(exp) else exp
for exp in expected]
return self._telnet_read_until_regexp(expected)
def _terminal_read_until_regexp(self, expected_list):
max_time = time.time() + self._timeout
regexps_bytes = [self._to_byte_regexp(rgx) for rgx in expected_list]
regexps_unicode = [re.compile(self._decode(rgx.pattern))
for rgx in regexps_bytes]
out = self._terminal_emulator.read_until_regexp(regexps_unicode)
if out:
return True, out
while time.time() < max_time:
output = self.expect(regexps_bytes, self._terminal_frequency)[-1]
self._terminal_emulator.feed(self._decode(output))
out = self._terminal_emulator.read_until_regexp(regexps_unicode)
if out:
return True, out
return False, self._terminal_emulator.read()
def _telnet_read_until_regexp(self, expected_list):
expected = [self._to_byte_regexp(exp) for exp in expected_list]
try:
index, _, output = self.expect(expected, self._timeout)
except TypeError:
index, output = -1, b''
return index != -1, self._decode(output)
def _to_byte_regexp(self, exp):
if is_bytes(exp):
return re.compile(exp)
if is_string(exp):
return re.compile(self._encode(exp))
pattern = exp.pattern
if is_bytes(pattern):
return exp
return re.compile(self._encode(pattern))
def read_until_regexp(self, *expected):
"""Reads output until any of the ``expected`` regular expressions match.
This keyword accepts any number of regular expressions patterns or
compiled Python regular expression objects as arguments. Text up to
and including the first match to any of the regular expressions is
returned and logged. If no match is found, this keyword fails. How much
to wait for the output depends on the [#Configuration|configured timeout].
If the last given argument is a [#Logging|valid log level], it is used
as ``loglevel`` similarly as with `Read Until` keyword.
See the documentation of
[http://docs.python.org/library/re.html|Python re module]
for more information about the supported regular expression syntax.
Notice that possible backslashes need to be escaped in Robot Framework
test data.
Examples:
| `Read Until Regexp` | (#|$) |
| `Read Until Regexp` | first_regexp | second_regexp |
| `Read Until Regexp` | \\\\d{4}-\\\\d{2}-\\\\d{2} | DEBUG |
"""
if not expected:
raise RuntimeError('At least one pattern required')
if self._is_valid_log_level(expected[-1]):
loglevel = expected[-1]
expected = expected[:-1]
else:
loglevel = None
success, output = self._read_until_regexp(*expected)
self._log(output, loglevel)
if not success:
expected = [exp if is_string(exp) else exp.pattern
for exp in expected]
raise NoMatchError(expected, self._timeout, output)
return output
def read_until_prompt(self, loglevel=None, strip_prompt=False):
"""Reads output until the prompt is encountered.
This keyword requires the prompt to be [#Configuration|configured]
either in `importing` or with `Open Connection` or `Set Prompt` keyword.
By default, text up to and including the prompt is returned and logged.
If no prompt is found, this keyword fails. How much to wait for the
output depends on the [#Configuration|configured timeout].
If you want to exclude the prompt from the returned output, set
``strip_prompt`` to a true value (see `Boolean arguments`). If your
prompt is a regular expression, make sure that the expression spans the
whole prompt, because only the part of the output that matches the
regular expression is stripped away.
See `Logging` section for more information about log levels.
"""
if not self._prompt_is_set():
raise RuntimeError('Prompt is not set.')
success, output = self._read_until_prompt()
self._log(output, loglevel)
if not success:
prompt, regexp = self._prompt
raise AssertionError("Prompt '%s' not found in %s."
% (prompt if not regexp else prompt.pattern,
secs_to_timestr(self._timeout)))
if is_truthy(strip_prompt):
output = self._strip_prompt(output)
return output
def _read_until_prompt(self):
prompt, regexp = self._prompt
read_until = self._read_until_regexp if regexp else self._read_until
return read_until(prompt)
def _strip_prompt(self, output):
prompt, regexp = self._prompt
if not regexp:
length = len(prompt)
else:
match = prompt.search(output)
length = match.end() - match.start()
return output[:-length]
def execute_command(self, command, loglevel=None, strip_prompt=False):
"""Executes the given ``command`` and reads, logs, and returns everything until the prompt.
This keyword requires the prompt to be [#Configuration|configured]
either in `importing` or with `Open Connection` or `Set Prompt` keyword.
This is a convenience keyword that uses `Write` and `Read Until Prompt`
internally. Following two examples are thus functionally identical:
| ${out} = | `Execute Command` | pwd |
| `Write` | pwd |
| ${out} = | `Read Until Prompt` |
See `Logging` section for more information about log levels and `Read
Until Prompt` for more information about the ``strip_prompt`` parameter.
"""
self.write(command, loglevel)
return self.read_until_prompt(loglevel, strip_prompt)
@contextmanager
def _custom_timeout(self, timeout):
old = self.set_timeout(timeout)
try:
yield
finally:
self.set_timeout(old)
def _verify_connection(self):
if not self.sock:
raise RuntimeError('No connection open')
def _log(self, msg, level=None):
msg = msg.strip()
if msg:
logger.write(msg, level or self._default_log_level)
def _negotiate_options(self, sock, cmd, opt):
# We don't have state changes in our accepted telnet options.
# Therefore, we just track if we've already responded to an option. If
# this is the case, we must not send any response.
if cmd in (telnetlib.DO, telnetlib.DONT, telnetlib.WILL, telnetlib.WONT):
if (cmd, opt) in self._opt_responses:
return
else:
self._opt_responses.append((cmd, opt))
# This is supposed to turn server side echoing on and turn other options off.
if opt == telnetlib.ECHO and cmd in (telnetlib.WILL, telnetlib.WONT):
self._opt_echo_on(opt)
elif cmd == telnetlib.DO and opt == telnetlib.TTYPE and self._terminal_type:
self._opt_terminal_type(opt, self._terminal_type)
elif cmd == telnetlib.DO and opt == telnetlib.NEW_ENVIRON and self._environ_user:
self._opt_environ_user(opt, self._environ_user)
elif cmd == telnetlib.DO and opt == telnetlib.NAWS and self._window_size:
self._opt_window_size(opt, *self._window_size)
elif opt != telnetlib.NOOPT:
self._opt_dont_and_wont(cmd, opt)
def _opt_echo_on(self, opt):
return self.sock.sendall(telnetlib.IAC + telnetlib.DO + opt)
def _opt_terminal_type(self, opt, terminal_type):
self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.TTYPE
+ self.NEW_ENVIRON_IS + terminal_type
+ telnetlib.IAC + telnetlib.SE)
def _opt_environ_user(self, opt, environ_user):
self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NEW_ENVIRON
+ self.NEW_ENVIRON_IS + self.NEW_ENVIRON_VAR
+ b"USER" + self.NEW_ENVIRON_VALUE + environ_user
+ telnetlib.IAC + telnetlib.SE)
def _opt_window_size(self, opt, window_x, window_y):
self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NAWS
+ struct.pack('!HH', window_x, window_y)
+ telnetlib.IAC + telnetlib.SE)
def _opt_dont_and_wont(self, cmd, opt):
if cmd in (telnetlib.DO, telnetlib.DONT):
self.sock.sendall(telnetlib.IAC + telnetlib.WONT + opt)
elif cmd in (telnetlib.WILL, telnetlib.WONT):
self.sock.sendall(telnetlib.IAC + telnetlib.DONT + opt)
def msg(self, msg, *args):
# Forward telnetlib's debug messages to log
if self._telnetlib_log_level != 'NONE':
logger.write(msg % args, self._telnetlib_log_level)
def _check_terminal_emulation(self, terminal_emulation):
if not terminal_emulation:
return False
if not pyte:
raise RuntimeError("Terminal emulation requires pyte module!\n"
"http://pypi.python.org/pypi/pyte/")
return TerminalEmulator(window_size=self._window_size,
newline=self._newline)
class TerminalEmulator(object):
def __init__(self, window_size=None, newline="\r\n"):
self._rows, self._columns = window_size or (200, 200)
self._newline = newline
self._stream = pyte.Stream()
self._screen = pyte.HistoryScreen(self._rows,
self._columns,
history=100000)
self._stream.attach(self._screen)
self._buffer = ''
self._whitespace_after_last_feed = ''
@property
def current_output(self):
return self._buffer + self._dump_screen()
def _dump_screen(self):
return self._get_history(self._screen) + \
self._get_screen(self._screen) + \
self._whitespace_after_last_feed
def _get_history(self, screen):
if not screen.history.top:
return ''
rows = []
for row in screen.history.top:
# Newer pyte versions store row data in mappings
data = (char.data for _, char in sorted(row.items()))
rows.append(''.join(data).rstrip())
return self._newline.join(rows).rstrip(self._newline) + self._newline
def _get_screen(self, screen):
rows = (row.rstrip() for row in screen.display)
return self._newline.join(rows).rstrip(self._newline)
def feed(self, text):
self._stream.feed(text)
self._whitespace_after_last_feed = text[len(text.rstrip()):]
def read(self):
current_out = self.current_output
self._update_buffer('')
return current_out
def read_until(self, expected):
current_out = self.current_output
exp_index = current_out.find(expected)
if exp_index != -1:
self._update_buffer(current_out[exp_index+len(expected):])
return current_out[:exp_index+len(expected)]
return None
def read_until_regexp(self, regexp_list):
current_out = self.current_output
for rgx in regexp_list:
match = rgx.search(current_out)
if match:
self._update_buffer(current_out[match.end():])
return current_out[:match.end()]
return None
def _update_buffer(self, terminal_buffer):
self._buffer = terminal_buffer
self._whitespace_after_last_feed = ''
self._screen.reset()
class NoMatchError(AssertionError):
ROBOT_SUPPRESS_NAME = True
def __init__(self, expected, timeout, output=None):
self.expected = expected
self.timeout = secs_to_timestr(timeout)
self.output = output
AssertionError.__init__(self, self._get_message())
def _get_message(self):
expected = "'%s'" % self.expected \
if is_string(self.expected) \
else seq2str(self.expected, lastsep=' or ')
msg = "No match found for %s in %s." % (expected, self.timeout)
if self.output is not None:
msg += ' Output:\n%s' % self.output
return msg | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libraries/Telnet.py | 0.79858 | 0.471527 | Telnet.py | pypi |
from __future__ import absolute_import
import os
import re
from fnmatch import fnmatchcase
from random import randint
from string import ascii_lowercase, ascii_uppercase, digits
from robotide.lib.robot.api import logger
from robotide.lib.robot.utils import (is_bytes, is_string, is_truthy, is_unicode, lower,
unic, Utf8Reader, PY3)
from robotide.lib.robot.version import get_version
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 |
"""
# 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 |
"""
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.
"""
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 Utf8Reader(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
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} |
"""
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 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) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libraries/String.py | 0.902341 | 0.483466 | String.py | pypi |
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.
User can press either ``PASS`` or ``FAIL`` button. In the latter case execution
fails and an additional dialog is opened for defining the error message.
``message`` is the instruction shown in the initial dialog and
``default_error`` is the default value shown in the possible error message
dialog.
"""
if not _validate_user_input(PassFailDialog(message)):
msg = get_value_from_user('Give error message:', default_error)
raise AssertionError(msg)
def get_value_from_user(message, default_value='', hidden=False):
"""Pauses test execution and asks user to input a value.
Value typed by the user, or the possible default value, is returned.
Returning an empty value is fine, but pressing ``Cancel`` fails the keyword.
``message`` is the instruction shown in the dialog and ``default_value`` is
the possible default value shown in the input field.
If ``hidden`` is given a true value, the value typed by the user is hidden.
``hidden`` is considered true if it is a non-empty string not equal to
``false``, ``none`` or ``no``, case-insensitively. If it is not a string,
its truth value is got directly using same
[http://docs.python.org/library/stdtypes.html#truth|rules as in Python].
Example:
| ${username} = | Get Value From User | Input user name | default |
| ${password} = | Get Value From User | Input password | hidden=yes |
Considering strings ``false`` and ``no`` to be false is new in RF 2.9
and considering string ``none`` false is new in RF 3.0.3.
"""
return _validate_user_input(InputDialog(message, default_value,
is_truthy(hidden)))
def get_selection_from_user(message, *values):
"""Pauses test execution and asks user to select a value.
The selected value is returned. Pressing ``Cancel`` fails the keyword.
``message`` is the instruction shown in the dialog and ``values`` are
the options given to the user.
Example:
| ${user} = | Get Selection From User | Select user | user1 | user2 | admin |
"""
return _validate_user_input(SelectionDialog(message, values))
def get_selections_from_user(message, *values):
"""Pauses test execution and asks user to select multiple values.
The selected values are returned as a list. Selecting no values is OK
and in that case the returned list is empty. Pressing ``Cancel`` fails
the keyword.
``message`` is the instruction shown in the dialog and ``values`` are
the options given to the user.
Example:
| ${users} = | Get Selections From User | Select users | user1 | user2 | admin |
New in Robot Framework 3.1.
"""
return _validate_user_input(MultipleSelectionDialog(message, values))
def _validate_user_input(dialog):
value = dialog.show()
if value is None:
raise RuntimeError('No value provided by user.')
return value | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libraries/Dialogs.py | 0.843509 | 0.259931 | Dialogs.py | pypi |
import difflib
import re
import time
import token
from tokenize import generate_tokens, untokenize
from robotide.lib.robot.api import logger
from robotide.lib.robot.errors import (ContinueForLoop, DataError, ExecutionFailed,
ExecutionFailures, ExecutionPassed, ExitForLoop,
PassExecution, ReturnFromKeyword)
from robotide.lib.robot.running import Keyword, RUN_KW_REGISTER
from robotide.lib.robot.running.context import EXECUTION_CONTEXTS
from robotide.lib.robot.running.usererrorhandler import UserErrorHandler
from robotide.lib.robot.utils import (DotDict, escape, format_assign_message,
get_error_message, get_time, html_escape, is_falsy, is_integer,
is_string, is_truthy, is_unicode, IRONPYTHON, JYTHON,
Matcher, normalize, NormalizedDict, parse_time, prepr,
plural_or_not as s, PY3, RERAISED_EXCEPTIONS, roundup,
secs_to_timestr, seq2str, split_from_equals, StringIO,
timestr_to_secs, type_name, unic, is_list_like)
from robotide.lib.robot.utils.asserts import assert_equal, assert_not_equal
from robotide.lib.robot.variables import (is_list_var, is_var, DictVariableTableValue,
VariableTableValue, VariableSplitter,
variable_not_found)
from robotide.lib.robot.version import get_version
if JYTHON:
from java.lang import String, Number
# TODO: Clean-up registering run keyword variants in RF 3.1.
# https://github.com/robotframework/robotframework/issues/2190
def run_keyword_variant(resolve):
def decorator(method):
RUN_KW_REGISTER.register_run_keyword('BuiltIn', method.__name__,
resolve, deprecation_warning=False)
return method
return decorator
class _BuiltInBase(object):
@property
def _context(self):
return self._get_context()
def _get_context(self, top=False):
ctx = EXECUTION_CONTEXTS.current if not top else EXECUTION_CONTEXTS.top
if ctx is None:
raise RobotNotRunningError('Cannot access execution context')
return ctx
@property
def _namespace(self):
return self._get_context().namespace
@property
def _variables(self):
return self._namespace.variables
def _matches(self, string, pattern, caseless=False):
# Must use this instead of fnmatch when string may contain newlines.
matcher = Matcher(pattern, caseless=caseless, spaceless=False)
return matcher.match(string)
def _is_true(self, condition):
if is_string(condition):
condition = self.evaluate(condition, modules='os,sys')
return bool(condition)
def _log_types(self, *args):
self._log_types_at_level('DEBUG', *args)
def _log_types_at_level(self, level, *args):
msg = ["Argument types are:"] + [self._get_type(a) for a in args]
self.log('\n'.join(msg), level)
def _get_type(self, arg):
# In IronPython type(u'x') is str. We want to report unicode anyway.
if is_unicode(arg):
return "<type 'unicode'>"
return str(type(arg))
class _Converter(_BuiltInBase):
def convert_to_integer(self, item, base=None):
"""Converts the given item to an integer number.
If the given item is a string, it is by default expected to be an
integer in base 10. There are two ways to convert from other bases:
- Give base explicitly to the keyword as ``base`` argument.
- Prefix the given string with the base so that ``0b`` means binary
(base 2), ``0o`` means octal (base 8), and ``0x`` means hex (base 16).
The prefix is considered only when ``base`` argument is not given and
may itself be prefixed with a plus or minus sign.
The syntax is case-insensitive and possible spaces are ignored.
Examples:
| ${result} = | Convert To Integer | 100 | | # Result is 100 |
| ${result} = | Convert To Integer | FF AA | 16 | # Result is 65450 |
| ${result} = | Convert To Integer | 100 | 8 | # Result is 64 |
| ${result} = | Convert To Integer | -100 | 2 | # Result is -4 |
| ${result} = | Convert To Integer | 0b100 | | # Result is 4 |
| ${result} = | Convert To Integer | -0x100 | | # Result is -256 |
See also `Convert To Number`, `Convert To Binary`, `Convert To Octal`,
`Convert To Hex`, and `Convert To Bytes`.
"""
self._log_types(item)
return self._convert_to_integer(item, base)
def _convert_to_integer(self, orig, base=None):
try:
item = self._handle_java_numbers(orig)
item, base = self._get_base(item, base)
if base:
return int(item, self._convert_to_integer(base))
return int(item)
except:
raise RuntimeError("'%s' cannot be converted to an integer: %s"
% (orig, get_error_message()))
def _handle_java_numbers(self, item):
if not JYTHON:
return item
if isinstance(item, String):
return unic(item)
if isinstance(item, Number):
return item.doubleValue()
return item
def _get_base(self, item, base):
if not is_string(item):
return item, base
item = normalize(item)
if item.startswith(('-', '+')):
sign = item[0]
item = item[1:]
else:
sign = ''
bases = {'0b': 2, '0o': 8, '0x': 16}
if base or not item.startswith(tuple(bases)):
return sign+item, base
return sign+item[2:], bases[item[:2]]
def convert_to_binary(self, item, base=None, prefix=None, length=None):
"""Converts the given item to a binary string.
The ``item``, with an optional ``base``, is first converted to an
integer using `Convert To Integer` internally. After that it
is converted to a binary number (base 2) represented as a
string such as ``1011``.
The returned value can contain an optional ``prefix`` and can be
required to be of minimum ``length`` (excluding the prefix and a
possible minus sign). If the value is initially shorter than
the required length, it is padded with zeros.
Examples:
| ${result} = | Convert To Binary | 10 | | | # Result is 1010 |
| ${result} = | Convert To Binary | F | base=16 | prefix=0b | # Result is 0b1111 |
| ${result} = | Convert To Binary | -2 | prefix=B | length=4 | # Result is -B0010 |
See also `Convert To Integer`, `Convert To Octal` and `Convert To Hex`.
"""
return self._convert_to_bin_oct_hex(item, base, prefix, length, 'b')
def convert_to_octal(self, item, base=None, prefix=None, length=None):
"""Converts the given item to an octal string.
The ``item``, with an optional ``base``, is first converted to an
integer using `Convert To Integer` internally. After that it
is converted to an octal number (base 8) represented as a
string such as ``775``.
The returned value can contain an optional ``prefix`` and can be
required to be of minimum ``length`` (excluding the prefix and a
possible minus sign). If the value is initially shorter than
the required length, it is padded with zeros.
Examples:
| ${result} = | Convert To Octal | 10 | | | # Result is 12 |
| ${result} = | Convert To Octal | -F | base=16 | prefix=0 | # Result is -017 |
| ${result} = | Convert To Octal | 16 | prefix=oct | length=4 | # Result is oct0020 |
See also `Convert To Integer`, `Convert To Binary` and `Convert To Hex`.
"""
return self._convert_to_bin_oct_hex(item, base, prefix, length, 'o')
def convert_to_hex(self, item, base=None, prefix=None, length=None,
lowercase=False):
"""Converts the given item to a hexadecimal string.
The ``item``, with an optional ``base``, is first converted to an
integer using `Convert To Integer` internally. After that it
is converted to a hexadecimal number (base 16) represented as
a string such as ``FF0A``.
The returned value can contain an optional ``prefix`` and can be
required to be of minimum ``length`` (excluding the prefix and a
possible minus sign). If the value is initially shorter than
the required length, it is padded with zeros.
By default the value is returned as an upper case string, but the
``lowercase`` argument a true value (see `Boolean arguments`) turns
the value (but not the given prefix) to lower case.
Examples:
| ${result} = | Convert To Hex | 255 | | | # Result is FF |
| ${result} = | Convert To Hex | -10 | prefix=0x | length=2 | # Result is -0x0A |
| ${result} = | Convert To Hex | 255 | prefix=X | lowercase=yes | # Result is Xff |
See also `Convert To Integer`, `Convert To Binary` and `Convert To Octal`.
"""
spec = 'x' if is_truthy(lowercase) else 'X'
return self._convert_to_bin_oct_hex(item, base, prefix, length, spec)
def _convert_to_bin_oct_hex(self, item, base, prefix, length, format_spec):
self._log_types(item)
ret = format(self._convert_to_integer(item, base), format_spec)
prefix = prefix or ''
if ret[0] == '-':
prefix = '-' + prefix
ret = ret[1:]
if length:
ret = ret.rjust(self._convert_to_integer(length), '0')
return prefix + ret
def convert_to_number(self, item, precision=None):
"""Converts the given item to a floating point number.
If the optional ``precision`` is positive or zero, the returned number
is rounded to that number of decimal digits. Negative precision means
that the number is rounded to the closest multiple of 10 to the power
of the absolute precision. If a number is equally close to a certain
precision, it is always rounded away from zero.
Examples:
| ${result} = | Convert To Number | 42.512 | | # Result is 42.512 |
| ${result} = | Convert To Number | 42.512 | 1 | # Result is 42.5 |
| ${result} = | Convert To Number | 42.512 | 0 | # Result is 43.0 |
| ${result} = | Convert To Number | 42.512 | -1 | # Result is 40.0 |
Notice that machines generally cannot store floating point numbers
accurately. This may cause surprises with these numbers in general
and also when they are rounded. For more information see, for example,
these resources:
- http://docs.python.org/tutorial/floatingpoint.html
- http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition
If you want to avoid possible problems with floating point numbers,
you can implement custom keywords using Python's
[http://docs.python.org/library/decimal.html|decimal] or
[http://docs.python.org/library/fractions.html|fractions] modules.
If you need an integer number, use `Convert To Integer` instead.
"""
self._log_types(item)
return self._convert_to_number(item, precision)
def _convert_to_number(self, item, precision=None):
number = self._convert_to_number_without_precision(item)
if precision is not None:
number = roundup(number, self._convert_to_integer(precision),
return_type=float)
return number
def _convert_to_number_without_precision(self, item):
try:
if JYTHON:
item = self._handle_java_numbers(item)
return float(item)
except:
error = get_error_message()
try:
return float(self._convert_to_integer(item))
except RuntimeError:
raise RuntimeError("'%s' cannot be converted to a floating "
"point number: %s" % (item, error))
def convert_to_string(self, item):
"""Converts the given item to a Unicode string.
Strings are also [http://www.macchiato.com/unicode/nfc-faq|
NFC normalized].
Use `Encode String To Bytes` and `Decode Bytes To String` keywords
in ``String`` library if you need to convert between Unicode and byte
strings using different encodings. Use `Convert To Bytes` if you just
want to create byte strings.
"""
self._log_types(item)
return self._convert_to_string(item)
def _convert_to_string(self, item):
return unic(item)
def convert_to_boolean(self, item):
"""Converts the given item to Boolean true or false.
Handles strings ``True`` and ``False`` (case-insensitive) as expected,
otherwise returns item's
[http://docs.python.org/library/stdtypes.html#truth|truth value]
using Python's ``bool()`` method.
"""
self._log_types(item)
if is_string(item):
if item.upper() == 'TRUE':
return True
if item.upper() == 'FALSE':
return False
return bool(item)
def convert_to_bytes(self, input, input_type='text'):
u"""Converts the given ``input`` to bytes according to the ``input_type``.
Valid input types are listed below:
- ``text:`` Converts text to bytes character by character. All
characters with ordinal below 256 can be used and are converted to
bytes with same values. Many characters are easiest to represent
using escapes like ``\\x00`` or ``\\xff``. Supports both Unicode
strings and bytes.
- ``int:`` Converts integers separated by spaces to bytes. Similarly as
with `Convert To Integer`, it is possible to use binary, octal, or
hex values by prefixing the values with ``0b``, ``0o``, or ``0x``,
respectively.
- ``hex:`` Converts hexadecimal values to bytes. Single byte is always
two characters long (e.g. ``01`` or ``FF``). Spaces are ignored and
can be used freely as a visual separator.
- ``bin:`` Converts binary values to bytes. Single byte is always eight
characters long (e.g. ``00001010``). Spaces are ignored and can be
used freely as a visual separator.
In addition to giving the input as a string, it is possible to use
lists or other iterables containing individual characters or numbers.
In that case numbers do not need to be padded to certain length and
they cannot contain extra spaces.
Examples (last column shows returned bytes):
| ${bytes} = | Convert To Bytes | hyv\xe4 | | # hyv\\xe4 |
| ${bytes} = | Convert To Bytes | \\xff\\x07 | | # \\xff\\x07 |
| ${bytes} = | Convert To Bytes | 82 70 | int | # RF |
| ${bytes} = | Convert To Bytes | 0b10 0x10 | int | # \\x02\\x10 |
| ${bytes} = | Convert To Bytes | ff 00 07 | hex | # \\xff\\x00\\x07 |
| ${bytes} = | Convert To Bytes | 5246212121 | hex | # RF!!! |
| ${bytes} = | Convert To Bytes | 0000 1000 | bin | # \\x08 |
| ${input} = | Create List | 1 | 2 | 12 |
| ${bytes} = | Convert To Bytes | ${input} | int | # \\x01\\x02\\x0c |
| ${bytes} = | Convert To Bytes | ${input} | hex | # \\x01\\x02\\x12 |
Use `Encode String To Bytes` in ``String`` library if you need to
convert text to bytes using a certain encoding.
"""
try:
try:
ordinals = getattr(self, '_get_ordinals_from_%s' % input_type)
except AttributeError:
raise RuntimeError("Invalid input type '%s'." % input_type)
return bytes(bytearray(o for o in ordinals(input)))
except:
raise RuntimeError("Creating bytes failed: %s" % get_error_message())
def _get_ordinals_from_text(self, input):
# https://github.com/IronLanguages/main/issues/1237
if IRONPYTHON and isinstance(input, bytearray):
input = bytes(input)
for char in input:
ordinal = char if is_integer(char) else ord(char)
yield self._test_ordinal(ordinal, char, 'Character')
def _test_ordinal(self, ordinal, original, type):
if 0 <= ordinal <= 255:
return ordinal
raise RuntimeError("%s '%s' cannot be represented as a byte."
% (type, original))
def _get_ordinals_from_int(self, input):
if is_string(input):
input = input.split()
elif is_integer(input):
input = [input]
for integer in input:
ordinal = self._convert_to_integer(integer)
yield self._test_ordinal(ordinal, integer, 'Integer')
def _get_ordinals_from_hex(self, input):
for token in self._input_to_tokens(input, length=2):
ordinal = self._convert_to_integer(token, base=16)
yield self._test_ordinal(ordinal, token, 'Hex value')
def _get_ordinals_from_bin(self, input):
for token in self._input_to_tokens(input, length=8):
ordinal = self._convert_to_integer(token, base=2)
yield self._test_ordinal(ordinal, token, 'Binary value')
def _input_to_tokens(self, input, length):
if not is_string(input):
return input
input = ''.join(input.split())
if len(input) % length != 0:
raise RuntimeError('Expected input to be multiple of %d.' % length)
return (input[i:i+length] for i in range(0, len(input), length))
def create_list(self, *items):
"""Returns a list containing given items.
The returned list can be assigned both to ``${scalar}`` and ``@{list}``
variables.
Examples:
| @{list} = | Create List | a | b | c |
| ${scalar} = | Create List | a | b | c |
| ${ints} = | Create List | ${1} | ${2} | ${3} |
"""
return list(items)
@run_keyword_variant(resolve=0)
def create_dictionary(self, *items):
"""Creates and returns a dictionary based on the given ``items``.
Items are typically given using the ``key=value`` syntax same way as
``&{dictionary}`` variables are created in the Variable table. Both
keys and values can contain variables, and possible equal sign in key
can be escaped with a backslash like ``escaped\\=key=value``. It is
also possible to get items from existing dictionaries by simply using
them like ``&{dict}``.
Alternatively items can be specified so that keys and values are given
separately. This and the ``key=value`` syntax can even be combined,
but separately given items must be first. If same key is used multiple
times, the last value has precedence.
The returned dictionary is ordered, and values with strings as keys
can also be accessed using a convenient dot-access syntax like
``${dict.key}``. Technically the returned dictionary is Robot
Framework's own ``DotDict`` instance. If there is a need, it can be
converted into a regular Python ``dict`` instance by using the
`Convert To Dictionary` keyword from the Collections library.
Examples:
| &{dict} = | Create Dictionary | key=value | foo=bar | | | # key=value syntax |
| Should Be True | ${dict} == {'key': 'value', 'foo': 'bar'} |
| &{dict2} = | Create Dictionary | key | value | foo | bar | # separate key and value |
| Should Be Equal | ${dict} | ${dict2} |
| &{dict} = | Create Dictionary | ${1}=${2} | &{dict} | foo=new | | # using variables |
| Should Be True | ${dict} == {1: 2, 'key': 'value', 'foo': 'new'} |
| Should Be Equal | ${dict.key} | value | | | | # dot-access |
This keyword was changed in Robot Framework 2.9 in many ways:
- Moved from the Collections library to BuiltIn.
- Support also non-string keys in ``key=value`` syntax.
- Returned dictionary is ordered and dot-accessible (i.e. ``DotDict``).
- Old syntax to give keys and values separately was deprecated, but
deprecation was later removed in RF 3.0.1.
"""
separate, combined = self._split_dict_items(items)
result = DotDict(self._format_separate_dict_items(separate))
combined = DictVariableTableValue(combined).resolve(self._variables)
result.update(combined)
return result
def _split_dict_items(self, items):
separate = []
for item in items:
name, value = split_from_equals(item)
if value is not None or VariableSplitter(item).is_dict_variable():
break
separate.append(item)
return separate, items[len(separate):]
def _format_separate_dict_items(self, separate):
separate = self._variables.replace_list(separate)
if len(separate) % 2 != 0:
raise DataError('Expected even number of keys and values, got %d.'
% len(separate))
return [separate[i:i+2] for i in range(0, len(separate), 2)]
class _Verify(_BuiltInBase):
def _set_and_remove_tags(self, tags):
set_tags = [tag for tag in tags if not tag.startswith('-')]
remove_tags = [tag[1:] for tag in tags if tag.startswith('-')]
if remove_tags:
self.remove_tags(*remove_tags)
if set_tags:
self.set_tags(*set_tags)
def fail(self, msg=None, *tags):
"""Fails the test with the given message and optionally alters its tags.
The error message is specified using the ``msg`` argument.
It is possible to use HTML in the given error message, similarly
as with any other keyword accepting an error message, by prefixing
the error with ``*HTML*``.
It is possible to modify tags of the current test case by passing tags
after the message. Tags starting with a hyphen (e.g. ``-regression``)
are removed and others added. Tags are modified using `Set Tags` and
`Remove Tags` internally, and the semantics setting and removing them
are the same as with these keywords.
Examples:
| Fail | Test not ready | | | # Fails with the given message. |
| Fail | *HTML*<b>Test not ready</b> | | | # Fails using HTML in the message. |
| Fail | Test not ready | not-ready | | # Fails and adds 'not-ready' tag. |
| Fail | OS not supported | -regression | | # Removes tag 'regression'. |
| Fail | My message | tag | -t* | # Removes all tags starting with 't' except the newly added 'tag'. |
See `Fatal Error` if you need to stop the whole test execution.
"""
self._set_and_remove_tags(tags)
raise AssertionError(msg) if msg else AssertionError()
def fatal_error(self, msg=None):
"""Stops the whole test execution.
The test or suite where this keyword is used fails with the provided
message, and subsequent tests fail with a canned message.
Possible teardowns will nevertheless be executed.
See `Fail` if you only want to stop one test case unconditionally.
"""
error = AssertionError(msg) if msg else AssertionError()
error.ROBOT_EXIT_ON_FAILURE = True
raise error
def should_not_be_true(self, condition, msg=None):
"""Fails if the given condition is true.
See `Should Be True` for details about how ``condition`` is evaluated
and how ``msg`` can be used to override the default error message.
"""
if self._is_true(condition):
raise AssertionError(msg or "'%s' should not be true." % condition)
def should_be_true(self, condition, msg=None):
"""Fails if the given condition is not true.
If ``condition`` is a string (e.g. ``${rc} < 10``), it is evaluated as
a Python expression as explained in `Evaluating expressions` and the
keyword status is decided based on the result. If a non-string item is
given, the status is got directly from its
[http://docs.python.org/library/stdtypes.html#truth|truth value].
The default error message (``<condition> should be true``) is not very
informative, but it can be overridden with the ``msg`` argument.
Examples:
| Should Be True | ${rc} < 10 |
| Should Be True | '${status}' == 'PASS' | # Strings must be quoted |
| Should Be True | ${number} | # Passes if ${number} is not zero |
| Should Be True | ${list} | # Passes if ${list} is not empty |
Variables used like ``${variable}``, as in the examples above, are
replaced in the expression before evaluation. Variables are also
available in the evaluation namespace and can be accessed using special
syntax ``$variable``. This is a new feature in Robot Framework 2.9
and it is explained more thoroughly in `Evaluating expressions`.
Examples:
| Should Be True | $rc < 10 |
| Should Be True | $status == 'PASS' | # Expected string must be quoted |
`Should Be True` automatically imports Python's
[http://docs.python.org/library/os.html|os] and
[http://docs.python.org/library/sys.html|sys] modules that contain
several useful attributes:
| Should Be True | os.linesep == '\\n' | # Unixy |
| Should Be True | os.linesep == '\\r\\n' | # Windows |
| Should Be True | sys.platform == 'darwin' | # OS X |
| Should Be True | sys.platform.startswith('java') | # Jython |
"""
if not self._is_true(condition):
raise AssertionError(msg or "'%s' should be true." % condition)
def should_be_equal(self, first, second, msg=None, values=True,
ignore_case=False, formatter='str'):
"""Fails if the given objects are unequal.
Optional ``msg``, ``values`` and ``formatter`` arguments specify how
to construct the error message if this keyword fails:
- If ``msg`` is not given, the error message is ``<first> != <second>``.
- If ``msg`` is given and ``values`` gets a true value (default),
the error message is ``<msg>: <first> != <second>``.
- If ``msg`` is given and ``values`` gets a false value (see
`Boolean arguments`), the error message is simply ``<msg>``.
- ``formatter`` controls how to format the values. Possible values are
``str`` (default), ``repr`` and ``ascii``, and they work similarly
as Python built-in functions with same names. See `String
representations` for more details.
If ``ignore_case`` is given a true value (see `Boolean arguments`) and
both arguments are strings, comparison is done case-insensitively.
If both arguments are multiline strings, this keyword uses
`multiline string comparison`.
Examples:
| Should Be Equal | ${x} | expected |
| Should Be Equal | ${x} | expected | Custom error message |
| Should Be Equal | ${x} | expected | Custom message | values=False |
| Should Be Equal | ${x} | expected | ignore_case=True | formatter=repr |
``ignore_case`` and ``formatter`` are new features in Robot Framework
3.0.1 and 3.1.2, respectively.
"""
self._log_types_at_info_if_different(first, second)
if is_truthy(ignore_case) and is_string(first) and is_string(second):
first = first.lower()
second = second.lower()
self._should_be_equal(first, second, msg, values, formatter)
def _should_be_equal(self, first, second, msg, values, formatter='str'):
include_values = self._include_values(values)
formatter = self._get_formatter(formatter)
if first == second:
return
if include_values and is_string(first) and is_string(second):
self._raise_multi_diff(first, second, formatter)
assert_equal(first, second, msg, include_values, formatter)
def _log_types_at_info_if_different(self, first, second):
level = 'DEBUG' if type(first) == type(second) else 'INFO'
self._log_types_at_level(level, first, second)
def _raise_multi_diff(self, first, second, formatter):
first_lines = first.splitlines(True) # keepends
second_lines = second.splitlines(True)
if len(first_lines) < 3 or len(second_lines) < 3:
return
self.log("%s\n\n!=\n\n%s" % (first.rstrip(), second.rstrip()))
diffs = list(difflib.unified_diff(first_lines, second_lines,
fromfile='first', tofile='second',
lineterm=''))
diffs[3:] = [item[0] + formatter(item[1:]).rstrip()
for item in diffs[3:]]
raise AssertionError('Multiline strings are different:\n' +
'\n'.join(diffs))
def _include_values(self, values):
return is_truthy(values) and str(values).upper() != 'NO VALUES'
def should_not_be_equal(self, first, second, msg=None, values=True,
ignore_case=False):
"""Fails if the given objects are equal.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``.
If ``ignore_case`` is given a true value (see `Boolean arguments`) and
both arguments are strings, comparison is done case-insensitively.
New option in Robot Framework 3.0.1.
"""
self._log_types_at_info_if_different(first, second)
if is_truthy(ignore_case) and is_string(first) and is_string(second):
first = first.lower()
second = second.lower()
self._should_not_be_equal(first, second, msg, values)
def _should_not_be_equal(self, first, second, msg, values):
assert_not_equal(first, second, msg, self._include_values(values))
def should_not_be_equal_as_integers(self, first, second, msg=None,
values=True, base=None):
"""Fails if objects are equal after converting them to integers.
See `Convert To Integer` for information how to convert integers from
other bases than 10 using ``base`` argument or ``0b/0o/0x`` prefixes.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``.
See `Should Be Equal As Integers` for some usage examples.
"""
self._log_types_at_info_if_different(first, second)
self._should_not_be_equal(self._convert_to_integer(first, base),
self._convert_to_integer(second, base),
msg, values)
def should_be_equal_as_integers(self, first, second, msg=None, values=True,
base=None):
"""Fails if objects are unequal after converting them to integers.
See `Convert To Integer` for information how to convert integers from
other bases than 10 using ``base`` argument or ``0b/0o/0x`` prefixes.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``.
Examples:
| Should Be Equal As Integers | 42 | ${42} | Error message |
| Should Be Equal As Integers | ABCD | abcd | base=16 |
| Should Be Equal As Integers | 0b1011 | 11 |
"""
self._log_types_at_info_if_different(first, second)
self._should_be_equal(self._convert_to_integer(first, base),
self._convert_to_integer(second, base),
msg, values)
def should_not_be_equal_as_numbers(self, first, second, msg=None,
values=True, precision=6):
"""Fails if objects are equal after converting them to real numbers.
The conversion is done with `Convert To Number` keyword using the
given ``precision``.
See `Should Be Equal As Numbers` for examples on how to use
``precision`` and why it does not always work as expected. See also
`Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``.
"""
self._log_types_at_info_if_different(first, second)
first = self._convert_to_number(first, precision)
second = self._convert_to_number(second, precision)
self._should_not_be_equal(first, second, msg, values)
def should_be_equal_as_numbers(self, first, second, msg=None, values=True,
precision=6):
"""Fails if objects are unequal after converting them to real numbers.
The conversion is done with `Convert To Number` keyword using the
given ``precision``.
Examples:
| Should Be Equal As Numbers | ${x} | 1.1 | | # Passes if ${x} is 1.1 |
| Should Be Equal As Numbers | 1.123 | 1.1 | precision=1 | # Passes |
| Should Be Equal As Numbers | 1.123 | 1.4 | precision=0 | # Passes |
| Should Be Equal As Numbers | 112.3 | 75 | precision=-2 | # Passes |
As discussed in the documentation of `Convert To Number`, machines
generally cannot store floating point numbers accurately. Because of
this limitation, comparing floats for equality is problematic and
a correct approach to use depends on the context. This keyword uses
a very naive approach of rounding the numbers before comparing them,
which is both prone to rounding errors and does not work very well if
numbers are really big or small. For more information about comparing
floats, and ideas on how to implement your own context specific
comparison algorithm, see
http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/.
If you want to avoid possible problems with floating point numbers,
you can implement custom keywords using Python's
[http://docs.python.org/library/decimal.html|decimal] or
[http://docs.python.org/library/fractions.html|fractions] modules.
See `Should Not Be Equal As Numbers` for a negative version of this
keyword and `Should Be Equal` for an explanation on how to override
the default error message with ``msg`` and ``values``.
"""
self._log_types_at_info_if_different(first, second)
first = self._convert_to_number(first, precision)
second = self._convert_to_number(second, precision)
self._should_be_equal(first, second, msg, values)
def should_not_be_equal_as_strings(self, first, second, msg=None,
values=True, ignore_case=False):
"""Fails if objects are equal after converting them to strings.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``.
If ``ignore_case`` is given a true value (see `Boolean arguments`),
comparison is done case-insensitively.
Strings are always [http://www.macchiato.com/unicode/nfc-faq|
NFC normalized].
``ignore_case`` is a new feature in Robot Framework 3.0.1.
"""
self._log_types_at_info_if_different(first, second)
first = self._convert_to_string(first)
second = self._convert_to_string(second)
if is_truthy(ignore_case):
first = first.lower()
second = second.lower()
self._should_not_be_equal(first, second, msg, values)
def should_be_equal_as_strings(self, first, second, msg=None, values=True,
ignore_case=False, formatter='str'):
"""Fails if objects are unequal after converting them to strings.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg``, ``values`` and ``formatter``.
If ``ignore_case`` is given a true value (see `Boolean arguments`),
comparison is done case-insensitively. If both arguments are
multiline strings, this keyword uses `multiline string comparison`.
Strings are always [http://www.macchiato.com/unicode/nfc-faq|
NFC normalized].
``ignore_case`` and ``formatter`` are new features in Robot Framework
3.0.1 and 3.1.2, respectively.
"""
self._log_types_at_info_if_different(first, second)
first = self._convert_to_string(first)
second = self._convert_to_string(second)
if is_truthy(ignore_case):
first = first.lower()
second = second.lower()
self._should_be_equal(first, second, msg, values, formatter)
def should_not_start_with(self, str1, str2, msg=None, values=True,
ignore_case=False):
"""Fails if the string ``str1`` starts with the string ``str2``.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``, as well as for semantics
of the ``ignore_case`` option.
"""
if is_truthy(ignore_case):
str1 = str1.lower()
str2 = str2.lower()
if str1.startswith(str2):
raise AssertionError(self._get_string_msg(str1, str2, msg, values,
'starts with'))
def should_start_with(self, str1, str2, msg=None, values=True,
ignore_case=False):
"""Fails if the string ``str1`` does not start with the string ``str2``.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``, as well as for semantics
of the ``ignore_case`` option.
"""
if is_truthy(ignore_case):
str1 = str1.lower()
str2 = str2.lower()
if not str1.startswith(str2):
raise AssertionError(self._get_string_msg(str1, str2, msg, values,
'does not start with'))
def should_not_end_with(self, str1, str2, msg=None, values=True,
ignore_case=False):
"""Fails if the string ``str1`` ends with the string ``str2``.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``, as well as for semantics
of the ``ignore_case`` option.
"""
if is_truthy(ignore_case):
str1 = str1.lower()
str2 = str2.lower()
if str1.endswith(str2):
raise AssertionError(self._get_string_msg(str1, str2, msg, values,
'ends with'))
def should_end_with(self, str1, str2, msg=None, values=True,
ignore_case=False):
"""Fails if the string ``str1`` does not end with the string ``str2``.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``, as well as for semantics
of the ``ignore_case`` option.
"""
if is_truthy(ignore_case):
str1 = str1.lower()
str2 = str2.lower()
if not str1.endswith(str2):
raise AssertionError(self._get_string_msg(str1, str2, msg, values,
'does not end with'))
def should_not_contain(self, container, item, msg=None, values=True,
ignore_case=False):
"""Fails if ``container`` contains ``item`` one or more times.
Works with strings, lists, and anything that supports Python's ``in``
operator.
See `Should Be Equal` for an explanation on how to override the default
error message with arguments ``msg`` and ``values``. ``ignore_case``
has exactly the same semantics as with `Should Contain`.
Examples:
| Should Not Contain | ${some list} | value |
| Should Not Contain | ${output} | FAILED | ignore_case=True |
"""
# TODO: It is inconsistent that errors show original case in 'container'
# 'item' is in lower case. Should rather show original case everywhere
# and add separate '(case-insensitive)' not to the error message.
# This same logic should be used with all keywords supporting
# case-insensitive comparisons.
orig_container = container
if is_truthy(ignore_case) and is_string(item):
item = item.lower()
if is_string(container):
container = container.lower()
elif is_list_like(container):
container = set(x.lower() if is_string(x) else x for x in container)
if item in container:
raise AssertionError(self._get_string_msg(orig_container, item, msg,
values, 'contains'))
def should_contain(self, container, item, msg=None, values=True,
ignore_case=False):
"""Fails if ``container`` does not contain ``item`` one or more times.
Works with strings, lists, and anything that supports Python's ``in``
operator.
See `Should Be Equal` for an explanation on how to override the default
error message with arguments ``msg`` and ``values``.
If ``ignore_case`` is given a true value (see `Boolean arguments`) and
compared items are strings, it indicates that comparison should be
case-insensitive. If the ``container`` is a list-like object, string
items in it are compared case-insensitively. New option in Robot
Framework 3.0.1.
Examples:
| Should Contain | ${output} | PASS |
| Should Contain | ${some list} | value | msg=Failure! | values=False |
| Should Contain | ${some list} | value | ignore_case=True |
"""
orig_container = container
if is_truthy(ignore_case) and is_string(item):
item = item.lower()
if is_string(container):
container = container.lower()
elif is_list_like(container):
container = set(x.lower() if is_string(x) else x for x in container)
if item not in container:
raise AssertionError(self._get_string_msg(orig_container, item, msg,
values, 'does not contain'))
def should_contain_any(self, container, *items, **configuration):
"""Fails if ``container`` does not contain any of the ``*items``.
Works with strings, lists, and anything that supports Python's ``in``
operator.
Supports additional configuration parameters ``msg``, ``values``
and ``ignore_case``, which have exactly the same semantics as arguments
with same names have with `Should Contain`. These arguments must
always be given using ``name=value`` syntax after all ``items``.
Note that possible equal signs in ``items`` must be escaped with
a backslash (e.g. ``foo\\=bar``) to avoid them to be passed in
as ``**configuration``.
Examples:
| Should Contain Any | ${string} | substring 1 | substring 2 |
| Should Contain Any | ${list} | item 1 | item 2 | item 3 |
| Should Contain Any | ${list} | item 1 | item 2 | item 3 | ignore_case=True |
| Should Contain Any | ${list} | @{items} | msg=Custom message | values=False |
New in Robot Framework 3.0.1.
"""
msg = configuration.pop('msg', None)
values = configuration.pop('values', True)
ignore_case = configuration.pop('ignore_case', False)
if configuration:
raise RuntimeError("Unsupported configuration parameter%s: %s."
% (s(configuration),
seq2str(sorted(configuration))))
if not items:
raise RuntimeError('One or more items required.')
orig_container = container
if is_truthy(ignore_case):
items = [x.lower() if is_string(x) else x for x in items]
if is_string(container):
container = container.lower()
elif is_list_like(container):
container = set(x.lower() if is_string(x) else x for x in container)
if not any(item in container for item in items):
msg = self._get_string_msg(orig_container,
seq2str(items, lastsep=' or '),
msg, values,
'does not contain any of',
quote_item2=False)
raise AssertionError(msg)
def should_not_contain_any(self, container, *items, **configuration):
"""Fails if ``container`` contains one or more of the ``*items``.
Works with strings, lists, and anything that supports Python's ``in``
operator.
Supports additional configuration parameters ``msg``, ``values``
and ``ignore_case``, which have exactly the same semantics as arguments
with same names have with `Should Contain`. These arguments must
always be given using ``name=value`` syntax after all ``items``.
Note that possible equal signs in ``items`` must be escaped with
a backslash (e.g. ``foo\\=bar``) to avoid them to be passed in
as ``**configuration``.
Examples:
| Should Not Contain Any | ${string} | substring 1 | substring 2 |
| Should Not Contain Any | ${list} | item 1 | item 2 | item 3 |
| Should Not Contain Any | ${list} | item 1 | item 2 | item 3 | ignore_case=True |
| Should Not Contain Any | ${list} | @{items} | msg=Custom message | values=False |
New in Robot Framework 3.0.1.
"""
msg = configuration.pop('msg', None)
values = configuration.pop('values', True)
ignore_case = configuration.pop('ignore_case', False)
if configuration:
raise RuntimeError("Unsupported configuration parameter%s: %s."
% (s(configuration),
seq2str(sorted(configuration))))
if not items:
raise RuntimeError('One or more items required.')
orig_container = container
if is_truthy(ignore_case):
items = [x.lower() if is_string(x) else x for x in items]
if is_string(container):
container = container.lower()
elif is_list_like(container):
container = set(x.lower() if is_string(x) else x for x in container)
if any(item in container for item in items):
msg = self._get_string_msg(orig_container,
seq2str(items, lastsep=' or '),
msg, values,
'contains one or more of',
quote_item2=False)
raise AssertionError(msg)
def should_contain_x_times(self, item1, item2, count, msg=None,
ignore_case=False):
"""Fails if ``item1`` does not contain ``item2`` ``count`` times.
Works with strings, lists and all objects that `Get Count` works
with. The default error message can be overridden with ``msg`` and
the actual count is always logged.
If ``ignore_case`` is given a true value (see `Boolean arguments`) and
compared items are strings, it indicates that comparison should be
case-insensitive. If the ``item1`` is a list-like object, string
items in it are compared case-insensitively. New option in Robot
Framework 3.0.1.
Examples:
| Should Contain X Times | ${output} | hello | 2 |
| Should Contain X Times | ${some list} | value | 3 | ignore_case=True |
"""
# TODO: Rename 'item1' and 'item2' to 'container' and 'item' in RF 3.1.
# Other 'contain' keywords use these names. And 'Get Count' should too.
# Cannot be done in minor release due to backwards compatibility.
# Remember to update it also in the docstring!!
count = self._convert_to_integer(count)
orig_item1 = item1
if is_truthy(ignore_case) and is_string(item2):
item2 = item2.lower()
if is_string(item1):
item1 = item1.lower()
elif is_list_like(item1):
item1 = [x.lower() if is_string(x) else x for x in item1]
x = self.get_count(item1, item2)
if not msg:
msg = "'%s' contains '%s' %d time%s, not %d time%s." \
% (unic(orig_item1), unic(item2), x, s(x), count, s(count))
self.should_be_equal_as_integers(x, count, msg, values=False)
def get_count(self, item1, item2):
"""Returns and logs how many times ``item2`` is found from ``item1``.
This keyword works with Python strings and lists and all objects
that either have ``count`` method or can be converted to Python lists.
Example:
| ${count} = | Get Count | ${some item} | interesting value |
| Should Be True | 5 < ${count} < 10 |
"""
if not hasattr(item1, 'count'):
try:
item1 = list(item1)
except:
raise RuntimeError("Converting '%s' to list failed: %s"
% (item1, get_error_message()))
count = item1.count(item2)
self.log('Item found from the first item %d time%s' % (count, s(count)))
return count
def should_not_match(self, string, pattern, msg=None, values=True,
ignore_case=False):
"""Fails if the given ``string`` matches the given ``pattern``.
Pattern matching is similar as matching files in a shell with
``*``, ``?`` and ``[chars]`` acting as wildcards. See the
`Glob patterns` section for more information.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``, as well as for semantics
of the ``ignore_case`` option.
"""
if self._matches(string, pattern, caseless=is_truthy(ignore_case)):
raise AssertionError(self._get_string_msg(string, pattern, msg,
values, 'matches'))
def should_match(self, string, pattern, msg=None, values=True,
ignore_case=False):
"""Fails if the given ``string`` does not match the given ``pattern``.
Pattern matching is similar as matching files in a shell with
``*``, ``?`` and ``[chars]`` acting as wildcards. See the
`Glob patterns` section for more information.
See `Should Be Equal` for an explanation on how to override the default
error message with ``msg`` and ``values``, as well as for semantics
of the ``ignore_case`` option.
"""
if not self._matches(string, pattern, caseless=is_truthy(ignore_case)):
raise AssertionError(self._get_string_msg(string, pattern, msg,
values, 'does not match'))
def should_match_regexp(self, string, pattern, msg=None, values=True):
"""Fails if ``string`` does not match ``pattern`` as a regular expression.
See the `Regular expressions` section for more information about
regular expressions and how to use then in Robot Framework test data.
Notice that the given pattern does not need to match the whole string.
For example, the pattern ``ello`` matches the string ``Hello world!``.
If a full match is needed, the ``^`` and ``$`` characters can be used
to denote the beginning and end of the string, respectively.
For example, ``^ello$`` only matches the exact string ``ello``.
Possible flags altering how the expression is parsed (e.g.
``re.IGNORECASE``, ``re.MULTILINE``) must be embedded to the
pattern like ``(?im)pattern``. The most useful flags are ``i``
(case-insensitive), ``m`` (multiline mode), ``s`` (dotall mode)
and ``x`` (verbose).
If this keyword passes, it returns the portion of the string that
matched the pattern. Additionally, the possible captured groups are
returned.
See the `Should Be Equal` keyword for an explanation on how to override
the default error message with the ``msg`` and ``values`` arguments.
Examples:
| Should Match Regexp | ${output} | \\\\d{6} | # Output contains six numbers |
| Should Match Regexp | ${output} | ^\\\\d{6}$ | # Six numbers and nothing more |
| ${ret} = | Should Match Regexp | Foo: 42 | (?i)foo: \\\\d+ |
| ${match} | ${group1} | ${group2} = |
| ... | Should Match Regexp | Bar: 43 | (Foo|Bar): (\\\\d+) |
=>
| ${ret} = 'Foo: 42'
| ${match} = 'Bar: 43'
| ${group1} = 'Bar'
| ${group2} = '43'
"""
res = re.search(pattern, string)
if res is None:
raise AssertionError(self._get_string_msg(string, pattern, msg,
values, 'does not match'))
match = res.group(0)
groups = res.groups()
if groups:
return [match] + list(groups)
return match
def should_not_match_regexp(self, string, pattern, msg=None, values=True):
"""Fails if ``string`` matches ``pattern`` as a regular expression.
See `Should Match Regexp` for more information about arguments.
"""
if re.search(pattern, string) is not None:
raise AssertionError(self._get_string_msg(string, pattern, msg,
values, 'matches'))
def get_length(self, item):
"""Returns and logs the length of the given item as an integer.
The item can be anything that has a length, for example, a string,
a list, or a mapping. The keyword first tries to get the length with
the Python function ``len``, which calls the item's ``__len__`` method
internally. If that fails, the keyword tries to call the item's
possible ``length`` and ``size`` methods directly. The final attempt is
trying to get the value of the item's ``length`` attribute. If all
these attempts are unsuccessful, the keyword fails.
Examples:
| ${length} = | Get Length | Hello, world! | |
| Should Be Equal As Integers | ${length} | 13 |
| @{list} = | Create List | Hello, | world! |
| ${length} = | Get Length | ${list} | |
| Should Be Equal As Integers | ${length} | 2 |
See also `Length Should Be`, `Should Be Empty` and `Should Not Be
Empty`.
"""
length = self._get_length(item)
self.log('Length is %d' % length)
return length
def _get_length(self, item):
try:
return len(item)
except RERAISED_EXCEPTIONS:
raise
except:
try:
return item.length()
except RERAISED_EXCEPTIONS:
raise
except:
try:
return item.size()
except RERAISED_EXCEPTIONS:
raise
except:
try:
return item.length
except RERAISED_EXCEPTIONS:
raise
except:
raise RuntimeError("Could not get length of '%s'." % item)
def length_should_be(self, item, length, msg=None):
"""Verifies that the length of the given item is correct.
The length of the item is got using the `Get Length` keyword. The
default error message can be overridden with the ``msg`` argument.
"""
length = self._convert_to_integer(length)
actual = self.get_length(item)
if actual != length:
raise AssertionError(msg or "Length of '%s' should be %d but is %d."
% (item, length, actual))
def should_be_empty(self, item, msg=None):
"""Verifies that the given item is empty.
The length of the item is got using the `Get Length` keyword. The
default error message can be overridden with the ``msg`` argument.
"""
if self.get_length(item) > 0:
raise AssertionError(msg or "'%s' should be empty." % item)
def should_not_be_empty(self, item, msg=None):
"""Verifies that the given item is not empty.
The length of the item is got using the `Get Length` keyword. The
default error message can be overridden with the ``msg`` argument.
"""
if self.get_length(item) == 0:
raise AssertionError(msg or "'%s' should not be empty." % item)
def _get_string_msg(self, item1, item2, custom_message, include_values,
delimiter, quote_item1=True, quote_item2=True):
if custom_message and not self._include_values(include_values):
return custom_message
item1 = "'%s'" % unic(item1) if quote_item1 else unic(item1)
item2 = "'%s'" % unic(item2) if quote_item2 else unic(item2)
default_message = '%s %s %s' % (item1, delimiter, item2)
if not custom_message:
return default_message
return '%s: %s' % (custom_message, default_message)
class _Variables(_BuiltInBase):
def get_variables(self, no_decoration=False):
"""Returns a dictionary containing all variables in the current scope.
Variables are returned as a special dictionary that allows accessing
variables in space, case, and underscore insensitive manner similarly
as accessing variables in the test data. This dictionary supports all
same operations as normal Python dictionaries and, for example,
Collections library can be used to access or modify it. Modifying the
returned dictionary has no effect on the variables available in the
current scope.
By default variables are returned with ``${}``, ``@{}`` or ``&{}``
decoration based on variable types. Giving a true value (see `Boolean
arguments`) to the optional argument ``no_decoration`` will return
the variables without the decoration. This option is new in Robot
Framework 2.9.
Example:
| ${example_variable} = | Set Variable | example value |
| ${variables} = | Get Variables | |
| Dictionary Should Contain Key | ${variables} | \\${example_variable} |
| Dictionary Should Contain Key | ${variables} | \\${ExampleVariable} |
| Set To Dictionary | ${variables} | \\${name} | value |
| Variable Should Not Exist | \\${name} | | |
| ${no decoration} = | Get Variables | no_decoration=Yes |
| Dictionary Should Contain Key | ${no decoration} | example_variable |
"""
return self._variables.as_dict(decoration=is_falsy(no_decoration))
@run_keyword_variant(resolve=0)
def get_variable_value(self, name, default=None):
"""Returns variable value or ``default`` if the variable does not exist.
The name of the variable can be given either as a normal variable name
(e.g. ``${NAME}``) or in escaped format (e.g. ``\\${NAME}``). Notice
that the former has some limitations explained in `Set Suite Variable`.
Examples:
| ${x} = | Get Variable Value | ${a} | default |
| ${y} = | Get Variable Value | ${a} | ${b} |
| ${z} = | Get Variable Value | ${z} | |
=>
| ${x} gets value of ${a} if ${a} exists and string 'default' otherwise
| ${y} gets value of ${a} if ${a} exists and value of ${b} otherwise
| ${z} is set to Python None if it does not exist previously
See `Set Variable If` for another keyword to set variables dynamically.
"""
try:
return self._variables[self._get_var_name(name)]
except DataError:
return self._variables.replace_scalar(default)
def log_variables(self, level='INFO'):
"""Logs all variables in the current scope with given log level."""
variables = self.get_variables()
for name in sorted(variables, key=lambda s: s[2:-1].lower()):
msg = format_assign_message(name, variables[name], cut_long=False)
self.log(msg, level)
@run_keyword_variant(resolve=0)
def variable_should_exist(self, name, msg=None):
"""Fails unless the given variable exists within the current scope.
The name of the variable can be given either as a normal variable name
(e.g. ``${NAME}``) or in escaped format (e.g. ``\\${NAME}``). Notice
that the former has some limitations explained in `Set Suite Variable`.
The default error message can be overridden with the ``msg`` argument.
See also `Variable Should Not Exist` and `Keyword Should Exist`.
"""
name = self._get_var_name(name)
msg = self._variables.replace_string(msg) if msg \
else "Variable %s does not exist." % name
try:
self._variables[name]
except DataError:
raise AssertionError(msg)
@run_keyword_variant(resolve=0)
def variable_should_not_exist(self, name, msg=None):
"""Fails if the given variable exists within the current scope.
The name of the variable can be given either as a normal variable name
(e.g. ``${NAME}``) or in escaped format (e.g. ``\\${NAME}``). Notice
that the former has some limitations explained in `Set Suite Variable`.
The default error message can be overridden with the ``msg`` argument.
See also `Variable Should Exist` and `Keyword Should Exist`.
"""
name = self._get_var_name(name)
msg = self._variables.replace_string(msg) if msg \
else "Variable %s exists." % name
try:
self._variables[name]
except DataError:
pass
else:
raise AssertionError(msg)
def replace_variables(self, text):
"""Replaces variables in the given text with their current values.
If the text contains undefined variables, this keyword fails.
If the given ``text`` contains only a single variable, its value is
returned as-is and it can be any object. Otherwise this keyword
always returns a string.
Example:
The file ``template.txt`` contains ``Hello ${NAME}!`` and variable
``${NAME}`` has the value ``Robot``.
| ${template} = | Get File | ${CURDIR}/template.txt |
| ${message} = | Replace Variables | ${template} |
| Should Be Equal | ${message} | Hello Robot! |
"""
return self._variables.replace_scalar(text)
def set_variable(self, *values):
"""Returns the given values which can then be assigned to a variables.
This keyword is mainly used for setting scalar variables.
Additionally it can be used for converting a scalar variable
containing a list to a list variable or to multiple scalar variables.
It is recommended to use `Create List` when creating new lists.
Examples:
| ${hi} = | Set Variable | Hello, world! |
| ${hi2} = | Set Variable | I said: ${hi} |
| ${var1} | ${var2} = | Set Variable | Hello | world |
| @{list} = | Set Variable | ${list with some items} |
| ${item1} | ${item2} = | Set Variable | ${list with 2 items} |
Variables created with this keyword are available only in the
scope where they are created. See `Set Global Variable`,
`Set Test Variable` and `Set Suite Variable` for information on how to
set variables so that they are available also in a larger scope.
"""
if len(values) == 0:
return ''
elif len(values) == 1:
return values[0]
else:
return list(values)
@run_keyword_variant(resolve=0)
def set_test_variable(self, name, *values):
"""Makes a variable available everywhere within the scope of the current test.
Variables set with this keyword are available everywhere within the
scope of the currently executed test case. For example, if you set a
variable in a user keyword, it is available both in the test case level
and also in all other user keywords used in the current test. Other
test cases will not see variables set with this keyword.
See `Set Suite Variable` for more information and examples.
"""
name = self._get_var_name(name)
value = self._get_var_value(name, values)
self._variables.set_test(name, value)
self._log_set_variable(name, value)
@run_keyword_variant(resolve=0)
def set_task_variable(self, name, *values):
"""Makes a variable available everywhere within the scope of the current task.
This is an alias for `Set Test Variable` that is more applicable when
creating tasks, not tests. New in RF 3.1.
"""
self.set_test_variable(name, *values)
@run_keyword_variant(resolve=0)
def set_suite_variable(self, name, *values):
"""Makes a variable available everywhere within the scope of the current suite.
Variables set with this keyword are available everywhere within the
scope of the currently executed test suite. Setting variables with this
keyword thus has the same effect as creating them using the Variable
table in the test data file or importing them from variable files.
Possible child test suites do not see variables set with this keyword
by default. Starting from Robot Framework 2.9, that can be controlled
by using ``children=<option>`` as the last argument. If the specified
``<option>`` is a non-empty string or any other value considered true
in Python, the variable is set also to the child suites. Parent and
sibling suites will never see variables set with this keyword.
The name of the variable can be given either as a normal variable name
(e.g. ``${NAME}``) or in escaped format as ``\\${NAME}`` or ``$NAME``.
Variable value can be given using the same syntax as when variables
are created in the Variable table.
If a variable already exists within the new scope, its value will be
overwritten. Otherwise a new variable is created. If a variable already
exists within the current scope, the value can be left empty and the
variable within the new scope gets the value within the current scope.
Examples:
| Set Suite Variable | ${SCALAR} | Hello, world! |
| Set Suite Variable | ${SCALAR} | Hello, world! | children=true |
| Set Suite Variable | @{LIST} | First item | Second item |
| Set Suite Variable | &{DICT} | key=value | foo=bar |
| ${ID} = | Get ID |
| Set Suite Variable | ${ID} |
To override an existing value with an empty value, use built-in
variables ``${EMPTY}``, ``@{EMPTY}`` or ``&{EMPTY}``:
| Set Suite Variable | ${SCALAR} | ${EMPTY} |
| Set Suite Variable | @{LIST} | @{EMPTY} |
| Set Suite Variable | &{DICT} | &{EMPTY} |
*NOTE:* If the variable has value which itself is a variable (escaped
or not), you must always use the escaped format to set the variable:
Example:
| ${NAME} = | Set Variable | \\${var} |
| Set Suite Variable | ${NAME} | value | # Sets variable ${var} |
| Set Suite Variable | \\${NAME} | value | # Sets variable ${NAME} |
This limitation applies also to `Set Test Variable`, `Set Global
Variable`, `Variable Should Exist`, `Variable Should Not Exist` and
`Get Variable Value` keywords.
"""
name = self._get_var_name(name)
if (values and is_string(values[-1]) and
values[-1].startswith('children=')):
children = self._variables.replace_scalar(values[-1][9:])
children = is_truthy(children)
values = values[:-1]
else:
children = False
value = self._get_var_value(name, values)
self._variables.set_suite(name, value, children=children)
self._log_set_variable(name, value)
@run_keyword_variant(resolve=0)
def set_global_variable(self, name, *values):
"""Makes a variable available globally in all tests and suites.
Variables set with this keyword are globally available in all
subsequent test suites, test cases and user keywords. Also variables
in variable tables are overridden. Variables assigned locally based
on keyword return values or by using `Set Test Variable` and
`Set Suite Variable` override these variables in that scope, but
the global value is not changed in those cases.
In practice setting variables with this keyword has the same effect
as using command line options ``--variable`` and ``--variablefile``.
Because this keyword can change variables everywhere, it should be
used with care.
See `Set Suite Variable` for more information and examples.
"""
name = self._get_var_name(name)
value = self._get_var_value(name, values)
self._variables.set_global(name, value)
self._log_set_variable(name, value)
# Helpers
def _get_var_name(self, orig):
name = self._resolve_possible_variable(orig)
try:
return self._unescape_variable_if_needed(name)
except ValueError:
raise RuntimeError("Invalid variable syntax '%s'." % orig)
def _resolve_possible_variable(self, name):
try:
resolved = self._variables.replace_string(name)
return self._unescape_variable_if_needed(resolved)
except (KeyError, ValueError, DataError):
return name
def _unescape_variable_if_needed(self, name):
if name.startswith('\\'):
name = name[1:]
if len(name) < 2:
raise ValueError
if name[0] in '$@&' and name[1] != '{':
name = '%s{%s}' % (name[0], name[1:])
if is_var(name):
return name
# Support for possible internal variables (issue 397)
name = '%s{%s}' % (name[0], self.replace_variables(name[2:-1]))
if is_var(name):
return name
raise ValueError
def _get_var_value(self, name, values):
if not values:
return self._variables[name]
if name[0] == '$':
# We could consider catenating values similarly as when creating
# scalar variables in the variable table, but that would require
# handling non-string values somehow. For details see
# https://github.com/robotframework/robotframework/issues/1919
if len(values) != 1 or VariableSplitter(values[0]).is_list_variable():
raise DataError("Setting list value to scalar variable '%s' "
"is not supported anymore. Create list "
"variable '@%s' instead." % (name, name[1:]))
return self._variables.replace_scalar(values[0])
return VariableTableValue(values, name).resolve(self._variables)
def _log_set_variable(self, name, value):
self.log(format_assign_message(name, value))
class _RunKeyword(_BuiltInBase):
# If you use any of these run keyword variants from another library, you
# should register those keywords with 'register_run_keyword' method. See
# the documentation of that method at the end of this file. There are also
# other run keyword variant keywords in BuiltIn which can also be seen
# at the end of this file.
@run_keyword_variant(resolve=1)
def run_keyword(self, name, *args):
"""Executes the given keyword with the given arguments.
Because the name of the keyword to execute is given as an argument, it
can be a variable and thus set dynamically, e.g. from a return value of
another keyword or from the command line.
"""
if not is_string(name):
raise RuntimeError('Keyword name must be a string.')
kw = Keyword(name, args=args)
return kw.run(self._context)
@run_keyword_variant(resolve=0)
def run_keywords(self, *keywords):
"""Executes all the given keywords in a sequence.
This keyword is mainly useful in setups and teardowns when they need
to take care of multiple actions and creating a new higher level user
keyword would be an overkill.
By default all arguments are expected to be keywords to be executed.
Examples:
| `Run Keywords` | `Initialize database` | `Start servers` | `Clear logs` |
| `Run Keywords` | ${KW 1} | ${KW 2} |
| `Run Keywords` | @{KEYWORDS} |
Keywords can also be run with arguments using upper case ``AND`` as
a separator between keywords. The keywords are executed so that the
first argument is the first keyword and proceeding arguments until
the first ``AND`` are arguments to it. First argument after the first
``AND`` is the second keyword and proceeding arguments until the next
``AND`` are its arguments. And so on.
Examples:
| `Run Keywords` | `Initialize database` | db1 | AND | `Start servers` | server1 | server2 |
| `Run Keywords` | `Initialize database` | ${DB NAME} | AND | `Start servers` | @{SERVERS} | AND | `Clear logs` |
| `Run Keywords` | ${KW} | AND | @{KW WITH ARGS} |
Notice that the ``AND`` control argument must be used explicitly and
cannot itself come from a variable. If you need to use literal ``AND``
string as argument, you can either use variables or escape it with
a backslash like ``\\AND``.
"""
self._run_keywords(self._split_run_keywords(list(keywords)))
def _run_keywords(self, iterable):
errors = []
for kw, args in iterable:
try:
self.run_keyword(kw, *args)
except ExecutionPassed as err:
err.set_earlier_failures(errors)
raise err
except ExecutionFailed as err:
errors.extend(err.get_errors())
if not err.can_continue(self._context.in_teardown):
break
if errors:
raise ExecutionFailures(errors)
def _split_run_keywords(self, keywords):
if 'AND' not in keywords:
for name in self._variables.replace_list(keywords):
yield name, ()
else:
for name, args in self._split_run_keywords_from_and(keywords):
yield name, args
def _split_run_keywords_from_and(self, keywords):
while 'AND' in keywords:
index = keywords.index('AND')
yield self._resolve_run_keywords_name_and_args(keywords[:index])
keywords = keywords[index+1:]
yield self._resolve_run_keywords_name_and_args(keywords)
def _resolve_run_keywords_name_and_args(self, kw_call):
kw_call = self._variables.replace_list(kw_call, replace_until=1)
if not kw_call:
raise DataError('Incorrect use of AND')
return kw_call[0], kw_call[1:]
@run_keyword_variant(resolve=2)
def run_keyword_if(self, condition, name, *args):
"""Runs the given keyword with the given arguments, if ``condition`` is true.
The given ``condition`` is evaluated in Python as explained in
`Evaluating expressions`, and ``name`` and ``*args`` have same
semantics as with `Run Keyword`.
Example, a simple if/else construct:
| ${status} | ${value} = | `Run Keyword And Ignore Error` | `My Keyword` |
| `Run Keyword If` | '${status}' == 'PASS' | `Some Action` | arg |
| `Run Keyword Unless` | '${status}' == 'PASS' | `Another Action` |
In this example, only either `Some Action` or `Another Action` is
executed, based on the status of `My Keyword`. Instead of `Run Keyword
And Ignore Error` you can also use `Run Keyword And Return Status`.
Variables used like ``${variable}``, as in the examples above, are
replaced in the expression before evaluation. Variables are also
available in the evaluation namespace and can be accessed using special
syntax ``$variable``. This is a new feature in Robot Framework 2.9
and it is explained more thoroughly in `Evaluating expressions`.
Example:
| `Run Keyword If` | $result is None or $result == 'FAIL' | `Keyword` |
This keyword supports also optional ELSE and ELSE IF branches. Both
of them are defined in ``*args`` and must use exactly format ``ELSE``
or ``ELSE IF``, respectively. ELSE branches must contain first the
name of the keyword to execute and then its possible arguments. ELSE
IF branches must first contain a condition, like the first argument
to this keyword, and then the keyword to execute and its possible
arguments. It is possible to have ELSE branch after ELSE IF and to
have multiple ELSE IF branches. Nested `Run Keyword If` usage is not
supported when using ELSE and/or ELSE IF branches.
Given previous example, if/else construct can also be created like this:
| ${status} | ${value} = | `Run Keyword And Ignore Error` | `My Keyword` |
| `Run Keyword If` | '${status}' == 'PASS' | `Some Action` | arg | ELSE | `Another Action` |
The return value of this keyword is the return value of the actually
executed keyword or Python ``None`` if no keyword was executed (i.e.
if ``condition`` was false). Hence, it is recommended to use ELSE
and/or ELSE IF branches to conditionally assign return values from
keyword to variables (see `Set Variable If` if you need to set fixed
values conditionally). This is illustrated by the example below:
| ${var1} = | `Run Keyword If` | ${rc} == 0 | `Some keyword returning a value` |
| ... | ELSE IF | 0 < ${rc} < 42 | `Another keyword` |
| ... | ELSE IF | ${rc} < 0 | `Another keyword with args` | ${rc} | arg2 |
| ... | ELSE | `Final keyword to handle abnormal cases` | ${rc} |
| ${var2} = | `Run Keyword If` | ${condition} | `Some keyword` |
In this example, ${var2} will be set to ``None`` if ${condition} is
false.
Notice that ``ELSE`` and ``ELSE IF`` control words must be used
explicitly and thus cannot come from variables. If you need to use
literal ``ELSE`` and ``ELSE IF`` strings as arguments, you can escape
them with a backslash like ``\\ELSE`` and ``\\ELSE IF``.
Python's [http://docs.python.org/library/os.html|os] and
[http://docs.python.org/library/sys.html|sys] modules are
automatically imported when evaluating the ``condition``.
Attributes they contain can thus be used in the condition:
| `Run Keyword If` | os.sep == '/' | `Unix Keyword` |
| ... | ELSE IF | sys.platform.startswith('java') | `Jython Keyword` |
| ... | ELSE | `Windows Keyword` |
"""
args, branch = self._split_elif_or_else_branch(args)
if self._is_true(condition):
return self.run_keyword(name, *args)
return branch()
def _split_elif_or_else_branch(self, args):
if 'ELSE IF' in args:
args, branch = self._split_branch(args, 'ELSE IF', 2,
'condition and keyword')
return args, lambda: self.run_keyword_if(*branch)
if 'ELSE' in args:
args, branch = self._split_branch(args, 'ELSE', 1, 'keyword')
return args, lambda: self.run_keyword(*branch)
return args, lambda: None
def _split_branch(self, args, control_word, required, required_error):
index = list(args).index(control_word)
branch = self._variables.replace_list(args[index+1:], required)
if len(branch) < required:
raise DataError('%s requires %s.' % (control_word, required_error))
return args[:index], branch
@run_keyword_variant(resolve=2)
def run_keyword_unless(self, condition, name, *args):
"""Runs the given keyword with the given arguments if ``condition`` is false.
See `Run Keyword If` for more information and an example. Notice that
this keyword does not support ``ELSE`` or ``ELSE IF`` branches like
`Run Keyword If` does, though.
"""
if not self._is_true(condition):
return self.run_keyword(name, *args)
@run_keyword_variant(resolve=1)
def run_keyword_and_ignore_error(self, name, *args):
"""Runs the given keyword with the given arguments and ignores possible error.
This keyword returns two values, so that the first is either string
``PASS`` or ``FAIL``, depending on the status of the executed keyword.
The second value is either the return value of the keyword or the
received error message. See `Run Keyword And Return Status` If you are
only interested in the execution status.
The keyword name and arguments work as in `Run Keyword`. See
`Run Keyword If` for a usage example.
Errors caused by invalid syntax, timeouts, or fatal exceptions are not
caught by this keyword. Otherwise this keyword itself never fails.
Since Robot Framework 2.9, variable errors are caught by this keyword.
"""
try:
return 'PASS', self.run_keyword(name, *args)
except ExecutionFailed as err:
if err.dont_continue:
raise
return 'FAIL', unic(err)
@run_keyword_variant(resolve=1)
def run_keyword_and_return_status(self, name, *args):
"""Runs the given keyword with given arguments and returns the status as a Boolean value.
This keyword returns Boolean ``True`` if the keyword that is executed
succeeds and ``False`` if it fails. This is useful, for example, in
combination with `Run Keyword If`. If you are interested in the error
message or return value, use `Run Keyword And Ignore Error` instead.
The keyword name and arguments work as in `Run Keyword`.
Example:
| ${passed} = | `Run Keyword And Return Status` | Keyword | args |
| `Run Keyword If` | ${passed} | Another keyword |
Errors caused by invalid syntax, timeouts, or fatal exceptions are not
caught by this keyword. Otherwise this keyword itself never fails.
"""
status, _ = self.run_keyword_and_ignore_error(name, *args)
return status == 'PASS'
@run_keyword_variant(resolve=1)
def run_keyword_and_continue_on_failure(self, name, *args):
"""Runs the keyword and continues execution even if a failure occurs.
The keyword name and arguments work as with `Run Keyword`.
Example:
| Run Keyword And Continue On Failure | Fail | This is a stupid example |
| Log | This keyword is executed |
The execution is not continued if the failure is caused by invalid syntax,
timeout, or fatal exception.
Since Robot Framework 2.9, variable errors are caught by this keyword.
"""
try:
return self.run_keyword(name, *args)
except ExecutionFailed as err:
if not err.dont_continue:
err.continue_on_failure = True
raise err
@run_keyword_variant(resolve=2)
def run_keyword_and_expect_error(self, expected_error, name, *args):
"""Runs the keyword and checks that the expected error occurred.
The keyword to execute and its arguments are specified using ``name``
and ``*args`` exactly like with `Run Keyword`.
The expected error must be given in the same format as in Robot
Framework reports. By default it is interpreted as a glob pattern
with ``*``, ``?`` and ``[chars]`` as wildcards, but starting from
Robot Framework 3.1 that can be changed by using various prefixes
explained in the table below. Prefixes are case-sensitive and they
must be separated from the actual message with a colon and an
optional space like ``PREFIX: Message`` or ``PREFIX:Message``.
| = Prefix = | = Explanation = |
| ``EQUALS`` | Exact match. Especially useful if the error contains glob wildcards. |
| ``STARTS`` | Error must start with the specified error. |
| ``REGEXP`` | Regular expression match. |
| ``GLOB`` | Same as the default behavior. |
See the `Pattern matching` section for more information about glob
patterns and regular expressions.
If the expected error occurs, the error message is returned and it can
be further processed or tested if needed. If there is no error, or the
error does not match the expected error, this keyword fails.
Examples:
| Run Keyword And Expect Error | My error | Keyword | arg |
| Run Keyword And Expect Error | ValueError: * | Some Keyword |
| Run Keyword And Expect Error | STARTS: ValueError: | Some Keyword |
| Run Keyword And Expect Error | EQUALS:No match for '//input[@type="text"]' |
| ... | Find Element | //input[@type="text"] |
| ${msg} = | Run Keyword And Expect Error | * |
| ... | Keyword | arg1 | arg2 |
| Log To Console | ${msg} |
Errors caused by invalid syntax, timeouts, or fatal exceptions are not
caught by this keyword.
Since Robot Framework 2.9, variable errors are caught by this keyword.
"""
try:
self.run_keyword(name, *args)
except ExecutionFailed as err:
if err.dont_continue:
raise
error = err.message
else:
raise AssertionError("Expected error '%s' did not occur."
% expected_error)
if not self._error_is_expected(error, expected_error):
raise AssertionError("Expected error '%s' but got '%s'."
% (expected_error, error))
return error
def _error_is_expected(self, error, expected_error):
glob = self._matches
matchers = {'GLOB': glob,
'EQUALS': lambda s, p: s == p,
'STARTS': lambda s, p: s.startswith(p),
'REGEXP': lambda s, p: re.match(p, s) is not None}
prefixes = tuple(prefix + ':' for prefix in matchers)
if not expected_error.startswith(prefixes):
return glob(error, expected_error)
prefix, expected_error = expected_error.split(':', 1)
return matchers[prefix](error, expected_error.lstrip())
@run_keyword_variant(resolve=2)
def repeat_keyword(self, repeat, name, *args):
"""Executes the specified keyword multiple times.
``name`` and ``args`` define the keyword that is executed similarly as
with `Run Keyword`. ``repeat`` specifies how many times (as a count) or
how long time (as a timeout) the keyword should be executed.
If ``repeat`` is given as count, it specifies how many times the
keyword should be executed. ``repeat`` can be given as an integer or
as a string that can be converted to an integer. If it is a string,
it can have postfix ``times`` or ``x`` (case and space insensitive)
to make the expression more explicit.
If ``repeat`` is given as timeout, it must be in Robot Framework's
time format (e.g. ``1 minute``, ``2 min 3 s``). Using a number alone
(e.g. ``1`` or ``1.5``) does not work in this context.
If ``repeat`` is zero or negative, the keyword is not executed at
all. This keyword fails immediately if any of the execution
rounds fails.
Examples:
| Repeat Keyword | 5 times | Go to Previous Page |
| Repeat Keyword | ${var} | Some Keyword | arg1 | arg2 |
| Repeat Keyword | 2 minutes | Some Keyword | arg1 | arg2 |
Specifying ``repeat`` as a timeout is new in Robot Framework 3.0.
"""
try:
count = self._get_repeat_count(repeat)
except RuntimeError as err:
timeout = self._get_repeat_timeout(repeat)
if timeout is None:
raise err
keywords = self._keywords_repeated_by_timeout(timeout, name, args)
else:
keywords = self._keywords_repeated_by_count(count, name, args)
self._run_keywords(keywords)
def _get_repeat_count(self, times, require_postfix=False):
times = normalize(str(times))
if times.endswith('times'):
times = times[:-5]
elif times.endswith('x'):
times = times[:-1]
elif require_postfix:
raise ValueError
return self._convert_to_integer(times)
def _get_repeat_timeout(self, timestr):
try:
float(timestr)
except ValueError:
pass
else:
return None
try:
return timestr_to_secs(timestr)
except ValueError:
return None
def _keywords_repeated_by_count(self, count, name, args):
if count <= 0:
self.log("Keyword '%s' repeated zero times." % name)
for i in range(count):
self.log("Repeating keyword, round %d/%d." % (i + 1, count))
yield name, args
def _keywords_repeated_by_timeout(self, timeout, name, args):
if timeout <= 0:
self.log("Keyword '%s' repeated zero times." % name)
repeat_round = 0
maxtime = time.time() + timeout
while time.time() < maxtime:
repeat_round += 1
self.log("Repeating keyword, round %d, %s remaining."
% (repeat_round,
secs_to_timestr(maxtime - time.time(), compact=True)))
yield name, args
@run_keyword_variant(resolve=3)
def wait_until_keyword_succeeds(self, retry, retry_interval, name, *args):
"""Runs the specified keyword and retries if it fails.
``name`` and ``args`` define the keyword that is executed similarly
as with `Run Keyword`. How long to retry running the keyword is
defined using ``retry`` argument either as timeout or count.
``retry_interval`` is the time to wait before trying to run the
keyword again after the previous run has failed.
If ``retry`` is given as timeout, it must be in Robot Framework's
time format (e.g. ``1 minute``, ``2 min 3 s``, ``4.5``) that is
explained in an appendix of Robot Framework User Guide. If it is
given as count, it must have ``times`` or ``x`` postfix (e.g.
``5 times``, ``10 x``). ``retry_interval`` must always be given in
Robot Framework's time format.
If the keyword does not succeed regardless of retries, this keyword
fails. If the executed keyword passes, its return value is returned.
Examples:
| Wait Until Keyword Succeeds | 2 min | 5 sec | My keyword | argument |
| ${result} = | Wait Until Keyword Succeeds | 3x | 200ms | My keyword |
All normal failures are caught by this keyword. Errors caused by
invalid syntax, test or keyword timeouts, or fatal exceptions (caused
e.g. by `Fatal Error`) are not caught.
Running the same keyword multiple times inside this keyword can create
lots of output and considerably increase the size of the generated
output files. It is possible to remove unnecessary keywords from
the outputs using ``--RemoveKeywords WUKS`` command line option.
Support for specifying ``retry`` as a number of times to retry is
a new feature in Robot Framework 2.9.
Since Robot Framework 2.9, variable errors are caught by this keyword.
"""
maxtime = count = -1
try:
count = self._get_repeat_count(retry, require_postfix=True)
except ValueError:
timeout = timestr_to_secs(retry)
maxtime = time.time() + timeout
message = 'for %s' % secs_to_timestr(timeout)
else:
if count <= 0:
raise ValueError('Retry count %d is not positive.' % count)
message = '%d time%s' % (count, s(count))
retry_interval = timestr_to_secs(retry_interval)
while True:
try:
return self.run_keyword(name, *args)
except ExecutionFailed as err:
if err.dont_continue:
raise
count -= 1
if time.time() > maxtime > 0 or count == 0:
raise AssertionError("Keyword '%s' failed after retrying "
"%s. The last error was: %s"
% (name, message, err))
self._sleep_in_parts(retry_interval)
@run_keyword_variant(resolve=1)
def set_variable_if(self, condition, *values):
"""Sets variable based on the given condition.
The basic usage is giving a condition and two values. The
given condition is first evaluated the same way as with the
`Should Be True` keyword. If the condition is true, then the
first value is returned, and otherwise the second value is
returned. The second value can also be omitted, in which case
it has a default value None. This usage is illustrated in the
examples below, where ``${rc}`` is assumed to be zero.
| ${var1} = | Set Variable If | ${rc} == 0 | zero | nonzero |
| ${var2} = | Set Variable If | ${rc} > 0 | value1 | value2 |
| ${var3} = | Set Variable If | ${rc} > 0 | whatever | |
=>
| ${var1} = 'zero'
| ${var2} = 'value2'
| ${var3} = None
It is also possible to have 'else if' support by replacing the
second value with another condition, and having two new values
after it. If the first condition is not true, the second is
evaluated and one of the values after it is returned based on
its truth value. This can be continued by adding more
conditions without a limit.
| ${var} = | Set Variable If | ${rc} == 0 | zero |
| ... | ${rc} > 0 | greater than zero | less then zero |
| |
| ${var} = | Set Variable If |
| ... | ${rc} == 0 | zero |
| ... | ${rc} == 1 | one |
| ... | ${rc} == 2 | two |
| ... | ${rc} > 2 | greater than two |
| ... | ${rc} < 0 | less than zero |
Use `Get Variable Value` if you need to set variables
dynamically based on whether a variable exist or not.
"""
values = self._verify_values_for_set_variable_if(list(values))
if self._is_true(condition):
return self._variables.replace_scalar(values[0])
values = self._verify_values_for_set_variable_if(values[1:], True)
if len(values) == 1:
return self._variables.replace_scalar(values[0])
return self.run_keyword('BuiltIn.Set Variable If', *values[0:])
def _verify_values_for_set_variable_if(self, values, default=False):
if not values:
if default:
return [None]
raise RuntimeError('At least one value is required')
if is_list_var(values[0]):
values[:1] = [escape(item) for item in self._variables[values[0]]]
return self._verify_values_for_set_variable_if(values)
return values
@run_keyword_variant(resolve=1)
def run_keyword_if_test_failed(self, name, *args):
"""Runs the given keyword with the given arguments, if the test failed.
This keyword can only be used in a test teardown. Trying to use it
anywhere else results in an error.
Otherwise, this keyword works exactly like `Run Keyword`, see its
documentation for more details.
Prior to Robot Framework 2.9 failures in test teardown itself were
not detected by this keyword.
"""
test = self._get_test_in_teardown('Run Keyword If Test Failed')
if not test.passed:
return self.run_keyword(name, *args)
@run_keyword_variant(resolve=1)
def run_keyword_if_test_passed(self, name, *args):
"""Runs the given keyword with the given arguments, if the test passed.
This keyword can only be used in a test teardown. Trying to use it
anywhere else results in an error.
Otherwise, this keyword works exactly like `Run Keyword`, see its
documentation for more details.
Prior to Robot Framework 2.9 failures in test teardown itself were
not detected by this keyword.
"""
test = self._get_test_in_teardown('Run Keyword If Test Passed')
if test.passed:
return self.run_keyword(name, *args)
@run_keyword_variant(resolve=1)
def run_keyword_if_timeout_occurred(self, name, *args):
"""Runs the given keyword if either a test or a keyword timeout has occurred.
This keyword can only be used in a test teardown. Trying to use it
anywhere else results in an error.
Otherwise, this keyword works exactly like `Run Keyword`, see its
documentation for more details.
"""
self._get_test_in_teardown('Run Keyword If Timeout Occurred')
if self._context.timeout_occurred:
return self.run_keyword(name, *args)
def _get_test_in_teardown(self, kwname):
ctx = self._context
if ctx.test and ctx.in_test_teardown:
return ctx.test
raise RuntimeError("Keyword '%s' can only be used in test teardown."
% kwname)
@run_keyword_variant(resolve=1)
def run_keyword_if_all_critical_tests_passed(self, name, *args):
"""Runs the given keyword with the given arguments, if all critical tests passed.
This keyword can only be used in suite teardown. Trying to use it in
any other place will result in an error.
Otherwise, this keyword works exactly like `Run Keyword`, see its
documentation for more details.
"""
suite = self._get_suite_in_teardown('Run Keyword If '
'All Critical Tests Passed')
if suite.statistics.critical.failed == 0:
return self.run_keyword(name, *args)
@run_keyword_variant(resolve=1)
def run_keyword_if_any_critical_tests_failed(self, name, *args):
"""Runs the given keyword with the given arguments, if any critical tests failed.
This keyword can only be used in a suite teardown. Trying to use it
anywhere else results in an error.
Otherwise, this keyword works exactly like `Run Keyword`, see its
documentation for more details.
"""
suite = self._get_suite_in_teardown('Run Keyword If '
'Any Critical Tests Failed')
if suite.statistics.critical.failed > 0:
return self.run_keyword(name, *args)
@run_keyword_variant(resolve=1)
def run_keyword_if_all_tests_passed(self, name, *args):
"""Runs the given keyword with the given arguments, if all tests passed.
This keyword can only be used in a suite teardown. Trying to use it
anywhere else results in an error.
Otherwise, this keyword works exactly like `Run Keyword`, see its
documentation for more details.
"""
suite = self._get_suite_in_teardown('Run Keyword If All Tests Passed')
if suite.statistics.all.failed == 0:
return self.run_keyword(name, *args)
@run_keyword_variant(resolve=1)
def run_keyword_if_any_tests_failed(self, name, *args):
"""Runs the given keyword with the given arguments, if one or more tests failed.
This keyword can only be used in a suite teardown. Trying to use it
anywhere else results in an error.
Otherwise, this keyword works exactly like `Run Keyword`, see its
documentation for more details.
"""
suite = self._get_suite_in_teardown('Run Keyword If Any Tests Failed')
if suite.statistics.all.failed > 0:
return self.run_keyword(name, *args)
def _get_suite_in_teardown(self, kwname):
if not self._context.in_suite_teardown:
raise RuntimeError("Keyword '%s' can only be used in suite teardown."
% kwname)
return self._context.suite
class _Control(_BuiltInBase):
def continue_for_loop(self):
"""Skips the current for loop iteration and continues from the next.
Skips the remaining keywords in the current for loop iteration and
continues from the next one. Can be used directly in a for loop or
in a keyword that the loop uses.
Example:
| :FOR | ${var} | IN | @{VALUES} |
| | Run Keyword If | '${var}' == 'CONTINUE' | Continue For Loop |
| | Do Something | ${var} |
See `Continue For Loop If` to conditionally continue a for loop without
using `Run Keyword If` or other wrapper keywords.
"""
self.log("Continuing for loop from the next iteration.")
raise ContinueForLoop()
def continue_for_loop_if(self, condition):
"""Skips the current for loop iteration if the ``condition`` is true.
A wrapper for `Continue For Loop` to continue a for loop based on
the given condition. The condition is evaluated using the same
semantics as with `Should Be True` keyword.
Example:
| :FOR | ${var} | IN | @{VALUES} |
| | Continue For Loop If | '${var}' == 'CONTINUE' |
| | Do Something | ${var} |
"""
if self._is_true(condition):
self.continue_for_loop()
def exit_for_loop(self):
"""Stops executing the enclosing for loop.
Exits the enclosing for loop and continues execution after it.
Can be used directly in a for loop or in a keyword that the loop uses.
Example:
| :FOR | ${var} | IN | @{VALUES} |
| | Run Keyword If | '${var}' == 'EXIT' | Exit For Loop |
| | Do Something | ${var} |
See `Exit For Loop If` to conditionally exit a for loop without
using `Run Keyword If` or other wrapper keywords.
"""
self.log("Exiting for loop altogether.")
raise ExitForLoop()
def exit_for_loop_if(self, condition):
"""Stops executing the enclosing for loop if the ``condition`` is true.
A wrapper for `Exit For Loop` to exit a for loop based on
the given condition. The condition is evaluated using the same
semantics as with `Should Be True` keyword.
Example:
| :FOR | ${var} | IN | @{VALUES} |
| | Exit For Loop If | '${var}' == 'EXIT' |
| | Do Something | ${var} |
"""
if self._is_true(condition):
self.exit_for_loop()
@run_keyword_variant(resolve=0)
def return_from_keyword(self, *return_values):
"""Returns from the enclosing user keyword.
This keyword can be used to return from a user keyword with PASS status
without executing it fully. It is also possible to return values
similarly as with the ``[Return]`` setting. For more detailed information
about working with the return values, see the User Guide.
This keyword is typically wrapped to some other keyword, such as
`Run Keyword If` or `Run Keyword If Test Passed`, to return based
on a condition:
| Run Keyword If | ${rc} < 0 | Return From Keyword |
| Run Keyword If Test Passed | Return From Keyword |
It is possible to use this keyword to return from a keyword also inside
a for loop. That, as well as returning values, is demonstrated by the
`Find Index` keyword in the following somewhat advanced example.
Notice that it is often a good idea to move this kind of complicated
logic into a test library.
| ***** Variables *****
| @{LIST} = foo baz
|
| ***** Test Cases *****
| Example
| ${index} = Find Index baz @{LIST}
| Should Be Equal ${index} ${1}
| ${index} = Find Index non existing @{LIST}
| Should Be Equal ${index} ${-1}
|
| ***** Keywords *****
| Find Index
| [Arguments] ${element} @{items}
| ${index} = Set Variable ${0}
| :FOR ${item} IN @{items}
| \\ Run Keyword If '${item}' == '${element}' Return From Keyword ${index}
| \\ ${index} = Set Variable ${index + 1}
| Return From Keyword ${-1} # Also [Return] would work here.
The most common use case, returning based on an expression, can be
accomplished directly with `Return From Keyword If`. See also
`Run Keyword And Return` and `Run Keyword And Return If`.
"""
self._return_from_keyword(return_values)
def _return_from_keyword(self, return_values=None, failures=None):
self.log('Returning from the enclosing user keyword.')
raise ReturnFromKeyword(return_values, failures)
@run_keyword_variant(resolve=1)
def return_from_keyword_if(self, condition, *return_values):
"""Returns from the enclosing user keyword if ``condition`` is true.
A wrapper for `Return From Keyword` to return based on the given
condition. The condition is evaluated using the same semantics as
with `Should Be True` keyword.
Given the same example as in `Return From Keyword`, we can rewrite the
`Find Index` keyword as follows:
| ***** Keywords *****
| Find Index
| [Arguments] ${element} @{items}
| ${index} = Set Variable ${0}
| :FOR ${item} IN @{items}
| \\ Return From Keyword If '${item}' == '${element}' ${index}
| \\ ${index} = Set Variable ${index + 1}
| Return From Keyword ${-1} # Also [Return] would work here.
See also `Run Keyword And Return` and `Run Keyword And Return If`.
"""
if self._is_true(condition):
self._return_from_keyword(return_values)
@run_keyword_variant(resolve=1)
def run_keyword_and_return(self, name, *args):
"""Runs the specified keyword and returns from the enclosing user keyword.
The keyword to execute is defined with ``name`` and ``*args`` exactly
like with `Run Keyword`. After running the keyword, returns from the
enclosing user keyword and passes possible return value from the
executed keyword further. Returning from a keyword has exactly same
semantics as with `Return From Keyword`.
Example:
| `Run Keyword And Return` | `My Keyword` | arg1 | arg2 |
| # Above is equivalent to: |
| ${result} = | `My Keyword` | arg1 | arg2 |
| `Return From Keyword` | ${result} | | |
Use `Run Keyword And Return If` if you want to run keyword and return
based on a condition.
"""
try:
ret = self.run_keyword(name, *args)
except ExecutionFailed as err:
self._return_from_keyword(failures=[err])
else:
self._return_from_keyword(return_values=[escape(ret)])
@run_keyword_variant(resolve=2)
def run_keyword_and_return_if(self, condition, name, *args):
"""Runs the specified keyword and returns from the enclosing user keyword.
A wrapper for `Run Keyword And Return` to run and return based on
the given ``condition``. The condition is evaluated using the same
semantics as with `Should Be True` keyword.
Example:
| `Run Keyword And Return If` | ${rc} > 0 | `My Keyword` | arg1 | arg2 |
| # Above is equivalent to: |
| `Run Keyword If` | ${rc} > 0 | `Run Keyword And Return` | `My Keyword ` | arg1 | arg2 |
Use `Return From Keyword If` if you want to return a certain value
based on a condition.
"""
if self._is_true(condition):
self.run_keyword_and_return(name, *args)
def pass_execution(self, message, *tags):
"""Skips rest of the current test, setup, or teardown with PASS status.
This keyword can be used anywhere in the test data, but the place where
used affects the behavior:
- When used in any setup or teardown (suite, test or keyword), passes
that setup or teardown. Possible keyword teardowns of the started
keywords are executed. Does not affect execution or statuses
otherwise.
- When used in a test outside setup or teardown, passes that particular
test case. Possible test and keyword teardowns are executed.
Possible continuable failures before this keyword is used, as well as
failures in executed teardowns, will fail the execution.
It is mandatory to give a message explaining why execution was passed.
By default the message is considered plain text, but starting it with
``*HTML*`` allows using HTML formatting.
It is also possible to modify test tags passing tags after the message
similarly as with `Fail` keyword. Tags starting with a hyphen
(e.g. ``-regression``) are removed and others added. Tags are modified
using `Set Tags` and `Remove Tags` internally, and the semantics
setting and removing them are the same as with these keywords.
Examples:
| Pass Execution | All features available in this version tested. |
| Pass Execution | Deprecated test. | deprecated | -regression |
This keyword is typically wrapped to some other keyword, such as
`Run Keyword If`, to pass based on a condition. The most common case
can be handled also with `Pass Execution If`:
| Run Keyword If | ${rc} < 0 | Pass Execution | Negative values are cool. |
| Pass Execution If | ${rc} < 0 | Negative values are cool. |
Passing execution in the middle of a test, setup or teardown should be
used with care. In the worst case it leads to tests that skip all the
parts that could actually uncover problems in the tested application.
In cases where execution cannot continue do to external factors,
it is often safer to fail the test case and make it non-critical.
"""
message = message.strip()
if not message:
raise RuntimeError('Message cannot be empty.')
self._set_and_remove_tags(tags)
log_message, level = self._get_logged_test_message_and_level(message)
self.log('Execution passed with message:\n%s' % log_message, level)
raise PassExecution(message)
@run_keyword_variant(resolve=1)
def pass_execution_if(self, condition, message, *tags):
"""Conditionally skips rest of the current test, setup, or teardown with PASS status.
A wrapper for `Pass Execution` to skip rest of the current test,
setup or teardown based the given ``condition``. The condition is
evaluated similarly as with `Should Be True` keyword, and ``message``
and ``*tags`` have same semantics as with `Pass Execution`.
Example:
| :FOR | ${var} | IN | @{VALUES} |
| | Pass Execution If | '${var}' == 'EXPECTED' | Correct value was found |
| | Do Something | ${var} |
"""
if self._is_true(condition):
message = self._variables.replace_string(message)
tags = self._variables.replace_list(tags)
self.pass_execution(message, *tags)
class _Misc(_BuiltInBase):
def no_operation(self):
"""Does absolutely nothing."""
def sleep(self, time_, reason=None):
"""Pauses the test executed for the given time.
``time`` may be either a number or a time string. Time strings are in
a format such as ``1 day 2 hours 3 minutes 4 seconds 5milliseconds`` or
``1d 2h 3m 4s 5ms``, and they are fully explained in an appendix of
Robot Framework User Guide. Optional `reason` can be used to explain why
sleeping is necessary. Both the time slept and the reason are logged.
Examples:
| Sleep | 42 |
| Sleep | 1.5 |
| Sleep | 2 minutes 10 seconds |
| Sleep | 10s | Wait for a reply |
"""
seconds = timestr_to_secs(time_)
# Python hangs with negative values
if seconds < 0:
seconds = 0
self._sleep_in_parts(seconds)
self.log('Slept %s' % secs_to_timestr(seconds))
if reason:
self.log(reason)
def _sleep_in_parts(self, seconds):
# time.sleep can't be stopped in windows
# to ensure that we can signal stop (with timeout)
# split sleeping to small pieces
endtime = time.time() + float(seconds)
while True:
remaining = endtime - time.time()
if remaining <= 0:
break
time.sleep(min(remaining, 0.01))
def catenate(self, *items):
"""Catenates the given items together and returns the resulted string.
By default, items are catenated with spaces, but if the first item
contains the string ``SEPARATOR=<sep>``, the separator ``<sep>`` is
used instead. Items are converted into strings when necessary.
Examples:
| ${str1} = | Catenate | Hello | world | |
| ${str2} = | Catenate | SEPARATOR=--- | Hello | world |
| ${str3} = | Catenate | SEPARATOR= | Hello | world |
=>
| ${str1} = 'Hello world'
| ${str2} = 'Hello---world'
| ${str3} = 'Helloworld'
"""
if not items:
return ''
items = [unic(item) for item in items]
if items[0].startswith('SEPARATOR='):
sep = items[0][len('SEPARATOR='):]
items = items[1:]
else:
sep = ' '
return sep.join(items)
def log(self, message, level='INFO', html=False, console=False,
repr=False, formatter='str'):
u"""Logs the given message with the given level.
Valid levels are TRACE, DEBUG, INFO (default), HTML, WARN, and ERROR.
Messages below the current active log level are ignored. See
`Set Log Level` keyword and ``--loglevel`` command line option
for more details about setting the level.
Messages logged with the WARN or ERROR levels will be automatically
visible also in the console and in the Test Execution Errors section
in the log file.
If the ``html`` argument is given a true value (see `Boolean
arguments`), the message will be considered HTML and special characters
such as ``<`` are not escaped. For example, logging
``<img src="image.png">`` creates an image when ``html`` is true, but
otherwise the message is that exact string. An alternative to using
the ``html`` argument is using the HTML pseudo log level. It logs
the message as HTML using the INFO level.
If the ``console`` argument is true, the message will be written to
the console where test execution was started from in addition to
the log file. This keyword always uses the standard output stream
and adds a newline after the written message. Use `Log To Console`
instead if either of these is undesirable,
The ``formatter`` argument controls how to format the string
representation of the message. Possible values are ``str`` (default),
``repr`` and ``ascii``, and they work similarly to Python built-in
functions with same names. When using ``repr``, bigger lists,
dictionaries and other containers are also pretty-printed so that
there is one item per row. For more details see `String
representations`. This is a new feature in Robot Framework 3.1.2.
The old way to control string representation was using the ``repr``
argument, and ``repr=True`` is still equivalent to using
``formatter=repr``. The ``repr`` argument will be deprecated in the
future, though, and using ``formatter`` is thus recommended.
Examples:
| Log | Hello, world! | | | # Normal INFO message. |
| Log | Warning, world! | WARN | | # Warning. |
| Log | <b>Hello</b>, world! | html=yes | | # INFO message as HTML. |
| Log | <b>Hello</b>, world! | HTML | | # Same as above. |
| Log | <b>Hello</b>, world! | DEBUG | html=true | # DEBUG as HTML. |
| Log | Hello, console! | console=yes | | # Log also to the console. |
| Log | Null is \\x00 | formatter=repr | | # Log ``'Null is \\x00'``. |
See `Log Many` if you want to log multiple messages in one go, and
`Log To Console` if you only want to write to the console.
"""
# TODO: Deprecate `repr` in RF 3.2 or latest in RF 3.3.
if is_truthy(repr):
formatter = prepr
else:
formatter = self._get_formatter(formatter)
message = formatter(message)
logger.write(message, level, is_truthy(html))
if is_truthy(console):
logger.console(message)
def _get_formatter(self, formatter):
try:
return {'str': unic,
'repr': prepr,
'ascii': ascii if PY3 else repr}[formatter.lower()]
except KeyError:
raise ValueError("Invalid formatter '%s'. Available "
"'str', 'repr' and 'ascii'." % formatter)
@run_keyword_variant(resolve=0)
def log_many(self, *messages):
"""Logs the given messages as separate entries using the INFO level.
Supports also logging list and dictionary variable items individually.
Examples:
| Log Many | Hello | ${var} |
| Log Many | @{list} | &{dict} |
See `Log` and `Log To Console` keywords if you want to use alternative
log levels, use HTML, or log to the console.
"""
for msg in self._yield_logged_messages(messages):
self.log(msg)
def _yield_logged_messages(self, messages):
for msg in messages:
var = VariableSplitter(msg)
value = self._variables.replace_scalar(msg)
if var.is_list_variable():
for item in value:
yield item
elif var.is_dict_variable():
for name, value in value.items():
yield '%s=%s' % (name, value)
else:
yield value
def log_to_console(self, message, stream='STDOUT', no_newline=False):
"""Logs the given message to the console.
By default uses the standard output stream. Using the standard error
stream is possibly by giving the ``stream`` argument value ``STDERR``
(case-insensitive).
By default appends a newline to the logged message. This can be
disabled by giving the ``no_newline`` argument a true value (see
`Boolean arguments`).
Examples:
| Log To Console | Hello, console! | |
| Log To Console | Hello, stderr! | STDERR |
| Log To Console | Message starts here and is | no_newline=true |
| Log To Console | continued without newline. | |
This keyword does not log the message to the normal log file. Use
`Log` keyword, possibly with argument ``console``, if that is desired.
"""
logger.console(message, newline=is_falsy(no_newline), stream=stream)
@run_keyword_variant(resolve=0)
def comment(self, *messages):
"""Displays the given messages in the log file as keyword arguments.
This keyword does nothing with the arguments it receives, but as they
are visible in the log, this keyword can be used to display simple
messages. Given arguments are ignored so thoroughly that they can even
contain non-existing variables. If you are interested about variable
values, you can use the `Log` or `Log Many` keywords.
"""
pass
def set_log_level(self, level):
"""Sets the log threshold to the specified level and returns the old level.
Messages below the level will not logged. The default logging level is
INFO, but it can be overridden with the command line option
``--loglevel``.
The available levels: TRACE, DEBUG, INFO (default), WARN, ERROR and NONE (no
logging).
"""
try:
old = self._context.output.set_log_level(level)
except DataError as err:
raise RuntimeError(unic(err))
self._namespace.variables.set_global('${LOG_LEVEL}', level.upper())
self.log('Log level changed from %s to %s.' % (old, level.upper()))
return old
def reload_library(self, name_or_instance):
"""Rechecks what keywords the specified library provides.
Can be called explicitly in the test data or by a library itself
when keywords it provides have changed.
The library can be specified by its name or as the active instance of
the library. The latter is especially useful if the library itself
calls this keyword as a method.
New in Robot Framework 2.9.
"""
library = self._namespace.reload_library(name_or_instance)
self.log('Reloaded library %s with %s keywords.' % (library.name,
len(library)))
@run_keyword_variant(resolve=0)
def import_library(self, name, *args):
"""Imports a library with the given name and optional arguments.
This functionality allows dynamic importing of libraries while tests
are running. That may be necessary, if the library itself is dynamic
and not yet available when test data is processed. In a normal case,
libraries should be imported using the Library setting in the Setting
table.
This keyword supports importing libraries both using library
names and physical paths. When paths are used, they must be
given in absolute format or found from
[http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#pythonpath-jythonpath-and-ironpythonpath|
search path]. Forward slashes can be used as path separators in all
operating systems.
It is possible to pass arguments to the imported library and also
named argument syntax works if the library supports it. ``WITH NAME``
syntax can be used to give a custom name to the imported library.
Examples:
| Import Library | MyLibrary |
| Import Library | ${CURDIR}/../Library.py | arg1 | named=arg2 |
| Import Library | ${LIBRARIES}/Lib.java | arg | WITH NAME | JavaLib |
"""
try:
self._namespace.import_library(name, list(args))
except DataError as err:
raise RuntimeError(unic(err))
@run_keyword_variant(resolve=0)
def import_variables(self, path, *args):
"""Imports a variable file with the given path and optional arguments.
Variables imported with this keyword are set into the test suite scope
similarly when importing them in the Setting table using the Variables
setting. These variables override possible existing variables with
the same names. This functionality can thus be used to import new
variables, for example, for each test in a test suite.
The given path must be absolute or found from
[http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#pythonpath-jythonpath-and-ironpythonpath|
search path]. Forward slashes can be used as path separator regardless
the operating system.
Examples:
| Import Variables | ${CURDIR}/variables.py | | |
| Import Variables | ${CURDIR}/../vars/env.py | arg1 | arg2 |
| Import Variables | file_from_pythonpath.py | | |
"""
try:
self._namespace.import_variables(path, list(args), overwrite=True)
except DataError as err:
raise RuntimeError(unic(err))
@run_keyword_variant(resolve=0)
def import_resource(self, path):
"""Imports a resource file with the given path.
Resources imported with this keyword are set into the test suite scope
similarly when importing them in the Setting table using the Resource
setting.
The given path must be absolute or found from
[http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#pythonpath-jythonpath-and-ironpythonpath|
search path]. Forward slashes can be used as path separator regardless
the operating system.
Examples:
| Import Resource | ${CURDIR}/resource.txt |
| Import Resource | ${CURDIR}/../resources/resource.resource |
| Import Resource | found_from_pythonpath.robot |
"""
try:
self._namespace.import_resource(path)
except DataError as err:
raise RuntimeError(unic(err))
def set_library_search_order(self, *search_order):
"""Sets the resolution order to use when a name matches multiple keywords.
The library search order is used to resolve conflicts when a keyword
name in the test data matches multiple keywords. The first library
(or resource, see below) containing the keyword is selected and that
keyword implementation used. If the keyword is not found from any library
(or resource), test executing fails the same way as when the search
order is not set.
When this keyword is used, there is no need to use the long
``LibraryName.Keyword Name`` notation. For example, instead of
having
| MyLibrary.Keyword | arg |
| MyLibrary.Another Keyword |
| MyLibrary.Keyword | xxx |
you can have
| Set Library Search Order | MyLibrary |
| Keyword | arg |
| Another Keyword |
| Keyword | xxx |
This keyword can be used also to set the order of keywords in different
resource files. In this case resource names must be given without paths
or extensions like:
| Set Library Search Order | resource | another_resource |
*NOTE:*
- The search order is valid only in the suite where this keywords is used.
- Keywords in resources always have higher priority than
keywords in libraries regardless the search order.
- The old order is returned and can be used to reset the search order later.
- Library and resource names in the search order are both case and space
insensitive.
"""
return self._namespace.set_search_order(search_order)
def keyword_should_exist(self, name, msg=None):
"""Fails unless the given keyword exists in the current scope.
Fails also if there are more than one keywords with the same name.
Works both with the short name (e.g. ``Log``) and the full name
(e.g. ``BuiltIn.Log``).
The default error message can be overridden with the ``msg`` argument.
See also `Variable Should Exist`.
"""
try:
runner = self._namespace.get_runner(name)
except DataError as error:
raise AssertionError(msg or error.message)
if isinstance(runner, UserErrorHandler):
raise AssertionError(msg or runner.error.message)
def get_time(self, format='timestamp', time_='NOW'):
"""Returns the given time in the requested format.
*NOTE:* DateTime library contains much more flexible keywords for
getting the current date and time and for date and time handling in
general.
How time is returned is determined based on the given ``format``
string as follows. Note that all checks are case-insensitive.
1) If ``format`` contains the word ``epoch``, the time is returned
in seconds after the UNIX epoch (1970-01-01 00:00:00 UTC).
The return value is always an integer.
2) If ``format`` contains any of the words ``year``, ``month``,
``day``, ``hour``, ``min``, or ``sec``, only the selected parts are
returned. The order of the returned parts is always the one
in the previous sentence and the order of words in ``format``
is not significant. The parts are returned as zero-padded
strings (e.g. May -> ``05``).
3) Otherwise (and by default) the time is returned as a
timestamp string in the format ``2006-02-24 15:08:31``.
By default this keyword returns the current local time, but
that can be altered using ``time`` argument as explained below.
Note that all checks involving strings are case-insensitive.
1) If ``time`` is a number, or a string that can be converted to
a number, it is interpreted as seconds since the UNIX epoch.
This documentation was originally written about 1177654467
seconds after the epoch.
2) If ``time`` is a timestamp, that time will be used. Valid
timestamp formats are ``YYYY-MM-DD hh:mm:ss`` and
``YYYYMMDD hhmmss``.
3) If ``time`` is equal to ``NOW`` (default), the current local
time is used.
4) If ``time`` is equal to ``UTC``, the current time in
[http://en.wikipedia.org/wiki/Coordinated_Universal_Time|UTC]
is used.
5) If ``time`` is in the format like ``NOW - 1 day`` or ``UTC + 1 hour
30 min``, the current local/UTC time plus/minus the time
specified with the time string is used. The time string format
is described in an appendix of Robot Framework User Guide.
Examples (expecting the current local time is 2006-03-29 15:06:21):
| ${time} = | Get Time | | | |
| ${secs} = | Get Time | epoch | | |
| ${year} = | Get Time | return year | | |
| ${yyyy} | ${mm} | ${dd} = | Get Time | year,month,day |
| @{time} = | Get Time | year month day hour min sec | | |
| ${y} | ${s} = | Get Time | seconds and year | |
=>
| ${time} = '2006-03-29 15:06:21'
| ${secs} = 1143637581
| ${year} = '2006'
| ${yyyy} = '2006', ${mm} = '03', ${dd} = '29'
| @{time} = ['2006', '03', '29', '15', '06', '21']
| ${y} = '2006'
| ${s} = '21'
Examples (expecting the current local time is 2006-03-29 15:06:21 and
UTC time is 2006-03-29 12:06:21):
| ${time} = | Get Time | | 1177654467 | # Time given as epoch seconds |
| ${secs} = | Get Time | sec | 2007-04-27 09:14:27 | # Time given as a timestamp |
| ${year} = | Get Time | year | NOW | # The local time of execution |
| @{time} = | Get Time | hour min sec | NOW + 1h 2min 3s | # 1h 2min 3s added to the local time |
| @{utc} = | Get Time | hour min sec | UTC | # The UTC time of execution |
| ${hour} = | Get Time | hour | UTC - 1 hour | # 1h subtracted from the UTC time |
=>
| ${time} = '2007-04-27 09:14:27'
| ${secs} = 27
| ${year} = '2006'
| @{time} = ['16', '08', '24']
| @{utc} = ['12', '06', '21']
| ${hour} = '11'
"""
return get_time(format, parse_time(time_))
def evaluate(self, expression, modules=None, namespace=None):
"""Evaluates the given expression in Python and returns the results.
``expression`` is evaluated in Python as explained in `Evaluating
expressions`.
``modules`` argument can be used to specify a comma separated
list of Python modules to be imported and added to the evaluation
namespace.
``namespace`` argument can be used to pass a custom evaluation
namespace as a dictionary. Possible ``modules`` are added to this
namespace.
Variables used like ``${variable}`` are replaced in the expression
before evaluation. Variables are also available in the evaluation
namespace and can be accessed using special syntax ``$variable``.
This is a new feature in Robot Framework 2.9 and it is explained more
thoroughly in `Evaluating expressions`.
Examples (expecting ``${result}`` is 3.14):
| ${status} = | Evaluate | 0 < ${result} < 10 | # Would also work with string '3.14' |
| ${status} = | Evaluate | 0 < $result < 10 | # Using variable itself, not string representation |
| ${random} = | Evaluate | random.randint(0, sys.maxint) | modules=random, sys |
| ${ns} = | Create Dictionary | x=${4} | y=${2} |
| ${result} = | Evaluate | x*10 + y | namespace=${ns} |
=>
| ${status} = True
| ${random} = <random integer>
| ${result} = 42
"""
if is_string(expression) and '$' in expression:
expression, variables = self._handle_variables_in_expression(expression)
else:
variables = {}
namespace = self._create_evaluation_namespace(namespace, modules)
try:
if not is_string(expression):
raise TypeError("Expression must be string, got %s."
% type_name(expression))
if not expression:
raise ValueError("Expression cannot be empty.")
return eval(expression, namespace, variables)
except:
raise RuntimeError("Evaluating expression '%s' failed: %s"
% (expression, get_error_message()))
def _handle_variables_in_expression(self, expression):
variables = None
variable_started = False
tokens = []
generated = generate_tokens(StringIO(expression).readline)
for toknum, tokval, _, _, _ in generated:
if variable_started:
if toknum == token.NAME:
if variables is None:
variables = self._variables.as_dict(decoration=False)
if tokval not in variables:
variable_not_found('$%s' % tokval, variables,
deco_braces=False)
tokval = 'RF_VAR_' + tokval
else:
tokens.append((token.ERRORTOKEN, '$'))
variable_started = False
if toknum == token.ERRORTOKEN and tokval == '$':
variable_started = True
else:
tokens.append((toknum, tokval))
if variables is None:
return expression, {}
decorated = [('RF_VAR_' + name, variables[name]) for name in variables]
return untokenize(tokens).strip(), NormalizedDict(decorated, ignore='_')
def _create_evaluation_namespace(self, namespace, modules):
namespace = dict(namespace or {})
modules = modules.replace(' ', '').split(',') if modules else []
namespace.update((m, __import__(m)) for m in modules if m)
return namespace
def call_method(self, object, method_name, *args, **kwargs):
"""Calls the named method of the given object with the provided arguments.
The possible return value from the method is returned and can be
assigned to a variable. Keyword fails both if the object does not have
a method with the given name or if executing the method raises an
exception.
Support for ``**kwargs`` is new in Robot Framework 2.9. Since that
possible equal signs in other arguments must be escaped with a
backslash like ``\\=``.
Examples:
| Call Method | ${hashtable} | put | myname | myvalue |
| ${isempty} = | Call Method | ${hashtable} | isEmpty | |
| Should Not Be True | ${isempty} | | | |
| ${value} = | Call Method | ${hashtable} | get | myname |
| Should Be Equal | ${value} | myvalue | | |
| Call Method | ${object} | kwargs | name=value | foo=bar |
| Call Method | ${object} | positional | escaped\\=equals |
"""
try:
method = getattr(object, method_name)
except AttributeError:
raise RuntimeError("Object '%s' does not have method '%s'."
% (object, method_name))
try:
return method(*args, **kwargs)
except:
raise RuntimeError("Calling method '%s' failed: %s"
% (method_name, get_error_message()))
def regexp_escape(self, *patterns):
"""Returns each argument string escaped for use as a regular expression.
This keyword can be used to escape strings to be used with
`Should Match Regexp` and `Should Not Match Regexp` keywords.
Escaping is done with Python's ``re.escape()`` function.
Examples:
| ${escaped} = | Regexp Escape | ${original} |
| @{strings} = | Regexp Escape | @{strings} |
"""
if len(patterns) == 0:
return ''
if len(patterns) == 1:
return re.escape(patterns[0])
return [re.escape(p) for p in patterns]
def set_test_message(self, message, append=False):
"""Sets message for the current test case.
If the optional ``append`` argument is given a true value (see `Boolean
arguments`), the given ``message`` is added after the possible earlier
message by joining the messages with a space.
In test teardown this keyword can alter the possible failure message,
but otherwise failures override messages set by this keyword. Notice
that in teardown the message is available as a built-in variable
``${TEST MESSAGE}``.
It is possible to use HTML format in the message by starting the message
with ``*HTML*``.
Examples:
| Set Test Message | My message | |
| Set Test Message | is continued. | append=yes |
| Should Be Equal | ${TEST MESSAGE} | My message is continued. |
| Set Test Message | `*`HTML`*` <b>Hello!</b> | |
This keyword can not be used in suite setup or suite teardown.
"""
test = self._context.test
if not test:
raise RuntimeError("'Set Test Message' keyword cannot be used in "
"suite setup or teardown.")
test.message = self._get_new_text(test.message, message,
append, handle_html=True)
if self._context.in_test_teardown:
self._variables.set_test("${TEST_MESSAGE}", test.message)
message, level = self._get_logged_test_message_and_level(test.message)
self.log('Set test message to:\n%s' % message, level)
def _get_new_text(self, old, new, append, handle_html=False):
if not is_unicode(new):
new = unic(new)
if not (is_truthy(append) and old):
return new
if handle_html:
if new.startswith('*HTML*'):
new = new[6:].lstrip()
if not old.startswith('*HTML*'):
old = '*HTML* %s' % html_escape(old)
elif old.startswith('*HTML*'):
new = html_escape(new)
return '%s %s' % (old, new)
def _get_logged_test_message_and_level(self, message):
if message.startswith('*HTML*'):
return message[6:].lstrip(), 'HTML'
return message, 'INFO'
def set_test_documentation(self, doc, append=False):
"""Sets documentation for the current test case.
By default the possible existing documentation is overwritten, but
this can be changed using the optional ``append`` argument similarly
as with `Set Test Message` keyword.
The current test documentation is available as a built-in variable
``${TEST DOCUMENTATION}``. This keyword can not be used in suite
setup or suite teardown.
"""
test = self._context.test
if not test:
raise RuntimeError("'Set Test Documentation' keyword cannot be "
"used in suite setup or teardown.")
test.doc = self._get_new_text(test.doc, doc, append)
self._variables.set_test('${TEST_DOCUMENTATION}', test.doc)
self.log('Set test documentation to:\n%s' % test.doc)
def set_suite_documentation(self, doc, append=False, top=False):
"""Sets documentation for the current test suite.
By default the possible existing documentation is overwritten, but
this can be changed using the optional ``append`` argument similarly
as with `Set Test Message` keyword.
This keyword sets the documentation of the current suite by default.
If the optional ``top`` argument is given a true value (see `Boolean
arguments`), the documentation of the top level suite is altered
instead.
The documentation of the current suite is available as a built-in
variable ``${SUITE DOCUMENTATION}``.
"""
top = is_truthy(top)
suite = self._get_context(top).suite
suite.doc = self._get_new_text(suite.doc, doc, append)
self._variables.set_suite('${SUITE_DOCUMENTATION}', suite.doc, top)
self.log('Set suite documentation to:\n%s' % suite.doc)
def set_suite_metadata(self, name, value, append=False, top=False):
"""Sets metadata for the current test suite.
By default possible existing metadata values are overwritten, but
this can be changed using the optional ``append`` argument similarly
as with `Set Test Message` keyword.
This keyword sets the metadata of the current suite by default.
If the optional ``top`` argument is given a true value (see `Boolean
arguments`), the metadata of the top level suite is altered instead.
The metadata of the current suite is available as a built-in variable
``${SUITE METADATA}`` in a Python dictionary. Notice that modifying this
variable directly has no effect on the actual metadata the suite has.
"""
top = is_truthy(top)
if not is_unicode(name):
name = unic(name)
metadata = self._get_context(top).suite.metadata
original = metadata.get(name, '')
metadata[name] = self._get_new_text(original, value, append)
self._variables.set_suite('${SUITE_METADATA}', metadata.copy(), top)
self.log("Set suite metadata '%s' to value '%s'." % (name, metadata[name]))
def set_tags(self, *tags):
"""Adds given ``tags`` for the current test or all tests in a suite.
When this keyword is used inside a test case, that test gets
the specified tags and other tests are not affected.
If this keyword is used in a suite setup, all test cases in
that suite, recursively, gets the given tags. It is a failure
to use this keyword in a suite teardown.
The current tags are available as a built-in variable ``@{TEST TAGS}``.
See `Remove Tags` if you want to remove certain tags and `Fail` if
you want to fail the test case after setting and/or removing tags.
"""
ctx = self._context
if ctx.test:
ctx.test.tags.add(tags)
ctx.variables.set_test('@{TEST_TAGS}', list(ctx.test.tags))
elif not ctx.in_suite_teardown:
ctx.suite.set_tags(tags, persist=True)
else:
raise RuntimeError("'Set Tags' cannot be used in suite teardown.")
self.log('Set tag%s %s.' % (s(tags), seq2str(tags)))
def remove_tags(self, *tags):
"""Removes given ``tags`` from the current test or all tests in a suite.
Tags can be given exactly or using a pattern with ``*``, ``?`` and
``[chars]`` acting as wildcards. See the `Glob patterns` section
for more information.
This keyword can affect either one test case or all test cases in a
test suite similarly as `Set Tags` keyword.
The current tags are available as a built-in variable ``@{TEST TAGS}``.
Example:
| Remove Tags | mytag | something-* | ?ython |
See `Set Tags` if you want to add certain tags and `Fail` if you want
to fail the test case after setting and/or removing tags.
"""
ctx = self._context
if ctx.test:
ctx.test.tags.remove(tags)
ctx.variables.set_test('@{TEST_TAGS}', list(ctx.test.tags))
elif not ctx.in_suite_teardown:
ctx.suite.set_tags(remove=tags, persist=True)
else:
raise RuntimeError("'Remove Tags' cannot be used in suite teardown.")
self.log('Removed tag%s %s.' % (s(tags), seq2str(tags)))
def get_library_instance(self, name=None, all=False):
"""Returns the currently active instance of the specified test library.
This keyword makes it easy for test libraries to interact with
other test libraries that have state. This is illustrated by
the Python example below:
| from robotide.lib.robot.libraries.BuiltIn import BuiltIn
|
| def title_should_start_with(expected):
| seleniumlib = BuiltIn().get_library_instance('SeleniumLibrary')
| title = seleniumlib.get_title()
| if not title.startswith(expected):
| raise AssertionError("Title '%s' did not start with '%s'"
| % (title, expected))
It is also possible to use this keyword in the test data and
pass the returned library instance to another keyword. If a
library is imported with a custom name, the ``name`` used to get
the instance must be that name and not the original library name.
If the optional argument ``all`` is given a true value, then a
dictionary mapping all library names to instances will be returned.
This feature is new in Robot Framework 2.9.2.
Example:
| &{all libs} = | Get library instance | all=True |
"""
if is_truthy(all):
return self._namespace.get_library_instances()
try:
return self._namespace.get_library_instance(name)
except DataError as err:
raise RuntimeError(unic(err))
class BuiltIn(_Verify, _Converter, _Variables, _RunKeyword, _Control, _Misc):
u"""An always available standard library with often needed keywords.
``BuiltIn`` is Robot Framework's standard library that provides a set
of generic keywords needed often. It is imported automatically and
thus always available. The provided keywords can be used, for example,
for verifications (e.g. `Should Be Equal`, `Should Contain`),
conversions (e.g. `Convert To Integer`) and for various other purposes
(e.g. `Log`, `Sleep`, `Run Keyword If`, `Set Global Variable`).
== Table of contents ==
- `HTML error messages`
- `Evaluating expressions`
- `Boolean arguments`
- `Pattern matching`
- `Multiline string comparison`
- `String representations`
- `Shortcuts`
- `Keywords`
= HTML error messages =
Many of the keywords accept an optional error message to use if the keyword
fails, and it is possible to use HTML in these messages by prefixing them
with ``*HTML*``. See `Fail` keyword for a usage example. Notice that using
HTML in messages is not limited to BuiltIn library but works with any
error message.
= Evaluating expressions =
Many keywords, such as `Evaluate`, `Run Keyword If` and `Should Be True`,
accept an expression that is evaluated in Python. These expressions are
evaluated using Python's
[http://docs.python.org/library/functions.html#eval|eval] function so
that all Python built-ins like ``len()`` and ``int()`` are available.
`Evaluate` allows configuring the execution namespace with custom modules,
and other keywords have [http://docs.python.org/library/os.html|os]
and [http://docs.python.org/library/sys.html|sys] modules available
automatically.
Examples:
| `Run Keyword If` | os.sep == '/' | Log | Not on Windows |
| ${random int} = | `Evaluate` | random.randint(0, 5) | modules=random |
When a variable is used in the expressing using the normal ``${variable}``
syntax, its value is replaces before the expression is evaluated. This
means that the value used in the expression will be the string
representation of the variable value, not the variable value itself.
This is not a problem with numbers and other objects that have a string
representation that can be evaluated directly, but with other objects
the behavior depends on the string representation. Most importantly,
strings must always be quoted, and if they can contain newlines, they must
be triple quoted.
Examples:
| `Should Be True` | ${rc} < 10 | Return code greater than 10 |
| `Run Keyword If` | '${status}' == 'PASS' | Log | Passed |
| `Run Keyword If` | 'FAIL' in '''${output}''' | Log | Output contains FAIL |
Starting from Robot Framework 2.9, variables themselves are automatically
available in the evaluation namespace. They can be accessed using special
variable syntax without the curly braces like ``$variable``. These
variables should never be quoted, and in fact they are not even replaced
inside strings.
Examples:
| `Should Be True` | $rc < 10 | Return code greater than 10 |
| `Run Keyword If` | $status == 'PASS' | `Log` | Passed |
| `Run Keyword If` | 'FAIL' in $output | `Log` | Output contains FAIL |
| `Should Be True` | len($result) > 1 and $result[1] == 'OK' |
Using the ``$variable`` syntax slows down expression evaluation a little.
This should not typically matter, but should be taken into account if
complex expressions are evaluated often and there are strict time
constrains.
Notice that instead of creating complicated expressions, it is often better
to move the logic into a test library. That eases maintenance and can also
enhance execution speed.
= 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 unless
the keyword documentation explicitly states otherwise, and other argument
types are tested using the same
[http://docs.python.org/library/stdtypes.html#truth|rules as in Python].
True examples:
| `Should Be Equal` | ${x} | ${y} | Custom error | values=True | # Strings are generally true. |
| `Should Be Equal` | ${x} | ${y} | Custom error | values=yes | # Same as the above. |
| `Should Be Equal` | ${x} | ${y} | Custom error | values=${TRUE} | # Python ``True`` is true. |
| `Should Be Equal` | ${x} | ${y} | Custom error | values=${42} | # Numbers other than 0 are true. |
False examples:
| `Should Be Equal` | ${x} | ${y} | Custom error | values=False | # String ``false`` is false. |
| `Should Be Equal` | ${x} | ${y} | Custom error | values=no | # Also string ``no`` is false. |
| `Should Be Equal` | ${x} | ${y} | Custom error | values=${EMPTY} | # Empty string is false. |
| `Should Be Equal` | ${x} | ${y} | Custom error | values=${FALSE} | # Python ``False`` is false. |
| `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.
= Pattern matching =
Many keywords accepts arguments as either glob or regular expression
patterns.
== Glob patterns ==
Some keywords, for example `Should Match`, support so called
[http://en.wikipedia.org/wiki/Glob_(programming)|glob patterns] where:
| ``*`` | matches any string, even an empty string |
| ``?`` | matches any single character |
| ``[chars]`` | matches one character in the bracket |
| ``[!chars]`` | matches one character not in the bracket |
| ``[a-z]`` | matches one character from the range in the bracket |
| ``[!a-z]`` | matches one character not from the range in the bracket |
Unlike with glob patterns normally, path separator characters ``/`` and
``\\`` and the newline character ``\\n`` are matches by the above
wildcards.
Support for brackets like ``[abc]`` and ``[!a-z]`` is new in
Robot Framework 3.1
== Regular expressions ==
Some keywords, for example `Should Match Regexp`, support
[http://en.wikipedia.org/wiki/Regular_expression|regular expressions]
that are more powerful but also more complicated that glob patterns.
The regular expression support is implemented using Python's
[http://docs.python.org/library/re.html|re module] and its documentation
should be consulted for more information about the syntax.
Because the backslash character (``\\``) is an escape character in
Robot Framework test data, possible backslash characters in regular
expressions need to be escaped with another backslash like ``\\\\d\\\\w+``.
Strings that may contain special characters but should be handled
as literal strings, can be escaped with the `Regexp Escape` keyword.
= Multiline string comparison =
`Should Be Equal` and `Should Be Equal As Strings` report the failures using
[http://en.wikipedia.org/wiki/Diff_utility#Unified_format|unified diff
format] if both strings have more than two lines. New in Robot Framework
2.9.1.
Example:
| ${first} = | `Catenate` | SEPARATOR=\\n | Not in second | Same | Differs | Same |
| ${second} = | `Catenate` | SEPARATOR=\\n | Same | Differs2 | Same | Not in first |
| `Should Be Equal` | ${first} | ${second} |
Results in the following error message:
| Multiline strings are different:
| --- first
| +++ second
| @@ -1,4 +1,4 @@
| -Not in second
| Same
| -Differs
| +Differs2
| Same
| +Not in first
= String representations =
Several keywords log values explicitly (e.g. `Log`) or implicitly (e.g.
`Should Be Equal` when there are failures). By default keywords log values
using "human readable" string representation, which means that strings
like ``Hello`` and numbers like ``42`` are logged as-is. Most of the time
this is the desired behavior, but there are some problems as well:
- It is not possible to see difference between different objects that
have same string representation like string ``42`` and integer ``42``.
`Should Be Equal` and some other keywords add the type information to
the error message in these cases, though.
- Non-printable characters such as the null byte are not visible.
- Trailing whitespace is not visible.
- Different newlines (``\\r\\n`` on Windows, ``\\n`` elsewhere) cannot
be separated from each others.
- There are several Unicode characters that are different but look the
same. One example is the Latin ``\u0061`` (``\\u0061``) and the Cyrillic
``\u0430`` (``\\u0430``). Error messages like ``\u0061 != \u0430`` are
not very helpful.
- Some Unicode characters can be represented using
[https://en.wikipedia.org/wiki/Unicode_equivalence|different forms].
For example, ``\xe4`` can be represented either as a single code point
``\\u00e4`` or using two code points ``\\u0061`` and ``\\u0308`` combined
together. Such forms are considered canonically equivalent, but strings
containing them are not considered equal when compared in Python. Error
messages like ``\xe4 != \u0061\u0308`` are not that helpful either.
- Containers such as lists and dictionaries are formatted into a single
line making it hard to see individual items they contain.
To overcome the above problems, some keywords such as `Log` and
`Should Be Equal` have an optional ``formatter`` argument that can be
used to configure the string representation. The supported values are
``str`` (default), ``repr``, and ``ascii`` that work similarly as
[https://docs.python.org/library/functions.html|Python built-in functions]
with same names. More detailed semantics are explained below.
The ``formatter`` argument is new in Robot Framework 3.1.2.
== str ==
Use the "human readable" string representation. Equivalent to using
``str()`` in Python 3 and ``unicode()`` in Python 2. This is the default.
== repr ==
Use the "machine readable" string representation. Similar to using
``repr()`` in Python, which means that strings like ``Hello`` are logged
like ``'Hello'``, newlines and non-printable characters are escaped like
``\\n`` and ``\\x00``, and so on. Non-ASCII characters are shown as-is
like ``\xe4`` in Python 3 and in escaped format like ``\\xe4`` in Python 2.
Use ``ascii`` to always get the escaped format.
There are also some enhancements compared to the standard ``repr()``:
- Bigger lists, dictionaries and other containers are pretty-printed so
that there is one item per row.
- On Python 2 the ``u`` prefix is omitted with Unicode strings and
the ``b`` prefix is added to byte strings.
== ascii ==
Same as using ``ascii()`` in Python 3 or ``repr()`` in Python 2 where
``ascii()`` does not exist. Similar to using ``repr`` explained above
but with the following differences:
- On Python 3 non-ASCII characters are escaped like ``\\xe4`` instead of
showing them as-is like ``\xe4``. This makes it easier to see differences
between Unicode characters that look the same but are not equal. This
is how ``repr()`` works in Python 2.
- On Python 2 just uses the standard ``repr()`` meaning that Unicode
strings get the ``u`` prefix and no ``b`` prefix is added to byte
strings.
- Containers are not pretty-printed.
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = get_version()
class RobotNotRunningError(AttributeError):
"""Used when something cannot be done because Robot is not running.
Based on AttributeError to be backwards compatible with RF < 2.8.5.
May later be based directly on Exception, so new code should except
this exception explicitly.
"""
pass
def register_run_keyword(library, keyword, args_to_process=None,
deprecation_warning=True):
"""Registers 'run keyword' so that its arguments can be handled correctly.
*NOTE:* This API will change in RF 3.1. For more information see
https://github.com/robotframework/robotframework/issues/2190. Use with
`deprecation_warning=False` to avoid related deprecation warnings.
1) Why is this method needed
Keywords running other keywords internally (normally using `Run Keyword`
or some variants of it in BuiltIn) must have the arguments meant to the
internally executed keyword handled specially to prevent processing them
twice. This is done ONLY for keywords registered using this method.
If the register keyword has same name as any keyword from Robot Framework
standard libraries, it can be used without getting warnings. Normally
there is a warning in such cases unless the keyword is used in long
format (e.g. MyLib.Keyword).
Keywords executed by registered run keywords can be tested in dry-run mode
if they have 'name' argument which takes the name of the executed keyword.
2) How to use this method
`library` is the name of the library where the registered keyword is
implemented.
`keyword` can be either a function or method implementing the
keyword, or name of the implemented keyword as a string.
`args_to_process` is needed when `keyword` is given as a string, and it
defines how many of the arguments to the registered keyword must be
processed normally. When `keyword` is a method or function, this
information is got directly from it so that varargs (those specified with
syntax '*args') are not processed but others are.
3) Examples
from robotide.lib.robot.libraries.BuiltIn import BuiltIn, register_run_keyword
def my_run_keyword(name, *args):
# do something
return BuiltIn().run_keyword(name, *args)
# Either one of these works
register_run_keyword(__name__, my_run_keyword)
register_run_keyword(__name__, 'My Run Keyword', 1)
-------------
from robotide.lib.robot.libraries.BuiltIn import BuiltIn, register_run_keyword
class MyLibrary:
def my_run_keyword_if(self, expression, name, *args):
# do something
return BuiltIn().run_keyword_if(expression, name, *args)
# Either one of these works
register_run_keyword('MyLibrary', MyLibrary.my_run_keyword_if)
register_run_keyword('MyLibrary', 'my_run_keyword_if', 2)
"""
RUN_KW_REGISTER.register_run_keyword(library, keyword, args_to_process,
deprecation_warning) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libraries/BuiltIn.py | 0.645679 | 0.292911 | BuiltIn.py | pypi |
import copy
import re
import os
try:
from lxml import etree as lxml_etree
except ImportError:
lxml_etree = None
from robotide.lib.robot.api import logger
from robotide.lib.robot.libraries.BuiltIn import BuiltIn
from robotide.lib.robot.utils import (asserts, ET, ETSource, is_falsy, is_string, is_truthy,
plural_or_not as s)
from robotide.lib.robot.version import get_version
should_be_equal = asserts.assert_equal
should_match = BuiltIn().should_match
class XML(object):
"""Robot Framework test library for verifying and modifying XML documents.
As the name implies, _XML_ is a test library for verifying contents of XML
files. In practice it is a pretty thin wrapper on top of Python's
[http://docs.python.org/library/xml.etree.elementtree.html|ElementTree XML API].
The library has the following main usages:
- Parsing an XML file, or a string containing XML, into an XML element
structure and finding certain elements from it for for further analysis
(e.g. `Parse XML` and `Get Element` keywords).
- Getting text or attributes of elements
(e.g. `Get Element Text` and `Get Element Attribute`).
- Directly verifying text, attributes, or whole elements
(e.g `Element Text Should Be` and `Elements Should Be Equal`).
- Modifying XML and saving it (e.g. `Set Element Text`, `Add Element`
and `Save XML`).
== Table of contents ==
- `Parsing XML`
- `Using lxml`
- `Example`
- `Finding elements with xpath`
- `Element attributes`
- `Handling XML namespaces`
- `Boolean arguments`
- `Pattern matching`
- `Shortcuts`
- `Keywords`
= Parsing XML =
XML can be parsed into an element structure using `Parse XML` keyword.
It accepts both paths to XML files and strings that contain XML. The
keyword returns the root element of the structure, which then contains
other elements as its children and their children. Possible comments and
processing instructions in the source XML are removed.
XML is not validated during parsing even if has a schema defined. How
possible doctype elements are handled otherwise depends on the used XML
module and on the platform. The standard ElementTree strips doctypes
altogether but when `using lxml` they are preserved when XML is saved.
The element structure returned by `Parse XML`, as well as elements
returned by keywords such as `Get Element`, can be used as the ``source``
argument with other keywords. In addition to an already parsed XML
structure, other keywords also accept paths to XML files and strings
containing XML similarly as `Parse XML`. Notice that keywords that modify
XML do not write those changes back to disk even if the source would be
given as a path to a file. Changes must always saved explicitly using
`Save XML` keyword.
When the source is given as a path to a file, the forward slash character
(``/``) can be used as the path separator regardless the operating system.
On Windows also the backslash works, but it the test data it needs to be
escaped by doubling it (``\\\\``). Using the built-in variable ``${/}``
naturally works too.
= Using lxml =
By default this library uses Python's standard
[http://docs.python.org/library/xml.etree.elementtree.html|ElementTree]
module for parsing XML, but it can be configured to use
[http://lxml.de|lxml] module instead when `importing` the library.
The resulting element structure has same API regardless which module
is used for parsing.
The main benefits of using lxml is that it supports richer xpath syntax
than the standard ElementTree and enables using `Evaluate Xpath` keyword.
It also preserves the doctype and possible namespace prefixes saving XML.
= Example =
The following simple example demonstrates parsing XML and verifying its
contents both using keywords in this library and in _BuiltIn_ and
_Collections_ libraries. How to use xpath expressions to find elements
and what attributes the returned elements contain are discussed, with
more examples, in `Finding elements with xpath` and `Element attributes`
sections.
In this example, as well as in many other examples in this documentation,
``${XML}`` refers to the following example XML document. In practice
``${XML}`` could either be a path to an XML file or it could contain the XML
itself.
| <example>
| <first id="1">text</first>
| <second id="2">
| <child/>
| </second>
| <third>
| <child>more text</child>
| <second id="child"/>
| <child><grandchild/></child>
| </third>
| <html>
| <p>
| Text with <b>bold</b> and <i>italics</i>.
| </p>
| </html>
| </example>
| ${root} = | `Parse XML` | ${XML} | | |
| `Should Be Equal` | ${root.tag} | example | | |
| ${first} = | `Get Element` | ${root} | first | |
| `Should Be Equal` | ${first.text} | text | | |
| `Dictionary Should Contain Key` | ${first.attrib} | id | |
| `Element Text Should Be` | ${first} | text | | |
| `Element Attribute Should Be` | ${first} | id | 1 | |
| `Element Attribute Should Be` | ${root} | id | 1 | xpath=first |
| `Element Attribute Should Be` | ${XML} | id | 1 | xpath=first |
Notice that in the example three last lines are equivalent. Which one to
use in practice depends on which other elements you need to get or verify.
If you only need to do one verification, using the last line alone would
suffice. If more verifications are needed, parsing the XML with `Parse XML`
only once would be more efficient.
= Finding elements with xpath =
ElementTree, and thus also this library, supports finding elements using
xpath expressions. ElementTree does not, however, support the full xpath
standard. The supported xpath syntax is explained below and
[https://docs.python.org/library/xml.etree.elementtree.html#xpath-support|
ElementTree documentation] provides more details. In the examples
``${XML}`` refers to the same XML structure as in the earlier example.
If lxml support is enabled when `importing` the library, the whole
[http://www.w3.org/TR/xpath/|xpath 1.0 standard] is supported.
That includes everything listed below but also lot of other useful
constructs.
== Tag names ==
When just a single tag name is used, xpath matches all direct child
elements that have that tag name.
| ${elem} = | `Get Element` | ${XML} | third |
| `Should Be Equal` | ${elem.tag} | third | |
| @{children} = | `Get Elements` | ${elem} | child |
| `Length Should Be` | ${children} | 2 | |
== Paths ==
Paths are created by combining tag names with a forward slash (``/``). For
example, ``parent/child`` matches all ``child`` elements under ``parent``
element. Notice that if there are multiple ``parent`` elements that all
have ``child`` elements, ``parent/child`` xpath will match all these
``child`` elements.
| ${elem} = | `Get Element` | ${XML} | second/child |
| `Should Be Equal` | ${elem.tag} | child | |
| ${elem} = | `Get Element` | ${XML} | third/child/grandchild |
| `Should Be Equal` | ${elem.tag} | grandchild | |
== Wildcards ==
An asterisk (``*``) can be used in paths instead of a tag name to denote
any element.
| @{children} = | `Get Elements` | ${XML} | */child |
| `Length Should Be` | ${children} | 3 | |
== Current element ==
The current element is denoted with a dot (``.``). Normally the current
element is implicit and does not need to be included in the xpath.
== Parent element ==
The parent element of another element is denoted with two dots (``..``).
Notice that it is not possible to refer to the parent of the current
element.
| ${elem} = | `Get Element` | ${XML} | */second/.. |
| `Should Be Equal` | ${elem.tag} | third | |
== Search all sub elements ==
Two forward slashes (``//``) mean that all sub elements, not only the
direct children, are searched. If the search is started from the current
element, an explicit dot is required.
| @{elements} = | `Get Elements` | ${XML} | .//second |
| `Length Should Be` | ${elements} | 2 | |
| ${b} = | `Get Element` | ${XML} | html//b |
| `Should Be Equal` | ${b.text} | bold | |
== Predicates ==
Predicates allow selecting elements using also other criteria than tag
names, for example, attributes or position. They are specified after the
normal tag name or path using syntax ``path[predicate]``. The path can have
wildcards and other special syntax explained earlier. What predicates
the standard ElementTree supports is explained in the table below.
| = Predicate = | = Matches = | = Example = |
| @attrib | Elements with attribute ``attrib``. | second[@id] |
| @attrib="value" | Elements with attribute ``attrib`` having value ``value``. | *[@id="2"] |
| position | Elements at the specified position. Position can be an integer (starting from 1), expression ``last()``, or relative expression like ``last() - 1``. | third/child[1] |
| tag | Elements with a child element named ``tag``. | third/child[grandchild] |
Predicates can also be stacked like ``path[predicate1][predicate2]``.
A limitation is that possible position predicate must always be first.
= Element attributes =
All keywords returning elements, such as `Parse XML`, and `Get Element`,
return ElementTree's
[http://docs.python.org/library/xml.etree.elementtree.html#element-objects|Element objects].
These elements can be used as inputs for other keywords, but they also
contain several useful attributes that can be accessed directly using
the extended variable syntax.
The attributes that are both useful and convenient to use in the test
data are explained below. Also other attributes, including methods, can
be accessed, but that is typically better to do in custom libraries than
directly in the test data.
The examples use the same ``${XML}`` structure as the earlier examples.
== tag ==
The tag of the element.
| ${root} = | `Parse XML` | ${XML} |
| `Should Be Equal` | ${root.tag} | example |
== text ==
The text that the element contains or Python ``None`` if the element has no
text. Notice that the text _does not_ contain texts of possible child
elements nor text after or between children. Notice also that in XML
whitespace is significant, so the text contains also possible indentation
and newlines. To get also text of the possible children, optionally
whitespace normalized, use `Get Element Text` keyword.
| ${1st} = | `Get Element` | ${XML} | first |
| `Should Be Equal` | ${1st.text} | text | |
| ${2nd} = | `Get Element` | ${XML} | second/child |
| `Should Be Equal` | ${2nd.text} | ${NONE} | |
| ${p} = | `Get Element` | ${XML} | html/p |
| `Should Be Equal` | ${p.text} | \\n${SPACE*6}Text with${SPACE} |
== tail ==
The text after the element before the next opening or closing tag. Python
``None`` if the element has no tail. Similarly as with ``text``, also
``tail`` contains possible indentation and newlines.
| ${b} = | `Get Element` | ${XML} | html/p/b |
| `Should Be Equal` | ${b.tail} | ${SPACE}and${SPACE} |
== attrib ==
A Python dictionary containing attributes of the element.
| ${2nd} = | `Get Element` | ${XML} | second |
| `Should Be Equal` | ${2nd.attrib['id']} | 2 | |
| ${3rd} = | `Get Element` | ${XML} | third |
| `Should Be Empty` | ${3rd.attrib} | | |
= Handling XML namespaces =
ElementTree and lxml handle possible namespaces in XML documents by adding
the namespace URI to tag names in so called Clark Notation. That is
inconvenient especially with xpaths, and by default this library strips
those namespaces away and moves them to ``xmlns`` attribute instead. That
can be avoided by passing ``keep_clark_notation`` argument to `Parse XML`
keyword. Alternatively `Parse XML` supports stripping namespace information
altogether by using ``strip_namespaces`` argument. The pros and cons of
different approaches are discussed in more detail below.
== How ElementTree handles namespaces ==
If an XML document has namespaces, ElementTree adds namespace information
to tag names in [http://www.jclark.com/xml/xmlns.htm|Clark Notation]
(e.g. ``{http://ns.uri}tag``) and removes original ``xmlns`` attributes.
This is done both with default namespaces and with namespaces with a prefix.
How it works in practice is illustrated by the following example, where
``${NS}`` variable contains this XML document:
| <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
| xmlns="http://www.w3.org/1999/xhtml">
| <xsl:template match="/">
| <html></html>
| </xsl:template>
| </xsl:stylesheet>
| ${root} = | `Parse XML` | ${NS} | keep_clark_notation=yes |
| `Should Be Equal` | ${root.tag} | {http://www.w3.org/1999/XSL/Transform}stylesheet |
| `Element Should Exist` | ${root} | {http://www.w3.org/1999/XSL/Transform}template/{http://www.w3.org/1999/xhtml}html |
| `Should Be Empty` | ${root.attrib} |
As you can see, including the namespace URI in tag names makes xpaths
really long and complex.
If you save the XML, ElementTree moves namespace information back to
``xmlns`` attributes. Unfortunately it does not restore the original
prefixes:
| <ns0:stylesheet xmlns:ns0="http://www.w3.org/1999/XSL/Transform">
| <ns0:template match="/">
| <ns1:html xmlns:ns1="http://www.w3.org/1999/xhtml"></ns1:html>
| </ns0:template>
| </ns0:stylesheet>
The resulting output is semantically same as the original, but mangling
prefixes like this may still not be desirable. Notice also that the actual
output depends slightly on ElementTree version.
== Default namespace handling ==
Because the way ElementTree handles namespaces makes xpaths so complicated,
this library, by default, strips namespaces from tag names and moves that
information back to ``xmlns`` attributes. How this works in practice is
shown by the example below, where ``${NS}`` variable contains the same XML
document as in the previous example.
| ${root} = | `Parse XML` | ${NS} |
| `Should Be Equal` | ${root.tag} | stylesheet |
| `Element Should Exist` | ${root} | template/html |
| `Element Attribute Should Be` | ${root} | xmlns | http://www.w3.org/1999/XSL/Transform |
| `Element Attribute Should Be` | ${root} | xmlns | http://www.w3.org/1999/xhtml | xpath=template/html |
Now that tags do not contain namespace information, xpaths are simple again.
A minor limitation of this approach is that namespace prefixes are lost.
As a result the saved output is not exactly same as the original one in
this case either:
| <stylesheet xmlns="http://www.w3.org/1999/XSL/Transform">
| <template match="/">
| <html xmlns="http://www.w3.org/1999/xhtml"></html>
| </template>
| </stylesheet>
Also this output is semantically same as the original. If the original XML
had only default namespaces, the output would also look identical.
== Namespaces when using lxml ==
This library handles namespaces same way both when `using lxml` and when
not using it. There are, however, differences how lxml internally handles
namespaces compared to the standard ElementTree. The main difference is
that lxml stores information about namespace prefixes and they are thus
preserved if XML is saved. Another visible difference is that lxml includes
namespace information in child elements got with `Get Element` if the
parent element has namespaces.
== Stripping namespaces altogether ==
Because namespaces often add unnecessary complexity, `Parse XML` supports
stripping them altogether by using ``strip_namespaces=True``. When this
option is enabled, namespaces are not shown anywhere nor are they included
if XML is saved.
== Attribute namespaces ==
Attributes in XML documents are, by default, in the same namespaces as
the element they belong to. It is possible to use different namespaces
by using prefixes, but this is pretty rare.
If an attribute has a namespace prefix, ElementTree will replace it with
Clark Notation the same way it handles elements. Because stripping
namespaces from attributes could cause attribute conflicts, this library
does not handle attribute namespaces at all. Thus the following example
works the same way regardless how namespaces are handled.
| ${root} = | `Parse XML` | <root id="1" ns:id="2" xmlns:ns="http://my.ns"/> |
| `Element Attribute Should Be` | ${root} | id | 1 |
| `Element Attribute Should Be` | ${root} | {http://my.ns}id | 2 |
= 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. 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:
| `Parse XML` | ${XML} | keep_clark_notation=True | # Strings are generally true. |
| `Parse XML` | ${XML} | keep_clark_notation=yes | # Same as the above. |
| `Parse XML` | ${XML} | keep_clark_notation=${TRUE} | # Python ``True`` is true. |
| `Parse XML` | ${XML} | keep_clark_notation=${42} | # Numbers other than 0 are true. |
False examples:
| `Parse XML` | ${XML} | keep_clark_notation=False | # String ``false`` is false. |
| `Parse XML` | ${XML} | keep_clark_notation=no | # Also string ``no`` is false. |
| `Parse XML` | ${XML} | keep_clark_notation=${EMPTY} | # Empty string is false. |
| `Parse XML` | ${XML} | keep_clark_notation=${FALSE} | # Python ``False`` is false. |
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.
== Pattern matching ==
Some keywords, for example `Elements Should Match`, support so called
[http://en.wikipedia.org/wiki/Glob_(programming)|glob patterns] where:
| ``*`` | matches any string, even an empty string |
| ``?`` | matches any single character |
| ``[chars]`` | matches one character in the bracket |
| ``[!chars]`` | matches one character not in the bracket |
| ``[a-z]`` | matches one character from the range in the bracket |
| ``[!a-z]`` | matches one character not from the range in the bracket |
Unlike with glob patterns normally, path separator characters ``/`` and
``\\`` and the newline character ``\\n`` are matches by the above
wildcards.
Support for brackets like ``[abc]`` and ``[!a-z]`` is new in
Robot Framework 3.1
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = get_version()
_xml_declaration = re.compile('^<\?xml .*\?>')
def __init__(self, use_lxml=False):
"""Import library with optionally lxml mode enabled.
By default this library uses Python's standard
[http://docs.python.org/library/xml.etree.elementtree.html|ElementTree]
module for parsing XML. If ``use_lxml`` argument is given a true value
(see `Boolean arguments`), the library will use [http://lxml.de|lxml]
module instead. See `Using lxml` section for benefits provided by lxml.
Using lxml requires that the lxml module is installed on the system.
If lxml mode is enabled but the module is not installed, this library
will emit a warning and revert back to using the standard ElementTree.
"""
use_lxml = is_truthy(use_lxml)
if use_lxml and lxml_etree:
self.etree = lxml_etree
self.modern_etree = True
self.lxml_etree = True
else:
self.etree = ET
self.modern_etree = ET.VERSION >= '1.3'
self.lxml_etree = False
if use_lxml and not lxml_etree:
logger.warn('XML library reverted to use standard ElementTree '
'because lxml module is not installed.')
self._ns_stripper = NameSpaceStripper(self.etree, self.lxml_etree)
def parse_xml(self, source, keep_clark_notation=False, strip_namespaces=False):
"""Parses the given XML file or string into an element structure.
The ``source`` can either be a path to an XML file or a string
containing XML. In both cases the XML is parsed into ElementTree
[http://docs.python.org/library/xml.etree.elementtree.html#element-objects|element structure]
and the root element is returned. Possible comments and processing
instructions in the source XML are removed.
As discussed in `Handling XML namespaces` section, this keyword, by
default, removes namespace information ElementTree has added to tag
names and moves it into ``xmlns`` attributes. This typically eases
handling XML documents with namespaces considerably. If you do not
want that to happen, or want to avoid the small overhead of going
through the element structure when your XML does not have namespaces,
you can disable this feature by giving ``keep_clark_notation`` argument
a true value (see `Boolean arguments`).
If you want to strip namespace information altogether so that it is
not included even if XML is saved, you can give a true value to
``strip_namespaces`` argument. This functionality is new in Robot
Framework 3.0.2.
Examples:
| ${root} = | Parse XML | <root><child/></root> |
| ${xml} = | Parse XML | ${CURDIR}/test.xml | keep_clark_notation=True |
| ${xml} = | Parse XML | ${CURDIR}/test.xml | strip_namespaces=True |
Use `Get Element` keyword if you want to get a certain element and not
the whole structure. See `Parsing XML` section for more details and
examples.
"""
with ETSource(source) as source:
tree = self.etree.parse(source)
if self.lxml_etree:
strip = (lxml_etree.Comment, lxml_etree.ProcessingInstruction)
lxml_etree.strip_elements(tree, *strip, **dict(with_tail=False))
root = tree.getroot()
if not is_truthy(keep_clark_notation):
self._ns_stripper.strip(root, preserve=is_falsy(strip_namespaces))
return root
def get_element(self, source, xpath='.'):
"""Returns an element in the ``source`` matching the ``xpath``.
The ``source`` can be a path to an XML file, a string containing XML, or
an already parsed XML element. The ``xpath`` specifies which element to
find. See the `introduction` for more details about both the possible
sources and the supported xpath syntax.
The keyword fails if more, or less, than one element matches the
``xpath``. Use `Get Elements` if you want all matching elements to be
returned.
Examples using ``${XML}`` structure from `Example`:
| ${element} = | Get Element | ${XML} | second |
| ${child} = | Get Element | ${element} | child |
`Parse XML` is recommended for parsing XML when the whole structure
is needed. It must be used if there is a need to configure how XML
namespaces are handled.
Many other keywords use this keyword internally, and keywords modifying
XML are typically documented to both to modify the given source and
to return it. Modifying the source does not apply if the source is
given as a string. The XML structure parsed based on the string and
then modified is nevertheless returned.
"""
elements = self.get_elements(source, xpath)
if len(elements) != 1:
self._raise_wrong_number_of_matches(len(elements), xpath)
return elements[0]
def _raise_wrong_number_of_matches(self, count, xpath, message=None):
if not message:
message = self._wrong_number_of_matches(count, xpath)
raise AssertionError(message)
def _wrong_number_of_matches(self, count, xpath):
if not count:
return "No element matching '%s' found." % xpath
if count == 1:
return "One element matching '%s' found." % xpath
return "Multiple elements (%d) matching '%s' found." % (count, xpath)
def get_elements(self, source, xpath):
"""Returns a list of elements in the ``source`` matching the ``xpath``.
The ``source`` can be a path to an XML file, a string containing XML, or
an already parsed XML element. The ``xpath`` specifies which element to
find. See the `introduction` for more details.
Elements matching the ``xpath`` are returned as a list. If no elements
match, an empty list is returned. Use `Get Element` if you want to get
exactly one match.
Examples using ``${XML}`` structure from `Example`:
| ${children} = | Get Elements | ${XML} | third/child |
| Length Should Be | ${children} | 2 | |
| ${children} = | Get Elements | ${XML} | first/child |
| Should Be Empty | ${children} | | |
"""
if is_string(source):
source = self.parse_xml(source)
finder = ElementFinder(self.etree, self.modern_etree, self.lxml_etree)
return finder.find_all(source, xpath)
def get_child_elements(self, source, xpath='.'):
"""Returns the child elements of the specified element as a list.
The element whose children to return is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword.
All the direct child elements of the specified element are returned.
If the element has no children, an empty list is returned.
Examples using ``${XML}`` structure from `Example`:
| ${children} = | Get Child Elements | ${XML} | |
| Length Should Be | ${children} | 4 | |
| ${children} = | Get Child Elements | ${XML} | xpath=first |
| Should Be Empty | ${children} | | |
"""
return list(self.get_element(source, xpath))
def get_element_count(self, source, xpath='.'):
"""Returns and logs how many elements the given ``xpath`` matches.
Arguments ``source`` and ``xpath`` have exactly the same semantics as
with `Get Elements` keyword that this keyword uses internally.
See also `Element Should Exist` and `Element Should Not Exist`.
"""
count = len(self.get_elements(source, xpath))
logger.info("%d element%s matched '%s'." % (count, s(count), xpath))
return count
def element_should_exist(self, source, xpath='.', message=None):
"""Verifies that one or more element match the given ``xpath``.
Arguments ``source`` and ``xpath`` have exactly the same semantics as
with `Get Elements` keyword. Keyword passes if the ``xpath`` matches
one or more elements in the ``source``. The default error message can
be overridden with the ``message`` argument.
See also `Element Should Not Exist` as well as `Get Element Count`
that this keyword uses internally.
"""
count = self.get_element_count(source, xpath)
if not count:
self._raise_wrong_number_of_matches(count, xpath, message)
def element_should_not_exist(self, source, xpath='.', message=None):
"""Verifies that no element match the given ``xpath``.
Arguments ``source`` and ``xpath`` have exactly the same semantics as
with `Get Elements` keyword. Keyword fails if the ``xpath`` matches any
element in the ``source``. The default error message can be overridden
with the ``message`` argument.
See also `Element Should Exist` as well as `Get Element Count`
that this keyword uses internally.
"""
count = self.get_element_count(source, xpath)
if count:
self._raise_wrong_number_of_matches(count, xpath, message)
def get_element_text(self, source, xpath='.', normalize_whitespace=False):
"""Returns all text of the element, possibly whitespace normalized.
The element whose text to return is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword.
This keyword returns all the text of the specified element, including
all the text its children and grandchildren contain. If the element
has no text, an empty string is returned. The returned text is thus not
always the same as the `text` attribute of the element.
By default all whitespace, including newlines and indentation, inside
the element is returned as-is. If ``normalize_whitespace`` is given
a true value (see `Boolean arguments`), then leading and trailing
whitespace is stripped, newlines and tabs converted to spaces, and
multiple spaces collapsed into one. This is especially useful when
dealing with HTML data.
Examples using ``${XML}`` structure from `Example`:
| ${text} = | Get Element Text | ${XML} | first |
| Should Be Equal | ${text} | text | |
| ${text} = | Get Element Text | ${XML} | second/child |
| Should Be Empty | ${text} | | |
| ${paragraph} = | Get Element | ${XML} | html/p |
| ${text} = | Get Element Text | ${paragraph} | normalize_whitespace=yes |
| Should Be Equal | ${text} | Text with bold and italics. |
See also `Get Elements Texts`, `Element Text Should Be` and
`Element Text Should Match`.
"""
element = self.get_element(source, xpath)
text = ''.join(self._yield_texts(element))
if is_truthy(normalize_whitespace):
text = self._normalize_whitespace(text)
return text
def _yield_texts(self, element, top=True):
if element.text:
yield element.text
for child in element:
for text in self._yield_texts(child, top=False):
yield text
if element.tail and not top:
yield element.tail
def _normalize_whitespace(self, text):
return ' '.join(text.split())
def get_elements_texts(self, source, xpath, normalize_whitespace=False):
"""Returns text of all elements matching ``xpath`` as a list.
The elements whose text to return is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Elements`
keyword.
The text of the matched elements is returned using the same logic
as with `Get Element Text`. This includes optional whitespace
normalization using the ``normalize_whitespace`` option.
Examples using ``${XML}`` structure from `Example`:
| @{texts} = | Get Elements Texts | ${XML} | third/child |
| Length Should Be | ${texts} | 2 | |
| Should Be Equal | @{texts}[0] | more text | |
| Should Be Equal | @{texts}[1] | ${EMPTY} | |
"""
return [self.get_element_text(elem, normalize_whitespace=normalize_whitespace)
for elem in self.get_elements(source, xpath)]
def element_text_should_be(self, source, expected, xpath='.',
normalize_whitespace=False, message=None):
"""Verifies that the text of the specified element is ``expected``.
The element whose text is verified is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword.
The text to verify is got from the specified element using the same
logic as with `Get Element Text`. This includes optional whitespace
normalization using the ``normalize_whitespace`` option.
The keyword passes if the text of the element is equal to the
``expected`` value, and otherwise it fails. The default error message
can be overridden with the ``message`` argument. Use `Element Text
Should Match` to verify the text against a pattern instead of an exact
value.
Examples using ``${XML}`` structure from `Example`:
| Element Text Should Be | ${XML} | text | xpath=first |
| Element Text Should Be | ${XML} | ${EMPTY} | xpath=second/child |
| ${paragraph} = | Get Element | ${XML} | xpath=html/p |
| Element Text Should Be | ${paragraph} | Text with bold and italics. | normalize_whitespace=yes |
"""
text = self.get_element_text(source, xpath, normalize_whitespace)
should_be_equal(text, expected, message, values=False)
def element_text_should_match(self, source, pattern, xpath='.',
normalize_whitespace=False, message=None):
"""Verifies that the text of the specified element matches ``expected``.
This keyword works exactly like `Element Text Should Be` except that
the expected value can be given as a pattern that the text of the
element must match.
Pattern matching is similar as matching files in a shell with
``*``, ``?`` and ``[chars]`` acting as wildcards. See the
`Pattern matching` section for more information.
Examples using ``${XML}`` structure from `Example`:
| Element Text Should Match | ${XML} | t??? | xpath=first |
| ${paragraph} = | Get Element | ${XML} | xpath=html/p |
| Element Text Should Match | ${paragraph} | Text with * and *. | normalize_whitespace=yes |
"""
text = self.get_element_text(source, xpath, normalize_whitespace)
should_match(text, pattern, message, values=False)
def get_element_attribute(self, source, name, xpath='.', default=None):
"""Returns the named attribute of the specified element.
The element whose attribute to return is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword.
The value of the attribute ``name`` of the specified element is returned.
If the element does not have such element, the ``default`` value is
returned instead.
Examples using ``${XML}`` structure from `Example`:
| ${attribute} = | Get Element Attribute | ${XML} | id | xpath=first |
| Should Be Equal | ${attribute} | 1 | | |
| ${attribute} = | Get Element Attribute | ${XML} | xx | xpath=first | default=value |
| Should Be Equal | ${attribute} | value | | |
See also `Get Element Attributes`, `Element Attribute Should Be`,
`Element Attribute Should Match` and `Element Should Not Have Attribute`.
"""
return self.get_element(source, xpath).get(name, default)
def get_element_attributes(self, source, xpath='.'):
"""Returns all attributes of the specified element.
The element whose attributes to return is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword.
Attributes are returned as a Python dictionary. It is a copy of the
original attributes so modifying it has no effect on the XML structure.
Examples using ``${XML}`` structure from `Example`:
| ${attributes} = | Get Element Attributes | ${XML} | first |
| Dictionary Should Contain Key | ${attributes} | id | |
| ${attributes} = | Get Element Attributes | ${XML} | third |
| Should Be Empty | ${attributes} | | |
Use `Get Element Attribute` to get the value of a single attribute.
"""
return dict(self.get_element(source, xpath).attrib)
def element_attribute_should_be(self, source, name, expected, xpath='.',
message=None):
"""Verifies that the specified attribute is ``expected``.
The element whose attribute is verified is specified using ``source``
and ``xpath``. They have exactly the same semantics as with
`Get Element` keyword.
The keyword passes if the attribute ``name`` of the element is equal to
the ``expected`` value, and otherwise it fails. The default error
message can be overridden with the ``message`` argument.
To test that the element does not have a certain attribute, Python
``None`` (i.e. variable ``${NONE}``) can be used as the expected value.
A cleaner alternative is using `Element Should Not Have Attribute`.
Examples using ``${XML}`` structure from `Example`:
| Element Attribute Should Be | ${XML} | id | 1 | xpath=first |
| Element Attribute Should Be | ${XML} | id | ${NONE} | |
See also `Element Attribute Should Match` and `Get Element Attribute`.
"""
attr = self.get_element_attribute(source, name, xpath)
should_be_equal(attr, expected, message, values=False)
def element_attribute_should_match(self, source, name, pattern, xpath='.',
message=None):
"""Verifies that the specified attribute matches ``expected``.
This keyword works exactly like `Element Attribute Should Be` except
that the expected value can be given as a pattern that the attribute of
the element must match.
Pattern matching is similar as matching files in a shell with
``*``, ``?`` and ``[chars]`` acting as wildcards. See the
`Pattern matching` section for more information.
Examples using ``${XML}`` structure from `Example`:
| Element Attribute Should Match | ${XML} | id | ? | xpath=first |
| Element Attribute Should Match | ${XML} | id | c*d | xpath=third/second |
"""
attr = self.get_element_attribute(source, name, xpath)
if attr is None:
raise AssertionError("Attribute '%s' does not exist." % name)
should_match(attr, pattern, message, values=False)
def element_should_not_have_attribute(self, source, name, xpath='.', message=None):
"""Verifies that the specified element does not have attribute ``name``.
The element whose attribute is verified is specified using ``source``
and ``xpath``. They have exactly the same semantics as with
`Get Element` keyword.
The keyword fails if the specified element has attribute ``name``. The
default error message can be overridden with the ``message`` argument.
Examples using ``${XML}`` structure from `Example`:
| Element Should Not Have Attribute | ${XML} | id |
| Element Should Not Have Attribute | ${XML} | xxx | xpath=first |
See also `Get Element Attribute`, `Get Element Attributes`,
`Element Text Should Be` and `Element Text Should Match`.
"""
attr = self.get_element_attribute(source, name, xpath)
if attr is not None:
raise AssertionError(message or "Attribute '%s' exists and "
"has value '%s'." % (name, attr))
def elements_should_be_equal(self, source, expected, exclude_children=False,
normalize_whitespace=False):
"""Verifies that the given ``source`` element is equal to ``expected``.
Both ``source`` and ``expected`` can be given as a path to an XML file,
as a string containing XML, or as an already parsed XML element
structure. See `introduction` for more information about parsing XML in
general.
The keyword passes if the ``source`` element and ``expected`` element
are equal. This includes testing the tag names, texts, and attributes
of the elements. By default also child elements are verified the same
way, but this can be disabled by setting ``exclude_children`` to a
true value (see `Boolean arguments`).
All texts inside the given elements are verified, but possible text
outside them is not. By default texts must match exactly, but setting
``normalize_whitespace`` to a true value makes text verification
independent on newlines, tabs, and the amount of spaces. For more
details about handling text see `Get Element Text` keyword and
discussion about elements' `text` and `tail` attributes in the
`introduction`.
Examples using ``${XML}`` structure from `Example`:
| ${first} = | Get Element | ${XML} | first |
| Elements Should Be Equal | ${first} | <first id="1">text</first> |
| ${p} = | Get Element | ${XML} | html/p |
| Elements Should Be Equal | ${p} | <p>Text with <b>bold</b> and <i>italics</i>.</p> | normalize_whitespace=yes |
| Elements Should Be Equal | ${p} | <p>Text with</p> | exclude | normalize |
The last example may look a bit strange because the ``<p>`` element
only has text ``Text with``. The reason is that rest of the text
inside ``<p>`` actually belongs to the child elements. This includes
the ``.`` at the end that is the `tail` text of the ``<i>`` element.
See also `Elements Should Match`.
"""
self._compare_elements(source, expected, should_be_equal,
exclude_children, normalize_whitespace)
def elements_should_match(self, source, expected, exclude_children=False,
normalize_whitespace=False):
"""Verifies that the given ``source`` element matches ``expected``.
This keyword works exactly like `Elements Should Be Equal` except that
texts and attribute values in the expected value can be given as
patterns.
Pattern matching is similar as matching files in a shell with
``*``, ``?`` and ``[chars]`` acting as wildcards. See the
`Pattern matching` section for more information.
Examples using ``${XML}`` structure from `Example`:
| ${first} = | Get Element | ${XML} | first |
| Elements Should Match | ${first} | <first id="?">*</first> |
See `Elements Should Be Equal` for more examples.
"""
self._compare_elements(source, expected, should_match,
exclude_children, normalize_whitespace)
def _compare_elements(self, source, expected, comparator, exclude_children,
normalize_whitespace):
normalizer = self._normalize_whitespace \
if is_truthy(normalize_whitespace) else None
comparator = ElementComparator(comparator, normalizer, exclude_children)
comparator.compare(self.get_element(source), self.get_element(expected))
def set_element_tag(self, source, tag, xpath='.'):
"""Sets the tag of the specified element.
The element whose tag to set is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword. The resulting XML structure is returned, and if the ``source``
is an already parsed XML structure, it is also modified in place.
Examples using ``${XML}`` structure from `Example`:
| Set Element Tag | ${XML} | newTag |
| Should Be Equal | ${XML.tag} | newTag |
| Set Element Tag | ${XML} | xxx | xpath=second/child |
| Element Should Exist | ${XML} | second/xxx |
| Element Should Not Exist | ${XML} | second/child |
Can only set the tag of a single element. Use `Set Elements Tag` to set
the tag of multiple elements in one call.
"""
source = self.get_element(source)
self.get_element(source, xpath).tag = tag
return source
def set_elements_tag(self, source, tag, xpath='.'):
"""Sets the tag of the specified elements.
Like `Set Element Tag` but sets the tag of all elements matching
the given ``xpath``.
"""
for elem in self.get_elements(source, xpath):
self.set_element_tag(elem, tag)
def set_element_text(self, source, text=None, tail=None, xpath='.'):
"""Sets text and/or tail text of the specified element.
The element whose text to set is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword. The resulting XML structure is returned, and if the ``source``
is an already parsed XML structure, it is also modified in place.
Element's text and tail text are changed only if new ``text`` and/or
``tail`` values are given. See `Element attributes` section for more
information about `text` and `tail` in general.
Examples using ``${XML}`` structure from `Example`:
| Set Element Text | ${XML} | new text | xpath=first |
| Element Text Should Be | ${XML} | new text | xpath=first |
| Set Element Text | ${XML} | tail=& | xpath=html/p/b |
| Element Text Should Be | ${XML} | Text with bold&italics. | xpath=html/p | normalize_whitespace=yes |
| Set Element Text | ${XML} | slanted | !! | xpath=html/p/i |
| Element Text Should Be | ${XML} | Text with bold&slanted!! | xpath=html/p | normalize_whitespace=yes |
Can only set the text/tail of a single element. Use `Set Elements Text`
to set the text/tail of multiple elements in one call.
"""
source = self.get_element(source)
element = self.get_element(source, xpath)
if text is not None:
element.text = text
if tail is not None:
element.tail = tail
return source
def set_elements_text(self, source, text=None, tail=None, xpath='.'):
"""Sets text and/or tail text of the specified elements.
Like `Set Element Text` but sets the text or tail of all elements
matching the given ``xpath``.
"""
for elem in self.get_elements(source, xpath):
self.set_element_text(elem, text, tail)
def set_element_attribute(self, source, name, value, xpath='.'):
"""Sets attribute ``name`` of the specified element to ``value``.
The element whose attribute to set is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword. The resulting XML structure is returned, and if the ``source``
is an already parsed XML structure, it is also modified in place.
It is possible to both set new attributes and to overwrite existing.
Use `Remove Element Attribute` or `Remove Element Attributes` for
removing them.
Examples using ``${XML}`` structure from `Example`:
| Set Element Attribute | ${XML} | attr | value |
| Element Attribute Should Be | ${XML} | attr | value |
| Set Element Attribute | ${XML} | id | new | xpath=first |
| Element Attribute Should Be | ${XML} | id | new | xpath=first |
Can only set an attribute of a single element. Use `Set Elements
Attribute` to set an attribute of multiple elements in one call.
"""
if not name:
raise RuntimeError('Attribute name can not be empty.')
source = self.get_element(source)
self.get_element(source, xpath).attrib[name] = value
return source
def set_elements_attribute(self, source, name, value, xpath='.'):
"""Sets attribute ``name`` of the specified elements to ``value``.
Like `Set Element Attribute` but sets the attribute of all elements
matching the given ``xpath``.
"""
for elem in self.get_elements(source, xpath):
self.set_element_attribute(elem, name, value)
def remove_element_attribute(self, source, name, xpath='.'):
"""Removes attribute ``name`` from the specified element.
The element whose attribute to remove is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword. The resulting XML structure is returned, and if the ``source``
is an already parsed XML structure, it is also modified in place.
It is not a failure to remove a non-existing attribute. Use `Remove
Element Attributes` to remove all attributes and `Set Element Attribute`
to set them.
Examples using ``${XML}`` structure from `Example`:
| Remove Element Attribute | ${XML} | id | xpath=first |
| Element Should Not Have Attribute | ${XML} | id | xpath=first |
Can only remove an attribute from a single element. Use `Remove Elements
Attribute` to remove an attribute of multiple elements in one call.
"""
source = self.get_element(source)
attrib = self.get_element(source, xpath).attrib
if name in attrib:
attrib.pop(name)
return source
def remove_elements_attribute(self, source, name, xpath='.'):
"""Removes attribute ``name`` from the specified elements.
Like `Remove Element Attribute` but removes the attribute of all
elements matching the given ``xpath``.
"""
for elem in self.get_elements(source, xpath):
self.remove_element_attribute(elem, name)
def remove_element_attributes(self, source, xpath='.'):
"""Removes all attributes from the specified element.
The element whose attributes to remove is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword. The resulting XML structure is returned, and if the ``source``
is an already parsed XML structure, it is also modified in place.
Use `Remove Element Attribute` to remove a single attribute and
`Set Element Attribute` to set them.
Examples using ``${XML}`` structure from `Example`:
| Remove Element Attributes | ${XML} | xpath=first |
| Element Should Not Have Attribute | ${XML} | id | xpath=first |
Can only remove attributes from a single element. Use `Remove Elements
Attributes` to remove all attributes of multiple elements in one call.
"""
source = self.get_element(source)
self.get_element(source, xpath).attrib.clear()
return source
def remove_elements_attributes(self, source, xpath='.'):
"""Removes all attributes from the specified elements.
Like `Remove Element Attributes` but removes all attributes of all
elements matching the given ``xpath``.
"""
for elem in self.get_elements(source, xpath):
self.remove_element_attributes(elem)
def add_element(self, source, element, index=None, xpath='.'):
"""Adds a child element to the specified element.
The element to whom to add the new element is specified using ``source``
and ``xpath``. They have exactly the same semantics as with `Get Element`
keyword. The resulting XML structure is returned, and if the ``source``
is an already parsed XML structure, it is also modified in place.
The ``element`` to add can be specified as a path to an XML file or
as a string containing XML, or it can be an already parsed XML element.
The element is copied before adding so modifying either the original
or the added element has no effect on the other
.
The element is added as the last child by default, but a custom index
can be used to alter the position. Indices start from zero (0 = first
position, 1 = second position, etc.), and negative numbers refer to
positions at the end (-1 = second last position, -2 = third last, etc.).
Examples using ``${XML}`` structure from `Example`:
| Add Element | ${XML} | <new id="x"><c1/></new> |
| Add Element | ${XML} | <c2/> | xpath=new |
| Add Element | ${XML} | <c3/> | index=1 | xpath=new |
| ${new} = | Get Element | ${XML} | new |
| Elements Should Be Equal | ${new} | <new id="x"><c1/><c3/><c2/></new> |
Use `Remove Element` or `Remove Elements` to remove elements.
"""
source = self.get_element(source)
parent = self.get_element(source, xpath)
element = self.copy_element(element)
if index is None:
parent.append(element)
else:
parent.insert(int(index), element)
return source
def remove_element(self, source, xpath='', remove_tail=False):
"""Removes the element matching ``xpath`` from the ``source`` structure.
The element to remove from the ``source`` is specified with ``xpath``
using the same semantics as with `Get Element` keyword. The resulting
XML structure is returned, and if the ``source`` is an already parsed
XML structure, it is also modified in place.
The keyword fails if ``xpath`` does not match exactly one element.
Use `Remove Elements` to remove all matched elements.
Element's tail text is not removed by default, but that can be changed
by giving ``remove_tail`` a true value (see `Boolean arguments`). See
`Element attributes` section for more information about `tail` in
general.
Examples using ``${XML}`` structure from `Example`:
| Remove Element | ${XML} | xpath=second |
| Element Should Not Exist | ${XML} | xpath=second |
| Remove Element | ${XML} | xpath=html/p/b | remove_tail=yes |
| Element Text Should Be | ${XML} | Text with italics. | xpath=html/p | normalize_whitespace=yes |
"""
source = self.get_element(source)
self._remove_element(source, self.get_element(source, xpath), remove_tail)
return source
def remove_elements(self, source, xpath='', remove_tail=False):
"""Removes all elements matching ``xpath`` from the ``source`` structure.
The elements to remove from the ``source`` are specified with ``xpath``
using the same semantics as with `Get Elements` keyword. The resulting
XML structure is returned, and if the ``source`` is an already parsed
XML structure, it is also modified in place.
It is not a failure if ``xpath`` matches no elements. Use `Remove
Element` to remove exactly one element.
Element's tail text is not removed by default, but that can be changed
by using ``remove_tail`` argument similarly as with `Remove Element`.
Examples using ``${XML}`` structure from `Example`:
| Remove Elements | ${XML} | xpath=*/child |
| Element Should Not Exist | ${XML} | xpath=second/child |
| Element Should Not Exist | ${XML} | xpath=third/child |
"""
source = self.get_element(source)
for element in self.get_elements(source, xpath):
self._remove_element(source, element, remove_tail)
return source
def _remove_element(self, root, element, remove_tail=False):
parent = self._find_parent(root, element)
if not is_truthy(remove_tail):
self._preserve_tail(element, parent)
parent.remove(element)
def _find_parent(self, root, element):
for parent in root.getiterator():
for child in parent:
if child is element:
return parent
raise RuntimeError('Cannot remove root element.')
def _preserve_tail(self, element, parent):
if not element.tail:
return
index = list(parent).index(element)
if index == 0:
parent.text = (parent.text or '') + element.tail
else:
sibling = parent[index-1]
sibling.tail = (sibling.tail or '') + element.tail
def clear_element(self, source, xpath='.', clear_tail=False):
"""Clears the contents of the specified element.
The element to clear is specified using ``source`` and ``xpath``. They
have exactly the same semantics as with `Get Element` keyword.
The resulting XML structure is returned, and if the ``source`` is
an already parsed XML structure, it is also modified in place.
Clearing the element means removing its text, attributes, and children.
Element's tail text is not removed by default, but that can be changed
by giving ``clear_tail`` a true value (see `Boolean arguments`). See
`Element attributes` section for more information about tail in
general.
Examples using ``${XML}`` structure from `Example`:
| Clear Element | ${XML} | xpath=first |
| ${first} = | Get Element | ${XML} | xpath=first |
| Elements Should Be Equal | ${first} | <first/> |
| Clear Element | ${XML} | xpath=html/p/b | clear_tail=yes |
| Element Text Should Be | ${XML} | Text with italics. | xpath=html/p | normalize_whitespace=yes |
| Clear Element | ${XML} |
| Elements Should Be Equal | ${XML} | <example/> |
Use `Remove Element` to remove the whole element.
"""
source = self.get_element(source)
element = self.get_element(source, xpath)
tail = element.tail
element.clear()
if not is_truthy(clear_tail):
element.tail = tail
return source
def copy_element(self, source, xpath='.'):
"""Returns a copy of the specified element.
The element to copy is specified using ``source`` and ``xpath``. They
have exactly the same semantics as with `Get Element` keyword.
If the copy or the original element is modified afterwards, the changes
have no effect on the other.
Examples using ``${XML}`` structure from `Example`:
| ${elem} = | Get Element | ${XML} | xpath=first |
| ${copy1} = | Copy Element | ${elem} |
| ${copy2} = | Copy Element | ${XML} | xpath=first |
| Set Element Text | ${XML} | new text | xpath=first |
| Set Element Attribute | ${copy1} | id | new |
| Elements Should Be Equal | ${elem} | <first id="1">new text</first> |
| Elements Should Be Equal | ${copy1} | <first id="new">text</first> |
| Elements Should Be Equal | ${copy2} | <first id="1">text</first> |
"""
return copy.deepcopy(self.get_element(source, xpath))
def element_to_string(self, source, xpath='.', encoding=None):
"""Returns the string representation of the specified element.
The element to convert to a string is specified using ``source`` and
``xpath``. They have exactly the same semantics as with `Get Element`
keyword.
By default the string is returned as Unicode. If ``encoding`` argument
is given any value, the string is returned as bytes in the specified
encoding. The resulting string never contains the XML declaration.
See also `Log Element` and `Save XML`.
"""
source = self.get_element(source, xpath)
string = self.etree.tostring(source, encoding='UTF-8').decode('UTF-8')
string = self._xml_declaration.sub('', string).strip()
if encoding:
string = string.encode(encoding)
return string
def log_element(self, source, level='INFO', xpath='.'):
"""Logs the string representation of the specified element.
The element specified with ``source`` and ``xpath`` is first converted
into a string using `Element To String` keyword internally. The
resulting string is then logged using the given ``level``.
The logged string is also returned.
"""
string = self.element_to_string(source, xpath)
logger.write(string, level)
return string
def save_xml(self, source, path, encoding='UTF-8'):
"""Saves the given element to the specified file.
The element to save is specified with ``source`` using the same
semantics as with `Get Element` keyword.
The file where the element is saved is denoted with ``path`` and the
encoding to use with ``encoding``. The resulting file always contains
the XML declaration.
The resulting XML file may not be exactly the same as the original:
- Comments and processing instructions are always stripped.
- Possible doctype and namespace prefixes are only preserved when
`using lxml`.
- Other small differences are possible depending on the ElementTree
or lxml version.
Use `Element To String` if you just need a string representation of
the element.
"""
path = os.path.abspath(path.replace('/', os.sep))
elem = self.get_element(source)
tree = self.etree.ElementTree(elem)
config = {'encoding': encoding}
if self.modern_etree:
config['xml_declaration'] = True
if self.lxml_etree:
elem = self._ns_stripper.unstrip(elem)
# https://bugs.launchpad.net/lxml/+bug/1660433
if tree.docinfo.doctype:
config['doctype'] = tree.docinfo.doctype
tree = self.etree.ElementTree(elem)
with open(path, 'wb') as output:
if 'doctype' in config:
output.write(self.etree.tostring(tree, **config))
else:
tree.write(output, **config)
logger.info('XML saved to <a href="file://%s">%s</a>.' % (path, path),
html=True)
def evaluate_xpath(self, source, expression, context='.'):
"""Evaluates the given xpath expression and returns results.
The element in which context the expression is executed is specified
using ``source`` and ``context`` arguments. They have exactly the same
semantics as ``source`` and ``xpath`` arguments have with `Get Element`
keyword.
The xpath expression to evaluate is given as ``expression`` argument.
The result of the evaluation is returned as-is.
Examples using ``${XML}`` structure from `Example`:
| ${count} = | Evaluate Xpath | ${XML} | count(third/*) |
| Should Be Equal | ${count} | ${3} |
| ${text} = | Evaluate Xpath | ${XML} | string(descendant::second[last()]/@id) |
| Should Be Equal | ${text} | child |
| ${bold} = | Evaluate Xpath | ${XML} | boolean(preceding-sibling::*[1] = 'bold') | context=html/p/i |
| Should Be Equal | ${bold} | ${True} |
This keyword works only if lxml mode is taken into use when `importing`
the library.
"""
if not self.lxml_etree:
raise RuntimeError("'Evaluate Xpath' keyword only works in lxml mode.")
return self.get_element(source, context).xpath(expression)
class NameSpaceStripper(object):
def __init__(self, etree, lxml_etree=False):
self.etree = etree
self.lxml_tree = lxml_etree
def strip(self, elem, preserve=True, current_ns=None, top=True):
if elem.tag.startswith('{') and '}' in elem.tag:
ns, elem.tag = elem.tag[1:].split('}', 1)
if preserve and ns != current_ns:
elem.attrib['xmlns'] = ns
current_ns = ns
elif current_ns:
elem.attrib['xmlns'] = ''
current_ns = None
for child in elem:
self.strip(child, preserve, current_ns, top=False)
if top and not preserve and self.lxml_tree:
self.etree.cleanup_namespaces(elem)
def unstrip(self, elem, current_ns=None, copied=False):
if not copied:
elem = copy.deepcopy(elem)
ns = elem.attrib.pop('xmlns', current_ns)
if ns:
elem.tag = '{%s}%s' % (ns, elem.tag)
for child in elem:
self.unstrip(child, ns, copied=True)
return elem
class ElementFinder(object):
def __init__(self, etree, modern=True, lxml=False):
self.etree = etree
self.modern = modern
self.lxml = lxml
def find_all(self, elem, xpath):
xpath = self._get_xpath(xpath)
if xpath == '.': # ET < 1.3 does not support '.' alone.
return [elem]
if not self.lxml:
return elem.findall(xpath)
finder = self.etree.ETXPath(xpath)
return finder(elem)
def _get_xpath(self, xpath):
if not xpath:
raise RuntimeError('No xpath given.')
if self.modern:
return xpath
try:
return str(xpath)
except UnicodeError:
if not xpath.replace('/', '').isalnum():
logger.warn('XPATHs containing non-ASCII characters and '
'other than tag names do not always work with '
'Python versions prior to 2.7. Verify results '
'manually and consider upgrading to 2.7.')
return xpath
class ElementComparator(object):
def __init__(self, comparator, normalizer=None, exclude_children=False):
self._comparator = comparator
self._normalizer = normalizer or (lambda text: text)
self._exclude_children = is_truthy(exclude_children)
def compare(self, actual, expected, location=None):
if not location:
location = Location(actual.tag)
self._compare_tags(actual, expected, location)
self._compare_attributes(actual, expected, location)
self._compare_texts(actual, expected, location)
if location.is_not_root:
self._compare_tails(actual, expected, location)
if not self._exclude_children:
self._compare_children(actual, expected, location)
def _compare_tags(self, actual, expected, location):
self._compare(actual.tag, expected.tag, 'Different tag name', location,
should_be_equal)
def _compare(self, actual, expected, message, location, comparator=None):
if location.is_not_root:
message = "%s at '%s'" % (message, location.path)
if not comparator:
comparator = self._comparator
comparator(actual, expected, message)
def _compare_attributes(self, actual, expected, location):
self._compare(sorted(actual.attrib), sorted(expected.attrib),
'Different attribute names', location, should_be_equal)
for key in actual.attrib:
self._compare(actual.attrib[key], expected.attrib[key],
"Different value for attribute '%s'" % key, location)
def _compare_texts(self, actual, expected, location):
self._compare(self._text(actual.text), self._text(expected.text),
'Different text', location)
def _text(self, text):
return self._normalizer(text or '')
def _compare_tails(self, actual, expected, location):
self._compare(self._text(actual.tail), self._text(expected.tail),
'Different tail text', location)
def _compare_children(self, actual, expected, location):
self._compare(len(actual), len(expected), 'Different number of child elements',
location, should_be_equal)
for act, exp in zip(actual, expected):
self.compare(act, exp, location.child(act.tag))
class Location(object):
def __init__(self, path, is_root=True):
self.path = path
self.is_not_root = not is_root
self._children = {}
def child(self, tag):
if tag not in self._children:
self._children[tag] = 1
else:
self._children[tag] += 1
tag += '[%d]' % self._children[tag]
return Location('%s/%s' % (self.path, tag), is_root=False) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/libraries/XML.py | 0.776877 | 0.465387 | XML.py | pypi |
import getopt # optparse was not supported by Jython 2.2
import os
import re
import shlex
import sys
import glob
import string
import textwrap
from robotide.lib.robot.errors import DataError, Information, FrameworkError
from robotide.lib.robot.version import get_full_version
from .misc import plural_or_not
from .encoding import console_decode, system_decode
from .utf8reader import Utf8Reader
from .robottypes import is_falsy, is_integer, is_list_like, is_string
ESCAPES = dict(
space=' ', apos="'", quot='"', lt='<', gt='>',
pipe='|', star='*', comma=',', slash='/', semic=';',
colon=':', quest='?', hash='#', amp='&', dollar='$',
percent='%', at='@', exclam='!', paren1='(', paren2=')',
square1='[', square2=']', curly1='{', curly2='}', bslash='\\'
)
def cmdline2list(args, escaping=False):
lexer = shlex.shlex(args, posix=True)
if is_falsy(escaping):
lexer.escape = ''
lexer.escapedquotes = '"\''
lexer.commenters = ''
lexer.whitespace_split = True
try:
return [token for token in lexer]
except ValueError as err:
raise ValueError("Parsing '%s' failed: %s" % (args, err))
class ArgumentParser(object):
_opt_line_re = re.compile(r"""
^\s{1,4} # 1-4 spaces in the beginning of the line
((-\S\s)*) # all possible short options incl. spaces (group 1)
--(\S{2,}) # required long option (group 3)
(\s\S+)? # optional value (group 4)
(\s\*)? # optional '*' telling option allowed multiple times (group 5)
""", re.VERBOSE)
_quotes_re = re.compile('(.*)(\".*\")(.*)?')
def __init__(self, usage, name=None, version=None, arg_limits=None,
validator=None, env_options=None, auto_help=True,
auto_version=True, auto_escape=True, auto_pythonpath=True,
auto_argumentfile=True):
"""Available options and tool name are read from the usage.
Tool name is got from the first row of the usage. It is either the
whole row or anything before first ' -- '.
"""
if not usage:
raise FrameworkError('Usage cannot be empty')
self.name = name or usage.splitlines()[0].split(' -- ')[0].strip()
self.version = version or get_full_version()
self._usage = usage
self._arg_limit_validator = ArgLimitValidator(arg_limits)
self._validator = validator
self._auto_help = auto_help
self._auto_version = auto_version
self._auto_escape = auto_escape
self._auto_pythonpath = auto_pythonpath
self._auto_argumentfile = auto_argumentfile
self._env_options = env_options
self._short_opts = ''
self._long_opts = []
self._multi_opts = []
self._flag_opts = []
self._short_to_long = {}
self._expected_args = ()
self._create_options(usage)
def parse_args(self, args):
"""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:
--escape option can be used to automatically unescape problematic
characters given in an escaped format.
--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. Possible <--ESCAPES--> is replaced with available
escapes so that they are wrapped to multiple lines but take the same
amount of horizontal space as <---ESCAPES--->. Both help and version
are wrapped to Information exception.
"""
# print(f"DEBUG: RFlib parse_args ENTER args={args}")
args = self._get_env_options() + self._save_filenames(args)
# args = self._get_env_options() + list(args)
# print(f"DEBUG: RFlib parse_args after _save_filenames: {args}")
args = [system_decode(a) for a in args]
# print(f"DEBUG: RFlib parse_args after system_decode: {args}")
if self._auto_argumentfile:
args = self._process_possible_argfile(args)
opts, args = self._parse_args(args)
if self._auto_argumentfile and opts.get('argumentfile'):
raise DataError("Using '--argumentfile' option in shortened format "
"like '--argumentf' is not supported.")
opts, args = self._handle_special_options(opts, args)
self._arg_limit_validator(args)
if self._validator:
opts, args = self._validator(opts, args)
# print(f"DEBUG: RFlib parse_args returning final = opts={opts} args={args}")
return opts, args
def _get_env_options(self):
if self._env_options:
options = os.getenv(self._env_options)
if options:
return cmdline2list(options)
return []
def _handle_special_options(self, opts, args):
if self._auto_escape and opts.get('escape'):
opts, args = self._unescape_opts_and_args(opts, args)
if self._auto_help and opts.get('help'):
self._raise_help()
if self._auto_version and opts.get('version'):
self._raise_version()
if self._auto_pythonpath and opts.get('pythonpath'):
sys.path = self._get_pythonpath(opts['pythonpath']) + sys.path
for auto, opt in [(self._auto_help, 'help'),
(self._auto_version, 'version'),
(self._auto_escape, 'escape'),
(self._auto_pythonpath, 'pythonpath'),
(self._auto_argumentfile, 'argumentfile')]:
if auto and opt in opts:
opts.pop(opt)
return opts, args
def _save_filenames(self, args):
res = self._quotes_re.match(args)
# print(f"DEBUG: RFlib ENTER _save_filenames res={res}")
if not res:
return args.strip().strip().split()
# DEBUG: example args
# --xunit "another output file.xml" --variablefile "a test file for variables.py" -v abc:new
# --debugfile "debug file.log"
clean = []
# DEBUG: example args
# --xunit "another output file.xml" --variablefile "a test file for variables.py" -v abc:new
# --debugfile "debug file.log"
# print(f"DEBUG: RFlib _save_filenames res.groups {res.groups()}")
for gr in res.groups():
line = []
if gr is not None and gr != '':
second_m = re.split('"', gr)
# print(f"DEBUG: RFlib _save_filenames second_m = {second_m}")
m = len(second_m)
if m > 2: # the middle element is the content
m = len(second_m)
for idx in range(0, m):
if second_m[idx]:
if idx % 2 == 0:
line.extend(second_m[idx].strip().strip().split())
elif idx % 2 != 0:
line.append(f"{second_m[idx]}")
else:
for idx in range(0, m):
if second_m[idx]:
line.extend(second_m[idx].strip().strip().split())
clean.extend(line)
# Fix variables
# print(f"DEBUG: RFlib _save_filenames DEFORE FIX VARIABLES clean= {clean}")
for idx, value in enumerate(clean):
if value[-1] == ':' and idx + 1 < len(clean):
clean[idx] = ''.join([value, clean[idx+1]])
clean.pop(idx+1)
# print(f"DEBUG: RFlib _save_filenames returnin clean= {clean}")
return clean
def _parse_args(self, args):
args = [self._lowercase_long_option(a) for a in args]
try:
opts, args = getopt.getopt(args, self._short_opts, self._long_opts)
except getopt.GetoptError as err:
raise DataError(err.msg)
return self._process_opts(opts), self._glob_args(args)
@staticmethod
def _lowercase_long_option(opt):
if not opt.startswith('--'):
return opt
if '=' not in opt:
return opt.lower()
opt, value = opt.split('=', 1)
return '%s=%s' % (opt.lower(), value)
def _unescape_opts_and_args(self, opts, args):
from robotide.lib.robot.output import LOGGER
with LOGGER.cache_only:
LOGGER.warn("Option '--escape' is deprecated. Use console escape "
"mechanism instead.")
try:
escape_strings = opts['escape']
except KeyError:
raise FrameworkError("No 'escape' in options")
escapes = self._get_escapes(escape_strings)
for name, value in opts.items():
if name != 'escape':
opts[name] = self._unescape(value, escapes)
return opts, [self._unescape(arg, escapes) for arg in args]
def _process_possible_argfile(self, args):
options = ['--argumentfile']
for short_opt, long_opt in self._short_to_long.items():
if long_opt == 'argumentfile':
options.append('-'+short_opt)
return ArgFileParser(options).process(args)
def _get_escapes(self, escape_strings):
escapes = {}
for estr in escape_strings:
try:
name, value = estr.split(':', 1)
except ValueError:
raise DataError("Invalid escape string syntax '%s'. "
"Expected: what:with" % estr)
try:
escapes[value] = ESCAPES[name.lower()]
except KeyError:
raise DataError("Invalid escape '%s'. Available: %s"
% (name, self._get_available_escapes()))
return escapes
def _unescape(self, value, escapes):
if value in [None, True, False]:
return value
if is_list_like(value):
return [self._unescape(item, escapes) for item in value]
for esc_name, esc_value in escapes.items():
if esc_name in value:
value = value.replace(esc_name, esc_value)
return value
def _process_opts(self, opt_tuple):
opts = self._get_default_opts()
for name, value in opt_tuple:
name = self._get_name(name)
if name in self._multi_opts:
opts[name].append(value)
elif name in self._flag_opts:
opts[name] = True
elif name.startswith('no') and name[2:] in self._flag_opts:
opts[name[2:]] = False
else:
opts[name] = value
return opts
def _get_default_opts(self) -> dict:
defaults = {}
for opt in self._long_opts:
opt = opt.rstrip('=')
if opt.startswith('no') and opt[2:] in self._flag_opts:
continue
defaults[opt] = [] if opt in self._multi_opts else None
return defaults
@staticmethod
def _glob_args(args):
temp = []
for path in args:
paths = sorted(glob.glob(path))
if paths:
temp.extend(paths)
else:
temp.append(path)
return temp
def _get_name(self, name):
name = name.lstrip('-')
try:
return self._short_to_long[name]
except KeyError:
return name
def _create_options(self, usage):
for line in usage.splitlines():
res = self._opt_line_re.match(line)
if res:
self._create_option(short_opts=[o[1] for o in res.group(1).split()],
long_opt=res.group(3).lower(),
takes_arg=bool(res.group(4)),
is_multi=bool(res.group(5)))
def _create_option(self, short_opts, long_opt, takes_arg, is_multi):
self._verify_long_not_already_used(long_opt, not takes_arg)
for sopt in short_opts:
if sopt in self._short_to_long:
self._raise_option_multiple_times_in_usage('-' + sopt)
self._short_to_long[sopt] = long_opt
if is_multi:
self._multi_opts.append(long_opt)
if takes_arg:
long_opt += '='
short_opts = [sopt+':' for sopt in short_opts]
else:
if long_opt.startswith('no'):
long_opt = long_opt[2:]
self._long_opts.append('no' + long_opt)
self._flag_opts.append(long_opt)
self._long_opts.append(long_opt)
self._short_opts += (''.join(short_opts))
def _verify_long_not_already_used(self, opt, flag=False):
if flag:
if opt.startswith('no'):
opt = opt[2:]
self._verify_long_not_already_used(opt)
self._verify_long_not_already_used('no' + opt)
elif opt in [o.rstrip('=') for o in self._long_opts]:
self._raise_option_multiple_times_in_usage('--' + opt)
def _get_pythonpath(self, paths):
if is_string(paths):
paths = [paths]
temp = []
for path in self._split_pythonpath(paths):
temp.extend(glob.glob(path))
return [os.path.abspath(path) for path in temp if path]
@staticmethod
def _split_pythonpath(paths):
# paths may already contain ':' as separator
tokens = ':'.join(paths).split(':')
if os.sep == '/':
return tokens
# Fix paths split like 'c:\temp' -> 'c', '\temp'
ret = []
drive = ''
for item in tokens:
item = item.replace('/', '\\')
if drive and item.startswith('\\'):
ret.append('%s:%s' % (drive, item))
drive = ''
continue
if drive:
ret.append(drive)
drive = ''
if len(item) == 1 and item in string.ascii_letters:
drive = item
else:
ret.append(item)
if drive:
ret.append(drive)
return ret
@staticmethod
def _get_available_escapes():
names = sorted(ESCAPES.keys(), key=str.lower)
return ', '.join('%s (%s)' % (n, ESCAPES[n]) for n in names)
def _raise_help(self):
msg = self._usage
if self.version:
msg = msg.replace('<VERSION>', self.version)
def replace_escapes(res):
escapes = 'Available escapes: ' + self._get_available_escapes()
lines = textwrap.wrap(escapes, width=len(res.group(2)))
indent = ' ' * len(res.group(1))
return '\n'.join(indent + line for line in lines)
msg = re.sub('( *)(<-+ESCAPES-+>)', replace_escapes, msg)
raise Information(msg)
def _raise_version(self):
raise Information('%s %s' % (self.name, self.version))
def _raise_option_multiple_times_in_usage(self, opt):
raise FrameworkError("Option '%s' multiple times in usage" % opt)
class ArgLimitValidator(object):
def __init__(self, arg_limits):
self._min_args, self._max_args = self._parse_arg_limits(arg_limits)
@staticmethod
def _parse_arg_limits(arg_limits):
if arg_limits is None:
return 0, sys.maxsize
if is_integer(arg_limits):
return arg_limits, arg_limits
if len(arg_limits) == 1:
return arg_limits[0], sys.maxsize
return arg_limits[0], arg_limits[1]
def __call__(self, args):
if not (self._min_args <= len(args) <= self._max_args):
self._raise_invalid_args(self._min_args, self._max_args, len(args))
@staticmethod
def _raise_invalid_args(min_args, max_args, arg_count):
min_end = plural_or_not(min_args)
if min_args == max_args:
expectation = "%d argument%s" % (min_args, min_end)
elif max_args != sys.maxsize:
expectation = "%d to %d arguments" % (min_args, max_args)
else:
expectation = "at least %d argument%s" % (min_args, min_end)
raise DataError("Expected %s, got %d." % (expectation, arg_count))
class ArgFileParser(object):
def __init__(self, options):
self._options = options
def process(self, args):
while True:
path, replace = self._get_index(args)
if not path:
break
args[replace] = self._get_args(path)
return args
def _get_index(self, args):
for opt in self._options:
start = opt + '=' if opt.startswith('--') else opt
for index, arg in enumerate(args):
normalized_arg = arg.lower() if opt.startswith('--') else arg
# Handles `--argumentfile foo` and `-A foo`
if normalized_arg == opt and index + 1 < len(args):
return args[index+1], slice(index, index+2)
# Handles `--argumentfile=foo` and `-Afoo`
if normalized_arg.startswith(start):
return arg[len(start):], slice(index, index+1)
return None, -1
def _get_args(self, path):
if path.upper() != 'STDIN':
content = self._read_from_file(path)
else:
content = self._read_from_stdin()
return self._process_file(content)
@staticmethod
def _read_from_file(path):
try:
with Utf8Reader(path) as reader:
return reader.read()
except (IOError, UnicodeError) as err:
raise DataError("Opening argument file '%s' failed: %s"
% (path, err))
@staticmethod
def _read_from_stdin():
return console_decode(sys.__stdin__.read())
def _process_file(self, content):
args = []
for line in content.splitlines():
line = line.strip()
if line.startswith('-'):
args.extend(self._split_option(line))
elif line and not line.startswith('#'):
args.append(line)
return args
def _split_option(self, line):
separator = self._get_option_separator(line)
if not separator:
return [line]
option, value = line.split(separator, 1)
if separator == ' ':
value = value.strip()
return [option, value]
@staticmethod
def _get_option_separator(line):
if ' ' not in line and '=' not in line:
return None
if '=' not in line:
return ' '
if ' ' not in line:
return '='
return ' ' if line.index(' ') < line.index('=') else '=' | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/utils/argumentparser.py | 0.432543 | 0.193833 | argumentparser.py | pypi |
import difflib
class RecommendationFinder(object):
def __init__(self, normalizer=None):
self.normalizer = normalizer or (lambda x: x)
def find_recommendations(self, name, candidates, max_matches=10):
"""Return a list of close matches to `name` from `candidates`."""
if not name or not candidates:
return []
norm_name = self.normalizer(name)
norm_candidates = self._get_normalized_candidates(candidates)
cutoff = self._calculate_cutoff(norm_name)
norm_matches = difflib.get_close_matches(norm_name,
norm_candidates,
n=max_matches,
cutoff=cutoff)
return self._get_original_candidates(norm_candidates, norm_matches)
@staticmethod
def format_recommendations(msg, recommendations):
"""Add recommendations to the given message.
The recommendation string looks like:
<msg> Did you mean:
<recommendations[0]>
<recommendations[1]>
<recommendations[2]>
"""
if recommendations:
msg += " Did you mean:"
for rec in recommendations:
msg += "\n %s" % rec
return msg
def _get_normalized_candidates(self, candidates):
norm_candidates = {}
# sort before normalization for consistent Python/Jython ordering
for cand in sorted(candidates):
norm = self.normalizer(cand)
norm_candidates.setdefault(norm, []).append(cand)
return norm_candidates
def _get_original_candidates(self, norm_candidates, norm_matches):
candidates = []
for norm_match in norm_matches:
candidates.extend(norm_candidates[norm_match])
return candidates
def _calculate_cutoff(self, string, min_cutoff=.5, max_cutoff=.85,
step=.03):
"""Calculate a cutoff depending on string length.
Default values determined by manual tuning until the results
"look right".
"""
cutoff = min_cutoff + len(string) * step
return min(cutoff, max_cutoff) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/utils/recommendations.py | 0.87142 | 0.279561 | recommendations.py | pypi |
import os
import sys
from .encodingsniffer import get_console_encoding, get_system_encoding
from .compat import isatty
from .platform import JYTHON, IRONPYTHON, PY3
from .robottypes import is_unicode
from .unic import unic
CONSOLE_ENCODING = get_console_encoding()
SYSTEM_ENCODING = get_system_encoding()
# IronPython and Jython streams have wrong encoding if outputs are redirected.
# Jython gets it right if PYTHONIOENCODING is set, though.
NON_TTY_ENCODING_CAN_BE_TRUSTED = \
not (IRONPYTHON or JYTHON and not os.getenv('PYTHONIOENCODING'))
def console_decode(string, encoding=CONSOLE_ENCODING, force=False):
"""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.
"""
if is_unicode(string) and not (IRONPYTHON and force):
return string
encoding = {'CONSOLE': CONSOLE_ENCODING,
'SYSTEM': SYSTEM_ENCODING}.get(encoding.upper(), encoding)
try:
return string.decode(encoding)
except UnicodeError:
return unic(string)
def console_encode(string, errors='replace', stream=sys.__stdout__):
"""Encodes Unicode to bytes in console or system encoding.
Determines the encoding to use based on the given stream and system
configuration. On Python 3 and IronPython returns Unicode, otherwise
returns bytes.
"""
encoding = _get_console_encoding(stream)
if PY3 and encoding != 'UTF-8':
return string.encode(encoding, errors).decode(encoding)
if PY3 or IRONPYTHON:
return string
return string.encode(encoding, errors)
def _get_console_encoding(stream):
encoding = getattr(stream, 'encoding', None)
if encoding and (NON_TTY_ENCODING_CAN_BE_TRUSTED or isatty(stream)):
return encoding
return CONSOLE_ENCODING if isatty(stream) else SYSTEM_ENCODING
# These interpreters handle communication with system APIs using Unicode.
if PY3 or JYTHON or IRONPYTHON:
def system_decode(string):
return string if is_unicode(string) else unic(string)
def system_encode(string, errors='replace'):
return string if is_unicode(string) else unic(string)
else:
def system_decode(string):
"""Decodes bytes from system (e.g. cli args or env vars) to Unicode."""
try:
return string.decode(SYSTEM_ENCODING)
except UnicodeError:
return unic(string)
def system_encode(string, errors='replace'):
"""Encodes Unicode to system encoding (e.g. cli args and env vars).
Non-Unicode values are first converted to Unicode.
"""
if not is_unicode(string):
string = unic(string)
return string.encode(SYSTEM_ENCODING, errors) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/utils/encoding.py | 0.494873 | 0.176069 | encoding.py | pypi |
from __future__ import division
from operator import add, sub
from .platform import PY2
from .robottypes import is_integer
from .unic import unic
def roundup(number, ndigits=0, return_type=None):
"""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 with ``return_type``.
With the built-in ``round()`` rounding equally close numbers as well as
the return type depends on the Python version.
"""
result = _roundup(number, ndigits)
if not return_type:
return_type = float if ndigits > 0 else int
return return_type(result)
# Python 2 rounds half away from zero (as taught in school) but Python 3
# uses "bankers' rounding" that rounds half towards the even number. We want
# consistent rounding and expect Python 2 style to be more familiar for users.
if PY2:
_roundup = round
else:
def _roundup(number, ndigits):
precision = 10 ** (-1 * ndigits)
if number % (0.5 * precision) == 0 and number % precision != 0:
operator = add if number > 0 else sub
number = operator(number, 0.1 * precision)
return round(number, ndigits)
def printable_name(string, code_style=False):
"""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'
'' -> ''
"""
if code_style and '_' in string:
string = string.replace('_', ' ')
parts = string.split()
if code_style and len(parts) == 1 \
and not (string.isalpha() and string.islower()):
parts = _split_camel_case(parts[0])
return ' '.join(part[0].upper() + part[1:] for part in parts)
def _split_camel_case(string):
tokens = []
token = []
for prev, char, next in zip(' ' + string, string, string[1:] + ' '):
if _is_camel_case_boundary(prev, char, next):
if token:
tokens.append(''.join(token))
token = [char]
else:
token.append(char)
if token:
tokens.append(''.join(token))
return tokens
def _is_camel_case_boundary(prev, char, next):
if prev.isdigit():
return not char.isdigit()
if char.isupper():
return next.islower() or prev.isalpha() and not prev.isupper()
return char.isdigit()
def plural_or_not(item):
count = item if is_integer(item) else len(item)
return '' if count == 1 else 's'
def seq2str(sequence, quote="'", sep=', ', lastsep=' and '):
"""Returns sequence in format `'item 1', 'item 2' and 'item 3'`."""
sequence = [quote + unic(item) + quote for item in sequence]
if not sequence:
return ''
if len(sequence) == 1:
return sequence[0]
last_two = lastsep.join(sequence[-2:])
return sep.join(sequence[:-2] + [last_two])
def seq2str2(sequence):
"""Returns sequence in format `[ item 1 | item 2 | ... ]`."""
if not sequence:
return '[ ]'
return '[ %s ]' % ' | '.join(unic(item) for item in sequence) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/utils/misc.py | 0.874426 | 0.409929 | misc.py | pypi |
import re
import fnmatch
from functools import partial
from .compat import py2to3
from .normalizing import normalize
from .platform import IRONPYTHON, PY3
from .robottypes import is_string
def eq(str1, str2, ignore=(), caseless=True, spaceless=True):
str1 = normalize(str1, ignore, caseless, spaceless)
str2 = normalize(str2, ignore, caseless, spaceless)
return str1 == str2
@py2to3
class Matcher(object):
def __init__(self, pattern, ignore=(), caseless=True, spaceless=True,
regexp=False):
if PY3 and isinstance(pattern, bytes):
raise TypeError('Matching bytes is not supported on Python 3.')
self.pattern = pattern
self._normalize = partial(normalize, ignore=ignore, caseless=caseless,
spaceless=spaceless)
self._regexp = self._compile(self._normalize(pattern), regexp=regexp)
def _compile(self, pattern, regexp=False):
if not regexp:
pattern = fnmatch.translate(pattern)
# https://github.com/IronLanguages/ironpython2/issues/515
if IRONPYTHON and "\\'" in pattern:
pattern = pattern.replace("\\'", "'")
return re.compile(pattern, re.DOTALL)
def match(self, string):
return self._regexp.match(self._normalize(string)) is not None
def match_any(self, strings):
return any(self.match(s) for s in strings)
def __nonzero__(self):
return bool(self._normalize(self.pattern))
class MultiMatcher(object):
def __init__(self, patterns=None, ignore=(), caseless=True, spaceless=True,
match_if_no_patterns=False, regexp=False):
self._matchers = [Matcher(pattern, ignore, caseless, spaceless, regexp)
for pattern in self._ensure_list(patterns)]
self._match_if_no_patterns = match_if_no_patterns
def _ensure_list(self, patterns):
if patterns is None:
return []
if is_string(patterns):
return [patterns]
return patterns
def match(self, string):
if self._matchers:
return any(m.match(string) for m in self._matchers)
return self._match_if_no_patterns
def match_any(self, strings):
return any(self.match(s) for s in strings)
def __len__(self):
return len(self._matchers)
def __iter__(self):
for matcher in self._matchers:
yield matcher.pattern | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/utils/match.py | 0.585101 | 0.233258 | match.py | pypi |
import os
import os.path
import sys
from robotide.lib.robot.errors import DataError
from .encoding import system_decode
from .platform import IRONPYTHON, PY_VERSION, PY2, WINDOWS
from .robottypes import is_unicode
from .unic import unic
if IRONPYTHON and PY_VERSION == (2, 7, 8):
# https://github.com/IronLanguages/ironpython2/issues/371
def _abspath(path):
if os.path.isabs(path):
if not os.path.splitdrive(path)[0]:
drive = os.path.splitdrive(os.getcwd())[0]
return drive + path
return path
return os.path.abspath(path)
else:
_abspath = os.path.abspath
if PY2:
from urllib import pathname2url
def path_to_url(path):
return pathname2url(path.encode('UTF-8'))
else:
from urllib.request import pathname2url as path_to_url
if WINDOWS:
CASE_INSENSITIVE_FILESYSTEM = True
else:
try:
CASE_INSENSITIVE_FILESYSTEM = os.listdir('/tmp') == os.listdir('/TMP')
except OSError:
CASE_INSENSITIVE_FILESYSTEM = False
def normpath(path, case_normalize=False):
"""Replacement for os.path.normpath with some enhancements.
1. Convert non-Unicode paths to Unicode using the file system encoding.
2. NFC normalize Unicode paths (affects mainly OSX).
3. Optionally lower-case paths on case-insensitive file systems.
That includes Windows and also OSX in default configuration.
4. Turn ``c:`` into ``c:\\`` on Windows instead of keeping it as ``c:``.
"""
if not is_unicode(path):
path = system_decode(path)
path = unic(path) # Handles NFC normalization on OSX
path = os.path.normpath(path)
if case_normalize and CASE_INSENSITIVE_FILESYSTEM:
path = path.lower()
if WINDOWS and len(path) == 2 and path[1] == ':':
return path + '\\'
return path
def abspath(path, case_normalize=False):
"""Replacement for os.path.abspath with some enhancements and bug fixes.
1. Non-Unicode paths are converted to Unicode using file system encoding.
2. Optionally lower-case paths on case-insensitive file systems.
That includes Windows and also OSX in default configuration.
3. Turn ``c:`` into ``c:\\`` on Windows instead of ``c:\\current\\path``.
"""
path = normpath(path, case_normalize)
return normpath(_abspath(path), case_normalize)
def get_link_path(target, base):
"""Returns a relative path to ``target`` from ``base``.
If ``base`` is an existing file, then its parent directory is considered to
be the base. Otherwise ``base`` is assumed to be a directory.
The returned path is URL encoded. On Windows returns an absolute path with
``file:`` prefix if the target is on a different drive.
"""
path = _get_link_path(target, base)
url = path_to_url(path)
if os.path.isabs(path):
url = 'file:' + url
return url
def _get_link_path(target, base):
target = abspath(target)
base = abspath(base)
if os.path.isfile(base):
base = os.path.dirname(base)
if base == target:
return '.'
base_drive, base_path = os.path.splitdrive(base)
# Target and base on different drives
if os.path.splitdrive(target)[0] != base_drive:
return target
common_len = len(_common_path(base, target))
if base_path == os.sep:
return target[common_len:]
if common_len == len(base_drive) + len(os.sep):
common_len -= len(os.sep)
dirs_up = os.sep.join([os.pardir] * base[common_len:].count(os.sep))
path = os.path.join(dirs_up, target[common_len + len(os.sep):])
return os.path.normpath(path)
def _common_path(p1, p2):
"""Returns the longest path common to p1 and p2.
Rationale: as os.path.commonprefix is character based, it doesn't consider
path separators as such, so it may return invalid paths:
commonprefix(('/foo/bar/', '/foo/baz.txt')) -> '/foo/ba' (instead of /foo)
"""
while p1 and p2:
if p1 == p2:
return p1
if len(p1) > len(p2):
p1 = os.path.dirname(p1)
else:
p2 = os.path.dirname(p2)
return ''
def find_file(path, basedir='.', file_type=None):
path = os.path.normpath(path.replace('/', os.sep))
if os.path.isabs(path):
ret = _find_absolute_path(path)
else:
ret = _find_relative_path(path, basedir)
if ret:
return ret
default = file_type or 'File'
file_type = {'Library': 'Test library',
'Variables': 'Variable file',
'Resource': 'Resource file'}.get(file_type, default)
raise DataError("%s '%s' does not exist." % (file_type, path))
def _find_absolute_path(path):
if _is_valid_file(path):
return path
return None
def _find_relative_path(path, basedir):
for base in [basedir] + sys.path:
if not (base and os.path.isdir(base)):
continue
if not is_unicode(base):
base = system_decode(base)
ret = os.path.abspath(os.path.join(base, path))
if _is_valid_file(ret):
return ret
return None
def _is_valid_file(path):
return os.path.isfile(path) or \
(os.path.isdir(path) and os.path.isfile(os.path.join(path, '__init__.py'))) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/utils/robotpath.py | 0.428473 | 0.159774 | robotpath.py | pypi |
from .robottypes import type_name
from .unic import unic
def fail(msg=None):
"""Fail test immediately with the given message."""
_report_failure(msg)
def assert_false(expr, msg=None):
"""Fail the test if the expression is True."""
if expr:
_report_failure(msg)
def assert_true(expr, msg=None):
"""Fail the test unless the expression is True."""
if not expr:
_report_failure(msg)
def assert_not_none(obj, msg=None, values=True):
"""Fail the test if given object is None."""
_msg = 'is None'
if obj is None:
if msg is None:
msg = _msg
elif values is True:
msg = '%s: %s' % (msg, _msg)
_report_failure(msg)
def assert_none(obj, msg=None, values=True):
"""Fail the test if given object is not None."""
_msg = '%r is not None' % obj
if obj is not None:
if msg is None:
msg = _msg
elif values is True:
msg = '%s: %s' % (msg, _msg)
_report_failure(msg)
def assert_raises(exc_class, callable_obj, *args, **kwargs):
"""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.
"""
try:
callable_obj(*args, **kwargs)
except exc_class as err:
return err
else:
if hasattr(exc_class,'__name__'):
exc_name = exc_class.__name__
else:
exc_name = str(exc_class)
_report_failure('%s not raised' % exc_name)
def assert_raises_with_msg(exc_class, expected_msg, callable_obj, *args,
**kwargs):
"""Similar to fail_unless_raises but also checks the exception message."""
try:
callable_obj(*args, **kwargs)
except exc_class as err:
assert_equal(expected_msg, unic(err),
'Correct exception but wrong message')
else:
if hasattr(exc_class,'__name__'):
exc_name = exc_class.__name__
else:
exc_name = str(exc_class)
_report_failure('%s not raised' % exc_name)
def assert_equal(first, second, msg=None, values=True, formatter=None):
"""Fail if given objects are unequal as determined by the '==' operator."""
if not first == second:
_report_inequality(first, second, '!=', msg, values, formatter)
def assert_not_equal(first, second, msg=None, values=True, formatter=None):
"""Fail if given objects are equal as determined by the '==' operator."""
if first == second:
_report_inequality(first, second, '==', msg, values, formatter)
def assert_almost_equal(first, second, places=7, msg=None, values=True):
"""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).
"""
if round(second - first, places) != 0:
extra = 'within %r places' % places
_report_inequality(first, second, '!=', msg, values, extra=extra)
def assert_not_almost_equal(first, second, places=7, msg=None, values=True):
"""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).
"""
if round(second-first, places) == 0:
extra = 'within %r places' % places
_report_inequality(first, second, '==', msg, values, extra=extra)
def _report_failure(msg):
if msg is None:
raise AssertionError()
raise AssertionError(msg)
def _report_inequality(obj1, obj2, delim, msg=None, values=False,
formatter=None, extra=None):
if not msg:
msg = _format_message(obj1, obj2, delim, formatter)
elif values:
msg = '%s: %s' % (msg, _format_message(obj1, obj2, delim, formatter))
if values and extra:
msg += ' ' + extra
raise AssertionError(msg)
def _format_message(obj1, obj2, delim, formatter=None):
formatter = formatter or unic
str1 = formatter(obj1)
str2 = formatter(obj2)
if delim == '!=' and str1 == str2:
return '%s (%s) != %s (%s)' % (str1, type_name(obj1),
str2, type_name(obj2))
return '%s %s %s' % (str1, delim, str2) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/utils/asserts.py | 0.683947 | 0.309885 | asserts.py | pypi |
try:
from collections import MutableMapping
except ImportError:
from collections.abc import MutableMapping # Python 3.10
from .platform import PY3
from .robottypes import is_dict_like, is_unicode
def normalize(string, ignore=(), caseless=True, spaceless=True):
"""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.
"""
empty = u'' if is_unicode(string) else b''
if PY3 and isinstance(ignore, bytes):
# Iterating bytes in Python3 yields integers.
ignore = [bytes([i]) for i in ignore]
if spaceless:
string = empty.join(string.split())
if caseless:
string = lower(string)
ignore = [lower(i) for i in ignore]
# both if statements below enhance performance a little
if ignore:
for ign in ignore:
if ign in string:
string = string.replace(ign, empty)
return string
def lower(string):
return string.lower()
def _normalize(name, ignore=(), caseless=True, spaceless=True):
return normalize(name, ignore, caseless, spaceless)
class NormalizedDict(MutableMapping):
"""Custom dictionary implementation automatically normalizing keys."""
def __init__(self, initial=None, ignore=(), caseless=True, spaceless=True):
"""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 :func:`normalize`
function.
"""
self._data = {}
self._keys = {}
self._ignore = ignore
self._caseless = caseless
self._spaceless = spaceless
if initial:
self._add_initial(initial)
def _add_initial(self, initial):
items = initial.items() if hasattr(initial, 'items') else initial
for key, value in items:
self[key] = value
def __getitem__(self, key):
return self._data[_normalize(key, ignore=self._ignore, caseless=self._caseless, spaceless=self._spaceless)]
def __setitem__(self, key, value):
norm_key = _normalize(key, ignore=self._ignore, caseless=self._caseless, spaceless=self._spaceless)
self._data[norm_key] = value
self._keys.setdefault(norm_key, key)
def __delitem__(self, key):
norm_key = _normalize(key, ignore=self._ignore, caseless=self._caseless, spaceless=self._spaceless)
del self._data[norm_key]
del self._keys[norm_key]
def __iter__(self):
return (self._keys[norm_key] for norm_key in sorted(self._keys))
def __len__(self):
return len(self._data)
def __str__(self):
return '{%s}' % ', '.join('%r: %r' % (key, self[key]) for key in self)
def __eq__(self, other):
if not is_dict_like(other):
return False
if not isinstance(other, NormalizedDict):
other = NormalizedDict(other, caseless=self._caseless)
return self._data == other._data
def __ne__(self, other):
return not self == other
def copy(self):
copy = NormalizedDict()
copy._data = self._data.copy()
copy._keys = self._keys.copy()
copy._normalize = _normalize
return copy
# Speed-ups. Following methods are faster than default implementations.
def __contains__(self, key):
return _normalize(key, ignore=self._ignore, caseless=self._caseless, spaceless=self._spaceless) in self._data
def clear(self):
self._data.clear()
self._keys.clear() | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/utils/normalizing.py | 0.879742 | 0.44734 | normalizing.py | pypi |
from robotide.lib.robot.utils import PY2
class JsonWriter(object):
def __init__(self, output, separator=''):
self._writer = JsonDumper(output)
self._separator = separator
def write_json(self, prefix, data, postfix=';\n', mapping=None,
separator=True):
self._writer.write(prefix)
self._writer.dump(data, mapping)
self._writer.write(postfix)
self._write_separator(separator)
def write(self, string, postfix=';\n', separator=True):
self._writer.write(string + postfix)
self._write_separator(separator)
def _write_separator(self, separator):
if separator and self._separator:
self._writer.write(self._separator)
class JsonDumper(object):
def __init__(self, output):
self._output = output
self._dumpers = (MappingDumper(self),
IntegerDumper(self),
TupleListDumper(self),
StringDumper(self),
NoneDumper(self),
DictDumper(self))
def dump(self, data, mapping=None):
for dumper in self._dumpers:
if dumper.handles(data, mapping):
dumper.dump(data, mapping)
return
raise ValueError('Dumping %s not supported.' % type(data))
def write(self, data):
self._output.write(data)
class _Dumper(object):
_handled_types = None
def __init__(self, jsondumper):
self._dump = jsondumper.dump
self._write = jsondumper.write
def handles(self, data, mapping):
return isinstance(data, self._handled_types)
def dump(self, data, mapping):
raise NotImplementedError
class StringDumper(_Dumper):
_handled_types = (str, unicode) if PY2 else str
_search_and_replace = [('\\', '\\\\'), ('"', '\\"'), ('\t', '\\t'),
('\n', '\\n'), ('\r', '\\r'), ('</', '\\x3c/')]
def dump(self, data, mapping):
self._write('"%s"' % (self._escape(data) if data else ''))
def _escape(self, string):
for search, replace in self._search_and_replace:
if search in string:
string = string.replace(search, replace)
return string
class IntegerDumper(_Dumper):
# Handles also bool
_handled_types = (int, long) if PY2 else int
def dump(self, data, mapping):
self._write(str(data).lower())
class DictDumper(_Dumper):
_handled_types = dict
def dump(self, data, mapping):
self._write('{')
last_index = len(data) - 1
for index, key in enumerate(sorted(data)):
self._dump(key, mapping)
self._write(':')
self._dump(data[key], mapping)
if index < last_index:
self._write(',')
self._write('}')
class TupleListDumper(_Dumper):
_handled_types = (tuple, list)
def dump(self, data, mapping):
self._write('[')
last_index = len(data) - 1
for index, item in enumerate(data):
self._dump(item, mapping)
if index < last_index:
self._write(',')
self._write(']')
class MappingDumper(_Dumper):
def handles(self, data, mapping):
try:
return mapping and data in mapping
except TypeError:
return False
def dump(self, data, mapping):
self._write(mapping[data])
class NoneDumper(_Dumper):
def handles(self, data, mapping):
return data is None
def dump(self, data, mapping):
self._write('null') | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/htmldata/jsonwriter.py | 0.666931 | 0.182298 | jsonwriter.py | pypi |
import itertools
class RowSplitter(object):
_comment_mark = '#'
_empty_cell_escape = '' # '${EMPTY}'
_line_continuation = '...'
setting_table = 'setting'
_indented_tables = ('test case', 'keyword')
_split_from = ('ELSE', 'ELSE IF', 'AND')
def __init__(self, cols=8, split_multiline_doc=False):
self._cols = cols
self._split_multiline_doc = split_multiline_doc
def split(self, row, table_type):
if not row:
return self._split_empty_row()
indent = self._get_indent(row, table_type)
if self._split_multiline_doc and self._is_doc_row(row, table_type):
return self._split_doc_row(row, indent)
return self._split_row(row, indent)
def _split_empty_row(self):
yield []
def _get_indent(self, row, table_type):
indent = self._get_first_non_empty_index(row)
min_indent = 1 if table_type in self._indented_tables else 0
return max(indent, min_indent)
def _get_first_non_empty_index(self, row, indented=False):
ignore = ['', '...'] if indented else ['']
return len(list(itertools.takewhile(lambda x: x in ignore, row)))
def _is_doc_row(self, row, table_type):
if table_type == self.setting_table:
return len(row) > 1 and row[0] == 'Documentation'
if table_type in self._indented_tables:
return len(row) > 2 and row[1] == '[Documentation]'
return False
def _split_doc_row(self, row, indent):
first, rest = self._split_doc(row[indent+1])
yield row[:indent+1] + [first] + row[indent+2:]
while rest:
current, rest = self._split_doc(rest)
row = [current] if current else []
yield self._continue_row(row, indent)
def _split_doc(self, doc):
if '\\n' not in doc:
return doc, ''
if '\\n ' in doc:
doc = doc.replace('\\n ', '\\n')
return doc.split('\\n', 1)
def _split_row(self, row, indent):
while row:
current, row = self._split(row)
yield self._escape_last_cell_if_empty(current)
if row:
row = self._continue_row(row, indent)
def _split(self, data):
index = min(self._get_possible_split_indices(data))
current, rest = data[:index], data[index:]
rest = self._comment_rest_if_needed(current, rest)
return current, rest
def _get_possible_split_indices(self, data):
min_index = self._get_first_non_empty_index(data, indented=True) + 1
for marker in self._split_from:
if marker in data[min_index:]:
yield data[min_index:].index(marker) + min_index
yield self._cols
def _comment_rest_if_needed(self, current, rest):
if rest and any(c.startswith(self._comment_mark) for c in current) \
and not rest[0].startswith(self._comment_mark):
rest = [self._comment_mark + ' ' + rest[0]] + rest[1:]
return rest
def _escape_last_cell_if_empty(self, row):
if row and not row[-1].strip():
row = row[:-1] + [self._empty_cell_escape]
return row
def _continue_row(self, row, indent):
row = [self._line_continuation] + row
if indent + 1 < self._cols:
row = [''] * indent + row
return row | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/writer/rowsplitter.py | 0.47171 | 0.264923 | rowsplitter.py | pypi |
import re
from robotide.lib.robot.utils import attribute_escape, html_escape
from .formatters import _DataFileFormatter
class HtmlFormatter(_DataFileFormatter):
_split_multiline_doc = False
def _format_row(self, row, table=None):
row = self._pad(self._escape_consecutive_whitespace(row), table)
if self._is_documentation_row(row):
return self._create_documentation_row(row)
first_cell = self._create_first_cell(row[0], table)
if self._is_indented_documentation_row(row[1:], table):
return self._create_indented_documentation_row(first_cell, row[1:])
return [first_cell] + [HtmlCell(c) for c in row[1:]]
def _is_documentation_row(self, row):
return row[0] == 'Documentation'
def _create_documentation_row(self, row):
return [NameCell(row[0]), DocumentationCell(row[1], span=self._column_count-1)]
def _is_indented_documentation_row(self, cells, table):
return self._is_indented_table(table) and cells and \
cells[0] == '[Documentation]'
def _create_indented_documentation_row(self, first_cell, cells):
start = [first_cell, HtmlCell(cells[0])]
if any(c.startswith('#') for c in cells):
return start + [HtmlCell(c) for c in cells[1:]]
return start + [DocumentationCell(cells[1], self._column_count-2)]
def _create_first_cell(self, cell, table):
if self._is_indented_table(table) and cell:
return AnchorNameCell(cell, 'keyword' if table.type == 'keyword'
else 'test')
return NameCell(cell)
def format_header(self, table):
if not self._should_align_columns(table) or len(table.header) == 1:
return [HeaderCell(table.header[0], self._column_count)]
headers = self._pad_header(table)
return [HeaderCell(hdr) for hdr in headers]
def _pad_header(self, table):
header = table.header
return header + [''] * (self._get_column_count(table) - len(header))
def _pad(self, row, table):
return row + [''] * (self._get_column_count(table) - len(row))
def _get_column_count(self, table):
if table is None or len(table.header) == 1 \
or not self._is_indented_table(table):
return self._column_count
return max(self._max_column_count(table), len(table.header))
def _max_column_count(self, table):
count = 0
for item in table:
for child in item:
count = max(count, len(child.as_list()) + 1)
return count
class HtmlCell(object):
_backslash_matcher = re.compile(r'(\\+)n ?')
def __init__(self, content='', attributes=None, tag='td', escape=True):
if escape:
content = html_escape(content)
self.content = self._replace_newlines(content)
self.attributes = attributes or {}
self.tag = tag
def _replace_newlines(self, content):
def replacer(match):
backslash_count = len(match.group(1))
if backslash_count % 2 == 1:
return '%sn<br>\n' % match.group(1)
return match.group()
return self._backslash_matcher.sub(replacer, content)
class NameCell(HtmlCell):
def __init__(self, name='', attributes=None):
HtmlCell.__init__(self, name, {'class': 'name'})
class AnchorNameCell(HtmlCell):
def __init__(self, name, type_):
HtmlCell.__init__(self, self._link_from_name(name, type_),
{'class': 'name'}, escape=False)
def _link_from_name(self, name, type_):
return '<a name="%s_%s">%s</a>' % (type_, attribute_escape(name),
html_escape(name))
class DocumentationCell(HtmlCell):
def __init__(self, content, span):
HtmlCell.__init__(self, content, {'class': 'colspan%d' % span,
'colspan': '%d' % span})
class HeaderCell(HtmlCell):
def __init__(self, name, span=1):
HtmlCell.__init__(self, name, {'class': 'name', 'colspan': '%d' % span},
tag='th') | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/writer/htmlformatter.py | 0.474388 | 0.30421 | htmlformatter.py | pypi |
import re
from .aligners import FirstColumnAligner, ColumnAligner, NullAligner
from .dataextractor import DataExtractor
from .rowsplitter import RowSplitter
class _DataFileFormatter(object):
_whitespace = re.compile(r"\s{2,}")
_split_multiline_doc = True
def __init__(self, column_count):
self._splitter = RowSplitter(column_count, self._split_multiline_doc)
self._column_count = column_count
self._extractor = DataExtractor(self._want_names_on_first_content_row)
def _want_names_on_first_content_row(self, table, name):
return True
def empty_row_after(self, table):
return self._format_row([], table)
def format_header(self, table):
header = self._format_row(table.header)
return self._format_header(header, table)
def format_table(self, table):
rows = self._extractor.rows_from_table(table)
if self._should_split_rows(table):
rows = self._split_rows(rows, table)
return (self._format_row(r, table) for r in rows)
def _should_split_rows(self, table):
return not self._should_align_columns(table)
def _split_rows(self, original_rows, table):
for original in original_rows:
for split in self._splitter.split(original, table.type):
yield split
def _should_align_columns(self, table):
return self._is_indented_table(table) and bool(table.header[1:])
@staticmethod
def _is_indented_table(table):
return table is not None and table.type in ['test case', 'keyword']
def _escape_consecutive_whitespace(self, row):
return [self._whitespace.sub(self._whitespace_escaper,
cell.replace('\n', ' ')) for cell in row]
@staticmethod
def _whitespace_escaper(match):
return '\\'.join(match.group(0))
def _format_row(self, row, table=None):
raise NotImplementedError
def _format_header(self, header, table):
raise NotImplementedError
class TsvFormatter(_DataFileFormatter):
def _format_header(self, header, table):
return [self._format_header_cell(cell) for cell in header]
@staticmethod
def _format_header_cell(cell):
return '*%s*' % cell if cell else ''
def _format_row(self, row, table=None):
return self._pad(self._escape(row))
def _escape(self, row):
return self._escape_consecutive_whitespace(self._escape_tabs(row))
@staticmethod
def _escape_tabs(row):
return [c.replace('\t', '\\t') for c in row]
def _pad(self, row):
row = [cell.replace('\n', ' ') for cell in row]
return row + [''] * (self._column_count - len(row))
class TxtFormatter(_DataFileFormatter):
_test_or_keyword_name_width = 18
_setting_and_variable_name_width = 14
def _format_row(self, row, table=None):
row = self._escape(row)
aligner = self._aligner_for(table)
return aligner.align_row(row)
def _aligner_for(self, table):
if table and table.type in ['setting', 'variable']:
return FirstColumnAligner(self._setting_and_variable_name_width)
if self._should_align_columns(table):
return ColumnAligner(self._test_or_keyword_name_width, table)
return NullAligner()
def _format_header(self, header, table):
header = ['*** %s ***' % header[0]] + header[1:]
aligner = self._aligner_for(table)
return aligner.align_row(header)
def _want_names_on_first_content_row(self, table, name):
return self._should_align_columns(table) and \
len(name) <= self._test_or_keyword_name_width
def _escape(self, row):
if not row:
return row
return list(self._escape_cells(self._escape_consecutive_whitespace(row)))
def _escape_cells(self, row):
escape = False
for cell in row:
if cell:
escape = True
elif escape:
cell = '\\'
yield cell
class PipeFormatter(TxtFormatter):
def _escape_cells(self, row):
return [self._escape_empty(self._escape_pipes(cell)) for cell in row]
@staticmethod
def _escape_empty(cell):
return cell or ' '
@staticmethod
def _escape_pipes(cell):
if ' | ' in cell:
cell = cell.replace(' | ', ' \\| ')
if cell.startswith('| '):
cell = '\\' + cell
if cell.endswith(' |'):
cell = cell[:-1] + '\\|'
return cell | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/writer/formatters.py | 0.605916 | 0.270769 | formatters.py | pypi |
import os
from robotide.lib.robot.errors import DataError
from robotide.lib.robot.utils import binary_file_writer, file_writer, PY2
from .filewriters import FileWriter
class DataFileWriter(object):
"""Object to write parsed test data file objects back to disk."""
def __init__(self, **options):
"""
:param `**options`: A :class:`.WritingContext` is created based on these.
"""
self._options = options
def write(self, datafile):
"""Writes given `datafile` using `**options`.
:param datafile: The parsed test data object to be written
:type datafile: :py:class:`~robot.parsing.model.TestCaseFile`,
:py:class:`~robot.parsing.model.ResourceFile`,
:py:class:`~robot.parsing.model.TestDataDirectory`
"""
with WritingContext(datafile, **self._options) as ctx:
FileWriter(ctx).write(datafile)
class WritingContext(object):
"""Contains configuration used in writing a test data file to disk."""
txt_format = 'txt'
html_format = 'html'
tsv_format = 'tsv'
robot_format = 'robot'
txt_column_count = 18
html_column_count = 5
tsv_column_count = 8
_formats = [txt_format, html_format, tsv_format, robot_format]
def __init__(self, datafile, format='', output=None, pipe_separated=False,
txt_separating_spaces=4, line_separator='\n'):
"""
:param datafile: The datafile to be written.
:type datafile: :py:class:`~robot.parsing.model.TestCaseFile`,
:py:class:`~robot.parsing.model.ResourceFile`,
:py:class:`~robot.parsing.model.TestDataDirectory`
:param str format: Output file format. If omitted, read from the
extension of the `source` attribute of the given `datafile`.
:param output: An open, file-like object used in writing. If
omitted, value of `source` attribute of the given `datafile` is
used to construct a new file object.
:param bool pipe_separated: Whether to use pipes as separator when
output file format is txt.
:param int txt_separating_spaces: Number of separating spaces between
cells in space separated format.
:param str line_separator: Line separator used in output files.
If `output` is not given, an output file is created based on the source
of the given datafile and value of `format`. Examples:
Write output in a StringIO instance using format of `datafile.source`::
WriteConfiguration(datafile, output=StringIO)
Output file is created from `datafile.source` by stripping extension
and replacing it with `html`::
WriteConfiguration(datafile, format='html')
"""
self.datafile = datafile
self.pipe_separated = pipe_separated
self.line_separator = line_separator
self._given_output = output
self.format = self._validate_format(format) or self._format_from_file()
self.txt_separating_spaces = txt_separating_spaces
self.output = output
def __enter__(self):
if not self.output:
path = self._output_path()
if PY2 and self.format == self.tsv_format:
self.output = binary_file_writer(path)
else:
self.output = file_writer(path, newline=self.line_separator)
return self
def __exit__(self, *exc_info):
if self._given_output is None:
self.output.close()
def _validate_format(self, format):
format = format.lower() if format else ''
if format and format not in self._formats:
raise DataError('Invalid format: %s' % format)
return format
def _format_from_file(self):
return self._format_from_extension(self._source_from_file())
def _format_from_extension(self, path):
return os.path.splitext(path)[1][1:].lower()
def _output_path(self):
return '%s.%s' % (self._base_name(), self.format)
def _base_name(self):
return os.path.splitext(self._source_from_file())[0]
def _source_from_file(self):
return getattr(self.datafile, 'initfile', self.datafile.source) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/writer/datafilewriter.py | 0.855957 | 0.388357 | datafilewriter.py | pypi |
from robotide.lib.robot.utils import (Matcher, NormalizedDict, is_string, py2to3, setter,
unic)
@py2to3
class Tags(object):
def __init__(self, tags=None):
self._tags = tags
@setter
def _tags(self, tags):
if not tags:
return ()
if is_string(tags):
tags = (tags,)
return self._normalize(tags)
def _normalize(self, tags):
normalized = NormalizedDict(((unic(t), 1) for t in tags), ignore='_')
for removed in '', 'NONE':
if removed in normalized:
normalized.pop(removed)
return tuple(normalized)
def add(self, tags):
self._tags = tuple(self) + tuple(Tags(tags))
def remove(self, tags):
tags = TagPatterns(tags)
self._tags = [t for t in self if not tags.match(t)]
def match(self, tags):
return TagPatterns(tags).match(self)
def __contains__(self, tags):
return self.match(tags)
def __len__(self):
return len(self._tags)
def __iter__(self):
return iter(self._tags)
def __unicode__(self):
return u'[%s]' % ', '.join(self)
def __repr__(self):
return repr(list(self))
def __getitem__(self, index):
item = self._tags[index]
return item if not isinstance(index, slice) else Tags(item)
def __add__(self, other):
return Tags(tuple(self) + tuple(Tags(other)))
@py2to3
class TagPatterns(object):
def __init__(self, patterns):
self._patterns = tuple(TagPattern(p) for p in Tags(patterns))
def match(self, tags):
tags = tags if isinstance(tags, Tags) else Tags(tags)
return any(p.match(tags) for p in self._patterns)
def __contains__(self, tag):
return self.match(tag)
def __len__(self):
return len(self._patterns)
def __iter__(self):
return iter(self._patterns)
def __getitem__(self, index):
return self._patterns[index]
def __unicode__(self):
return u'[%s]' % u', '.join(pattern.__unicode__() for pattern in self)
def TagPattern(pattern):
pattern = pattern.replace(' ', '')
if 'NOT' in pattern:
return NotTagPattern(*pattern.split('NOT'))
if 'OR' in pattern:
return OrTagPattern(pattern.split('OR'))
if 'AND' in pattern or '&' in pattern:
return AndTagPattern(pattern.replace('&', 'AND').split('AND'))
return SingleTagPattern(pattern)
@py2to3
class SingleTagPattern(object):
def __init__(self, pattern):
self._matcher = Matcher(pattern, ignore='_')
def match(self, tags):
return self._matcher.match_any(tags)
def __iter__(self):
yield self
def __unicode__(self):
return self._matcher.pattern
def __nonzero__(self):
return bool(self._matcher)
@py2to3
class AndTagPattern(object):
def __init__(self, patterns):
self._patterns = tuple(TagPattern(p) for p in patterns)
def match(self, tags):
return all(p.match(tags) for p in self._patterns)
def __iter__(self):
return iter(self._patterns)
def __unicode__(self):
return ' AND '.join(pattern.__unicode__() for pattern in self)
@py2to3
class OrTagPattern(object):
def __init__(self, patterns):
self._patterns = tuple(TagPattern(p) for p in patterns)
def match(self, tags):
return any(p.match(tags) for p in self._patterns)
def __iter__(self):
return iter(self._patterns)
def __unicode__(self):
return ' OR '.join(pattern.__unicode__() for pattern in self)
@py2to3
class NotTagPattern(object):
def __init__(self, must_match, *must_not_match):
self._first = TagPattern(must_match)
self._rest = OrTagPattern(must_not_match)
def match(self, tags):
if not self._first:
return not self._rest.match(tags)
return self._first.match(tags) and not self._rest.match(tags)
def __iter__(self):
yield self._first
for pattern in self._rest:
yield pattern
def __unicode__(self):
return ' NOT '.join(pattern.__unicode__() for pattern in self).lstrip() | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/model/tags.py | 0.799677 | 0.294443 | tags.py | pypi |
from itertools import chain
import re
from robotide.lib.robot.utils import NormalizedDict, unicode
from .stats import CombinedTagStat, CriticalTagStat, TagStat
from .tags import SingleTagPattern, TagPatterns
class TagStatistics(object):
"""Container for tag statistics."""
def __init__(self, critical_stats, non_critical_stats, combined_stats):
#: Dictionary, where key is the name of the tag as a string and value
#: is an instance of :class:`~robot.model.stats.TagStat`.
self.tags = NormalizedDict(ignore='_')
#: List of :class:`~robot.model.stats.CriticalTagStat` objects.
self.critical = critical_stats
#: List of :class:`~robot.model.stats.CriticalTagStat` objects.
self.non_critical = non_critical_stats
#: List of :class:`~robot.model.stats.CombinedTagStat` objects.
self.combined = combined_stats
def visit(self, visitor):
visitor.visit_tag_statistics(self)
def __iter__(self):
crits = self._get_critical_and_non_critical_matcher()
tags = [t for t in self.tags.values() if t.name not in crits]
return iter(sorted(chain(self.critical, self.non_critical,
self.combined, tags)))
def _get_critical_and_non_critical_matcher(self):
crits = [stat for stat in self.critical + self.non_critical
if isinstance(stat.pattern, SingleTagPattern)]
return NormalizedDict([(unicode(stat.pattern), None) for stat in crits],
ignore='_')
class TagStatisticsBuilder(object):
def __init__(self, criticality=None, included=None, excluded=None,
combined=None, docs=None, links=None):
self._included = TagPatterns(included)
self._excluded = TagPatterns(excluded)
self._info = TagStatInfo(docs, links)
self.stats = TagStatistics(
self._info.get_critical_stats(criticality),
self._info.get_critical_stats(criticality, critical=False),
self._info.get_combined_stats(combined)
)
def add_test(self, test):
self._add_tags_to_statistics(test)
self._add_to_critical_and_combined_statistics(test)
def _add_tags_to_statistics(self, test):
for tag in test.tags:
if self._is_included(tag):
if tag not in self.stats.tags:
self.stats.tags[tag] = self._info.get_stat(tag)
self.stats.tags[tag].add_test(test)
def _is_included(self, tag):
if self._included and not self._included.match(tag):
return False
return not self._excluded.match(tag)
def _add_to_critical_and_combined_statistics(self, test):
stats = self.stats
for stat in stats.critical + stats.non_critical + stats.combined:
if stat.match(test.tags):
stat.add_test(test)
class TagStatInfo(object):
def __init__(self, docs=None, links=None):
self._docs = [TagStatDoc(*doc) for doc in docs or []]
self._links = [TagStatLink(*link) for link in links or []]
def get_stat(self, tag):
return TagStat(tag, self.get_doc(tag), self.get_links(tag))
def get_critical_stats(self, criticality, critical=True):
if not criticality:
return []
tag_patterns = (criticality.critical_tags
if critical else criticality.non_critical_tags)
return [self._get_critical_stat(p, critical) for p in tag_patterns]
def _get_critical_stat(self, pattern, critical):
name = unicode(pattern)
return CriticalTagStat(pattern, name, critical, self.get_doc(name),
self.get_links(name))
def get_combined_stats(self, combined=None):
return [self._get_combined_stat(*comb) for comb in combined or []]
def _get_combined_stat(self, pattern, name=None):
name = name or pattern
return CombinedTagStat(pattern, name, self.get_doc(name),
self.get_links(name))
def get_doc(self, tag):
return ' & '.join(doc.text for doc in self._docs if doc.match(tag))
def get_links(self, tag):
return [link.get_link(tag) for link in self._links if link.match(tag)]
class TagStatDoc(object):
def __init__(self, pattern, doc):
self._matcher = TagPatterns(pattern)
self.text = doc
def match(self, tag):
return self._matcher.match(tag)
class TagStatLink(object):
_match_pattern_tokenizer = re.compile(r"(\*|\?+)")
def __init__(self, pattern, link, title):
self._regexp = self._get_match_regexp(pattern)
self._link = link
self._title = title.replace('_', ' ')
def match(self, tag):
return self._regexp.match(tag) is not None
def get_link(self, tag):
match = self._regexp.match(tag)
if not match:
return None
link, title = self._replace_groups(self._link, self._title, match)
return link, title
@staticmethod
def _replace_groups(link, title, match):
for index, group in enumerate(match.groups()):
placefolder = '%%%d' % (index+1)
link = link.replace(placefolder, group)
title = title.replace(placefolder, group)
return link, title
def _get_match_regexp(self, pattern):
pattern = '^%s$' % ''.join(self._yield_match_pattern(pattern))
return re.compile(pattern, re.IGNORECASE)
def _yield_match_pattern(self, pattern):
for token in self._match_pattern_tokenizer.split(pattern):
if token.startswith('?'):
yield '(%s)' % ('.'*len(token))
elif token == '*':
yield '(.*)'
else:
yield re.escape(token) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/model/tagstatistics.py | 0.799129 | 0.279317 | tagstatistics.py | pypi |
from robotide.lib.robot.utils import (Sortable, elapsed_time_to_string, html_escape,
is_string, normalize, py2to3, unicode)
from .tags import TagPattern
@py2to3
class Stat(Sortable):
"""Generic statistic object used for storing all the statistic values."""
def __init__(self, name):
#: Human readable identifier of the object these statistics
#: belong to. Either `All Tests` or `Critical Tests` for
#: :class:`~robot.model.totalstatistics.TotalStatistics`,
#: long name of the suite for
#: :class:`~robot.model.suitestatistics.SuiteStatistics`
#: or name of the tag for
#: :class:`~robot.model.tagstatistics.TagStatistics`
self.name = name
#: Number of passed tests.
self.passed = 0
#: Number of failed tests.
self.failed = 0
#: Number of milliseconds it took to execute.
self.elapsed = 0
self._norm_name = normalize(name, ignore='_')
def get_attributes(self, include_label=False, include_elapsed=False,
exclude_empty=True, values_as_strings=False,
html_escape=False):
attrs = {'pass': self.passed, 'fail': self.failed}
attrs.update(self._get_custom_attrs())
if include_label:
attrs['label'] = self.name
if include_elapsed:
attrs['elapsed'] = elapsed_time_to_string(self.elapsed,
include_millis=False)
if exclude_empty:
attrs = dict((k, v) for k, v in attrs.items() if v not in ('', None))
if values_as_strings:
attrs = dict((k, unicode(v if v is not None else ''))
for k, v in attrs.items())
if html_escape:
attrs = dict((k, self._html_escape(v)) for k, v in attrs.items())
return attrs
def _get_custom_attrs(self):
return {}
def _html_escape(self, item):
return html_escape(item) if is_string(item) else item
@property
def total(self):
return self.passed + self.failed
def add_test(self, test):
self._update_stats(test)
self._update_elapsed(test)
def _update_stats(self, test):
if test.passed:
self.passed += 1
else:
self.failed += 1
def _update_elapsed(self, test):
self.elapsed += test.elapsedtime
@property
def _sort_key(self):
return self._norm_name
def __nonzero__(self):
return not self.failed
def visit(self, visitor):
visitor.visit_stat(self)
class TotalStat(Stat):
"""Stores statistic values for a test run."""
type = 'total'
class SuiteStat(Stat):
"""Stores statistics values for a single suite."""
type = 'suite'
def __init__(self, suite):
Stat.__init__(self, suite.longname)
#: Identifier of the suite, e.g. `s1-s2`.
self.id = suite.id
#: Number of milliseconds it took to execute this suite,
#: including sub-suites.
self.elapsed = suite.elapsedtime
self._name = suite.name
def _get_custom_attrs(self):
return {'id': self.id, 'name': self._name}
def _update_elapsed(self, test):
pass
def add_stat(self, other):
self.passed += other.passed
self.failed += other.failed
class TagStat(Stat):
"""Stores statistic values for a single tag."""
type = 'tag'
def __init__(self, name, doc='', links=None, critical=False,
non_critical=False, combined=None):
Stat.__init__(self, name)
#: Documentation of tag as a string.
self.doc = doc
#: List of tuples in which the first value is the link URL and
#: the second is the link title. An empty list by default.
self.links = links or []
#: ``True`` if tag is considered critical, ``False`` otherwise.
self.critical = critical
#: ``True`` if tag is considered non-critical, ``False`` otherwise.
self.non_critical = non_critical
#: Pattern as a string if the tag is combined, ``None`` otherwise.
self.combined = combined
@property
def info(self):
"""Returns additional information of the tag statistics
are about. Either `critical`, `non-critical`, `combined` or an
empty string.
"""
if self.critical:
return 'critical'
if self.non_critical:
return 'non-critical'
if self.combined:
return 'combined'
return ''
def _get_custom_attrs(self):
return {'doc': self.doc, 'links': self._get_links_as_string(),
'info': self.info, 'combined': self.combined}
def _get_links_as_string(self):
return ':::'.join('%s:%s' % (title, url) for url, title in self.links)
@property
def _sort_key(self):
return (not self.critical,
not self.non_critical,
not self.combined,
self._norm_name)
class CombinedTagStat(TagStat):
def __init__(self, pattern, name=None, doc='', links=None):
TagStat.__init__(self, name or pattern, doc, links, combined=pattern)
self.pattern = TagPattern(pattern)
def match(self, tags):
return self.pattern.match(tags)
class CriticalTagStat(TagStat):
def __init__(self, tag_pattern, name=None, critical=True, doc='',
links=None):
TagStat.__init__(self, name or unicode(tag_pattern), doc, links,
critical=critical, non_critical=not critical)
self.pattern = tag_pattern
def match(self, tags):
return self.pattern.match(tags) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/model/stats.py | 0.91301 | 0.296642 | stats.py | pypi |
from robotide.lib.robot.utils import py2to3, setter
from .tags import TagPatterns
from .namepatterns import SuiteNamePatterns, TestNamePatterns
from .visitor import SuiteVisitor
class EmptySuiteRemover(SuiteVisitor):
def end_suite(self, suite):
suite.suites = [s for s in suite.suites if s.test_count]
def visit_test(self, test):
pass
def visit_keyword(self, kw):
pass
@py2to3
class Filter(EmptySuiteRemover):
def __init__(self, include_suites=None, include_tests=None,
include_tags=None, exclude_tags=None):
self.include_suites = include_suites
self.include_tests = include_tests
self.include_tags = include_tags
self.exclude_tags = exclude_tags
@setter
def include_suites(self, suites):
return SuiteNamePatterns(suites) \
if not isinstance(suites, SuiteNamePatterns) else suites
@setter
def include_tests(self, tests):
return TestNamePatterns(tests) \
if not isinstance(tests, TestNamePatterns) else tests
@setter
def include_tags(self, tags):
return TagPatterns(tags) if not isinstance(tags, TagPatterns) else tags
@setter
def exclude_tags(self, tags):
return TagPatterns(tags) if not isinstance(tags, TagPatterns) else tags
def start_suite(self, suite):
if not self:
return False
if hasattr(suite, 'starttime'):
suite.starttime = suite.endtime = None
if self.include_suites:
return self._filter_by_suite_name(suite)
if self.include_tests:
suite.tests = self._filter(suite, self._included_by_test_name)
if self.include_tags:
suite.tests = self._filter(suite, self._included_by_tags)
if self.exclude_tags:
suite.tests = self._filter(suite, self._not_excluded_by_tags)
return bool(suite.suites)
def _filter_by_suite_name(self, suite):
if self.include_suites.match(suite.name, suite.longname):
suite.visit(Filter(include_suites=[],
include_tests=self.include_tests,
include_tags=self.include_tags,
exclude_tags=self.exclude_tags))
return False
suite.tests = []
return True
def _filter(self, suite, filter):
return [t for t in suite.tests if filter(t)]
def _included_by_test_name(self, test):
return self.include_tests.match(test.name, test.longname)
def _included_by_tags(self, test):
return self.include_tags.match(test.tags)
def _not_excluded_by_tags(self, test):
return not self.exclude_tags.match(test.tags)
def __nonzero__(self):
return bool(self.include_suites or self.include_tests or
self.include_tags or self.exclude_tags) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/model/filter.py | 0.585101 | 0.189953 | filter.py | pypi |
from robotide.lib.robot.utils import py2to3, unicode
@py2to3
class ItemList(object):
__slots__ = ['_item_class', '_common_attrs', '_items']
def __init__(self, item_class, common_attrs=None, items=None):
self._item_class = item_class
self._common_attrs = common_attrs
self._items = ()
if items:
self.extend(items)
def create(self, *args, **kwargs):
return self.append(self._item_class(*args, **kwargs))
def append(self, item):
self._check_type_and_set_attrs(item)
self._items += (item,)
return item
def _check_type_and_set_attrs(self, *items):
common_attrs = self._common_attrs or {}
for item in items:
if not isinstance(item, self._item_class):
raise TypeError("Only %s objects accepted, got %s."
% (self._item_class.__name__,
item.__class__.__name__))
for attr in common_attrs:
setattr(item, attr, common_attrs[attr])
return items
def extend(self, items):
self._items += self._check_type_and_set_attrs(*items)
def insert(self, index, item):
self._check_type_and_set_attrs(item)
items = list(self._items)
items.insert(index, item)
self._items = tuple(items)
def pop(self, *index):
items = list(self._items)
result = items.pop(*index)
self._items = tuple(items)
return result
def index(self, item, *start_and_end):
return self._items.index(item, *start_and_end)
def clear(self):
self._items = ()
def visit(self, visitor):
for item in self._items:
item.visit(visitor)
def __iter__(self):
return iter(self._items)
def __getitem__(self, index):
if not isinstance(index, slice):
return self._items[index]
items = self.__class__(self._item_class)
items._common_attrs = self._common_attrs
items.extend(self._items[index])
return items
def __setitem__(self, index, item):
if isinstance(index, slice):
self._check_type_and_set_attrs(*item)
else:
self._check_type_and_set_attrs(item)
items = list(self._items)
items[index] = item
self._items = tuple(items)
def __len__(self):
return len(self._items)
def __unicode__(self):
return u'[%s]' % ', '.join(unicode(item) for item in self) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/model/itemlist.py | 0.721547 | 0.1933 | itemlist.py | pypi |
class SuiteVisitor(object):
"""Abstract class to ease traversing through the test suite structure.
See the :mod:`module level <robot.model.visitor>` documentation for more
information and an example.
"""
def visit_suite(self, suite):
"""Implements traversing through the suite and its direct children.
Can be overridden to allow modifying the passed in ``suite`` without
calling :func:`start_suite` or :func:`end_suite` nor visiting child
suites, tests or keywords (setup and teardown) at all.
"""
if self.start_suite(suite) is not False:
suite.keywords.visit(self)
suite.suites.visit(self)
suite.tests.visit(self)
self.end_suite(suite)
def start_suite(self, suite):
"""Called when suite starts. Default implementation does nothing.
Can return explicit ``False`` to stop visiting.
"""
pass
def end_suite(self, suite):
"""Called when suite ends. Default implementation does nothing."""
pass
def visit_test(self, test):
"""Implements traversing through the test and its keywords.
Can be overridden to allow modifying the passed in ``test`` without
calling :func:`start_test` or :func:`end_test` nor visiting keywords.
"""
if self.start_test(test) is not False:
test.keywords.visit(self)
self.end_test(test)
def start_test(self, test):
"""Called when test starts. Default implementation does nothing.
Can return explicit ``False`` to stop visiting.
"""
pass
def end_test(self, test):
"""Called when test ends. Default implementation does nothing."""
pass
def visit_keyword(self, kw):
"""Implements traversing through the keyword and its child keywords.
Can be overridden to allow modifying the passed in ``kw`` without
calling :func:`start_keyword` or :func:`end_keyword` nor visiting
child keywords.
"""
if self.start_keyword(kw) is not False:
kw.keywords.visit(self)
kw.messages.visit(self)
self.end_keyword(kw)
def start_keyword(self, keyword):
"""Called when keyword starts. Default implementation does nothing.
Can return explicit ``False`` to stop visiting.
"""
pass
def end_keyword(self, keyword):
"""Called when keyword ends. Default implementation does nothing."""
pass
def visit_message(self, msg):
"""Implements visiting the message.
Can be overridden to allow modifying the passed in ``msg`` without
calling :func:`start_message` or :func:`end_message`.
"""
if self.start_message(msg) is not False:
self.end_message(msg)
def start_message(self, msg):
"""Called when message starts. Default implementation does nothing.
Can return explicit ``False`` to stop visiting.
"""
pass
def end_message(self, msg):
"""Called when message ends. Default implementation does nothing."""
pass | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/model/visitor.py | 0.905994 | 0.599514 | visitor.py | pypi |
import copy
from robotide.lib.robot.utils import SetterAwareType, py2to3, with_metaclass
@py2to3
class ModelObject(with_metaclass(SetterAwareType, object)):
__slots__ = []
def copy(self, **attributes):
"""Return shallow copy of this object.
:param attributes: Attributes to be set for the returned copy
automatically. For example, ``test.copy(name='New name')``.
See also :meth:`deepcopy`. The difference between these two is the same
as with the standard ``copy.copy`` and ``copy.deepcopy`` functions
that these methods also use internally.
New in Robot Framework 3.0.1.
"""
copied = copy.copy(self)
for name in attributes:
setattr(copied, name, attributes[name])
return copied
def deepcopy(self, **attributes):
"""Return deep copy of this object.
:param attributes: Attributes to be set for the returned copy
automatically. For example, ``test.deepcopy(name='New name')``.
See also :meth:`copy`. The difference between these two is the same
as with the standard ``copy.copy`` and ``copy.deepcopy`` functions
that these methods also use internally.
New in Robot Framework 3.0.1.
"""
copied = copy.deepcopy(self)
for name in attributes:
setattr(copied, name, attributes[name])
return copied
def __unicode__(self):
return self.name
def __repr__(self):
return repr(str(self))
def __setstate__(self, state):
"""Customize attribute updating when using the `copy` module.
This may not be needed in the future if we fix the mess we have with
different timeout types.
"""
# We have __slots__ so state is always a two-tuple.
# Refer to: https://www.python.org/dev/peps/pep-0307
dictstate, slotstate = state
if dictstate is not None:
self.__dict__.update(dictstate)
for name in slotstate:
# If attribute is defined in __slots__ and overridden by @setter
# (this is the case at least with 'timeout' of 'running.TestCase')
# we must not set the "real" attribute value because that would run
# the setter method and that would recreate the object when it
# should not. With timeouts recreating object using the object
# itself would also totally fail.
setter_name = '_setter__' + name
if setter_name not in slotstate:
setattr(self, name, slotstate[name]) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/lib/robot/model/modelobject.py | 0.799521 | 0.457924 | modelobject.py | pypi |
import re
from .. import robotapi, utils
from .basecontroller import _BaseController
from .cellinfo import CellPosition, CellType, CellInfo, CellContent, ContentType, UPPERCASE_KWS
from ..namespace.local_namespace import local_namespace
from ..utils import variablematcher
class StepController(_BaseController):
_GIVEN_WHEN_THEN_MATCHER = re.compile(r'^(given|when|then|and|but)\s*', re.I)
indent = None
def __init__(self, parent, step):
self._init(parent, step)
self.step_controller_step.args = self._change_last_empty_to_empty_var(
self.step_controller_step.args, self.step_controller_step.comment)
def _init(self, parent, step):
self.parent = parent
self.step_controller_step = step
self.indent = []
index = 0
if isinstance(self.step_controller_step, list):
while index < len(self.step_controller_step) and self.step_controller_step[index] == '':
self.indent.append('')
elif isinstance(self.step_controller_step, robotapi.Step):
cells = self.step_controller_step.as_list()
for index in range(0, len(cells)):
if cells[index] == '':
self.increase_indent()
else:
self.step_controller_step.args = self.step_controller_step.comment = []
@property
def display_name(self):
return 'Step'
@property
def datafile_controller(self):
return self.parent.datafile_controller
@staticmethod
def _change_last_empty_to_empty_var(args, comment):
if not args: # and not comment:
return []
if comment:
return args
return args[:-1] + ['${EMPTY}'] if args[-1] == '' else args
def get_keyword_info(self, kw):
if not kw:
return None
return self.parent.get_keyword_info(kw)
def __eq__(self, other):
if self is other:
return True
return self._steps_are_equal(self.step_controller_step, other.step_controller_step)
@staticmethod
def _steps_are_equal(fst, snd):
if fst is snd:
return True
if not snd:
return False
return (fst.assign == snd.assign and
fst.name == snd.name and
fst.args == snd.args)
def get_value(self, col):
values = self.as_list()
if len(values) <= col:
return ''
return values[col]
def get_cell_info(self, col):
position = self._get_cell_position(col)
content = self._get_content_with_type(col, position)
if content.type == ContentType.COMMENTED:
return self._build_cell_info(content, CellPosition(CellType.OPTIONAL, None))
return self._build_cell_info(content, position)
@property
def assignments(self):
return self.step_controller_step.assign
def is_assigning(self, value):
for assignment in self.assignments:
if assignment.replace('=', '').strip() == value.replace('=', '').strip():
return True
if value.strip().endswith('='):
return True
return False
def _build_cell_info(self, content, position):
return CellInfo(content, position)
def _get_cell_position(self, column):
col = column
if self.parent.has_template():
return CellPosition(CellType.UNKNOWN, None)
column -= len(self.step_controller_step.assign)
value_at_col = self.get_value(col)
info = self.get_keyword_info(value_at_col) # Getting info for the keyword cell
keyword_col = col if col >= self._keyword_column else self._keyword_column
if info:
casesensitive = (value_at_col.upper() != value_at_col and value_at_col.upper() in UPPERCASE_KWS)
if casesensitive:
return CellPosition(CellType.UNKNOWN, ContentType.STRING)
return CellPosition(CellType.KEYWORD, None)
else:
while not info and keyword_col > 0 and keyword_col > self._keyword_column:
keyword_col -= 1
value_at_col = self.get_value(keyword_col)
info = self.get_keyword_info(value_at_col) # Getting info for the previous cell
casesensitive = (value_at_col.upper() != value_at_col and value_at_col.upper() in UPPERCASE_KWS)
if casesensitive:
return CellPosition(CellType.UNKNOWN, None)
if info:
args = info.arguments
else:
args = []
args_amount = len(args)
if column > keyword_col and self.get_value(keyword_col) == "FOR" and self.is_assigning(value_at_col):
return CellPosition(CellType.ASSIGN, None)
if column <= keyword_col and self.is_assigning(value_at_col):
return CellPosition(CellType.ASSIGN, None)
if col < keyword_col:
return CellPosition(CellType.UNKNOWN, None)
if not info and not self.is_assigning(value_at_col)\
and not self.is_assigning(self.get_value(self._keyword_column)) and col >= keyword_col:
return CellPosition(CellType.UNKNOWN, None)
if args_amount == 0:
return CellPosition(CellType.MUST_BE_EMPTY, None)
mandatory_args_amount = self._number_of_mandatory_arguments(args, args_amount)
if self._has_list_or_dict_var_value_before(col - 1):
return CellPosition(CellType.UNKNOWN, None)
if col <= keyword_col + mandatory_args_amount:
return CellPosition(CellType.MANDATORY, args[col-keyword_col - 1])
if col >= keyword_col + args_amount - mandatory_args_amount and self._last_argument_is_varargs(args):
return CellPosition(CellType.OPTIONAL, args[-1])
if keyword_col + mandatory_args_amount < col <= keyword_col + args_amount:
return CellPosition(CellType.OPTIONAL, args[col-keyword_col-1])
return CellPosition(CellType.MUST_BE_EMPTY, None)
def _number_of_mandatory_arguments(self, args, args_amount):
defaults = [arg for arg in args if '=' in arg]
n = args_amount - len(defaults)
if self._last_argument_is_varargs(args):
n -= 1
return n
@staticmethod
def _last_argument_is_varargs(args):
return args[-1].startswith('*')
def _has_list_or_dict_var_value_before(self, arg_index):
if self.args:
for idx, value in enumerate(self.args):
if idx > arg_index:
return False
if variablematcher.is_list_variable(value) and \
not variablematcher.is_list_variable_subitem(value):
return True
if robotapi.is_dict_var(value) and \
not variablematcher.is_dict_var_access(value):
return True
return False
def _get_content_with_type(self, col, position):
value = self.get_value(col)
if self._is_commented(col):
return CellContent(ContentType.COMMENTED, value)
last_none_empty = self._get_last_none_empty_col_idx()
if isinstance(last_none_empty, int) and last_none_empty < col:
return CellContent(ContentType.EMPTY, value)
if variablematcher.is_variable(value):
if self._is_unknow_variable(value, position):
return CellContent(ContentType.UNKNOWN_VARIABLE, value)
return CellContent(ContentType.VARIABLE, value)
if self.is_user_keyword(value):
return CellContent(
ContentType.USER_KEYWORD, value,
self.get_keyword_info(value).source)
if self.is_library_keyword(value):
return CellContent(
ContentType.LIBRARY_KEYWORD, value,
self.get_keyword_info(value).source)
if value == 'END': # DEBUG Don't consider start column (col == 0 and)
return CellContent(ContentType.END, value)
return CellContent(ContentType.STRING, value)
def _is_unknow_variable(self, value, position):
if position.type == CellType.ASSIGN:
return False
try:
is_known = self._get_local_namespace().has_name(value)
except AttributeError:
return False
if is_known:
return False
inner_value = value[2:-1]
modified = re.split(r'\W', inner_value, 1)[0]
return not self._get_local_namespace().has_name(
'%s{%s}' % (value[0], modified))
def _get_local_namespace(self):
index = self.parent.index_of_step(self.step_controller_step)
return local_namespace(
self.parent, self.datafile_controller.namespace, index)
def _get_last_none_empty_col_idx(self):
values = self.as_list()
for i in reversed(range(len(values))):
if values[i].strip() != '':
return i
return None
def is_modifiable(self):
return self.datafile_controller.is_modifiable()
def is_user_keyword(self, value):
return self.parent.is_user_keyword(value)
def is_library_keyword(self, value):
return self.parent.is_library_keyword(value)
def as_list(self):
# print(f"\nDEBUG: Stepcontrollers enter as_list")
return self.step_controller_step.as_list()
def contains_variable(self, name):
return any(variablematcher.value_contains_variable(item, name)
for item in self.as_list())
def contains_variable_assignment(self, name):
return any(variablematcher.value_contains_variable(item, "%s=" % name)
for item in self.as_list())
def contains_keyword(self, name):
return any(self._kw_name_match(item, name)
for item in [self.keyword or ''] + self.args)
def _kw_name_match(self, item, expected):
if isinstance(expected, str):
return utils.eq(item, expected) or (
self._GIVEN_WHEN_THEN_MATCHER.match(item) and
utils.eq(
self._GIVEN_WHEN_THEN_MATCHER.sub('', item), expected))
return expected.match(item)
def replace_keyword(self, new_name, old_name):
# DEBUG: Create setters for Step.name and Step.args
if self._kw_name_match(self.keyword or '', old_name):
self.step_controller_step.name = self.step_controller_step.cells[self.step_controller_step.inner_kw_pos] =\
self._kw_name_replace(self.keyword, new_name, old_name)
for index, value in enumerate(self.args):
if self._kw_name_match(value, old_name):
self.step_controller_step.args[index] = self.step_controller_step.cells[
self.step_controller_step.inner_kw_pos + 1 + index] =\
self._kw_name_replace(value, new_name, old_name)
def _kw_name_replace(self, old_value, new_match, old_match):
old_prefix_matcher = self._GIVEN_WHEN_THEN_MATCHER.match(old_value)
if not old_prefix_matcher:
return new_match
old_prefix = old_prefix_matcher.group(0)
old_match_matcher = self._GIVEN_WHEN_THEN_MATCHER.match(old_match)
if old_match_matcher and old_match_matcher.group(0) == old_prefix:
return new_match
return old_prefix + new_match
@property
def datafile(self):
return self.parent.datafile
@property
def keyword(self):
return self.step_controller_step.name
@property
def assign(self):
return self.step_controller_step.assign
@property
def args(self):
return self.step_controller_step.args
@property
def vars(self):
return self.step_controller_step.vars
def change(self, col, new_value):
cells = self.as_list()
if col >= len(cells):
cells = cells + ['' for _ in range(col - len(cells) + 1)]
cells[col] = new_value
comment = self._get_comment(cells)
if comment:
cells.pop()
self.recreate(cells, comment)
def insert_value_before(self, col, new_value):
self.shift_right(col)
self.change(col, new_value)
def comment(self):
col = self._first_non_empty_cell() # .step_controller_step.inner_kw_pos
self.insert_value_before(col, 'Comment')
def sharp_comment(self):
col = self._first_non_empty_cell()
self.insert_sharp_comment(col)
def insert_sharp_comment(self, col):
cell_value = self.get_value(col)
new_value = "# " + cell_value
self.change(col, new_value)
def sharp_uncomment(self):
col = self._first_non_empty_cell()
self.remove_sharp_comment(col)
def remove_sharp_comment(self, col):
cell_value = self.get_value(col)
if cell_value.startswith('#'):
new_value = cell_value.lstrip('#').lstrip(' ')
else:
return
self.change(col, new_value)
def _is_commented(self, col):
if self._has_comment_keyword():
return col > self._keyword_column
for i in range(min(col + 1, len(self.as_list()))):
if self.get_value(i).startswith('#'):
return True
return False
def _first_non_empty_cell(self):
index = self.step_controller_step.first_non_empty_cell()
return index
@property
def _keyword_column(self):
return self.step_controller_step.inner_kw_pos # ._first_non_empty_cell()
def recalculate_keyword_column(self):
index = self._first_non_empty_cell()
cells = self.as_list()
if 0 < len(cells) == index:
self.step_controller_step.inner_kw_pos = index - 1
return
if index < len(cells) and cells[index] == '':
return
while index < len(cells) and (len(cells[index]) > 0 and cells[index][0] in ['$', '@', '&', '%']):
index += 1
self.step_controller_step.inner_kw_pos = index
def _has_comment_keyword(self):
if self.keyword is None:
return False
return self.keyword.strip().lower() == "comment" or self.keyword.strip().lower() == 'builtin.comment'
def uncomment(self):
index_of_comment = self._first_non_empty_cell()
if self.step_controller_step.as_list()[index_of_comment].lower() == 'comment' or\
self.step_controller_step.as_list()[index_of_comment].lower() == 'builtin.comment':
self.shift_left(index_of_comment, True)
self.recalculate_keyword_column()
def shift_right(self, from_column):
cells = self.as_list()
comment = self._get_comment(cells)
if len(cells) > from_column:
if comment:
cells.pop()
cells = cells[:from_column] + [''] + cells[from_column:]
self.recreate(cells, comment)
def shift_left(self, from_column, delete=False):
cells = self.as_list()
while not delete and from_column > 0 and cells[from_column] != '':
from_column -= 1
if not delete and from_column == 0 and cells[from_column] != '':
return
if len(cells) > from_column:
cells = cells[:from_column] + cells[from_column + 1:]
self.recreate(cells)
@staticmethod
def first_non_empty_cell(cells):
index = 0
while index < len(cells) and cells[index] == '':
index += 1
return index
def insert_before(self, new_step):
steps = self.parent.get_raw_steps()
index = steps.index(self.step_controller_step)
if not new_step or not new_step.as_list():
new_step = robotapi.Step([])
if index > 0:
upper_indent = steps[index-1].first_non_empty_cell() # self.first_non_empty_cell(steps[index-1].as_list())
current_indent = new_step.first_non_empty_cell() # self.first_non_empty_cell(new_step.as_list())
delta_indent = upper_indent - current_indent
if delta_indent > 0:
e_list = []
for _ in range(1, delta_indent):
e_list.append('')
new_step = robotapi.Step(e_list + new_step.as_list(indent=True))
elif delta_indent < 0 and len(new_step.as_list()) > 1:
for _ in range(delta_indent, 0):
if new_step.as_list()[0] == '':
new_step = robotapi.Step(new_step.as_list(indent=True)[1:])
elif delta_indent == 0 and len(steps[index-1].as_list()) > upper_indent:
if steps[index-1].as_list()[upper_indent-1] in ['END'] \
or steps[index-1].as_list()[upper_indent] in ['FOR']:
new_step = robotapi.Step([''] + new_step.as_list(indent=True))
self.parent.set_raw_steps(steps[:index] + [new_step] + steps[index:])
else:
current_indent = len(new_step.indent)
delta_indent = current_indent - len(self.step_controller_step.indent)
if delta_indent > 0:
for _ in range(0, delta_indent):
if new_step.as_list()[0] == '':
new_step = robotapi.Step(new_step.as_list(indent=False)[1:])
else:
new_step = robotapi.Step(new_step.as_list(indent=False))
self.parent.set_raw_steps([new_step] + steps[index:])
def insert_after(self, new_step):
steps = self.parent.get_raw_steps()
index = steps.index(self.step_controller_step) + 1
if not self._is_end_step(new_step.as_list()):
if self._is_intended_step(steps[index-1].as_list()):
if not self._is_intended_step(new_step.as_list()):
new_step.increase_indent() # shift_right(0) # DEBUG Hard coded!
else:
if self._is_intended_step(new_step.as_list()) and isinstance(new_step, StepController):
new_step.decrease_indent() # shift_left(1) # DEBUG Hard coded!
self.parent.set_raw_steps(steps[:index] + [new_step] + steps[index:])
def remove_empty_columns_from_end(self):
cells = self.as_list()
while cells != [] and cells[-1].strip() == '':
cells.pop()
self.recreate(cells)
def remove_empty_columns_from_beginning(self):
cells = self.step_controller_step.as_list()
if cells != [] and cells[0].strip() == '':
cells = cells[1:]
self.recreate(cells)
def remove(self):
self.parent.data.steps.remove(self.step_controller_step)
self.parent.clear_cached_steps()
def move_up(self):
previous_step = self.parent.step(self._index() - 1)
self.remove()
previous_step.insert_before(self.step_controller_step)
def move_down(self):
next_step = self.parent.step(self._index() + 1)
self.remove()
next_step.insert_after(self.step_controller_step)
def _index(self):
return self.parent.index_of_step(self.step_controller_step)
def has_only_comment(self):
non_empty_cells = [cell for cell
in self.step_controller_step.as_list() if cell.strip() != '']
return len(non_empty_cells) == 1 and \
non_empty_cells[0].startswith('#')
def _get_comment(self, cells):
if not cells:
return None
return cells[-1].strip() if cells[-1].startswith('#') else None
def recreate(self, cells, comment=None):
self.step_controller_step.__init__(cells, comment)
self.recalculate_keyword_column()
def _is_partial_for_loop_step(self, cells):
return cells and (cells[self._keyword_column].replace(' ', '').upper() == ':FOR'
or cells[self._keyword_column] == 'FOR')
def _is_for_loop(self):
return self.keyword == 'FOR'
def _is_intended_step(self, cells):
return cells and not cells[0].strip() and any(c.strip() for c in cells) and self._index() > 0
@staticmethod
def _is_end_step(cells):
return cells and ('END' in cells) # cells[0] == 'END' # DEBUG: Improve check
def _recreate_as_intended_step(self, for_loop_step, cells, comment, index):
self.remove()
for_loop_step.add_step(robotapi.Step(cells[:], comment))
self._recreate_next_step(index)
def _recreate_next_step(self, index):
if len(self.parent.steps) > index + 1:
next_step = self.parent.step(index + 1)
next_step.recreate(next_step.as_list())
def notify_value_changed(self):
self.parent.notify_steps_changed()
def increase_indent(self):
self.indent.append('')
return len(self.indent)
def decrease_indent(self):
self.indent = self.indent[:-1] if len(self.indent) > 0 else []
return len(self.indent)
@property
def steps(self):
return [IntendedStepController(self, sub_step)
for sub_step in self.get_raw_steps()]
def __len__(self):
return len(self.step_controller_step)
class ForLoopStepController(StepController):
def __init__(self, parent, step):
StepController.__init__(self, parent, step)
self.inner_kw_pos = self._first_non_empty_cell()
@property
def name(self):
return self.parent.name
@property
def assignments(self):
return self.step_controller_step.vars
"""
@property
def _keyword_column(self):
return self.inner_kw_pos
"""
def move_up(self):
previous_step = self.parent.step(self._index() - 1)
if isinstance(previous_step, ForLoopStepController):
self._swap_forloop_headers(previous_step)
else:
self.get_raw_steps().insert(0, previous_step.step_controller_step)
previous_step.remove()
def _swap_forloop_headers(self, previous_step):
previous_step.step_controller_step.steps = self.step_controller_step.steps
self.step_controller_step.steps = []
steps = self.parent.get_raw_steps()
i = steps.index(self.step_controller_step)
steps[i - 1] = self.step_controller_step
steps[i] = previous_step.step_controller_step
self.parent.set_raw_steps(steps)
def move_down(self):
next_step = self.step(self._index() + 1)
next_step.move_up()
if len(self.step_controller_step.steps) == 0:
self._recreate_complete_for_loop_header(cells=self.as_list())
def insert_after(self, new_step):
self.get_raw_steps().insert(0, new_step)
def step(self, index):
return self.parent.step(index)
def _has_comment_keyword(self):
return False
def get_raw_steps(self):
return self.step_controller_step.steps
def set_raw_steps(self, steps):
self.step_controller_step.steps = steps
def _get_cell_position(self, col):
until_range = len(self.step_controller_step.vars) + 1
flavor = self.step_controller_step.flavor
if col == self._keyword_column:
return CellPosition(CellType.KEYWORD, None)
if col < self._keyword_column + until_range:
return CellPosition(CellType.ASSIGN, self.step_controller_step.vars[:])
if col == self._keyword_column + until_range:
return CellPosition(CellType.MANDATORY, None)
if 'IN RANGE' not in flavor:
return CellPosition(CellType.OPTIONAL, None)
if col <= self._keyword_column + until_range + 1:
return CellPosition(CellType.MANDATORY, None)
if col <= self._keyword_column + until_range + 3:
return CellPosition(CellType.OPTIONAL, None)
return CellPosition(CellType.MUST_BE_EMPTY, None)
def get_cell_info(self, col):
position = self._get_cell_position(col)
content = self._get_content_with_type(col, position)
return self._build_cell_info(content, position)
def _build_cell_info(self, content, position):
return CellInfo(content, position, for_loop=True)
@property
def steps(self):
return [IntendedStepController(self, sub_step)
for sub_step in self.get_raw_steps()]
def index_of_step(self, step):
index_in_for_loop = self.get_raw_steps().index(step)
return self._index() + index_in_for_loop + 1
def _get_comment(self, cells):
return None
def comment(self):
print(f"\nDEBUG: ForLoopStepController RAW STEPS: {self.get_raw_steps()}")
for i in self.get_raw_steps():
print(f"\nDEBUG: ForLoopStepController PRINT STEPS: {i.as_list()}")
col = self.step_controller_step.inner_kw_pos
header = self.as_list()
if col > 0:
self._replace_with_new_cells(header[0:col-1] + ['Comment'] + header[col:])
else:
self._replace_with_new_cells(['Comment'] + header)
def contains_keyword(self, name):
return False
def add_step(self, step):
print(f"\nDEBUG: ForLoopStepController enter add_step step={step.as_list()}")
self.get_raw_steps().append(step)
def recreate(self, cells, comment=None, delete=False):
kw_index = None
for idx in range(0, len(cells)):
if cells[idx] == '':
continue
if cells[idx] == 'FOR':
kw_index = idx
break
if kw_index and not delete: # Avoid IndentedStep when DeleteCells
if comment:
self._recreate_complete_for_loop_header(['', cells[:], comment[:]])
else:
self._recreate_complete_for_loop_header([''] + cells)
else:
new_cells = cells[:]
index = self._index()
self.parent.replace_step(index, robotapi.Step(new_cells, comment))
self.recalculate_keyword_column()
def _recreate_complete_for_loop_header(self, cells):
self.step_controller_step.__init__(self.parent, cells[:])
def remove(self):
steps = self.parent.data.steps
index = steps.index(self.step_controller_step)
steps.remove(self.step_controller_step)
self.parent.data.steps = \
steps[:index] + self.get_raw_steps() + steps[index:]
self.step_controller_step.steps = []
def _represent_valid_for_loop_header(self, cells):
if not cells:
return False
if cells[0] != self.as_list()[0]:
return False
in_token_index = len(self.vars) + 1
if len(cells) <= in_token_index:
return False
if len(self.as_list()) <= in_token_index:
return False
if cells[in_token_index] != self.as_list()[in_token_index]:
return False
return True
def _replace_with_new_cells(self, cells):
index = self.parent.index_of_step(self.step_controller_step)
self.parent.replace_step(index, robotapi.Step(cells))
self.get_raw_steps().reverse()
for substep in self.steps:
self.parent.add_step(index + 1, robotapi.Step(substep.as_list()))
def notify_steps_changed(self):
self.notify_value_changed()
def has_template(self):
return self.parent.has_template()
class IntendedStepController(StepController):
_invalid = False
def _get_cell_position(self, col):
if col < self._keyword_column:
return CellPosition(CellType.MUST_BE_EMPTY, None)
return StepController._get_cell_position(self, col)
def _get_local_namespace(self):
p = self.parent.parent
index = p.index_of_step(self.step_controller_step)
return local_namespace(p, self.datafile_controller.namespace, index)
def _get_content_with_type(self, col, position):
if col < self._keyword_column:
return CellContent(ContentType.EMPTY, None)
return StepController._get_content_with_type(self, col, position)
def recreate(self, cells, comment=None, delete=False):
if (cells == [] or cells[0] == '') and not delete: # Avoid IndentedStep when DeleteCells
self.step_controller_step.__init__(cells[:], comment=comment)
if self.step_controller_step not in self.parent.get_raw_steps():
self.parent.add_step(self.step_controller_step)
else:
self.step_controller_step.__init__(cells[:], comment=comment)
if self.step_controller_step not in self.parent.get_raw_steps():
self.parent.add_step(self.step_controller_step)
if not delete:
self._recreate_as_normal_step(cells, comment)
self.recalculate_keyword_column()
def _recreate_as_normal_step(self, cells, comment=None):
steps = self.parent.steps
index = [s.step_controller_step for s in steps].index(self.step_controller_step)
for i, step in reversed(list(enumerate(steps))):
if i == index:
break
step.replace_with_normal_step(i, step.as_list())
self.replace_with_normal_step(index, cells, comment)
def replace_with_normal_step(self, index, cells=None, comment=None):
index_of_parent = self.parent.parent.index_of_step(self.parent.step_controller_step)
self.parent.parent.add_step(
index_of_parent + index + 2,
robotapi.Step(cells or self.as_list(), comment=comment))
self.parent.get_raw_steps().pop(index)
def remove(self):
self.parent.get_raw_steps().remove(self.step_controller_step)
def remove_empty_columns_from_end(self):
if self._invalid:
return
StepController.remove_empty_columns_from_end(self) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/controller/stepcontrollers.py | 0.534127 | 0.266882 | stepcontrollers.py | pypi |
from ..publish.messages import RideModificationPrevented
class _BaseController(object):
@property
def display_name(self):
return self.data.name
def execute(self, command):
if not command.modifying or self.is_modifiable():
return command.execute(self)
else:
RideModificationPrevented(controller=self).publish()
def is_modifiable(self):
return True
def is_excluded(self):
return False
class ControllerWithParent(_BaseController):
@property
def parent(self):
return self._parent
def set_parent(self, new_parent):
self._parent = new_parent
def mark_dirty(self):
if self._parent:
self._parent.mark_dirty()
@property
def dirty(self):
return self._parent.dirty
@property
def datafile_controller(self):
return self._parent.datafile_controller
@property
def datafile(self):
return self._parent.datafile
@property
def datafiles(self):
return self._parent.datafiles
def is_modifiable(self):
return self.datafile_controller.is_modifiable()
class WithNamespace(object):
namespace = None # Ensure namespace exists
def _set_namespace_from(self, controller):
self._set_namespace(controller.namespace)
def _set_namespace(self, namespace):
self.namespace = namespace
def get_namespace(self):
return self.namespace
def update_namespace(self):
if not self.namespace:
return
self.namespace.update()
def register_for_namespace_updates(self, listener):
if not self.namespace:
return
self.namespace.register_update_listener(listener)
def unregister_namespace_updates(self, listener):
if not self.namespace:
return
self.namespace.unregister_update_listener(listener)
def clear_namespace_update_listeners(self):
self.namespace.clear_update_listeners()
def is_user_keyword(self, datafile, value):
return self.namespace.is_user_keyword(datafile, value)
def is_library_keyword(self, datafile, value):
return self.namespace.is_library_keyword(datafile, value)
def get_all_keywords_from(self, *datafiles):
return self.namespace.get_all_keywords(*datafiles)
def get_all_cached_library_names(self):
return self.namespace.get_all_cached_library_names()
def keyword_info(self, datafile, keyword_name):
return self.namespace.find_keyword(datafile, keyword_name)
def is_library_import_ok(self, imp):
return self.namespace.is_library_import_ok(self.datafile, imp)
def is_variables_import_ok(self, imp):
# print("DEBUG: BaseController is_variables_import_ok %s\n" % imp.name)
return self.namespace.is_variables_import_ok(self.datafile, imp)
class WithUndoRedoStacks(object):
@property
def _undo(self):
if not hasattr(self, '_undo_stack'):
self._undo_stack = []
return self._undo_stack
@property
def _redo(self):
if not hasattr(self, '_redo_stack'):
self._redo_stack = []
return self._redo_stack
def clear_undo(self):
self._undo_stack = []
def is_undo_empty(self):
return self._undo == []
def pop_from_undo(self):
return self._undo.pop()
def push_to_undo(self, command):
self._undo.append(command)
def clear_redo(self):
self._redo_stack = []
def is_redo_empty(self):
return self._redo == []
def pop_from_redo(self):
return self._redo.pop()
def push_to_redo(self, command):
self._redo.append(command) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/controller/basecontroller.py | 0.443841 | 0.291497 | basecontroller.py | pypi |
import os
from itertools import chain
from .. import robotapi
from .arguments import parse_arguments_to_var_dict
from .basecontroller import ControllerWithParent, WithUndoRedoStacks
from .settingcontrollers import (DocumentationController, FixtureController, TagsController, TimeoutController,
TemplateController, ArgumentsController, ReturnValueController)
from .stepcontrollers import ForLoopStepController, StepController, IntendedStepController
from .tags import Tag
from ..namespace.local_namespace import local_namespace
from ..publish.messages import (RideItemStepsChanged, RideItemNameChanged, RideItemSettingsChanged,
RideUserKeywordRemoved)
from ..spec.iteminfo import ResourceUserKeywordInfo, TestCaseUserKeywordInfo
from ..utils import variablematcher
KEYWORD_NAME_FIELD = 'Keyword Name'
TESTCASE_NAME_FIELD = 'Test Case Name'
def _empty_step():
return robotapi.Step([])
class ItemNameController(object):
def __init__(self, item):
self._item = item
def contains_keyword(self, name):
if isinstance(name, str):
return self._item.name == name
return name.match(self._item.name)
def contains_variable(self, name):
return variablematcher.value_contains_variable(self._item.name, name)
def replace_keyword(self, new_name, old_value=None):
print(f"DEBUG: macrocontrollers.py replace_keyword new_name={new_name} old_value={old_value}")
self._item.rename(new_name)
def rename(self, new_name):
self._item.rename(new_name)
def notify_value_changed(self):
self._item.notify_name_changed()
@property
def parent(self):
return self._item
class KeywordNameController(ItemNameController):
_name_field = KEYWORD_NAME_FIELD
class TestCaseNameController(ItemNameController):
__test__ = False
_name_field = TESTCASE_NAME_FIELD
class WithStepsController(ControllerWithParent, WithUndoRedoStacks):
def __init__(self, parent_controller, data):
self._parent = parent_controller
self.data = data
self._init(data)
self._has_steps_changed = True
self._steps_cached = None
self.datafile_controller.register_for_namespace_updates(
self.clear_cached_steps)
@property
def source(self):
return os.path.basename(self.data.source) if self.data.source else ''
@property
def name(self):
return self.data.name
@property
def steps(self):
if self._has_steps_changed:
self._recreate_steps()
return self._steps_cached
def set_parent(self, new_parent):
self.clear_cached_steps()
ControllerWithParent.set_parent(self, new_parent)
def _recreate_steps(self):
flattened_steps = []
for step in self.data.steps:
if step.is_for_loop():
for_loop = ForLoopStepController(self, step)
flattened_steps.append(for_loop)
flattened_steps.extend(for_loop.steps)
else:
flattened_steps.append(StepController(self, step))
self._steps_cached = flattened_steps
self._has_steps_changed = False
def clear_cached_steps(self):
self._has_steps_changed = True
self._steps_cached = None
@property
def max_columns(self):
return max(chain((len(step) for step in self.steps), [0]))
def has_template(self):
return False
def step(self, index):
return self.steps[index]
def index_of_step(self, step):
return [s.step_controller_step for s in self.steps].index(step)
def replace_step(self, index, new_step):
corrected_index = index
for i in range(index):
if isinstance(self.step(i), IntendedStepController):
corrected_index -= 1
self.data.steps[corrected_index] = new_step
self._has_steps_changed = True
def move_step_up(self, index):
self.step(index).move_up()
self._has_steps_changed = True
def move_step_down(self, index):
self.step(index).move_down()
self._has_steps_changed = True
def set_steps(self, steps):
self.data.steps = steps
self._has_steps_changed = True
def update_namespace(self):
self.datafile_controller.update_namespace()
def get_local_namespace(self):
# print(f"DEBUG: local namespace controller.namespace {self.datafile_controller.namespace}")
return local_namespace(self, self.datafile_controller.namespace)
def get_local_namespace_for_row(self, row):
# print(f"DEBUG: local namespace_for_row controller.namespace {self.datafile_controller.namespace} row {row}")
return local_namespace(self, self.datafile_controller.namespace, row)
def get_cell_info(self, row, col):
steps = self.steps
if row < 0 or len(steps) <= row:
return None
return steps[row].get_cell_info(col)
def get_keyword_info(self, kw_name):
return self.datafile_controller.keyword_info(None, kw_name)
def is_user_keyword(self, value):
return self.datafile_controller.is_user_keyword(None, value)
def is_library_keyword(self, value):
return self.datafile_controller.is_library_keyword(None, value)
def delete(self):
self.datafile_controller.unregister_namespace_updates(
self.clear_cached_steps)
self._parent.delete(self)
self.notify_keyword_removed()
def rename(self, new_name):
self.data.name = new_name.strip()
self.mark_dirty()
def copy(self, name):
new = self._parent.new(name)
for orig, copied in zip(self.settings, new.settings):
copied.set_from(orig)
new.data.steps = [robotapi.Step(s.as_list()) for s in self.steps]
new.notify_steps_changed()
return new
def get_empty_rows(self):
return [index for index, step in enumerate(self.steps)
if self._is_empty_step(step)]
@staticmethod
def _is_empty_step(step):
return step.as_list() in [[], ['']]
def remove_step(self, index):
self._remove_step(self.steps[index])
self._has_steps_changed = True
def recreate(self):
self._parent.add(self)
def _remove_step(self, step):
step.remove()
self._has_steps_changed = True
def add_step(self, index, step=None):
# print(f"\nDEBUG: WithStepsController enter add_step step={step}")
if step is None:
step = _empty_step()
if index == len(self.steps):
self.data.steps.append(step)
else:
previous_step = self.step(index)
previous_step.insert_before(step)
self._has_steps_changed = True
def create_keyword(self, name, argstr):
name = self._remove_bdd_prefix(name)
validation = self.datafile_controller.validate_keyword_name(name)
if validation.error_message:
raise ValueError(validation.error_message)
return self.datafile_controller.create_keyword(name, argstr)
@staticmethod
def _remove_bdd_prefix(name):
matcher = name.lower()
for match in ['given ', 'when ', 'then ', 'and ', 'but ']:
if matcher.startswith(match):
return name[len(match):]
return name
def create_test(self, name):
return self.datafile_controller.create_test(name)
def extract_keyword(self, name, argstr, step_range):
extracted_steps = self._extract_steps(step_range)
self._replace_steps_with_kw(name, step_range)
self._create_extracted_kw(name, argstr, extracted_steps)
def get_raw_steps(self):
# Reveales inner state so can't be sure if cache is up-to-date
self._has_steps_changed = True
return self.data.steps
def set_raw_steps(self, steps):
self.set_steps(steps)
def _extract_steps(self, step_range):
rem_start, rem_end = step_range
extracted_steps = self.steps[rem_start:rem_end + 1]
return self._convert_controller_to_steps(extracted_steps)
@staticmethod
def _convert_controller_to_steps(step_controllers):
return [robotapi.Step(s.as_list()) for s in step_controllers]
def _replace_steps_with_kw(self, name, step_range):
steps_before_extraction_point = self._convert_controller_to_steps(
self.steps[:step_range[0]])
extracted_kw_step = [robotapi.Step([name])]
steps_after_extraction_point = self._convert_controller_to_steps(
self.steps[step_range[1] + 1:])
self.set_steps(steps_before_extraction_point + extracted_kw_step +
steps_after_extraction_point)
def _create_extracted_kw(self, name, argstr, extracted_steps):
controller = self.datafile_controller.create_keyword(name, argstr)
controller.set_steps(extracted_steps)
return controller
def validate_name(self, name):
return self._parent.validate_name(name, self)
def notify_name_changed(self, old_name=None):
self.update_namespace()
self.mark_dirty()
RideItemNameChanged(item=self, old_name=old_name).publish()
def notify_keyword_removed(self):
self.update_namespace()
RideUserKeywordRemoved(datafile=self.datafile, name=self.name, item=self).publish()
self.notify_steps_changed()
def notify_settings_changed(self):
self.update_namespace()
self._notify(RideItemSettingsChanged)
def notify_steps_changed(self):
self._has_steps_changed = True
self._notify(RideItemStepsChanged)
def _notify(self, messageclass):
self.mark_dirty()
messageclass(item=self).publish()
class TestCaseController(WithStepsController):
__test__ = False
_populator = robotapi.TestCasePopulator
filename = ""
def _init(self, test):
self._test = test
self._run_passed = None
def __eq__(self, other):
if self is other:
return True
if other.__class__ != self.__class__:
return False
return self._test == other._test
def __hash__(self):
return hash(repr(self))
@property
def longname(self):
return self.parent.parent.longname + '.' + self.data.name
@property
def test_name(self):
return TestCaseNameController(self)
@property
def tags(self):
return TagsController(self, self._test.tags)
@property
def force_tags(self):
return self.datafile_controller.force_tags
@property
def default_tags(self):
return self.datafile_controller.default_tags
def add_tag(self, name):
self.tags.add(Tag(name))
@property
def settings(self):
return [
self.documentation,
FixtureController(self, self._test.setup),
FixtureController(self, self._test.teardown),
TimeoutController(self, self._test.timeout),
TemplateController(self, self._test.template),
self.tags
]
@property
def documentation(self):
return DocumentationController(self, self._test.doc)
def move_up(self):
return self._parent.move_up(self._test)
def move_down(self):
return self._parent.move_down(self._test)
def validate_test_name(self, name):
return self._parent.validate_name(name)
def validate_keyword_name(self, name):
return self.datafile_controller.validate_keyword_name(name)
@staticmethod
def get_local_variables():
return {}
def has_template(self):
template = self._get_template()
if not template:
return False
return bool(template.value)
def _get_template(self):
template = self._test.template
if template.value is not None:
return template
return self.datafile_controller.get_template()
@property
def run_passed(self):
return self._run_passed
@run_passed.setter
def run_passed(self, value):
if value not in [True, False, None]:
self._run_passed = None # Test did not run
if value:
self._run_passed = True # Test execution passed
else:
self._run_passed = False # Test execution failed
class UserKeywordController(WithStepsController):
_populator = robotapi.UserKeywordPopulator
_TEARDOWN_NOT_SET = object()
_teardown = _TEARDOWN_NOT_SET
def _init(self, kw):
self.kw = kw
# Needed for API compatibility in tag search
self.force_tags = []
self.default_tags = []
def __eq__(self, other):
if self is other:
return True
if other.__class__ != self.__class__:
return False
return self.kw == other.kw
def __hash__(self):
return hash(repr(self))
@property
def info(self):
if isinstance(self.datafile, robotapi.ResourceFile):
return ResourceUserKeywordInfo(self.data)
return TestCaseUserKeywordInfo(self.data)
@property
def keyword_name(self):
return KeywordNameController(self)
def move_up(self):
return self._parent.move_up(self.kw)
def move_down(self):
return self._parent.move_down(self.kw)
@property
def settings(self):
result = [
DocumentationController(self, self.kw.doc),
ArgumentsController(self, self.kw.args),
self.teardown,
ReturnValueController(self, self.kw.return_),
TimeoutController(self, self.kw.timeout),
TagsController(self, self.kw.tags),
]
return result
@property
def teardown(self):
if self._teardown == self._TEARDOWN_NOT_SET:
self._teardown = FixtureController(self, self.kw.teardown)
return self._teardown
@property
def arguments(self):
return ArgumentsController(self, self.kw.args)
def validate_keyword_name(self, name):
return self._parent.validate_name(name)
def get_local_variables(self):
return parse_arguments_to_var_dict(self.kw.args.value, self.kw.name) | /robotframework-ride-2.0.7.tar.gz/robotframework-ride-2.0.7/src/robotide/controller/macrocontrollers.py | 0.498535 | 0.186021 | macrocontrollers.py | pypi |
from functools import lru_cache
from pathlib import Path
from pathspec import PathSpec
from robocop.exceptions import FileError
DEFAULT_EXCLUDES = r"(\.direnv|\.eggs|\.git|\.hg|\.nox|\.tox|\.venv|venv|\.svn)"
def find_project_root(srcs):
"""Return a directory containing .git, .robocop or pyproject.toml.
That directory will be a common parent of all files and directories
passed in `srcs`.
If no directory in the tree contains a marker that would specify it's the
project root, the root of the file system is returned.
"""
if not srcs:
return Path("/").resolve()
path_srcs = [Path(Path.cwd(), src).resolve() for src in srcs]
# A list of lists of parents for each 'src'. 'src' is included as a
# "parent" of itself if it is a directory
src_parents = [list(path.parents) + ([path] if path.is_dir() else []) for path in path_srcs]
common_base = max(
set.intersection(*(set(parents) for parents in src_parents)),
key=lambda path: path.parts,
)
for directory in (common_base, *common_base.parents):
if (
(directory / ".git").exists()
or (directory / "pyproject.toml").is_file()
or (directory / ".robocop").is_file()
):
return directory
return directory
def find_file_in_project_root(config_name, root):
for parent in (root, *root.parents):
if (parent / ".git").exists() or (parent / config_name).is_file():
return parent / config_name
return parent / config_name
@lru_cache()
def get_gitignore(root):
"""Return a PathSpec matching gitignore content if present."""
gitignore = root / ".gitignore"
lines = []
if gitignore.is_file():
with gitignore.open(encoding="utf-8") as gf:
lines = gf.readlines()
return PathSpec.from_lines("gitwildmatch", lines)
def get_files(config):
gitignore = get_gitignore(config.root)
for file in config.paths:
yield from get_absolute_path(Path(file), config, gitignore)
def get_absolute_path(path, config, gitignore):
if not path.exists():
raise FileError(path)
if config.is_path_ignored(path):
return
if gitignore is not None and gitignore.match_file(path):
return
if path.is_file():
if should_parse(config, path):
yield path.absolute()
elif path.is_dir():
for file in path.iterdir():
if file.is_dir() and not config.recursive:
continue
yield from get_absolute_path(
file,
config,
gitignore + get_gitignore(path) if gitignore is not None else None,
)
def should_parse(config, file):
"""Check if file extension is in list of supported file types (can be configured from cli)"""
return file.suffix and file.suffix.lower() in config.filetypes | /robotframework_robocop-2.2.0-py3-none-any.whl/robocop/files.py | 0.679285 | 0.333449 | files.py | pypi |
class RobocopFatalError(ValueError):
pass
class ConfigGeneralError(RobocopFatalError):
pass
class InvalidExternalCheckerError(RobocopFatalError):
def __init__(self, path):
msg = f'Fatal error: Failed to load external rules from file "{path}". Verify if the file exists'
super().__init__(msg)
class FileError(RobocopFatalError):
def __init__(self, source):
msg = f'File "{source}" does not exist'
super().__init__(msg)
class ArgumentFileNotFoundError(RobocopFatalError):
def __init__(self, source):
msg = f'Argument file "{source}" does not exist'
super().__init__(msg)
class NestedArgumentFileError(RobocopFatalError):
def __init__(self, source):
msg = f'Nested argument file in "{source}"'
super().__init__(msg)
class InvalidArgumentError(RobocopFatalError):
def __init__(self, msg):
super().__init__(f"Invalid configuration for Robocop:\n{msg}")
class RuleNotFoundError(RobocopFatalError):
def __init__(self, rule, checker):
super().__init__(
f"{checker.__class__.__name__} checker does not contain rule `{rule}`. "
f"Available rules: {', '.join(checker.rules.keys())}"
)
class RuleParamNotFoundError(RobocopFatalError):
def __init__(self, rule, param, checker):
super().__init__(
f"Rule `{rule.name}` in `{checker.__class__.__name__}` checker does not contain `{param}` param. "
f"Available params:\n {rule.available_configurables()[1]}"
)
class RuleParamFailedInitError(RobocopFatalError):
def __init__(self, param, value, err):
desc = f" Parameter info: {param.desc}" if param.desc else ""
super().__init__(
f"Failed to configure param `{param.name}` with value `{value}`. Received error `{err}`.\n"
f" Parameter type: {param.converter}\n" + desc
)
class RuleReportsNotFoundError(RobocopFatalError):
def __init__(self, rule, checker):
super().__init__(f"{checker.__class__.__name__} checker `reports` attribute contains unknown rule `{rule}`") | /robotframework_robocop-2.2.0-py3-none-any.whl/robocop/exceptions.py | 0.725454 | 0.27229 | exceptions.py | pypi |
from collections import defaultdict
from robot.api import Token
from robocop.checkers import VisitorChecker
from robocop.rules import Rule, RuleSeverity
rules = {
"0601": Rule(
rule_id="0601",
name="tag-with-space",
msg="Tag '{{ tag }}' should not contain spaces",
severity=RuleSeverity.WARNING,
docs="""
Example of rule violation::
Test
[Tags] ${tag with space}
""",
),
"0602": Rule(
rule_id="0602",
name="tag-with-or-and",
msg="Tag '{{ tag }}' with reserved word OR/AND."
" Hint: make sure to include this tag using lowercase name to avoid issues",
severity=RuleSeverity.INFO,
docs="""
OR and AND words are used to combine tags when selecting tests to be run in Robot Framework. Using following
configuration::
robot --include tagANDtag2
Robot Framework will only execute tests that contain `tag` and `tag2`. That's why it's best to avoid AND and OR
in tag names. See
`docs <https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#tag-patterns>`_
for more information.
Tag matching is case-insensitive. If your tag contains OR or AND you can use lowercase to match it.
For example, if your tag is `PORT` you can match it with `port`.
""",
),
"0603": Rule(
rule_id="0603",
name="tag-with-reserved-word",
msg="Tag '{{ tag }}' prefixed with reserved word `robot:`",
severity=RuleSeverity.WARNING,
docs="""
This prefix is used by Robot Framework special tags. More details
`here <https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#reserved-tags>`_.
Special tags currently in use:
- robot:exit
- robot:no-dry-run
- robot:continue-on-failure
- robot:recursive-continue-on-failure
- robot:skip
- robot:skip-on-failure
- robot:exclude
""",
),
"0605": Rule(
rule_id="0605",
name="could-be-forced-tags",
msg="All tests in suite share these tags: '{{ tags }}'. "
"You can define them in 'Force Tags' in suite settings instead",
severity=RuleSeverity.INFO,
docs="""
Example::
*** Test Cases ***
Test
[Tag] featureX smoke
Step
Test 2
[Tag] featureX
Step
In this example all tests share one common tag `featureX`. It can be declared just once using `Force Tags`.
""",
),
"0606": Rule(
rule_id="0606",
name="tag-already-set-in-force-tags",
msg="Tag '{{ tag }}' is already set by Force Tags in suite settings",
severity=RuleSeverity.INFO,
docs="""
Avoid repeating same tags in tests when the tag is already declared in `Force Tags`.
Example of rule violation::
*** Setting ***
Force Tags common-tag
*** Test Cases ***
Test
[Tag] sanity common-tag
""",
),
"0607": Rule(
rule_id="0607",
name="unnecessary-default-tags",
msg="Tags defined in Default Tags are always overwritten",
severity=RuleSeverity.INFO,
docs="""
Example of rule violation::
*** Settings ***
Default Tags tag1 tag2
*** Test Cases ***
Test
[Tags] tag3
Step
Test 2
[Tags] tag4
Step
Since `Test` and `Test 2` have `[Tags]` section, `Default Tags` setting is never used.
""",
),
"0608": Rule(
rule_id="0608",
name="empty-tags",
msg="[Tags] setting without values{{ optional_warning }}",
severity=RuleSeverity.WARNING,
docs="""
If you want to use empty `[Tags]` (for example to overwrite `Default Tags`) then use `NONE` value
to be explicit.
""",
),
"0609": Rule(
rule_id="0609",
name="duplicated-tags",
msg="Multiple tags with name '{{ name }}' (first occurrence at line {{ line }} column {{ column }})",
severity=RuleSeverity.WARNING,
docs="""
Tags are free text, but they are normalized so that they are converted to lowercase and all spaces are removed.
Only first tag is used, other occurrences are ignored.
Example of duplicated tags::
Test
[Tags] Tag TAG tag t a g
""",
),
}
class TagNameChecker(VisitorChecker):
"""Checker for tag names. It scans for tags with spaces or Robot Framework reserved words."""
reports = (
"tag-with-space",
"tag-with-or-and",
"tag-with-reserved-word",
"duplicated-tags",
)
is_keyword = False
reserved_tags = {
"robot:exit",
"robot:no-dry-run",
"robot:continue-on-failure",
"robot:recursive-continue-on-failure",
"robot:skip",
"robot:skip-on-failure",
"robot:exclude",
}
def visit_ForceTags(self, node): # noqa
self.check_tags(node)
visit_DefaultTags = visit_Tags = visit_ForceTags
def visit_Documentation(self, node): # noqa
if self.is_keyword:
*_, last_line = node.lines
filtered_line = filter(
lambda tag: tag.type not in Token.NON_DATA_TOKENS and tag.type != Token.DOCUMENTATION,
last_line,
)
tags = defaultdict(list)
for index, token in enumerate(filtered_line):
if index == 0 and token.value.lower() != "tags:":
break
token.value = token.value.rstrip(",")
normalized_tag = token.value.lower().replace(" ", "")
tags[normalized_tag].append(token)
self.check_tag(token, node)
self.check_duplicates(tags)
def visit_Keyword(self, node): # noqa
self.is_keyword = True
super().generic_visit(node)
self.is_keyword = False
def check_tags(self, node):
tags = defaultdict(list)
for tag in node.data_tokens[1:]:
normalized_tag = tag.value.lower().replace(" ", "")
tags[normalized_tag].append(tag)
self.check_tag(tag, node)
self.check_duplicates(tags)
def check_duplicates(self, tags):
for nodes in tags.values():
for duplicate in nodes[1:]:
self.report(
"duplicated-tags",
name=duplicate.value,
line=nodes[0].lineno,
column=nodes[0].col_offset + 1,
node=duplicate,
col=duplicate.col_offset + 1,
)
def check_tag(self, tag, node):
if " " in tag.value:
self.report("tag-with-space", tag=tag.value, node=node, lineno=tag.lineno, col=tag.col_offset + 1)
if "OR" in tag.value or "AND" in tag.value:
self.report("tag-with-or-and", tag=tag.value, node=node, lineno=tag.lineno, col=tag.col_offset + 1)
if tag.value.startswith("robot:") and tag.value not in self.reserved_tags:
self.report(
"tag-with-reserved-word",
tag=tag.value,
node=node,
lineno=tag.lineno,
col=tag.col_offset + 1,
)
class TagScopeChecker(VisitorChecker):
"""Checker for tag scopes. If all tests in suite have the same tags, it will suggest using `Force Tags`"""
reports = (
"could-be-forced-tags",
"tag-already-set-in-force-tags",
"unnecessary-default-tags",
"empty-tags",
)
def __init__(self):
self.tags = []
self.force_tags = []
self.default_tags = []
self.force_tags_node = None
self.default_tags_node = None
self.test_cases_count = 0
self.in_keywords = False
super().__init__()
def visit_File(self, node): # noqa
self.tags = []
self.force_tags = []
self.default_tags = []
self.test_cases_count = 0
self.force_tags_node = None
super().visit_File(node)
if not self.tags:
return
if len(self.tags) != self.test_cases_count:
return
if self.default_tags:
self.report(
"unnecessary-default-tags",
node=node if self.default_tags_node is None else self.default_tags_node,
)
if self.test_cases_count < 2:
return
common_tags = set.intersection(*[set(tags) for tags in self.tags])
common_tags = common_tags - set(self.force_tags)
if common_tags:
self.report(
"could-be-forced-tags",
tags=", ".join(common_tags),
node=node if self.force_tags_node is None else self.force_tags_node,
)
def visit_KeywordSection(self, node): # noqa
self.in_keywords = True
self.generic_visit(node)
self.in_keywords = False
def visit_TestCase(self, node): # noqa
self.test_cases_count += 1
self.generic_visit(node)
def visit_ForceTags(self, node): # noqa
self.force_tags = [token.value for token in node.data_tokens[1:]]
self.force_tags_node = node
def visit_DefaultTags(self, node): # noqa
self.default_tags = [token.value for token in node.data_tokens[1:]]
self.default_tags_node = node
def visit_Tags(self, node): # noqa
if not node.values:
suffix = "" if self.in_keywords else ". Consider using NONE if you want to overwrite the Default Tags"
self.report("empty-tags", optional_warning=suffix, node=node, col=node.end_col_offset)
self.tags.append([tag.value for tag in node.data_tokens[1:]])
for tag in node.data_tokens[1:]:
if tag.value in self.force_tags:
self.report(
"tag-already-set-in-force-tags",
tag=tag.value,
node=node,
lineno=tag.lineno,
col=tag.col_offset + 1,
) | /robotframework_robocop-2.2.0-py3-none-any.whl/robocop/checkers/tags.py | 0.759136 | 0.407805 | tags.py | pypi |
from collections import defaultdict
from robot.api import Token
from robocop.checkers import VisitorChecker
from robocop.rules import Rule, RuleParam, RuleSeverity
from robocop.utils import get_errors, normalize_robot_name, normalize_robot_var_name
def configure_sections_order(value):
section_map = {
"settings": Token.SETTING_HEADER,
"variables": Token.VARIABLE_HEADER,
"testcase": Token.TESTCASE_HEADER,
"testcases": Token.TESTCASE_HEADER,
"task": "TASK HEADER",
"tasks": "TASK HEADER",
"keyword": Token.KEYWORD_HEADER,
"keywords": Token.KEYWORD_HEADER,
}
sections_order = {}
for index, name in enumerate(value.split(",")):
if name.lower() not in section_map or section_map[name.lower()] in sections_order:
raise ValueError(f"Invalid section name: `{name}`")
sections_order[section_map[name.lower()]] = index
if Token.TESTCASE_HEADER in sections_order:
sections_order["TASK HEADER"] = sections_order[Token.TESTCASE_HEADER]
return sections_order
rules = {
"0801": Rule(
rule_id="0801",
name="duplicated-test-case",
msg="Multiple test cases with name '{{ name }}' (first occurrence in line {{ first_occurrence_line }})",
severity=RuleSeverity.ERROR,
docs="""
It is not allowed to reuse the same name of the test case within the same suite in Robot Framework.
Name matching is case-insensitive and ignores spaces and underscore characters.
Duplicated test cases example::
*** Test Cases ***
Test with name
No Operation
test_with Name # it is a duplicate of 'Test with name'
No Operation
""",
),
"0802": Rule(
rule_id="0802",
name="duplicated-keyword",
msg="Multiple keywords with name '{{ name }}' (first occurrence in line {{ first_occurrence_line }})",
severity=RuleSeverity.ERROR,
docs="""
Do not define keywords with the same name inside the same file. Name matching is case-insensitive and
ignores spaces and underscore characters.
Duplicated keyword names example::
*** Keywords ***
Keyword
No Operation
keyword
No Operation
K_eywor d
No Operation
""",
),
"0803": Rule(
rule_id="0803",
name="duplicated-variable",
msg="Multiple variables with name '{{ name }}' in Variables section (first occurrence in line "
"{{ first_occurrence_line }}). "
"Note that Robot Framework is case-insensitive",
severity=RuleSeverity.ERROR,
docs="""
Variable names in Robot Framework are case-insensitive and ignore spaces and underscores. Following variables
are duplicates::
*** Variables ***
${variable} 1
${VARIAble} a
@{variable} a b
${v ariabl e} c
${v_ariable} d
""",
),
"0804": Rule(
rule_id="0804",
name="duplicated-resource",
msg="Multiple resource imports with path '{{ name }}' (first occurrence in line {{ first_occurrence_line }})",
severity=RuleSeverity.WARNING,
),
"0805": Rule(
rule_id="0805",
name="duplicated-library",
msg="Multiple library imports with name '{{ name }}' and identical arguments (first occurrence in line "
"{{ first_occurrence_line }})",
severity=RuleSeverity.WARNING,
docs="""
If you need to reimport library use alias::
*** Settings ***
Library RobotLibrary
Library RobotLibrary AS OtherRobotLibrary
""",
),
"0806": Rule(
rule_id="0806",
name="duplicated-metadata",
msg="Duplicated metadata '{{ name }}' (first occurrence in line {{ first_occurrence_line }})",
severity=RuleSeverity.WARNING,
),
"0807": Rule(
rule_id="0807",
name="duplicated-variables-import",
msg="Duplicated variables import with path '{{ name }}' (first occurrence in line {{ first_occurrence_line }})",
severity=RuleSeverity.WARNING,
),
"0808": Rule(
rule_id="0808",
name="section-already-defined",
msg="'{{ section_name }}' section header already defined in file (first occurrence in line "
"{{ first_occurrence_line }})",
severity=RuleSeverity.WARNING,
docs="""
Duplicated section in the file. Robot Framework will handle repeated sections but it is recommended to not
duplicate them.
Example::
*** Test Cases ***
My Test
Keyword
*** Keywords ***
Keyword
No Operation
*** Test Cases *** # duplicate
Other Test
Keyword
""",
),
"0809": Rule(
RuleParam(
name="sections_order",
default="settings,variables,testcases,keywords",
converter=configure_sections_order,
desc="order of sections in comma-separated list",
),
rule_id="0809",
name="section-out-of-order",
msg="'{{ section_name }}' section header is defined in wrong order: {{ recommended_order }}",
severity=RuleSeverity.WARNING,
docs="""
Sections should be defined in order set by `sections_order`
parameter (default: `settings,variables,testcases,keywords`).
To change the default order use following option::
robocop --configure section-out-of-order:sections_order:comma,separated,list,of,sections
where section should be case-insensitive name from the list: comments, settings, variables, testcases, keywords.
Order of not configured sections is ignored.
Example::
*** Settings ***
*** Keywords ***
*** Test Cases *** # it will report issue because Test Cases should be defined before Keywords
""",
),
"0810": Rule(
rule_id="0810",
name="both-tests-and-tasks",
msg="Both Task(s) and Test Case(s) section headers defined in file",
severity=RuleSeverity.ERROR,
docs="""
The file contains both Test Case and Task sections. Use only one of them. ::
*** Test Cases ***
*** Tasks ***
""",
),
"0811": Rule(
rule_id="0811",
name="duplicated-argument-name",
msg="Argument name '{{ argument_name }}' is already used",
severity=RuleSeverity.ERROR,
docs="""
Variable names in Robot Framework are case-insensitive and ignores spaces and underscores. Following arguments
are duplicates::
*** Keywords ***
Keyword
[Arguments] ${var} ${VAR} ${v_ar} ${v ar}
Other Keyword
""",
),
"0812": Rule(
rule_id="0812",
name="duplicated-assigned-var-name",
msg="Assigned variable name '{{ variable_name }}' is already used",
severity=RuleSeverity.INFO,
docs="""
Variable names in Robot Framework are case-insensitive and ignores spaces and underscores. Following variables
are duplicates::
*** Test Cases ***
Test
${var} ${VAR} ${v_ar} ${v ar} Keyword
""",
),
"0813": Rule(
rule_id="0813",
name="duplicated-setting",
msg="{{ error_msg }}",
severity=RuleSeverity.WARNING,
docs="""
Some settings can be used only once in a file. Only the first value is used.
Example::
*** Settings ***
Force Tags F1
Force Tags F2 # this setting will be ignored
""",
),
}
class DuplicationsChecker(VisitorChecker):
"""Checker for duplicated names."""
reports = (
"duplicated-test-case",
"duplicated-keyword",
"duplicated-variable",
"duplicated-resource",
"duplicated-library",
"duplicated-metadata",
"duplicated-variables-import",
"duplicated-argument-name",
"duplicated-assigned-var-name",
"duplicated-setting",
)
def __init__(self):
self.test_cases = defaultdict(list)
self.keywords = defaultdict(list)
self.variables = defaultdict(list)
self.resources = defaultdict(list)
self.libraries = defaultdict(list)
self.metadata = defaultdict(list)
self.variable_imports = defaultdict(list)
super().__init__()
def visit_File(self, node): # noqa
self.test_cases = defaultdict(list)
self.keywords = defaultdict(list)
self.variables = defaultdict(list)
self.resources = defaultdict(list)
self.libraries = defaultdict(list)
self.metadata = defaultdict(list)
self.variable_imports = defaultdict(list)
super().visit_File(node)
self.check_duplicates(self.test_cases, "duplicated-test-case")
self.check_duplicates(self.keywords, "duplicated-keyword")
self.check_duplicates(self.variables, "duplicated-variable")
self.check_duplicates(self.resources, "duplicated-resource")
self.check_duplicates(self.libraries, "duplicated-library")
self.check_duplicates(self.metadata, "duplicated-metadata")
self.check_duplicates(self.variable_imports, "duplicated-variables-import")
def check_duplicates(self, container, rule):
for nodes in container.values():
for duplicate in nodes[1:]:
self.report(rule, name=duplicate.name, first_occurrence_line=nodes[0].lineno, node=duplicate)
def visit_TestCase(self, node): # noqa
testcase_name = normalize_robot_name(node.name)
self.test_cases[testcase_name].append(node)
self.generic_visit(node)
def visit_Keyword(self, node): # noqa
keyword_name = normalize_robot_name(node.name)
self.keywords[keyword_name].append(node)
self.generic_visit(node)
def visit_KeywordCall(self, node): # noqa
assign = node.get_tokens(Token.ASSIGN)
seen = set()
for var in assign:
name = normalize_robot_var_name(var.value)
if name in seen:
self.report(
"duplicated-assigned-var-name",
variable_name=var.value,
node=node,
lineno=var.lineno,
col=var.col_offset + 1,
)
else:
seen.add(name)
def visit_VariableSection(self, node): # noqa
self.generic_visit(node)
def visit_Variable(self, node): # noqa
if not node.name or get_errors(node):
return
var_name = normalize_robot_name(self.replace_chars(node.name, "${}@&"))
self.variables[var_name].append(node)
@staticmethod
def replace_chars(name, chars):
return "".join(c for c in name if c not in chars)
def visit_ResourceImport(self, node): # noqa
if node.name:
self.resources[node.name].append(node)
def visit_LibraryImport(self, node): # noqa
if not node.name:
return
name_with_args = node.name + "".join(token.value for token in node.data_tokens[2:])
self.libraries[name_with_args].append(node)
def visit_Metadata(self, node): # noqa
if node.name is not None:
self.metadata[node.name + node.value].append(node)
def visit_VariablesImport(self, node): # noqa
if not node.name:
return
# only python files can have arguments - covered in E0404 variables-import-with-args
if not node.name.endswith(".py") and node.get_token(Token.ARGUMENT):
return
name_with_args = node.name + "".join(token.value for token in node.data_tokens[2:])
self.variable_imports[name_with_args].append(node)
def visit_Arguments(self, node): # noqa
args = set()
for arg in node.get_tokens(Token.ARGUMENT):
orig, *_ = arg.value.split("=", maxsplit=1)
name = normalize_robot_var_name(orig)
if name in args:
self.report(
"duplicated-argument-name",
argument_name=orig,
node=node,
lineno=arg.lineno,
col=arg.col_offset + 1,
)
else:
args.add(name)
def visit_Error(self, node): # noqa
for error in get_errors(node):
self.report("duplicated-setting", error_msg=error, node=node)
class SectionHeadersChecker(VisitorChecker):
"""Checker for duplicated or out of order section headers."""
reports = (
"section-already-defined",
"section-out-of-order",
"both-tests-and-tasks",
)
def __init__(self):
self.sections_by_order = []
self.sections_by_existence = dict()
super().__init__()
@staticmethod
def section_order_to_str(order):
by_index = sorted([(key, value) for key, value in order.items()], key=lambda x: x[1])
name_map = {
Token.SETTING_HEADER: "Settings",
Token.VARIABLE_HEADER: "Variables",
Token.TESTCASE_HEADER: "Test Cases / Tasks",
"TASK HEADER": "Test Cases / Tasks",
Token.KEYWORD_HEADER: "Keywords",
}
order_str = []
for name, _ in by_index:
mapped_name = name_map[name]
if mapped_name not in order_str:
order_str.append(mapped_name)
return " > ".join(order_str)
def visit_File(self, node): # noqa
self.sections_by_order = []
self.sections_by_existence = dict()
super().visit_File(node)
def visit_SectionHeader(self, node): # noqa
section_name = node.type
if section_name not in self.param("section-out-of-order", "sections_order"):
return
if section_name == Token.TESTCASE_HEADER:
if "task" in node.name.lower():
section_name = "TASK HEADER"
if Token.TESTCASE_HEADER in self.sections_by_existence:
self.report("both-tests-and-tasks", node=node)
else:
if "TASK HEADER" in self.sections_by_existence:
self.report("both-tests-and-tasks", node=node)
order_id = self.param("section-out-of-order", "sections_order")[section_name]
if section_name in self.sections_by_existence:
self.report(
"section-already-defined",
section_name=node.data_tokens[0].value,
first_occurrence_line=self.sections_by_existence[section_name],
node=node,
)
else:
self.sections_by_existence[section_name] = node.lineno
if any(previous_id > order_id for previous_id in self.sections_by_order):
self.report(
"section-out-of-order",
section_name=node.data_tokens[0].value,
recommended_order=self.section_order_to_str(self.param("section-out-of-order", "sections_order")),
node=node,
)
self.sections_by_order.append(order_id) | /robotframework_robocop-2.2.0-py3-none-any.whl/robocop/checkers/duplications.py | 0.670716 | 0.400749 | duplications.py | pypi |
from robot.parsing.model.blocks import SettingSection
from robot.parsing.model.statements import Documentation
from robocop.checkers import VisitorChecker
from robocop.rules import Rule, RuleParam, RuleSeverity
from robocop.utils.misc import str2bool
rules = {
"0201": Rule(
rule_id="0201",
name="missing-doc-keyword",
msg="Missing documentation in '{{ name }}' keyword",
severity=RuleSeverity.WARNING,
docs="""
You can add documentation to keyword using following syntax::
Keyword
[Documentation] Keyword documentation
Keyword Step
Other Step
""",
),
"0202": Rule(
RuleParam(
name="ignore_templated",
default="True",
converter=str2bool,
desc="whether templated tests should be documented or not",
),
rule_id="0202",
name="missing-doc-test-case",
msg="Missing documentation in '{{ name }}' test case",
severity=RuleSeverity.WARNING,
docs="""
You can add documentation to test case using following syntax::
Test
[Documentation] Test documentation
Keyword Step
Other Step
The rule by default ignores templated test cases but it can be configured with::
robocop --configure missing-doc-test-case:ignore_templated:False
Possible values are: Yes / 1 / True (default) or No / False / 0.
""",
),
"0203": Rule(
rule_id="0203",
name="missing-doc-suite",
msg="Missing documentation in suite",
severity=RuleSeverity.WARNING,
docs="""
You can add documentation to suite using following syntax::
*** Settings ***
Documentation Suite documentation
""",
),
}
class MissingDocumentationChecker(VisitorChecker):
"""Checker for missing documentation."""
reports = (
"missing-doc-keyword",
"missing-doc-test-case",
"missing-doc-suite",
)
def visit_Keyword(self, node): # noqa
if node.name.lstrip().startswith("#"):
return
self.check_if_docs_are_present(node, "missing-doc-keyword")
def visit_TestCase(self, node): # noqa
if self.param("missing-doc-test-case", "ignore_templated") and self.templated_suite:
return
self.check_if_docs_are_present(node, "missing-doc-test-case")
def visit_SettingSection(self, node): # noqa
self.check_if_docs_are_present(node, "missing-doc-suite")
def visit_File(self, node): # noqa
for section in node.sections:
if isinstance(section, SettingSection):
break
else:
self.report("missing-doc-suite", node=node, lineno=1)
super().visit_File(node)
def check_if_docs_are_present(self, node, msg):
for statement in node.body:
if isinstance(statement, Documentation):
break
else:
if hasattr(node, "name"):
self.report(msg, name=node.name, node=node)
else:
self.report(msg, node=node) | /robotframework_robocop-2.2.0-py3-none-any.whl/robocop/checkers/documentation.py | 0.645679 | 0.370225 | documentation.py | pypi |
import inspect
try:
from robot.api.parsing import ModelVisitor
except ImportError:
from robot.parsing.model.visitor import ModelVisitor
from robot.utils import FileReader
from robocop.exceptions import RuleNotFoundError, RuleParamNotFoundError, RuleReportsNotFoundError
from robocop.utils import modules_from_paths, modules_in_current_dir
class BaseChecker:
rules = None
def __init__(self):
self.disabled = False
self.source = None
self.lines = None
self.issues = []
self.rules = {}
self.templated_suite = False
def param(self, rule, param_name):
try:
return self.rules[rule].config[param_name].value
except KeyError:
if rule not in self.rules:
raise RuleNotFoundError(rule, self) from None
if param_name not in self.rules[rule].config:
raise RuleParamNotFoundError(self.rules[rule], param_name, self) from None
def report(
self,
rule,
node=None,
lineno=None,
col=None,
end_lineno=None,
end_col=None,
ext_disablers=None,
**kwargs,
):
if rule not in self.rules:
raise ValueError(f"Missing definition for message with name {rule}")
message = self.rules[rule].prepare_message(
source=self.source,
node=node,
lineno=lineno,
col=col,
end_lineno=end_lineno,
end_col=end_col,
ext_disablers=ext_disablers,
**kwargs,
)
if message.enabled:
self.issues.append(message)
class VisitorChecker(BaseChecker, ModelVisitor): # noqa
type = "visitor_checker"
def scan_file(self, ast_model, filename, in_memory_content, templated=False):
self.issues = []
self.source = filename
self.templated_suite = templated
if in_memory_content is not None:
self.lines = in_memory_content.splitlines(keepends=True)
else:
self.lines = None
self.visit_File(ast_model)
return self.issues
def visit_File(self, node): # noqa
"""Perform generic ast visit on file node."""
self.generic_visit(node)
class RawFileChecker(BaseChecker): # noqa
type = "rawfile_checker"
def scan_file(self, ast_model, filename, in_memory_content, templated=False):
self.issues = []
self.source = filename
self.templated_suite = templated
if in_memory_content is not None:
self.lines = in_memory_content.splitlines(keepends=True)
else:
self.lines = None
self.parse_file()
return self.issues
def parse_file(self):
"""Read file line by line and for each call check_line method."""
if self.lines is not None:
for lineno, line in enumerate(self.lines):
self.check_line(line, lineno + 1)
else:
with FileReader(self.source) as file_reader:
for lineno, line in enumerate(file_reader.readlines()):
self.check_line(line, lineno + 1)
def check_line(self, line, lineno):
raise NotImplementedError
def init(linter):
"""For each module get `rules` dictionary and visitors. Instantiate each visitor and map it to the
rule class instance using `reports` visitor attribute."""
for module in get_modules(linter.config.ext_rules):
classes = inspect.getmembers(module, inspect.isclass)
module_rules = {rule.name: rule for rule in getattr(module, "rules", {}).values()}
for checker in classes:
if issubclass(checker[1], BaseChecker) and getattr(checker[1], "reports", False):
checker_instance = checker[1]()
for reported_rule in checker_instance.reports:
if reported_rule not in module_rules:
raise RuleReportsNotFoundError(reported_rule, checker_instance) from None
checker_instance.rules[reported_rule] = module_rules[reported_rule]
linter.register_checker(checker_instance)
def get_modules(ext_rules):
yield from modules_in_current_dir(__file__, __name__)
yield from modules_from_paths(ext_rules)
def get_rules():
for module in modules_in_current_dir(__file__, __name__):
module_name = module.__name__.split(".")[-1]
for rule in getattr(module, "rules", {}).values():
yield module_name, rule | /robotframework_robocop-2.2.0-py3-none-any.whl/robocop/checkers/__init__.py | 0.574395 | 0.172939 | __init__.py | pypi |
import re
from robot.parsing.model.blocks import CommentSection, TestCase
from robot.parsing.model.statements import Arguments, Comment, EmptyLine, KeywordCall
from robocop.checkers import RawFileChecker, VisitorChecker
from robocop.rules import Rule, RuleParam, RuleSeverity
from robocop.utils import get_section_name, last_non_empty_line, normalize_robot_name, pattern_type
rules = {
"0501": Rule(
RuleParam(name="max_len", default=40, converter=int, desc="number of lines allowed in a keyword"),
rule_id="0501",
name="too-long-keyword",
msg="Keyword '{{ keyword_name }}' is too long ({{ keyword_length }}/{{ allowed_length}})",
severity=RuleSeverity.WARNING,
),
"0502": Rule(
RuleParam(name="min_calls", default=1, converter=int, desc="number of keyword calls required in a keyword"),
rule_id="0502",
name="too-few-calls-in-keyword",
msg="Keyword '{{ keyword_name }}' has too few keywords inside ({{ keyword_count }}/{{ min_allowed_count }})",
severity=RuleSeverity.WARNING,
),
"0503": Rule(
RuleParam(name="max_calls", default=10, converter=int, desc="number of keyword calls allowed in a keyword"),
rule_id="0503",
name="too-many-calls-in-keyword",
msg="Keyword '{{ keyword_name }}' has too many keywords inside ({{ keyword_count }}/{{ max_allowed_count }})",
severity=RuleSeverity.WARNING,
),
"0504": Rule(
RuleParam(name="max_len", default=20, converter=int, desc="number of lines allowed in a test case"),
rule_id="0504",
name="too-long-test-case",
msg="Test case '{{ test_name }}' is too long ({{ test_length }}/{{ allowed_length }})",
severity=RuleSeverity.WARNING,
),
"0505": Rule(
RuleParam(name="max_calls", default=10, converter=int, desc="number of keyword calls allowed in a test case"),
rule_id="0505",
name="too-many-calls-in-test-case",
msg="Test case '{{ test_name }}' has too many keywords inside ({{ keyword_count }}/{{ max_allowed_count }})",
severity=RuleSeverity.WARNING,
),
"0506": Rule(
RuleParam(name="max_lines", default=400, converter=int, desc="number of lines allowed in a file"),
rule_id="0506",
name="file-too-long",
msg="File has too many lines ({{ lines_count }}/{{max_allowed_count }})",
severity=RuleSeverity.WARNING,
),
"0507": Rule(
RuleParam(name="max_args", default=5, converter=int, desc="number of lines allowed in a file"),
rule_id="0507",
name="too-many-arguments",
msg="Keyword '{{ keyword_name }}' has too many arguments ({{ arguments_count }}/{{ max_allowed_count }})",
severity=RuleSeverity.WARNING,
),
"0508": Rule(
RuleParam(name="line_length", default=120, converter=int, desc="number of characters allowed in line"),
RuleParam(
name="ignore_pattern",
default=re.compile(r"https?://\S+"),
converter=pattern_type,
desc="ignore lines that contain configured pattern",
),
rule_id="0508",
name="line-too-long",
msg="Line is too long ({{ line_length }}/{{ allowed_length }})",
severity=RuleSeverity.WARNING,
docs="""
It is possible to ignore lines that match regex pattern. Configure it using following option::
robocop --configure line-too-long:ignore_pattern:pattern
The default pattern is `https?://\S+` that ignores the lines that look like an URL.
""",
),
"0509": Rule(
rule_id="0509", name="empty-section", msg="Section '{{ section_name }}' is empty", severity=RuleSeverity.WARNING
),
"0510": Rule(
RuleParam(
name="max_returns", default=4, converter=int, desc="allowed number of returned values from a keyword"
),
rule_id="0510",
name="number-of-returned-values",
msg="Too many return values ({{ return_count }}/{{ max_allowed_count }})",
severity=RuleSeverity.WARNING,
),
"0511": Rule(
rule_id="0511",
name="empty-metadata",
msg="Metadata settings does not have any value set",
severity=RuleSeverity.WARNING,
),
"0512": Rule(
rule_id="0512",
name="empty-documentation",
msg="Documentation of {{ block_name }} is empty",
severity=RuleSeverity.WARNING,
),
"0513": Rule(rule_id="0513", name="empty-force-tags", msg="Force Tags are empty", severity=RuleSeverity.WARNING),
"0514": Rule(
rule_id="0514", name="empty-default-tags", msg="Default Tags are empty", severity=RuleSeverity.WARNING
),
"0515": Rule(
rule_id="0515", name="empty-variables-import", msg="Import variables path is empty", severity=RuleSeverity.ERROR
),
"0516": Rule(
rule_id="0516", name="empty-resource-import", msg="Import resource path is empty", severity=RuleSeverity.ERROR
),
"0517": Rule(
rule_id="0517", name="empty-library-import", msg="Import library path is empty", severity=RuleSeverity.ERROR
),
"0518": Rule(
rule_id="0518",
name="empty-setup",
msg="Setup of {{ block_name }} does not have any keywords",
severity=RuleSeverity.ERROR,
),
"0519": Rule(
rule_id="0519",
name="empty-suite-setup",
msg="Suite Setup does not have any keywords",
severity=RuleSeverity.ERROR,
),
"0520": Rule(
rule_id="0520",
name="empty-test-setup",
msg="Test Setup does not have any keywords",
severity=RuleSeverity.ERROR,
),
"0521": Rule(
rule_id="0521",
name="empty-teardown",
msg="Teardown of {{ block_name }} does not have any keywords",
severity=RuleSeverity.ERROR,
),
"0522": Rule(
rule_id="0522",
name="empty-suite-teardown",
msg="Suite Teardown does not have any keywords",
severity=RuleSeverity.ERROR,
),
"0523": Rule(
rule_id="0523",
name="empty-test-teardown",
msg="Test Teardown does not have any keywords",
severity=RuleSeverity.ERROR,
),
"0524": Rule(
rule_id="0524", name="empty-timeout", msg="Timeout of {{ block_name }} is empty", severity=RuleSeverity.WARNING
),
"0525": Rule(rule_id="0525", name="empty-test-timeout", msg="Test Timeout is empty", severity=RuleSeverity.WARNING),
"0526": Rule(
rule_id="0526",
name="empty-arguments",
msg="Arguments of {{ block_name }} are empty",
severity=RuleSeverity.ERROR,
),
"0527": Rule(
RuleParam(name="max_testcases", default=50, converter=int, desc="number of test cases allowed in a suite"),
RuleParam(
name="max_templated_testcases",
default=100,
converter=int,
desc="number of test cases allowed in a templated suite",
),
rule_id="0527",
name="too-many-test-cases",
msg="Too many test cases ({{ test_count }}/{{ max_allowed_count }})",
severity=RuleSeverity.WARNING,
),
}
class LengthChecker(VisitorChecker):
"""Checker for max and min length of keyword or test case. It analyses number of lines and also number of
keyword calls (as you can have just few keywords but very long ones or vice versa).
"""
reports = (
"too-long-keyword",
"too-few-calls-in-keyword",
"too-many-calls-in-keyword",
"too-long-test-case",
"too-many-calls-in-test-case",
"file-too-long",
"too-many-arguments",
)
def visit_File(self, node):
if node.end_lineno > self.param("file-too-long", "max_lines"):
self.report(
"file-too-long",
lines_count=node.end_lineno,
max_allowed_count=self.param("file-too-long", "max_lines"),
node=node,
lineno=node.end_lineno,
)
super().visit_File(node)
def visit_Keyword(self, node): # noqa
if node.name.lstrip().startswith("#"):
return
for child in node.body:
if isinstance(child, Arguments):
args_number = len(child.values)
if args_number > self.param("too-many-arguments", "max_args"):
self.report(
"too-many-arguments",
keyword_name=node.name,
arguments_count=args_number,
max_allowed_count=self.param("too-many-arguments", "max_args"),
node=node,
)
break
length = LengthChecker.check_node_length(node)
if length > self.param("too-long-keyword", "max_len"):
self.report(
"too-long-keyword",
keyword_name=node.name,
keyword_length=length,
allowed_length=self.param("too-long-keyword", "max_len"),
node=node,
lineno=node.end_lineno,
ext_disablers=(node.lineno, last_non_empty_line(node)),
)
return
key_calls = LengthChecker.count_keyword_calls(node)
if key_calls < self.param("too-few-calls-in-keyword", "min_calls"):
self.report(
"too-few-calls-in-keyword",
keyword_name=node.name,
keyword_count=key_calls,
min_allowed_count=self.param("too-few-calls-in-keyword", "min_calls"),
node=node,
)
return
if key_calls > self.param("too-many-calls-in-keyword", "max_calls"):
self.report(
"too-many-calls-in-keyword",
keyword_name=node.name,
keyword_count=key_calls,
max_allowed_count=self.param("too-many-calls-in-keyword", "max_calls"),
node=node,
)
return
def visit_TestCase(self, node): # noqa
length = LengthChecker.check_node_length(node)
if length > self.param("too-long-test-case", "max_len"):
self.report(
"too-long-test-case",
test_name=node.name,
test_length=length,
allowed_length=self.param("too-long-test-case", "max_len"),
node=node,
)
key_calls = LengthChecker.count_keyword_calls(node)
if key_calls > self.param("too-many-calls-in-test-case", "max_calls"):
self.report(
"too-many-calls-in-test-case",
test_name=node.name,
keyword_count=key_calls,
max_allowed_count=self.param("too-many-calls-in-test-case", "max_calls"),
node=node,
)
return
@staticmethod
def check_node_length(node):
return node.end_lineno - node.lineno
@staticmethod
def count_keyword_calls(node):
if isinstance(node, KeywordCall):
return 1
if not hasattr(node, "body"):
return 0
return sum(LengthChecker.count_keyword_calls(child) for child in node.body)
class LineLengthChecker(RawFileChecker):
"""Checker for maximum length of a line."""
reports = ("line-too-long",)
# replace `# noqa` or `# robocop`, `# robocop: enable`, `# robocop: disable=optional,rule,names`
disabler_pattern = re.compile(r"(# )+(noqa|robocop: ?(?P<disabler>disable|enable)=?(?P<rules>[\w\-,]*))")
def check_line(self, line, lineno):
if self.param("line-too-long", "ignore_pattern") and self.param("line-too-long", "ignore_pattern").search(line):
return
line = self.disabler_pattern.sub("", line)
line = line.rstrip().expandtabs(4)
if len(line) > self.param("line-too-long", "line_length"):
self.report(
"line-too-long",
line_length=len(line),
allowed_length=self.param("line-too-long", "line_length"),
lineno=lineno,
)
class EmptySectionChecker(VisitorChecker):
"""Checker for detecting empty sections."""
reports = ("empty-section",)
def check_if_empty(self, node):
if not node.header:
return
anything_but = EmptyLine if isinstance(node, CommentSection) else (Comment, EmptyLine)
if all(isinstance(child, anything_but) for child in node.body):
self.report("empty-section", section_name=get_section_name(node), node=node)
def visit_Section(self, node): # noqa
self.check_if_empty(node)
class NumberOfReturnedArgsChecker(VisitorChecker):
"""Checker for number of returned values from a keyword."""
reports = ("number-of-returned-values",)
def visit_Return(self, node): # noqa
self.check_node_returns(len(node.values), node)
visit_ReturnStatement = visit_Return
def visit_KeywordCall(self, node): # noqa
if not node.keyword:
return
normalized_name = normalize_robot_name(node.keyword, remove_prefix="builtin.")
if normalized_name == "returnfromkeyword":
self.check_node_returns(len(node.args), node)
elif normalized_name == "returnfromkeywordif":
self.check_node_returns(len(node.args) - 1, node)
def check_node_returns(self, return_count, node):
if return_count > self.param("number-of-returned-values", "max_returns"):
self.report(
"number-of-returned-values",
return_count=return_count,
max_allowed_count=self.param("number-of-returned-values", "max_returns"),
node=node,
col=node.data_tokens[0].col_offset + 1,
)
class EmptySettingsChecker(VisitorChecker):
"""Checker for detecting empty settings."""
reports = (
"empty-metadata",
"empty-documentation",
"empty-force-tags",
"empty-default-tags",
"empty-variables-import",
"empty-resource-import",
"empty-library-import",
"empty-setup",
"empty-suite-setup",
"empty-test-setup",
"empty-teardown",
"empty-suite-teardown",
"empty-test-teardown",
"empty-timeout",
"empty-test-timeout",
"empty-arguments",
)
def __init__(self):
self.parent_node_name = ""
super().__init__()
def visit_SettingSection(self, node): # noqa
self.parent_node_name = "Test Suite"
self.generic_visit(node)
def visit_TestCaseName(self, node): # noqa
if node.name:
self.parent_node_name = f"'{node.name}' Test Case"
else:
self.parent_node_name = ""
self.generic_visit(node)
def visit_Keyword(self, node): # noqa
if node.name:
self.parent_node_name = f"'{node.name}' Keyword"
else:
self.parent_node_name = ""
self.generic_visit(node)
def visit_Metadata(self, node): # noqa
if node.name is None:
self.report("empty-metadata", node=node, col=node.end_col_offset)
def visit_Documentation(self, node): # noqa
if not node.value:
self.report("empty-documentation", block_name=self.parent_node_name, node=node, col=node.end_col_offset)
def visit_ForceTags(self, node): # noqa
if not node.values:
self.report("empty-force-tags", node=node, col=node.end_col_offset)
def visit_DefaultTags(self, node): # noqa
if not node.values:
self.report("empty-default-tags", node=node, col=node.end_col_offset)
def visit_VariablesImport(self, node): # noqa
if not node.name:
self.report("empty-variables-import", node=node, col=node.end_col_offset)
def visit_ResourceImport(self, node): # noqa
if not node.name:
self.report("empty-resource-import", node=node, col=node.end_col_offset)
def visit_LibraryImport(self, node): # noqa
if not node.name:
self.report("empty-library-import", node=node, col=node.end_col_offset)
def visit_Setup(self, node): # noqa
if not node.name:
self.report("empty-setup", block_name=self.parent_node_name, node=node, col=node.end_col_offset + 1)
def visit_SuiteSetup(self, node): # noqa
if not node.name:
self.report("empty-suite-setup", node=node, col=node.end_col_offset)
def visit_TestSetup(self, node): # noqa
if not node.name:
self.report("empty-test-setup", node=node, col=node.end_col_offset)
def visit_Teardown(self, node): # noqa
if not node.name:
self.report("empty-teardown", block_name=self.parent_node_name, node=node, col=node.end_col_offset + 1)
def visit_SuiteTeardown(self, node): # noqa
if not node.name:
self.report("empty-suite-teardown", node=node, col=node.end_col_offset)
def visit_TestTeardown(self, node): # noqa
if not node.name:
self.report("empty-test-teardown", node=node, col=node.end_col_offset)
def visit_Timeout(self, node): # noqa
if not node.value:
self.report("empty-timeout", block_name=self.parent_node_name, node=node, col=node.end_col_offset + 1)
def visit_TestTimeout(self, node): # noqa
if not node.value:
self.report("empty-test-timeout", node=node, col=node.end_col_offset)
def visit_Arguments(self, node): # noqa
if not node.values:
self.report("empty-arguments", block_name=self.parent_node_name, node=node, col=node.end_col_offset + 1)
class TestCaseNumberChecker(VisitorChecker):
"""Checker for counting number of test cases depending on suite type"""
reports = ("too-many-test-cases",)
def visit_TestCaseSection(self, node): # noqa
max_testcases = (
self.param("too-many-test-cases", "max_templated_testcases")
if self.templated_suite
else self.param("too-many-test-cases", "max_testcases")
)
discovered_testcases = sum([isinstance(child, TestCase) for child in node.body])
if discovered_testcases > max_testcases:
self.report(
"too-many-test-cases", test_count=discovered_testcases, max_allowed_count=max_testcases, node=node
) | /robotframework_robocop-2.2.0-py3-none-any.whl/robocop/checkers/lengths.py | 0.506591 | 0.277381 | lengths.py | pypi |
import subprocess
from pathlib import Path
from robot.api import logger
from robot.api.deco import library, keyword
from robot.libraries.BuiltIn import BuiltIn
from robot.running.model import TestCase
from robot.result.model import TestCase as TestCaseResult
import shlex
class ErrorsAreFatal:
ROBOT_LISTENER_API_VERSION = 3
def __init__(self) -> None:
self.test_failed: bool = False
def start_test(self, test: TestCase, result: TestCaseResult) -> None:
logger.console("") # just to go to next line in console at beginning
if self.test_failed:
test.keywords.clear()
def end_test(self, test: TestCase, result: TestCaseResult) -> None:
if self.test_failed:
result.message = "Skipped execution due previous errors"
result.status = "FAIL" # todo: make it "SKIP" when using RF 4.0
if not result.passed:
self.test_failed = True
def close(self) -> None:
# added as unit tests somehow kept the state
self.test_failed = False
@library(scope="TEST SUITE", version="1.0", listener=ErrorsAreFatal())
class RoboOps:
"""Library for creating, sharing and running DevOps tasks easily and efficiently.
When is imported, any failure within a suite is fatal - preventing other steps from execution and failing whole run.
== Example ==
| *** Settings ***
| Library RoboOps
| *** Variables ***
| &{install python env} command=poetry install
| &{unit tests} command=poetry run coverage run --source=RoboOps -m pytest .
| &{report coverage} command=poetry run coverage report -m --fail-under=80
| &{generate wheel} command=poetry build
| *** Tasks ***
| Unit Test Stage
| Roboops Run Command &{install python env}
| Roboops Run Command &{unit tests}
| ${coverage} Roboops Run Command &{report coverage}
| Create File coverage.log ${coverage.stdout.decode()}
| Roboops Save File Artifact coverage.log coverage.log
|
| Build Package Stage
| Roboops Run Command &{generate wheel}
"""
def __init__(self, artifacts_dir: str = "artifacts"):
"""RoboOps library can take below optional arguments:
- ``artifacts_dir`` <str>
Points to directory where artifacts will be stored."""
self.artifacts_dir = Path(artifacts_dir)
self.artifacts_dir.mkdir(parents=True, exist_ok=True)
@keyword
def roboops_run_command(
self,
command: str,
shell: bool = False,
cwd: str = None,
ignore_rc: bool = False,
) -> subprocess.CompletedProcess:
"""Runs given command using subprocess.run and returns result ``subprocess.CompletedProcess`` object.
Arguments:
- ``command`` <str>:
Command to be executed.
- ``shell`` <bool>:
Specifies if command should be executed in separate shell (see subprocess.run documentation for more details).
Defaults to ``False``
- ``cwd`` <str>:
Sets working directory for given command.
Defaults to ``None``
- ``ignore_rc`` <bool>:
Ignore return code.
By default if return code of executed command is other than 0, then keyword fails.
"""
logger.info(
f"running: '{command}' {'in shell' if shell else ''}", also_console=True
)
if not shell:
command = shlex.split(command) # type: ignore
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
cwd=cwd,
)
logger.info(result.stdout.decode())
if result.stderr:
logger.error(result.stderr.decode())
if not ignore_rc:
result.check_returncode()
return result
@keyword
def roboops_save_file_artifact(self, source: Path, name: str = None) -> None:
"""
Moves given file to ``artifacts_dir`` with given name and add to ``Artifacts`` metadata in report for easy view/download
Arguments:
- ``source`` <Path>: Path to file
- ``name`` <str>: new name of the file. If not provided, original name will be used.
"""
source = Path(source)
name = name if name else source.name
destination = self.artifacts_dir / name
source.rename(destination)
self._add_artifact_to_suite_metadata(name, destination)
def _add_artifact_to_suite_metadata(self, name: str, file_path: Path) -> None:
entry = f"- [{file_path}|{name}]\n"
BuiltIn().set_suite_metadata("artifacts", entry, append=True, top=True) | /robotframework_roboops-0.2.4-py3-none-any.whl/RoboOps/RoboOps.py | 0.577972 | 0.366221 | RoboOps.py | pypi |
import json
from itertools import count
from subprocess import Popen, PIPE
import sys
from os.path import realpath
from pathlib import Path
from typing import Any, Dict, List, Mapping, Tuple
from robot.errors import RemoteError
from robot.libraries.Remote import RemoteResult
class RoboSAPiensClient(object):
def __init__(self, args: Mapping[str, Any]):
self.args = list(args.items())
self.server_cmd = Path(realpath(__file__)).parent / "lib" / "RoboSAPiens.exe"
self._server = self.server
self.counter = count(1)
@property
def server(self):
return self._start_server(self.server_cmd, _cli_args(self.args))
def _start_server(self, server: Path, args: List[str]):
return Popen(
[str(server)] + args,
stdout=PIPE,
stdin=PIPE,
bufsize=1,
universal_newlines=True,
encoding="utf-8"
)
def __del__(self):
self._server.terminate()
# All methods have to be private so that they are not interpreted as keywords by RF
def _run_keyword(self, name: str, args: List[str], result: Dict[str, str]): # type: ignore
request = {
"jsonrpc": "2.0",
"method": name,
"params": args,
"id": next(self.counter)
}
assert self._server.stdout is not None
assert self._server.stdin is not None
self._server.stdin.write(json.dumps(request) + '\n')
response = ''.join(list(iter(self._server.stdout.readline, '\n')))
json_response = json.loads(response)
if json_response["result"]:
rf_result = RemoteResult(json_response["result"])
else:
rf_result = RemoteResult(json_response["error"]["data"])
if rf_result.status != "PASS": # type: ignore
error_type, error_message = rf_result.error.split("|")
if error_type in {"SapError", "Exception"}:
message = result[error_type].format(error_message)
else:
message = result[error_type].format(*args)
raise RemoteError(
message,
rf_result.traceback,
rf_result.fatal,
rf_result.continuable
)
sys.stdout.write(result["Pass"].format(*args))
return rf_result.return_ # type: ignore
def _cli_args(args: List[Tuple[str, Any]]) -> List[str]:
if len(args) == 0:
return []
(name, value), *rest = args
name = '--' + name.replace("_", "-")
if isinstance(value, bool):
if value:
return [name] + _cli_args(rest)
return _cli_args(rest)
return [name, str(value)] + _cli_args(rest) | /robotframework_robosapiens-1.2.7-py3-none-any.whl/RoboSAPiens/client.py | 0.506836 | 0.15785 | client.py | pypi |
from robot.api.deco import keyword
from RoboSAPiens.client import RoboSAPiensClient
class RoboSAPiens(RoboSAPiensClient):
"""
RoboSAPiens: SAP GUI-Automation for Humans
In order to use this library the following requirements must be satisfied:
- Scripting on the SAP Server must be [https://help.sap.com/saphelp_aii710/helpdata/en/ba/b8710932b8c64a9e8acf5b6f65e740/content.htm|activated].
- Scripting Support must be [https://help.sap.com/docs/sap_gui_for_windows/63bd20104af84112973ad59590645513/7ddb7c9c4a4c43219a65eee4ca8db001.html?locale=en-US|activated] in the SAP GUI.
This library is also available in the following languages:
- RoboSAPiens.DE (German)
"""
def __init__(self, presenter_mode: bool=False):
"""
*presenter_mode*: Highlight each GUI element acted upon
"""
args = {
'presenter_mode': presenter_mode,
}
super().__init__(args)
@keyword('Select Tab') # type: ignore
def activate_tab(self, tab_name: str): # type: ignore
"""
Select the tab with the name provided.
| ``Select Tab tab_name``
"""
args = [tab_name]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The tab '{0}' could not be found Hint: Check the spelling",
"SapError": "SAP Error: {0}",
"Pass": "The tab {0} was selected",
"Exception": "The tab could not be selected. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('ActivateTab', args, result) # type: ignore
@keyword('Open SAP') # type: ignore
def open_sap(self, path: str): # type: ignore
"""
Open the SAP GUI. The standard path is
| ``C:\\Program Files (x86)\\SAP\\FrontEnd\\SAPgui\\saplogon.exe``
"""
args = [path]
result = {
"Pass": "The SAP GUI was opened.",
"SAPNotStarted": "The SAP GUI could not be opened. Verify that the path is correct.",
"Exception": "The SAP GUI could not be opened. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('OpenSap', args, result) # type: ignore
@keyword('Disconnect from Server') # type: ignore
def close_connection(self): # type: ignore
"""
Terminate the connection to the SAP server.
"""
args = []
result = {
"NoSapGui": "No open SAP GUI found. Call the keyword \"Open SAP\" first.",
"NoGuiScripting": "The scripting support is not activated. It must be activated in the Settings of SAP Logon.",
"NoConnection": "No existing connection to an SAP server. Call the keyword \"Connect to Server\" first.",
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"Pass": "Disconnected from the server.",
"Exception": "Could not disconnect from the server. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('CloseConnection', args, result) # type: ignore
@keyword('Close SAP') # type: ignore
def close_sap(self): # type: ignore
"""
Close the SAP GUI
"""
args = []
result = {
"NoSapGui": "No open SAP GUI found. Call the keyword \"Open SAP\" first.",
"Pass": "The SAP GUI was closed."
}
return super()._run_keyword('CloseSap', args, result) # type: ignore
@keyword('Export Spreadsheet') # type: ignore
def export_spreadsheet(self, table_index: str): # type: ignore
"""
The export function 'Spreadsheet' will be executed for the specified table, if available.
| ``Export spreadsheet table_index``
table_index: 1, 2,...
"""
args = [table_index]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"Exception": "The export function 'Spreadsheet' could not be called\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html",
"NotFound": "No table was found that supports the export function 'Spreadsheet'",
"Pass": "The export function 'Spreadsheet' was successfully called on the table with index {0}."
}
return super()._run_keyword('ExportSpreadsheet', args, result) # type: ignore
@keyword('Export Function Tree') # type: ignore
def export_tree(self, filepath: str): # type: ignore
"""
Export the function tree in JSON format to the file provided.
| ``Export Function Tree filepath``
"""
args = [filepath]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The window contains no tree element",
"Pass": "The function tree was exported to {0}",
"Exception": "The function tree could not be exported. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('ExportTree', args, result) # type: ignore
@keyword('Connect to Running SAP') # type: ignore
def attach_to_running_sap(self): # type: ignore
"""
Connect to a running SAP instance and take control of it.
"""
args = []
result = {
"NoSapGui": "No open SAP GUI found. Call the keyword \"Open SAP\" first.",
"NoGuiScripting": "The scripting support is not activated. It must be activated in the Settings of SAP Logon.",
"NoConnection": "No existing connection to an SAP server. Call the keyword \"Connect to Server\" first.",
"NoServerScripting": "Scripting is not activated on the server side. Please consult the documentation of RoboSAPiens.",
"Pass": "Connected to a running SAP instance.",
"Exception": "Could not connect to a running SAP instance. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('AttachToRunningSap', args, result) # type: ignore
@keyword('Connect to Server') # type: ignore
def connect_to_server(self, server_name: str): # type: ignore
"""
Connect to the SAP Server provided.
| ``Connect to Server servername``
"""
args = [server_name]
result = {
"NoSapGui": "No open SAP GUI found. Call the keyword \"Open SAP\" first.",
"NoGuiScripting": "The scripting support is not activated. It must be activated in the Settings of SAP Logon.",
"Pass": "Connected to the server {0}",
"SapError": "SAP Error: {0}",
"NoServerScripting": "Scripting is not activated on the server side. Please consult the documentation of RoboSAPiens.",
"Exception": "Could not establish the connection. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('ConnectToServer', args, result) # type: ignore
@keyword('Double-click Cell') # type: ignore
def double_click_cell(self, row_locator: str, column: str): # type: ignore
"""
Double-click the cell at the intersection of the row and the column provided.
| ``Double-click Cell row_locator column``
row_locator: either the row number or the content of a cell in the row.
"""
args = [row_locator, column]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The cell with the locator '{0}, {1}' could not be found. Hint: Check the spelling",
"Pass": "The cell with the locator '{0}, {1}' was double-clicked.",
"Exception": "The cell could not be double-clicked. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('DoubleClickCell', args, result) # type: ignore
@keyword('Double-click Text Field') # type: ignore
def double_click_text_field(self, content: str): # type: ignore
"""
Double click the text field with the content provided.
| ``Double-click Text Field Content``
"""
args = [content]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The text field with the content '{0}' could not be found Hint: Check the spelling",
"Pass": "The text field with the content '{0}' was double-clicked.",
"Exception": "The text field could not be double-clicked. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('DoubleClickTextField', args, result) # type: ignore
@keyword('Execute Transaction') # type: ignore
def execute_transaction(self, T_Code: str): # type: ignore
"""
Execute the transaction with the given T-Code.
| ``Execute Transaction T_Code``
"""
args = [T_Code]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"Pass": "The transaction with T-Code {0} was executed.",
"Exception": "The transaction could not be executed. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('ExecuteTransaction', args, result) # type: ignore
@keyword('Export Dynpro') # type: ignore
def export_form(self, name: str, directory: str): # type: ignore
"""
Write all texts in the Dynpro to a JSON file. Also a screenshot will be saved in PNG format.
| ``Export Dynpro name directory``
directory: Absolute path to the directory where the files will be saved.
"""
args = [name, directory]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"Pass": "The Dynpro was exported to the JSON file {0} and the PNG image {1}",
"Exception": "The Dynpro could not be exported. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('ExportForm', args, result) # type: ignore
@keyword('Fill Cell') # type: ignore
def fill_table_cell(self, row_locator: str, column_content: str): # type: ignore
"""
Fill the cell at the intersection of the row and the column specified with the content provided.
| ``Fill Cell row column = content``
row: either the row number or the contents of a cell in the row.
*Hint*: Some cells can be filled using the keyword 'Fill Text Field' providing as locator the description obtained by selecting the cell and pressing F1.
"""
args = [row_locator, column_content]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"InvalidFormat": "The format of the second parameter must be 'column = content'",
"NotFound": "The cell with the locator '{0}, {1}' could not be found Hint: Check the spelling",
"NotChangeable": "The cell with the locator '{0}, {1}' is not changeable.",
"Pass": "The cell with the locator '{0}, {1}' was filled.",
"Exception": "The cell could not be filled. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('FillTableCell', args, result) # type: ignore
@keyword('Fill Text Field') # type: ignore
def fill_text_field(self, locator: str, content: str): # type: ignore
"""
Fill the text Field specified by the locator with the content provided.
*Text field with a label to its left*
| ``Fill Text Field label content``
*Text field with a label above*
| ``Fill Text Field @ label content``
*Text field at the intersection of a label to its left and a label above it (including a heading)*
| ``Fill Text Field label to its left @ label above it content``
*Text field without label below a text field with a label (e.g. an address line)*
| ``Fill Text Field position (1,2,..) @ label content``
*Text field without a label to the right of a text field with a label*
| ``Fill Text Field label @ position (1,2,..) content``
*Text field with a non-unique label to the right of a text field with a label*
| ``Fill Text Field left label >> right label content``
*Hint*: The description obtained by selecting a text field and pressing F1 can also be used as label.
"""
args = [locator, content]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The text field with the locator '{0}' could not be found. Hint: Check the spelling",
"Pass": "The text field with the locator '{0}' was filled.",
"Exception": "The text field could not be filled. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('FillTextField', args, result) # type: ignore
@keyword('Highlight Button') # type: ignore
def highlight_button(self, name_or_tooltip: str): # type: ignore
"""
Highlight the button with the given name or tooltip.
| ``Highlight Button name or tooltip``
"""
args = [name_or_tooltip]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The button '{0}' could not be found. Hint: Check the spelling",
"Pass": "The button '{0}' was highlighted.",
"Exception": "The button could not be highlighted. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('HighlightButton', args, result) # type: ignore
@keyword('Push Button') # type: ignore
def push_button(self, name_or_tooltip: str): # type: ignore
"""
Push the button with the given name or tooltip.
| ``Push Button name or tooltip``
"""
args = [name_or_tooltip]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"SapError": "SAP Error: {0}",
"NotFound": "The button '{0}' could not be found. Hint: Check the spelling",
"Pass": "The button '{0}' was pushed.",
"Exception": "The button could not be pushed. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('PushButton', args, result) # type: ignore
@keyword('Push Button Cell') # type: ignore
def push_button_cell(self, row_or_label: str, column: str): # type: ignore
"""
Push the button cell located at the intersection of the row and column provided.
| ``Push Button Cell row_locator column``
row_locator: Row number, label or tooltip.
"""
args = [row_or_label, column]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The button cell with the locator '{0}, {1}' could not be found. Hint: Check the spelling",
"Pass": "The button cell with the locator '{0}' was pushed.",
"Exception": "The button cell could not be pushed. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('PushButtonCell', args, result) # type: ignore
@keyword('Read Statusbar') # type: ignore
def read_statusbar(self): # type: ignore
"""
Read the message in the statusbar.
| ``Read Statusbar``
"""
args = []
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "No statusbar was found.",
"Pass": "The statusbar was read.",
"Exception": "The statusbar could not be read\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('ReadStatusbar', args, result) # type: ignore
@keyword('Read Text Field') # type: ignore
def read_text_field(self, locator: str): # type: ignore
"""
Read the contents of the text field specified by the locator.
*Text field with a label to its left*
| ``Read Text Field label``
*Text field with a label above it*
| ``Read Text Field @ label``
*Text field at the intersection of a label to its left and a label above it*
| ``Read Text Field left label @ label above``
*Text field whose content starts with a given text*
| ``Read Text Field = text``
"""
args = [locator]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The text field with the locator '{0}' could not be found. Hint: Check the spelling",
"Pass": "The text field with the locator '{0}' was read.",
"Exception": "The text field could not be read. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('ReadTextField', args, result) # type: ignore
@keyword('Read Text') # type: ignore
def read_text(self, locator: str): # type: ignore
"""
Read the text specified by the locator.
*Text starting with a given substring*
| ``Read Text = substring``
*Text following a label*
| ``Read Text Label``
"""
args = [locator]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "No text with the locator '{0}' was found. Hint: Check the spelling",
"Pass": "A text with the locator '{0}' was read.",
"Exception": "The text could not be read. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('ReadText', args, result) # type: ignore
@keyword('Read Cell') # type: ignore
def read_table_cell(self, row_locator: str, column: str): # type: ignore
"""
Read the contents of the cell at the intersection of the row and column provided.
| ``Read Cell row_locator column``
row_locator: either the row number or the contents of a cell in the row.
"""
args = [row_locator, column]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The cell with the locator '{0}, {1}' could not be found. Hint: Check the spelling",
"Pass": "The cell with the locator '{0}, {1}' was read.",
"Exception": "The cell could not be read. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('ReadTableCell', args, result) # type: ignore
@keyword('Save Screenshot') # type: ignore
def save_screenshot(self, filepath: str): # type: ignore
"""
Save a screenshot of the current window in the file provided.
| ``Save Screenshot filepath``
filepath: Absolute path to a .png file.
"""
args = [filepath]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"InvalidPath": "The path '{0}' is invalid.",
"UNCPath": "UNC paths (i.e. beginning with \\\\) are not allowed",
"NoAbsPath": "The path '{0}' is not an absolute path.",
"Pass": "The screenshot was saved in {0}.",
"Exception": "The screenshot could not be saved. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('SaveScreenshot', args, result) # type: ignore
@keyword('Select Cell') # type: ignore
def select_cell(self, row_locator: str, column: str): # type: ignore
"""
Select the cell at the intersection of the row and column provided.
| ``Select Cell row_locator column``
row_locator: either the row number or the contents of a cell in the row.
"""
args = [row_locator, column]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The cell with the locator '{0}, {1}' could not be found. Hint: Check the spelling",
"Pass": "The cell with the locator '{0}, {1}' was selected.",
"Exception": "The cell could not be selected. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('SelectCell', args, result) # type: ignore
@keyword('Select Dropdown Menu Entry') # type: ignore
def select_combo_box_entry(self, dropdown_menu: str, entry: str): # type: ignore
"""
Select the specified entry from the dropdown menu provided.
| ``Select Dropdown Menu Entry dropdown menu entry``
"""
args = [dropdown_menu, entry]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The dropdown menu '{0}' could not be found. Hint: Check the spelling",
"EntryNotFound": "In the dropdown menu '{0}' no entry '{1}' could be found. Hint: Check the spelling",
"Pass": "In the dropdown menu '{0}' the entry '{1}' was selected.",
"Exception": "The entry could not be selected. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('SelectComboBoxEntry', args, result) # type: ignore
@keyword('Select Radio Button') # type: ignore
def select_radio_button(self, locator: str): # type: ignore
"""
Select the radio button specified by the locator.
*Radio button with a label to its left or its right*
| ``Select Radio Button label``
*Radio button with a label above it*
| ``Select Radio Button @ label``
*Radio button at the intersection of a label to its left or its right and a label above it*
| ``Select Radio Button left or right label @ label above``
"""
args = [locator]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The radio button with locator '{0}' could not be found. Hint: Check the spelling",
"Pass": "The radio button with locator '{0}' was selected.",
"Exception": "The radio button could not be selected. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('SelectRadioButton', args, result) # type: ignore
@keyword('Select Table Row') # type: ignore
def select_table_row(self, row_number: str): # type: ignore
"""
Select the specified table row.
| ``Select Table Row row_number``
"""
args = [row_number]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"Exception": "The row with index '{0}' could not be selected\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html",
"NotFound": "The table contains no row with index '{0}'",
"Pass": "The row with index '{0}' was selected"
}
return super()._run_keyword('SelectTableRow', args, result) # type: ignore
@keyword('Select Text Field') # type: ignore
def select_text_field(self, locator: str): # type: ignore
"""
Select the text field specified by the locator.
*Text field with a label to its left*
| ``Select Text Field label``
*Text field with a label above it*
| ``Select Text Field @ label``
*Text field at the intersection of a label to its left and a label above it*
| ``Select Text Field left label @ label above``
*Text field whose content starts with the given text*
| ``Select Text Field = text``
"""
args = [locator]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The text field with the locator '{0}' could not be found. Hint: Check the spelling",
"Pass": "The text field with the locator '{0}' was selected.",
"Exception": "The text field could not be selected. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('SelectTextField', args, result) # type: ignore
@keyword('Select Text Line') # type: ignore
def select_text_line(self, content: str): # type: ignore
"""
Select the text line starting with the given content.
| ``Select Text Line content``
"""
args = [content]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The text line starting with '{0}' could not be found. Hint: Check the spelling",
"Pass": "The text line starting with '{0}' was selected.",
"Exception": "The text line could not be selected. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('SelectTextLine', args, result) # type: ignore
@keyword('Tick Checkbox') # type: ignore
def tick_check_box(self, locator: str): # type: ignore
"""
Tick the checkbox specified by the locator.
*Checkbox with a label to its left or its right*
| ``Tick Checkbox label``
*Checkbox with a label above it*
| ``Tick Checkbox @ label``
*Checkbox at the intersection of a label to its left and a label above it*
| ``Tick Checkbox left label @ label above``
"""
args = [locator]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The checkbox with the locator '{0}' could not be found. Hint: Check the spelling",
"Pass": "The checkbox with the locator '{0}' was ticked.",
"Exception": "The checkbox could not be ticked. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('TickCheckBox', args, result) # type: ignore
@keyword('Untick Checkbox') # type: ignore
def untick_check_box(self, locator: str): # type: ignore
"""
Untick the checkbox specified by the locator.
*Checkbox with a label to its left or its right*
| ``Untick Checkbox label``
*Checkbox with a label above it*
| ``Untick Checkbox @ label``
*Checkbox at the intersection of a label to its left and a label above it*
| ``Untick Checkbox left label @ label above``
"""
args = [locator]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The checkbox with the locator '{0}' could not be found. Hint: Check the spelling",
"Pass": "The checkbox with the locator '{0}' was unticked.",
"Exception": "The checkbox could not be unticked. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('UntickCheckBox', args, result) # type: ignore
@keyword('Tick Checkbox Cell') # type: ignore
def tick_check_box_cell(self, row_number: str, column: str): # type: ignore
"""
Tick the checkbox cell at the intersection of the row and the column provided.
| ``Tick Checkbox Cell row number column``
"""
args = [row_number, column]
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"NotFound": "The checkbox cell with the locator '{0}, {1}' coud not be found. Hint: Check the spelling",
"Pass": "The checkbox cell with the locator '{0}' was ticked.",
"Exception": "The checkbox cell could not be ticked. {0}\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('TickCheckBoxCell', args, result) # type: ignore
@keyword('Get Window Title') # type: ignore
def get_window_title(self): # type: ignore
"""
Get the title of the window in the foreground.
| ``${Title} Get Window Title``
"""
args = []
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"Pass": "The title of the window was obtained.",
"Exception": "The window title could not be read.\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('GetWindowTitle', args, result) # type: ignore
@keyword('Get Window Text') # type: ignore
def get_window_text(self): # type: ignore
"""
Get the text message of the window in the foreground.
| ``${Text} Get Window Text``
"""
args = []
result = {
"NoSession": "No existing SAP-Session. Call the keyword \"Connect To Server\" first.",
"Pass": "The text message of the window was obtained.",
"Exception": "The text message of the window could not be read.\nFor more details run 'robot --loglevel DEBUG test.robot' and consult the file log.html"
}
return super()._run_keyword('GetWindowText', args, result) # type: ignore
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = '1.2.7' | /robotframework_robosapiens-1.2.7-py3-none-any.whl/RoboSAPiens/__init__.py | 0.701713 | 0.248802 | __init__.py | pypi |
from robot.api.deco import keyword
from RoboSAPiens.client import RoboSAPiensClient
class DE(RoboSAPiensClient):
"""
RoboSAPiens: SAP GUI-Automatisierung für Menschen
Um diese Bibliothek zu verwenden, müssen die folgenden Bedingungen erfüllt werden:
- Das [https://help.sap.com/saphelp_aii710/helpdata/de/ba/b8710932b8c64a9e8acf5b6f65e740/content.htm|Scripting] muss auf dem SAP Server aktiviert werden.
- Die [https://help.sap.com/docs/sap_gui_for_windows/63bd20104af84112973ad59590645513/7ddb7c9c4a4c43219a65eee4ca8db001.html|Skriptunterstützung] muss in der SAP GUI aktiviert werden.
"""
def __init__(self, vortragsmodus: bool=False):
"""
*vortragsmodus*: Jedes GUI Element wird vor seiner Betätigung bzw. Änderung kurz hervorgehoben
"""
args = {
'presenter_mode': vortragsmodus,
}
super().__init__(args)
@keyword('Reiter auswählen') # type: ignore
def activate_tab(self, Reitername: str): # type: ignore
"""
Der Reiter mit dem angegebenen Namen wird ausgewählt.
| ``Reiter auswählen Reitername``
"""
args = [Reitername]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Der Reiter '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"SapError": "SAP Fehlermeldung: {0}",
"Pass": "Der Reiter '{0}' wurde ausgewählt.",
"Exception": "Der Reiter konnte nicht ausgewählt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('ActivateTab', args, result) # type: ignore
@keyword('SAP starten') # type: ignore
def open_sap(self, Pfad: str): # type: ignore
"""
Die SAP GUI wird gestartet. Der übliche Pfad ist
| ``C:\\Program Files (x86)\\SAP\\FrontEnd\\SAPgui\\saplogon.exe``
"""
args = [Pfad]
result = {
"Pass": "Die SAP GUI wurde gestartet",
"SAPNotStarted": "Die SAP GUI konnte nicht gestartet werden. Überprüfe den Pfad '{0}'.",
"Exception": "Die SAP GUI konnte nicht gestartet werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('OpenSap', args, result) # type: ignore
@keyword('Verbindung zum Server trennen') # type: ignore
def close_connection(self): # type: ignore
"""
Die Verbindung mit dem SAP Server wird getrennt.
"""
args = []
result = {
"NoSapGui": "Keine laufende SAP GUI gefunden. Das Keyword \"SAP starten\" muss zuerst aufgerufen werden.",
"NoGuiScripting": "Die Skriptunterstützung ist nicht verfügbar. Sie muss in den Einstellungen von SAP Logon aktiviert werden.",
"NoConnection": "Es besteht keine Verbindung zu einem SAP Server. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"Pass": "Die Verbindung zum Server wurde getrennt.",
"Exception": "Die Verbindung zum Server konnte nicht getrennt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('CloseConnection', args, result) # type: ignore
@keyword('SAP beenden') # type: ignore
def close_sap(self): # type: ignore
"""
Die SAP GUI wird beendet.
"""
args = []
result = {
"NoSapGui": "Keine laufende SAP GUI gefunden. Das Keyword \"SAP starten\" muss zuerst aufgerufen werden.",
"Pass": "Die SAP GUI wurde beendet"
}
return super()._run_keyword('CloseSap', args, result) # type: ignore
@keyword('Tabellenkalkulation exportieren') # type: ignore
def export_spreadsheet(self, Tabellenindex: str): # type: ignore
"""
Die Export-Funktion 'Tabellenkalkulation' wird für die angegebene Tabelle aufgerufen, falls vorhanden.
| ``Tabellenkalkulation exportieren Tabellenindex``
Tabellenindex: 1, 2,...
"""
args = [Tabellenindex]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Keine Tabelle wurde gefunden, welche die Export-Funktion 'Tabellenkalkulation' unterstützt\nHinweis: Prüfe die Rechtschreibung",
"Exception": "Die Export-Funktion 'Tabellenkalkulation' konnte nicht aufgerufen werden\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen.",
"Pass": "Die Export-Funktion 'Tabellenkalkulation' wurde für die Tabelle mit Index {0} aufgerufen"
}
return super()._run_keyword('ExportSpreadsheet', args, result) # type: ignore
@keyword('Funktionsbaum exportieren') # type: ignore
def export_tree(self, Dateipfad: str): # type: ignore
"""
Der Funktionsbaum wird in der angegebenen Datei gespeichert.
| ``Funktionsbaum exportieren Dateipfad``
"""
args = [Dateipfad]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Die Maske enthält keine Baumstruktur",
"Pass": "Die Baumstruktur wurde in JSON Format in der Datei '{0}' gespeichert",
"Exception": "Die Baumstruktur konnte nicht exportiert werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('ExportTree', args, result) # type: ignore
@keyword('Laufende SAP GUI übernehmen') # type: ignore
def attach_to_running_sap(self): # type: ignore
"""
Nach der Ausführung dieses Keywords, kann eine laufende SAP GUI mit RoboSAPiens gesteuert werden.
"""
args = []
result = {
"NoSapGui": "Keine laufende SAP GUI gefunden. Das Keyword \"SAP starten\" muss zuerst aufgerufen werden.",
"NoGuiScripting": "Die Skriptunterstützung ist nicht verfügbar. Sie muss in den Einstellungen von SAP Logon aktiviert werden.",
"NoConnection": "Es besteht keine Verbindung zu einem SAP Server. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NoServerScripting": "Das Scripting ist auf dem SAP Server nicht freigeschaltet. Siehe die Dokumentation von RoboSAPiens.",
"Pass": "Die laufende SAP GUI wurde erfolgreich übernommen.",
"Exception": "Die laufende SAP GUI konnte nicht übernommen werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('AttachToRunningSap', args, result) # type: ignore
@keyword('Verbindung zum Server herstellen') # type: ignore
def connect_to_server(self, Servername: str): # type: ignore
"""
Die Verbindung mit dem angegebenen SAP Server wird hergestellt.
| ``Verbindung zum Server herstellen Servername``
"""
args = [Servername]
result = {
"NoSapGui": "Keine laufende SAP GUI gefunden. Das Keyword \"SAP starten\" muss zuerst aufgerufen werden.",
"NoGuiScripting": "Die Skriptunterstützung ist nicht verfügbar. Sie muss in den Einstellungen von SAP Logon aktiviert werden.",
"Pass": "Die Verbindung mit dem Server '{0}' wurde erfolgreich hergestellt.",
"SapError": "SAP Fehlermeldung: {0}",
"NoServerScripting": "Das Scripting ist auf dem SAP Server nicht freigeschaltet. Siehe die Dokumentation von RoboSAPiens.",
"Exception": "Die Verbindung konnte nicht hergestellt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('ConnectToServer', args, result) # type: ignore
@keyword('Tabellenzelle doppelklicken') # type: ignore
def double_click_cell(self, Zeile: str, Spaltentitel: str): # type: ignore
"""
Die angegebene Tabellenzelle wird doppelgeklickt.
| ``Tabellenzelle doppelklicken Zeile Spaltentitel``
Zeile: entweder die Zeilennummer oder der Inhalt der Zelle.
"""
args = [Zeile, Spaltentitel]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Die Zelle mit dem Lokator '{0}, {1}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Die Zelle mit dem Lokator '{0}, {1}' wurde doppelgeklickt.",
"Exception": "Die Zelle konnte nicht doppelgeklickt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('DoubleClickCell', args, result) # type: ignore
@keyword('Textfeld doppelklicken') # type: ignore
def double_click_text_field(self, Inhalt: str): # type: ignore
"""
Das angegebene Textfeld wird doppelgeklickt.
| ``Textfeld doppelklicken Inhalt``
"""
args = [Inhalt]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Das Textfeld mit dem Lokator '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Das Textfeld mit dem Lokator '{0}' wurde doppelgeklickt.",
"Exception": "Das Textfeld konnte nicht doppelgeklickt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('DoubleClickTextField', args, result) # type: ignore
@keyword('Transaktion ausführen') # type: ignore
def execute_transaction(self, T_Code: str): # type: ignore
"""
Die Transaktion mit dem angegebenen T-Code wird ausgeführt.
| ``Transaktion ausführen T-Code``
"""
args = [T_Code]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"Pass": "Die Transaktion mit T-Code '{0}' wurde erfolgreich ausgeführt.",
"Exception": "Die Transaktion konnte nicht ausgeführt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('ExecuteTransaction', args, result) # type: ignore
@keyword('Maske exportieren') # type: ignore
def export_form(self, Name: str, Verzeichnis: str): # type: ignore
"""
Alle Texte in der aktuellen Maske werden in einer JSON-Datei gespeichert. Außerdem wird ein Bildschirmfoto in PNG-Format erstellt.
| ``Maske exportieren Name Verzeichnis``
Verzeichnis: Der absolute Pfad des Verzeichnisses, wo die Dateien abgelegt werden.
"""
args = [Name, Verzeichnis]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"Pass": "Die Maske wurde in den Dateien '{0}' und '{1}' gespeichert",
"Exception": "Die Maske konnte nicht exportiert werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('ExportForm', args, result) # type: ignore
@keyword('Tabellenzelle ausfüllen') # type: ignore
def fill_table_cell(self, Zeile: str, Spaltentitel_gleich_Inhalt: str): # type: ignore
"""
Die Zelle am Schnittpunkt der angegebenen Zeile und Spalte wird mit dem angegebenen Inhalt ausgefüllt.
| ``Tabellenzelle ausfüllen Zeile Spaltentitel = Inhalt``
Zeile: entweder eine Zeilennummer oder der Inhalt einer Zelle in der Zeile.
*Hinweis*: Eine Tabellenzelle hat u.U. eine Beschriftung, die man über die Hilfe (Taste F1) herausfinden kann. In diesem Fall kann man die Zelle mit dem Keyword [#Textfeld%20Ausfüllen|Textfeld ausfüllen] ausfüllen.
"""
args = [Zeile, Spaltentitel_gleich_Inhalt]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"InvalidFormat": "Das zweite Argument muss dem Muster `Spalte = Inhalt` entsprechen",
"NotFound": "Die Zelle mit dem Lokator '{0}, {1}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"NotChangeable": "Die Zelle mit dem Lokator '{0}, {1}' ist nicht bearbeitbar.",
"Pass": "Die Zelle mit dem Lokator '{0}, {1}' wurde ausgefüllt.",
"Exception": "Die Zelle konnte nicht ausgefüllt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('FillTableCell', args, result) # type: ignore
@keyword('Textfeld ausfüllen') # type: ignore
def fill_text_field(self, Beschriftung_oder_Lokator: str, Inhalt: str): # type: ignore
"""
Das angegebene Textfeld wird mit dem angegebenen Inhalt ausgefüllt.
*Textfeld mit einer Beschriftung links*
| ``Textfeld ausfüllen Beschriftung Inhalt``
*Textfeld mit einer Beschriftung oben*
| ``Textfeld ausfüllen @ Beschriftung Inhalt``
*Textfeld am Schnittpunkt einer Beschriftung links und einer oben (z.B. eine Abschnittsüberschrift)*
| ``Textfeld ausfüllen Beschriftung links @ Beschriftung oben Inhalt``
*Textfeld ohne Beschriftung unter einem Textfeld mit einer Beschriftung (z.B. eine Adresszeile)*
| ``Textfeld ausfüllen Position (1,2,..) @ Beschriftung Inhalt``
*Textfeld ohne Beschriftung rechts von einem Textfeld mit einer Beschriftung*
| ``Textfeld ausfüllen Beschriftung @ Position (1,2,..) Inhalt``
*Textfeld mit einer nicht eindeutigen Beschriftung rechts von einem Textfeld mit einer Beschriftung*
| ``Textfeld ausfüllen Beschriftung des linken Textfelds >> Beschriftung Inhalt``
*Hinweis*: In der Regel hat ein Textfeld eine unsichtbare Beschriftung, die man über die Hilfe (Taste F1) herausfinden kann.
"""
args = [Beschriftung_oder_Lokator, Inhalt]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Das Textfeld mit dem Lokator '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Das Textfeld mit dem Lokator '{0}' wurde ausgefüllt.",
"Exception": "Das Textfeld konnte nicht ausgefüllt werden. Möglicherweise, weil der Inhalt nicht dazu passt.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('FillTextField', args, result) # type: ignore
@keyword('Knopf hervorheben') # type: ignore
def highlight_button(self, Name_oder_Kurzinfo: str): # type: ignore
"""
Der Knopf mit dem angegebenen Namen oder Kurzinfo (Tooltip) wird hervorgehoben.
| ``Knopf hervorheben Name oder Kurzinfo (Tooltip)``
"""
args = [Name_oder_Kurzinfo]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Der Knopf '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Der Knopf '{0}' wurde hervorgehoben.",
"Exception": "Der Knopf konnte nicht hervorgehoben werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('HighlightButton', args, result) # type: ignore
@keyword('Knopf drücken') # type: ignore
def push_button(self, Name_oder_Kurzinfo: str): # type: ignore
"""
Der Knopf mit dem angegebenen Namen oder Kurzinfo (Tooltip) wird gedrückt.
| ``Knopf drücken Name oder Kurzinfo (Tooltip)``
"""
args = [Name_oder_Kurzinfo]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"SapError": "SAP Fehlermeldung: {0}",
"NotFound": "Der Knopf '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Der Knopf '{0}' wurde gedrückt.",
"Exception": "Der Knopf konnte nicht gedrückt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('PushButton', args, result) # type: ignore
@keyword('Tabellenzelle drücken') # type: ignore
def push_button_cell(self, Zeile: str, Spaltentitel: str): # type: ignore
"""
Die angegebene Tabellenzelle wird gedrückt.
| ``Tabellenzelle drücken Zeile Spaltentitel``
Zeile: Zeilennummer, Beschriftung oder Kurzinfo (Tooltip).
"""
args = [Zeile, Spaltentitel]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Die Zelle mit dem Lokator '{0}, {1}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Die Zelle mit dem Lokator '{0}, {1}' wurde gedrückt.",
"Exception": "Die Zelle konnte nicht gedrückt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('PushButtonCell', args, result) # type: ignore
@keyword('Textfeld auslesen') # type: ignore
def read_text_field(self, Beschriftung_oder_Lokator: str): # type: ignore
"""
Der Inhalt des angegebenen Textfeldes wird zurückgegeben.
*Textfeld mit einer Beschriftung links*
| ``Textfeld auslesen Beschriftung``
*Textfeld mit einer Beschriftung oben*
| ``Textfeld auslesen @ Beschriftung``
*Textfeld am Schnittpunkt einer Beschriftung links und einer oben*
| ``Textfeld auslesen Beschriftung links @ Beschriftung oben``
*Textfeld mit dem angegebenen Inhalt*
| ``Textfeld auslesen = Inhalt``
"""
args = [Beschriftung_oder_Lokator]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Das Textfeld mit dem Lokator '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Das Textfeld mit dem Lokator '{0}' wurde ausgelesen.",
"Exception": "Das Textfeld konnte nicht ausgelesen werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('ReadTextField', args, result) # type: ignore
@keyword('Text auslesen') # type: ignore
def read_text(self, Lokator: str): # type: ignore
"""
Der Inhalt des angegebenen Texts wird zurückgegeben.
*Text beginnt mit der angegebenen Teilzeichenfolge*
| ``Text auslesen = Teilzeichenfolge``
*Text folgt einer Beschriftung*
| ``Text auslesen Beschriftung``
"""
args = [Lokator]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Der Text mit dem Lokator '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Der Text mit dem Lokator '{0}' wurde ausgelesen.",
"Exception": "Der Text konnte nicht ausgelesen werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('ReadText', args, result) # type: ignore
@keyword('Tabellenzelle auslesen') # type: ignore
def read_table_cell(self, Zeile: str, Spaltentitel: str): # type: ignore
"""
Der Inhalt der angegebenen Tabellenzelle wird zurückgegeben.
| ``Tabellenzelle auslesen Zeile Spaltentitel``
Zeile: Zeilennummer oder Zellinhalt.
"""
args = [Zeile, Spaltentitel]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Die Zelle mit dem Lokator '{0}, {1}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Die Zelle mit dem Lokator '{0}, {1}' wurde ausgelesen.",
"Exception": "Die Zelle konnte nicht ausgelesen werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('ReadTableCell', args, result) # type: ignore
@keyword('Fenster aufnehmen') # type: ignore
def save_screenshot(self, Dateipfad: str): # type: ignore
"""
Eine Bildschirmaufnahme des Fensters wird im eingegebenen Dateipfad gespeichert.
| ``Fenster aufnehmen Dateipfad``
Dateifpad: Der absolute Pfad einer .png Datei.
"""
args = [Dateipfad]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"InvalidPath": "Der Pfad '{0}' ist ungültig",
"UNCPath": "Ein UNC Pfad (d.h. beginnend mit \\\\) ist nicht erlaubt",
"NoAbsPath": "'{0}' ist kein absoluter Pfad",
"Pass": "Eine Aufnahme des Fensters wurde in '{0}' gespeichert.",
"Exception": "Eine Aufnahme des Fensters konnte nicht gespeichert werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('SaveScreenshot', args, result) # type: ignore
@keyword('Tabellenzelle markieren') # type: ignore
def select_cell(self, Zeile: str, Spaltentitel: str): # type: ignore
"""
Die angegebene Tabellenzelle wird markiert.
| ``Tabellenzelle markieren Zeile Spaltentitel``
Zeile: Zeilennummer oder Zellinhalt.
"""
args = [Zeile, Spaltentitel]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Die Zelle mit dem Lokator '{0}, {1}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Die Zelle mit dem Lokator '{0}, {1}' wurde markiert.",
"Exception": "Die Zelle konnte nicht markiert werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('SelectCell', args, result) # type: ignore
@keyword('Auswahlmenüeintrag auswählen') # type: ignore
def select_combo_box_entry(self, Name: str, Eintrag: str): # type: ignore
"""
Aus dem angegebenen Auswahlmenü wird der angegebene Eintrag ausgewählt.
| ``Auswahlmenüeintrag auswählen Auswahlmenü Eintrag``
"""
args = [Name, Eintrag]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Das Auswahlmenü mit dem Lokator '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"EntryNotFound": "Der Eintrag '{1}' wurde im Auswahlmenü '{0}' nicht gefunden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Der Eintrag '{1}' wurde ausgewählt.",
"Exception": "Der Eintrag konnte nicht ausgewählt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('SelectComboBoxEntry', args, result) # type: ignore
@keyword('Optionsfeld auswählen') # type: ignore
def select_radio_button(self, Beschriftung_oder_Lokator: str): # type: ignore
"""
Das angegebene Optionsfeld wird ausgewählt.
*Optionsfeld mit einer Beschriftung links oder rechts*
| ``Optionsfeld auswählen Beschriftung``
*Optionsfeld mit einer Beschriftung oben*
| ``Optionsfeld auswählen @ Beschriftung``
*Optionsfeld am Schnittpunkt einer Beschriftung links (oder rechts) und einer oben*
| ``Optionsfeld auswählen Beschriftung links @ Beschriftung oben``
"""
args = [Beschriftung_oder_Lokator]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Das Optionsfeld mit dem Lokator '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Das Optionsfeld mit dem Lokator '{0}' wurde ausgewählt.",
"Exception": "Das Optionsfeld konnte nicht ausgewählt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('SelectRadioButton', args, result) # type: ignore
@keyword('Tabellenzeile markieren') # type: ignore
def select_table_row(self, Zeilennummer: str): # type: ignore
"""
Die angegebene Tabellenzeile wird markiert.
| ``Tabellenzeile markieren Zeilennummer``
"""
args = [Zeilennummer]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"Exception": "Die Zeile '{0}' konnte nicht markiert werden\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen.",
"NotFound": "Die Tabelle enthält keine Zeile '{0}'",
"Pass": "Die Zeile '{0}' wurde markiert"
}
return super()._run_keyword('SelectTableRow', args, result) # type: ignore
@keyword('Textfeld markieren') # type: ignore
def select_text_field(self, Beschriftungen_oder_Lokator: str): # type: ignore
"""
Das angegebene Textfeld wird markiert.
*Textfeld mit einer Beschriftung links*
| ``Textfeld markieren Beschriftung``
*Textfeld mit einer Beschriftung oben*
| ``Textfeld markieren @ Beschriftung``
*Textfeld am Schnittpunkt einer Beschriftung links und einer oben*
| ``Textfeld markieren Beschriftung links @ Beschriftung oben``
*Textfeld mit dem angegebenen Inhalt*
| ``Textfeld markieren = Inhalt``
"""
args = [Beschriftungen_oder_Lokator]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Das Textfeld mit dem Lokator '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Das Textfeld mit dem Lokator '{0}' wurde markiert.",
"Exception": "Das Textfeld konnte nicht markiert werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('SelectTextField', args, result) # type: ignore
@keyword('Textzeile markieren') # type: ignore
def select_text_line(self, Inhalt: str): # type: ignore
"""
Die Textzeile mit dem angegebenen Inhalt wird markiert.
| ``Textzeile markieren Inhalt``
"""
args = [Inhalt]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Die Textzeile mit dem Inhalt '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Die Textzeile mit dem Inhalt '{0}' wurde markiert.",
"Exception": "Die Textzeile konnte nicht markiert werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('SelectTextLine', args, result) # type: ignore
@keyword('Formularfeld ankreuzen') # type: ignore
def tick_check_box(self, Beschriftung_oder_Lokator: str): # type: ignore
"""
Das angegebene Formularfeld wird angekreuzt.
*Formularfeld mit einer Beschriftung links oder rechts *
| ``Formularfeld ankreuzen Beschriftung``
*Formularfeld mit einer Beschriftung oben*
| ``Formularfeld ankreuzen @ Beschriftung``
*Formularfeld am Schnittpunkt einer Beschriftung links und einer oben*
| ``Formularfeld ankreuzen Beschriftung links @ Beschriftung oben``
"""
args = [Beschriftung_oder_Lokator]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Das Formularfeld mit dem Lokator '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Das Formularfeld mit dem Lokator '{0}' wurde angekreuzt.",
"Exception": "Das Formularfeld konnte nicht angekreuzt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('TickCheckBox', args, result) # type: ignore
@keyword('Statusleiste auslesen') # type: ignore
def read_statusbar(self): # type: ignore
"""
Die Nachricht der Statusleiste wird ausgelesen.
``Statusleiste auslesen``
"""
args = []
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Keine Statusleiste gefunden.",
"Exception": "Die Statusleiste konnte nicht ausgelesen werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen.",
"Pass": "Die Statusleiste wurde ausgelesen."
}
return super()._run_keyword('ReadStatusbar', args, result) # type: ignore
@keyword('Formularfeld abwählen') # type: ignore
def untick_check_box(self, Beschriftung_oder_Lokator: str): # type: ignore
"""
Das angegebene Formularfeld wird abgewählt.
*Formularfeld mit einer Beschriftung links oder rechts*
| ``Formularfeld abwählen Beschriftung``
*Formularfeld mit einer Beschriftung oben*
| ``Formularfeld abwählen @ Beschriftung``
*Formularfeld am Schnittpunkt einer Beschriftung links und einer oben*
| ``Formularfeld abwählen Beschriftung links @ Beschriftung oben``
"""
args = [Beschriftung_oder_Lokator]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Das Formularfeld mit dem Lokator '{0}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Das Formularfeld mit dem Lokator '{0}' wurde abgewählt.",
"Exception": "Das Formularfeld konnte nicht abgewählt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('UntickCheckBox', args, result) # type: ignore
@keyword('Tabellenzelle ankreuzen') # type: ignore
def tick_check_box_cell(self, Zeilennummer: str, Spaltentitel: str): # type: ignore
"""
Die angegebene Tabellenzelle wird angekreuzt.
| ``Tabellenzelle ankreuzen Zeilennummer Spaltentitel``
"""
args = [Zeilennummer, Spaltentitel]
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"NotFound": "Die Zelle mit dem Lokator '{0}, {1}' konnte nicht gefunden werden.\nHinweis: Prüfe die Rechtschreibung",
"Pass": "Die Zelle mit dem Lokator '{0}, {1}' wurde angekreuzt.",
"Exception": "Die Zelle konnte nicht angekreuzt werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('TickCheckBoxCell', args, result) # type: ignore
@keyword('Fenstertitel auslesen') # type: ignore
def get_window_title(self): # type: ignore
"""
Der Titel des Fensters im Fordergrund wird zurückgegeben.
| ``${Titel} Fenstertitel auslesen``
"""
args = []
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"Pass": "Der Fenstertitel wurde ausgelesen",
"Exception": "Der Titel des Fensters konnte nicht ausgelesen werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('GetWindowTitle', args, result) # type: ignore
@keyword('Fenstertext auslesen') # type: ignore
def get_window_text(self): # type: ignore
"""
Der Text des Fensters im Fordergrund wird zurückgegeben.
| ``${Text} Fenstertext auslesen``
"""
args = []
result = {
"NoSession": "Keine SAP-Session vorhanden. Versuche zuerst das Keyword \"Verbindung zum Server Herstellen\" aufzurufen.",
"Pass": "Der Text des Fensters wurde ausgelesen",
"Exception": "Der Text des Fensters konnte nicht ausgelesen werden.\n{0}\nFür mehr Infos robot --loglevel DEBUG datei.robot ausführen und die log.html Datei durchsuchen."
}
return super()._run_keyword('GetWindowText', args, result) # type: ignore
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = '1.2.7' | /robotframework_robosapiens-1.2.7-py3-none-any.whl/RoboSAPiens/DE/__init__.py | 0.50415 | 0.264082 | __init__.py | pypi |
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
import roslibpy
from roslibpy import Service, ServiceRequest
class ROS(object):
"""Robot Framework test library for the Robot Operating System (ROS)
This library utilizes Robot Framework's
[https://robotframework.org/robotframework/latest/libraries/Process.html|Process]
library for running processes.
== Table of contents ==
%TOC%
"""
ROBOT_LIBRARY_SCOPE = 'SUITE'
def __init__(self):
self.process_lib = BuiltIn().get_library_instance('Process')
@keyword("roslaunch")
def roslaunch(self, package, executable, *args, **kwargs):
"""
Launch a launch file from a specified ROS package using `roslaunch`
Uses robot.libraries.Process
See also https://wiki.ros.org/roslaunch/API%20Usage
"""
return self.process_lib.start_process('roslaunch',
package, executable, *args, **kwargs)
@keyword("rosrun")
def rosrun(self, package, executable, *args, **kwargs):
"""
Run an executable from a specified ROS package using `rosrun`
Uses robot.libraries.Process
"""
return self.process_lib.start_process('rosrun',
package, executable, *args, **kwargs)
'''
rosbridge
http://wiki.ros.org/rosbridge_suite
https://stackoverflow.com/questions/54199557/using-rosbridge-between-two-processes-on-the-same-computer
'''
@keyword("Start rosbridge")
def start_rosbridge(self):
return self.start_rosbridge(9090)
@keyword("Start rosbridge on ${port}")
def start_rosbridge(self, port=9090):
return self.process_lib.start_process('roslaunch',
'rosbridge_server',
'rosbridge_websocket.launch',
'port:=%s' % port
)
@keyword
def rosbridge_connect(self, host='localhost', port=9090):
self.client = roslibpy.Ros(host=host, port=port)
self.client.run()
@keyword
def rosbridge_close(self):
self.client.close()
@keyword
def get_time(self):
return self.client.get_time()
# rosparam
@keyword
def rosparam_set(self, name, value):
''' set parameter '''
self.client.set_param(name, value)
@keyword
def rosparam_get(self, name):
''' get parameter '''
return self.client.get_param(name)
@keyword
def rosparam_load(self, file):
''' TODO load parameters from file '''
@keyword
def rosparam_dump(self, file):
''' TODO dump parameters to file '''
@keyword
def rosparam_delete(self, name):
''' delete parameter '''
return self.client.delete_param(name)
@keyword
def rosparam_list(self):
''' TODO list parameter names '''
# rosservice
@keyword
def rosservice_call(self, name, service_type='std_srvs/Empty', values=None):
return Service(self.client, name, service_type).call(ServiceRequest(values)) | /robotframework-rosgazebolibrary-0.0.5.tar.gz/robotframework-rosgazebolibrary-0.0.5/src/RosGazeboLibrary/ROS.py | 0.668447 | 0.257059 | ROS.py | pypi |
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
class Gazebo(object):
"""Robot Framework test library for the Gazebo simulator
See also http://gazebosim.org/tutorials/?tut=ros_comm
== Table of contents ==
%TOC%
"""
ROBOT_LIBRARY_SCOPE = 'SUITE'
def __init__(self):
self.ros_lib = BuiltIn().get_library_instance('RosGazeboLibrary.ROS')
# Create and destroy models in simulation
# http://gazebosim.org/tutorials/?tut=ros_comm#Services:Createanddestroymodelsinsimulation
@keyword
def spawn_urdf_model(self, urdf_path: str, position: tuple, model_name: str):
''' TODO: Refactor to use service call '''
return self.ros_lib.rosrun('gazebo_ros', 'spawn_model', *[
'-file', urdf_path,
'-urdf',
'-model', model_name,
'-x', position[0],
'-y', position[1],
'-z', position[2],
])
@keyword
def spawn_sdf_model(self, sdf_path: str, position: tuple, model_name: str):
''' TODO: Refactor to use service call '''
return self.ros_lib.rosrun('gazebo_ros', 'spawn_model', *[
'-file', sdf_path,
'-sdf',
'-model', model_name,
'-x', position[0],
'-y', position[1],
'-z', position[2],
])
@keyword
def delete_model(self, model_name: str):
''' Delete a model from simulation
http://gazebosim.org/tutorials/?tut=ros_comm#DeleteModel
'''
return self.ros_lib.rosservice_call(
'gazebo/delete_model', 'gazebo_msgs/DeleteModel',
{ 'model_name': model_name }
)
# State and property setters
# http://gazebosim.org/tutorials/?tut=ros_comm#Services:Stateandpropertysetters
''' TODO
def set_link_properties(self, ...):
def set_physics_properties(self, ...):
def set_model_state(self, ...):
def set_model_configuration(self, ...):
def set_joint_properties(self, ...):
def set_link_state(self, ...):
'''
# State and property getters
# http://gazebosim.org/tutorials/?tut=ros_comm#Services:Stateandpropertygetters
@keyword
def get_model_properties(self, model_name: str):
return self.ros_lib.rosservice_call(
'gazebo/get_model_properties', 'gazebo_msgs/GetModelProperties',
{ 'model_name': model_name }
)
@keyword
def get_model_state(self, model_name: str):
return self.ros_lib.rosservice_call(
'gazebo/get_model_state', 'gazebo_msgs/GetModelState',
{ 'model_name': model_name }
)
''' TODO
def get_world_properties(self, ...):
def get_joint_properties(self, ...):
def get_link_properties(self, ...):
def get_link_state(self, ...):
def get_physics_properties(self, ...):
def link_states(self, ...): # investigate
def model_states(self, ...): # investigate
'''
# Force control
# http://gazebosim.org/tutorials/?tut=ros_comm#Services:Forcecontrol
''' TODO
/gazebo/apply_body_wrench
/gazebo/apply_joint_effort
/gazebo/clear_body_wrenches
/gazebo/clear_joint_forces
'''
# Simulation control
# http://gazebosim.org/tutorials/?tut=ros_comm#Services:Simulationcontrol
@keyword
def reset_simulation(self):
return self.ros_lib.rosservice_call('/gazebo/reset_simulation')
@keyword
def reset_world(self):
return self.ros_lib.rosservice_call('/gazebo/reset_world')
@keyword
def pause_physics(self):
return self.ros_lib.rosservice_call('/gazebo/pause_physics')
@keyword
def unpause_physics(self):
return self.ros_lib.rosservice_call('/gazebo/unpause_physics')
# Undocumented services
# Found via `rosservice list`
'''
/gazebo/delete_light
/gazebo/get_light_properties
/gazebo/get_loggers
/gazebo/set_light_properties
/gazebo/set_logger_level
/gazebo/set_parameters
/gazebo_gui/get_loggers
/gazebo_gui/set_logger_level
'''
# Convenience keywords
@keyword
def launch_empty_world(self):
return self.ros_lib.roslaunch('gazebo_ros', 'empty_world.launch') | /robotframework-rosgazebolibrary-0.0.5.tar.gz/robotframework-rosgazebolibrary-0.0.5/src/RosGazeboLibrary/Gazebo.py | 0.533397 | 0.423041 | Gazebo.py | pypi |
from datetime import datetime
ENTITY_MAP = {
'Keyword': 'STEP',
'SuiteKeyword': 'STEP',
'TestKeyword': 'STEP',
'KeywordKeyword': 'STEP',
'SuiteSetup': 'BEFORE_SUITE',
'SuiteTeardown': 'AFTER_SUITE',
'TestSetup': 'BEFORE_TEST',
'TestTeardown': 'AFTER_TEST',
'KeywordSetup': 'BEFORE_TEST',
'KeywordTeardown': 'AFTER_TEST',
'TestFor': 'TEST',
'KeywordForitem': 'STEP',
'KeywordFor item': 'STEP',
'KeywordFor': 'STEP',
}
def get_item_time(item_time):
if not item_time:
return item_time
return str(int(
datetime.strptime(item_time, '%Y%m%d %H:%M:%S.%f').timestamp() * 1000
))
class Entity:
def __init__(self, name, **attributes):
self.name = name
self.doc = attributes['doc']
self.status = attributes.get('status')
self.message = attributes.get('message')
self.robot_id = attributes.get('id')
self.start_time = get_item_time(attributes.get('starttime'))
self.end_time = get_item_time(attributes.get('endtime'))
self.tags = [str(item) for item in attributes.get('tags', ())]
class Suite(Entity):
def __init__(self, name, **attributes):
super().__init__(name, **attributes)
self.name = attributes['longname']
self.suites = attributes['suites']
self.tests = attributes['tests']
self.source = attributes['source']
self.total_tests = attributes['totaltests']
self.metadata = attributes['metadata']
self.statistics = attributes.get('statistics')
self.entity_type = 'SUITE'
class Test(Entity):
def __init__(self, name, **attributes):
super().__init__(name, **attributes)
self.longname = attributes.get('longname', '')
self.critical = attributes['critical']
self.entity_type = 'TEST'
class Keyword(Entity):
def __init__(self, name, **attributes):
super().__init__(name, **attributes)
self.libname = attributes['libname']
self.keyword_name = attributes['kwname']
self.args = attributes['args']
self.assign = attributes['assign']
self.keyword_type = attributes['type']
self.parent_type = attributes.get('parent_type', '')
self.entity_type = ENTITY_MAP[f'{self.parent_type}{self.keyword_type}']
assign = ', '.join(self.assign)
assignment = f'{assign} = ' if self.assign else ''
arguments = ', '.join(self.args)
self.name = f'{assignment}{self.name} ({arguments})'[:256]
class Message:
def __init__(self, **attributes):
self.message = attributes['message']
self.level = attributes.get('level', 'INFO')
self.attachment = attributes.get('attachment')
self.timestamp = get_item_time(attributes.get('timestamp'))
self.html = attributes['html'] | /robotframework_rp_tools-0.0.6-py3-none-any.whl/robotframework_rp_tools/listener_model.py | 0.699254 | 0.217275 | listener_model.py | pypi |
from datetime import datetime
ENTITY_MAP = {
'TestSuite': 'SUITE',
'TestCase': 'TEST',
'Keyword': 'STEP',
'TestSuiteKeyword': 'STEP',
'TestCaseKeyword': 'STEP',
'KeywordKeyword': 'STEP',
'TestSuiteSetup': 'BEFORE_SUITE',
'TestSuiteTeardown': 'AFTER_SUITE',
'TestCaseSetup': 'BEFORE_TEST',
'TestCaseTeardown': 'AFTER_TEST',
'KeywordSetup': 'BEFORE_TEST',
'KeywordTeardown': 'AFTER_TEST',
'TestCaseFor': 'TEST',
'KeywordForitem': 'STEP',
'KeywordFor': 'STEP',
}
def get_item_time(item_time):
if not item_time:
return item_time
return str(int(
datetime.strptime(item_time, '%Y%m%d %H:%M:%S.%f').timestamp() * 1000
))
class Entity:
def __init__(self, data):
self.name = data.name
self.doc = data.doc
self.status = data.status
self.message = data.message
self.robot_id = data.id
self.tags = [str(item) for item in getattr(data, 'tags', [])]
self.entity_type = ENTITY_MAP[data.__class__.__name__]
self.start_time = get_item_time(getattr(data, 'starttime', None))
self.end_time = get_item_time(getattr(data, 'endtime', None))
class Suite(Entity):
def __init__(self, data):
super().__init__(data)
self.name = data.longname
self.suites = data.suites
self.tests = data.tests
self.source = data.source
self.total_tests = data.test_count
self.metadata = data.metadata
self.statistics = data.statistics
class Test(Entity):
def __init__(self, data):
super().__init__(data)
self.longname = data.longname
self.critical = data.critical
class Keyword(Entity):
def __init__(self, data):
super().__init__(data)
self.libname = data.libname
self.keyword_name = data.kwname
self.args = data.args
self.assign = data.assign
parent_entity_type = self._get_parent_type(data.parent)
if parent_entity_type and data.type != 'kw':
self.entity_type = ENTITY_MAP[f'{parent_entity_type}{data.type.capitalize()}']
assign = ', '.join(self.assign)
assignment = f'{assign} = ' if self.assign else ''
arguments = ', '.join(self.args)
self.name = f'{assignment}{self.name} ({arguments})'[:256]
@staticmethod
def _get_parent_type(data):
if not data:
return None
return data.__class__.__name__
class Message:
def __init__(self, data):
self.message = data.message
self.level = data.level
self.attachment = getattr(data, 'attachment', None)
self.timestamp = get_item_time(data.timestamp)
self.html = data.html | /robotframework_rp_tools-0.0.6-py3-none-any.whl/robotframework_rp_tools/visitor_model.py | 0.634204 | 0.411347 | visitor_model.py | pypi |
import pythoncom
import win32com.client
import time
from pythoncom import com_error
import robot.libraries.Screenshot as screenshot
import os
from robot.api import logger
class SapGuiLibrary:
"""The SapGuiLibrary is a library that enables users to create tests for the Sap Gui application
The library uses the Sap Scripting Engine, therefore Scripting must be enabled in Sap in order for this library to work.
= Opening a connection / Before running tests =
First of all, you have to *make sure the Sap Logon Pad is started*. You can automate this process by using the
AutoIT library or the Process Library.
After the Sap Login Pad is started, you can connect to the Sap Session using the keyword `connect to session`.
If you have a successful connection you can use `Open Connection` to open a new connection from the Sap Logon Pad
or `Connect To Existing Connection` to connect to a connection that is already open.
= Locating or specifying elements =
You need to specify elements starting from the window ID, for example, wnd[0]/tbar[1]/btn[8]. In some cases the SAP
ID contains backslashes. Make sure you escape these backslashes by adding another backslash in front of it.
= Screenshots (on error) =
The SapGUILibrary offers an option for automatic screenshots on error.
Default this option is enabled, use keyword `disable screenshots on error` to skip the screenshot functionality.
Alternatively, this option can be set at import.
"""
__version__ = '1.1'
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def __init__(self, screenshots_on_error=True, screenshot_directory=None):
"""Sets default variables for the library
"""
self.explicit_wait = float(0.0)
self.sapapp = -1
self.session = -1
self.connection = -1
self.take_screenshots = screenshots_on_error
self.screenshot = screenshot.Screenshot()
if screenshot_directory is not None:
if not os.path.exists(screenshot_directory):
os.makedirs(screenshot_directory)
self.screenshot.set_screenshot_directory(screenshot_directory)
def click_element(self, element_id):
"""Performs a single click on a given element. Used only for buttons, tabs and menu items.
In case you want to change a value of an element like checkboxes of selecting an option in dropdown lists,
use `select checkbox` or `select from list by label` instead.
"""
# Performing the correct method on an element, depending on the type of element
element_type = self.get_element_type(element_id)
if (element_type == "GuiTab"
or element_type == "GuiMenu"):
self.session.findById(element_id).select()
elif element_type == "GuiButton":
self.session.findById(element_id).press()
else:
self.take_screenshot()
message = "You cannot use 'click_element' on element type '%s', maybe use 'select checkbox' instead?" % element_type
raise Warning(message)
time.sleep(self.explicit_wait)
def click_toolbar_button(self, table_id, button_id):
"""Clicks a button of a toolbar within a GridView 'table_id' which is contained within a shell object.
Use the Scripting tracker recorder to find the 'button_id' of the button to click
"""
self.element_should_be_present(table_id)
try:
self.session.findById(table_id).pressToolbarButton(button_id)
except AttributeError:
self.take_screenshot()
self.session.findById(table_id).pressButton(button_id)
except com_error:
self.take_screenshot()
message = "Cannot find Button_id '%s'." % button_id
raise ValueError(message)
time.sleep(self.explicit_wait)
def connect_to_existing_connection(self, connection_name):
"""Connects to an open connection. If the connection matches the given connection_name, the session is connected
to this connection.
"""
self.connection = self.sapapp.Children(0)
if self.connection.Description == connection_name:
self.session = self.connection.children(0)
else:
self.take_screenshot()
message = "No existing connection for '%s' found." % connection_name
raise ValueError(message)
def connect_to_session(self, explicit_wait=0):
"""Connects to an open session SAP.
See `Opening a connection / Before running tests` for details about requirements before connecting to a session.
Optionally `set explicit wait` can be used to set the explicit wait time.
*Examples*:
| *Keyword* | *Attributes* |
| connect to session | |
| connect to session | 3 |
| connect to session | explicit_wait=500ms |
"""
lenstr = len("SAPGUI")
rot = pythoncom.GetRunningObjectTable()
rotenum = rot.EnumRunning()
while True:
monikers = rotenum.Next()
if not monikers:
break
ctx = pythoncom.CreateBindCtx(0)
name = monikers[0].GetDisplayName(ctx, None);
if name[-lenstr:] == "SAPGUI":
obj = rot.GetObject(monikers[0])
sapgui = win32com.client.Dispatch(obj.QueryInterface(pythoncom.IID_IDispatch))
self.sapapp = sapgui.GetScriptingEngine
# Set explicit_wait after connection succeed
self.set_explicit_wait(explicit_wait)
if hasattr(self.sapapp, "OpenConnection") == False:
self.take_screenshot()
message = "Could not connect to Session, is Sap Logon Pad open?"
raise Warning(message)
# run explicit wait last
time.sleep(self.explicit_wait)
def disable_screenshots_on_error(self):
"""Disables automatic screenshots on error.
"""
self.take_screenshots = False
def doubleclick_element(self, element_id, item_id, column_id):
"""Performs a double-click on a given element. Used only for shell objects.
"""
# Performing the correct method on an element, depending on the type of element
element_type = self.get_element_type(element_id)
if element_type == "GuiShell":
self.session.findById(element_id).doubleClickItem(item_id, column_id)
else:
self.take_screenshot()
message = "You cannot use 'doubleclick element' on element type '%s', maybe use 'click element' instead?" % element_type
raise Warning(message)
time.sleep(self.explicit_wait)
def element_should_be_present(self, element_id, message=None):
"""Checks whether an element is present on the screen.
"""
try:
self.session.findById(element_id)
except com_error:
self.take_screenshot()
if message is None:
message = "Cannot find Element '%s'." % element_id
raise ValueError(message)
def element_value_should_be(self, element_id, expected_value, message=None):
"""Checks whether the element value is the same as the expected value.
The possible expected values depend on the type of element (see usage).
Usage:
| *Element type* | *possible values* |
| textfield | text |
| label | text |
| checkbox | checked / unchecked |
| radiobutton | checked / unchecked |
| combobox | text of the option to be expected |
"""
element_type = self.get_element_type(element_id)
actual_value = self.get_value(element_id)
# Breaking up the different element types so we can check the value the correct way
if (element_type == "GuiTextField"
or element_type == "GuiCTextField"
or element_type == "GuiComboBox"
or element_type == "GuiLabel"):
self.session.findById(element_id).setfocus()
time.sleep(self.explicit_wait)
# In these cases we can simply check the text value against the value of the element
if expected_value != actual_value:
if message is None:
message = "Element value of '%s' should be '%s', but was '%s'" % (
element_id, expected_value, actual_value)
self.take_screenshot()
raise AssertionError(message)
elif element_type == "GuiStatusPane":
if expected_value != actual_value:
if message is None:
message = "Element value of '%s' should be '%s', but was '%s'" % (
element_id, expected_value, actual_value)
self.take_screenshot()
raise AssertionError(message)
elif (element_type == "GuiCheckBox"
or element_type == "GuiRadioButton"):
# First check if there is a correct value given, otherwise raise an assertion error
self.session.findById(element_id).setfocus()
if (expected_value.lower() != "checked"
and expected_value.lower() != "unchecked"):
# Raise an AsertionError when no correct expected_value is given
self.take_screenshot()
if message is None:
message = "Incorrect value for element type '%s', provide checked or unchecked" % element_type
raise AssertionError(message)
# Check whether the expected value matches the actual value. If not, raise an assertion error
if expected_value.lower() != actual_value:
self.take_screenshot()
if message is None:
message = "Element value of '%s' didn't match the expected value" % element_id
raise AssertionError(message)
else:
# When the type of element can't be checked, raise an assertion error
self.take_screenshot()
message = "Cannot use keyword 'element value should be' for element type '%s'" % element_type
raise Warning(message)
# Run explicit wait as last
time.sleep(self.explicit_wait)
def element_value_should_contain(self, element_id, expected_value, message=None):
"""Checks whether the element value contains the expected value.
The possible expected values depend on the type of element (see usage).
Usage:
| *Element type* | *possible values* |
| textfield | text |
| label | text |
| combobox | text of the option to be expected |
"""
element_type = self.get_element_type(element_id)
# Breaking up the different element types so we can check the value the correct way
if (element_type == "GuiTextField"
or element_type == "GuiCTextField"
or element_type == "GuiComboBox"
or element_type == "GuiLabel"):
self.session.findById(element_id).setfocus()
actual_value = self.get_value(element_id)
time.sleep(self.explicit_wait)
# In these cases we can simply check the text value against the value of the element
if expected_value not in actual_value:
self.take_screenshot()
if message is None:
message = "Element value '%s' does not contain '%s', (but was '%s')" % (
element_id, expected_value, actual_value)
raise AssertionError(message)
else:
# When the element content can't be checked, raise an assertion error
self.take_screenshot()
message = "Cannot use keyword 'element value should contain' for element type '%s'" % element_type
raise Warning(message)
# Run explicit wait as last
time.sleep(self.explicit_wait)
def enable_screenshots_on_error(self):
"""Enables automatic screenshots on error.
"""
self.take_screenshots = True
def get_cell_value(self, table_id, row_num, col_id):
"""Returns the cell value for the specified cell.
"""
self.element_should_be_present(table_id)
try:
cellValue = self.session.findById(table_id).getCellValue(row_num, col_id)
return cellValue
except com_error:
self.take_screenshot()
message = "Cannot find Column_id '%s'." % col_id
raise ValueError(message)
def get_element_location(self, element_id):
"""Returns the Sap element location for the given element.
"""
self.element_should_be_present(element_id)
screenleft = self.session.findById(element_id).screenLeft
screentop = self.session.findById(element_id).screenTop
return screenleft, screentop
def get_element_type(self, element_id):
"""Returns the Sap element type for the given element.
"""
try:
type = self.session.findById(element_id).type
return type
except com_error:
self.take_screenshot()
message = "Cannot find element with id '%s'" % element_id
raise ValueError(message)
def get_row_count(self, table_id):
"""Returns the number of rows found in the specified table.
"""
self.element_should_be_present(table_id)
rowCount = self.session.findById(table_id).rowCount
return rowCount
def get_scroll_position(self, element_id):
"""Returns the scroll position of the scrollbar of an element 'element_id' that is contained within a shell object.
"""
self.element_should_be_present(element_id)
currentPosition = self.session.findById(element_id).verticalScrollbar.position
return currentPosition
def get_value(self, element_id):
"""Gets the value of the given element. The possible return values depend on the type of element (see Return values).
Return values:
| *Element type* | *Return values* |
| textfield | text |
| label | text |
| checkbox | checked / unchecked |
| radiobutton | checked / unchecked |
| combobox | text of the selected option |
| guibutton | text |
| guititlebar | text |
| guistatusbar | text |
| guitab | text |
"""
element_type = self.get_element_type(element_id)
return_value = ""
if (element_type == "GuiTextField"
or element_type == "GuiCTextField"
or element_type == "GuiLabel"
or element_type == "GuiTitlebar"
or element_type == "GuiStatusbar"
or element_type == "GuiButton"
or element_type == "GuiTab"
or element_type == "GuiShell"):
self.set_focus(element_id)
return_value = self.session.findById(element_id).text
elif element_type == "GuiStatusPane":
return_value = self.session.findById(element_id).text
elif (element_type == "GuiCheckBox"
or element_type == "GuiRadioButton"):
actual_value = self.session.findById(element_id).selected
# In these situations we return check / unchecked, so we change these values here
if actual_value == True:
return_value = "checked"
elif actual_value == False:
return_value = "unchecked"
elif element_type == "GuiComboBox":
return_value = self.session.findById(element_id).text
# In comboboxes there are many spaces after the value. In order to check the value, we strip them away.
return_value = return_value.strip()
else:
# If we can't return the value for this element type, raise an assertion error
self.take_screenshot()
message = "Cannot get value for element type '%s'" % element_type
raise Warning(message)
return return_value
def get_window_title(self, locator):
"""Retrieves the window title of the given window.
"""
return_value = ""
try:
return_value = self.session.findById(locator).text
except com_error:
self.take_screenshot()
message = "Cannot find window with locator '%s'" % locator
raise ValueError(message)
return return_value
def input_password(self, element_id, password):
"""Inserts the given password into the text field identified by locator.
The password is not recorded in the log.
"""
element_type = self.get_element_type(element_id)
if (element_type == "GuiTextField"
or element_type == "GuiCTextField"
or element_type == "GuiShell"
or element_type == "GuiPasswordField"):
self.session.findById(element_id).text = password
logger.info("Typing password into text field '%s'." % element_id)
time.sleep(self.explicit_wait)
else:
self.take_screenshot()
message = "Cannot use keyword 'input password' for element type '%s'" % element_type
raise ValueError(message)
def input_text(self, element_id, text):
"""Inserts the given text into the text field identified by locator.
Use keyword `input password` to insert a password in a text field.
"""
element_type = self.get_element_type(element_id)
if (element_type == "GuiTextField"
or element_type == "GuiCTextField"
or element_type == "GuiShell"
or element_type == "GuiPasswordField"):
self.session.findById(element_id).text = text
logger.info("Typing text '%s' into text field '%s'." % (text, element_id))
time.sleep(self.explicit_wait)
else:
self.take_screenshot()
message = "Cannot use keyword 'input text' for element type '%s'" % element_type
raise ValueError(message)
def maximize_window(self, window=0):
"""Maximizes the SapGui window.
"""
try:
self.session.findById("wnd[%s]" % window).maximize()
time.sleep(self.explicit_wait)
except com_error:
self.take_screenshot()
message = "Cannot maximize window wnd[% s], is the window actually open?" % window
raise ValueError(message)
# run explicit wait last
time.sleep(self.explicit_wait)
def open_connection(self, connection_name):
"""Opens a connection to the given connection name. Be sure to provide the full connection name, including the bracket part.
"""
# First check if the sapapp is set and OpenConnection method exists
if hasattr(self.sapapp, "OpenConnection") == False:
self.take_screenshot()
message = "Cannot find an open Sap Login Pad, is Sap Logon Pad open?"
raise Warning(message)
try:
self.connection = self.sapapp.OpenConnection(connection_name, True)
except com_error:
self.take_screenshot()
message = "Cannot open connection '%s', please check connection name." % connection_name
raise ValueError(message)
self.session = self.connection.children(0)
# run explicit wait last
time.sleep(self.explicit_wait)
def run_transaction(self, transaction):
"""Runs a Sap transaction. An error is given when an unknown transaction is specified.
"""
self.session.findById("wnd[0]/tbar[0]/okcd").text = transaction
time.sleep(self.explicit_wait)
self.send_vkey(0)
if transaction == '/nex':
return
pane_value = self.session.findById("wnd[0]/sbar/pane[0]").text
if pane_value in ("Transactie %s bestaat niet" % transaction.upper(),
"Transaction %s does not exist" % transaction.upper(),
"Transaktion %s existiert nicht" % transaction.upper()):
self.take_screenshot()
message = "Unknown transaction: '%s'" % transaction
raise ValueError(message)
def scroll(self, element_id, position):
"""Scrolls the scrollbar of an element 'element_id' that is contained within a shell object.
'Position' is the number of rows to scroll.
"""
self.element_should_be_present(element_id)
self.session.findById(element_id).verticalScrollbar.position = position
time.sleep(self.explicit_wait)
def select_checkbox(self, element_id):
"""Selects checkbox identified by locator.
Does nothing if the checkbox is already selected.
"""
element_type = self.get_element_type(element_id)
if element_type == "GuiCheckBox":
self.session.findById(element_id).selected = True
else:
self.take_screenshot()
message = "Cannot use keyword 'select checkbox' for element type '%s'" % element_type
raise ValueError(message)
time.sleep(self.explicit_wait)
def select_context_menu_item(self, element_id, menu_or_button_id, item_id):
"""Selects an item from the context menu by clicking a button or right-clicking in the node context menu.
"""
self.element_should_be_present(element_id)
# The function checks if the element has an attribute "nodeContextMenu" or "pressContextButton"
if hasattr(self.session.findById(element_id), "nodeContextMenu"):
self.session.findById(element_id).nodeContextMenu(menu_or_button_id)
elif hasattr(self.session.findById(element_id), "pressContextButton"):
self.session.findById(element_id).pressContextButton(menu_or_button_id)
# The element has neither attributes, give an error message
else:
self.take_screenshot()
element_type = self.get_element_type(element_id)
message = "Cannot use keyword 'select context menu item' for element type '%s'" % element_type
raise ValueError(message)
self.session.findById(element_id).selectContextMenuItem(item_id)
time.sleep(self.explicit_wait)
def select_from_list_by_label(self, element_id, value):
"""Selects the specified option from the selection list.
"""
element_type = self.get_element_type(element_id)
if element_type == "GuiComboBox":
self.session.findById(element_id).value = value
time.sleep(self.explicit_wait)
else:
self.take_screenshot()
message = "Cannot use keyword 'select from list by label' for element type '%s'" % element_type
raise ValueError(message)
def select_node(self, tree_id, node_id, expand=False):
"""Selects a node of a TableTreeControl 'tree_id' which is contained within a shell object.
Use the Scripting tracker recorder to find the 'node_id' of the node.
Expand can be set to True to expand the node. If the node cannot be expanded, no error is given.
"""
self.element_should_be_present(tree_id)
self.session.findById(tree_id).selectedNode = node_id
if expand:
#TODO: elegantere manier vinden om dit af te vangen
try:
self.session.findById(tree_id).expandNode(node_id)
except com_error:
pass
time.sleep(self.explicit_wait)
def select_node_link(self, tree_id, link_id1, link_id2):
"""Selects a link of a TableTreeControl 'tree_id' which is contained within a shell object.
Use the Scripting tracker recorder to find the 'link_id1' and 'link_id2' of the link to select.
"""
self.element_should_be_present(tree_id)
self.session.findById(tree_id).selectItem(link_id1, link_id2)
self.session.findById(tree_id).clickLink(link_id1, link_id2)
time.sleep(self.explicit_wait)
def select_radio_button(self, element_id):
"""Sets radio button to the specified value.
"""
element_type = self.get_element_type(element_id)
if element_type == "GuiRadioButton":
self.session.findById(element_id).selected = True
else:
self.take_screenshot()
message = "Cannot use keyword 'select radio button' for element type '%s'" % element_type
raise ValueError(message)
time.sleep(self.explicit_wait)
def select_table_column(self, table_id, column_id):
"""Selects an entire column of a GridView 'table_id' which is contained within a shell object.
Use the Scripting tracker recorder to find the 'column_id' of the column to select.
"""
self.element_should_be_present(table_id)
try:
self.session.findById(table_id).selectColumn(column_id)
except com_error:
self.take_screenshot()
message = "Cannot find Column_id '%s'." % column_id
raise ValueError(message)
time.sleep(self.explicit_wait)
def select_table_row(self, table_id, row_num):
"""Selects an entire row of a table. This can either be a TableControl or a GridView 'table_id'
which is contained within a shell object. The row is an index to select the row, starting from 0.
"""
element_type = self.get_element_type(table_id)
if (element_type == "GuiTableControl"):
id = self.session.findById(table_id).getAbsoluteRow(row_num)
id.selected = -1
else:
try:
self.session.findById(table_id).selectedRows = row_num
except com_error:
self.take_screenshot()
message = "Cannot use keyword 'select table row' for element type '%s'" % element_type
raise ValueError(message)
time.sleep(self.explicit_wait)
def send_vkey(self, vkey_id, window=0):
"""Sends a SAP virtual key combination to the window, not into an element.
If you want to send a value to a text field, use `input text` instead.
To send a vkey, you can either use te *VKey ID* or the *Key combination*.
Sap Virtual Keys (on Windows)
| *VKey ID* | *Key combination* | *VKey ID* | *Key combination* | *VKey ID* | *Key combination* |
| *0* | Enter | *26* | Ctrl + F2 | *72* | Ctrl + A |
| *1* | F1 | *27* | Ctrl + F3 | *73* | Ctrl + D |
| *2* | F2 | *28* | Ctrl + F4 | *74* | Ctrl + N |
| *3* | F3 | *29* | Ctrl + F5 | *75* | Ctrl + O |
| *4* | F4 | *30* | Ctrl + F6 | *76* | Shift + Del |
| *5* | F5 | *31* | Ctrl + F7 | *77* | Ctrl + Ins |
| *6* | F6 | *32* | Ctrl + F8 | *78* | Shift + Ins |
| *7* | F7 | *33* | Ctrl + F9 | *79* | Alt + Backspace |
| *8* | F8 | *34* | Ctrl + F10 | *80* | Ctrl + Page Up |
| *9* | F9 | *35* | Ctrl + F11 | *81* | Page Up |
| *10* | F10 | *36* | Ctrl + F12 | *82* | Page Down |
| *11* | F11 or Ctrl + S | *37* | Ctrl + Shift + F1 | *83* | Ctrl + Page Down |
| *12* | F12 or ESC | *38* | Ctrl + Shift + F2 | *84* | Ctrl + G |
| *14* | Shift + F2 | *39* | Ctrl + Shift + F3 | *85* | Ctrl + R |
| *15* | Shift + F3 | *40* | Ctrl + Shift + F4 | *86* | Ctrl + P |
| *16* | Shift + F4 | *41* | Ctrl + Shift + F5 | *87* | Ctrl + B |
| *17* | Shift + F5 | *42* | Ctrl + Shift + F6 | *88* | Ctrl + K |
| *18* | Shift + F6 | *43* | Ctrl + Shift + F7 | *89* | Ctrl + T |
| *19* | Shift + F7 | *44* | Ctrl + Shift + F8 | *90* | Ctrl + Y |
| *20* | Shift + F8 | *45* | Ctrl + Shift + F9 | *91* | Ctrl + X |
| *21* | Shift + F9 | *46* | Ctrl + Shift + F10 | *92* | Ctrl + C |
| *22* | Ctrl + Shift + 0 | *47* | Ctrl + Shift + F11 | *93* | Ctrl + V |
| *23* | Shift + F11 | *48* | Ctrl + Shift + F12 | *94* | Shift + F10 |
| *24* | Shift + F12 | *70* | Ctrl + E | *97* | Ctrl + # |
| *25* | Ctrl + F1 | *71* | Ctrl + F | | |
Examples:
| *Keyword* | *Attributes* | |
| send_vkey | 8 | |
| send_vkey | Ctrl + Shift + F1 | |
| send_vkey | Ctrl + F7 | window=1 |
"""
vkey_id = str(vkey_id)
vkeys_array = ["ENTER", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
None, "SHIFT+F2", "SHIFT+F3", "SHIFT+F4", "SHIFT+F5", "SHIFT+F6", "SHIFT+F7", "SHIFT+F8",
"SHIFT+F9", "CTRL+SHIFT+0", "SHIFT+F11", "SHIFT+F12", "CTRL+F1", "CTRL+F2", "CTRL+F3", "CTRL+F4",
"CTRL+F5", "CTRL+F6", "CTRL+F7", "CTRL+F8", "CTRL+F9", "CTRL+F10", "CTRL+F11", "CTRL+F12",
"CTRL+SHIFT+F1", "CTRL+SHIFT+F2", "CTRL+SHIFT+F3", "CTRL+SHIFT+F4", "CTRL+SHIFT+F5",
"CTRL+SHIFT+F6", "CTRL+SHIFT+F7", "CTRL+SHIFT+F8", "CTRL+SHIFT+F9", "CTRL+SHIFT+F10",
"CTRL+SHIFT+F11", "CTRL+SHIFT+F12", None, None, None, None, None, None, None, None, None, None,
None, None, None, None, None, None, None, None, None, None, None, "CTRL+E", "CTRL+F", "CTRL+A",
"CTRL+D", "CTRL+N", "CTRL+O", "SHIFT+DEL", "CTRL+INS", "SHIFT+INS", "ALT+BACKSPACE",
"CTRL+PAGEUP", "PAGEUP",
"PAGEDOWN", "CTRL+PAGEDOWN", "CTRL+G", "CTRL+R", "CTRL+P", "CTRL+B", "CTRL+K", "CTRL+T",
"CTRL+Y",
"CTRL+X", "CTRL+C", "CTRL+V", "SHIFT+F10", None, None, "CTRL+#"]
# If a key combi is given, replace vkey_id by correct id based on given combination
if not vkey_id.isdigit():
search_comb = vkey_id.upper()
search_comb = search_comb.replace(" ", "")
search_comb = search_comb.replace("CONTROL", "CTRL")
search_comb = search_comb.replace("DELETE", "DEL")
search_comb = search_comb.replace("INSERT", "INS")
try:
vkey_id = vkeys_array.index(search_comb)
except ValueError:
if search_comb == "CTRL+S":
vkey_id = 11
elif search_comb == "ESC":
vkey_id = 12
else:
message = "Cannot find given Vkey, provide a valid Vkey number or combination"
raise ValueError(message)
try:
self.session.findById("wnd[% s]" % window).sendVKey(vkey_id)
except com_error:
self.take_screenshot()
message = "Cannot send Vkey to given window, is window wnd[% s] actually open?" % window
raise ValueError(message)
time.sleep(self.explicit_wait)
def set_cell_value(self, table_id, row_num, col_id, text):
"""Sets the cell value for the specified cell of a GridView 'table_id' which is contained within a shell object.
Use the Scripting tracker recorder to find the 'col_id' of the cell to set.
"""
self.element_should_be_present(table_id)
try:
self.session.findById(table_id).modifyCell(row_num, col_id, text)
logger.info("Typing text '%s' into cell '%s', '%s'" % (text, row_num, col_id))
time.sleep(self.explicit_wait)
except com_error:
self.take_screenshot()
message = "Cannot type text '%s' into cell '%s', '%s'" % (text, row_num, col_id)
raise ValueError(message)
def set_explicit_wait(self, speed):
"""Sets the delay time that is waited after each SapGui keyword.
The value can be given as a number that is considered to be seconds or as a human-readable string like 1 second
or 700 ms.
This functionality is designed to be used for demonstration and debugging purposes. It is not advised to use
this keyword to wait for an element to appear or function to finish.
*Possible time formats:*
| miliseconds | milliseconds, millisecond, millis, ms |
| seconds | seconds, second, secs, sec, s |
| minutes | minutes, minute, mins, min, m |
*Example:*
| *Keyword* | *Attributes* |
| Set explicit wait | 1 |
| Set explicit wait | 3 seconds |
| Set explicit wait | 500 ms |
"""
speed = str(speed)
if not speed.isdigit():
speed_elements = speed.split()
if not speed_elements[0].isdigit():
message = "The given speed %s doesn't begin with an numeric value, but it should" % speed
raise ValueError(message)
else:
speed_elements[0] = float(speed_elements[0])
speed_elements[1] = speed_elements[1].lower()
if (speed_elements[1] == "seconds"
or speed_elements[1] == "second"
or speed_elements[1] == "s"
or speed_elements[1] == "secs"
or speed_elements[1] == "sec"):
self.explicit_wait = speed_elements[0]
elif (speed_elements[1] == "minutes"
or speed_elements[1] == "minute"
or speed_elements[1] == "mins"
or speed_elements[1] == "min"
or speed_elements[1] == "m"):
self.explicit_wait = speed_elements[0] * 60
elif (speed_elements[1] == "milliseconds"
or speed_elements[1] == "millisecond"
or speed_elements[1] == "millis"
or speed_elements[1] == "ms"):
self.explicit_wait = speed_elements[0] / 1000
else:
self.take_screenshot()
message = "%s is a unknown time format" % speed_elements[1]
raise ValueError(message)
else:
# No timeformat given, so time is expected to be given in seconds
self.explicit_wait = float(speed)
def set_focus(self, element_id):
"""Sets the focus to the given element.
"""
element_type = self.get_element_type(element_id)
if element_type != "GuiStatusPane":
self.session.findById(element_id).setFocus()
time.sleep(self.explicit_wait)
def take_screenshot(self, screenshot_name="sap-screenshot"):
"""Takes a screenshot, only if 'screenshots on error' has been enabled,
either at import of with keyword `enable screenshots on error`.
This keyword uses Robots' internal `Screenshot` library.
"""
if self.take_screenshots == True:
self.screenshot.take_screenshot(screenshot_name)
def unselect_checkbox(self, element_id):
"""Removes selection of checkbox identified by locator.
Does nothing if the checkbox is not selected.
"""
element_type = self.get_element_type(element_id)
if element_type == "GuiCheckBox":
self.session.findById(element_id).selected = False
else:
self.take_screenshot()
message = "Cannot use keyword 'unselect checkbox' for element type '%s'" % element_type
raise ValueError(message)
time.sleep(self.explicit_wait) | /robotframework-sapguilibrary-1.1.tar.gz/robotframework-sapguilibrary-1.1/SapGuiLibrary/SapGuiLibrary.py | 0.707304 | 0.35987 | SapGuiLibrary.py | pypi |
from typing import Optional
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary import SeleniumLibrary
from saucebindings.options import SauceOptions
from saucebindings.session import SauceSession
from robot.utils import is_truthy
class SauceLabs(LibraryComponent):
def __init__(self: "SauceLabs",
ctx: SeleniumLibrary,
automatic_wait: bool = True,
timeout: str = "30 seconds",
error_on_timeout: bool = True,
automatic_injection: bool = True) -> None:
LibraryComponent.__init__(self, ctx)
self.sauce_options = SauceOptions()
self.session = SauceSession()
self.sauce_data_centre = "us-west"
self.automatic_wait = is_truthy(automatic_wait)
self.automatic_injection = is_truthy(automatic_injection)
self.error_on_timeout = is_truthy(error_on_timeout)
self.timeout = timeout # type: ignore
"""Testing/assertion keywords."""
@keyword
def browser_version_should_be_latest(self):
assert self.session.options.browser_version == "latest"
@keyword
def browser_should_be_chrome(self):
assert self.session.options.browser_name == "chrome"
@keyword
def browser_should_be_firefox(self):
assert self.session.options.browser_name == "firefox"
@keyword
def platform_version_should_be_windows_10(self):
assert self.session.options.platform_name == "Windows 10"
@keyword
def browser_should_be_safari(self):
assert self.session.options.browser_name == "safari"
"""Keywords"""
@keyword
def start_sauce_browser(self,
url: Optional[str] = None,
alias: Optional[str] = None,
browserName: Optional[str] = 'chrome',
browserVersion: Optional[str] = None,
platformName: Optional[str] = None,
**kwargs):
"""Start a browser on Sauce. Defaults to starting the latest Chrome on Windows 10"""
index = self.drivers.get_index(alias)
if index:
self.info(f"Using existing browser from index {index}.")
self.switch_browser(alias)
if url:
self.go_to(url)
return index
if not any([browserVersion, platformName]):
self.options = SauceOptions(**kwargs)
else:
self.options = SauceOptions(browserName=browserName, browserVersion=browserVersion, platformName=platformName, **kwargs)
self.session = SauceSession(self.options, data_center=self.sauce_data_centre)
driver = self.session.start()
index = self.ctx.register_driver(driver, alias)
if url:
driver.get(url)
return index
@keyword
def stop_sauce_session(self, passed: bool):
if self.session:
self.session.stop(passed)
self.ctx.close_browser()
@keyword
def start_latest_chrome_on_sauce(self,
url: Optional[str] = None,
alias: Optional[str] = None):
index = self.drivers.get_index(alias)
if index:
self.info(f"Using existing browser from index {index}.")
self.switch_browser(alias)
if url:
self.go_to(url)
return index
self.options = SauceOptions('chrome')
self.session = SauceSession(self.options, data_center=self.sauce_data_centre)
driver = self.session.start()
index = self.ctx.register_driver(driver, alias)
if url:
driver.get(url)
return index
@keyword
def start_latest_firefox_on_sauce(self,
url: Optional[str] = None,
alias: Optional[str] = None):
index = self.drivers.get_index(alias)
if index:
self.info(f"Using existing browser from index {index}.")
self.switch_browser(alias)
if url:
self.go_to(url)
return index
self.options = SauceOptions('firefox')
self.session = SauceSession(self.options, data_center=self.sauce_data_centre)
driver = self.session.start()
index = self.ctx.register_driver(driver, alias)
if url:
driver.get(url)
return index
@keyword
def set_data_centre(self, data_centre: str="us-west-1"):
self.sauce_data_centre = data_centre | /robotframework-saucelabs-0.2.2.tar.gz/robotframework-saucelabs-0.2.2/src/SauceLabs/plugin.py | 0.842831 | 0.263226 | plugin.py | pypi |
import scp
from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn
class SCPLibrary(object):
"""Robot Framework Secure Copy (SCP) test library.
This library uses the current connection established via default
SSHLibrary (robotframework-sshlibrary). Because of this, and unlike
another SCPLibrary (robotframework-scplibrary), there are no keyword
clashes and it can be used alongside SSHLibrary.
Only works with the Python version of SSHLibrary.
SSHLibrary uses paramiko, and this SCPLibrary uses the 'scp' wrapper.
= Connection =
Establishing and closing the connection is done via the SSHLibrary.
= File transfer =
Files can be downloaded from a remote machine using the `Download File`
keyword. Reversely, files can be uploaded to a remote machine using the
`Upload File` keyword.
An existing connection must have been established via the SSHLibrary
before calling any of these keywords.
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def __init__(self):
self.sshlibrary = BuiltIn().get_library_instance('SSHLibrary')
def _get_transport(self):
"""Gets the transport connection from the current SSH connection."""
logger.debug("Getting current transport from SSHLibrary")
try:
transport = self.sshlibrary.current.client.get_transport()
except AttributeError:
raise AssertionError("Only works with the Python SSHLibrary")
else:
if not transport:
raise AssertionError("Connection not open")
return transport
def download_file(
self, remote_source_path, local_dest_path, recursive=False):
"""Download a remote file using SCP over the current SSH connection.
This is basically a wrapper around 'scp.SCPClient.get', as such
multiple files (i.e. a list of files) can be passed in.
The remote path is evaluated on the host and may contain wildcards or
environmental variables (from the *remote* host).
Recursive must be 'True' for directories.
Examples:
| Download File | /home/remote/foo.tar.gz | /tmp/foo.tar.gz |
| Download File | /home/remote/*.tar.gz | /tmp/ |
| Download File | /home/remote/ | /tmp/bar/ | recursive=True |
"""
copy_pipe = scp.SCPClient(self._get_transport())
logger.debug("Transferring {} (remote) to {} (local)".format(
remote_source_path, local_dest_path))
try:
copy_pipe.get(
remote_source_path,
local_dest_path,
recursive=bool(recursive))
except scp.SCPException as e:
raise RuntimeError(e)
finally:
if copy_pipe:
copy_pipe.close()
def upload_file(self, local_source_files, remote_dest_path, recursive=False):
"""Upload a local file using SCP over the current SSH connection.
This is basically a wrapper around 'scp.SCPClient.put', as such
multiple files (i.e. a list of files) can be passed in.
Recursive must be 'True' for directories.
Examples:
| Upload File | /home/local/foo.tar.gz | /tmp/foo.tar.gz |
| Upload File | /home/local/ | /tmp/ | recursive=True |
"""
copy_pipe = scp.SCPClient(self._get_transport())
logger.debug("Transferring {} (local) to {} (remote)".format(
local_source_files, remote_dest_path))
try:
copy_pipe.put(
local_source_files,
remote_dest_path,
recursive=bool(recursive))
except scp.SCPException as e:
raise RuntimeError(e)
finally:
if copy_pipe:
copy_pipe.close() | /robotframework-scpcompat-0.1.0.tar.gz/robotframework-scpcompat-0.1.0/SCPLibrary/library.py | 0.736306 | 0.327803 | library.py | pypi |
from paramiko import SSHClient
from paramiko.client import AutoAddPolicy
from scp import SCPClient
from six import string_types
try:
from _version import __version__, __revision__
except ImportError:
__version__ = "UNKNOWN"
__revision__ = "UNKNOWN"
class SCPNotConnectedError(RuntimeError):
ROBOT_EXIT_ON_FAILURE = False
class SCPLibrary(object):
"""Robot Framework test library for Secure Copy (SCP).
This library can be used to copy files to and from a remote machine using Secure Copy (SCP). It uses the
Paramiko SSH Python library (just like robotframework-sshlibrary) and an SCP wrapper ('scp' by James Bardin).
The library does not currently support Jython or IronPython at this time.
== Table of contents ==
- `Connection`
- `File transfer`
= Connection =
Before files can be transferred a connection to remote machine must first be made. A connection can be made with the
`Open Connection` keyword. Both normal username/password authentication and asymmetric key-pair authentication may
be used.
Connections should be closed using the `Close Connection` when they are no longer in use.
= File transfer =
Files and directories can be uploaded to the remote machine using the `Put File` or `Put Directory` keywords or
downloaded to the local machine using the `Get File` keyword.
A connection must be made using the `Open Connection` keyword before file transfers may be made.
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = __version__
def __init__(self):
self.ssh = None
self.scp_client = None
def open_connection(self, hostname, port='22', username=None, password=None, key_filename=None):
"""Opens a new SCP connection to the given host.
The default port used is `22`:
| Open Connection | host.tylercrumpton.com |
A different port may be optionally given by using the `port` argument:
| Open Connection | host.tylercrumpton.com | port=4242 |
Authentication may be done using a username and password:
| Open Connection | host.tylercrumpton.com | username=tyler | password=iamateapot |
Or by using a private keyfile:
| Open Connection | host.tylercrumpton.com | username=tyler | key_filename=myprivatekey |
"""
try:
port = int(port)
except:
raise ValueError('Port must be a valid number.')
self.ssh = SSHClient()
self.ssh.set_missing_host_key_policy(AutoAddPolicy())
self.ssh.connect(hostname, port=port, username=username, password=password, key_filename=key_filename)
self.scp_client = SCPClient(self.ssh.get_transport())
def close_connection(self):
"""Closes the SCP connection.
Example:
| Open Connection | host.tylercrumpton.com | username=tyler | password=iamateapot |
| Get File | tea.txt | /mytea/newtea.txt |
| Close Connection |
"""
if self.scp_client is not None:
self.scp_client.close()
self.scp_client = None
if self.ssh is not None:
self.ssh.close()
self.ssh = None
def put_file(self, local_filepath, remote_filepath):
"""Uploads a file to the remote machine from the local machine.
Note: A connection to the remote machine must be made first using the `Open Connection` keyword.
Examples:
| Put File | mytea.txt | /home/tyler/tea.txt |
| Put File | mytea.txt | /home/tyler/ |
"""
if self.scp_client is None:
raise SCPNotConnectedError("An SCPLibrary connection must be created first using the 'Open Connection' keyword.")
self.scp_client.put(local_filepath, remote_filepath, recursive=False)
def put_directory(self, local_directory, remote_filepath):
"""Uploads a directory to the remote machine from the local machine.
Note: A connection to the remote machine must be made first using the `Open Connection` keyword.
Examples:
| Put File | mytea_dir | /home/tyler/newtea_dir |
| Put File | mytea.txt | /home/tyler/ |
"""
if self.scp_client is None:
raise SCPNotConnectedError("An SCPLibrary connection must be created first using the 'Open Connection' keyword.")
self.scp_client.put(local_directory, remote_filepath, recursive=True)
def get_file(self, remote_filepath, local_filepath, recursive=False):
"""Downloads a file from the remote machine to the local machine.
`remote_filepath` determines the path to retrieve from remote host. Shell wildcards and environment variables
on the remote machine may be used.
Setting `recursive` to True will transfer files and directories recursively.
Note: A connection to the remote machine must be made first using the `Open Connection` keyword.
Example:
| Get File | /home/tyler/tea.txt | sametea.txt | |
| Get File | /home/tyler/*.txt | myteas/ | |
| Get File | /home/tyler/ | mytylerdir/ | recursive=True |
"""
if self.scp_client is None:
raise SCPNotConnectedError("An SCPLibrary connection must be created first using the 'Open Connection' keyword.")
self.scp_client.get(remote_filepath, local_filepath, recursive=self._is_true_arg(recursive))
@staticmethod
def _is_true_arg(arg):
if isinstance(arg, string_types):
return arg.lower() not in ['false', 'no']
return bool(arg) | /robotframework-scplibrary-1.2.0.tar.gz/robotframework-scplibrary-1.2.0/SCPLibrary/library.py | 0.764452 | 0.257888 | library.py | pypi |
from .version import VERSION
from .client import Client
from .videoclient import VideoClient
from .gifclient import GifClient
__version__ = VERSION
class ScreenCapLibrary:
""" Test Library for taking screenshots on the machine where tests are run.
Note that successfully taking screenshots requires tests to be run with
a physical or virtual display.
= Usage =
How screenshots are taken when using Python depends on the chosen format.
There are several supported formats: PNG, JPG/JPEG, GIF and WebP. If no format
is specified the screenshots will have the PNG format.
For taking screenshots the following modules are used:
- [https://python-mss.readthedocs.io| mss ] a fast cross-platform module used for taking screenshots and saving
them in PNG format.
- [https://pillow.readthedocs.io | Pillow] used on top of ``mss`` in order to save the screenshots in JPG/JPEG/WebP format.
- [http://pygtk.org/ | PyGTK] is an alternative to ``mss`` for taking screenshots when using VNC.
For video recording, [https://github.com/skvark/opencv-python/blob/master/README.md | OpenCV-Python] is used and
the output file is in WebM format.
= 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.
= Time format =
All delays and time intervals can be given as numbers considered seconds
(e.g. ``0.5`` or ``42``) or in Robot Framework's time syntax
(e.g. ``1.5 seconds`` or ``1 min 30 s``). For more information about
the time syntax see the
[http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#time-format|Robot Framework User Guide].
= 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``. Other strings are considered true regardless
their value, and other argument types are tested using the same
[http://docs.python.org/2/library/stdtypes.html#truth-value-testing|rules
as in Python].
True examples:
| `Take Partial Screenshot` | embed=True | # Strings are generally true. |
| `Take Partial Screenshot` | embed=yes | # Same as the above. |
| `Take Partial Screenshot` | embed=${TRUE} | # Python ``True`` is true. |
| `Take Partial Screenshot` | embed=${42} | # Numbers other than 0 are true. |
False examples:
| `Take Partial Screenshot` | embed=False | # String ``false`` is false. |
| `Take Partial Screenshot` | embed=no | # Also string ``no`` is false. |
| `Take Partial Screenshot` | embed=${EMPTY} | # Empty string is false. |
| `Take Partial Screenshot` | embed=${FALSE} | # Python ``False`` is false. |
"""
ROBOT_LIBRARY_VERSION = __version__
started_recordings = []
started_gifs = []
def __init__(self, screenshot_module=None, screenshot_directory=None, format='png', quality=50, delay=0,
display_cursor=False):
"""
``screenshot_module`` specifies the module or tool to use when taking screenshots using this library.
If no tool or module is specified, ``mss`` will be used by default. For running
on Linux with VNC, use ``PyGTK``.
To configure where screenshots are saved use ``screenshot_directory``. If no value is given,
screenshots are saved into same directory as the log file. The directory can also be set using
`Set Screenshot Directory` keyword.
``format`` specifies the format in which the screenshots will be saved.
Possible values are ``png``, ``jpeg``, ``jpg`` and ``webp``, case-insensitively.
If no value is given the format is set by default to ``png``.
``quality`` can take values in range [0, 100]. Value 0 is lowest quality,
while value 100 is maximum quality. The quality is directly proportional
with file size. Because PNG uses lossless compression its size
may be larger than the size of the JPG file. The default value is 50.
``delay`` specifies the waiting time before taking a screenshot. See
`Time format` section for more information. By default the delay is 0.
``display_cursor`` displays a cursor which copies the mouse
movements in order to perform an enhanced visualization of mouse
position. By default ``display_cursor`` is set to False. See
`Boolean arguments` section for more details.
``display_cursor`` is new in ScreenCapLibrary 1.5.0.
Examples (use only one of these):
| =Setting= | =Value= | =Value= |
| Library | Screenshot | |
| Library | Screenshot | PyGTK |
| Library | Screenshot | screenshot_directory=${TEMPDIR} |
| Library | Screenshot | format=jpg |
| Library | Screenshot | quality=0 |
"""
self.client = Client(
screenshot_module=screenshot_module,
screenshot_directory=screenshot_directory,
format=format,
quality=quality,
delay=delay,
display_cursor=display_cursor
)
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`.
"""
return self.client.set_screenshot_directory(path)
def take_screenshot(self, name='screenshot', format=None, quality=None, width='800px', delay=0,
monitor=1, save_to_disk=True):
"""Takes a screenshot in the specified format at library import and
embeds it into the log file (PNG by default).
Name of the file where the screenshot is stored is derived from the
given ``name``. If the ``name`` ends with extension ``.jpg``, ``.jpeg``,
``.png`` or ``.webp``, 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.
``format`` specifies the format in which the screenshot is saved. If
no format is provided the library import value will be used which is
``png`` by default. Can be either ``jpg``, ``jpeg``, ``png``, or ``webp``,
case insensitive.
``quality`` can take values in range [0, 100]. In case of JPEG format
it can drastically reduce the file size of the image.
``width`` specifies the size of the screenshot in the log file.
``delay`` specifies the waiting time before taking a screenshot. See
`Time format` section for more information. By default the delay is 0.
``monitor`` selects which monitor you want to capture. Use value 0 to capture all.
``save_to_disk`` specifies whether the image will be saved on the disk or only be available in the log file
Examples: (LOGDIR is determined automatically by the library)
| `Take Screenshot` | | | # LOGDIR/screenshot_1.png (index automatically incremented) |
| `Take Screenshot` | mypic | | # LOGDIR/mypic_1.png (index automatically incremented) |
| `Take Screenshot` | ${TEMPDIR}/mypic | | # /tmp/mypic_1.png (index automatically incremented) |
| `Take Screenshot` | pic.jpg | | # LOGDIR/pic.jpg (always uses this file) |
| `Take Screenshot` | images/login.jpg | 300px | # Specify both name and width. |
| `Take Screenshot` | width=550px | | # Specify only width. |
| `Take Screenshot` | format=jpg | quality=15 | # Specify both image format and quality |
The path where the screenshot is saved is returned.
"""
return self.client.take_screenshot(name, format, quality, width, delay, monitor, save_to_disk)
def start_gif_recording(self, name="screenshot", size_percentage=0.5,
embed=True, embed_width='800px', monitor=1, optimize=True):
"""
Starts the recording of a GIF in the background with the specified ``name``.
The recording can be stopped by calling the `Stop Gif Recording` keyword.
``name`` specifies the name by which the screenshot will be saved.
``size_percentage`` is used to reduce the size of the GIFs a resize of the
screen captures. It will specify how much this reduction is with respect to
screen resolution. By default this parameter is set to resize the images to
0.5 of the screen resolution.
``embed`` specifies if the screenshot should be embedded in the log file
or not. See `Boolean arguments` section for more details.
``embed_width`` specifies the size of the screenshot that is
embedded in the log file.
``monitor`` selects which monitor you want to capture. Use value 0 to capture all.
``optimize`` drastically reduces the size (and quality) of the gif file.
Examples:
| `Start Gif Recording` | | # Starts the GIF recording in background |
| `Sleep` | 10 seconds | # Here should be the actions that will be recorded |
| `Stop Gif Recording` | | # Will create the GIF containing the screen recording \
since `Start Gif Recording` was called. |
"""
if len(self.started_gifs) > 0:
raise Exception('A gif recording is already in progress!')
gif_client = GifClient(self.client.screenshot_module, self.client.screenshot_dir)
self.started_gifs.append(gif_client)
gif_client.start_gif_recording(name, size_percentage, embed, embed_width, monitor, optimize)
def stop_gif_recording(self, save_to_disk=True):
"""
Stops the GIF recording and generates the file. If ``embed`` argument was set to ``True`` the
GIF will be displayed in the log file. Furthermore, if the ``save_to_disk`` parameter is set to ``False``, the
video will be embedded and available in the log file only.
"""
if len(self.started_gifs) == 0:
raise Exception('No gif recordings are started!')
try:
return self.started_gifs.pop().stop_gif_recording(save_to_disk)
except RuntimeError as error:
del self.started_gifs[:]
raise error
def take_partial_screenshot(self, name='screenshot', format=None, quality=None,
left=0, top=0, width=700, height=300, embed=True, embed_width='800px', monitor=1, save_to_disk=True):
"""
Takes a partial screenshot in the specified format and dimensions at
library import and embeds it into the log file (PNG by default).
This keyword is similar with `Take Screenshot` but has some extra parameters listed below:.
``left`` specifies the cropping distance on the X axis from the left of the screen capture.
``top`` specifies the cropping distance on the Y axis from the top of the screen capture.
``width`` specifies the width of a screen capture when using partial screen captures.
``height`` specifies the height of a screen capture when using partial screen captures.
``embed`` specifies if the screenshot should be embedded in the log file or not. See
`Boolean arguments` section for more details.
``embed_width`` specifies the size of the screenshot that is embedded in the log file.
``monitor`` selects which monitor you want to capture. Use value 0 to capture all.
``save_to_disk`` specifies whether the image will be saved on the disk or only be available in the log file
"""
return self.client.take_partial_screenshot(name, format, quality,
left, top, width, height, embed, embed_width, monitor, save_to_disk)
def take_screenshot_without_embedding(self, name="screenshot", format=None, quality=None, delay=0, monitor=1):
"""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.
"""
return self.client.take_screenshot_without_embedding(name, format, quality, delay, monitor)
def take_multiple_screenshots(self, name="screenshot", format=None, quality=None,
screenshot_number=2, delay_time=0, monitor=1):
"""Takes the specified number of screenshots in the specified format
at library import and embeds it into the log file (PNG by default).
This keyword is similar with `Take Screenshot` but has some extra
parameters listed below:
``screenshot_number`` specifies the number of screenshots to be taken.
By default this number is 2.
``delay_time`` specifies the waiting time before taking another
screenshot. See `Time format` section for more information. By
default the delay time is 0.
"""
return self.client.take_multiple_screenshots(name, format, quality, screenshot_number, delay_time, monitor)
def start_video_recording(self, alias=None, name="recording", fps=None, size_percentage=1, embed=True, embed_width='800px', monitor=1):
"""Starts the recording of a video in the background with the specified ``name``.
The recording can be stopped by calling the `Stop Video Recording` keyword.
``alias`` helps identify the recording, if you want to close a specific one.
``name`` specifies the name by which the record will be saved.
``fps`` specifies the frame rate at which the video is displayed. If is set to ``None`` it will be
automatically computed based on the performance of the system.
``size_percentage`` is used to reduce the size of the screen recordings. It will specify
how much this reduction is with respect to screen resolution. By default this parameter
is set to full screen resolution i.e. 1.
``embed`` specifies if the record should be embedded in the log file
or not. See `Boolean arguments` section for more details.
``embed_width`` specifies the size of the video record that is
embedded in the log file.
``monitor`` selects which monitor you want to capture. Use value 0 to capture all.
Examples:
| `Start Video Recording` | | # Starts the video recording in background |
| `Sleep` | 10 seconds | # Here should be the actions that will be recorded |
| `Stop Video Recording` | | # Will create the video containing the screen recording \
since `Start Video Recording` was called. |
*Note:* Be aware that during recording the number of the collected frames are dependent on the
performance of your system. Check different values for ``fps`` to find optimal results. (e.g.
for a 15 seconds recording the output might be a 2 second video with 30 fps).
"""
if size_percentage <= 0 or size_percentage > 1:
raise Exception('Size percentage should take values > than 0 and <= to 1.')
video_client = VideoClient(self.client.screenshot_module, self.client.screenshot_dir, fps, self.client.cursor)
self.started_recordings.append(video_client)
video_client.start_video_recording(alias, name, size_percentage, embed, embed_width, monitor)
def stop_all_video_recordings(self, save_to_disk=True):
"""Stops all the video recordings and generates the files in WebM format. If ``embed`` argument
was set to ``True`` the videos will be displayed in the log file.
The paths where the videos are saved are returned.
"""
paths = []
if len(self.started_recordings) == 0:
raise Exception('No video recordings are started!')
for recording in self.started_recordings:
recording.stop_video_recording(save_to_disk)
paths.append(recording.path)
del self.started_recordings[:]
return paths
def stop_video_recording(self, alias=None, save_to_disk=True):
"""Stops the video recording corresponding to the given ``alias`` and generates the file in WebM format. If no
``alias`` is specified, the last opened recording will be closed. If there are more recordings with the same
alias all of them will be closed. If ``embed`` argument was set to
``True`` the video will be displayed in the log file.
Furthermore, if the ``save_to_disk`` parameter is set to ``False``, the video will be embedded and available in
the log file only.
The path where the video is saved is returned.
"""
if len(self.started_recordings) == 0:
raise Exception('No video recordings are started!')
try:
if alias:
aliases = [x.alias for x in self.started_recordings]
paths = []
if alias not in aliases:
raise Exception('No video recording with alias `%s` found!' % alias)
copy_list = self.started_recordings[:]
for recording in copy_list:
if recording.alias == alias:
self.started_recordings.remove(recording)
recording.stop_video_recording(save_to_disk)
paths.append(recording.path)
return paths if len(paths) > 1 else paths[0]
else:
return self.started_recordings.pop().stop_video_recording(save_to_disk)
except RuntimeError as error:
del self.started_recordings[:]
raise error
def pause_video_recording(self, alias=None):
"""Temporarily stops the video recording corresponding to the given ``alias``. If no ``alias`` is specified the
last started recording would be paused. If there are more recordings with the same
alias all of them will be paused.
"""
if len(self.started_recordings) == 0:
raise Exception('No video recordings were started! Please start a video recording and then pause it!')
try:
if alias:
aliases = [x.alias for x in self.started_recordings]
if alias not in aliases:
raise Exception('No video recording with alias `%s` found!' % alias)
for recording in self.started_recordings:
if recording.alias == alias:
recording.pause_video_recording()
else:
self.started_recordings[-1].pause_video_recording()
except RuntimeError as error:
raise error
def resume_video_recording(self, alias=None):
"""Resumes the previous paused video recording corresponding to the given ``alias``. If no ``alias`` is
specified the last paused recording would be resumed. If there are more recordings with the same alias all of them
will be resumed.
"""
if len(self.started_recordings) == 0:
raise Exception('No video recordings were started! Please start a video recording and then pause it!')
try:
if alias:
aliases = [x.alias for x in self.started_recordings]
if alias not in aliases:
raise Exception('No video recording with alias `%s` found!' % alias)
for recording in self.started_recordings:
if recording.alias == alias:
recording.resume_video_recording()
else:
self.started_recordings[-1].resume_video_recording()
except RuntimeError as error:
raise error | /robotframework-screencaplibrary-1.6.0rc1.tar.gz/robotframework-screencaplibrary-1.6.0rc1/src/ScreenCapLibrary/library.py | 0.869853 | 0.635081 | library.py | pypi |
import os
import cv2
import numpy as np
cursor_x_list = [0, 8, 6, 14, 12, 4, 2, 0]
cursor_y_list = [0, 2, 4, 12, 14, 6, 8, 0]
def _norm_path(path):
if not path:
return path
return os.path.normpath(path.replace('/', os.sep))
def _compression_value_conversion(value):
"""
PNG compression values are within range [0, 9]. This value must
be mapped to a [0-100] interval.
"""
try:
if int(value) < 0 or int(value) > 100:
raise RuntimeError("Quality argument must be of between 0 and 100.")
return 0 if int(value) == 100 else int(9 - (int(value) / 11))
except ValueError:
raise RuntimeError("Quality argument must be of type integer.")
def _pil_quality_conversion(value):
"""
The quality in Pillow is between [1, 95] and must be converted to
a [0-100] interval.
"""
try:
if int(value) < 0 or int(value) > 100:
raise RuntimeError("Quality argument must be of between 0 and 100.")
if int(value) < 1:
return 1
elif int(value) >= 95:
return 95
return int(value)
except ValueError:
raise RuntimeError("The image quality argument must be of type integer.")
def resize_array(width, height, numpy_array, size_percentage):
resized_array = cv2.resize(numpy_array, dsize=(int(width * size_percentage), int(height * size_percentage)),
interpolation=cv2.INTER_AREA) \
if size_percentage != 1 else numpy_array
return resized_array
def draw_cursor(frame, mouse_x, mouse_y):
cursor_x = [x + mouse_x for x in cursor_x_list]
cursor_y = [y + mouse_y for y in cursor_y_list]
cursor_points = list(zip(cursor_x, cursor_y))
cursor_points = np.array(cursor_points, 'int32')
cv2.fillPoly(frame, [cursor_points], color=[0, 255, 255])
def is_pygtk(screenshot_module):
return screenshot_module and screenshot_module.lower() == 'pygtk'
class suppress_stderr(object):
def __init__(self):
# Open a null file
self.null_fd = os.open(os.devnull, os.O_RDWR)
# Save the actual stderr (2) file descriptor.
self.save_fd = os.dup(2)
def __enter__(self):
# Assign the null pointer to stderr.
os.dup2(self.null_fd, 2)
def __exit__(self, *_):
# Re-assign the real stderr back to (2)
os.dup2(self.save_fd, 2)
# Close all file descriptors
os.close(self.null_fd)
os.close(self.save_fd) | /robotframework-screencaplibrary-1.6.0rc1.tar.gz/robotframework-screencaplibrary-1.6.0rc1/src/ScreenCapLibrary/utils.py | 0.483161 | 0.294158 | utils.py | pypi |
from SeleniumLibrary.base import LibraryComponent, keyword
from selenium.webdriver.common.action_chains import ActionChains
class SeleniumMouseExtensions(LibraryComponent):
def __init__(self, ctx):
LibraryComponent.__init__(self, ctx)
@keyword
def mouse_down_with_offset(self, locator, xoffset, yoffset):
"""Simulates pressing the left mouse button on the element ``locator`` with the specified offset.
See the `Locating elements` section for details about the locator
syntax.
Offsets are relative to the top-left corner of the element.
Args:
locator: The WebElement to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
The element is pressed without releasing the mouse button.
See also the more specific keywords `Mouse Down On Image` and
`Mouse Down On Link`.
"""
self.info("Simulating Mouse Down on element '%s' with offset (%s, %s)." % (locator, xoffset, yoffset))
element = self.find_element(locator)
action = ActionChains(self.driver)
action.move_to_element_with_offset(element, int(xoffset), int(yoffset))
action.click_and_hold().perform()
@keyword
def mouse_move_to_element_with_offset(self, locator, xoffset, yoffset):
"""Simulates moving the mouse cursor to the element ``locator`` with the specified offset.
See the `Locating elements` section for details about the locator
syntax.
Move the mouse by an offset of the specified element.
Offsets are relative to the top-left corner of the element.
Args:
locator: The WebElement to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.info("Simulating Mouse Move to element '%s' with offset (%s, %s)." % (locator, xoffset, yoffset))
element = self.find_element(locator)
action = ActionChains(self.driver)
action.move_to_element_with_offset(element, xoffset, yoffset).perform()
@keyword
def mouse_move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to, as a positive or negative integer.
yoffset: Y offset to move to, as a positive or negative integer.
"""
self.info("Simulating Mouse Move By Offset ({0}, {1})".format(xoffset, yoffset))
action = ActionChains(self.driver)
action.move_by_offset(int(xoffset), int(yoffset)).perform()
@keyword
def mouse_up(self, locator=None):
"""Simulates releasing the left mouse button on the element ``locator``.
See the `Locating elements` section for details about the locator
syntax.
If locator is not given the mouse is released on current position.
"""
if locator:
self.info("Simulating Mouse Up on element '%s'." % locator)
element = self.find_element(locator)
ActionChains(self.driver).release(element).perform()
else:
self.info("Simulating Mouse Up.")
ActionChains(self.driver).release().perform() | /robotframework_selenium_mouseextensions-0.1-py3-none-any.whl/SeleniumMouseExtensions/MouseExtensions.py | 0.873781 | 0.356139 | MouseExtensions.py | pypi |
import os
from keywords import *
from version import VERSION
from utils import LibraryListener
__version__ = VERSION
class Selenium2Library(
_LoggingKeywords,
_RunOnFailureKeywords,
_BrowserManagementKeywords,
_ElementKeywords,
_TableElementKeywords,
_FormElementKeywords,
_SelectElementKeywords,
_JavaScriptKeywords,
_CookieKeywords,
_ScreenshotKeywords,
_WaitingKeywords,
_AlertKeywords
):
"""Selenium2Library is a web testing library for Robot Framework.
This document is about using Selenium2Library. For information about
installation, support, and more please visit the
[https://github.com/robotframework/Selenium2Library|project page].
Selenium2Library uses the Selenium 2 (WebDriver) libraries internally to control a web browser.
See http://seleniumhq.org/docs/03_webdriver.html for more information on Selenium 2
and WebDriver.
Selenium2Library runs tests in a real browser instance. It should work in
most modern browsers and can be used with both Python and Jython interpreters.
= Before running tests =
Prior to running test cases using Selenium2Library, Selenium2Library must be
imported into your Robot test suite (see `importing` section), and the
`Open Browser` keyword must be used to open a browser to the desired location.
*--- Note important change starting with Version 1.7.0 release ---*
= Locating or specifying elements =
All keywords in Selenium2Library that need to find an element on the page
take an argument, either a `locator` or now a `webelement`. `locator`
is a string that describes how to locate an element using a syntax
specifying different location strategies. `webelement` is a variable that
holds a WebElement instance, which is a representation of the element.
*Using locators*
---------------
By default, when a locator value is provided, it is matched against the
key attributes of the particular element type. For example, `id` and
`name` are key attributes to all elements, and locating elements is easy
using just the `id` as a `locator`. For example:
| Click Element my_element
It is also possible to specify the approach Selenium2Library should take
to find an element by specifying a lookup strategy with a locator
prefix. Supported strategies are:
| *Strategy* | *Example* | *Description* |
| identifier | Click Element `|` identifier=my_element | Matches by @id or @name attribute |
| id | Click Element `|` id=my_element | Matches by @id attribute |
| name | Click Element `|` name=my_element | Matches by @name attribute |
| xpath | Click Element `|` xpath=//div[@id='my_element'] | Matches with arbitrary XPath expression |
| dom | Click Element `|` dom=document.images[56] | Matches with arbitrary DOM express |
| link | Click Element `|` link=My Link | Matches anchor elements by their link text |
| partial link | Click Element `|` partial link=y Lin | Matches anchor elements by their partial link text |
| css | Click Element `|` css=div.my_class | Matches by CSS selector |
| class | Click Element `|` class=my_class | Matches by class name selector |
| jquery | Click Element `|` jquery=div.my_class | Matches by jQuery/sizzle selector |
| sizzle | Click Element `|` sizzle=div.my_class | Matches by jQuery/sizzle selector |
| tag | Click Element `|` tag=div | Matches by HTML tag name |
| default* | Click Link `|` default=page?a=b | Matches key attributes with value after first '=' |
* Explicitly specifying the default strategy is only necessary if locating
elements by matching key attributes is desired and an attribute value
contains a '='. The following would fail because it appears as if _page?a_
is the specified lookup strategy:
| Click Link page?a=b
This can be fixed by changing the locator to:
| Click Link default=page?a=b
*Using webelements*
------------------
Starting with version 1.7 of the Selenium2Library, one can pass an argument
that contains a WebElement instead of a string locator. To get a WebElement,
use the new `Get WebElements` keyword. For example:
| ${elem} = | Get WebElement | id=my_element |
| Click Element | ${elem} | |
Locating Tables, Table Rows, Columns, etc.
------------------------------------------
Table related keywords, such as `Table Should Contain`, work differently.
By default, when a table locator value is provided, it will search for
a table with the specified `id` attribute. For example:
| Table Should Contain my_table text
More complex table lookup strategies are also supported:
| *Strategy* | *Example* | *Description* |
| css | Table Should Contain `|` css=table.my_class `|` text | Matches by @id or @name attribute |
| xpath | Table Should Contain `|` xpath=//table/[@name="my_table"] `|` text | Matches by @id or @name attribute |
= Custom Locators =
If more complex lookups are required than what is provided through the default locators, custom lookup strategies can
be created. Using custom locators is a two part process. First, create a keyword that returns the WebElement
that should be acted on.
| Custom Locator Strategy | [Arguments] | ${browser} | ${criteria} | ${tag} | ${constraints} |
| | ${retVal}= | Execute Javascript | return window.document.getElementById('${criteria}'); |
| | [Return] | ${retVal} |
This keyword is a reimplementation of the basic functionality of the `id` locator where `${browser}` is a reference
to the WebDriver instance and `${criteria}` is the text of the locator (i.e. everything that comes after the = sign).
To use this locator it must first be registered with `Add Location Strategy`.
| Add Location Strategy custom Custom Locator Strategy
The first argument of `Add Location Strategy` specifies the name of the lookup strategy (which must be unique). After
registration of the lookup strategy, the usage is the same as other locators. See `Add Location Strategy` for more details.
= Timeouts =
There are several `Wait ...` keywords that take timeout as an
argument. All of these timeout arguments are optional. The timeout
used by all of them can be set globally using the
`Set Selenium Timeout` keyword. The same timeout also applies to
`Execute Async Javascript`.
All timeouts can be given as numbers considered seconds (e.g. 0.5 or 42)
or in Robot Framework's time syntax (e.g. '1.5 seconds' or '1 min 30 s').
For more information about the time syntax see the
[http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#time-format|Robot Framework User Guide].
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = VERSION
def __init__(self,
timeout=5.0,
implicit_wait=0.0,
run_on_failure='Capture Page Screenshot',
screenshot_root_directory=None
):
"""Selenium2Library can be imported with optional arguments.
`timeout` is the default timeout used to wait for all waiting actions.
It can be later set with `Set Selenium Timeout`.
'implicit_wait' is the implicit timeout that Selenium waits when
looking for elements.
It can be later set with `Set Selenium Implicit Wait`.
See `WebDriver: Advanced Usage`__ section of the SeleniumHQ documentation
for more information about WebDriver's implicit wait functionality.
__ http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-and-implicit-waits
`run_on_failure` specifies the name of a keyword (from any available
libraries) to execute when a Selenium2Library keyword fails. By default
`Capture Page Screenshot` will be used to take a screenshot of the current page.
Using the value "Nothing" will disable this feature altogether. See
`Register Keyword To Run On Failure` keyword for more information about this
functionality.
`screenshot_root_directory` specifies the default root directory that screenshots should be
stored in. If not provided the default directory will be where robotframework places its logfile.
Examples:
| Library `|` Selenium2Library `|` 15 | # Sets default timeout to 15 seconds |
| Library `|` Selenium2Library `|` 0 `|` 5 | # Sets default timeout to 0 seconds and default implicit_wait to 5 seconds |
| Library `|` Selenium2Library `|` 5 `|` run_on_failure=Log Source | # Sets default timeout to 5 seconds and runs `Log Source` on failure |
| Library `|` Selenium2Library `|` implicit_wait=5 `|` run_on_failure=Log Source | # Sets default implicit_wait to 5 seconds and runs `Log Source` on failure |
| Library `|` Selenium2Library `|` timeout=10 `|` run_on_failure=Nothing | # Sets default timeout to 10 seconds and does nothing on failure |
"""
for base in Selenium2Library.__bases__:
base.__init__(self)
self.screenshot_root_directory = screenshot_root_directory
self.set_selenium_timeout(timeout)
self.set_selenium_implicit_wait(implicit_wait)
self.register_keyword_to_run_on_failure(run_on_failure)
self.ROBOT_LIBRARY_LISTENER = LibraryListener() | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/__init__.py | 0.675551 | 0.528412 | __init__.py | pypi |
import time
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from keywordgroup import KeywordGroup
class _AlertKeywords(KeywordGroup):
__ACCEPT_ALERT = 'accept'
__DISMISS_ALERT = 'dismiss'
def __init__(self):
self._next_alert_dismiss_type = self.__ACCEPT_ALERT
# Public
def input_text_into_prompt(self, text):
"""Types the given `text` into alert box. """
try:
alert = self._wait_alert()
alert.send_keys(text)
except WebDriverException:
raise RuntimeError('There were no alerts')
def alert_should_be_present(self, text=''):
"""Verifies an alert is present and dismisses it.
If `text` is a non-empty string, then it is also verified that the
message of the alert equals to `text`.
Will fail if no alert is present. Note that following keywords
will fail unless the alert is dismissed by this
keyword or another like `Get Alert Message`.
"""
alert_text = self._handle_alert(self.__ACCEPT_ALERT)
if text and alert_text != text:
raise AssertionError("Alert text should have been "
"'%s' but was '%s'"
% (text, alert_text))
def choose_cancel_on_next_confirmation(self):
"""Cancel will be selected the next time `Confirm Action` is used."""
self._next_alert_dismiss_type = self.__DISMISS_ALERT
def choose_ok_on_next_confirmation(self):
"""Undo the effect of using keywords `Choose Cancel On Next Confirmation`. Note
that Selenium's overridden window.confirm() function will normally
automatically return true, as if the user had manually clicked OK, so
you shouldn't need to use this command unless for some reason you need
to change your mind prior to the next confirmation. After any
confirmation, Selenium will resume using the default behavior for
future confirmations, automatically returning true (OK) unless/until
you explicitly use `Choose Cancel On Next Confirmation` for each
confirmation.
Note that every time a confirmation comes up, you must
consume it by using a keywords such as `Get Alert Message`, or else
the following selenium operations will fail.
"""
self._next_alert_dismiss_type = self.__ACCEPT_ALERT
def confirm_action(self):
"""Dismisses currently shown confirmation dialog and returns it's message.
By default, this keyword chooses 'OK' option from the dialog. If
'Cancel' needs to be chosen, keyword `Choose Cancel On Next
Confirmation` must be called before the action that causes the
confirmation dialog to be shown.
Examples:
| Click Button | Send | # Shows a confirmation dialog |
| ${message}= | Confirm Action | # Chooses Ok |
| Should Be Equal | ${message} | Are your sure? |
| | | |
| Choose Cancel On Next Confirmation | | |
| Click Button | Send | # Shows a confirmation dialog |
| Confirm Action | | # Chooses Cancel |
"""
text = self._handle_alert(self._next_alert_dismiss_type)
self._next_alert_dismiss_type = self.__DISMISS_ALERT
return text
def get_alert_message(self, dismiss=True):
"""Returns the text of current JavaScript alert.
By default the current JavaScript alert will be dismissed.
This keyword will fail if no alert is present. Note that
following keywords will fail unless the alert is
dismissed by this keyword or another like `Get Alert Message`.
"""
if dismiss:
return self._handle_alert(self.__DISMISS_ALERT)
else:
return self._handle_alert()
def dismiss_alert(self, accept=True):
""" Returns true if alert was confirmed, false if it was dismissed
This keyword will fail if no alert is present. Note that
following keywords will fail unless the alert is
dismissed by this keyword or another like `Get Alert Message`.
"""
if accept:
return self._handle_alert(self.__ACCEPT_ALERT)
else:
return self._handle_alert()
def _handle_alert(self, dismiss_type=None):
"""Alert re-try for Chrome
Because Chrome has difficulties to handle alerts, like::
alert.text
alert.dismiss
This function creates a re-try funtionality to better support
alerts in Chrome.
"""
retry = 0
while retry < 4:
try:
return self._alert_worker(dismiss_type)
except WebDriverException:
time.sleep(0.2)
retry += 1
raise RuntimeError('There were no alerts')
def _alert_worker(self, dismiss_type=None):
alert = self._wait_alert()
text = ' '.join(alert.text.splitlines())
if dismiss_type == self.__DISMISS_ALERT:
alert.dismiss()
elif dismiss_type == self.__ACCEPT_ALERT:
alert.accept()
return text
def _wait_alert(self):
return WebDriverWait(self._current_browser(), 1).until(
EC.alert_is_present()) | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/keywords/_alert.py | 0.681515 | 0.190649 | _alert.py | pypi |
import os
from keywordgroup import KeywordGroup
class _JavaScriptKeywords(KeywordGroup):
# Public
def execute_javascript(self, *code):
"""Executes the given JavaScript code.
`code` may contain multiple lines of code and may be divided into
multiple cells in the test data. In that case, the parts are
catenated together without adding spaces.
If `code` is an absolute path to an existing file, the JavaScript
to execute will be read from that file. Forward slashes work as
a path separator on all operating systems.
The JavaScript executes in the context of the currently selected
frame or window as the body of an anonymous function. Use _window_ to
refer to the window of your application and _document_ to refer to the
document object of the current frame or window, e.g.
_document.getElementById('foo')_.
This keyword returns None unless there is a return statement in the
JavaScript. Return values are converted to the appropriate type in
Python, including WebElements.
Examples:
| Execute JavaScript | window.my_js_function('arg1', 'arg2') | |
| Execute JavaScript | ${CURDIR}/js_to_execute.js | |
| ${sum}= | Execute JavaScript | return 1 + 1; |
| Should Be Equal | ${sum} | ${2} |
"""
js = self._get_javascript_to_execute(''.join(code))
self._info("Executing JavaScript:\n%s" % js)
return self._current_browser().execute_script(js)
def execute_async_javascript(self, *code):
"""Executes asynchronous JavaScript code.
Similar to `Execute Javascript` except that scripts executed with
this keyword must explicitly signal they are finished by invoking the
provided callback. This callback is always injected into the executed
function as the last argument.
Scripts must complete within the script timeout or this keyword will
fail. See the `Timeouts` section for more information.
Examples:
| Execute Async JavaScript | var callback = arguments[arguments.length - 1]; | window.setTimeout(callback, 2000); |
| Execute Async JavaScript | ${CURDIR}/async_js_to_execute.js | |
| ${retval}= | Execute Async JavaScript | |
| ... | var callback = arguments[arguments.length - 1]; | |
| ... | function answer(){callback("text");}; | |
| ... | window.setTimeout(answer, 2000); | |
| Should Be Equal | ${retval} | text |
"""
js = self._get_javascript_to_execute(''.join(code))
self._info("Executing Asynchronous JavaScript:\n%s" % js)
return self._current_browser().execute_async_script(js)
# Private
def _get_javascript_to_execute(self, code):
codepath = code.replace('/', os.sep)
if not (os.path.isabs(codepath) and os.path.isfile(codepath)):
return code
self._html('Reading JavaScript from file <a href="file://%s">%s</a>.'
% (codepath.replace(os.sep, '/'), codepath))
codefile = open(codepath)
try:
return codefile.read().strip()
finally:
codefile.close() | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/keywords/_javascript.py | 0.716417 | 0.506469 | _javascript.py | pypi |
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.remote.webelement import WebElement
from Selenium2Library import utils
from Selenium2Library.locators import ElementFinder
from Selenium2Library.locators import CustomLocator
from keywordgroup import KeywordGroup
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
except NameError:
def isstr(s):
return isinstance(s, str)
class _ElementKeywords(KeywordGroup):
def __init__(self):
self._element_finder = ElementFinder()
# Public, get element(s)
def get_webelement(self, locator):
"""Returns the first WebElement matching the given locator.
See `introduction` for details about locating elements.
"""
return self._element_find(locator, True, True)
def get_webelements(self, locator):
"""Returns list of WebElement objects matching locator.
See `introduction` for details about locating elements.
"""
return self._element_find(locator, False, True)
# Public, element lookups
def current_frame_contains(self, text, loglevel='INFO'):
"""Verifies that current frame contains `text`.
See `Page Should Contain ` for explanation about `loglevel` argument.
"""
if not self._is_text_present(text):
self.log_source(loglevel)
raise AssertionError("Page should have contained text '%s' "
"but did not" % text)
self._info("Current page contains text '%s'." % text)
def current_frame_should_not_contain(self, text, loglevel='INFO'):
"""Verifies that current frame contains `text`.
See `Page Should Contain ` for explanation about `loglevel` argument.
"""
if self._is_text_present(text):
self.log_source(loglevel)
raise AssertionError("Page should not have contained text '%s' "
"but it did" % text)
self._info("Current page should not contain text '%s'." % text)
def element_should_contain(self, locator, expected, message=''):
"""Verifies element identified by `locator` contains text `expected`.
If you wish to assert an exact (not a substring) match on the text
of the element, use `Element Text Should Be`.
`message` can be used to override the default error message.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Verifying element '%s' contains text '%s'."
% (locator, expected))
actual = self._get_text(locator)
if not expected in actual:
if not message:
message = "Element '%s' should have contained text '%s' but "\
"its text was '%s'." % (locator, expected, actual)
raise AssertionError(message)
def element_should_not_contain(self, locator, expected, message=''):
"""Verifies element identified by `locator` does not contain text `expected`.
`message` can be used to override the default error message.
Key attributes for arbitrary elements are `id` and `name`. See
`Element Should Contain` for more details.
"""
self._info("Verifying element '%s' does not contain text '%s'."
% (locator, expected))
actual = self._get_text(locator)
if expected in actual:
if not message:
message = "Element '%s' should not contain text '%s' but " \
"it did." % (locator, expected)
raise AssertionError(message)
def frame_should_contain(self, locator, text, loglevel='INFO'):
"""Verifies frame identified by `locator` contains `text`.
See `Page Should Contain ` for explanation about `loglevel` argument.
Key attributes for frames are `id` and `name.` See `introduction` for
details about locating elements.
"""
if not self._frame_contains(locator, text):
self.log_source(loglevel)
raise AssertionError("Page should have contained text '%s' "
"but did not" % text)
self._info("Current page contains text '%s'." % text)
def page_should_contain(self, text, loglevel='INFO'):
"""Verifies that current page contains `text`.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Valid log levels are DEBUG, INFO (default), WARN, and NONE. If the
log level is NONE or below the current active log level the source
will not be logged.
"""
if not self._page_contains(text):
self.log_source(loglevel)
raise AssertionError("Page should have contained text '%s' "
"but did not" % text)
self._info("Current page contains text '%s'." % text)
def page_should_contain_element(self, locator, message='', loglevel='INFO'):
"""Verifies element identified by `locator` is found on the current page.
`message` can be used to override default error message.
See `Page Should Contain` for explanation about `loglevel` argument.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._page_should_contain_element(locator, None, message, loglevel)
def locator_should_match_x_times(self, locator, expected_locator_count, message='', loglevel='INFO'):
"""Verifies that the page contains the given number of elements located by the given `locator`.
See `introduction` for details about locating elements.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
"""
actual_locator_count = len(self._element_find(locator, False, False))
if int(actual_locator_count) != int(expected_locator_count):
if not message:
message = "Locator %s should have matched %s times but matched %s times"\
%(locator, expected_locator_count, actual_locator_count)
self.log_source(loglevel)
raise AssertionError(message)
self._info("Current page contains %s elements matching '%s'."
% (actual_locator_count, locator))
def page_should_not_contain(self, text, loglevel='INFO'):
"""Verifies the current page does not contain `text`.
See `Page Should Contain ` for explanation about `loglevel` argument.
"""
if self._page_contains(text):
self.log_source(loglevel)
raise AssertionError("Page should not have contained text '%s'" % text)
self._info("Current page does not contain text '%s'." % text)
def page_should_not_contain_element(self, locator, message='', loglevel='INFO'):
"""Verifies element identified by `locator` is not found on the current page.
`message` can be used to override the default error message.
See `Page Should Contain ` for explanation about `loglevel` argument.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._page_should_not_contain_element(locator, None, message, loglevel)
# Public, attributes
def assign_id_to_element(self, locator, id):
"""Assigns a temporary identifier to element specified by `locator`.
This is mainly useful if the locator is complicated/slow XPath expression.
Identifier expires when the page is reloaded.
Example:
| Assign ID to Element | xpath=//div[@id="first_div"] | my id |
| Page Should Contain Element | my id |
"""
self._info("Assigning temporary id '%s' to element '%s'" % (id, locator))
element = self._element_find(locator, True, True)
self._current_browser().execute_script("arguments[0].id = '%s';" % id, element)
def element_should_be_disabled(self, locator):
"""Verifies that element identified with `locator` is disabled.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
if self._is_enabled(locator):
raise AssertionError("Element '%s' is enabled." % (locator))
def element_should_be_enabled(self, locator):
"""Verifies that element identified with `locator` is enabled.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
if not self._is_enabled(locator):
raise AssertionError("Element '%s' is disabled." % (locator))
def element_should_be_visible(self, locator, message=''):
"""Verifies that the element identified by `locator` is visible.
Herein, visible means that the element is logically visible, not optically
visible in the current browser viewport. For example, an element that carries
display:none is not logically visible, so using this keyword on that element
would fail.
`message` can be used to override the default error message.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Verifying element '%s' is visible." % locator)
visible = self._is_visible(locator)
if not visible:
if not message:
message = "The element '%s' should be visible, but it "\
"is not." % locator
raise AssertionError(message)
def element_should_not_be_visible(self, locator, message=''):
"""Verifies that the element identified by `locator` is NOT visible.
This is the opposite of `Element Should Be Visible`.
`message` can be used to override the default error message.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Verifying element '%s' is not visible." % locator)
visible = self._is_visible(locator)
if visible:
if not message:
message = "The element '%s' should not be visible, "\
"but it is." % locator
raise AssertionError(message)
def element_text_should_be(self, locator, expected, message=''):
"""Verifies element identified by `locator` exactly contains text `expected`.
In contrast to `Element Should Contain`, this keyword does not try
a substring match but an exact match on the element identified by `locator`.
`message` can be used to override the default error message.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Verifying element '%s' contains exactly text '%s'."
% (locator, expected))
element = self._element_find(locator, True, True)
actual = element.text
if expected != actual:
if not message:
message = "The text of element '%s' should have been '%s' but "\
"in fact it was '%s'." % (locator, expected, actual)
raise AssertionError(message)
def get_element_attribute(self, attribute_locator):
"""Return value of element attribute.
`attribute_locator` consists of element locator followed by an @ sign
and attribute name, for example "element_id@class".
"""
locator, attribute_name = self._parse_attribute_locator(attribute_locator)
element = self._element_find(locator, True, False)
if element is None:
raise ValueError("Element '%s' not found." % (locator))
return element.get_attribute(attribute_name)
def get_horizontal_position(self, locator):
"""Returns horizontal position of element identified by `locator`.
The position is returned in pixels off the left side of the page,
as an integer. Fails if a matching element is not found.
See also `Get Vertical Position`.
"""
element = self._element_find(locator, True, False)
if element is None:
raise AssertionError("Could not determine position for '%s'" % (locator))
return element.location['x']
def get_element_size(self, locator):
"""Returns width and height of element identified by `locator`.
The element width and height is returned.
Fails if a matching element is not found.
"""
element = self._element_find(locator, True, True)
return element.size['width'], element.size['height']
def get_value(self, locator):
"""Returns the value attribute of element identified by `locator`.
See `introduction` for details about locating elements.
"""
return self._get_value(locator)
def get_text(self, locator):
"""Returns the text value of element identified by `locator`.
See `introduction` for details about locating elements.
"""
return self._get_text(locator)
def clear_element_text(self, locator):
"""Clears the text value of text entry element identified by `locator`.
See `introduction` for details about locating elements.
"""
element = self._element_find(locator, True, True)
element.clear()
def get_vertical_position(self, locator):
"""Returns vertical position of element identified by `locator`.
The position is returned in pixels off the top of the page,
as an integer. Fails if a matching element is not found.
See also `Get Horizontal Position`.
"""
element = self._element_find(locator, True, False)
if element is None:
raise AssertionError("Could not determine position for '%s'" % (locator))
return element.location['y']
# Public, mouse input/events
def click_element(self, locator):
"""Click element identified by `locator`.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Clicking element '%s'." % locator)
self._element_find(locator, True, True).click()
def click_element_at_coordinates(self, locator, xoffset, yoffset):
"""Click element identified by `locator` at x/y coordinates of the element.
Cursor is moved and the center of the element and x/y coordinates are
calculted from that point.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Click clicking element '%s' in coordinates '%s', '%s'." % (locator, xoffset, yoffset))
element = self._element_find(locator, True, True)
#self._element_find(locator, True, True).click()
#ActionChains(self._current_browser()).move_to_element_with_offset(element, xoffset, yoffset).click().perform()
ActionChains(self._current_browser()).move_to_element(element).move_by_offset(xoffset, yoffset).click().perform()
def double_click_element(self, locator):
"""Double click element identified by `locator`.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Double clicking element '%s'." % locator)
element = self._element_find(locator, True, True)
ActionChains(self._current_browser()).double_click(element).perform()
def focus(self, locator):
"""Sets focus to element identified by `locator`."""
element = self._element_find(locator, True, True)
self._current_browser().execute_script("arguments[0].focus();", element)
def drag_and_drop(self, source, target):
"""Drags element identified with `source` which is a locator.
Element can be moved on top of another element with `target`
argument.
`target` is a locator of the element where the dragged object is
dropped.
Examples:
| Drag And Drop | elem1 | elem2 | # Move elem1 over elem2. |
"""
src_elem = self._element_find(source,True,True)
trg_elem = self._element_find(target,True,True)
ActionChains(self._current_browser()).drag_and_drop(src_elem, trg_elem).perform()
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Drags element identified with `source` which is a locator.
Element will be moved by xoffset and yoffset, each of which is a
negative or positive number specify the offset.
Examples:
| Drag And Drop By Offset | myElem | 50 | -35 | # Move myElem 50px right and 35px down. |
"""
src_elem = self._element_find(source, True, True)
ActionChains(self._current_browser()).drag_and_drop_by_offset(src_elem, xoffset, yoffset).perform()
def mouse_down(self, locator):
"""Simulates pressing the left mouse button on the element specified by `locator`.
The element is pressed without releasing the mouse button.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
See also the more specific keywords `Mouse Down On Image` and
`Mouse Down On Link`.
"""
self._info("Simulating Mouse Down on element '%s'" % locator)
element = self._element_find(locator, True, False)
if element is None:
raise AssertionError("ERROR: Element %s not found." % (locator))
ActionChains(self._current_browser()).click_and_hold(element).perform()
def mouse_out(self, locator):
"""Simulates moving mouse away from the element specified by `locator`.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Simulating Mouse Out on element '%s'" % locator)
element = self._element_find(locator, True, False)
if element is None:
raise AssertionError("ERROR: Element %s not found." % (locator))
size = element.size
offsetx = (size['width'] / 2) + 1
offsety = (size['height'] / 2) + 1
ActionChains(self._current_browser()).move_to_element(element).move_by_offset(offsetx, offsety).perform()
def mouse_over(self, locator):
"""Simulates hovering mouse over the element specified by `locator`.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Simulating Mouse Over on element '%s'" % locator)
element = self._element_find(locator, True, False)
if element is None:
raise AssertionError("ERROR: Element %s not found." % (locator))
ActionChains(self._current_browser()).move_to_element(element).perform()
def mouse_up(self, locator):
"""Simulates releasing the left mouse button on the element specified by `locator`.
Key attributes for arbitrary elements are `id` and `name`. See
`introduction` for details about locating elements.
"""
self._info("Simulating Mouse Up on element '%s'" % locator)
element = self._element_find(locator, True, False)
if element is None:
raise AssertionError("ERROR: Element %s not found." % (locator))
ActionChains(self._current_browser()).release(element).perform()
def open_context_menu(self, locator):
"""Opens context menu on element identified by `locator`."""
element = self._element_find(locator, True, True)
ActionChains(self._current_browser()).context_click(element).perform()
def simulate(self, locator, event):
"""Simulates `event` on element identified by `locator`.
This keyword is useful if element has OnEvent handler that needs to be
explicitly invoked.
See `introduction` for details about locating elements.
"""
element = self._element_find(locator, True, True)
script = """
element = arguments[0];
eventName = arguments[1];
if (document.createEventObject) { // IE
return element.fireEvent('on' + eventName, document.createEventObject());
}
var evt = document.createEvent("HTMLEvents");
evt.initEvent(eventName, true, true);
return !element.dispatchEvent(evt);
"""
self._current_browser().execute_script(script, element, event)
def press_key(self, locator, key):
"""Simulates user pressing key on element identified by `locator`.
`key` is either a single character, a string, or a numerical ASCII code of the key
lead by '\\\\'.
Examples:
| Press Key | text_field | q |
| Press Key | text_field | abcde |
| Press Key | login_button | \\\\13 | # ASCII code for enter key |
"""
if key.startswith('\\') and len(key) > 1:
key = self._map_ascii_key_code_to_key(int(key[1:]))
element = self._element_find(locator, True, True)
#select it
element.send_keys(key)
# Public, links
def click_link(self, locator):
"""Clicks a link identified by locator.
Key attributes for links are `id`, `name`, `href` and link text. See
`introduction` for details about locating elements.
"""
self._info("Clicking link '%s'." % locator)
link = self._element_find(locator, True, True, tag='a')
link.click()
def get_all_links(self):
"""Returns a list containing ids of all links found in current page.
If a link has no id, an empty string will be in the list instead.
"""
links = []
for anchor in self._element_find("tag=a", False, False, 'a'):
links.append(anchor.get_attribute('id'))
return links
def mouse_down_on_link(self, locator):
"""Simulates a mouse down event on a link.
Key attributes for links are `id`, `name`, `href` and link text. See
`introduction` for details about locating elements.
"""
element = self._element_find(locator, True, True, 'link')
ActionChains(self._current_browser()).click_and_hold(element).perform()
def page_should_contain_link(self, locator, message='', loglevel='INFO'):
"""Verifies link identified by `locator` is found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for links are `id`, `name`, `href` and link text. See
`introduction` for details about locating elements.
"""
self._page_should_contain_element(locator, 'link', message, loglevel)
def page_should_not_contain_link(self, locator, message='', loglevel='INFO'):
"""Verifies image identified by `locator` is not found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for images are `id`, `src` and `alt`. See
`introduction` for details about locating elements.
"""
self._page_should_not_contain_element(locator, 'link', message, loglevel)
# Public, images
def click_image(self, locator):
"""Clicks an image found by `locator`.
Key attributes for images are `id`, `src` and `alt`. See
`introduction` for details about locating elements.
"""
self._info("Clicking image '%s'." % locator)
element = self._element_find(locator, True, False, 'image')
if element is None:
# A form may have an image as it's submit trigger.
element = self._element_find(locator, True, True, 'input')
element.click()
def mouse_down_on_image(self, locator):
"""Simulates a mouse down event on an image.
Key attributes for images are `id`, `src` and `alt`. See
`introduction` for details about locating elements.
"""
element = self._element_find(locator, True, True, 'image')
ActionChains(self._current_browser()).click_and_hold(element).perform()
def page_should_contain_image(self, locator, message='', loglevel='INFO'):
"""Verifies image identified by `locator` is found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for images are `id`, `src` and `alt`. See
`introduction` for details about locating elements.
"""
self._page_should_contain_element(locator, 'image', message, loglevel)
def page_should_not_contain_image(self, locator, message='', loglevel='INFO'):
"""Verifies image identified by `locator` is found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for images are `id`, `src` and `alt`. See
`introduction` for details about locating elements.
"""
self._page_should_not_contain_element(locator, 'image', message, loglevel)
# Public, xpath
def get_matching_xpath_count(self, xpath):
"""Returns number of elements matching `xpath`
One should not use the xpath= prefix for 'xpath'. XPath is assumed.
Correct:
| count = | Get Matching Xpath Count | //div[@id='sales-pop']
Incorrect:
| count = | Get Matching Xpath Count | xpath=//div[@id='sales-pop']
If you wish to assert the number of matching elements, use
`Xpath Should Match X Times`.
"""
count = len(self._element_find("xpath=" + xpath, False, False))
return str(count)
def xpath_should_match_x_times(self, xpath, expected_xpath_count, message='', loglevel='INFO'):
"""Verifies that the page contains the given number of elements located by the given `xpath`.
One should not use the xpath= prefix for 'xpath'. XPath is assumed.
Correct:
| Xpath Should Match X Times | //div[@id='sales-pop'] | 1
Incorrect:
| Xpath Should Match X Times | xpath=//div[@id='sales-pop'] | 1
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
"""
actual_xpath_count = len(self._element_find("xpath=" + xpath, False, False))
if int(actual_xpath_count) != int(expected_xpath_count):
if not message:
message = "Xpath %s should have matched %s times but matched %s times"\
%(xpath, expected_xpath_count, actual_xpath_count)
self.log_source(loglevel)
raise AssertionError(message)
self._info("Current page contains %s elements matching '%s'."
% (actual_xpath_count, xpath))
# Public, custom
def add_location_strategy(self, strategy_name, strategy_keyword=None, persist=False, location=None):
"""Add a custom location strategy based on given user keyword
< strategy_name > an unique short name as a customized prefix, such as 'myid', so that you can
use 'myid=User Name' instead of a legacy locator '//div[text()="User Name"]/../input' when using
Selenium2Library keywords. Scoped locally if persist=False, or the whole test if persist=True.
< strategy_keyword > an user keyword with arguments (location, criteria) to be registered.
It should return a legacy locator (string like 'id=xxx', 'css=xxx', 'xpath=//xxx', '//div/button[1]')
retrieved from ${location} by given ${criteria}, or the matched web element if ${location} is None.
${criteria} could be meaningful text to increase test case's readability, such as element's GUI text.
Once registered, this keyword will be hook-called internally when Selenium2Library keyword is called.
< location > the source that stores the mapping from ${criteria} to legacy locator, such as a dictionary,
page objects, or database.
Examples A ( location is a database ):
| # *** Define strategy keyword *** |
| Get Locator From DB | ${location} | ${criteria} |
| | ${index}= | Convert To Integer | ${criteria} |
| | ${locator}= | Read MySQL | ${location} | ${index} |
| | [Return] | ${locator} |
| # *** Register and use *** |
| Add Location Strategy | db | Get Locator From DB | ${False} | ${MySQL} |
| Page Should Contain Element | db=${obj_index} |
Examples B ( location is a python dictionary, strategy keyword could be omitted ):
| # *** Define python file and import *** |
| div_blocks = '//form' |
| page = '${div_blocks}/div[${index}]' | # ${index} defined in user keyword |
| dict_page = {'Add Button': '${page}/div/button[1]', 'Delete Button': '${page}/div/button[2]} |
| # *** Register and use *** |
| Add Location Strategy | pg | | location=${dict_page} |
| ${index}= | Set Variable | 1 |
| Click Button | pg=Add Button |
Examples C ( location is None, strategy keyword must return web element object ):
| # *** Define Strategy Keyword, 4 args needed *** |
| Return Web Element By Javascript | ${browser} | ${criteria} | ${tag} | ${constraints} |
| | ${element_object}= | Execute Javascript | return window.document.getElementById('${criteria}'); |
| | [Return] | ${element_object} |
| Return Web Element By Element Text | ${browser} | ${criteria} | ${tag} | ${constraints} |
| | ${element_object}= | Get Webelement | &${myPageDict}[${criteria}] |
| | [Return] | ${element_object} |
| # *** Register and use *** |
| Add Location Strategy | byjs | Return Web Element By Javascript |
| Add Location Strategy | byui | Return Web Element By Element Text |
| Page Should Contain Element | byjs=${an_element_id} |
| Page Should Contain Element | byui=User Name |
See `Remove Location Strategy` for details about removing a custom location strategy.
"""
strategy = CustomLocator(strategy_name, strategy_keyword)
self._element_finder.register(strategy, persist, location)
def remove_location_strategy(self, strategy_name):
"""Removes a previously added custom location strategy.
Will fail if a default strategy is specified.
See `Add Location Strategy` for details about adding a custom location strategy.
"""
self._element_finder.unregister(strategy_name)
# Private
def _element_find(self, locator, first_only, required, tag=None):
browser = self._current_browser()
if isstr(locator):
elements = self._element_finder.find(browser, locator, tag)
if required and len(elements) == 0:
raise ValueError("Element locator '" + locator + "' did not match any elements.")
if first_only:
if len(elements) == 0: return None
return elements[0]
elif isinstance(locator, WebElement):
elements = locator
# do some other stuff here like deal with list of webelements
# ... or raise locator/element specific error if required
return elements
def _frame_contains(self, locator, text):
browser = self._current_browser()
element = self._element_find(locator, True, True)
browser.switch_to_frame(element)
self._info("Searching for text from frame '%s'." % locator)
found = self._is_text_present(text)
browser.switch_to_default_content()
return found
def _get_text(self, locator):
element = self._element_find(locator, True, True)
if element is not None:
return element.text
return None
def _get_value(self, locator, tag=None):
element = self._element_find(locator, True, False, tag=tag)
return element.get_attribute('value') if element is not None else None
def _is_enabled(self, locator):
element = self._element_find(locator, True, True)
if not self._is_form_element(element):
raise AssertionError("ERROR: Element %s is not an input." % (locator))
if not element.is_enabled():
return False
read_only = element.get_attribute('readonly')
if read_only == 'readonly' or read_only == 'true':
return False
return True
def _is_text_present(self, text):
locator = "xpath=//*[contains(., %s)]" % utils.escape_xpath_value(text);
return self._is_element_present(locator)
def _is_visible(self, locator):
element = self._element_find(locator, True, False)
if element is not None:
return element.is_displayed()
return None
def _map_ascii_key_code_to_key(self, key_code):
map = {
0: Keys.NULL,
8: Keys.BACK_SPACE,
9: Keys.TAB,
10: Keys.RETURN,
13: Keys.ENTER,
24: Keys.CANCEL,
27: Keys.ESCAPE,
32: Keys.SPACE,
42: Keys.MULTIPLY,
43: Keys.ADD,
44: Keys.SEPARATOR,
45: Keys.SUBTRACT,
56: Keys.DECIMAL,
57: Keys.DIVIDE,
59: Keys.SEMICOLON,
61: Keys.EQUALS,
127: Keys.DELETE
}
key = map.get(key_code)
if key is None:
key = chr(key_code)
return key
def _map_named_key_code_to_special_key(self, key_name):
try:
return getattr(Keys, key_name)
except AttributeError:
message = "Unknown key named '%s'." % (key_name)
self._debug(message)
raise ValueError(message)
def _parse_attribute_locator(self, attribute_locator):
parts = attribute_locator.rpartition('@')
if len(parts[0]) == 0:
raise ValueError("Attribute locator '%s' does not contain an element locator." % (attribute_locator))
if len(parts[2]) == 0:
raise ValueError("Attribute locator '%s' does not contain an attribute name." % (attribute_locator))
return (parts[0], parts[2])
def _is_element_present(self, locator, tag=None):
return (self._element_find(locator, True, False, tag=tag) is not None)
def _page_contains(self, text):
browser = self._current_browser()
browser.switch_to_default_content()
if self._is_text_present(text):
return True
subframes = self._element_find("xpath=//frame|//iframe", False, False)
self._debug('Current frame has %d subframes' % len(subframes))
for frame in subframes:
browser.switch_to_frame(frame)
found_text = self._is_text_present(text)
browser.switch_to_default_content()
if found_text:
return True
return False
def _page_should_contain_element(self, locator, tag, message, loglevel):
element_name = tag if tag is not None else 'element'
if not self._is_element_present(locator, tag):
if not message:
message = "Page should have contained %s '%s' but did not"\
% (element_name, locator)
self.log_source(loglevel)
raise AssertionError(message)
self._info("Current page contains %s '%s'." % (element_name, locator))
def _page_should_not_contain_element(self, locator, tag, message, loglevel):
element_name = tag if tag is not None else 'element'
if self._is_element_present(locator, tag):
if not message:
message = "Page should not have contained %s '%s'"\
% (element_name, locator)
self.log_source(loglevel)
raise AssertionError(message)
self._info("Current page does not contain %s '%s'."
% (element_name, locator)) | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/keywords/_element.py | 0.773302 | 0.237631 | _element.py | pypi |
import robot
import os, errno
from Selenium2Library import utils
from keywordgroup import KeywordGroup
class _ScreenshotKeywords(KeywordGroup):
def __init__(self):
self._screenshot_index = {}
self._screenshot_path_stack = []
self.screenshot_root_directory = None
# Public
def set_screenshot_directory(self, path, persist=False):
"""Sets the root output directory for captured screenshots.
``path`` argument specifies the absolute path where the screenshots
should be written to. If the specified ``path`` does not exist,
it will be created. Setting ``persist`` specifies that the given
``path`` should be used for the rest of the test execution, otherwise
the path will be restored at the end of the currently executing scope.
"""
path = os.path.abspath(path)
self._create_directory(path)
if persist is False:
self._screenshot_path_stack.append(self.screenshot_root_directory)
# Restore after current scope ends
utils.events.on('scope_end', 'current',
self._restore_screenshot_directory)
self.screenshot_root_directory = path
def capture_page_screenshot(self,
filename='selenium-screenshot-{index}.png'):
"""Takes a screenshot of the current page and embeds it into the log.
``filename`` argument specifies the name of the file to write the
screenshot into. If no ``filename`` is given, the screenshot is saved
into file _selenium-screenshot-{index}.png_ under the directory where
the Robot Framework log file is written into. The ``filename`` is
also considered relative to the same directory, if it is not
given in absolute format. If an absolute or relative path is given
but the path does not exist it will be created.
Starting from Selenium2Library 1.8 if ``filename`` contains _{index}_
characters, it will be automatically replaced with running index.
The running index is unique for each different filename. The absolute
path of the saved screenshot is always returned and it does not depend
does the ``filename`` contain _{index}_. See example 1 and 2 for more
details.
The _{index}_ is replaced with the actual index by using Python's
[https://docs.python.org/2/library/stdtypes.html#str.format|
str.format] method, and it can be formatted using the standard
[https://docs.python.org/2/library/string.html#format-string-syntax|
format string syntax]. The example 3 shows this by setting the width and
the fill character.
If there is a need to write literal _{index}_ or if ``filename``
contains _{_ or _}_ characters, then the braces must be doubled.
Example 1:
| ${file1} = | Capture Page Screenshot |
| File Should Exist | ${OUTPUTDIR}${/}selenium-screenshot-1.png |
| Should Be Equal | ${file1} | ${OUTPUTDIR}${/}selenium-screenshot-1.png |
| ${file2} = | Capture Page Screenshot |
| File Should Exist | ${OUTPUTDIR}${/}selenium-screenshot-2.png |
| Should Be Equal | ${file2} | ${OUTPUTDIR}${/}selenium-screenshot-2.png |
Example 2:
| ${file1} = | Capture Page Screenshot | ${OTHER_DIR}${/}other-{index}-name.png |
| ${file2} = | Capture Page Screenshot | ${OTHER_DIR}${/}some-other-name-{index}.png |
| ${file3} = | Capture Page Screenshot | ${OTHER_DIR}${/}other-{index}-name.png |
| File Should Exist | ${OTHER_DIR}${/}other-1-name.png |
| Should Be Equal | ${file1} | ${OTHER_DIR}${/}other-1-name.png |
| File Should Exist | ${OTHER_DIR}${/}some-other-name-1.png |
| Should Be Equal | ${file2} | ${OTHER_DIR}${/}some-other-name-1.png |
| File Should Exist | ${OTHER_DIR}${/}other-2-name.png |
| Should Be Equal | ${file3} | ${OTHER_DIR}${/}other-2-name.png |
Example 3:
| Capture Page Screenshot | ${OTHER_DIR}${/}sc-{index:06}.png |
| File Should Exist | ${OTHER_DIR}${/}sc-000001.png |
"""
path, link = self._get_screenshot_paths(filename)
self._create_directory(path)
if hasattr(self._current_browser(), 'get_screenshot_as_file'):
if not self._current_browser().get_screenshot_as_file(path):
raise RuntimeError('Failed to save screenshot ' + link)
else:
if not self._current_browser().save_screenshot(path):
raise RuntimeError('Failed to save screenshot ' + link)
# Image is shown on its own row and thus prev row is closed on purpose
self._html('</td></tr><tr><td colspan="3"><a href="%s">'
'<img src="%s" width="800px"></a>' % (link, link))
return path
# Private
def _create_directory(self, path):
target_dir = os.path.dirname(path)
if not os.path.exists(target_dir):
try:
os.makedirs(target_dir)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(target_dir):
pass
else:
raise
def _get_screenshot_directory(self):
# Use screenshot root directory if set
if self.screenshot_root_directory is not None:
return self.screenshot_root_directory
# Otherwise use RF's log directory
return self._get_log_dir()
# should only be called by set_screenshot_directory
def _restore_screenshot_directory(self):
self.screenshot_root_directory = self._screenshot_path_stack.pop()
def _get_screenshot_paths(self, filename):
filename = filename.format(
index=self._get_screenshot_index(filename))
filename = filename.replace('/', os.sep)
screenshotdir = self._get_screenshot_directory()
logdir = self._get_log_dir()
path = os.path.join(screenshotdir, filename)
link = robot.utils.get_link_path(path, logdir)
return path, link
def _get_screenshot_index(self, filename):
if filename not in self._screenshot_index:
self._screenshot_index[filename] = 0
self._screenshot_index[filename] += 1
return self._screenshot_index[filename] | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/keywords/_screenshot.py | 0.641198 | 0.265035 | _screenshot.py | pypi |
import os
from keywordgroup import KeywordGroup
from selenium.common.exceptions import WebDriverException
class _FormElementKeywords(KeywordGroup):
# Public, form
def submit_form(self, locator=None):
"""Submits a form identified by `locator`.
If `locator` is empty, first form in the page will be submitted.
Key attributes for forms are `id` and `name`. See `introduction` for
details about locating elements.
"""
self._info("Submitting form '%s'." % locator)
if not locator:
locator = 'xpath=//form'
element = self._element_find(locator, True, True, 'form')
element.submit()
# Public, checkboxes
def checkbox_should_be_selected(self, locator):
"""Verifies checkbox identified by `locator` is selected/checked.
Key attributes for checkboxes are `id` and `name`. See `introduction`
for details about locating elements.
"""
self._info("Verifying checkbox '%s' is selected." % locator)
element = self._get_checkbox(locator)
if not element.is_selected():
raise AssertionError("Checkbox '%s' should have been selected "
"but was not" % locator)
def checkbox_should_not_be_selected(self, locator):
"""Verifies checkbox identified by `locator` is not selected/checked.
Key attributes for checkboxes are `id` and `name`. See `introduction`
for details about locating elements.
"""
self._info("Verifying checkbox '%s' is not selected." % locator)
element = self._get_checkbox(locator)
if element.is_selected():
raise AssertionError("Checkbox '%s' should not have been selected"
% locator)
def page_should_contain_checkbox(self, locator, message='', loglevel='INFO'):
"""Verifies checkbox identified by `locator` is found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for checkboxes are `id` and `name`. See `introduction`
for details about locating elements.
"""
self._page_should_contain_element(locator, 'checkbox', message, loglevel)
def page_should_not_contain_checkbox(self, locator, message='', loglevel='INFO'):
"""Verifies checkbox identified by `locator` is not found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for checkboxes are `id` and `name`. See `introduction`
for details about locating elements.
"""
self._page_should_not_contain_element(locator, 'checkbox', message, loglevel)
def select_checkbox(self, locator):
"""Selects checkbox identified by `locator`.
Does nothing if checkbox is already selected. Key attributes for
checkboxes are `id` and `name`. See `introduction` for details about
locating elements.
"""
self._info("Selecting checkbox '%s'." % locator)
element = self._get_checkbox(locator)
if not element.is_selected():
element.click()
def unselect_checkbox(self, locator):
"""Removes selection of checkbox identified by `locator`.
Does nothing if the checkbox is not checked. Key attributes for
checkboxes are `id` and `name`. See `introduction` for details about
locating elements.
"""
self._info("Unselecting checkbox '%s'." % locator)
element = self._get_checkbox(locator)
if element.is_selected():
element.click()
# Public, radio buttons
def page_should_contain_radio_button(self, locator, message='', loglevel='INFO'):
"""Verifies radio button identified by `locator` is found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for radio buttons are `id`, `name` and `value`. See
`introduction` for details about locating elements.
"""
self._page_should_contain_element(locator, 'radio button', message, loglevel)
def page_should_not_contain_radio_button(self, locator, message='', loglevel='INFO'):
"""Verifies radio button identified by `locator` is not found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for radio buttons are `id`, `name` and `value`. See
`introduction` for details about locating elements.
"""
self._page_should_not_contain_element(locator, 'radio button', message, loglevel)
def radio_button_should_be_set_to(self, group_name, value):
"""Verifies radio button group identified by `group_name` has its selection set to `value`.
See `Select Radio Button` for information about how radio buttons are
located.
"""
self._info("Verifying radio button '%s' has selection '%s'." \
% (group_name, value))
elements = self._get_radio_buttons(group_name)
actual_value = self._get_value_from_radio_buttons(elements)
if actual_value is None or actual_value != value:
raise AssertionError("Selection of radio button '%s' should have "
"been '%s' but was '%s'"
% (group_name, value, actual_value))
def radio_button_should_not_be_selected(self, group_name):
"""Verifies radio button group identified by `group_name` has no selection.
See `Select Radio Button` for information about how radio buttons are
located.
"""
self._info("Verifying radio button '%s' has no selection." % group_name)
elements = self._get_radio_buttons(group_name)
actual_value = self._get_value_from_radio_buttons(elements)
if actual_value is not None:
raise AssertionError("Radio button group '%s' should not have had "
"selection, but '%s' was selected"
% (group_name, actual_value))
def select_radio_button(self, group_name, value):
"""Sets selection of radio button group identified by `group_name` to `value`.
The radio button to be selected is located by two arguments:
- `group_name` is used as the name of the radio input
- `value` is used for the value attribute or for the id attribute
The XPath used to locate the correct radio button then looks like this:
//input[@type='radio' and @name='group_name' and (@value='value' or @id='value')]
Examples:
| Select Radio Button | size | XL | # Matches HTML like <input type="radio" name="size" value="XL">XL</input> |
| Select Radio Button | size | sizeXL | # Matches HTML like <input type="radio" name="size" value="XL" id="sizeXL">XL</input> |
"""
self._info("Selecting '%s' from radio button '%s'." % (value, group_name))
element = self._get_radio_button_with_value(group_name, value)
if not element.is_selected():
element.click()
# Public, text fields
def choose_file(self, locator, file_path):
"""Inputs the `file_path` into file input field found by `locator`.
This keyword is most often used to input files into upload forms.
The file specified with `file_path` must be available on the same host
where the Selenium Server is running.
Example:
| Choose File | my_upload_field | /home/user/files/trades.csv |
"""
if not os.path.isfile(file_path):
raise AssertionError("File '%s' does not exist on the local file system"
% file_path)
self._element_find(locator, True, True).send_keys(file_path)
def input_password(self, locator, text):
"""Types the given password into text field identified by `locator`.
Difference between this keyword and `Input Text` is that this keyword
does not log the given password. See `introduction` for details about
locating elements.
"""
self._info("Typing password into text field '%s'" % locator)
self._input_text_into_text_field(locator, text)
def input_text(self, locator, text):
"""Types the given `text` into text field identified by `locator`.
See `introduction` for details about locating elements.
"""
self._info("Typing text '%s' into text field '%s'" % (text, locator))
self._input_text_into_text_field(locator, text)
def page_should_contain_textfield(self, locator, message='', loglevel='INFO'):
"""Verifies text field identified by `locator` is found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for text fields are `id` and `name`. See `introduction`
for details about locating elements.
"""
self._page_should_contain_element(locator, 'text field', message, loglevel)
def page_should_not_contain_textfield(self, locator, message='', loglevel='INFO'):
"""Verifies text field identified by `locator` is not found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for text fields are `id` and `name`. See `introduction`
for details about locating elements.
"""
self._page_should_not_contain_element(locator, 'text field', message, loglevel)
def textfield_should_contain(self, locator, expected, message=''):
"""Verifies text field identified by `locator` contains text `expected`.
`message` can be used to override default error message.
Key attributes for text fields are `id` and `name`. See `introduction`
for details about locating elements.
"""
actual = self._get_value(locator, 'text field')
if not expected in actual:
if not message:
message = "Text field '%s' should have contained text '%s' "\
"but it contained '%s'" % (locator, expected, actual)
raise AssertionError(message)
self._info("Text field '%s' contains text '%s'." % (locator, expected))
def textfield_value_should_be(self, locator, expected, message=''):
"""Verifies the value in text field identified by `locator` is exactly `expected`.
`message` can be used to override default error message.
Key attributes for text fields are `id` and `name`. See `introduction`
for details about locating elements.
"""
element = self._element_find(locator, True, False, 'text field')
if element is None: element = self._element_find(locator, True, False, 'file upload')
actual = element.get_attribute('value') if element is not None else None
if actual != expected:
if not message:
message = "Value of text field '%s' should have been '%s' "\
"but was '%s'" % (locator, expected, actual)
raise AssertionError(message)
self._info("Content of text field '%s' is '%s'." % (locator, expected))
def textarea_should_contain(self, locator, expected, message=''):
"""Verifies text area identified by `locator` contains text `expected`.
`message` can be used to override default error message.
Key attributes for text areas are `id` and `name`. See `introduction`
for details about locating elements.
"""
actual = self._get_value(locator, 'text area')
if actual is not None:
if not expected in actual:
if not message:
message = "Text field '%s' should have contained text '%s' "\
"but it contained '%s'" % (locator, expected, actual)
raise AssertionError(message)
else:
raise ValueError("Element locator '" + locator + "' did not match any elements.")
self._info("Text area '%s' contains text '%s'." % (locator, expected))
def textarea_value_should_be(self, locator, expected, message=''):
"""Verifies the value in text area identified by `locator` is exactly `expected`.
`message` can be used to override default error message.
Key attributes for text areas are `id` and `name`. See `introduction`
for details about locating elements.
"""
actual = self._get_value(locator, 'text area')
if actual is not None:
if expected!=actual:
if not message:
message = "Text field '%s' should have contained text '%s' "\
"but it contained '%s'" % (locator, expected, actual)
raise AssertionError(message)
else:
raise ValueError("Element locator '" + locator + "' did not match any elements.")
self._info("Content of text area '%s' is '%s'." % (locator, expected))
# Public, buttons
def click_button(self, locator):
"""Clicks a button identified by `locator`.
Key attributes for buttons are `id`, `name` and `value`. See
`introduction` for details about locating elements.
"""
self._info("Clicking button '%s'." % locator)
element = self._element_find(locator, True, False, 'input')
if element is None:
element = self._element_find(locator, True, True, 'button')
element.click()
def page_should_contain_button(self, locator, message='', loglevel='INFO'):
"""Verifies button identified by `locator` is found from current page.
This keyword searches for buttons created with either `input` or `button` tag.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for buttons are `id`, `name` and `value`. See
`introduction` for details about locating elements.
"""
try:
self._page_should_contain_element(locator, 'input', message, loglevel)
except AssertionError:
self._page_should_contain_element(locator, 'button', message, loglevel)
def page_should_not_contain_button(self, locator, message='', loglevel='INFO'):
"""Verifies button identified by `locator` is not found from current page.
This keyword searches for buttons created with either `input` or `button` tag.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for buttons are `id`, `name` and `value`. See
`introduction` for details about locating elements.
"""
self._page_should_not_contain_element(locator, 'button', message, loglevel)
self._page_should_not_contain_element(locator, 'input', message, loglevel)
# Private
def _get_checkbox(self, locator):
return self._element_find(locator, True, True, tag='input')
def _get_radio_buttons(self, group_name):
xpath = "xpath=//input[@type='radio' and @name='%s']" % group_name
self._debug('Radio group locator: ' + xpath)
return self._element_find(xpath, False, True)
def _get_radio_button_with_value(self, group_name, value):
xpath = "xpath=//input[@type='radio' and @name='%s' and (@value='%s' or @id='%s')]" \
% (group_name, value, value)
self._debug('Radio group locator: ' + xpath)
return self._element_find(xpath, True, True)
def _get_value_from_radio_buttons(self, elements):
for element in elements:
if element.is_selected():
return element.get_attribute('value')
return None
def _input_text_into_text_field(self, locator, text):
element = self._element_find(locator, True, True)
element.clear()
element.send_keys(text)
def _is_form_element(self, element):
if element is None:
return False
tag = element.tag_name.lower()
return tag == 'input' or tag == 'select' or tag == 'textarea' or tag == 'button' or tag == 'option' | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/keywords/_formelement.py | 0.657758 | 0.188866 | _formelement.py | pypi |
import os
import sys
from Selenium2Library.locators import TableElementFinder
from keywordgroup import KeywordGroup
class _TableElementKeywords(KeywordGroup):
def __init__(self):
self._table_element_finder = TableElementFinder()
# Public
def get_table_cell(self, table_locator, row, column, loglevel='INFO'):
"""Returns the content from a table cell.
Row and column number start from 1. Header and footer rows are
included in the count. A negative row or column number can be used
to get rows counting from the end (end: -1). Cell content from header
or footer rows can be obtained with this keyword. To understand how
tables are identified, please take a look at the `introduction`.
See `Page Should Contain` for explanation about `loglevel` argument.
"""
row = int(row)
row_index = row
if row > 0: row_index = row - 1
column = int(column)
column_index = column
if column > 0: column_index = column - 1
table = self._table_element_finder.find(self._current_browser(), table_locator)
if table is not None:
rows = table.find_elements_by_xpath("./thead/tr")
if row_index >= len(rows) or row_index < 0:
rows.extend(table.find_elements_by_xpath("./tbody/tr"))
if row_index >= len(rows) or row_index < 0:
rows.extend(table.find_elements_by_xpath("./tfoot/tr"))
if row_index < len(rows):
columns = rows[row_index].find_elements_by_tag_name('th')
if column_index >= len(columns) or column_index < 0:
columns.extend(rows[row_index].find_elements_by_tag_name('td'))
if column_index < len(columns):
return columns[column_index].text
self.log_source(loglevel)
raise AssertionError("Cell in table %s in row #%s and column #%s could not be found."
% (table_locator, str(row), str(column)))
def table_cell_should_contain(self, table_locator, row, column, expected, loglevel='INFO'):
"""Verifies that a certain cell in a table contains `expected`.
Row and column number start from 1. This keyword passes if the
specified cell contains the given content. If you want to test
that the cell content matches exactly, or that it e.g. starts
with some text, use `Get Table Cell` keyword in combination
with built-in keywords such as `Should Be Equal` or `Should
Start With`.
To understand how tables are identified, please take a look at
the `introduction`.
See `Page Should Contain` for explanation about `loglevel` argument.
"""
message = ("Cell in table '%s' in row #%s and column #%s "
"should have contained text '%s'."
% (table_locator, row, column, expected))
try:
content = self.get_table_cell(table_locator, row, column, loglevel='NONE')
except AssertionError as err:
self._info(err)
self.log_source(loglevel)
raise AssertionError(message)
self._info("Cell contains %s." % (content))
if expected not in content:
self.log_source(loglevel)
raise AssertionError(message)
def table_column_should_contain(self, table_locator, col, expected, loglevel='INFO'):
"""Verifies that a specific column contains `expected`.
The first leftmost column is column number 1. A negative column
number can be used to get column counting from the end of the row (end: -1).
If the table contains cells that span multiple columns, those merged cells
count as a single column. For example both tests below work,
if in one row columns A and B are merged with colspan="2", and
the logical third column contains "C".
Example:
| Table Column Should Contain | tableId | 3 | C |
| Table Column Should Contain | tableId | 2 | C |
To understand how tables are identified, please take a look at
the `introduction`.
See `Page Should Contain Element` for explanation about
`loglevel` argument.
"""
element = self._table_element_finder.find_by_col(self._current_browser(), table_locator, col, expected)
if element is None:
self.log_source(loglevel)
raise AssertionError("Column #%s in table identified by '%s' "
"should have contained text '%s'."
% (col, table_locator, expected))
def table_footer_should_contain(self, table_locator, expected, loglevel='INFO'):
"""Verifies that the table footer contains `expected`.
With table footer can be described as any <td>-element that is
child of a <tfoot>-element. To understand how tables are
identified, please take a look at the `introduction`.
See `Page Should Contain Element` for explanation about
`loglevel` argument.
"""
element = self._table_element_finder.find_by_footer(self._current_browser(), table_locator, expected)
if element is None:
self.log_source(loglevel)
raise AssertionError("Footer in table identified by '%s' should have contained "
"text '%s'." % (table_locator, expected))
def table_header_should_contain(self, table_locator, expected, loglevel='INFO'):
"""Verifies that the table header, i.e. any <th>...</th> element, contains `expected`.
To understand how tables are identified, please take a look at
the `introduction`.
See `Page Should Contain Element` for explanation about
`loglevel` argument.
"""
element = self._table_element_finder.find_by_header(self._current_browser(), table_locator, expected)
if element is None:
self.log_source(loglevel)
raise AssertionError("Header in table identified by '%s' should have contained "
"text '%s'." % (table_locator, expected))
def table_row_should_contain(self, table_locator, row, expected, loglevel='INFO'):
"""Verifies that a specific table row contains `expected`.
The uppermost row is row number 1. A negative column
number can be used to get column counting from the end of the row
(end: -1). For tables that are structured with thead, tbody and tfoot,
only the tbody section is searched. Please use `Table Header Should Contain`
or `Table Footer Should Contain` for tests against the header or
footer content.
If the table contains cells that span multiple rows, a match
only occurs for the uppermost row of those merged cells. To
understand how tables are identified, please take a look at
the `introduction`.
See `Page Should Contain Element` for explanation about `loglevel` argument.
"""
element = self._table_element_finder.find_by_row(self._current_browser(), table_locator, row, expected)
if element is None:
self.log_source(loglevel)
raise AssertionError("Row #%s in table identified by '%s' should have contained "
"text '%s'." % (row, table_locator, expected))
def table_should_contain(self, table_locator, expected, loglevel='INFO'):
"""Verifies that `expected` can be found somewhere in the table.
To understand how tables are identified, please take a look at
the `introduction`.
See `Page Should Contain Element` for explanation about
`loglevel` argument.
"""
element = self._table_element_finder.find_by_content(self._current_browser(), table_locator, expected)
if element is None:
self.log_source(loglevel)
raise AssertionError("Table identified by '%s' should have contained text '%s'." \
% (table_locator, expected)) | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/keywords/_tableelement.py | 0.605449 | 0.661909 | _tableelement.py | pypi |
from selenium.webdriver.support.ui import Select
from keywordgroup import KeywordGroup
from selenium.common.exceptions import NoSuchElementException
class _SelectElementKeywords(KeywordGroup):
# Public
def get_list_items(self, locator):
"""Returns the values in the select list identified by `locator`.
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
select, options = self._get_select_list_options(locator)
return self._get_labels_for_options(options)
def get_selected_list_label(self, locator):
"""Returns the visible label of the selected element from the select list identified by `locator`.
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
select = self._get_select_list(locator)
return select.first_selected_option.text
def get_selected_list_labels(self, locator):
"""Returns the visible labels of selected elements (as a list) from the select list identified by `locator`.
Fails if there is no selection.
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
select, options = self._get_select_list_options_selected(locator)
if len(options) == 0:
raise ValueError("Select list with locator '%s' does not have any selected values")
return self._get_labels_for_options(options)
def get_selected_list_value(self, locator):
"""Returns the value of the selected element from the select list identified by `locator`.
Return value is read from `value` attribute of the selected element.
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
select = self._get_select_list(locator)
return select.first_selected_option.get_attribute('value')
def get_selected_list_values(self, locator):
"""Returns the values of selected elements (as a list) from the select list identified by `locator`.
Fails if there is no selection.
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
select, options = self._get_select_list_options_selected(locator)
if len(options) == 0:
raise ValueError("Select list with locator '%s' does not have any selected values")
return self._get_values_for_options(options)
def list_selection_should_be(self, locator, *items):
"""Verifies the selection of select list identified by `locator` is exactly `*items`.
If you want to test that no option is selected, simply give no `items`.
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
items_str = items and "option(s) [ %s ]" % " | ".join(items) or "no options"
self._info("Verifying list '%s' has %s selected." % (locator, items_str))
items = list(items)
self.page_should_contain_list(locator)
select, options = self._get_select_list_options_selected(locator)
if not items and len(options) == 0:
return
selected_values = self._get_values_for_options(options)
selected_labels = self._get_labels_for_options(options)
err = "List '%s' should have had selection [ %s ] but it was [ %s ]" \
% (locator, ' | '.join(items), ' | '.join(selected_labels))
for item in items:
if item not in selected_values + selected_labels:
raise AssertionError(err)
for selected_value, selected_label in zip(selected_values, selected_labels):
if selected_value not in items and selected_label not in items:
raise AssertionError(err)
def list_should_have_no_selections(self, locator):
"""Verifies select list identified by `locator` has no selections.
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
self._info("Verifying list '%s' has no selection." % locator)
select, options = self._get_select_list_options_selected(locator)
if options:
selected_labels = self._get_labels_for_options(options)
items_str = " | ".join(selected_labels)
raise AssertionError("List '%s' should have had no selection "
"(selection was [ %s ])" % (locator, items_str))
def page_should_contain_list(self, locator, message='', loglevel='INFO'):
"""Verifies select list identified by `locator` is found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for lists are `id` and `name`. See `introduction` for
details about locating elements.
"""
self._page_should_contain_element(locator, 'list', message, loglevel)
def page_should_not_contain_list(self, locator, message='', loglevel='INFO'):
"""Verifies select list identified by `locator` is not found from current page.
See `Page Should Contain Element` for explanation about `message` and
`loglevel` arguments.
Key attributes for lists are `id` and `name`. See `introduction` for
details about locating elements.
"""
self._page_should_not_contain_element(locator, 'list', message, loglevel)
def select_all_from_list(self, locator):
"""Selects all values from multi-select list identified by `id`.
Key attributes for lists are `id` and `name`. See `introduction` for
details about locating elements.
"""
self._info("Selecting all options from list '%s'." % locator)
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError("Keyword 'Select all from list' works only for multiselect lists.")
for i in range(len(select.options)):
select.select_by_index(i)
def select_from_list(self, locator, *items):
"""Selects `*items` from list identified by `locator`
If more than one value is given for a single-selection list, the last
value will be selected. If the target list is a multi-selection list,
and `*items` is an empty list, all values of the list will be selected.
*items try to select by value then by label.
It's faster to use 'by index/value/label' functions.
An exception is raised for a single-selection list if the last
value does not exist in the list and a warning for all other non-
existing items. For a multi-selection list, an exception is raised
for any and all non-existing values.
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
non_existing_items = []
items_str = items and "option(s) '%s'" % ", ".join(items) or "all options"
self._info("Selecting %s from list '%s'." % (items_str, locator))
select = self._get_select_list(locator)
if not items:
for i in range(len(select.options)):
select.select_by_index(i)
return
for item in items:
try:
select.select_by_value(item)
except:
try:
select.select_by_visible_text(item)
except:
non_existing_items = non_existing_items + [item]
continue
if any(non_existing_items):
if select.is_multiple:
raise ValueError("Options '%s' not in list '%s'." % (", ".join(non_existing_items), locator))
else:
if any (non_existing_items[:-1]):
items_str = non_existing_items[:-1] and "Option(s) '%s'" % ", ".join(non_existing_items[:-1])
self._warn("%s not found within list '%s'." % (items_str, locator))
if items and items[-1] in non_existing_items:
raise ValueError("Option '%s' not in list '%s'." % (items[-1], locator))
def select_from_list_by_index(self, locator, *indexes):
"""Selects `*indexes` from list identified by `locator`
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
if not indexes:
raise ValueError("No index given.")
items_str = "index(es) '%s'" % ", ".join(indexes)
self._info("Selecting %s from list '%s'." % (items_str, locator))
select = self._get_select_list(locator)
for index in indexes:
select.select_by_index(int(index))
def select_from_list_by_value(self, locator, *values):
"""Selects `*values` from list identified by `locator`
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
if not values:
raise ValueError("No value given.")
items_str = "value(s) '%s'" % ", ".join(values)
self._info("Selecting %s from list '%s'." % (items_str, locator))
select = self._get_select_list(locator)
for value in values:
select.select_by_value(value)
def select_from_list_by_label(self, locator, *labels):
"""Selects `*labels` from list identified by `locator`
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
if not labels:
raise ValueError("No value given.")
items_str = "label(s) '%s'" % ", ".join(labels)
self._info("Selecting %s from list '%s'." % (items_str, locator))
select = self._get_select_list(locator)
for label in labels:
select.select_by_visible_text(label)
def unselect_from_list(self, locator, *items):
"""Unselects given values from select list identified by locator.
As a special case, giving empty list as `*items` will remove all
selections.
*items try to unselect by value AND by label.
It's faster to use 'by index/value/label' functions.
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
items_str = items and "option(s) '%s'" % ", ".join(items) or "all options"
self._info("Unselecting %s from list '%s'." % (items_str, locator))
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError("Keyword 'Unselect from list' works only for multiselect lists.")
if not items:
select.deselect_all()
return
select, options = self._get_select_list_options(select)
for item in items:
# Only Selenium 2.52 and newer raise exceptions when there is no match.
# For backwards compatibility reasons we want to ignore them.
try:
select.deselect_by_value(item)
except NoSuchElementException:
pass
try:
select.deselect_by_visible_text(item)
except NoSuchElementException:
pass
def unselect_from_list_by_index(self, locator, *indexes):
"""Unselects `*indexes` from list identified by `locator`
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
if not indexes:
raise ValueError("No index given.")
items_str = "index(es) '%s'" % ", ".join(indexes)
self._info("Unselecting %s from list '%s'." % (items_str, locator))
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError("Keyword 'Unselect from list' works only for multiselect lists.")
for index in indexes:
select.deselect_by_index(int(index))
def unselect_from_list_by_value(self, locator, *values):
"""Unselects `*values` from list identified by `locator`
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
if not values:
raise ValueError("No value given.")
items_str = "value(s) '%s'" % ", ".join(values)
self._info("Unselecting %s from list '%s'." % (items_str, locator))
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError("Keyword 'Unselect from list' works only for multiselect lists.")
for value in values:
select.deselect_by_value(value)
def unselect_from_list_by_label(self, locator, *labels):
"""Unselects `*labels` from list identified by `locator`
Select list keywords work on both lists and combo boxes. Key attributes for
select lists are `id` and `name`. See `introduction` for details about
locating elements.
"""
if not labels:
raise ValueError("No value given.")
items_str = "label(s) '%s'" % ", ".join(labels)
self._info("Unselecting %s from list '%s'." % (items_str, locator))
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError("Keyword 'Unselect from list' works only for multiselect lists.")
for label in labels:
select.deselect_by_visible_text(label)
# Private
def _get_labels_for_options(self, options):
labels = []
for option in options:
labels.append(option.text)
return labels
def _get_select_list(self, locator):
el = self._element_find(locator, True, True, 'select')
return Select(el)
def _get_select_list_options(self, select_list_or_locator):
if isinstance(select_list_or_locator, Select):
select = select_list_or_locator
else:
select = self._get_select_list(select_list_or_locator)
return select, select.options
def _get_select_list_options_selected(self, locator):
select = self._get_select_list(locator)
# TODO: Handle possible exception thrown by all_selected_options
return select, select.all_selected_options
def _get_values_for_options(self, options):
values = []
for option in options:
values.append(option.get_attribute('value'))
return values
def _is_multiselect_list(self, select):
multiple_value = select.get_attribute('multiple')
if multiple_value is not None and (multiple_value == 'true' or multiple_value == 'multiple'):
return True
return False
def _unselect_all_options_from_multi_select_list(self, select):
self._current_browser().execute_script("arguments[0].selectedIndex = -1;", select)
def _unselect_option_from_multi_select_list(self, select, options, index):
if options[index].is_selected():
options[index].click() | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/keywords/_selectelement.py | 0.727104 | 0.386474 | _selectelement.py | pypi |
from robot.libraries import BuiltIn
from keywordgroup import KeywordGroup
BUILTIN = BuiltIn.BuiltIn()
class _RunOnFailureKeywords(KeywordGroup):
def __init__(self):
self._run_on_failure_keyword = None
self._running_on_failure_routine = False
# Public
def register_keyword_to_run_on_failure(self, keyword):
"""Sets the keyword to execute when a Selenium2Library keyword fails.
`keyword_name` is the name of a keyword (from any available
libraries) that will be executed if a Selenium2Library keyword fails.
It is not possible to use a keyword that requires arguments.
Using the value "Nothing" will disable this feature altogether.
The initial keyword to use is set in `importing`, and the
keyword that is used by default is `Capture Page Screenshot`.
Taking a screenshot when something failed is a very useful
feature, but notice that it can slow down the execution.
This keyword returns the name of the previously registered
failure keyword. It can be used to restore the original
value later.
Example:
| Register Keyword To Run On Failure | Log Source | # Run `Log Source` on failure. |
| ${previous kw}= | Register Keyword To Run On Failure | Nothing | # Disables run-on-failure functionality and stores the previous kw name in a variable. |
| Register Keyword To Run On Failure | ${previous kw} | # Restore to the previous keyword. |
This run-on-failure functionality only works when running tests on Python/Jython 2.4
or newer and it does not work on IronPython at all.
"""
old_keyword = self._run_on_failure_keyword
old_keyword_text = old_keyword if old_keyword is not None else "No keyword"
new_keyword = keyword if keyword.strip().lower() != "nothing" else None
new_keyword_text = new_keyword if new_keyword is not None else "No keyword"
self._run_on_failure_keyword = new_keyword
self._info('%s will be run on failure.' % new_keyword_text)
return old_keyword_text
# Private
def _run_on_failure(self):
if self._run_on_failure_keyword is None:
return
if self._running_on_failure_routine:
return
self._running_on_failure_routine = True
try:
BUILTIN.run_keyword(self._run_on_failure_keyword)
except Exception as err:
self._run_on_failure_error(err)
finally:
self._running_on_failure_routine = False
def _run_on_failure_error(self, err):
err = "Keyword '%s' could not be run on failure: %s" % (self._run_on_failure_keyword, err)
if hasattr(self, '_warn'):
self._warn(err)
return
raise Exception(err) | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/keywords/_runonfailure.py | 0.788217 | 0.209712 | _runonfailure.py | pypi |
import time
import robot
from keywordgroup import KeywordGroup
class _WaitingKeywords(KeywordGroup):
# Public
def wait_for_condition(self, condition, timeout=None, error=None):
"""Waits until the given `condition` is true or `timeout` expires.
The `condition` can be arbitrary JavaScript expression but must contain a
return statement (with the value to be returned) at the end.
See `Execute JavaScript` for information about accessing the
actual contents of the window through JavaScript.
`error` can be used to override the default error message.
See `introduction` for more information about `timeout` and its
default value.
See also `Wait Until Page Contains`, `Wait Until Page Contains
Element`, `Wait Until Element Is Visible` and BuiltIn keyword
`Wait Until Keyword Succeeds`.
"""
if not error:
error = "Condition '%s' did not become true in <TIMEOUT>" % condition
self._wait_until(timeout, error,
lambda: self._current_browser().execute_script(condition) == True)
def wait_until_page_contains(self, text, timeout=None, error=None):
"""Waits until `text` appears on current page.
Fails if `timeout` expires before the text appears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains Element`, `Wait For Condition`,
`Wait Until Element Is Visible` and BuiltIn keyword `Wait Until
Keyword Succeeds`.
"""
if not error:
error = "Text '%s' did not appear in <TIMEOUT>" % text
self._wait_until(timeout, error, self._is_text_present, text)
def wait_until_page_does_not_contain(self, text, timeout=None, error=None):
"""Waits until `text` disappears from current page.
Fails if `timeout` expires before the `text` disappears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait For Condition`,
`Wait Until Element Is Visible` and BuiltIn keyword `Wait Until
Keyword Succeeds`.
"""
def check_present():
present = self._is_text_present(text)
if not present:
return
else:
return error or "Text '%s' did not disappear in %s" % (text, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_present)
def wait_until_page_contains_element(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` appears on current page.
Fails if `timeout` expires before the element appears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait For Condition`,
`Wait Until Element Is Visible` and BuiltIn keyword `Wait Until
Keyword Succeeds`.
"""
if not error:
error = "Element '%s' did not appear in <TIMEOUT>" % locator
self._wait_until(timeout, error, self._is_element_present, locator)
def wait_until_page_does_not_contain_element(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` disappears from current page.
Fails if `timeout` expires before the element disappears. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait For Condition`,
`Wait Until Element Is Visible` and BuiltIn keyword `Wait Until
Keyword Succeeds`.
"""
def check_present():
present = self._is_element_present(locator)
if not present:
return
else:
return error or "Element '%s' did not disappear in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_present)
def wait_until_element_is_visible(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` is visible.
Fails if `timeout` expires before the element is visible. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait Until Page Contains
Element`, `Wait For Condition` and BuiltIn keyword `Wait Until Keyword
Succeeds`.
"""
def check_visibility():
visible = self._is_visible(locator)
if visible:
return
elif visible is None:
return error or "Element locator '%s' did not match any elements after %s" % (locator, self._format_timeout(timeout))
else:
return error or "Element '%s' was not visible in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_visibility)
def wait_until_element_is_not_visible(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` is not visible.
Fails if `timeout` expires before the element is not visible. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait Until Page Contains
Element`, `Wait For Condition` and BuiltIn keyword `Wait Until Keyword
Succeeds`.
"""
def check_hidden():
visible = self._is_visible(locator)
if not visible:
return
elif visible is None:
return error or "Element locator '%s' did not match any elements after %s" % (locator, self._format_timeout(timeout))
else:
return error or "Element '%s' was still visible in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_hidden)
def wait_until_element_is_enabled(self, locator, timeout=None, error=None):
"""Waits until element specified with `locator` is enabled.
Fails if `timeout` expires before the element is enabled. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait Until Page Contains
Element`, `Wait For Condition` and BuiltIn keyword `Wait Until Keyword
Succeeds`.
"""
def check_enabled():
element = self._element_find(locator, True, False)
if not element:
return error or "Element locator '%s' did not match any elements after %s" % (locator, self._format_timeout(timeout))
enabled = not element.get_attribute("disabled")
if enabled:
return
else:
return error or "Element '%s' was not enabled in %s" % (locator, self._format_timeout(timeout))
self._wait_until_no_error(timeout, check_enabled)
def wait_until_element_contains(self, locator, text, timeout=None, error=None):
"""Waits until given element contains `text`.
Fails if `timeout` expires before the text appears on given element. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait Until Page Contains Element`, `Wait For Condition`,
`Wait Until Element Is Visible` and BuiltIn keyword `Wait Until
Keyword Succeeds`.
"""
element = self._element_find(locator, True, True)
def check_text():
actual = element.text
if text in actual:
return
else:
return error or "Text '%s' did not appear in %s to element '%s'. " \
"Its text was '%s'." % (text, self._format_timeout(timeout), locator, actual)
self._wait_until_no_error(timeout, check_text)
def wait_until_element_does_not_contain(self, locator, text, timeout=None, error=None):
"""Waits until given element does not contain `text`.
Fails if `timeout` expires before the text disappears from given element. See
`introduction` for more information about `timeout` and its
default value.
`error` can be used to override the default error message.
See also `Wait Until Page Contains`, `Wait Until Page Contains Element`, `Wait For Condition`,
`Wait Until Element Is Visible` and BuiltIn keyword `Wait Until
Keyword Succeeds`.
"""
element = self._element_find(locator, True, True)
def check_text():
actual = element.text
if not text in actual:
return
else:
return error or "Text '%s' did not disappear in %s from element '%s'." % (text, self._format_timeout(timeout), locator)
self._wait_until_no_error(timeout, check_text)
# Private
def _wait_until(self, timeout, error, function, *args):
error = error.replace('<TIMEOUT>', self._format_timeout(timeout))
def wait_func():
return None if function(*args) else error
self._wait_until_no_error(timeout, wait_func)
def _wait_until_no_error(self, timeout, wait_func, *args):
timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs
maxtime = time.time() + timeout
while True:
timeout_error = wait_func(*args)
if not timeout_error: return
if time.time() > maxtime:
raise AssertionError(timeout_error)
time.sleep(0.2)
def _format_timeout(self, timeout):
timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs
return robot.utils.secs_to_timestr(timeout) | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/keywords/_waiting.py | 0.759671 | 0.296433 | _waiting.py | pypi |
from Selenium2Library import utils
from robot.api import logger
from robot.utils import NormalizedDict
from robot.libraries.BuiltIn import BuiltIn
class ElementFinder(object):
def __init__(self):
strategies = {
'identifier': self._find_by_identifier,
'id': self._find_by_id,
'name': self._find_by_name,
'xpath': self._find_by_xpath,
'dom': self._find_by_dom,
'link': self._find_by_link_text,
'partial link': self._find_by_partial_link_text,
'css': self._find_by_css_selector,
'class': self._find_by_class_name,
'jquery': self._find_by_sizzle_selector,
'sizzle': self._find_by_sizzle_selector,
'tag': self._find_by_tag_name,
'scLocator': self._find_by_sc_locator,
'default': self._find_by_default
}
self._strategies = NormalizedDict(initial=strategies, caseless=True, spaceless=True)
self._default_strategies = list(strategies.keys())
self._locations = {}
def find(self, browser, locator, tag=None):
assert browser is not None
assert locator is not None and len(locator) > 0
(prefix, criteria) = self._parse_locator(locator)
prefix = 'default' if prefix is None else prefix
strategy = self._strategies.get(prefix)
location = self._locations.get(prefix)
if location is not None:
if hasattr(strategy, '__call__'):
locator = strategy(location, criteria)
elif isinstance(strategy, basestring) and len(strategy) > 0:
locator = BuiltIn().run_keyword(strategy, location, criteria)
logger.debug("Get locator via keyword '" + strategy + "': '" + criteria + "' -> '" + locator + "'")
elif isinstance(location, dict):
locator = location.get(criteria, criteria)
logger.debug("Get locator via dictionary: '" + criteria + "' -> '" + locator + "'")
else:
raise ValueError("Invaild strategy '" + str(strategy) + "' with location '"+ str(location) + "'")
if isinstance(locator, basestring):
while locator.find('${') >= 0:
locator = BuiltIn().run_keyword('Replace Variables', locator)
logger.debug("Locator replaced variables: " + locator)
(prefix, criteria) = self._parse_locator(locator)
prefix = 'default' if prefix is None else prefix
strategy = self._strategies.get(prefix)
if strategy is None:
raise ValueError("Element locator with prefix '" + prefix + "' is not supported")
(tag, constraints) = self._get_tag_and_constraints(tag)
return strategy(browser, criteria, tag, constraints)
def register(self, strategy, persist, location):
if strategy.name in self._strategies:
raise AttributeError("The custom locator '" + strategy.name +
"' cannot be registered. A locator of that name already exists.")
self._strategies[strategy.name] = strategy.find if location is None else strategy.finder
self._locations[strategy.name] = location
if not persist:
# Unregister after current scope ends
utils.events.on('scope_end', 'current', self.unregister, strategy.name)
def unregister(self, strategy_name):
if strategy_name in self._default_strategies:
raise AttributeError("Cannot unregister the default strategy '" + strategy_name + "'")
elif strategy_name not in self._strategies:
logger.info("Cannot unregister the non-registered strategy '" + strategy_name + "'")
else:
del self._strategies[strategy_name]
del self._locations[strategy_name]
def has_strategy(self, strategy_name):
return strategy_name in self.strategies
# Strategy routines, private
def _find_by_identifier(self, browser, criteria, tag, constraints):
elements = self._normalize_result(browser.find_elements_by_id(criteria))
elements.extend(self._normalize_result(browser.find_elements_by_name(criteria)))
return self._filter_elements(elements, tag, constraints)
def _find_by_id(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_id(criteria),
tag, constraints)
def _find_by_name(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_name(criteria),
tag, constraints)
def _find_by_xpath(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_xpath(criteria),
tag, constraints)
def _find_by_dom(self, browser, criteria, tag, constraints):
result = browser.execute_script("return %s;" % criteria)
if result is None:
return []
if not isinstance(result, list):
result = [result]
return self._filter_elements(result, tag, constraints)
def _find_by_sizzle_selector(self, browser, criteria, tag, constraints):
js = "return jQuery('%s').get();" % criteria.replace("'", "\\'")
return self._filter_elements(
browser.execute_script(js),
tag, constraints)
def _find_by_link_text(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_link_text(criteria),
tag, constraints)
def _find_by_partial_link_text(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_partial_link_text(criteria),
tag, constraints)
def _find_by_css_selector(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_css_selector(criteria),
tag, constraints)
def _find_by_class_name(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_class_name(criteria),
tag, constraints)
def _find_by_tag_name(self, browser, criteria, tag, constraints):
return self._filter_elements(
browser.find_elements_by_tag_name(criteria),
tag, constraints)
def _find_by_sc_locator(self, browser, criteria, tag, constraints):
js = "return isc.AutoTest.getElement('%s')" % criteria.replace("'", "\\'")
return self._filter_elements([browser.execute_script(js)], tag, constraints)
def _find_by_default(self, browser, criteria, tag, constraints):
if criteria.startswith('//'):
return self._find_by_xpath(browser, criteria, tag, constraints)
return self._find_by_key_attrs(browser, criteria, tag, constraints)
def _find_by_key_attrs(self, browser, criteria, tag, constraints):
key_attrs = self._key_attrs.get(None)
if tag is not None:
key_attrs = self._key_attrs.get(tag, key_attrs)
xpath_criteria = utils.escape_xpath_value(criteria)
xpath_tag = tag if tag is not None else '*'
xpath_constraints = ["@%s='%s'" % (name, constraints[name]) for name in constraints]
xpath_searchers = ["%s=%s" % (attr, xpath_criteria) for attr in key_attrs]
xpath_searchers.extend(
self._get_attrs_with_url(key_attrs, criteria, browser))
xpath = "//%s[%s(%s)]" % (
xpath_tag,
' and '.join(xpath_constraints) + ' and ' if len(xpath_constraints) > 0 else '',
' or '.join(xpath_searchers))
return self._normalize_result(browser.find_elements_by_xpath(xpath))
# Private
_key_attrs = {
None: ['@id', '@name'],
'a': ['@id', '@name', '@href', 'normalize-space(descendant-or-self::text())'],
'img': ['@id', '@name', '@src', '@alt'],
'input': ['@id', '@name', '@value', '@src'],
'button': ['@id', '@name', '@value', 'normalize-space(descendant-or-self::text())']
}
def _get_tag_and_constraints(self, tag):
if tag is None: return None, {}
tag = tag.lower()
constraints = {}
if tag == 'link':
tag = 'a'
if tag == 'partial link':
tag = 'a'
elif tag == 'image':
tag = 'img'
elif tag == 'list':
tag = 'select'
elif tag == 'radio button':
tag = 'input'
constraints['type'] = 'radio'
elif tag == 'checkbox':
tag = 'input'
constraints['type'] = 'checkbox'
elif tag == 'text field':
tag = 'input'
constraints['type'] = 'text'
elif tag == 'file upload':
tag = 'input'
constraints['type'] = 'file'
elif tag == 'text area':
tag = 'textarea'
return tag, constraints
def _element_matches(self, element, tag, constraints):
if not element.tag_name.lower() == tag:
return False
for name in constraints:
if not element.get_attribute(name) == constraints[name]:
return False
return True
def _filter_elements(self, elements, tag, constraints):
elements = self._normalize_result(elements)
if tag is None: return elements
return [element for element in elements if self._element_matches(element, tag, constraints)]
def _get_attrs_with_url(self, key_attrs, criteria, browser):
attrs = []
url = None
xpath_url = None
for attr in ['@src', '@href']:
if attr in key_attrs:
if url is None or xpath_url is None:
url = self._get_base_url(browser) + "/" + criteria
xpath_url = utils.escape_xpath_value(url)
attrs.append("%s=%s" % (attr, xpath_url))
return attrs
def _get_base_url(self, browser):
url = browser.get_current_url()
if '/' in url:
url = '/'.join(url.split('/')[:-1])
return url
def _parse_locator(self, locator):
prefix = None
criteria = locator
if not locator.startswith('//'):
locator_parts = locator.partition('=')
if len(locator_parts[1]) > 0:
prefix = locator_parts[0]
criteria = locator_parts[2].strip()
return (prefix, criteria)
def _normalize_result(self, elements):
if not isinstance(elements, list):
logger.debug("WebDriver find returned %s" % elements)
return []
return elements | /robotframework-selenium2library-divfor-1.8.1.tar.gz/robotframework-selenium2library-divfor-1.8.1/src/Selenium2Library/locators/elementfinder.py | 0.716318 | 0.164181 | elementfinder.py | pypi |
from .version import VERSION
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
from robot.api import logger
from .attribute import AttributeHelper
from .click import ClickHelper
from .frame import FrameHelper
from .input import InputHelper
from .select import SelectHelper
from .textarea import TextareaHelper
from .title import TitleHelper
from .wait import WaitHelper
from .text import TextHelper
from .link import LinkHelper
from .button import ButtonHelper
from .web_element import WebElementHelper
from .util import Util
class SeleniumHelperLibrary(AttributeHelper, ClickHelper,
FrameHelper, InputHelper, SelectHelper, TextareaHelper, TitleHelper, WaitHelper,
LinkHelper, ButtonHelper, WebElementHelper, TextHelper):
"""
Core Principal:
Achieve synchronization before performing any action on ``WebElement``
Every ``Keyword`` consist following steps
- Wait For WebElement
- Scroll To WebElement (ignores scroll issue)
- Perform Respective Action
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = VERSION
def __init__(self):
pass
@keyword("Scroll By Coordinates")
def scroll_by_coordinates(self, x, y):
"""
Perform scroll in webpage based on co-ordinates
"""
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
js = "window.scroll({x},{y})".format(x=x, y=y)
self.sellib.execute_javascript(js)
@keyword("Should Contain With Screenshot")
def should_contain_with_screenshot(self, actual, expected):
"""
Validates `actual` contains `expected` value.
- Captures screenshot if failed
"""
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
isPassed = BuiltIn().run_keyword_and_return_status("BuiltIn.Should Contain", actual, expected)
if not isPassed:
error_msg = "{expected_value} is not found in {actual_value}".format(expected_value=expected, actual_value=actual)
Util.log_failure(self, self.sellib, error_msg)
@keyword("Should Not Contain With Screenshot")
def should_not_contain_with_screenshot(self, actual, expected):
"""
Validates `actual` not contains `expected` value.
- Captures screenshot if failed
"""
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
isPassed = BuiltIn().run_keyword_and_return_status("BuiltIn.Should Not Contain", actual, expected)
if not isPassed:
error_msg = "{expected_value} is not found in {actual_value}".format(expected_value=expected, actual_value=actual)
Util.log_failure(self, self.sellib, error_msg)
@keyword("Should Be Equal As Strings With Screenshot")
def should_be_equal_as_strings_with_screenshot(self, actual, expected):
"""
Validates `actual` equals `expected` value.
- Captures screenshot if failed
"""
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
isPassed = BuiltIn().run_keyword_and_return_status("BuiltIn.Should Be Equal As Strings", actual, expected)
if not isPassed:
error_msg = "{expected_value} is not same as {actual_value}".format(expected_value=expected, actual_value=actual)
Util.log_failure(self, self.sellib, error_msg)
@keyword("Reload Webpage")
def reload_webpage(self):
"""
Performs reload in webpage and waits until dom get loaded
"""
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
self.sellib.reload_page()
BuiltIn().run_keyword("SeleniumHelperLibrary.Wait Until DOM Loaded") | /robotframework_seleniumhelperlibrary-0.1.8-py3-none-any.whl/SeleniumHelperLibrary/helper.py | 0.731634 | 0.270784 | helper.py | pypi |
from .version import VERSION
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
from robot.api import logger
from .util import Util
class WebElementHelper(Util):
def __init__(self):
pass
@keyword("WebElement By Text Should Be Present")
def webelement_by_text_should_be_present(self, text, index="last()"):
"""
Wait for webelement with exact `text` present in web page
- uses ``(//*[normalize-space()='{text}'])[{index}]`` locator internally
"""
locator = "(//*[normalize-space()='{text}'])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("WebElement By Text Should Not Be Present")
def webelement_by_text_should_not_be_present(self, text, index="last()"):
"""
Wait for webelement with exact `text` present in web page
- uses ``(//*[normalize-space()='{text}'])[{index}]`` locator internally
"""
locator = "(//*[normalize-space()='{text}'])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element_not_present(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On WebElement By Text")
def click_on_webelement_by_text(self, text, index="last()"):
"""
Wait for webelement with exact `text` present in web page
- uses ``(//*[normalize-space()='{text}'])[{index}]`` locator internally
"""
locator = "(//*[normalize-space()='{text}'])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
self.sellib.click_element(locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On WebElement By Text With Retry")
def click_on_webelement_by_text_with_retry(self, text, index="last()", retry="3x", retry_interval="2s"):
"""
Similar to `Click On WebElement` with retry
"""
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumHelperLibrary.Click On WebElement By Text", text, index)
@keyword("WebElement With Text Should Be Present")
def webelement_with_text_should_be_present(self, text, index="last()"):
"""
Wait for webelement contains `text` present in web page
- uses ``(//*[contains(normalize-space(),'{text}')])[{index}]`` locator internally
"""
locator = "(//*[contains(normalize-space(),'{text}')])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("WebElement With Text Should Not Be Present")
def webelement_with_text_should_not_be_present(self, text, index="last()"):
"""
Wait for webelement contains `text` not present in web page
- uses ``(//*[contains(normalize-space(),'{text}')])[{index}]`` locator internally
"""
locator = "(//*[contains(normalize-space(),'{text}')])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element_not_present(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On WebElement With Text")
def click_on_webelement_with_text(self, text, index="last()"):
"""
Wait for webelement contains `text` present in web page then scroll to element and perform click operation
- uses ``(//*[contains(normalize-space(),'{text}')])[{index}]`` locator internally
"""
locator = "(//*[contains(normalize-space(),'{text}')])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
self.sellib.click_element(locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On WebElement With Text Retry")
def click_on_webelement_with_text_retry(self, text, index="last()", retry="3x", retry_interval="2s"):
"""
Similar to `Click On WebElement By Text` with retry
"""
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumHelperLibrary.Click On WebElement With Text", text, index)
@keyword("WebElement By Title Should Be Present")
def webelement_by_title_should_be_present(self, title, index="last()"):
"""
Wait for webelement with ``@title`` attribute contains value present in web page
- uses ``(//*[contains(normalize-space(@title),'{title}')])[{index}]`` locator internally
"""
locator = "(//*[contains(normalize-space(@title),'{title}')])[{index}]".format(title=title, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("WebElement By Title Should Not Be Present")
def webelement_by_title_should_not_be_present(self, title, index="last()"):
"""
Wait for webelement with ``@title`` attribute contains value not present in web page
- uses ``(//*[contains(normalize-space(@title),'{title}')])[{index}]`` locator internally
"""
locator = "(//*[contains(normalize-space(@title),'{title}')])[{index}]".format(title=title, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element_not_present(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On WebElement By Title")
def click_on_webelement_by_title(self, title, index="last()"):
"""
Wait for webelement with ``@title`` attribute contains value then scroll to element & perform click action on element in web page
- uses ``(//*[contains(normalize-space(@title),'{title}')])[{index}]`` locator internally
"""
locator = "(//*[contains(normalize-space(@title),'{title}')])[{index}]".format(title=title, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
self.sellib.click_element(locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On WebElement By Title With Retry")
def click_on_webelement_by_title_with_retry(self, title, index="last()", retry="3x", retry_interval="2s"):
"""
Similar to `Click On WebElement By Title` with retry
"""
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumHelperLibrary.Click On WebElement By Title", title, index)
@keyword("WebElement By Attribute Should Be Present")
def webelement_by_attribute_should_be_present(self, attribute, value, index="last()"):
"""
Wait for webelement with ``@attribute`` & ``value`` present in web page
- uses ``(//*[contains(normalize-space(@{attribute}),'{value}')])[{index}]`` locator internally
"""
locator = "(//*[contains(normalize-space(@{attribute}),'{value}')])[{index}]".format(attribute=attribute, value=value, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("WebElement By Attribute Should Not Be Present")
def webelement_by_attribute_should_not_be_present(self, attribute, value, index="last()"):
"""
Wait for webelement with ``@attribute`` & ``value`` not present in web page
- uses ``(//*[contains(normalize-space(@{attribute}),'{value}')])[{index}]`` locator internally
"""
locator = "(//*[contains(normalize-space(@{attribute}),'{value}')])[{index}]".format(attribute=attribute, value=value, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element_not_present(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On WebElement By Attribute")
def click_on_webelement_by_attribute(self, attribute, value, index="last()"):
"""
Wait for webelement with ``@attribute`` & ``value`` present in web page then scroll to element & perform click operation
- uses ``(//*[contains(normalize-space(@{attribute}),'{value}')])[{index}]`` locator internally
"""
locator = "(//*[contains(normalize-space(@{attribute}),'{value}')])[{index}]".format(attribute=attribute, value=value, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
self.sellib.click_element(locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On WebElement By Attribute With Retry")
def click_on_webelement_by_attribute_with_retry(self, attribute, value, index="last()", retry="3x", retry_interval="2s"):
"""
Similar to `Click On WebElement By Attribute` with retry
"""
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumHelperLibrary.Click On WebElement By Attribute", attribute, value, index) | /robotframework_seleniumhelperlibrary-0.1.8-py3-none-any.whl/SeleniumHelperLibrary/web_element.py | 0.616359 | 0.237112 | web_element.py | pypi |
from .version import VERSION
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
from robot.api import logger
from .util import Util
class LinkHelper(Util):
def __init__(self):
pass
@keyword("Link Should Be Present")
def link_should_be_present(self, text, index="last()"):
"""
Wait for link with exact ``text`` present in web page
- uses ``(//a[normalize-space()='{text}'])[{index}]`` locator internally
"""
locator = "(//a[normalize-space()='{text}'])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Link Should Not Be Present")
def link_should_not_be_present(self, text, index="last()"):
"""
Wait for link with exact ``text`` present in web page
- uses ``(//a[normalize-space()='{text}'])[{index}]`` locator internally
"""
locator = "(//a[normalize-space()='{text}'])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element_not_present(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On Link")
def click_on_link(self, text, index="last()"):
"""
Wait for link with exact ``text`` present in web page
- uses ``(//a[normalize-space()='{text}'])[{index}]`` locator internally
"""
locator = "(//a[normalize-space()='{text}'])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
self.sellib.click_element(locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On Link With Retry")
def click_on_link_with_retry(self, text, retry="3x", retry_interval="2s"):
"""
Similar to `Click On Link` with retry
"""
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumHelperLibrary.Click On Link", text)
@keyword("Link By Text Should Be Present")
def link_by_text_should_be_present(self, text, index="last()"):
"""
Wait for link contains ``text`` present in web page
- uses ``(//a[contains(normalize-space(),'{text}')])[{index}]`` locator internally
"""
locator = "(//a[contains(normalize-space(),'{text}')])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Link By Text Should Not Be Present")
def link_by_text_should_not_be_present(self, text, index="last()"):
"""
Wait for link contains ``text`` not present in web page
- uses ``(//a[contains(normalize-space(),'{text}')])[{index}]`` locator internally
"""
locator = "(//a[contains(normalize-space(),'{text}')])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element_not_present(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On Link By Text")
def click_on_link_by_text(self, text, index="last()"):
"""
Wait for link contains ``text`` present in web page then scroll to element & perform click operation
- uses ``(//a[contains(normalize-space(),'{text}')])[{index}]`` locator internally
"""
locator = "(//a[contains(normalize-space(),'{text}')])[{index}]".format(text=text, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
self.sellib.click_element(locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On Link By Text With Retry")
def click_on_link_by_text_with_retry(self, text, index="last()", retry="3x", retry_interval="2s"):
"""
Similar to `Click On Link By Text` with retry
"""
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumHelperLibrary.Click On Link By Text", text, index)
@keyword("Link By Title Should Be Present")
def link_by_title_should_be_present(self, title, index="last()"):
"""
Wait for link with ``@title`` attribute contains value present in web page
- uses ``(//a[contains(normalize-space(@title),'{title}')])[{index}]`` locator internally
"""
locator = "(//a[contains(normalize-space(@title),'{title}')])[{index}]".format(title=title, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Link By Title Should Not Be Present")
def link_by_title_should_not_be_present(self, title, index="last()"):
"""
Wait for link with ``@title`` attribute contains value not present in web page
- uses ``(//a[contains(normalize-space(@title),'{title}')])[{index}]`` locator internally
"""
locator = "(//a[contains(normalize-space(@title),'{title}')])[{index}]".format(title=title, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element_not_present(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On Link By Title")
def click_on_link_by_title(self, title, index="last()"):
"""
Wait for link with ``@title`` attribute contains value present in web page then scroll to element & perform click
- uses ``(//a[contains(normalize-space(@title),'{title}')])[{index}]`` locator internally
"""
locator = "(//a[contains(normalize-space(@title),'{title}')])[{index}]".format(title=title, index=index)
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
self.sellib.click_element(locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Click On Link By Title With Retry")
def click_on_link_by_title_with_retry(self, title, index="last()", retry="3x", retry_interval="2s"):
"""
Similar to `Click On Link By Title` with retry
"""
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumHelperLibrary.Click On Link By Title", title, index) | /robotframework_seleniumhelperlibrary-0.1.8-py3-none-any.whl/SeleniumHelperLibrary/link.py | 0.568775 | 0.157137 | link.py | pypi |
from .version import VERSION
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
from robot.api import logger
from .util import Util
class WaitHelper(Util):
def __init__(self):
pass
@keyword("Wait Until Element Is Visible With Retry")
def wait_until_element_is_visible_with_retry(self, locator, retry="3x", retry_interval="2s"):
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumLibrary.Wait Until Element Is Visible", locator)
@keyword("Wait Until Element Is Not Visible With Retry")
def wait_until_element_is_not_visible_with_retry(self, locator, retry="3x", retry_interval="2s"):
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumLibrary.Wait Until Element Is Not Visible", locator)
@keyword("Wait Until Page Contains With Retry")
def wait_until_page_contains_with_retry(self, text, retry="3x", retry_interval="2s"):
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumLibrary.Wait Until Page Contains", text)
@keyword("Wait Until Page Does Not Contain With Retry")
def wait_until_page_does_not_contain_with_retry(self, text, retry="3x", retry_interval="2s"):
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumLibrary.Wait Until Page Does Not Contain", text)
@keyword("Wait Until Page Contains Element With Retry")
def wait_until_page_contains_element_with_retry(self, locator, retry="3x", retry_interval="2s"):
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumLibrary.Wait Until Page Contains Element", locator)
@keyword("Wait Until Page Does Not Contain Element With Retry")
def wait_until_page_does_not_contain_element_with_retry(self, locator, retry="3x", retry_interval="2s"):
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumLibrary.Wait Until Page Does Not Contain Element", locator)
@keyword("Wait For WebElement")
def wait_for_webelement(self, locator):
"""
Wait for `locator` present in webpage then scroll to element
"""
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Wait For WebElement Disappear")
def wait_for_webelement_disappear(self, locator):
"""
Wait for `locator` not present in webpage
"""
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
Util.wait_for_element_not_present(self, self.sellib, locator)
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Wait For WebElement With Retry")
def wait_for_webelement_with_retry(self, locator, retry="3x", retry_interval="2s"):
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumHelperLibrary.Wait For WebElement", locator)
@keyword("Wait For WebElement Disappear With Retry")
def wait_for_webelement_disappear_with_retry(self, locator, retry="3x", retry_interval="2s"):
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumHelperLibrary.Wait For WebElement Disappear", locator)
@keyword("Wait Until DOM Loaded")
def wait_until_dom_loaded(self):
"""
Wait until dom loaded in web page
"""
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
try:
self.sellib.wait_for_condition('return window.document.readyState === "complete"')
except Exception as e:
Util.log_failure(self, self.sellib, e)
@keyword("Wait Until Element Contains With Retry")
def wait_until_element_contains_with_retry(self, locator, value, retry="3x", retry_interval="2s"):
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
Util.wait_for_element(self, self.sellib, locator)
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumLibrary.Wait Until Element Contains", locator, value)
@keyword("Wait Until Element Does Not Contain With Retry")
def wait_until_element_does_not_contain_with_retry(self, locator, value, retry="3x", retry_interval="2s"):
self.sellib = BuiltIn().get_library_instance('SeleniumLibrary')
Util.wait_for_element(self, self.sellib, locator)
BuiltIn().wait_until_keyword_succeeds(retry, retry_interval, "SeleniumLibrary.Wait Until Element Does Not Contain", locator, value) | /robotframework_seleniumhelperlibrary-0.1.8-py3-none-any.whl/SeleniumHelperLibrary/wait.py | 0.666497 | 0.181753 | wait.py | pypi |
from collections import namedtuple
from datetime import timedelta
from inspect import getdoc, isclass
from typing import Optional, List
from robot.api import logger
from robot.errors import DataError
from robot.libraries.BuiltIn import BuiltIn
from robot.utils import is_string
from robot.utils.importer import Importer
from robotlibcore import DynamicCore
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from SeleniumLibrary.base import LibraryComponent
from SeleniumLibrary.errors import NoOpenBrowser, PluginError
from SeleniumLibrary.keywords import (
AlertKeywords,
BrowserManagementKeywords,
CookieKeywords,
ElementKeywords,
FormElementKeywords,
FrameKeywords,
JavaScriptKeywords,
RunOnFailureKeywords,
ScreenshotKeywords,
SelectElementKeywords,
TableElementKeywords,
WaitingKeywords,
WebDriverCache,
WindowKeywords,
)
from SeleniumLibrary.keywords.screenshot import EMBED
from SeleniumLibrary.locators import ElementFinder
from SeleniumLibrary.utils import LibraryListener, is_truthy, _convert_timeout, _convert_delay
__version__ = "6.1.2rc1"
class SeleniumLibrary(DynamicCore):
"""SeleniumLibrary is a web testing library for Robot Framework.
This document explains how to use keywords provided by SeleniumLibrary.
For information about installation, support, and more, please visit the
[https://github.com/robotframework/SeleniumLibrary|project pages].
For more information about Robot Framework, see http://robotframework.org.
SeleniumLibrary uses the Selenium WebDriver modules internally to
control a web browser. See http://seleniumhq.org for more information
about Selenium in general and SeleniumLibrary README.rst
[https://github.com/robotframework/SeleniumLibrary#browser-drivers|Browser drivers chapter]
for more details about WebDriver binary installation.
%TOC%
= Locating elements =
All keywords in SeleniumLibrary that need to interact with an element
on a web page take an argument typically named ``locator`` that specifies
how to find the element. Most often the locator is given as a string
using the locator syntax described below, but `using WebElements` is
possible too.
== Locator syntax ==
SeleniumLibrary supports finding elements based on different strategies
such as the element id, XPath expressions, or CSS selectors. The strategy
can either be explicitly specified with a prefix or the strategy can be
implicit.
=== Default locator strategy ===
By default, locators are considered to use the keyword specific default
locator strategy. All keywords support finding elements based on ``id``
and ``name`` attributes, but some keywords support additional attributes
or other values that make sense in their context. For example, `Click
Link` supports the ``href`` attribute and the link text and addition
to the normal ``id`` and ``name``.
Examples:
| `Click Element` | example | # Match based on ``id`` or ``name``. |
| `Click Link` | example | # Match also based on link text and ``href``. |
| `Click Button` | example | # Match based on ``id``, ``name`` or ``value``. |
If a locator accidentally starts with a prefix recognized as `explicit
locator strategy` or `implicit XPath strategy`, it is possible to use
the explicit ``default`` prefix to enable the default strategy.
Examples:
| `Click Element` | name:foo | # Find element with name ``foo``. |
| `Click Element` | default:name:foo | # Use default strategy with value ``name:foo``. |
| `Click Element` | //foo | # Find element using XPath ``//foo``. |
| `Click Element` | default: //foo | # Use default strategy with value ``//foo``. |
=== Explicit locator strategy ===
The explicit locator strategy is specified with a prefix using either
syntax ``strategy:value`` or ``strategy=value``. The former syntax
is preferred because the latter is identical to Robot Framework's
[http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#named-argument-syntax|
named argument syntax] and that can cause problems. Spaces around
the separator are ignored, so ``id:foo``, ``id: foo`` and ``id : foo``
are all equivalent.
Locator strategies that are supported by default are listed in the table
below. In addition to them, it is possible to register `custom locators`.
| = Strategy = | = Match based on = | = Example = |
| id | Element ``id``. | ``id:example`` |
| name | ``name`` attribute. | ``name:example`` |
| identifier | Either ``id`` or ``name``. | ``identifier:example`` |
| class | Element ``class``. | ``class:example`` |
| tag | Tag name. | ``tag:div`` |
| xpath | XPath expression. | ``xpath://div[@id="example"]`` |
| css | CSS selector. | ``css:div#example`` |
| dom | DOM expression. | ``dom:document.images[5]`` |
| link | Exact text a link has. | ``link:The example`` |
| partial link | Partial link text. | ``partial link:he ex`` |
| sizzle | Sizzle selector deprecated. | ``sizzle:div.example`` |
| data | Element ``data-*`` attribute | ``data:id:my_id`` |
| jquery | jQuery expression. | ``jquery:div.example`` |
| default | Keyword specific default behavior. | ``default:example`` |
See the `Default locator strategy` section below for more information
about how the default strategy works. Using the explicit ``default``
prefix is only necessary if the locator value itself accidentally
matches some of the explicit strategies.
Different locator strategies have different pros and cons. Using ids,
either explicitly like ``id:foo`` or by using the `default locator
strategy` simply like ``foo``, is recommended when possible, because
the syntax is simple and locating elements by id is fast for browsers.
If an element does not have an id or the id is not stable, other
solutions need to be used. If an element has a unique tag name or class,
using ``tag``, ``class`` or ``css`` strategy like ``tag:h1``,
``class:example`` or ``css:h1.example`` is often an easy solution. In
more complex cases using XPath expressions is typically the best
approach. They are very powerful but a downside is that they can also
get complex.
Examples:
| `Click Element` | id:foo | # Element with id 'foo'. |
| `Click Element` | css:div#foo h1 | # h1 element under div with id 'foo'. |
| `Click Element` | xpath: //div[@id="foo"]//h1 | # Same as the above using XPath, not CSS. |
| `Click Element` | xpath: //*[contains(text(), "example")] | # Element containing text 'example'. |
*NOTE:*
- The ``strategy:value`` syntax is only supported by SeleniumLibrary 3.0
and newer.
- Using the ``sizzle`` strategy or its alias ``jquery`` requires that
the system under test contains the jQuery library.
- Prior to SeleniumLibrary 3.0, table related keywords only supported
``xpath``, ``css`` and ``sizzle/jquery`` strategies.
- ``data`` strategy is conveniance locator that will construct xpath from the parameters.
If you have element like `<div data-automation="automation-id-2">`, you locate the element via
``data:automation:automation-id-2``. This feature was added in SeleniumLibrary 5.2.0
=== Implicit XPath strategy ===
If the locator starts with ``//`` or multiple opening parenthesis in front
of the ``//``, the locator is considered to be an XPath expression. In other
words, using ``//div`` is equivalent to using explicit ``xpath://div`` and
``((//div))`` is equivalent to using explicit ``xpath:((//div))``
Examples:
| `Click Element` | //div[@id="foo"]//h1 |
| `Click Element` | (//div)[2] |
The support for the ``(//`` prefix is new in SeleniumLibrary 3.0.
Supporting multiple opening parenthesis is new in SeleniumLibrary 5.0.
=== Chaining locators ===
It is possible chain multiple locators together as single locator. Each chained locator must start with locator
strategy. Chained locators must be separated with single space, two greater than characters and followed with
space. It is also possible mix different locator strategies, example css or xpath. Also a list can also be
used to specify multiple locators. This is useful, is some part of locator would match as the locator separator
but it should not. Or if there is need to existing WebElement as locator.
Although all locators support chaining, some locator strategies do not abey the chaining. This is because
some locator strategies use JavaScript to find elements and JavaScript is executed for the whole browser context
and not for the element found be the previous locator. Chaining is supported by locator strategies which
are based on Selenium API, like `xpath` or `css`, but example chaining is not supported by `sizzle` or `jquery
Examples:
| `Click Element` | css:.bar >> xpath://a | # To find a link which is present after an element with class "bar" |
List examples:
| ${locator_list} = | `Create List` | css:div#div_id | xpath://*[text(), " >> "] |
| `Page Should Contain Element` | ${locator_list} | | |
| ${element} = | Get WebElement | xpath://*[text(), " >> "] | |
| ${locator_list} = | `Create List` | css:div#div_id | ${element} |
| `Page Should Contain Element` | ${locator_list} | | |
Chaining locators in new in SeleniumLibrary 5.0
== Using WebElements ==
In addition to specifying a locator as a string, it is possible to use
Selenium's WebElement objects. This requires first getting a WebElement,
for example, by using the `Get WebElement` keyword.
| ${elem} = | `Get WebElement` | id:example |
| `Click Element` | ${elem} | |
== Custom locators ==
If more complex lookups are required than what is provided through the
default locators, custom lookup strategies can be created. Using custom
locators is a two part process. First, create a keyword that returns
a WebElement that should be acted on:
| Custom Locator Strategy | [Arguments] | ${browser} | ${locator} | ${tag} | ${constraints} |
| | ${element}= | Execute Javascript | return window.document.getElementById('${locator}'); |
| | [Return] | ${element} |
This keyword is a reimplementation of the basic functionality of the
``id`` locator where ``${browser}`` is a reference to a WebDriver
instance and ``${locator}`` is the name of the locator strategy. To use
this locator, it must first be registered by using the
`Add Location Strategy` keyword:
| `Add Location Strategy` | custom | Custom Locator Strategy |
The first argument of `Add Location Strategy` specifies the name of
the strategy and it must be unique. After registering the strategy,
the usage is the same as with other locators:
| `Click Element` | custom:example |
See the `Add Location Strategy` keyword for more details.
= Browser and Window =
There is different conceptual meaning when SeleniumLibrary talks
about windows or browsers. This chapter explains those differences.
== Browser ==
When `Open Browser` or `Create WebDriver` keyword is called, it
will create a new Selenium WebDriver instance by using the
[https://www.seleniumhq.org/docs/03_webdriver.jsp|Selenium WebDriver]
API. In SeleniumLibrary terms, a new browser is created. It is
possible to start multiple independent browsers (Selenium Webdriver
instances) at the same time, by calling `Open Browser` or
`Create WebDriver` multiple times. These browsers are usually
independent of each other and do not share data like cookies,
sessions or profiles. Typically when the browser starts, it
creates a single window which is shown to the user.
== Window ==
Windows are the part of a browser that loads the web site and presents
it to the user. All content of the site is the content of the window.
Windows are children of a browser. In SeleniumLibrary browser is a
synonym for WebDriver instance. One browser may have multiple
windows. Windows can appear as tabs, as separate windows or pop-ups with
different position and size. Windows belonging to the same browser
typically share the sessions detail, like cookies. If there is a
need to separate sessions detail, example login with two different
users, two browsers (Selenium WebDriver instances) must be created.
New windows can be opened example by the application under test or
by example `Execute Javascript` keyword:
| `Execute Javascript` window.open() # Opens a new window with location about:blank
The example below opens multiple browsers and windows,
to demonstrate how the different keywords can be used to interact
with browsers, and windows attached to these browsers.
Structure:
| BrowserA
| Window 1 (location=https://robotframework.org/)
| Window 2 (location=https://robocon.io/)
| Window 3 (location=https://github.com/robotframework/)
|
| BrowserB
| Window 1 (location=https://github.com/)
Example:
| `Open Browser` | https://robotframework.org | ${BROWSER} | alias=BrowserA | # BrowserA with first window is opened. |
| `Execute Javascript` | window.open() | | | # In BrowserA second window is opened. |
| `Switch Window` | locator=NEW | | | # Switched to second window in BrowserA |
| `Go To` | https://robocon.io | | | # Second window navigates to robocon site. |
| `Execute Javascript` | window.open() | | | # In BrowserA third window is opened. |
| ${handle} | `Switch Window` | locator=NEW | | # Switched to third window in BrowserA |
| `Go To` | https://github.com/robotframework/ | | | # Third windows goes to robot framework github site. |
| `Open Browser` | https://github.com | ${BROWSER} | alias=BrowserB | # BrowserB with first windows is opened. |
| ${location} | `Get Location` | | | # ${location} is: https://www.github.com |
| `Switch Window` | ${handle} | browser=BrowserA | | # BrowserA second windows is selected. |
| ${location} | `Get Location` | | | # ${location} = https://robocon.io/ |
| @{locations 1} | `Get Locations` | | | # By default, lists locations under the currectly active browser (BrowserA). |
| @{locations 2} | `Get Locations` | browser=ALL | | # By using browser=ALL argument keyword list all locations from all browsers. |
The above example, @{locations 1} contains the following items:
https://robotframework.org/, https://robocon.io/ and
https://github.com/robotframework/'. The @{locations 2}
contains the following items: https://robotframework.org/,
https://robocon.io/, https://github.com/robotframework/'
and 'https://github.com/.
= Timeouts, waits, and delays =
This section discusses different ways how to wait for elements to
appear on web pages and to slow down execution speed otherwise.
It also explains the `time format` that can be used when setting various
timeouts, waits, and delays.
== Timeout ==
SeleniumLibrary contains various keywords that have an optional
``timeout`` argument that specifies how long these keywords should
wait for certain events or actions. These keywords include, for example,
``Wait ...`` keywords and keywords related to alerts. Additionally
`Execute Async Javascript`. Although it does not have ``timeout``,
argument, uses a timeout to define how long asynchronous JavaScript
can run.
The default timeout these keywords use can be set globally either by
using the `Set Selenium Timeout` keyword or with the ``timeout`` argument
when `importing` the library. If no default timeout is set globally, the
default is 5 seconds. If None is specified for the timeout argument in the
keywords, the default is used. See `time format` below for supported
timeout syntax.
== Implicit wait ==
Implicit wait specifies the maximum time how long Selenium waits when
searching for elements. It can be set by using the `Set Selenium Implicit
Wait` keyword or with the ``implicit_wait`` argument when `importing`
the library. See [https://www.seleniumhq.org/docs/04_webdriver_advanced.jsp|
Selenium documentation] for more information about this functionality.
See `time format` below for supported syntax.
== Page load ==
Page load timeout is the amount of time to wait for page load to complete until error is raised.
The default page load timeout can be set globally
when `importing` the library with the ``page_load_timeout`` argument
or by using the `Set Selenium Page Load Timeout` keyword.
See `time format` below for supported timeout syntax.
Support for page load is new in SeleniumLibrary 6.1
== Selenium speed ==
Selenium execution speed can be slowed down globally by using `Set
Selenium speed` keyword. This functionality is designed to be used for
demonstrating or debugging purposes. Using it to make sure that elements
appear on a page is not a good idea. The above-explained timeouts
and waits should be used instead.
See `time format` below for supported syntax.
== Time format ==
All timeouts and waits can be given as numbers considered seconds
(e.g. ``0.5`` or ``42``) or in Robot Framework's time syntax
(e.g. ``1.5 seconds`` or ``1 min 30 s``). For more information about
the time syntax see the
[http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#time-format|Robot Framework User Guide].
= Run-on-failure functionality =
SeleniumLibrary has a handy feature that it can automatically execute
a keyword if any of its own keywords fails. By default, it uses the
`Capture Page Screenshot` keyword, but this can be changed either by
using the `Register Keyword To Run On Failure` keyword or with the
``run_on_failure`` argument when `importing` the library. It is
possible to use any keyword from any imported library or resource file.
The run-on-failure functionality can be disabled by using a special value
``NOTHING`` or anything considered false (see `Boolean arguments`)
such as ``NONE``.
= Boolean arguments =
Starting from 5.0 SeleniumLibrary relies on Robot Framework to perform the
boolean conversion based on keyword arguments [https://docs.python.org/3/library/typing.html|type hint].
More details in Robot Framework
[http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#supported-conversions|user guide]
Please note SeleniumLibrary 3 and 4 did have own custom methods to covert
arguments to boolean values.
= EventFiringWebDriver =
The SeleniumLibrary offers support for
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.event_firing_webdriver.html#module-selenium.webdriver.support.event_firing_webdriver|EventFiringWebDriver].
See the Selenium and SeleniumLibrary
[https://github.com/robotframework/SeleniumLibrary/blob/master/docs/extending/extending.rst#EventFiringWebDriver|EventFiringWebDriver support]
documentation for further details.
EventFiringWebDriver is new in SeleniumLibrary 4.0
= Thread support =
SeleniumLibrary is not thread-safe. This is mainly due because the underlying
[https://github.com/SeleniumHQ/selenium/wiki/Frequently-Asked-Questions#q-is-webdriver-thread-safe|
Selenium tool is not thread-safe] within one browser/driver instance.
Because of the limitation in the Selenium side, the keywords or the
API provided by the SeleniumLibrary is not thread-safe.
= Plugins =
SeleniumLibrary offers plugins as a way to modify and add library keywords and modify some of the internal
functionality without creating a new library or hacking the source code. See
[https://github.com/robotframework/SeleniumLibrary/blob/master/docs/extending/extending.rst#Plugins|plugin API]
documentation for further details.
Plugin API is new SeleniumLibrary 4.0
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_VERSION = __version__
def __init__(
self,
timeout=timedelta(seconds=5),
implicit_wait=timedelta(seconds=0),
run_on_failure="Capture Page Screenshot",
screenshot_root_directory: Optional[str] = None,
plugins: Optional[str] = None,
event_firing_webdriver: Optional[str] = None,
page_load_timeout=timedelta(minutes=5),
action_chain_delay=timedelta(seconds=0.25),
):
"""SeleniumLibrary can be imported with several optional arguments.
- ``timeout``:
Default value for `timeouts` used with ``Wait ...`` keywords.
- ``implicit_wait``:
Default value for `implicit wait` used when locating elements.
- ``run_on_failure``:
Default action for the `run-on-failure functionality`.
- ``screenshot_root_directory``:
Path to folder where possible screenshots are created or EMBED.
See `Set Screenshot Directory` keyword for further details about EMBED.
If not given, the directory where the log file is written is used.
- ``plugins``:
Allows extending the SeleniumLibrary with external Python classes.
- ``event_firing_webdriver``:
Class for wrapping Selenium with
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.event_firing_webdriver.html#module-selenium.webdriver.support.event_firing_webdriver|EventFiringWebDriver]
- ``page_load_timeout``:
Default value to wait for page load to complete until error is raised.
- ``action_chain_delay``:
Default value for `ActionChains` delay to wait in between actions.
"""
self.timeout = _convert_timeout(timeout)
self.implicit_wait = _convert_timeout(implicit_wait)
self.action_chain_delay = _convert_delay(action_chain_delay)
self.page_load_timeout = _convert_timeout(page_load_timeout)
self.speed = 0.0
self.run_on_failure_keyword = RunOnFailureKeywords.resolve_keyword(
run_on_failure
)
self._running_on_failure_keyword = False
self.screenshot_root_directory = screenshot_root_directory
self._resolve_screenshot_root_directory()
self._element_finder = ElementFinder(self)
self._plugin_keywords = []
libraries = [
AlertKeywords(self),
BrowserManagementKeywords(self),
CookieKeywords(self),
ElementKeywords(self),
FormElementKeywords(self),
FrameKeywords(self),
JavaScriptKeywords(self),
RunOnFailureKeywords(self),
ScreenshotKeywords(self),
SelectElementKeywords(self),
TableElementKeywords(self),
WaitingKeywords(self),
WindowKeywords(self),
]
self.ROBOT_LIBRARY_LISTENER = LibraryListener()
self._running_keyword = None
self.event_firing_webdriver = None
if is_truthy(event_firing_webdriver):
self.event_firing_webdriver = self._parse_listener(event_firing_webdriver)
self._plugins = []
if is_truthy(plugins):
plugin_libs = self._parse_plugins(plugins)
self._plugins = plugin_libs
libraries = libraries + plugin_libs
self._drivers = WebDriverCache()
DynamicCore.__init__(self, libraries)
def run_keyword(self, name: str, args: tuple, kwargs: dict):
try:
return DynamicCore.run_keyword(self, name, args, kwargs)
except Exception:
self.failure_occurred()
raise
def get_keyword_tags(self, name: str) -> list:
tags = list(DynamicCore.get_keyword_tags(self, name))
if name in self._plugin_keywords:
tags.append("plugin")
return tags
def get_keyword_documentation(self, name: str) -> str:
if name == "__intro__":
return self._get_intro_documentation()
return DynamicCore.get_keyword_documentation(self, name)
def _parse_plugin_doc(self):
Doc = namedtuple("Doc", "doc, name")
for plugin in self._plugins:
yield Doc(
doc=getdoc(plugin) or "No plugin documentation found.",
name=plugin.__class__.__name__,
)
def _get_intro_documentation(self):
intro = DynamicCore.get_keyword_documentation(self, "__intro__")
for plugin_doc in self._parse_plugin_doc():
intro = f"{intro}\n\n"
intro = f"{intro}= Plugin: {plugin_doc.name} =\n\n"
intro = f"{intro}{plugin_doc.doc}"
return intro
def register_driver(self, driver: WebDriver, alias: str):
"""Add's a `driver` to the library WebDriverCache.
:param driver: Instance of the Selenium `WebDriver`.
:type driver: selenium.webdriver.remote.webdriver.WebDriver
:param alias: Alias given for this `WebDriver` instance.
:type alias: str
:return: The index of the `WebDriver` instance.
:rtype: int
"""
return self._drivers.register(driver, alias)
def failure_occurred(self):
"""Method that is executed when a SeleniumLibrary keyword fails.
By default, executes the registered run-on-failure keyword.
Libraries extending SeleniumLibrary can overwrite this hook
method if they want to provide custom functionality instead.
"""
if self._running_on_failure_keyword or not self.run_on_failure_keyword:
return
try:
self._running_on_failure_keyword = True
if self.run_on_failure_keyword.lower() == "capture page screenshot":
self.capture_page_screenshot()
else:
BuiltIn().run_keyword(self.run_on_failure_keyword)
except Exception as err:
logger.warn(
f"Keyword '{self.run_on_failure_keyword}' could not be run on failure: {err}"
)
finally:
self._running_on_failure_keyword = False
@property
def driver(self) -> WebDriver:
"""Current active driver.
:rtype: selenium.webdriver.remote.webdriver.WebDriver
:raises SeleniumLibrary.errors.NoOpenBrowser: If browser is not open.
"""
if not self._drivers.current:
raise NoOpenBrowser("No browser is open.")
return self._drivers.current
def find_element(
self, locator: str, parent: Optional[WebElement] = None
) -> WebElement:
"""Find element matching `locator`.
:param locator: Locator to use when searching the element.
See library documentation for the supported locator syntax.
:type locator: str or selenium.webdriver.remote.webelement.WebElement
:param parent: Optional parent `WebElememt` to search child elements
from. By default, search starts from the root using `WebDriver`.
:type parent: selenium.webdriver.remote.webelement.WebElement
:return: Found `WebElement`.
:rtype: selenium.webdriver.remote.webelement.WebElement
:raises SeleniumLibrary.errors.ElementNotFound: If element not found.
"""
return self._element_finder.find(locator, parent=parent)
def find_elements(
self, locator: str, parent: WebElement = None
) -> List[WebElement]:
"""Find all elements matching `locator`.
:param locator: Locator to use when searching the element.
See library documentation for the supported locator syntax.
:type locator: str or selenium.webdriver.remote.webelement.WebElement
:param parent: Optional parent `WebElememt` to search child elements
from. By default, search starts from the root using `WebDriver`.
:type parent: selenium.webdriver.remote.webelement.WebElement
:return: list of found `WebElement` or e,mpty if elements are not found.
:rtype: list[selenium.webdriver.remote.webelement.WebElement]
"""
return self._element_finder.find(
locator, first_only=False, required=False, parent=parent
)
def _parse_plugins(self, plugins):
libraries = []
importer = Importer("test library")
for parsed_plugin in self._string_to_modules(plugins):
plugin = importer.import_class_or_module(parsed_plugin.module)
if not isclass(plugin):
message = f"Importing test library: '{parsed_plugin.module}' failed."
raise DataError(message)
plugin = plugin(self, *parsed_plugin.args, **parsed_plugin.kw_args)
if not isinstance(plugin, LibraryComponent):
message = (
"Plugin does not inherit SeleniumLibrary.base.LibraryComponent"
)
raise PluginError(message)
self._store_plugin_keywords(plugin)
libraries.append(plugin)
return libraries
def _parse_listener(self, event_firing_webdriver):
listener_module = self._string_to_modules(event_firing_webdriver)
listener_count = len(listener_module)
if listener_count > 1:
message = f"Is is possible import only one listener but there was {listener_count} listeners."
raise ValueError(message)
listener_module = listener_module[0]
importer = Importer("test library")
listener = importer.import_class_or_module(listener_module.module)
if not isclass(listener):
message = f"Importing test Selenium lister class '{listener_module.module}' failed."
raise DataError(message)
return listener
def _string_to_modules(self, modules):
Module = namedtuple("Module", "module, args, kw_args")
parsed_modules = []
for module in modules.split(","):
module = module.strip()
module_and_args = module.split(";")
module_name = module_and_args.pop(0)
kw_args = {}
args = []
for argument in module_and_args:
if "=" in argument:
key, value = argument.split("=")
kw_args[key] = value
else:
args.append(argument)
module = Module(module=module_name, args=args, kw_args=kw_args)
parsed_modules.append(module)
return parsed_modules
def _store_plugin_keywords(self, plugin):
dynamic_core = DynamicCore([plugin])
self._plugin_keywords.extend(dynamic_core.get_keyword_names())
def _resolve_screenshot_root_directory(self):
screenshot_root_directory = self.screenshot_root_directory
if is_string(screenshot_root_directory):
if screenshot_root_directory.upper() == EMBED:
self.screenshot_root_directory = EMBED | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/__init__.py | 0.917714 | 0.396652 | __init__.py | pypi |
from typing import Union
from selenium.webdriver.remote.webelement import WebElement
from SeleniumLibrary.base import LibraryComponent, keyword
class FrameKeywords(LibraryComponent):
@keyword
def select_frame(self, locator: Union[WebElement, str]):
"""Sets frame identified by ``locator`` as the current frame.
See the `Locating elements` section for details about the locator
syntax.
Works both with frames and iframes. Use `Unselect Frame` to cancel
the frame selection and return to the main frame.
Example:
| `Select Frame` | top-frame | # Select frame with id or name 'top-frame' |
| `Click Link` | example | # Click link 'example' in the selected frame |
| `Unselect Frame` | | # Back to main frame. |
| `Select Frame` | //iframe[@name='xxx'] | # Select frame using xpath |
"""
self.info(f"Selecting frame '{locator}'.")
element = self.find_element(locator)
self.driver.switch_to.frame(element)
@keyword
def unselect_frame(self):
"""Sets the main frame as the current frame.
In practice cancels the previous `Select Frame` call.
"""
self.driver.switch_to.default_content()
@keyword
def current_frame_should_contain(self, text: str, loglevel: str = "TRACE"):
"""Verifies that the current frame contains ``text``.
See `Page Should Contain` for an explanation about the ``loglevel``
argument.
Prior to SeleniumLibrary 3.0 this keyword was named
`Current Frame Contains`.
"""
if not self.is_text_present(text):
self.log_source(loglevel)
raise AssertionError(
f"Frame should have contained text '{text}' but did not."
)
self.info(f"Current frame contains text '{text}'.")
@keyword
def current_frame_should_not_contain(self, text: str, loglevel: str = "TRACE"):
"""Verifies that the current frame does not contain ``text``.
See `Page Should Contain` for an explanation about the ``loglevel``
argument.
"""
if self.is_text_present(text):
self.log_source(loglevel)
raise AssertionError(
f"Frame should not have contained text '{text}' but it did."
)
self.info(f"Current frame did not contain text '{text}'.")
@keyword
def frame_should_contain(
self, locator: Union[WebElement, str], text: str, loglevel: str = "TRACE"
):
"""Verifies that frame identified by ``locator`` contains ``text``.
See the `Locating elements` section for details about the locator
syntax.
See `Page Should Contain` for an explanation about the ``loglevel``
argument.
"""
if not self._frame_contains(locator, text):
self.log_source(loglevel)
raise AssertionError(
f"Frame '{locator}' should have contained text '{text}' but did not."
)
self.info(f"Frame '{locator}' contains text '{text}'.")
def _frame_contains(self, locator: Union[WebElement, str], text: str):
element = self.find_element(locator)
self.driver.switch_to.frame(element)
self.info(f"Searching for text from frame '{locator}'.")
found = self.is_text_present(text)
self.driver.switch_to.default_content()
return found | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/frames.py | 0.899528 | 0.316924 | frames.py | pypi |
import os
from typing import Optional, Union
from robot.libraries.BuiltIn import BuiltIn
from selenium.webdriver.remote.webelement import WebElement
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary.errors import ElementNotFound
class FormElementKeywords(LibraryComponent):
@keyword
def submit_form(self, locator: Union[WebElement, None, str] = None):
"""Submits a form identified by ``locator``.
If ``locator`` is not given, first form on the page is submitted.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Submitting form '{locator}'.")
if locator is None:
locator = "tag:form"
element = self.find_element(locator, tag="form")
element.submit()
@keyword
def checkbox_should_be_selected(self, locator: Union[WebElement, str]):
"""Verifies checkbox ``locator`` is selected/checked.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Verifying checkbox '{locator}' is selected.")
element = self._get_checkbox(locator)
if not element.is_selected():
raise AssertionError(
f"Checkbox '{locator}' should have been selected but was not."
)
@keyword
def checkbox_should_not_be_selected(self, locator: Union[WebElement, str]):
"""Verifies checkbox ``locator`` is not selected/checked.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Verifying checkbox '{locator}' is not selected.")
element = self._get_checkbox(locator)
if element.is_selected():
raise AssertionError(f"Checkbox '{locator}' should not have been selected.")
@keyword
def page_should_contain_checkbox(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies checkbox ``locator`` is found from the current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax.
"""
self.assert_page_contains(locator, "checkbox", message, loglevel)
@keyword
def page_should_not_contain_checkbox(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies checkbox ``locator`` is not found from the current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax.
"""
self.assert_page_not_contains(locator, "checkbox", message, loglevel)
@keyword
def select_checkbox(self, locator: Union[WebElement, str]):
"""Selects the checkbox identified by ``locator``.
Does nothing if checkbox is already selected.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Selecting checkbox '{locator}'.")
element = self._get_checkbox(locator)
if not element.is_selected():
element.click()
@keyword
def unselect_checkbox(self, locator: Union[WebElement, str]):
"""Removes the selection of checkbox identified by ``locator``.
Does nothing if the checkbox is not selected.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Unselecting checkbox '{locator}'.")
element = self._get_checkbox(locator)
if element.is_selected():
element.click()
@keyword
def page_should_contain_radio_button(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies radio button ``locator`` is found from current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, radio buttons are
searched using ``id``, ``name`` and ``value``.
"""
self.assert_page_contains(locator, "radio button", message, loglevel)
@keyword
def page_should_not_contain_radio_button(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies radio button ``locator`` is not found from current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, radio buttons are
searched using ``id``, ``name`` and ``value``.
"""
self.assert_page_not_contains(locator, "radio button", message, loglevel)
@keyword
def radio_button_should_be_set_to(self, group_name: str, value: str):
"""Verifies radio button group ``group_name`` is set to ``value``.
``group_name`` is the ``name`` of the radio button group.
"""
self.info(f"Verifying radio button '{group_name}' has selection '{value}'.")
elements = self._get_radio_buttons(group_name)
actual_value = self._get_value_from_radio_buttons(elements)
if actual_value is None or actual_value != value:
raise AssertionError(
f"Selection of radio button '{group_name}' should have "
f"been '{value}' but was '{actual_value}'."
)
@keyword
def radio_button_should_not_be_selected(self, group_name: str):
"""Verifies radio button group ``group_name`` has no selection.
``group_name`` is the ``name`` of the radio button group.
"""
self.info(f"Verifying radio button '{group_name}' has no selection.")
elements = self._get_radio_buttons(group_name)
actual_value = self._get_value_from_radio_buttons(elements)
if actual_value is not None:
raise AssertionError(
f"Radio button group '{group_name}' should not have "
f"had selection, but '{actual_value}' was selected."
)
@keyword
def select_radio_button(self, group_name: str, value: str):
"""Sets the radio button group ``group_name`` to ``value``.
The radio button to be selected is located by two arguments:
- ``group_name`` is the name of the radio button group.
- ``value`` is the ``id`` or ``value`` attribute of the actual
radio button.
Examples:
| `Select Radio Button` | size | XL |
| `Select Radio Button` | contact | email |
"""
self.info(f"Selecting '{value}' from radio button '{group_name}'.")
element = self._get_radio_button_with_value(group_name, value)
if not element.is_selected():
element.click()
@keyword
def choose_file(self, locator: Union[WebElement, str], file_path: str):
"""Inputs the ``file_path`` into the file input field ``locator``.
This keyword is most often used to input files into upload forms.
The keyword does not check ``file_path`` is the file or folder
available on the machine where tests are executed. If the ``file_path``
points at a file and when using Selenium Grid, Selenium will
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.command.html?highlight=upload#selenium.webdriver.remote.command.Command.UPLOAD_FILE|magically],
transfer the file from the machine where the tests are executed
to the Selenium Grid node where the browser is running.
Then Selenium will send the file path, from the nodes file
system, to the browser.
That ``file_path`` is not checked, is new in SeleniumLibrary 4.0.
Example:
| `Choose File` | my_upload_field | ${CURDIR}/trades.csv |
"""
self.ctx._running_keyword = "choose_file"
try:
self.info(f"Sending {os.path.abspath(file_path)} to browser.")
self.find_element(locator).send_keys(file_path)
finally:
self.ctx._running_keyword = None
@keyword
def input_password(
self, locator: Union[WebElement, str], password: str, clear: bool = True
):
"""Types the given password into the text field identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax. See `Input Text` for ``clear`` argument details.
Difference compared to `Input Text` is that this keyword does not
log the given password on the INFO level. Notice that if you use
the keyword like
| Input Password | password_field | password |
the password is shown as a normal keyword argument. A way to avoid
that is using variables like
| Input Password | password_field | ${PASSWORD} |
Please notice that Robot Framework logs all arguments using
the TRACE level and tests must not be executed using level below
DEBUG if the password should not be logged in any format.
The `clear` argument is new in SeleniumLibrary 4.0. Hiding password
logging from Selenium logs is new in SeleniumLibrary 4.2.
"""
self.info(f"Typing password into text field '{locator}'.")
self._input_text_into_text_field(locator, password, clear, disable_log=True)
@keyword
def input_text(
self, locator: Union[WebElement, str], text: str, clear: bool = True
):
"""Types the given ``text`` into the text field identified by ``locator``.
When ``clear`` is true, the input element is cleared before
the text is typed into the element. When false, the previous text
is not cleared from the element. Use `Input Password` if you
do not want the given ``text`` to be logged.
If [https://github.com/SeleniumHQ/selenium/wiki/Grid2|Selenium Grid]
is used and the ``text`` argument points to a file in the file system,
then this keyword prevents the Selenium to transfer the file to the
Selenium Grid hub. Instead, this keyword will send the ``text`` string
as is to the element. If a file should be transferred to the hub and
upload should be performed, please use `Choose File` keyword.
See the `Locating elements` section for details about the locator
syntax. See the `Boolean arguments` section how Boolean values are
handled.
Disabling the file upload the Selenium Grid node and the `clear`
argument are new in SeleniumLibrary 4.0
"""
self.info(f"Typing text '{text}' into text field '{locator}'.")
self._input_text_into_text_field(locator, text, clear)
@keyword
def page_should_contain_textfield(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies text field ``locator`` is found from current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax.
"""
self.assert_page_contains(locator, "text field", message, loglevel)
@keyword
def page_should_not_contain_textfield(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies text field ``locator`` is not found from current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax.
"""
self.assert_page_not_contains(locator, "text field", message, loglevel)
@keyword
def textfield_should_contain(
self,
locator: Union[WebElement, str],
expected: str,
message: Optional[str] = None,
):
"""Verifies text field ``locator`` contains text ``expected``.
``message`` can be used to override the default error message.
See the `Locating elements` section for details about the locator
syntax.
"""
actual = self._get_value(locator, "text field")
if expected not in actual:
if message is None:
message = (
f"Text field '{locator}' should have contained text "
f"'{expected}' but it contained '{actual}'."
)
raise AssertionError(message)
self.info(f"Text field '{locator}' contains text '{expected}'.")
@keyword
def textfield_value_should_be(
self,
locator: Union[WebElement, str],
expected: str,
message: Optional[str] = None,
):
"""Verifies text field ``locator`` has exactly text ``expected``.
``message`` can be used to override default error message.
See the `Locating elements` section for details about the locator
syntax.
"""
actual = self._get_value(locator, "text field")
if actual != expected:
if message is None:
message = (
f"Value of text field '{locator}' should have been "
f"'{expected}' but was '{actual}'."
)
raise AssertionError(message)
self.info(f"Content of text field '{locator}' is '{expected}'.")
@keyword
def textarea_should_contain(
self,
locator: Union[WebElement, str],
expected: str,
message: Optional[str] = None,
):
"""Verifies text area ``locator`` contains text ``expected``.
``message`` can be used to override default error message.
See the `Locating elements` section for details about the locator
syntax.
"""
actual = self._get_value(locator, "text area")
if expected not in actual:
if message is None:
message = (
f"Text area '{locator}' should have contained text "
f"'{expected}' but it had '{actual}'."
)
raise AssertionError(message)
self.info(f"Text area '{locator}' contains text '{expected}'.")
@keyword
def textarea_value_should_be(
self,
locator: Union[WebElement, str],
expected: str,
message: Optional[str] = None,
):
"""Verifies text area ``locator`` has exactly text ``expected``.
``message`` can be used to override default error message.
See the `Locating elements` section for details about the locator
syntax.
"""
actual = self._get_value(locator, "text area")
if expected != actual:
if message is None:
message = (
f"Text area '{locator}' should have had text "
f"'{expected}' but it had '{actual}'."
)
raise AssertionError(message)
self.info(f"Content of text area '{locator}' is '{expected}'.")
@keyword
def page_should_contain_button(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies button ``locator`` is found from current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, buttons are
searched using ``id``, ``name``, and ``value``.
"""
try:
self.assert_page_contains(locator, "input", message, loglevel)
except AssertionError:
self.assert_page_contains(locator, "button", message, loglevel)
@keyword
def page_should_not_contain_button(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies button ``locator`` is not found from current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, buttons are
searched using ``id``, ``name``, and ``value``.
"""
self.assert_page_not_contains(locator, "button", message, loglevel)
self.assert_page_not_contains(locator, "input", message, loglevel)
def _get_value(self, locator, tag):
return self.find_element(locator, tag).get_attribute("value")
def _get_checkbox(self, locator: Union[WebElement, str]):
return self.find_element(locator, tag="checkbox")
def _get_radio_buttons(self, group_name):
xpath = f"xpath://input[@type='radio' and @name='{group_name}']"
self.debug(f"Radio group locator: {xpath}")
elements = self.find_elements(xpath)
if not elements:
raise ElementNotFound(f"No radio button with name '{group_name}' found.")
return elements
def _get_radio_button_with_value(self, group_name, value):
xpath = (
f"xpath://input[@type='radio' and @name='{group_name}' and "
f"(@value='{value}' or @id='{value}')]"
)
self.debug(f"Radio group locator: {xpath}")
try:
return self.find_element(xpath)
except ElementNotFound:
raise ElementNotFound(
f"No radio button with name '{group_name}' "
f"and value '{value}' found."
)
def _get_value_from_radio_buttons(self, elements):
for element in elements:
if element.is_selected():
return element.get_attribute("value")
return None
def _input_text_into_text_field(self, locator, text, clear=True, disable_log=False):
element = self.find_element(locator)
if clear:
element.clear()
if disable_log:
self.info("Temporally setting log level to: NONE")
previous_level = BuiltIn().set_log_level("NONE")
try:
element.send_keys(text)
finally:
if disable_log:
BuiltIn().set_log_level(previous_level) | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/formelement.py | 0.869382 | 0.23421 | formelement.py | pypi |
from datetime import timedelta
from typing import Optional
from selenium.common.exceptions import TimeoutException, WebDriverException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from SeleniumLibrary.base import keyword, LibraryComponent
from SeleniumLibrary.utils import secs_to_timestr
class AlertKeywords(LibraryComponent):
ACCEPT = "ACCEPT"
DISMISS = "DISMISS"
LEAVE = "LEAVE"
_next_alert_action = ACCEPT
@keyword
def input_text_into_alert(
self, text: str, action: str = ACCEPT, timeout: Optional[timedelta] = None
):
"""Types the given ``text`` into an input field in an alert.
The alert is accepted by default, but that behavior can be controlled
by using the ``action`` argument same way as with `Handle Alert`.
``timeout`` specifies how long to wait for the alert to appear.
If it is not given, the global default `timeout` is used instead.
New in SeleniumLibrary 3.0.
"""
alert = self._wait_alert(timeout)
alert.send_keys(text)
self._handle_alert(alert, action)
@keyword
def alert_should_be_present(
self,
text: str = "",
action: str = ACCEPT,
timeout: Optional[timedelta] = None,
):
"""Verifies that an alert is present and by default, accepts it.
Fails if no alert is present. If ``text`` is a non-empty string,
then it is used to verify alert's message. The alert is accepted
by default, but that behavior can be controlled by using the
``action`` argument same way as with `Handle Alert`.
``timeout`` specifies how long to wait for the alert to appear.
If it is not given, the global default `timeout` is used instead.
``action`` and ``timeout`` arguments are new in SeleniumLibrary 3.0.
In earlier versions, the alert was always accepted and a timeout was
hardcoded to one second.
"""
message = self.handle_alert(action, timeout)
if text and text != message:
raise AssertionError(
f"Alert message should have been '{text}' but it " f"was '{message}'."
)
@keyword
def alert_should_not_be_present(
self, action: str = ACCEPT, timeout: Optional[timedelta] = None
):
"""Verifies that no alert is present.
If the alert actually exists, the ``action`` argument determines
how it should be handled. By default, the alert is accepted, but
it can be also dismissed or left open the same way as with the
`Handle Alert` keyword.
``timeout`` specifies how long to wait for the alert to appear.
By default, is not waited for the alert at all, but a custom time can
be given if alert may be delayed. See the `time format` section
for information about the syntax.
New in SeleniumLibrary 3.0.
"""
try:
alert = self._wait_alert(timeout)
except AssertionError:
return
text = self._handle_alert(alert, action)
raise AssertionError(f"Alert with message '{text}' present.")
@keyword
def handle_alert(self, action: str = ACCEPT, timeout: Optional[timedelta] = None):
"""Handles the current alert and returns its message.
By default, the alert is accepted, but this can be controlled
with the ``action`` argument that supports the following
case-insensitive values:
- ``ACCEPT``: Accept the alert i.e. press ``Ok``. Default.
- ``DISMISS``: Dismiss the alert i.e. press ``Cancel``.
- ``LEAVE``: Leave the alert open.
The ``timeout`` argument specifies how long to wait for the alert
to appear. If it is not given, the global default `timeout` is used
instead.
Examples:
| Handle Alert | | | # Accept alert. |
| Handle Alert | action=DISMISS | | # Dismiss alert. |
| Handle Alert | timeout=10 s | | # Use custom timeout and accept alert. |
| Handle Alert | DISMISS | 1 min | # Use custom timeout and dismiss alert. |
| ${message} = | Handle Alert | | # Accept alert and get its message. |
| ${message} = | Handle Alert | LEAVE | # Leave alert open and get its message. |
New in SeleniumLibrary 3.0.
"""
self.info(f"HANDLE::{type(timeout)}::{timeout}")
alert = self._wait_alert(timeout)
return self._handle_alert(alert, action)
def _handle_alert(self, alert, action):
action = action.upper()
text = " ".join(alert.text.splitlines())
if action == self.ACCEPT:
alert.accept()
elif action == self.DISMISS:
alert.dismiss()
elif action != self.LEAVE:
raise ValueError(f"Invalid alert action '{action}'.")
return text
def _wait_alert(self, timeout=None):
timeout = self.get_timeout(timeout)
wait = WebDriverWait(self.driver, timeout)
try:
return wait.until(EC.alert_is_present())
except TimeoutException:
raise AssertionError(f"Alert not found in {secs_to_timestr(timeout)}.")
except WebDriverException as err:
raise AssertionError(f"An exception occurred waiting for alert: {err}") | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/alert.py | 0.89751 | 0.395193 | alert.py | pypi |
import time
from datetime import timedelta
from typing import Optional, Union
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.remote.webelement import WebElement
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary.errors import ElementNotFound
from SeleniumLibrary.utils import secs_to_timestr
class WaitingKeywords(LibraryComponent):
@keyword
def wait_for_condition(
self,
condition: str,
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
):
"""Waits until ``condition`` is true or ``timeout`` expires.
The condition can be arbitrary JavaScript expression but it
must return a value to be evaluated. See `Execute JavaScript` for
information about accessing content on pages.
Fails if the timeout expires before the condition becomes true. See
the `Timeouts` section for more information about using timeouts
and their default value.
``error`` can be used to override the default error message.
Examples:
| `Wait For Condition` | return document.title == "New Title" |
| `Wait For Condition` | return jQuery.active == 0 |
| `Wait For Condition` | style = document.querySelector('h1').style; return style.background == "red" && style.color == "white" |
"""
if "return" not in condition:
raise ValueError(
f"Condition '{condition}' did not have mandatory 'return'."
)
self._wait_until(
lambda: self.driver.execute_script(condition) is True,
f"Condition '{condition}' did not become true in <TIMEOUT>.",
timeout,
error,
)
@keyword
def wait_until_location_is(
self,
expected: str,
timeout: Optional[timedelta] = None,
message: Optional[str] = None,
):
"""Waits until the current URL is ``expected``.
The ``expected`` argument is the expected value in url.
Fails if ``timeout`` expires before the location is. See
the `Timeouts` section for more information about using timeouts
and their default value.
The ``message`` argument can be used to override the default error
message.
New in SeleniumLibrary 4.0
"""
expected = str(expected)
self._wait_until(
lambda: expected == self.driver.current_url,
f"Location did not become '{expected}' in <TIMEOUT>.",
timeout,
message,
)
@keyword
def wait_until_location_is_not(
self,
location: str,
timeout: Optional[timedelta] = None,
message: Optional[str] = None,
):
"""Waits until the current URL is not ``location``.
The ``location`` argument is the unexpected value in url.
Fails if ``timeout`` expires before the location is not. See
the `Timeouts` section for more information about using timeouts
and their default value.
The ``message`` argument can be used to override the default error
message.
New in SeleniumLibrary 4.3
"""
location = str(location)
self._wait_until(
lambda: location != self.driver.current_url,
f"Location is '{location}' in <TIMEOUT>.",
timeout,
message,
)
@keyword
def wait_until_location_contains(
self,
expected: str,
timeout: Optional[timedelta] = None,
message: Optional[str] = None,
):
"""Waits until the current URL contains ``expected``.
The ``expected`` argument contains the expected value in url.
Fails if ``timeout`` expires before the location contains. See
the `Timeouts` section for more information about using timeouts
and their default value.
The ``message`` argument can be used to override the default error
message.
New in SeleniumLibrary 4.0
"""
expected = str(expected)
self._wait_until(
lambda: expected in self.driver.current_url,
f"Location did not contain '{expected}' in <TIMEOUT>.",
timeout,
message,
)
@keyword
def wait_until_location_does_not_contain(
self,
location: str,
timeout: Optional[timedelta] = None,
message: Optional[str] = None,
):
"""Waits until the current URL does not contains ``location``.
The ``location`` argument contains value not expected in url.
Fails if ``timeout`` expires before the location not contains. See
the `Timeouts` section for more information about using timeouts
and their default value.
The ``message`` argument can be used to override the default error
message.
New in SeleniumLibrary 4.3
"""
location = str(location)
self._wait_until(
lambda: location not in self.driver.current_url,
f"Location did contain '{location}' in <TIMEOUT>.",
timeout,
message,
)
@keyword
def wait_until_page_contains(
self,
text: str,
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
):
"""Waits until ``text`` appears on the current page.
Fails if ``timeout`` expires before the text appears. See
the `Timeouts` section for more information about using timeouts
and their default value.
``error`` can be used to override the default error message.
"""
self._wait_until(
lambda: self.is_text_present(text),
f"Text '{text}' did not appear in <TIMEOUT>.",
timeout,
error,
)
@keyword
def wait_until_page_does_not_contain(
self,
text: str,
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
):
"""Waits until ``text`` disappears from the current page.
Fails if ``timeout`` expires before the text disappears. See
the `Timeouts` section for more information about using timeouts
and their default value.
``error`` can be used to override the default error message.
"""
self._wait_until(
lambda: not self.is_text_present(text),
f"Text '{text}' did not disappear in <TIMEOUT>.",
timeout,
error,
)
@keyword
def wait_until_page_contains_element(
self,
locator: Union[WebElement, None, str],
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
limit: Optional[int] = None,
):
"""Waits until the element ``locator`` appears on the current page.
Fails if ``timeout`` expires before the element appears. See
the `Timeouts` section for more information about using timeouts and
their default value and the `Locating elements` section for details
about the locator syntax.
``error`` can be used to override the default error message.
The ``limit`` argument can used to define how many elements the
page should contain. When ``limit`` is `None` (default) page can
contain one or more elements. When limit is a number, page must
contain same number of elements.
``limit`` is new in SeleniumLibrary 4.4
"""
if limit is None:
return self._wait_until(
lambda: self.find_element(locator, required=False) is not None,
f"Element '{locator}' did not appear in <TIMEOUT>.",
timeout,
error,
)
self._wait_until(
lambda: len(self.find_elements(locator)) == limit,
f'Page should have contained "{limit}" {locator} element(s) within <TIMEOUT>.',
timeout,
error,
)
@keyword
def wait_until_page_does_not_contain_element(
self,
locator: Union[WebElement, None, str],
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
limit: Optional[int] = None,
):
"""Waits until the element ``locator`` disappears from the current page.
Fails if ``timeout`` expires before the element disappears. See
the `Timeouts` section for more information about using timeouts and
their default value and the `Locating elements` section for details
about the locator syntax.
``error`` can be used to override the default error message.
The ``limit`` argument can used to define how many elements the
page should not contain. When ``limit`` is `None` (default) page can`t
contain any elements. When limit is a number, page must not
contain same number of elements.
``limit`` is new in SeleniumLibrary 4.4
"""
if limit is None:
return self._wait_until(
lambda: self.find_element(locator, required=False) is None,
f"Element '{locator}' did not disappear in <TIMEOUT>.",
timeout,
error,
)
self._wait_until(
lambda: len(self.find_elements(locator)) != limit,
f'Page should have not contained "{limit}" {locator} element(s) within <TIMEOUT>.',
timeout,
error,
)
@keyword
def wait_until_element_is_visible(
self,
locator: Union[WebElement, None, str],
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
):
"""Waits until the element ``locator`` is visible.
Fails if ``timeout`` expires before the element is visible. See
the `Timeouts` section for more information about using timeouts and
their default value and the `Locating elements` section for details
about the locator syntax.
``error`` can be used to override the default error message.
"""
self._wait_until(
lambda: self.is_visible(locator),
f"Element '{locator}' not visible after <TIMEOUT>.",
timeout,
error,
)
@keyword
def wait_until_element_is_not_visible(
self,
locator: Union[WebElement, None, str],
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
):
"""Waits until the element ``locator`` is not visible.
Fails if ``timeout`` expires before the element is not visible. See
the `Timeouts` section for more information about using timeouts and
their default value and the `Locating elements` section for details
about the locator syntax.
``error`` can be used to override the default error message.
"""
self._wait_until(
lambda: not self.is_visible(locator),
f"Element '{locator}' still visible after <TIMEOUT>.",
timeout,
error,
)
@keyword
def wait_until_element_is_enabled(
self,
locator: Union[WebElement, None, str],
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
):
"""Waits until the element ``locator`` is enabled.
Element is considered enabled if it is not disabled nor read-only.
Fails if ``timeout`` expires before the element is enabled. See
the `Timeouts` section for more information about using timeouts and
their default value and the `Locating elements` section for details
about the locator syntax.
``error`` can be used to override the default error message.
Considering read-only elements to be disabled is a new feature
in SeleniumLibrary 3.0.
"""
self._wait_until(
lambda: self.is_element_enabled(locator),
f"Element '{locator}' was not enabled in <TIMEOUT>.",
timeout,
error,
)
@keyword
def wait_until_element_contains(
self,
locator: Union[WebElement, None, str],
text: str,
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
):
"""Waits until the element ``locator`` contains ``text``.
Fails if ``timeout`` expires before the text appears. See
the `Timeouts` section for more information about using timeouts and
their default value and the `Locating elements` section for details
about the locator syntax.
``error`` can be used to override the default error message.
"""
self._wait_until(
lambda: text in self.find_element(locator).text,
f"Element '{locator}' did not get text '{text}' in <TIMEOUT>.",
timeout,
error,
)
@keyword
def wait_until_element_does_not_contain(
self,
locator: Union[WebElement, None, str],
text: str,
timeout: Optional[timedelta] = None,
error: Optional[str] = None,
):
"""Waits until the element ``locator`` does not contain ``text``.
Fails if ``timeout`` expires before the text disappears. See
the `Timeouts` section for more information about using timeouts and
their default value and the `Locating elements` section for details
about the locator syntax.
``error`` can be used to override the default error message.
"""
self._wait_until(
lambda: text not in self.find_element(locator).text,
f"Element '{locator}' still had text '{text}' after <TIMEOUT>.",
timeout,
error,
)
def _wait_until(self, condition, error, timeout=None, custom_error=None):
timeout = self.get_timeout(timeout)
if custom_error is None:
error = error.replace("<TIMEOUT>", secs_to_timestr(timeout))
else:
error = custom_error
self._wait_until_worker(condition, timeout, error)
def _wait_until_worker(self, condition, timeout, error):
max_time = time.time() + timeout
not_found = None
while time.time() < max_time:
try:
if condition():
return
except ElementNotFound as err:
not_found = str(err)
except StaleElementReferenceException as err:
self.info("Suppressing StaleElementReferenceException from Selenium.")
not_found = err
else:
not_found = None
time.sleep(0.2)
raise AssertionError(not_found or error) | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/waiting.py | 0.906407 | 0.326943 | waiting.py | pypi |
from typing import Union
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from SeleniumLibrary.base import LibraryComponent, keyword
class TableElementKeywords(LibraryComponent):
@keyword
def get_table_cell(
self,
locator: Union[WebElement, None, str],
row: int,
column: int,
loglevel: str = "TRACE",
) -> str:
"""Returns contents of a table cell.
The table is located using the ``locator`` argument and its cell
found using ``row`` and ``column``. See the `Locating elements`
section for details about the locator syntax.
Both row and column indexes start from 1, and header and footer
rows are included in the count. It is possible to refer to rows
and columns from the end by using negative indexes so that -1
is the last row/column, -2 is the second last, and so on.
All ``<th>`` and ``<td>`` elements anywhere in the table are
considered to be cells.
See `Page Should Contain` for an explanation about the ``loglevel``
argument.
"""
if row == 0 or column == 0:
raise ValueError(
"Both row and column must be non-zero, "
f"got row {row} and column {column}."
)
try:
cell = self._get_cell(locator, row, column)
except AssertionError:
self.log_source(loglevel)
raise
return cell.text
def _get_cell(self, locator, row, column):
rows = self._get_rows(locator, row)
if len(rows) < abs(row):
raise AssertionError(
f"Table '{locator}' should have had at least {abs(row)} "
f"rows but had only {len(rows)}."
)
index = row - 1 if row > 0 else row
cells = rows[index].find_elements(By.XPATH, "./th|./td")
if len(cells) < abs(column):
raise AssertionError(
f"Table '{locator}' row {row} should have had at "
f"least {abs(column)} columns but had only {len(cells)}."
)
index = column - 1 if column > 0 else column
return cells[index]
def _get_rows(self, locator, count):
# Get rows in same order as browsers render them.
table = self.find_element(locator, tag="table")
rows = table.find_elements(By.XPATH, "./thead/tr")
if count < 0 or len(rows) < count:
rows.extend(table.find_elements(By.XPATH, "./tbody/tr"))
if count < 0 or len(rows) < count:
rows.extend(table.find_elements(By.XPATH, "./tfoot/tr"))
return rows
@keyword
def table_cell_should_contain(
self,
locator: Union[WebElement, None, str],
row: int,
column: int,
expected: str,
loglevel: str = "TRACE",
):
"""Verifies table cell contains text ``expected``.
See `Get Table Cell` that this keyword uses internally for
an explanation about accepted arguments.
"""
content = self.get_table_cell(locator, row, column, loglevel)
if expected not in content:
self.ctx.log_source(loglevel)
raise AssertionError(
f"Table '{locator}' cell on row {row} and column {column} "
f"should have contained text '{expected}' but it had '{content}'."
)
self.info(f"Table cell contains '{content}'.")
@keyword
def table_column_should_contain(
self,
locator: Union[WebElement, None, str],
column: int,
expected: str,
loglevel: str = "TRACE",
):
"""Verifies table column contains text ``expected``.
The table is located using the ``locator`` argument and its column
found using ``column``. See the `Locating elements` section for
details about the locator syntax.
Column indexes start from 1. It is possible to refer to columns
from the end by using negative indexes so that -1 is the last column,
-2 is the second last, and so on.
If a table contains cells that span multiple columns, those merged
cells count as a single column.
See `Page Should Contain Element` for an explanation about the
``loglevel`` argument.
"""
element = self._find_by_column(locator, column, expected)
if element is None:
self.ctx.log_source(loglevel)
raise AssertionError(
f"Table '{locator}' column {column} did not contain text '{expected}'."
)
@keyword
def table_footer_should_contain(
self,
locator: Union[WebElement, None, str],
expected: str,
loglevel: str = "TRACE",
):
"""Verifies table footer contains text ``expected``.
Any ``<td>`` element inside ``<tfoot>`` element is considered to
be part of the footer.
The table is located using the ``locator`` argument. See the
`Locating elements` section for details about the locator syntax.
See `Page Should Contain Element` for an explanation about the
``loglevel`` argument.
"""
element = self._find_by_footer(locator, expected)
if element is None:
self.ctx.log_source(loglevel)
raise AssertionError(
f"Table '{locator}' footer did not contain text '{expected}'."
)
@keyword
def table_header_should_contain(
self,
locator: Union[WebElement, None, str],
expected: str,
loglevel: str = "TRACE",
):
"""Verifies table header contains text ``expected``.
Any ``<th>`` element anywhere in the table is considered to be
part of the header.
The table is located using the ``locator`` argument. See the
`Locating elements` section for details about the locator syntax.
See `Page Should Contain Element` for an explanation about the
``loglevel`` argument.
"""
element = self._find_by_header(locator, expected)
if element is None:
self.ctx.log_source(loglevel)
raise AssertionError(
f"Table '{locator}' header did not contain text '{expected}'."
)
@keyword
def table_row_should_contain(
self,
locator: Union[WebElement, None, str],
row: int,
expected: str,
loglevel: str = "TRACE",
):
"""Verifies that table row contains text ``expected``.
The table is located using the ``locator`` argument and its column
found using ``column``. See the `Locating elements` section for
details about the locator syntax.
Row indexes start from 1. It is possible to refer to rows
from the end by using negative indexes so that -1 is the last row,
-2 is the second last, and so on.
If a table contains cells that span multiple rows, a match
only occurs for the uppermost row of those merged cells.
See `Page Should Contain Element` for an explanation about the
``loglevel`` argument.
"""
element = self._find_by_row(locator, row, expected)
if element is None:
self.ctx.log_source(loglevel)
raise AssertionError(
f"Table '{locator}' row {row} did not contain text '{expected}'."
)
@keyword
def table_should_contain(
self,
locator: Union[WebElement, None, str],
expected: str,
loglevel: str = "TRACE",
):
"""Verifies table contains text ``expected``.
The table is located using the ``locator`` argument. See the
`Locating elements` section for details about the locator syntax.
See `Page Should Contain Element` for an explanation about the
``loglevel`` argument.
"""
element = self._find_by_content(locator, expected)
if element is None:
self.ctx.log_source(loglevel)
raise AssertionError(
f"Table '{locator}' did not contain text '{expected}'."
)
def _find_by_content(self, table_locator, content):
return self._find(table_locator, "xpath:.//*", content)
def _find_by_header(self, table_locator, content):
return self._find(table_locator, "xpath:.//th", content)
def _find_by_footer(self, table_locator, content):
return self._find(table_locator, "xpath:.//tfoot//td", content)
def _find_by_row(self, table_locator, row, content):
position = self._index_to_position(row)
locator = f"//tr[{position}]"
return self._find(table_locator, locator, content)
def _find_by_column(self, table_locator, col, content):
position = self._index_to_position(col)
locator = f"//tr//*[self::td or self::th][{position}]"
return self._find(table_locator, locator, content)
def _index_to_position(self, index):
if index == 0:
raise ValueError("Row and column indexes must be non-zero.")
if index > 0:
return str(index)
if index == -1:
return "position()=last()"
return f"position()=last()-{abs(index) - 1}"
def _find(self, table_locator, locator, content):
table = self.find_element(table_locator)
elements = self.find_elements(locator, parent=table)
for element in elements:
if content is None:
return element
if element.text and content in element.text:
return element
return None | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/tableelement.py | 0.897659 | 0.389372 | tableelement.py | pypi |
from datetime import datetime
from typing import Union, Optional
from robot.libraries.DateTime import convert_date
from robot.utils import DotDict
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary.errors import CookieNotFound
class CookieInformation:
def __init__(
self,
name,
value,
path=None,
domain=None,
secure=False,
httpOnly=False,
expiry=None,
**extra,
):
self.name = name
self.value = value
self.path = path
self.domain = domain
self.secure = secure
self.httpOnly = httpOnly
self.expiry = datetime.fromtimestamp(expiry) if expiry else None
self.extra = extra
def __str__(self):
items = "name value path domain secure httpOnly expiry".split()
string = "\n".join(f"{item}={getattr(self, item)}" for item in items)
if self.extra:
string = f"{string}\nextra={self.extra}\n"
return string
class CookieKeywords(LibraryComponent):
@keyword
def delete_all_cookies(self):
"""Deletes all cookies."""
self.driver.delete_all_cookies()
@keyword
def delete_cookie(self, name):
"""Deletes the cookie matching ``name``.
If the cookie is not found, nothing happens.
"""
self.driver.delete_cookie(name)
@keyword
def get_cookies(self, as_dict: bool = False) -> Union[str, dict]:
"""Returns all cookies of the current page.
If ``as_dict`` argument evaluates as false, see `Boolean arguments`
for more details, then cookie information is returned as
a single string in format ``name1=value1; name2=value2; name3=value3``.
When ``as_dict`` argument evaluates as true, cookie information
is returned as Robot Framework dictionary format. The string format
can be used, for example, for logging purposes or in headers when
sending HTTP requests. The dictionary format is helpful when
the result can be passed to requests library's Create Session
keyword's optional cookies parameter.
The `` as_dict`` argument is new in SeleniumLibrary 3.3
"""
if not as_dict:
pairs = []
for cookie in self.driver.get_cookies():
pairs.append(f"{cookie['name']}={cookie['value']}")
return "; ".join(pairs)
else:
pairs = DotDict()
for cookie in self.driver.get_cookies():
pairs[cookie["name"]] = cookie["value"]
return pairs
@keyword
def get_cookie(self, name: str) -> CookieInformation:
"""Returns information of cookie with ``name`` as an object.
If no cookie is found with ``name``, keyword fails. The cookie object
contains details about the cookie. Attributes available in the object
are documented in the table below.
| = Attribute = | = Explanation = |
| name | The name of a cookie. |
| value | Value of the cookie. |
| path | Indicates a URL path, for example ``/``. |
| domain | The domain, the cookie is visible to. |
| secure | When true, the cookie is only used with HTTPS connections. |
| httpOnly | When true, the cookie is not accessible via JavaScript. |
| expiry | Python datetime object indicating when the cookie expires. |
| extra | Possible attributes outside of the WebDriver specification |
See the
[https://w3c.github.io/webdriver/#cookies|WebDriver specification]
for details about the cookie information.
Notice that ``expiry`` is specified as a
[https://docs.python.org/3/library/datetime.html#datetime.datetime|datetime object],
not as seconds since Unix Epoch like WebDriver natively does.
In some cases, example when running a browser in the cloud, it is possible that
the cookie contains other attributes than is defined in the
[https://w3c.github.io/webdriver/#cookies|WebDriver specification].
These other attributes are available in an ``extra`` attribute in the cookie
object and it contains a dictionary of the other attributes. The ``extra``
attribute is new in SeleniumLibrary 4.0.
Example:
| `Add Cookie` | foo | bar |
| ${cookie} = | `Get Cookie` | foo |
| `Should Be Equal` | ${cookie.name} | foo |
| `Should Be Equal` | ${cookie.value} | bar |
| `Should Be True` | ${cookie.expiry.year} > 2017 |
New in SeleniumLibrary 3.0.
"""
cookie = self.driver.get_cookie(name)
if not cookie:
raise CookieNotFound(f"Cookie with name '{name}' not found.")
return CookieInformation(**cookie)
@keyword
def add_cookie(
self,
name: str,
value: str,
path: Optional[str] = None,
domain: Optional[str] = None,
secure: Optional[bool] = None,
expiry: Optional[str] = None,
):
"""Adds a cookie to your current session.
``name`` and ``value`` are required, ``path``, ``domain``, ``secure``
and ``expiry`` are optional. Expiry supports the same formats as
the [http://robotframework.org/robotframework/latest/libraries/DateTime.html|DateTime]
library or an epoch timestamp.
Example:
| `Add Cookie` | foo | bar | |
| `Add Cookie` | foo | bar | domain=example.com |
| `Add Cookie` | foo | bar | expiry=2027-09-28 16:21:35 | # Expiry as timestamp. |
| `Add Cookie` | foo | bar | expiry=1822137695 | # Expiry as epoch seconds. |
Prior to SeleniumLibrary 3.0 setting expiry did not work.
"""
new_cookie = {"name": name, "value": value}
if path is not None:
new_cookie["path"] = path
if domain is not None:
new_cookie["domain"] = domain
# Secure must be True or False
if secure is not None:
new_cookie["secure"] = secure
if expiry is not None:
new_cookie["expiry"] = self._expiry(expiry)
self.driver.add_cookie(new_cookie)
def _expiry(self, expiry):
try:
return int(expiry)
except (ValueError, TypeError):
return int(convert_date(expiry, result_format="epoch")) | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/cookie.py | 0.91193 | 0.246369 | cookie.py | pypi |
import os
from typing import Union
from robot.utils import get_link_path
from selenium.webdriver.remote.webelement import WebElement
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary.utils.path_formatter import _format_path
DEFAULT_FILENAME_PAGE = "selenium-screenshot-{index}.png"
DEFAULT_FILENAME_ELEMENT = "selenium-element-screenshot-{index}.png"
EMBED = "EMBED"
class ScreenshotKeywords(LibraryComponent):
@keyword
def set_screenshot_directory(self, path: Union[None, str]) -> str:
"""Sets the directory for captured screenshots.
``path`` argument specifies the absolute path to a directory where
the screenshots should be written to. If the directory does not
exist, it will be created. The directory can also be set when
`importing` the library. If it is not configured anywhere,
screenshots are saved to the same directory where Robot Framework's
log file is written.
If ``path`` equals to EMBED (case insensitive) and
`Capture Page Screenshot` or `capture Element Screenshot` keywords
filename argument is not changed from the default value, then
the page or element screenshot is embedded as Base64 image to
the log.html.
The previous value is returned and can be used to restore
the original value later if needed.
Returning the previous value is new in SeleniumLibrary 3.0.
The persist argument was removed in SeleniumLibrary 3.2 and
EMBED is new in SeleniumLibrary 4.2.
"""
if path is None:
path = None
elif path.upper() == EMBED:
path = EMBED
else:
path = os.path.abspath(path)
self._create_directory(path)
previous = self._screenshot_root_directory
self._screenshot_root_directory = path
return previous
@keyword
def capture_page_screenshot(self, filename: str = DEFAULT_FILENAME_PAGE) -> str:
"""Takes a screenshot of the current page and embeds it into a log file.
``filename`` argument specifies the name of the file to write the
screenshot into. The directory where screenshots are saved can be
set when `importing` the library or by using the `Set Screenshot
Directory` keyword. If the directory is not configured, screenshots
are saved to the same directory where Robot Framework's log file is
written.
If ``filename`` equals to EMBED (case insensitive), then screenshot
is embedded as Base64 image to the log.html. In this case file is not
created in the filesystem.
Starting from SeleniumLibrary 1.8, if ``filename`` contains marker
``{index}``, it will be automatically replaced with an unique running
index, preventing files to be overwritten. Indices start from 1,
and how they are represented can be customized using Python's
[https://docs.python.org/3/library/string.html#format-string-syntax|
format string syntax].
An absolute path to the created screenshot file is returned or if
``filename`` equals to EMBED, word `EMBED` is returned.
Support for EMBED is new in SeleniumLibrary 4.2
Examples:
| `Capture Page Screenshot` | |
| `File Should Exist` | ${OUTPUTDIR}/selenium-screenshot-1.png |
| ${path} = | `Capture Page Screenshot` |
| `File Should Exist` | ${OUTPUTDIR}/selenium-screenshot-2.png |
| `File Should Exist` | ${path} |
| `Capture Page Screenshot` | custom_name.png |
| `File Should Exist` | ${OUTPUTDIR}/custom_name.png |
| `Capture Page Screenshot` | custom_with_index_{index}.png |
| `File Should Exist` | ${OUTPUTDIR}/custom_with_index_1.png |
| `Capture Page Screenshot` | formatted_index_{index:03}.png |
| `File Should Exist` | ${OUTPUTDIR}/formatted_index_001.png |
| `Capture Page Screenshot` | EMBED |
| `File Should Not Exist` | EMBED |
"""
if not self.drivers.current:
self.info("Cannot capture screenshot because no browser is open.")
return
if self._decide_embedded(filename):
return self._capture_page_screen_to_log()
return self._capture_page_screenshot_to_file(filename)
def _capture_page_screenshot_to_file(self, filename):
path = self._get_screenshot_path(filename)
self._create_directory(path)
if not self.driver.save_screenshot(path):
raise RuntimeError(f"Failed to save screenshot '{path}'.")
self._embed_to_log_as_file(path, 800)
return path
def _capture_page_screen_to_log(self):
screenshot_as_base64 = self.driver.get_screenshot_as_base64()
self._embed_to_log_as_base64(screenshot_as_base64, 800)
return EMBED
@keyword
def capture_element_screenshot(
self,
locator: Union[WebElement, None, str],
filename: str = DEFAULT_FILENAME_ELEMENT,
) -> str:
"""Captures a screenshot from the element identified by ``locator`` and embeds it into log file.
See `Capture Page Screenshot` for details about ``filename`` argument.
See the `Locating elements` section for details about the locator
syntax.
An absolute path to the created element screenshot is returned.
Support for capturing the screenshot from an element has limited support
among browser vendors. Please check the browser vendor driver documentation
does the browser support capturing a screenshot from an element.
New in SeleniumLibrary 3.3. Support for EMBED is new in SeleniumLibrary 4.2.
Examples:
| `Capture Element Screenshot` | id:image_id | |
| `Capture Element Screenshot` | id:image_id | ${OUTPUTDIR}/id_image_id-1.png |
| `Capture Element Screenshot` | id:image_id | EMBED |
"""
if not self.drivers.current:
self.info(
"Cannot capture screenshot from element because no browser is open."
)
return
element = self.find_element(locator, required=True)
if self._decide_embedded(filename):
return self._capture_element_screen_to_log(element)
return self._capture_element_screenshot_to_file(element, filename)
def _capture_element_screenshot_to_file(self, element, filename):
path = self._get_screenshot_path(filename)
self._create_directory(path)
if not element.screenshot(path):
raise RuntimeError(f"Failed to save element screenshot '{path}'.")
self._embed_to_log_as_file(path, 400)
return path
def _capture_element_screen_to_log(self, element):
self._embed_to_log_as_base64(element.screenshot_as_base64, 400)
return EMBED
@property
def _screenshot_root_directory(self):
return self.ctx.screenshot_root_directory
@_screenshot_root_directory.setter
def _screenshot_root_directory(self, value):
self.ctx.screenshot_root_directory = value
def _decide_embedded(self, filename):
filename = filename.lower()
if (
filename == DEFAULT_FILENAME_PAGE
and self._screenshot_root_directory == EMBED
):
return True
if (
filename == DEFAULT_FILENAME_ELEMENT
and self._screenshot_root_directory == EMBED
):
return True
if filename == EMBED.lower():
return True
return False
def _get_screenshot_path(self, filename):
if self._screenshot_root_directory != EMBED:
directory = self._screenshot_root_directory or self.log_dir
else:
directory = self.log_dir
filename = filename.replace("/", os.sep)
index = 0
while True:
index += 1
formatted = _format_path(filename, index)
path = os.path.join(directory, formatted)
# filename didn't contain {index} or unique path was found
if formatted == filename or not os.path.exists(path):
return path
def _create_directory(self, path):
target_dir = os.path.dirname(path)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
def _embed_to_log_as_base64(self, screenshot_as_base64, width):
# base64 image is shown as on its own row and thus previous row is closed on
# purpose. Depending on Robot's log structure is a bit risky.
self.info(
'</td></tr><tr><td colspan="3">'
'<img alt="screenshot" class="robot-seleniumlibrary-screenshot" '
f'src="data:image/png;base64,{screenshot_as_base64}" width="{width}px">',
html=True,
)
def _embed_to_log_as_file(self, path, width):
# Image is shown on its own row and thus previous row is closed on
# purpose. Depending on Robot's log structure is a bit risky.
src = get_link_path(path, self.log_dir)
self.info(
'</td></tr><tr><td colspan="3">'
f'<a href="{src}"><img src="{src}" width="{width}px"></a>',
html=True,
) | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/screenshot.py | 0.850996 | 0.231213 | screenshot.py | pypi |
from typing import Optional
from SeleniumLibrary.base import LibraryComponent, keyword
class RunOnFailureKeywords(LibraryComponent):
@keyword
def register_keyword_to_run_on_failure(self, keyword: Optional[str]) -> str:
"""Sets the keyword to execute, when a SeleniumLibrary keyword fails.
``keyword`` is the name of a keyword that will be executed if a
SeleniumLibrary keyword fails. It is possible to use any available
keyword, including user keywords or keywords from other libraries,
but the keyword must not take any arguments.
The initial keyword to use is set when `importing` the library, and
the keyword that is used by default is `Capture Page Screenshot`.
Taking a screenshot when something failed is a very useful
feature, but notice that it can slow down the execution.
It is possible to use string ``NOTHING`` or ``NONE``,
case-insensitively, as well as Python ``None`` to disable this
feature altogether.
This keyword returns the name of the previously registered
failure keyword or Python ``None`` if this functionality was
previously disabled. The return value can be always used to
restore the original value later.
Example:
| `Register Keyword To Run On Failure` | Log Source |
| ${previous kw}= | `Register Keyword To Run On Failure` | NONE |
| `Register Keyword To Run On Failure` | ${previous kw} |
Changes in SeleniumLibrary 3.0:
- Possible to use string ``NONE`` or Python ``None`` to disable the
functionality.
- Return Python ``None`` when the functionality was disabled earlier.
In previous versions special value ``No Keyword`` was returned and
it could not be used to restore the original state.
"""
old_keyword = self.ctx.run_on_failure_keyword
new_keyword = self.resolve_keyword(keyword)
self.ctx.run_on_failure_keyword = new_keyword
self.info(f"{(new_keyword or 'No keyword')} will be run on failure.")
return old_keyword
@staticmethod
def resolve_keyword(name):
if name is None:
return None
if (
isinstance(name, str)
and name.upper() == "NOTHING"
or name.upper() == "NONE"
):
return None
return name | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/runonfailure.py | 0.912799 | 0.229638 | runonfailure.py | pypi |
from typing import List, Optional, Union
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.ui import Select
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary.utils import is_truthy, plural_or_not
class SelectElementKeywords(LibraryComponent):
@keyword
def get_list_items(
self, locator: Union[WebElement, str], values: bool = False
) -> List[str]:
"""Returns all labels or values of selection list ``locator``.
See the `Locating elements` section for details about the locator
syntax.
Returns visible labels by default, but values can be returned by
setting the ``values`` argument to a true value (see `Boolean
arguments`).
Example:
| ${labels} = | `Get List Items` | mylist | |
| ${values} = | `Get List Items` | css:#example select | values=True |
Support to return values is new in SeleniumLibrary 3.0.
"""
options = self._get_options(locator)
if is_truthy(values):
return self._get_values(options)
else:
return self._get_labels(options)
@keyword
def get_selected_list_label(self, locator: Union[WebElement, str]) -> str:
"""Returns the label of selected option from selection list ``locator``.
If there are multiple selected options, the label of the first option
is returned.
See the `Locating elements` section for details about the locator
syntax.
"""
select = self._get_select_list(locator)
return select.first_selected_option.text
@keyword
def get_selected_list_labels(self, locator: Union[WebElement, str]) -> List[str]:
"""Returns labels of selected options from selection list ``locator``.
Starting from SeleniumLibrary 3.0, returns an empty list if there
are no selections. In earlier versions, this caused an error.
See the `Locating elements` section for details about the locator
syntax.
"""
options = self._get_selected_options(locator)
return self._get_labels(options)
@keyword
def get_selected_list_value(self, locator: Union[WebElement, str]) -> str:
"""Returns the value of selected option from selection list ``locator``.
If there are multiple selected options, the value of the first option
is returned.
See the `Locating elements` section for details about the locator
syntax.
"""
select = self._get_select_list(locator)
return select.first_selected_option.get_attribute("value")
@keyword
def get_selected_list_values(self, locator: Union[WebElement, str]) -> List[str]:
"""Returns values of selected options from selection list ``locator``.
Starting from SeleniumLibrary 3.0, returns an empty list if there
are no selections. In earlier versions, this caused an error.
See the `Locating elements` section for details about the locator
syntax.
"""
options = self._get_selected_options(locator)
return self._get_values(options)
@keyword
def list_selection_should_be(self, locator: Union[WebElement, str], *expected: str):
"""Verifies selection list ``locator`` has ``expected`` options selected.
It is possible to give expected options both as visible labels and
as values. Starting from SeleniumLibrary 3.0, mixing labels and
values is not possible. Order of the selected options is not
validated.
If no expected options are given, validates that the list has
no selections. A more explicit alternative is using `List Should
Have No Selections`.
See the `Locating elements` section for details about the locator
syntax.
Examples:
| `List Selection Should Be` | gender | Female | |
| `List Selection Should Be` | interests | Test Automation | Python |
"""
self.info(
f"Verifying list '{locator}' has option{plural_or_not(expected)} "
f"[ {' | '.join(expected)} ] selected."
)
self.page_should_contain_list(locator)
options = self._get_selected_options(locator)
labels = self._get_labels(options)
values = self._get_values(options)
if sorted(expected) not in [sorted(labels), sorted(values)]:
raise AssertionError(
f"List '{locator}' should have had selection [ {' | '.join(expected)} ] "
f"but selection was [ {self._format_selection(labels, values)} ]."
)
def _format_selection(self, labels, values):
return " | ".join(f"{label} ({value})" for label, value in zip(labels, values))
@keyword
def list_should_have_no_selections(self, locator: Union[WebElement, str]):
"""Verifies selection list ``locator`` has no options selected.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Verifying list '{locator}' has no selections.")
options = self._get_selected_options(locator)
if options:
selection = self._format_selection(
self._get_labels(options), self._get_values(options)
)
raise AssertionError(
f"List '{locator}' should have had no selection "
f"but selection was [ {selection} ]."
)
@keyword
def page_should_contain_list(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies selection list ``locator`` is found from current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax.
"""
self.assert_page_contains(locator, "list", message, loglevel)
@keyword
def page_should_not_contain_list(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies selection list ``locator`` is not found from current page.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
See the `Locating elements` section for details about the locator
syntax.
"""
self.assert_page_not_contains(locator, "list", message, loglevel)
@keyword
def select_all_from_list(self, locator: Union[WebElement, str]):
"""Selects all options from multi-selection list ``locator``.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Selecting all options from list '{locator}'.")
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError(
"'Select All From List' works only with multi-selection lists."
)
for index in range(len(select.options)):
select.select_by_index(index)
@keyword
def select_from_list_by_index(self, locator: Union[WebElement, str], *indexes: str):
"""Selects options from selection list ``locator`` by ``indexes``.
Indexes of list options start from 0.
If more than one option is given for a single-selection list,
the last value will be selected. With multi-selection lists all
specified options are selected, but possible old selections are
not cleared.
See the `Locating elements` section for details about the locator
syntax.
"""
if not indexes:
raise ValueError("No indexes given.")
plural = "" if len(indexes) == 1 else "es"
self.info(
f"Selecting options from selection list '{locator}' "
f"by index{plural} {', '.join(indexes)}."
)
select = self._get_select_list(locator)
for index in indexes:
select.select_by_index(int(index))
@keyword
def select_from_list_by_value(self, locator: Union[WebElement, str], *values: str):
"""Selects options from selection list ``locator`` by ``values``.
If more than one option is given for a single-selection list,
the last value will be selected. With multi-selection lists all
specified options are selected, but possible old selections are
not cleared.
See the `Locating elements` section for details about the locator
syntax.
"""
if not values:
raise ValueError("No values given.")
self.info(
f"Selecting options from selection list '{locator}' by "
f"value{plural_or_not(values)} {', '.join(values)}."
)
select = self._get_select_list(locator)
for value in values:
select.select_by_value(value)
@keyword
def select_from_list_by_label(self, locator: Union[WebElement, str], *labels: str):
"""Selects options from selection list ``locator`` by ``labels``.
If more than one option is given for a single-selection list,
the last value will be selected. With multi-selection lists all
specified options are selected, but possible old selections are
not cleared.
See the `Locating elements` section for details about the locator
syntax.
"""
if not labels:
raise ValueError("No labels given.")
self.info(
f"Selecting options from selection list '{locator}' "
f"by label{plural_or_not(labels)} {', '.join(labels)}."
)
select = self._get_select_list(locator)
for label in labels:
select.select_by_visible_text(label)
@keyword
def unselect_all_from_list(self, locator: Union[WebElement, str]):
"""Unselects all options from multi-selection list ``locator``.
See the `Locating elements` section for details about the locator
syntax.
New in SeleniumLibrary 3.0.
"""
self.info(f"Unselecting all options from list '{locator}'.")
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError(
"Un-selecting options works only with multi-selection lists."
)
select.deselect_all()
@keyword
def unselect_from_list_by_index(
self, locator: Union[WebElement, str], *indexes: str
):
"""Unselects options from selection list ``locator`` by ``indexes``.
Indexes of list options start from 0. This keyword works only with
multi-selection lists.
See the `Locating elements` section for details about the locator
syntax.
"""
if not indexes:
raise ValueError("No indexes given.")
plurar = "" if len(indexes) == 1 else "es"
self.info(
f"Un-selecting options from selection list '{locator}' by index{plurar} "
f"{', '.join(indexes)}."
)
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError(
"Un-selecting options works only with multi-selection lists."
)
for index in indexes:
select.deselect_by_index(int(index))
@keyword
def unselect_from_list_by_value(
self, locator: Union[WebElement, str], *values: str
):
"""Unselects options from selection list ``locator`` by ``values``.
This keyword works only with multi-selection lists.
See the `Locating elements` section for details about the locator
syntax.
"""
if not values:
raise ValueError("No values given.")
self.info(
f"Un-selecting options from selection list '{locator}' by "
f"value{plural_or_not(values)} {', '.join(values)}."
)
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError(
"Un-selecting options works only with multi-selection lists."
)
for value in values:
select.deselect_by_value(value)
@keyword
def unselect_from_list_by_label(
self, locator: Union[WebElement, str], *labels: str
):
"""Unselects options from selection list ``locator`` by ``labels``.
This keyword works only with multi-selection lists.
See the `Locating elements` section for details about the locator
syntax.
"""
if not labels:
raise ValueError("No labels given.")
self.info(
f"Un-selecting options from selection list '{locator}' by "
f"label{plural_or_not(labels)} {', '.join(labels)}."
)
select = self._get_select_list(locator)
if not select.is_multiple:
raise RuntimeError(
"Un-selecting options works only with multi-selection lists."
)
for label in labels:
select.deselect_by_visible_text(label)
def _get_select_list(self, locator: Union[WebElement, str]):
el = self.find_element(locator, tag="list")
return Select(el)
def _get_options(self, locator: Union[WebElement, str]):
return self._get_select_list(locator).options
def _get_selected_options(self, locator: Union[WebElement, str]):
return self._get_select_list(locator).all_selected_options
def _get_labels(self, options):
return [opt.text for opt in options]
def _get_values(self, options):
return [opt.get_attribute("value") for opt in options] | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/selectelement.py | 0.931009 | 0.425307 | selectelement.py | pypi |
from collections import namedtuple
from typing import List, Optional, Tuple, Union
from SeleniumLibrary.utils import is_noney
from robot.utils import plural_or_not, is_truthy
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remote.webelement import WebElement
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary.errors import ElementNotFound
from SeleniumLibrary.utils.types import type_converter
class ElementKeywords(LibraryComponent):
@keyword(name="Get WebElement")
def get_webelement(self, locator: Union[WebElement, str]) -> WebElement:
"""Returns the first WebElement matching the given ``locator``.
See the `Locating elements` section for details about the locator
syntax.
"""
return self.find_element(locator)
@keyword(name="Get WebElements")
def get_webelements(self, locator: Union[WebElement, str]) -> List[WebElement]:
"""Returns a list of WebElement objects matching the ``locator``.
See the `Locating elements` section for details about the locator
syntax.
Starting from SeleniumLibrary 3.0, the keyword returns an empty
list if there are no matching elements. In previous releases, the
keyword failed in this case.
"""
return self.find_elements(locator)
@keyword
def element_should_contain(
self,
locator: Union[WebElement, str],
expected: Union[None, str],
message: Optional[str] = None,
ignore_case: bool = False,
):
"""Verifies that element ``locator`` contains text ``expected``.
See the `Locating elements` section for details about the locator
syntax.
The ``message`` argument can be used to override the default error
message.
The ``ignore_case`` argument can be set to True to compare case
insensitive, default is False. New in SeleniumLibrary 3.1.
``ignore_case`` argument is new in SeleniumLibrary 3.1.
Use `Element Text Should Be` if you want to match the exact text,
not a substring.
"""
actual = actual_before = self.find_element(locator).text
expected_before = expected
if ignore_case:
actual = actual.lower()
expected = expected.lower()
if expected not in actual:
if message is None:
message = (
f"Element '{locator}' should have contained text '{expected_before}' but "
f"its text was '{actual_before}'."
)
raise AssertionError(message)
self.info(f"Element '{locator}' contains text '{expected_before}'.")
@keyword
def element_should_not_contain(
self,
locator: Union[WebElement, str],
expected: Union[None, str],
message: Optional[str] = None,
ignore_case: bool = False,
):
"""Verifies that element ``locator`` does not contain text ``expected``.
See the `Locating elements` section for details about the locator
syntax.
The ``message`` argument can be used to override the default error
message.
The ``ignore_case`` argument can be set to True to compare case
insensitive, default is False.
``ignore_case`` argument new in SeleniumLibrary 3.1.
"""
actual = self.find_element(locator).text
expected_before = expected
if ignore_case:
actual = actual.lower()
expected = expected.lower()
if expected in actual:
if message is None:
message = (
f"Element '{locator}' should not contain text '{expected_before}' but "
"it did."
)
raise AssertionError(message)
self.info(f"Element '{locator}' does not contain text '{expected_before}'.")
@keyword
def page_should_contain(self, text: str, loglevel: str = "TRACE"):
"""Verifies that current page contains ``text``.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional ``loglevel``
argument. Valid log levels are ``TRACE`` (default), ``DEBUG``,
``INFO``, ``WARN``, and ``NONE``. If the log level is ``NONE``
or below the current active log level the source will not be logged.
"""
if not self._page_contains(text):
self.ctx.log_source(loglevel)
raise AssertionError(
f"Page should have contained text '{text}' but did not."
)
self.info(f"Current page contains text '{text}'.")
@keyword
def page_should_contain_element(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
limit: Optional[int] = None,
):
"""Verifies that element ``locator`` is found on the current page.
See the `Locating elements` section for details about the locator
syntax.
The ``message`` argument can be used to override the default error
message.
The ``limit`` argument can used to define how many elements the
page should contain. When ``limit`` is ``None`` (default) page can
contain one or more elements. When limit is a number, page must
contain same number of elements.
See `Page Should Contain` for an explanation about the ``loglevel``
argument.
Examples assumes that locator matches to two elements.
| `Page Should Contain Element` | div_name | limit=1 | # Keyword fails. |
| `Page Should Contain Element` | div_name | limit=2 | # Keyword passes. |
| `Page Should Contain Element` | div_name | limit=none | # None is considered one or more. |
| `Page Should Contain Element` | div_name | | # Same as above. |
The ``limit`` argument is new in SeleniumLibrary 3.0.
"""
if limit is None:
return self.assert_page_contains(
locator, message=message, loglevel=loglevel
)
count = len(self.find_elements(locator))
if count == limit:
self.info(f"Current page contains {count} element(s).")
else:
if message is None:
message = (
f'Page should have contained "{limit}" element(s), '
f'but it did contain "{count}" element(s).'
)
self.ctx.log_source(loglevel)
raise AssertionError(message)
@keyword
def page_should_not_contain(self, text: str, loglevel: str = "TRACE"):
"""Verifies the current page does not contain ``text``.
See `Page Should Contain` for an explanation about the ``loglevel``
argument.
"""
if self._page_contains(text):
self.ctx.log_source(loglevel)
raise AssertionError(f"Page should not have contained text '{text}'.")
self.info(f"Current page does not contain text '{text}'.")
@keyword
def page_should_not_contain_element(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies that element ``locator`` is not found on the current page.
See the `Locating elements` section for details about the locator
syntax.
See `Page Should Contain` for an explanation about ``message`` and
``loglevel`` arguments.
"""
self.assert_page_not_contains(locator, message=message, loglevel=loglevel)
@keyword
def assign_id_to_element(self, locator: Union[WebElement, str], id: str):
"""Assigns a temporary ``id`` to the element specified by ``locator``.
This is mainly useful if the locator is complicated and/or slow XPath
expression and it is needed multiple times. Identifier expires when
the page is reloaded.
See the `Locating elements` section for details about the locator
syntax.
Example:
| `Assign ID to Element` | //ul[@class='example' and ./li[contains(., 'Stuff')]] | my id |
| `Page Should Contain Element` | my id |
"""
self.info(f"Assigning temporary id '{id}' to element '{locator}'.")
element = self.find_element(locator)
self.driver.execute_script(f"arguments[0].id = '{id}';", element)
@keyword
def element_should_be_disabled(self, locator: Union[WebElement, str]):
"""Verifies that element identified by ``locator`` is disabled.
This keyword considers also elements that are read-only to be
disabled.
See the `Locating elements` section for details about the locator
syntax.
"""
if self.is_element_enabled(locator):
raise AssertionError(f"Element '{locator}' is enabled.")
@keyword
def element_should_be_enabled(self, locator: Union[WebElement, str]):
"""Verifies that element identified by ``locator`` is enabled.
This keyword considers also elements that are read-only to be
disabled.
See the `Locating elements` section for details about the locator
syntax.
"""
if not self.is_element_enabled(locator):
raise AssertionError(f"Element '{locator}' is disabled.")
@keyword
def element_should_be_focused(self, locator: Union[WebElement, str]):
"""Verifies that element identified by ``locator`` is focused.
See the `Locating elements` section for details about the locator
syntax.
New in SeleniumLibrary 3.0.
"""
element = self.find_element(locator)
focused = self.driver.switch_to.active_element
# Selenium 3.6.0 with Firefox return dict which contains the selenium WebElement
if isinstance(focused, dict):
focused = focused["value"]
if element != focused:
raise AssertionError(f"Element '{locator}' does not have focus.")
@keyword
def element_should_be_visible(
self, locator: Union[WebElement, str], message: Optional[str] = None
):
"""Verifies that the element identified by ``locator`` is visible.
Herein, visible means that the element is logically visible, not
optically visible in the current browser viewport. For example,
an element that carries ``display:none`` is not logically visible,
so using this keyword on that element would fail.
See the `Locating elements` section for details about the locator
syntax.
The ``message`` argument can be used to override the default error
message.
"""
if not self.find_element(locator).is_displayed():
if message is None:
message = f"The element '{locator}' should be visible, but it is not."
raise AssertionError(message)
self.info(f"Element '{locator}' is displayed.")
@keyword
def element_should_not_be_visible(
self, locator: Union[WebElement, str], message: Optional[str] = None
):
"""Verifies that the element identified by ``locator`` is NOT visible.
Passes if the element does not exists. See `Element Should Be Visible`
for more information about visibility and supported arguments.
"""
element = self.find_element(locator, required=False)
if element is None:
self.info(f"Element '{locator}' did not exist.")
elif not element.is_displayed():
self.info(f"Element '{locator}' exists but is not displayed.")
else:
if message is None:
message = f"The element '{locator}' should not be visible, but it is."
raise AssertionError(message)
@keyword
def element_text_should_be(
self,
locator: Union[WebElement, str],
expected: Union[None, str],
message: Optional[str] = None,
ignore_case: bool = False,
):
"""Verifies that element ``locator`` contains exact the text ``expected``.
See the `Locating elements` section for details about the locator
syntax.
The ``message`` argument can be used to override the default error
message.
The ``ignore_case`` argument can be set to True to compare case
insensitive, default is False.
``ignore_case`` argument is new in SeleniumLibrary 3.1.
Use `Element Should Contain` if a substring match is desired.
"""
self.info(f"Verifying element '{locator}' contains exact text '{expected}'.")
text = before_text = self.find_element(locator).text
if ignore_case:
text = text.lower()
expected = expected.lower()
if text != expected:
if message is None:
message = (
f"The text of element '{locator}' should have been '{expected}' "
f"but it was '{before_text}'."
)
raise AssertionError(message)
@keyword
def element_text_should_not_be(
self,
locator: Union[WebElement, str],
not_expected: Union[None, str],
message: Optional[str] = None,
ignore_case: bool = False,
):
"""Verifies that element ``locator`` does not contain exact the text ``not_expected``.
See the `Locating elements` section for details about the locator
syntax.
The ``message`` argument can be used to override the default error
message.
The ``ignore_case`` argument can be set to True to compare case
insensitive, default is False.
New in SeleniumLibrary 3.1.1
"""
self.info(
f"Verifying element '{locator}' does not contain exact text '{not_expected}'."
)
text = self.find_element(locator).text
before_not_expected = not_expected
if ignore_case:
text = text.lower()
not_expected = not_expected.lower()
if text == not_expected:
if message is None:
message = f"The text of element '{locator}' was not supposed to be '{before_not_expected}'."
raise AssertionError(message)
@keyword
def get_element_attribute(
self, locator: Union[WebElement, str], attribute: str
) -> str:
"""Returns the value of ``attribute`` from the element ``locator``.
See the `Locating elements` section for details about the locator
syntax.
Example:
| ${id}= | `Get Element Attribute` | css:h1 | id |
Passing attribute name as part of the ``locator`` was removed
in SeleniumLibrary 3.2. The explicit ``attribute`` argument
should be used instead.
"""
return self.find_element(locator).get_attribute(attribute)
@keyword
def element_attribute_value_should_be(
self,
locator: Union[WebElement, str],
attribute: str,
expected: Union[None, str],
message: Optional[str] = None,
):
"""Verifies element identified by ``locator`` contains expected attribute value.
See the `Locating elements` section for details about the locator
syntax.
Example:
`Element Attribute Value Should Be` | css:img | href | value
New in SeleniumLibrary 3.2.
"""
current_expected = self.find_element(locator).get_attribute(attribute)
if current_expected != expected:
if message is None:
message = (
f"Element '{locator}' attribute should have value '{expected}' "
f"({type_converter(expected)}) but its value was '{current_expected}' "
f"({type_converter(current_expected)})."
)
raise AssertionError(message)
self.info(
f"Element '{locator}' attribute '{attribute}' contains value '{expected}'."
)
@keyword
def get_horizontal_position(self, locator: Union[WebElement, str]) -> int:
"""Returns the horizontal position of the element identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax.
The position is returned in pixels off the left side of the page,
as an integer.
See also `Get Vertical Position`.
"""
return self.find_element(locator).location["x"]
@keyword
def get_element_size(self, locator: Union[WebElement, str]) -> Tuple[int, int]:
"""Returns width and height of the element identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax.
Both width and height are returned as integers.
Example:
| ${width} | ${height} = | `Get Element Size` | css:div#container |
"""
element = self.find_element(locator)
return element.size["width"], element.size["height"]
@keyword
def cover_element(self, locator: Union[WebElement, str]):
"""Will cover elements identified by ``locator`` with a blue div without breaking page layout.
See the `Locating elements` section for details about the locator
syntax.
New in SeleniumLibrary 3.3.0
Example:
|`Cover Element` | css:div#container |
"""
elements = self.find_elements(locator)
if not elements:
raise ElementNotFound(f"No element with locator '{locator}' found.")
for element in elements:
script = """
old_element = arguments[0];
let newDiv = document.createElement('div');
newDiv.setAttribute("name", "covered");
newDiv.style.backgroundColor = 'blue';
newDiv.style.zIndex = '999';
newDiv.style.top = old_element.offsetTop + 'px';
newDiv.style.left = old_element.offsetLeft + 'px';
newDiv.style.height = old_element.offsetHeight + 'px';
newDiv.style.width = old_element.offsetWidth + 'px';
old_element.parentNode.insertBefore(newDiv, old_element);
old_element.remove();
newDiv.parentNode.style.overflow = 'hidden';
"""
self.driver.execute_script(script, element)
@keyword
def get_value(self, locator: Union[WebElement, str]) -> str:
"""Returns the value attribute of the element identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax.
"""
return self.get_element_attribute(locator, "value")
@keyword
def get_text(self, locator: Union[WebElement, str]) -> str:
"""Returns the text value of the element identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax.
"""
return self.find_element(locator).text
@keyword
def clear_element_text(self, locator: Union[WebElement, str]):
"""Clears the value of the text-input-element identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax.
"""
self.find_element(locator).clear()
@keyword
def get_vertical_position(self, locator: Union[WebElement, str]) -> int:
"""Returns the vertical position of the element identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax.
The position is returned in pixels off the top of the page,
as an integer.
See also `Get Horizontal Position`.
"""
return self.find_element(locator).location["y"]
@keyword
def click_button(
self, locator: Union[WebElement, str], modifier: Union[bool, str] = False
):
"""Clicks the button identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, buttons are
searched using ``id``, ``name``, and ``value``.
See the `Click Element` keyword for details about the
``modifier`` argument.
The ``modifier`` argument is new in SeleniumLibrary 3.3
"""
if not modifier:
self.info(f"Clicking button '{locator}'.")
element = self.find_element(locator, tag="input", required=False)
if not element:
element = self.find_element(locator, tag="button")
element.click()
else:
self._click_with_modifier(locator, ["button", "input"], modifier)
@keyword
def click_image(
self, locator: Union[WebElement, str], modifier: Union[bool, str] = False
):
"""Clicks an image identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, images are searched
using ``id``, ``name``, ``src`` and ``alt``.
See the `Click Element` keyword for details about the
``modifier`` argument.
The ``modifier`` argument is new in SeleniumLibrary 3.3
"""
if not modifier:
self.info(f"Clicking image '{locator}'.")
element = self.find_element(locator, tag="image", required=False)
if not element:
# A form may have an image as it's submit trigger.
element = self.find_element(locator, tag="input")
element.click()
else:
self._click_with_modifier(locator, ["image", "input"], modifier)
@keyword
def click_link(
self, locator: Union[WebElement, str], modifier: Union[bool, str] = False
):
"""Clicks a link identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, links are searched
using ``id``, ``name``, ``href`` and the link text.
See the `Click Element` keyword for details about the
``modifier`` argument.
The ``modifier`` argument is new in SeleniumLibrary 3.3
"""
if not modifier:
self.info(f"Clicking link '{locator}'.")
self.find_element(locator, tag="link").click()
else:
self._click_with_modifier(locator, ["link", "link"], modifier)
@keyword
def click_element(
self,
locator: Union[WebElement, str],
modifier: Union[bool, str] = False,
action_chain: bool = False,
):
"""Click the element identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax.
The ``modifier`` argument can be used to pass
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html#selenium.webdriver.common.keys.Keys|Selenium Keys]
when clicking the element. The `+` can be used as a separator
for different Selenium Keys. The `CTRL` is internally translated to
the `CONTROL` key. The ``modifier`` is space and case insensitive, example
"alt" and " aLt " are supported formats to
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html#selenium.webdriver.common.keys.Keys.ALT|ALT key]
. If ``modifier`` does not match to Selenium Keys, keyword fails.
If ``action_chain`` argument is true, see `Boolean arguments` for more
details on how to set boolean argument, then keyword uses ActionChain
based click instead of the <web_element>.click() function. If both
``action_chain`` and ``modifier`` are defined, the click will be
performed using ``modifier`` and ``action_chain`` will be ignored.
Example:
| Click Element | id:button | | # Would click element without any modifiers. |
| Click Element | id:button | CTRL | # Would click element with CTLR key pressed down. |
| Click Element | id:button | CTRL+ALT | # Would click element with CTLR and ALT keys pressed down. |
| Click Element | id:button | action_chain=True | # Clicks the button using an Selenium ActionChains |
The ``modifier`` argument is new in SeleniumLibrary 3.2
The ``action_chain`` argument is new in SeleniumLibrary 4.1
"""
if is_truthy(modifier):
self._click_with_modifier(locator, [None, None], modifier)
elif action_chain:
self._click_with_action_chain(locator)
else:
self.info(f"Clicking element '{locator}'.")
self.find_element(locator).click()
def _click_with_action_chain(self, locator: Union[WebElement, str]):
self.info(f"Clicking '{locator}' using an action chain.")
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
element = self.find_element(locator)
action.move_to_element(element)
action.click()
action.perform()
def _click_with_modifier(self, locator, tag, modifier):
self.info(
f"Clicking {tag if tag[0] else 'element'} '{locator}' with {modifier}."
)
modifier = self.parse_modifier(modifier)
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
for item in modifier:
action.key_down(item)
element = self.find_element(locator, tag=tag[0], required=False)
if not element:
element = self.find_element(locator, tag=tag[1])
action.click(element)
for item in modifier:
action.key_up(item)
action.perform()
@keyword
def click_element_at_coordinates(
self, locator: Union[WebElement, str], xoffset: int, yoffset: int
):
"""Click the element ``locator`` at ``xoffset/yoffset``.
The Cursor is moved and the center of the element and x/y coordinates are
calculated from that point.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(
f"Clicking element '{locator}' at coordinates x={xoffset}, y={yoffset}."
)
element = self.find_element(locator)
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.move_to_element(element)
action.move_by_offset(xoffset, yoffset)
action.click()
action.perform()
@keyword
def double_click_element(self, locator: Union[WebElement, str]):
"""Double clicks the element identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Double clicking element '{locator}'.")
element = self.find_element(locator)
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.double_click(element).perform()
@keyword
def set_focus_to_element(self, locator: Union[WebElement, str]):
"""Sets the focus to the element identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax.
Prior to SeleniumLibrary 3.0 this keyword was named `Focus`.
"""
element = self.find_element(locator)
self.driver.execute_script("arguments[0].focus();", element)
@keyword
def scroll_element_into_view(self, locator: Union[WebElement, str]):
"""Scrolls the element identified by ``locator`` into view.
See the `Locating elements` section for details about the locator
syntax.
New in SeleniumLibrary 3.2.0
"""
element = self.find_element(locator)
ActionChains(self.driver, duration=self.ctx.action_chain_delay).move_to_element(element).perform()
@keyword
def drag_and_drop(
self, locator: Union[WebElement, str], target: Union[WebElement, str]
):
"""Drags the element identified by ``locator`` into the ``target`` element.
The ``locator`` argument is the locator of the dragged element
and the ``target`` is the locator of the target. See the
`Locating elements` section for details about the locator syntax.
Example:
| `Drag And Drop` | css:div#element | css:div.target |
"""
element = self.find_element(locator)
target = self.find_element(target)
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.drag_and_drop(element, target).perform()
@keyword
def drag_and_drop_by_offset(
self, locator: Union[WebElement, str], xoffset: int, yoffset: int
):
"""Drags the element identified with ``locator`` by ``xoffset/yoffset``.
See the `Locating elements` section for details about the locator
syntax.
The element will be moved by ``xoffset`` and ``yoffset``, each of which
is a negative or positive number specifying the offset.
Example:
| `Drag And Drop By Offset` | myElem | 50 | -35 | # Move myElem 50px right and 35px down |
"""
element = self.find_element(locator)
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.drag_and_drop_by_offset(element, xoffset, yoffset)
action.perform()
@keyword
def mouse_down(self, locator: Union[WebElement, str]):
"""Simulates pressing the left mouse button on the element ``locator``.
See the `Locating elements` section for details about the locator
syntax.
The element is pressed without releasing the mouse button.
See also the more specific keywords `Mouse Down On Image` and
`Mouse Down On Link`.
"""
self.info(f"Simulating Mouse Down on element '{locator}'.")
element = self.find_element(locator)
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.click_and_hold(element).perform()
@keyword
def mouse_out(self, locator: Union[WebElement, str]):
"""Simulates moving the mouse away from the element ``locator``.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Simulating Mouse Out on element '{locator}'.")
element = self.find_element(locator)
size = element.size
offsetx = (size["width"] / 2) + 1
offsety = (size["height"] / 2) + 1
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.move_to_element(element)
action.move_by_offset(offsetx, offsety)
action.perform()
@keyword
def mouse_over(self, locator: Union[WebElement, str]):
"""Simulates hovering the mouse over the element ``locator``.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Simulating Mouse Over on element '{locator}'.")
element = self.find_element(locator)
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.move_to_element(element).perform()
@keyword
def mouse_up(self, locator: Union[WebElement, str]):
"""Simulates releasing the left mouse button on the element ``locator``.
See the `Locating elements` section for details about the locator
syntax.
"""
self.info(f"Simulating Mouse Up on element '{locator}'.")
element = self.find_element(locator)
ActionChains(self.driver, duration=self.ctx.action_chain_delay).release(element).perform()
@keyword
def open_context_menu(self, locator: Union[WebElement, str]):
"""Opens the context menu on the element identified by ``locator``."""
element = self.find_element(locator)
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.context_click(element).perform()
@keyword
def simulate_event(self, locator: Union[WebElement, str], event: str):
"""Simulates ``event`` on the element identified by ``locator``.
This keyword is useful if element has ``OnEvent`` handler that
needs to be explicitly invoked.
See the `Locating elements` section for details about the locator
syntax.
Prior to SeleniumLibrary 3.0 this keyword was named `Simulate`.
"""
element = self.find_element(locator)
script = """
element = arguments[0];
eventName = arguments[1];
if (document.createEventObject) { // IE
return element.fireEvent('on' + eventName, document.createEventObject());
}
var evt = document.createEvent("HTMLEvents");
evt.initEvent(eventName, true, true);
return !element.dispatchEvent(evt);
"""
self.driver.execute_script(script, element, event)
@keyword
def press_key(self, locator: Union[WebElement, str], key: str):
"""*DEPRECATED in SeleniumLibrary 4.0.* use `Press Keys` instead."""
if key.startswith("\\") and len(key) > 1:
key = self._map_ascii_key_code_to_key(int(key[1:]))
element = self.find_element(locator)
element.send_keys(key)
@keyword
def press_keys(self, locator: Union[WebElement, None, str] = None, *keys: str):
"""Simulates the user pressing key(s) to an element or on the active browser.
If ``locator`` evaluates as false, see `Boolean arguments` for more
details, then the ``keys`` are sent to the currently active browser.
Otherwise element is searched and ``keys`` are send to the element
identified by the ``locator``. In later case, keyword fails if element
is not found. See the `Locating elements` section for details about
the locator syntax.
``keys`` arguments can contain one or many strings, but it can not
be empty. ``keys`` can also be a combination of
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html|Selenium Keys]
and strings or a single Selenium Key. If Selenium Key is combined
with strings, Selenium key and strings must be separated by the
`+` character, like in `CONTROL+c`. Selenium Keys
are space and case sensitive and Selenium Keys are not parsed
inside of the string. Example AALTO, would send string `AALTO`
and `ALT` not parsed inside of the string. But `A+ALT+O` would
found Selenium ALT key from the ``keys`` argument. It also possible
to press many Selenium Keys down at the same time, example
'ALT+ARROW_DOWN`.
If Selenium Keys are detected in the ``keys`` argument, keyword
will press the Selenium Key down, send the strings and
then release the Selenium Key. If keyword needs to send a Selenium
Key as a string, then each character must be separated with
`+` character, example `E+N+D`.
`CTRL` is alias for
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html#selenium.webdriver.common.keys.Keys.CONTROL|Selenium CONTROL]
and ESC is alias for
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html#selenium.webdriver.common.keys.Keys.ESCAPE|Selenium ESCAPE]
New in SeleniumLibrary 3.3
Examples:
| `Press Keys` | text_field | AAAAA | | # Sends string "AAAAA" to element. |
| `Press Keys` | None | BBBBB | | # Sends string "BBBBB" to currently active browser. |
| `Press Keys` | text_field | E+N+D | | # Sends string "END" to element. |
| `Press Keys` | text_field | XXX | YY | # Sends strings "XXX" and "YY" to element. |
| `Press Keys` | text_field | XXX+YY | | # Same as above. |
| `Press Keys` | text_field | ALT+ARROW_DOWN | | # Pressing "ALT" key down, then pressing ARROW_DOWN and then releasing both keys. |
| `Press Keys` | text_field | ALT | ARROW_DOWN | # Pressing "ALT" key and then pressing ARROW_DOWN. |
| `Press Keys` | text_field | CTRL+c | | # Pressing CTRL key down, sends string "c" and then releases CTRL key. |
| `Press Keys` | button | RETURN | | # Pressing "ENTER" key to element. |
"""
parsed_keys = self._parse_keys(*keys)
if not is_noney(locator):
self.info(f"Sending key(s) {keys} to {locator} element.")
element = self.find_element(locator)
ActionChains(self.driver, duration=self.ctx.action_chain_delay).click(element).perform()
else:
self.info(f"Sending key(s) {keys} to page.")
element = None
for parsed_key in parsed_keys:
actions = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
for key in parsed_key:
if key.special:
self._press_keys_special_keys(actions, element, parsed_key, key)
else:
self._press_keys_normal_keys(actions, key)
self._special_key_up(actions, parsed_key)
actions.perform()
def _press_keys_normal_keys(self, actions, key):
self.info(f"Sending key{plural_or_not(key.converted)} {key.converted}")
actions.send_keys(key.converted)
def _press_keys_special_keys(self, actions, element, parsed_key, key):
if len(parsed_key) == 1 and element:
self.info(f"Pressing special key {key.original} to element.")
actions.send_keys(key.converted)
elif len(parsed_key) == 1 and not element:
self.info(f"Pressing special key {key.original} to browser.")
actions.send_keys(key.converted)
else:
self.info(f"Pressing special key {key.original} down.")
actions.key_down(key.converted)
def _special_key_up(self, actions, parsed_key):
for key in parsed_key:
if key.special:
self.info(f"Releasing special key {key.original}.")
actions.key_up(key.converted)
@keyword
def get_all_links(self) -> List[str]:
"""Returns a list containing ids of all links found in current page.
If a link has no id, an empty string will be in the list instead.
"""
links = self.find_elements("tag=a")
return [link.get_attribute("id") for link in links]
@keyword
def mouse_down_on_link(self, locator: Union[WebElement, str]):
"""Simulates a mouse down event on a link identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, links are searched
using ``id``, ``name``, ``href`` and the link text.
"""
element = self.find_element(locator, tag="link")
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.click_and_hold(element).perform()
@keyword
def page_should_contain_link(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies link identified by ``locator`` is found from current page.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, links are searched
using ``id``, ``name``, ``href`` and the link text.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
"""
self.assert_page_contains(locator, "link", message, loglevel)
@keyword
def page_should_not_contain_link(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies link identified by ``locator`` is not found from current page.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, links are searched
using ``id``, ``name``, ``href`` and the link text.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
"""
self.assert_page_not_contains(locator, "link", message, loglevel)
@keyword
def mouse_down_on_image(self, locator: Union[WebElement, str]):
"""Simulates a mouse down event on an image identified by ``locator``.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, images are searched
using ``id``, ``name``, ``src`` and ``alt``.
"""
element = self.find_element(locator, tag="image")
action = ActionChains(self.driver, duration=self.ctx.action_chain_delay)
action.click_and_hold(element).perform()
@keyword
def page_should_contain_image(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies image identified by ``locator`` is found from current page.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, images are searched
using ``id``, ``name``, ``src`` and ``alt``.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
"""
self.assert_page_contains(locator, "image", message, loglevel)
@keyword
def page_should_not_contain_image(
self,
locator: Union[WebElement, str],
message: Optional[str] = None,
loglevel: str = "TRACE",
):
"""Verifies image identified by ``locator`` is not found from current page.
See the `Locating elements` section for details about the locator
syntax. When using the default locator strategy, images are searched
using ``id``, ``name``, ``src`` and ``alt``.
See `Page Should Contain Element` for an explanation about ``message``
and ``loglevel`` arguments.
"""
self.assert_page_not_contains(locator, "image", message, loglevel)
@keyword
def get_element_count(self, locator: Union[WebElement, str]) -> int:
"""Returns the number of elements matching ``locator``.
If you wish to assert the number of matching elements, use
`Page Should Contain Element` with ``limit`` argument. Keyword will
always return an integer.
Example:
| ${count} = | `Get Element Count` | name:div_name |
| `Should Be True` | ${count} > 2 | |
New in SeleniumLibrary 3.0.
"""
return len(self.find_elements(locator))
@keyword
def add_location_strategy(
self, strategy_name: str, strategy_keyword: str, persist: bool = False
):
"""Adds a custom location strategy.
See `Custom locators` for information on how to create and use
custom strategies. `Remove Location Strategy` can be used to
remove a registered strategy.
Location strategies are automatically removed after leaving the
current scope by default. Setting ``persist`` to a true value (see
`Boolean arguments`) will cause the location strategy to stay
registered throughout the life of the test.
"""
self.element_finder.register(strategy_name, strategy_keyword, persist)
@keyword
def remove_location_strategy(self, strategy_name: str):
"""Removes a previously added custom location strategy.
See `Custom locators` for information on how to create and use
custom strategies.
"""
self.element_finder.unregister(strategy_name)
def _map_ascii_key_code_to_key(self, key_code):
map = {
0: Keys.NULL,
8: Keys.BACK_SPACE,
9: Keys.TAB,
10: Keys.RETURN,
13: Keys.ENTER,
24: Keys.CANCEL,
27: Keys.ESCAPE,
32: Keys.SPACE,
42: Keys.MULTIPLY,
43: Keys.ADD,
44: Keys.SEPARATOR,
45: Keys.SUBTRACT,
56: Keys.DECIMAL,
57: Keys.DIVIDE,
59: Keys.SEMICOLON,
61: Keys.EQUALS,
127: Keys.DELETE,
}
key = map.get(key_code)
if key is None:
key = chr(key_code)
return key
def _map_named_key_code_to_special_key(self, key_name):
try:
return getattr(Keys, key_name)
except AttributeError:
message = f"Unknown key named '{key_name}'."
self.debug(message)
raise ValueError(message)
def _page_contains(self, text):
self.driver.switch_to.default_content()
if self.is_text_present(text):
return True
subframes = self.find_elements("xpath://frame|//iframe")
self.debug(f"Current frame has {len(subframes)} subframes.")
for frame in subframes:
self.driver.switch_to.frame(frame)
found_text = self.is_text_present(text)
self.driver.switch_to.default_content()
if found_text:
return True
return False
def parse_modifier(self, modifier):
modifier = modifier.upper()
modifiers = modifier.split("+")
keys = []
for item in modifiers:
item = item.strip()
item = self._parse_aliases(item)
if hasattr(Keys, item):
keys.append(getattr(Keys, item))
else:
raise ValueError(f"'{item}' modifier does not match to Selenium Keys")
return keys
def _parse_keys(self, *keys):
if not keys:
raise AssertionError('"keys" argument can not be empty.')
list_keys = []
for key in keys:
separate_keys = self._separate_key(key)
separate_keys = self._convert_special_keys(separate_keys)
list_keys.append(separate_keys)
return list_keys
def _parse_aliases(self, key):
if key == "CTRL":
return "CONTROL"
if key == "ESC":
return "ESCAPE"
return key
def _separate_key(self, key):
one_key = ""
list_keys = []
for char in key:
if char == "+" and one_key != "":
list_keys.append(one_key)
one_key = ""
else:
one_key += char
if one_key:
list_keys.append(one_key)
return list_keys
def _convert_special_keys(self, keys):
KeysRecord = namedtuple("KeysRecord", "converted, original special")
converted_keys = []
for key in keys:
key = self._parse_aliases(key)
if self._selenium_keys_has_attr(key):
converted_keys.append(KeysRecord(getattr(Keys, key), key, True))
else:
converted_keys.append(KeysRecord(key, key, False))
return converted_keys
def _selenium_keys_has_attr(self, key):
return hasattr(Keys, key) | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/element.py | 0.924313 | 0.358325 | element.py | pypi |
import time
from typing import Optional, List, Tuple, Union
from SeleniumLibrary.utils import is_truthy, is_falsy, timestr_to_secs
from selenium.common.exceptions import NoSuchWindowException
from SeleniumLibrary.base import keyword, LibraryComponent
from SeleniumLibrary.locators import WindowManager
from SeleniumLibrary.utils import plural_or_not, is_string
class WindowKeywords(LibraryComponent):
def __init__(self, ctx):
LibraryComponent.__init__(self, ctx)
self._window_manager = WindowManager(ctx)
@keyword
def switch_window(
self,
locator: Union[list, str] = "MAIN",
timeout: Optional[str] = None,
browser: str = "CURRENT",
):
"""Switches to browser window matching ``locator``.
If the window is found, all subsequent commands use the selected
window, until this keyword is used again. If the window is not
found, this keyword fails. The previous windows handle is returned
and can be used to switch back to it later.
Notice that alerts should be handled with
`Handle Alert` or other alert related keywords.
The ``locator`` can be specified using different strategies somewhat
similarly as when `locating elements` on pages.
- By default, the ``locator`` is matched against window handle, name,
title, and URL. Matching is done in that order and the first
matching window is selected.
- The ``locator`` can specify an explicit strategy by using the format
``strategy:value`` (recommended) or ``strategy=value``. Supported
strategies are ``name``, ``title``, and ``url``. These matches windows
using their name, title, or URL, respectively. Additionally, ``default``
can be used to explicitly use the default strategy explained above.
- If the ``locator`` is ``NEW`` (case-insensitive), the latest
opened window is selected. It is an error if this is the same
as the current window.
- If the ``locator`` is ``MAIN`` (default, case-insensitive),
the main window is selected.
- If the ``locator`` is ``CURRENT`` (case-insensitive), nothing is
done. This effectively just returns the current window handle.
- If the ``locator`` is not a string, it is expected to be a list
of window handles _to exclude_. Such a list of excluded windows
can be got from `Get Window Handles` before doing an action that
opens a new window.
The ``timeout`` is used to specify how long keyword will poll to select
the new window. The ``timeout`` is new in SeleniumLibrary 3.2.
Example:
| `Click Link` | popup1 | | # Open new window |
| `Switch Window` | example | | # Select window using default strategy |
| `Title Should Be` | Pop-up 1 | |
| `Click Button` | popup2 | | # Open another window |
| ${handle} = | `Switch Window` | NEW | # Select latest opened window |
| `Title Should Be` | Pop-up 2 | |
| `Switch Window` | ${handle} | | # Select window using handle |
| `Title Should Be` | Pop-up 1 | |
| `Switch Window` | MAIN | | # Select the main window |
| `Title Should Be` | Main | |
| ${excludes} = | `Get Window Handles` | | # Get list of current windows |
| `Click Link` | popup3 | | # Open one more window |
| `Switch Window` | ${excludes} | | # Select window using excludes |
| `Title Should Be` | Pop-up 3 | |
The ``browser`` argument allows with ``index_or_alias`` to implicitly switch to
a specific browser when switching to a window. See `Switch Browser`
- If the ``browser`` is ``CURRENT`` (case-insensitive), no other browser is
selected.
*NOTE:*
- The ``strategy:value`` syntax is only supported by SeleniumLibrary
3.0 and newer.
- Prior to SeleniumLibrary 3.0 matching windows by name, title
and URL was case-insensitive.
- Earlier versions supported aliases ``None``, ``null`` and the
empty string for selecting the main window, and alias ``self``
for selecting the current window. Support for these aliases was
removed in SeleniumLibrary 3.2.
"""
epoch = time.time()
timeout = epoch if is_falsy(timeout) else timestr_to_secs(timeout) + epoch
try:
return self.driver.current_window_handle
except NoSuchWindowException:
pass
finally:
if not is_string(browser) or not browser.upper() == "CURRENT":
self.drivers.switch(browser)
self._window_manager.select(locator, timeout)
@keyword
def close_window(self):
"""Closes currently opened and selected browser window/tab. """
self.driver.close()
@keyword
def get_window_handles(self, browser: str = "CURRENT") -> List[str]:
"""Returns all child window handles of the selected browser as a list.
Can be used as a list of windows to exclude with `Select Window`.
How to select the ``browser`` scope of this keyword, see `Get Locations`.
Prior to SeleniumLibrary 3.0, this keyword was named `List Windows`.
"""
return self._window_manager.get_window_handles(browser)
@keyword
def get_window_identifiers(self, browser: str = "CURRENT") -> List:
"""Returns and logs id attributes of all windows of the selected browser.
How to select the ``browser`` scope of this keyword, see `Get Locations`."""
ids = [info.id for info in self._window_manager.get_window_infos(browser)]
return self._log_list(ids)
@keyword
def get_window_names(self, browser: str = "CURRENT") -> List[str]:
"""Returns and logs names of all windows of the selected browser.
How to select the ``browser`` scope of this keyword, see `Get Locations`."""
names = [info.name for info in self._window_manager.get_window_infos(browser)]
return self._log_list(names)
@keyword
def get_window_titles(self, browser: str = "CURRENT") -> List[str]:
"""Returns and logs titles of all windows of the selected browser.
How to select the ``browser`` scope of this keyword, see `Get Locations`."""
titles = [info.title for info in self._window_manager.get_window_infos(browser)]
return self._log_list(titles)
@keyword
def get_locations(self, browser: str = "CURRENT") -> List[str]:
"""Returns and logs URLs of all windows of the selected browser.
*Browser Scope:*
The ``browser`` argument specifies the browser that shall return
its windows information.
- ``browser`` can be ``index_or_alias`` like in `Switch Browser`.
- If ``browser`` is ``CURRENT`` (default, case-insensitive)
the currently active browser is selected.
- If ``browser`` is ``ALL`` (case-insensitive)
the window information of all windows of all opened browsers are returned."""
urls = [info.url for info in self._window_manager.get_window_infos(browser)]
return self._log_list(urls)
@keyword
def maximize_browser_window(self):
"""Maximizes current browser window."""
self.driver.maximize_window()
@keyword
def get_window_size(self, inner: bool = False) -> Tuple[float, float]:
"""Returns current window width and height as integers.
See also `Set Window Size`.
If ``inner`` parameter is set to True, keyword returns
HTML DOM window.innerWidth and window.innerHeight properties.
See `Boolean arguments` for more details on how to set boolean
arguments. The ``inner`` is new in SeleniumLibrary 4.0.
Example:
| ${width} | ${height}= | `Get Window Size` | |
| ${width} | ${height}= | `Get Window Size` | True |
"""
if is_truthy(inner):
inner_width = int(self.driver.execute_script("return window.innerWidth;"))
inner_height = int(self.driver.execute_script("return window.innerHeight;"))
return inner_width, inner_height
size = self.driver.get_window_size()
return size["width"], size["height"]
@keyword
def set_window_size(self, width: int, height: int, inner: bool = False):
"""Sets current windows size to given ``width`` and ``height``.
Values can be given using strings containing numbers or by using
actual numbers. See also `Get Window Size`.
Browsers have a limit on their minimum size. Trying to set them
smaller will cause the actual size to be bigger than the requested
size.
If ``inner`` parameter is set to True, keyword sets the necessary
window width and height to have the desired HTML DOM _window.innerWidth_
and _window.innerHeight_. See `Boolean arguments` for more details on how to set boolean
arguments.
The ``inner`` argument is new since SeleniumLibrary 4.0.
This ``inner`` argument does not support Frames. If a frame is selected,
switch to default before running this.
Example:
| `Set Window Size` | 800 | 600 | |
| `Set Window Size` | 800 | 600 | True |
"""
if is_falsy(inner):
return self.driver.set_window_size(width, height)
self.driver.set_window_size(width, height)
inner_width = int(self.driver.execute_script("return window.innerWidth;"))
inner_height = int(self.driver.execute_script("return window.innerHeight;"))
self.info(
f"window.innerWidth is {inner_width} and window.innerHeight is {inner_height}"
)
width_offset = width - inner_width
height_offset = height - inner_height
window_width = width + width_offset
window_height = height + height_offset
self.info(f"Setting window size to {window_width} {window_height}")
self.driver.set_window_size(window_width, window_height)
result_width = int(self.driver.execute_script("return window.innerWidth;"))
result_height = int(self.driver.execute_script("return window.innerHeight;"))
if result_width != width or result_height != height:
raise AssertionError("Keyword failed setting correct window size.")
@keyword
def get_window_position(self) -> Tuple[int, int]:
"""Returns current window position.
The position is relative to the top left corner of the screen. Returned
values are integers. See also `Set Window Position`.
Example:
| ${x} | ${y}= | `Get Window Position` |
"""
position = self.driver.get_window_position()
return position["x"], position["y"]
@keyword
def set_window_position(self, x: int, y: int):
"""Sets window position using ``x`` and ``y`` coordinates.
The position is relative to the top left corner of the screen,
but some browsers exclude possible task bar set by the operating
system from the calculation. The actual position may thus be
different with different browsers.
Values can be given using strings containing numbers or by using
actual numbers. See also `Get Window Position`.
Example:
| `Set Window Position` | 100 | 200 |
"""
self.driver.set_window_position(x, y)
def _log_list(self, items, what="item"):
msg = [f"Altogether {len(items)} {what}{plural_or_not(items)}."]
for index, item in enumerate(items):
msg.append(f"{index + 1}: {item}")
self.info("\n".join(msg))
return items | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/window.py | 0.922578 | 0.38217 | window.py | pypi |
import time
import types
from datetime import timedelta
from typing import Optional, Union, Any, List
from selenium import webdriver
from selenium.webdriver import FirefoxProfile
from selenium.webdriver.support.event_firing_webdriver import EventFiringWebDriver
from SeleniumLibrary.base import keyword, LibraryComponent
from SeleniumLibrary.locators import WindowManager
from SeleniumLibrary.utils import timestr_to_secs, secs_to_timestr, _convert_timeout, _convert_delay
from .webdrivertools import WebDriverCreator
class BrowserManagementKeywords(LibraryComponent):
def __init__(self, ctx):
LibraryComponent.__init__(self, ctx)
self._window_manager = WindowManager(ctx)
self._webdriver_creator = WebDriverCreator(self.log_dir)
@keyword
def close_all_browsers(self):
"""Closes all open browsers and resets the browser cache.
After this keyword, new indexes returned from `Open Browser` keyword
are reset to 1.
This keyword should be used in test or suite teardown to make sure
all browsers are closed.
"""
self.debug("Closing all browsers.")
self.drivers.close_all()
@keyword
def close_browser(self):
"""Closes the current browser."""
if self.drivers.current:
self.debug(f"Closing browser with session id {self.driver.session_id}.")
self.drivers.close()
@keyword
def open_browser(
self,
url: Optional[str] = None,
browser: str = "firefox",
alias: Optional[str] = None,
remote_url: Union[bool, str] = False,
desired_capabilities: Union[dict, None, str] = None,
ff_profile_dir: Union[FirefoxProfile, str, None] = None,
options: Any = None,
service_log_path: Optional[str] = None,
executable_path: Optional[str] = None,
) -> str:
"""Opens a new browser instance to the optional ``url``.
The ``browser`` argument specifies which browser to use. The
supported browsers are listed in the table below. The browser names
are case-insensitive and some browsers have multiple supported names.
| = Browser = | = Name(s) = |
| Firefox | firefox, ff |
| Google Chrome | googlechrome, chrome, gc |
| Headless Firefox | headlessfirefox |
| Headless Chrome | headlesschrome |
| Internet Explorer | internetexplorer, ie |
| Edge | edge |
| Safari | safari |
To be able to actually use one of these browsers, you need to have
a matching Selenium browser driver available. See the
[https://github.com/robotframework/SeleniumLibrary#browser-drivers|
project documentation] for more details. Headless Firefox and
Headless Chrome are new additions in SeleniumLibrary 3.1.0
and require Selenium 3.8.0 or newer.
After opening the browser, it is possible to use optional
``url`` to navigate the browser to the desired address.
Optional ``alias`` is an alias given for this browser instance and
it can be used for switching between browsers. When same ``alias``
is given with two `Open Browser` keywords, the first keyword will
open a new browser, but the second one will switch to the already
opened browser and will not open a new browser. The ``alias``
definition overrules ``browser`` definition. When same ``alias``
is used but a different ``browser`` is defined, then switch to
a browser with same alias is done and new browser is not opened.
An alternative approach for switching is using an index returned
by this keyword. These indices start from 1, are incremented when new
browsers are opened, and reset back to 1 when `Close All Browsers`
is called. See `Switch Browser` for more information and examples.
Optional ``remote_url`` is the URL for a
[https://github.com/SeleniumHQ/selenium/wiki/Grid2|Selenium Grid].
Optional ``desired_capabilities`` is deprecated and will be ignored. Capabilities of each
individual browser is now done through options or services. Please refer to those arguments
for configuring specific browsers.
Optional ``ff_profile_dir`` is the path to the Firefox profile
directory if you wish to overwrite the default profile Selenium
uses. Notice that prior to SeleniumLibrary 3.0, the library
contained its own profile that was used by default. The
``ff_profile_dir`` can also be an instance of the
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.firefox_profile.html|selenium.webdriver.FirefoxProfile]
. As a third option, it is possible to use `FirefoxProfile` methods
and attributes to define the profile using methods and attributes
in the same way as with ``options`` argument. Example: It is possible
to use FirefoxProfile `set_preference` to define different
profile settings. See ``options`` argument documentation in below
how to handle backslash escaping.
Optional ``options`` argument allows defining browser specific
Selenium options. Example for Chrome, the ``options`` argument
allows defining the following
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.options.html#selenium.webdriver.chrome.options.Options|methods and attributes]
and for Firefox these
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.options.html?highlight=firefox#selenium.webdriver.firefox.options.Options|methods and attributes]
are available. Please note that not all browsers, supported by the
SeleniumLibrary, have Selenium options available. Therefore please
consult the Selenium documentation which browsers do support
the Selenium options. Selenium options are also supported, when ``remote_url``
argument is used.
The SeleniumLibrary ``options`` argument accepts Selenium
options in two different formats: as a string and as Python object
which is an instance of the Selenium options class.
The string format allows defining Selenium options methods
or attributes and their arguments in Robot Framework test data.
The method and attributes names are case and space sensitive and
must match to the Selenium options methods and attributes names.
When defining a method, it must be defined in a similar way as in
python: method name, opening parenthesis, zero to many arguments
and closing parenthesis. If there is a need to define multiple
arguments for a single method, arguments must be separated with
comma, just like in Python. Example: `add_argument("--headless")`
or `add_experimental_option("key", "value")`. Attributes are
defined in a similar way as in Python: attribute name, equal sign,
and attribute value. Example, `headless=True`. Multiple methods
and attributes must be separated by a semicolon. Example:
`add_argument("--headless");add_argument("--start-maximized")`.
Arguments allow defining Python data types and arguments are
evaluated by using Python
[https://docs.python.org/3/library/ast.html#ast.literal_eval|ast.literal_eval].
Strings must be quoted with single or double quotes, example "value"
or 'value'. It is also possible to define other Python builtin
data types, example `True` or `None`, by not using quotes
around the arguments.
The string format is space friendly. Usually, spaces do not alter
the defining methods or attributes. There are two exceptions.
In some Robot Framework test data formats, two or more spaces are
considered as cell separator and instead of defining a single
argument, two or more arguments may be defined. Spaces in string
arguments are not removed and are left as is. Example
`add_argument ( "--headless" )` is same as
`add_argument("--headless")`. But `add_argument(" --headless ")` is
not same same as `add_argument ( "--headless" )`, because
spaces inside of quotes are not removed. Please note that if
options string contains backslash, example a Windows OS path,
the backslash needs escaping both in Robot Framework data and
in Python side. This means single backslash must be writen using
four backslash characters. Example, Windows path:
"C:\\path\\to\\profile" must be written as
"C:\\\\\\\\path\\\\\\to\\\\\\\\profile". Another way to write
backslash is use Python
[https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals|raw strings]
and example write: r"C:\\\\path\\\\to\\\\profile".
As last format, ``options`` argument also supports receiving
the Selenium options as Python class instance. In this case, the
instance is used as-is and the SeleniumLibrary will not convert
the instance to other formats.
For example, if the following code return value is saved to
`${options}` variable in the Robot Framework data:
| options = webdriver.ChromeOptions()
| options.add_argument('--disable-dev-shm-usage')
| return options
Then the `${options}` variable can be used as an argument to
``options``.
Example the ``options`` argument can be used to launch Chomium-based
applications which utilize the
[https://bitbucket.org/chromiumembedded/cef/wiki/UsingChromeDriver|Chromium Embedded Framework]
. To lauch Chomium-based application, use ``options`` to define
`binary_location` attribute and use `add_argument` method to define
`remote-debugging-port` port for the application. Once the browser
is opened, the test can interact with the embedded web-content of
the system under test.
Optional ``service_log_path`` argument defines the name of the
file where to write the browser driver logs. If the
``service_log_path`` argument contain a marker ``{index}``, it
will be automatically replaced with unique running
index preventing files to be overwritten. Indices start's from 1,
and how they are represented can be customized using Python's
[https://docs.python.org/3/library/string.html#format-string-syntax|
format string syntax].
Optional ``executable_path`` argument defines the path to the driver
executable, example to a chromedriver or a geckodriver. If not defined
it is assumed the executable is in the
[https://en.wikipedia.org/wiki/PATH_(variable)|$PATH].
Examples:
| `Open Browser` | http://example.com | Chrome | |
| `Open Browser` | http://example.com | Firefox | alias=Firefox |
| `Open Browser` | http://example.com | Edge | remote_url=http://127.0.0.1:4444/wd/hub |
| `Open Browser` | about:blank | | |
| `Open Browser` | browser=Chrome | | |
Alias examples:
| ${1_index} = | `Open Browser` | http://example.com | Chrome | alias=Chrome | # Opens new browser because alias is new. |
| ${2_index} = | `Open Browser` | http://example.com | Firefox | | # Opens new browser because alias is not defined. |
| ${3_index} = | `Open Browser` | http://example.com | Chrome | alias=Chrome | # Switches to the browser with Chrome alias. |
| ${4_index} = | `Open Browser` | http://example.com | Chrome | alias=${1_index} | # Switches to the browser with Chrome alias. |
| Should Be Equal | ${1_index} | ${3_index} | | | |
| Should Be Equal | ${1_index} | ${4_index} | | | |
| Should Be Equal | ${2_index} | ${2} | | | |
Example when using
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver_chrome/selenium.webdriver.chrome.options.html#selenium.webdriver.chrome.options.Options|Chrome options]
method:
| `Open Browser` | http://example.com | Chrome | options=add_argument("--disable-popup-blocking"); add_argument("--ignore-certificate-errors") | # Sting format. |
| ${options} = | Get Options | | | # Selenium options instance. |
| `Open Browser` | http://example.com | Chrome | options=${options} | |
| `Open Browser` | None | Chrome | options=binary_location="/path/to/binary";add_argument("remote-debugging-port=port") | # Start Chomium-based application. |
| `Open Browser` | None | Chrome | options=binary_location=r"C:\\\\path\\\\to\\\\binary" | # Windows OS path escaping. |
Example for FirefoxProfile
| `Open Browser` | http://example.com | Firefox | ff_profile_dir=/path/to/profile | # Using profile from disk. |
| `Open Browser` | http://example.com | Firefox | ff_profile_dir=${FirefoxProfile_instance} | # Using instance of FirefoxProfile. |
| `Open Browser` | http://example.com | Firefox | ff_profile_dir=set_preference("key", "value");set_preference("other", "setting") | # Defining profile using FirefoxProfile mehtods. |
If the provided configuration options are not enough, it is possible
to use `Create Webdriver` to customize browser initialization even
more.
Applying ``desired_capabilities`` argument also for local browser is
new in SeleniumLibrary 3.1.
Using ``alias`` to decide, is the new browser opened is new
in SeleniumLibrary 4.0. The ``options`` and ``service_log_path``
are new in SeleniumLibrary 4.0. Support for ``ff_profile_dir``
accepting an instance of the `selenium.webdriver.FirefoxProfile`
and support defining FirefoxProfile with methods and
attributes are new in SeleniumLibrary 4.0.
Making ``url`` optional is new in SeleniumLibrary 4.1.
The ``executable_path`` argument is new in SeleniumLibrary 4.2.
"""
index = self.drivers.get_index(alias)
if index:
self.info(f"Using existing browser from index {index}.")
self.switch_browser(alias)
if url:
self.go_to(url)
return index
if desired_capabilities:
self.warn("desired_capabilities has been deprecated and removed. Please use options to configure browsers as per documentation.")
return self._make_new_browser(
url,
browser,
alias,
remote_url,
desired_capabilities,
ff_profile_dir,
options,
service_log_path,
executable_path,
)
def _make_new_browser(
self,
url=None,
browser="firefox",
alias=None,
remote_url=False,
desired_capabilities=None,
ff_profile_dir=None,
options=None,
service_log_path=None,
executable_path=None,
):
if remote_url:
self.info(
f"Opening browser '{browser}' to base url '{url}' through "
f"remote server at '{remote_url}'."
)
else:
self.info(f"Opening browser '{browser}' to base url '{url}'.")
driver = self._make_driver(
browser,
desired_capabilities,
ff_profile_dir,
remote_url,
options,
service_log_path,
executable_path,
)
driver = self._wrap_event_firing_webdriver(driver)
index = self.ctx.register_driver(driver, alias)
if url:
try:
driver.get(url)
except Exception:
self.debug(
f"Opened browser with session id {driver.session_id} but failed to open url '{url}'."
)
raise
self.debug(f"Opened browser with session id {driver.session_id}.")
return index
@keyword
def create_webdriver(
self, driver_name: str, alias: Optional[str] = None, kwargs={}, **init_kwargs
) -> str:
"""Creates an instance of Selenium WebDriver.
Like `Open Browser`, but allows passing arguments to the created
WebDriver instance directly. This keyword should only be used if
the functionality provided by `Open Browser` is not adequate.
``driver_name`` must be a WebDriver implementation name like Firefox,
Chrome, Ie, Edge, Safari, or Remote.
The initialized WebDriver can be configured either with a Python
dictionary ``kwargs`` or by using keyword arguments ``**init_kwargs``.
These arguments are passed directly to WebDriver without any
processing. See [https://seleniumhq.github.io/selenium/docs/api/py/api.html|
Selenium API documentation] for details about the supported arguments.
Examples:
| # Use proxy with Firefox | | | |
| ${proxy}= | `Evaluate` | selenium.webdriver.Proxy() | modules=selenium, selenium.webdriver |
| ${proxy.http_proxy}= | `Set Variable` | localhost:8888 | |
| `Create Webdriver` | Firefox | proxy=${proxy} | |
Returns the index of this browser instance which can be used later to
switch back to it. Index starts from 1 and is reset back to it when
`Close All Browsers` keyword is used. See `Switch Browser` for an
example.
"""
if not isinstance(kwargs, dict):
raise RuntimeError("kwargs must be a dictionary.")
for arg_name in kwargs:
if arg_name in init_kwargs:
raise RuntimeError(f"Got multiple values for argument '{arg_name}'.")
init_kwargs[arg_name] = kwargs[arg_name]
driver_name = driver_name.strip()
try:
creation_func = getattr(webdriver, driver_name)
except AttributeError:
raise RuntimeError(f"'{driver_name}' is not a valid WebDriver name.")
self.info(f"Creating an instance of the {driver_name} WebDriver.")
driver = creation_func(**init_kwargs)
self.debug(
f"Created {driver_name} WebDriver instance with session id {driver.session_id}."
)
driver = self._wrap_event_firing_webdriver(driver)
return self.ctx.register_driver(driver, alias)
def _wrap_event_firing_webdriver(self, driver):
if not self.ctx.event_firing_webdriver:
return driver
self.debug("Wrapping driver to event_firing_webdriver.")
return EventFiringWebDriver(driver, self.ctx.event_firing_webdriver())
@keyword
def switch_browser(self, index_or_alias: str):
"""Switches between active browsers using ``index_or_alias``.
Indices are returned by the `Open Browser` keyword and aliases can
be given to it explicitly. Indices start from 1.
Example:
| `Open Browser` | http://google.com | ff |
| `Location Should Be` | http://google.com | |
| `Open Browser` | http://yahoo.com | ie | alias=second |
| `Location Should Be` | http://yahoo.com | |
| `Switch Browser` | 1 | # index |
| `Page Should Contain` | I'm feeling lucky | |
| `Switch Browser` | second | # alias |
| `Page Should Contain` | More Yahoo! | |
| `Close All Browsers` | | |
Above example expects that there was no other open browsers when
opening the first one because it used index ``1`` when switching to
it later. If you are not sure about that, you can store the index
into a variable as below.
| ${index} = | `Open Browser` | http://google.com |
| # Do something ... | | |
| `Switch Browser` | ${index} | |
"""
try:
self.drivers.switch(index_or_alias)
except RuntimeError:
raise RuntimeError(
f"No browser with index or alias '{index_or_alias}' found."
)
self.debug(
f"Switched to browser with Selenium session id {self.driver.session_id}."
)
@keyword
def get_browser_ids(self) -> List[str]:
"""Returns index of all active browser as list.
Example:
| @{browser_ids}= | Get Browser Ids | | |
| FOR | ${id} | IN | @{browser_ids} |
| | @{window_titles}= | Get Window Titles | browser=${id} |
| | Log | Browser ${id} has these windows: ${window_titles} | |
| END | | | |
See `Switch Browser` for more information and examples.
New in SeleniumLibrary 4.0
"""
return self.drivers.active_driver_ids
@keyword
def get_browser_aliases(self) -> List[str]:
"""Returns aliases of all active browser that has an alias as NormalizedDict.
The dictionary contains the aliases as keys and the index as value.
This can be accessed as dictionary ``${aliases.key}`` or as list ``@{aliases}[0]``.
Example:
| `Open Browser` | https://example.com | alias=BrowserA | |
| `Open Browser` | https://example.com | alias=BrowserB | |
| &{aliases} | `Get Browser Aliases` | | # &{aliases} = { BrowserA=1|BrowserB=2 } |
| `Log` | ${aliases.BrowserA} | | # logs ``1`` |
| FOR | ${alias} | IN | @{aliases} |
| | `Log` | ${alias} | # logs ``BrowserA`` and ``BrowserB`` |
| END | | | |
See `Switch Browser` for more information and examples.
New in SeleniumLibrary 4.0
"""
return self.drivers.active_aliases
@keyword
def get_session_id(self) -> str:
"""Returns the currently active browser session id.
New in SeleniumLibrary 3.2
"""
return self.driver.session_id
@keyword
def get_source(self) -> str:
"""Returns the entire HTML source of the current page or frame."""
return self.driver.page_source
@keyword
def get_title(self) -> str:
"""Returns the title of the current page."""
return self.driver.title
@keyword
def get_location(self) -> str:
"""Returns the current browser window URL."""
return self.driver.current_url
@keyword
def location_should_be(self, url: str, message: Optional[str] = None):
"""Verifies that the current URL is exactly ``url``.
The ``url`` argument contains the exact url that should exist in browser.
The ``message`` argument can be used to override the default error
message.
``message`` argument is new in SeleniumLibrary 3.2.0.
"""
actual = self.get_location()
if actual != url:
if message is None:
message = f"Location should have been '{url}' but " f"was '{actual}'."
raise AssertionError(message)
self.info(f"Current location is '{url}'.")
@keyword
def location_should_contain(self, expected: str, message: Optional[str] = None):
"""Verifies that the current URL contains ``expected``.
The ``expected`` argument contains the expected value in url.
The ``message`` argument can be used to override the default error
message.
``message`` argument is new in SeleniumLibrary 3.2.0.
"""
actual = self.get_location()
if expected not in actual:
if message is None:
message = (
f"Location should have contained '{expected}' but "
f"it was '{actual}'."
)
raise AssertionError(message)
self.info(f"Current location contains '{expected}'.")
@keyword
def log_location(self) -> str:
"""Logs and returns the current browser window URL."""
url = self.get_location()
self.info(url)
return url
@keyword
def log_source(self, loglevel: str = "INFO") -> str:
"""Logs and returns the HTML source of the current page or frame.
The ``loglevel`` argument defines the used log level. Valid log
levels are ``WARN``, ``INFO`` (default), ``DEBUG``, ``TRACE``
and ``NONE`` (no logging).
"""
source = self.get_source()
self.log(source, loglevel)
return source
@keyword
def log_title(self) -> str:
"""Logs and returns the title of the current page."""
title = self.get_title()
self.info(title)
return title
@keyword
def title_should_be(self, title: str, message: Optional[str] = None):
"""Verifies that the current page title equals ``title``.
The ``message`` argument can be used to override the default error
message.
``message`` argument is new in SeleniumLibrary 3.1.
"""
actual = self.get_title()
if actual != title:
if message is None:
message = f"Title should have been '{title}' but was '{actual}'."
raise AssertionError(message)
self.info(f"Page title is '{title}'.")
@keyword
def go_back(self):
"""Simulates the user clicking the back button on their browser."""
self.driver.back()
@keyword
def go_to(self, url):
"""Navigates the current browser window to the provided ``url``."""
self.info(f"Opening url '{url}'")
self.driver.get(url)
@keyword
def reload_page(self):
"""Simulates user reloading page."""
self.driver.refresh()
@keyword
def get_selenium_speed(self) -> str:
"""Gets the delay that is waited after each Selenium command.
The value is returned as a human-readable string like ``1 second``.
See the `Selenium Speed` section above for more information.
"""
return secs_to_timestr(self.ctx.speed)
@keyword
def get_selenium_timeout(self) -> str:
"""Gets the timeout that is used by various keywords.
The value is returned as a human-readable string like ``1 second``.
See the `Timeout` section above for more information.
"""
return secs_to_timestr(self.ctx.timeout)
@keyword
def get_selenium_implicit_wait(self) -> str:
"""Gets the implicit wait value used by Selenium.
The value is returned as a human-readable string like ``1 second``.
See the `Implicit wait` section above for more information.
"""
return secs_to_timestr(self.ctx.implicit_wait)
@keyword
def get_selenium_page_load_timeout(self) -> str:
"""Gets the timeout to wait for a page load to complete
before throwing an error.
The value is returned as a human-readable string like ``1 second``.
See the `Page load` section above for more information.
New in SeleniumLibrary 6.1
"""
return secs_to_timestr(self.ctx.page_load_timeout)
@keyword
def set_selenium_speed(self, value: timedelta) -> str:
"""Sets the delay that is waited after each Selenium command.
The value can be given as a number that is considered to be
seconds or as a human-readable string like ``1 second``.
The previous value is returned and can be used to restore
the original value later if needed.
See the `Selenium Speed` section above for more information.
Example:
| `Set Selenium Speed` | 0.5 seconds |
"""
old_speed = self.get_selenium_speed()
self.ctx.speed = _convert_timeout(value)
for driver in self.drivers.active_drivers:
self._monkey_patch_speed(driver)
return old_speed
@keyword
def set_selenium_timeout(self, value: timedelta) -> str:
"""Sets the timeout that is used by various keywords.
The value can be given as a number that is considered to be
seconds or as a human-readable string like ``1 second``.
The previous value is returned and can be used to restore
the original value later if needed.
See the `Timeout` section above for more information.
Example:
| ${orig timeout} = | `Set Selenium Timeout` | 15 seconds |
| `Open page that loads slowly` |
| `Set Selenium Timeout` | ${orig timeout} |
"""
old_timeout = self.get_selenium_timeout()
self.ctx.timeout = _convert_timeout(value)
for driver in self.drivers.active_drivers:
driver.set_script_timeout(self.ctx.timeout)
return old_timeout
@keyword
def set_selenium_implicit_wait(self, value: timedelta) -> str:
"""Sets the implicit wait value used by Selenium.
The value can be given as a number that is considered to be
seconds or as a human-readable string like ``1 second``.
The previous value is returned and can be used to restore
the original value later if needed.
This keyword sets the implicit wait for all opened browsers.
Use `Set Browser Implicit Wait` to set it only to the current
browser.
See the `Implicit wait` section above for more information.
Example:
| ${orig wait} = | `Set Selenium Implicit Wait` | 10 seconds |
| `Perform AJAX call that is slow` |
| `Set Selenium Implicit Wait` | ${orig wait} |
"""
old_wait = self.get_selenium_implicit_wait()
self.ctx.implicit_wait = _convert_timeout(value)
for driver in self.drivers.active_drivers:
driver.implicitly_wait(self.ctx.implicit_wait)
return old_wait
@keyword
def set_action_chain_delay(self, value: timedelta) -> str:
"""Sets the duration of delay in ActionChains() used by SeleniumLibrary.
The value can be given as a number that is considered to be
seconds or as a human-readable string like ``1 second``.
Value is always stored as milliseconds internally.
The previous value is returned and can be used to restore
the original value later if needed.
"""
old_action_chain_delay = self.ctx.action_chain_delay
self.ctx.action_chain_delay = _convert_delay(value)
return timestr_to_secs(f"{old_action_chain_delay} milliseconds")
@keyword
def get_action_chain_delay(self):
"""Gets the currently stored value for chain_delay_value in timestr format.
"""
return timestr_to_secs(f"{self.ctx.action_chain_delay} milliseconds")
@keyword
def set_browser_implicit_wait(self, value: timedelta):
"""Sets the implicit wait value used by Selenium.
Same as `Set Selenium Implicit Wait` but only affects the current
browser.
"""
self.driver.implicitly_wait(_convert_timeout(value))
@keyword
def set_selenium_page_load_timeout(self, value: timedelta) -> str:
"""Sets the page load timeout value used by Selenium.
The value can be given as a number that is considered to be
seconds or as a human-readable string like ``1 second``.
The previous value is returned and can be used to restore
the original value later if needed.
In contrast to `Set Selenium Timeout` and `Set Selenium Implicit Wait`
this keywords sets the time for Webdriver to wait until page
is loaded before throwing an error.
See the `Page load` section above for more information.
Example:
| ${orig page load timeout} = | `Set Selenium Page Load Timeout` | 30 seconds |
| `Open page that loads slowly` |
| `Set Selenium Page Load Timeout` | ${orig page load timeout} |
New in SeleniumLibrary 6.1
"""
old_page_load_timeout = self.get_selenium_page_load_timeout()
self.ctx.page_load_timeout = _convert_timeout(value)
for driver in self.drivers.active_drivers:
driver.set_page_load_timeout(self.ctx.page_load_timeout)
return old_page_load_timeout
def _make_driver(
self,
browser,
desired_capabilities=None,
profile_dir=None,
remote=None,
options=None,
service_log_path=None,
executable_path=None,
):
driver = self._webdriver_creator.create_driver(
browser=browser,
desired_capabilities=desired_capabilities,
remote_url=remote,
profile_dir=profile_dir,
options=options,
service_log_path=service_log_path,
executable_path=executable_path,
)
driver.set_script_timeout(self.ctx.timeout)
driver.implicitly_wait(self.ctx.implicit_wait)
driver.set_page_load_timeout(self.ctx.page_load_timeout)
if self.ctx.speed:
self._monkey_patch_speed(driver)
return driver
def _monkey_patch_speed(self, driver):
def execute(self, driver_command, params=None):
result = self._base_execute(driver_command, params)
speed = self._speed if hasattr(self, "_speed") else 0.0
if speed > 0:
time.sleep(speed)
return result
if not hasattr(driver, "_base_execute"):
driver._base_execute = driver.execute
driver.execute = types.MethodType(execute, driver)
driver._speed = self.ctx.speed | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/browsermanagement.py | 0.878451 | 0.258361 | browsermanagement.py | pypi |
import os
from collections import namedtuple
from typing import Any, Union
from robot.utils import plural_or_not, seq2str
from selenium.webdriver.remote.webelement import WebElement
from SeleniumLibrary.base import LibraryComponent, keyword
class JavaScriptKeywords(LibraryComponent):
js_marker = "JAVASCRIPT"
arg_marker = "ARGUMENTS"
@keyword
def execute_javascript(self, *code: Union[WebElement, str]) -> Any:
"""Executes the given JavaScript code with possible arguments.
``code`` may be divided into multiple cells in the test data and
``code`` may contain multiple lines of code and arguments. In that case,
the JavaScript code parts are concatenated together without adding
spaces and optional arguments are separated from ``code``.
If ``code`` is a path to an existing file, the JavaScript
to execute will be read from that file. Forward slashes work as
a path separator on all operating systems.
The JavaScript executes in the context of the currently selected
frame or window as the body of an anonymous function. Use ``window``
to refer to the window of your application and ``document`` to refer
to the document object of the current frame or window, e.g.
``document.getElementById('example')``.
This keyword returns whatever the executed JavaScript code returns.
Return values are converted to the appropriate Python types.
Starting from SeleniumLibrary 3.2 it is possible to provide JavaScript
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webdriver.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script|
arguments] as part of ``code`` argument. The JavaScript code and
arguments must be separated with `JAVASCRIPT` and `ARGUMENTS` markers
and must be used exactly with this format. If the Javascript code is
first, then the `JAVASCRIPT` marker is optional. The order of
`JAVASCRIPT` and `ARGUMENTS` markers can be swapped, but if `ARGUMENTS`
is the first marker, then `JAVASCRIPT` marker is mandatory. It is only
allowed to use `JAVASCRIPT` and `ARGUMENTS` markers only one time in the
``code`` argument.
Examples:
| `Execute JavaScript` | window.myFunc('arg1', 'arg2') |
| `Execute JavaScript` | ${CURDIR}/js_to_execute.js |
| `Execute JavaScript` | alert(arguments[0]); | ARGUMENTS | 123 |
| `Execute JavaScript` | ARGUMENTS | 123 | JAVASCRIPT | alert(arguments[0]); |
"""
js_code, js_args = self._get_javascript_to_execute(code)
self._js_logger("Executing JavaScript", js_code, js_args)
return self.driver.execute_script(js_code, *js_args)
@keyword
def execute_async_javascript(self, *code: Union[WebElement, str]) -> Any:
"""Executes asynchronous JavaScript code with possible arguments.
Similar to `Execute Javascript` except that scripts executed with
this keyword must explicitly signal they are finished by invoking the
provided callback. This callback is always injected into the executed
function as the last argument.
Scripts must complete within the script timeout or this keyword will
fail. See the `Timeout` section for more information.
Starting from SeleniumLibrary 3.2 it is possible to provide JavaScript
[https://seleniumhq.github.io/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webdriver.html#selenium.webdriver.remote.webdriver.WebDriver.execute_async_script|
arguments] as part of ``code`` argument. See `Execute Javascript` for
more details.
Examples:
| `Execute Async JavaScript` | var callback = arguments[arguments.length - 1]; window.setTimeout(callback, 2000); |
| `Execute Async JavaScript` | ${CURDIR}/async_js_to_execute.js |
| ${result} = | `Execute Async JavaScript` |
| ... | var callback = arguments[arguments.length - 1]; |
| ... | function answer(){callback("text");}; |
| ... | window.setTimeout(answer, 2000); |
| `Should Be Equal` | ${result} | text |
"""
js_code, js_args = self._get_javascript_to_execute(code)
self._js_logger("Executing Asynchronous JavaScript", js_code, js_args)
return self.driver.execute_async_script(js_code, *js_args)
def _js_logger(self, base, code, args):
message = f"{base}:\n{code}\n"
if args:
message = (
f"{message}By using argument{plural_or_not(args)}:\n{seq2str(args)}"
)
else:
message = f"{message}Without any arguments."
self.info(message)
def _get_javascript_to_execute(self, code):
js_code, js_args = self._separate_code_and_args(code)
if not js_code:
raise ValueError("JavaScript code was not found from code argument.")
js_code = "".join(js_code)
path = js_code.replace("/", os.sep)
if os.path.isabs(path) and os.path.isfile(path):
js_code = self._read_javascript_from_file(path)
return js_code, js_args
def _separate_code_and_args(self, code):
code = list(code)
self._check_marker_error(code)
index = self._get_marker_index(code)
if self.arg_marker not in code:
return code[index.js + 1 :], []
if self.js_marker not in code:
return code[0 : index.arg], code[index.arg + 1 :]
else:
if index.js == 0:
return code[index.js + 1 : index.arg], code[index.arg + 1 :]
else:
return code[index.js + 1 :], code[index.arg + 1 : index.js]
def _check_marker_error(self, code):
if not code:
raise ValueError("There must be at least one argument defined.")
message = None
template = " marker was found two times in the code."
if code.count(self.js_marker) > 1:
message = f"{self.js_marker}{template}"
if code.count(self.arg_marker) > 1:
message = f"{self.arg_marker}{template}"
index = self._get_marker_index(code)
if index.js > 0 and index.arg != 0:
message = f"{self.js_marker}{template}"
if message:
raise ValueError(message)
def _get_marker_index(self, code):
Index = namedtuple("Index", "js arg")
if self.js_marker in code:
js = code.index(self.js_marker)
else:
js = -1
if self.arg_marker in code:
arg = code.index(self.arg_marker)
else:
arg = -1
return Index(js=js, arg=arg)
def _read_javascript_from_file(self, path):
self.info(
f'Reading JavaScript from file <a href="file://{path.replace(os.sep, "/")}">{path}</a>.',
html=True,
)
with open(path) as file:
return file.read().strip() | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/keywords/javascript.py | 0.782621 | 0.400456 | javascript.py | pypi |
from typing import Any, Optional, List
from selenium.webdriver.remote.webelement import WebElement
from SeleniumLibrary.utils import escape_xpath_value
class ContextAware:
def __init__(self, ctx):
"""Base class exposing attributes from the common context.
:param ctx: The library itself as a context object.
:type ctx: SeleniumLibrary.SeleniumLibrary
"""
self.ctx = ctx
@property
def driver(self):
return self.ctx.driver
@property
def drivers(self):
return self.ctx._drivers
@property
def element_finder(self):
return self.ctx._element_finder
@element_finder.setter
def element_finder(self, value: Any):
self.ctx._element_finder = value
@property
def event_firing_webdriver(self):
return self.ctx.event_firing_webdriver
@event_firing_webdriver.setter
def event_firing_webdriver(self, event_firing_webdriver: Any):
self.ctx.event_firing_webdriver = event_firing_webdriver
def find_element(
self,
locator: str,
tag: Optional[str] = None,
required: bool = True,
parent: WebElement = None,
) -> WebElement:
"""Find element matching `locator`.
:param locator: Locator to use when searching the element.
See library documentation for the supported locator syntax.
:type locator: str or selenium.webdriver.remote.webelement.WebElement
:param tag: Limit searching only to these elements.
:type tag: str
:param required: Raise `ElementNotFound` if element not found when
true, return `None` otherwise.
:type required: True or False
:param parent: Optional parent `WebElememt` to search child elements
from. By default, search starts from the root using `WebDriver`.
:type parent: selenium.webdriver.remote.webelement.WebElement
:return: Found `WebElement` or `None` if element not found and
`required` is false.
:rtype: selenium.webdriver.remote.webelement.WebElement
:raises SeleniumLibrary.errors.ElementNotFound: If element not found
and `required` is true.
"""
return self.element_finder.find(locator, tag, True, required, parent)
def find_elements(
self, locator: str, tag: Optional[str] = None, parent: WebElement = None
) -> List[WebElement]:
"""Find all elements matching `locator`.
:param locator: Locator to use when searching the element.
See library documentation for the supported locator syntax.
:type locator: str or selenium.webdriver.remote.webelement.WebElement
:param tag: Limit searching only to these elements.
:type tag: str
:param parent: Optional parent `WebElememt` to search child elements
from. By default, search starts from the root using `WebDriver`.
:type parent: selenium.webdriver.remote.webelement.WebElement
:return: list of found `WebElement` or empty if elements are not found.
:rtype: list[selenium.webdriver.remote.webelement.WebElement]
"""
return self.element_finder.find(locator, tag, False, False, parent)
def is_text_present(self, text: str):
locator = f"xpath://*[contains(., {escape_xpath_value(text)})]"
return self.find_element(locator, required=False) is not None
def is_element_enabled(self, locator: str, tag: Optional[str] = None) -> bool:
element = self.find_element(locator, tag)
return element.is_enabled() and element.get_attribute("readonly") is None
def is_visible(self, locator: str) -> bool:
element = self.find_element(locator, required=False)
return element.is_displayed() if element else None | /robotframework-seleniumlibrary-6.1.2rc1.tar.gz/robotframework-seleniumlibrary-6.1.2rc1/src/SeleniumLibrary/base/context.py | 0.940216 | 0.226741 | context.py | pypi |
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
from SeleniumLibraryExtends.FindElements.findElements import FindElements
from SeleniumLibraryExtends.report import Report
class ElementInteraction:
def __init__(self):
pass
@keyword("I press the element ${locator}")
def clickElement(self, locator: str):
self.driver = BuiltIn().get_library_instance("SeleniumLibrary")
try:
FindElements().waitForElementVisible(locator)
REPEAT = "12x"
REPEAT_INTERVAL = "5 sec"
BuiltIn().wait_until_keyword_succeeds(REPEAT, REPEAT_INTERVAL, "Click Element", locator)
except Exception as e:
Report().fail(e)
@keyword("I press the button ${locator}")
def clickButton(self, locator: str):
self.driver = BuiltIn().get_library_instance("SeleniumLibrary")
try:
FindElements().waitForElementVisible(locator)
REPEAT = "12x"
REPEAT_INTERVAL = "5 sec"
BuiltIn().wait_until_keyword_succeeds(REPEAT, REPEAT_INTERVAL, "Click Button", locator)
except Exception as e:
Report().fail(e)
@keyword("I press the link ${locator}")
def clickLink(self, locator: str):
self.driver = BuiltIn().get_library_instance("SeleniumLibrary")
try:
FindElements().waitForElementVisible(locator)
REPEAT = "12x"
REPEAT_INTERVAL = "5 sec"
BuiltIn().wait_until_keyword_succeeds(REPEAT, REPEAT_INTERVAL, "Click Link", locator)
except Exception as e:
Report().fail(e)
@keyword("I press the image ${locator}")
def clickImage(self, locator: str):
self.driver = BuiltIn().get_library_instance("SeleniumLibrary")
try:
FindElements().waitForElementVisible(locator)
REPEAT = "12x"
REPEAT_INTERVAL = "5 sec"
BuiltIn().wait_until_keyword_succeeds(REPEAT, REPEAT_INTERVAL, "Click Image", locator)
except Exception as e:
Report().fail(e)
@keyword("I fill in the ${locator} field with ${text}")
def sendKeys(self, locator: str, text: str):
self.driver = BuiltIn().get_library_instance("SeleniumLibrary")
try:
FindElements().waitForElementVisible(locator)
REPEAT = "12x"
REPEAT_INTERVAL = "5 sec"
BuiltIn().wait_until_keyword_succeeds(REPEAT, REPEAT_INTERVAL, "Input Text", locator, text)
except Exception as e:
Report().fail(e)
@keyword("I submit the form")
def submitForm(self):
self.driver = BuiltIn().get_library_instance("SeleniumLibrary")
try:
self.driver.submit_form()
except Exception as e:
Report().fail(e) | /robotframework_seleniumlibraryextends-1.0.0-py3-none-any.whl/SeleniumLibraryExtends/ElementInteraction/elementInteraction.py | 0.513668 | 0.231093 | elementInteraction.py | pypi |
from collections import OrderedDict
from collections.abc import Mapping, MutableMapping
from SeleniumProxy.logger import get_logger, kwargstr, argstr
from selenium.common.exceptions import TimeoutException
import wrapt
import time
@wrapt.decorator
def log_wrapper(wrapped, instance, args, kwargs):
instance.logger.debug("{}({}) [ENTERING]".format(
wrapped.__name__, ", ".join([argstr(args), kwargstr(kwargs)])))
ret = wrapped(*args, **kwargs)
instance.logger.debug("{}() [LEAVING]".format(wrapped.__name__))
return ret
class InspectRequestsMixin:
@property
def requests(self):
return [Request(r, self._client) for r in self._client.get_requests()]
@requests.deleter
def requests(self):
self._client.clear_requests()
@property
def last_request(self):
data = self._client.get_last_request()
if data is not None:
return Request(data, self._client)
return None
@log_wrapper
def wait_for_request(self, path, timeout=10):
start = time.time()
while time.time() - start < timeout:
request = self._client.find(path)
if request is not None:
return Request(request, self._client)
else:
time.sleep(0.2)
raise TimeoutException('Timed out after {}s waiting for request {}'.format(timeout, path))
@log_wrapper
def wait_for_response(self, path, timeout=10):
start = time.time()
while time.time() - start < timeout:
request = self._client.find(path)
if request is not None:
req = Request(request, self._client)
return req.response.body
else:
time.sleep(0.2)
raise TimeoutException('Timed out after {}s waiting for response {}'.format(timeout, path))
@property
def header_overrides(self):
"""The header overrides for outgoing browser requests.
The value of the headers should be a dictionary. Where a header in
the dictionary exists in the request, the dictionary value will
overwrite the one in the request. Where a header in the dictionary
does not exist in the request, it will be added to the request as a
new header. To filter out a header from the request, set that header
in the dictionary with a value of None. Header names are case insensitive.
"""
return self._client.get_header_overrides()
@header_overrides.setter
def header_overrides(self, headers):
self._client.set_header_overrides(headers)
@header_overrides.deleter
def header_overrides(self):
self._client.clear_header_overrides()
@property
def rewrite_rules(self):
"""The rules used to rewrite request URLs.
The value of the rewrite rules should be a list of sublists (or tuples)
with each sublist containing the pattern and replacement.
i.e:
rewrite_rules = [
('pattern', 'replacement'),
('pattern', 'replacement'),
]
"""
return self._client.get_rewrite_rules()
@rewrite_rules.setter
def rewrite_rules(self, rewrite_rules):
self._client.set_rewrite_rules(rewrite_rules)
@rewrite_rules.deleter
def rewrite_rules(self):
self._client.clear_rewrite_rules()
@property
def scopes(self):
"""The URL patterns used to scope request capture.
The value of the scopes should be a list (or tuple) of
regular expressions.
For example:
scopes = [
'.*stackoverflow.*',
'.*github.*'
]
"""
return self._client.get_scopes()
@scopes.setter
def scopes(self, scopes):
self._client.set_scopes(scopes)
@scopes.deleter
def scopes(self):
self._client.reset_scopes()
class Request:
"""Represents a captured browser request."""
def __init__(self, data, client):
"""Initialises a new Request object with a dictionary of data and a
proxy client instance.
See the proxy client doc for the dictionary structure.
Note that the response attribute may be None where no response is associated
with a given request.
Args:
data: The dictionary of data.
client: The proxy client instance.
"""
self._data = data
self._client = client
self.method = data['method']
self.path = data['path']
self.headers = CaseInsensitiveDict(data['headers'])
if data['response'] is not None:
self.response = Response(self._data['id'], data['response'], client)
else:
self.response = None
@property
def body(self):
"""Lazily retrieves the request body when it is asked for.
Returns:
The response bytes.
"""
if self._data.get('body') is None:
self._data['body'] = self._client.get_request_body(self._data['id'])
return self._data['body']
def __repr__(self):
return 'Request({})'.format(self._data)
def __str__(self):
return self.path
class Response:
"""Represents a captured server response associated with a previous request."""
def __init__(self, request_id, data, client):
"""Initialise a new Response object with a request id, a dictionary
of data and a proxy client instance.
See the proxy client doc for the dictionary structure.
Args:
request_id: The request id.
data: The dictionary of data.
client: The proxy client instance.
"""
self._request_id = request_id
self._client = client
self._data = data
self.status_code = data['status_code']
self.reason = data['reason']
self.headers = CaseInsensitiveDict(data['headers'])
@property
def body(self):
"""Lazily retrieves the response body when it is asked for.
Returns:
The response bytes.
"""
if self._data.get('body') is None:
self._data['body'] = self._client.get_response_body(self._request_id)
return self._data['body']
def __repr__(self):
return "Response('{}', {})".format(self._request_id, self._data)
def __str__(self):
return '{} {}'.format(self.status_code, self.reason)
# This class has been taken from the requests library.
# https://github.com/requests/requests.
class CaseInsensitiveDict(MutableMapping):
"""A case-insensitive ``dict``-like object.
Implements all methods and operations of
``MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The structure remembers the
case of the last key to be set, and ``iter(instance)``,
``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
will contain case-sensitive keys. However, querying and contains
testing is case insensitive::
cid = CaseInsensitiveDict()
cid['Accept'] = 'application/json'
cid['aCCEPT'] == 'application/json' # True
list(cid) == ['Accept'] # True
For example, ``headers['content-encoding']`` will return the
value of a ``'Content-Encoding'`` response header, regardless
of how the header name was originally stored.
If the constructor, ``.update``, or equality comparison
operations are given keys that have equal ``.lower()``s, the
behavior is undefined.
"""
def __init__(self, data=None, **kwargs):
self._store = OrderedDict()
if data is None:
data = {}
self.update(data, **kwargs)
def __setitem__(self, key, value):
# Use the lowercased key for lookups, but store the actual
# key alongside the value.
self._store[key.lower()] = (key, value)
def __getitem__(self, key):
return self._store[key.lower()][1]
def __delitem__(self, key):
del self._store[key.lower()]
def __iter__(self):
return (casedkey for casedkey, mappedvalue in self._store.values())
def __len__(self):
return len(self._store)
def lower_items(self):
"""Like iteritems(), but with all lowercase keys."""
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in self._store.items()
)
def __eq__(self, other):
if isinstance(other, Mapping):
other = CaseInsensitiveDict(other)
else:
return NotImplemented
# Compare insensitively
return dict(self.lower_items()) == dict(other.lower_items())
# Copy is required
def copy(self):
return CaseInsensitiveDict(self._store.values())
def __repr__(self):
return str(dict(self.items())) | /robotframework-seleniumproxy-0.0.4.tar.gz/robotframework-seleniumproxy-0.0.4/src/SeleniumProxy/webdriver/request.py | 0.833053 | 0.199113 | request.py | pypi |
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary.keywords import BrowserManagementKeywords
from selenium.webdriver.support.events import EventFiringWebDriver
from robot.utils import is_truthy
from SeleniumProxy import webdriver
from SeleniumProxy.logger import get_logger, kwargstr, argstr
import wrapt
@wrapt.decorator
def log_wrapper(wrapped, instance, args, kwargs):
instance.logger.debug("{}({}) [ENTERING]".format(
wrapped.__name__, ", ".join([argstr(args), kwargstr(kwargs)])))
ret = wrapped(*args, **kwargs)
instance.logger.debug("{}() [LEAVING]".format(wrapped.__name__))
return ret
class BrowserKeywords(LibraryComponent):
def __init__(self, ctx):
LibraryComponent.__init__(self, ctx)
self.logger = get_logger("SeleniumProxy")
self.logger.debug("BrowserKeywords_{}".format(ctx))
self.manager = BrowserManagementKeywords(ctx)
@log_wrapper
@keyword
def open_proxy_browser(self, url=None, browser='chrome', proxy_options=None, alias=None):
"""Open Browser.
The ``url`` is the address you wish to open the browser with. https://google.com
The ``browser`` argument is the browser type you wish to run. Chrome or Firefox
``proxy_settings`` parameter is optional and if provided, it must be a dictionary.
Optional Settings:
If the site you are testing uses a self-signed certificate then you must set the verify_ssl option to False
```
{
'verify_ssl': False
}
```
The number of seconds Selenium Wire should wait before timing out requests.
```
{
'connection_timeout': None # Never timeout
}
```
If the site you are testing sits behind a proxy server you can tell Selenium Wire about that proxy server in the options you pass to the webdriver instance. The configuration takes the following format:
```
{
'proxy': {
'http': 'http://username:password@host:port',
'https': 'https://username:password@host:port',
'no_proxy': 'localhost,127.0.0.1,dev_server:8080'
}
}
```
Example:
| `Open Proxy Browser` | https://duckduckgo.com | Chrome | ${proxy_dict_options}
"""
index = self.drivers.get_index(alias)
if index:
self.info('Using existing browser from index %s.' % index)
self.manager.switch_browser(alias)
if is_truthy(url):
self.manager.go_to(url)
return index
return self._make_new_browser(url, browser, proxy_options, alias)
@keyword
def create_webdriver(self, driver_name, alias=None, kwargs={}, **init_kwargs):
pass
def _make_new_browser(self, url, browser, proxy_options, alias=None):
driver = self._make_proxy_driver(browser, proxy_options)
driver = self._wrap_event_firing_webdriver(driver)
index = self.ctx.register_driver(driver, alias)
if is_truthy(url):
try:
driver.get(url)
except Exception:
self.debug("Opened browser with session id %s but failed to open url '%s'." % (
driver.session_id, url))
raise
self.debug('Opened browser with session id %s.' % driver.session_id)
return index
def _wrap_event_firing_webdriver(self, driver):
if not self.ctx.event_firing_webdriver:
return driver
self.debug('Wrapping driver to event_firing_webdriver.')
return EventFiringWebDriver(driver, self.ctx.event_firing_webdriver())
@log_wrapper
def _make_proxy_driver(self, browser, proxy_options):
if browser == 'Chrome':
driver = webdriver.Chrome(options=proxy_options)
elif browser == 'Firefox':
driver = webdriver.Firefox(options=proxy_options)
else:
raise Exception("Browser Type Not Available")
driver.set_script_timeout(self.ctx.timeout)
driver.implicitly_wait(self.ctx.implicit_wait)
return driver | /robotframework-seleniumproxy-0.0.4.tar.gz/robotframework-seleniumproxy-0.0.4/src/SeleniumProxy/keywords/browser_keywords.py | 0.690037 | 0.298581 | browser_keywords.py | pypi |
import re
import threading
from urllib.parse import urlsplit
from SeleniumProxy.proxy.util import is_list_alike
class RequestModifier:
"""This class is responsible for modifying the URL and headers
of a request.
Instances of this class are designed to be stateful and threadsafe.
"""
def __init__(self):
"""Initialise a new RequestModifier."""
self._lock = threading.Lock()
self._headers = []
self._rewrite_rules = []
@property
def headers(self):
"""The headers that should be used to override the request headers.
The value of the headers could be a dictionary or list of sublists,
with each sublist having two elements - the pattern and headers.
Where a header in the dictionary exists in the request, the dictionary
value will overwrite the one in the request. Where a header in the
dictionary does not exist in the request, it will be added to the
request as a new header. To filter out a header from the request,
set that header in the dictionary with a value of None.
Header names are case insensitive.
For example:
headers = {'User-Agent':'Firefox'}
headers = [
('.*google.com.*', {'User-Agent':'Firefox'}),
('url2', {'User-Agent':'IE'}),
]
"""
with self._lock:
if is_list_alike(self._headers):
return self._headers
else:
return dict(self._headers)
@headers.setter
def headers(self, headers):
"""Sets the headers to override request headers.
Args:
headers: The dictionary of headers or list of sublists,
with each sublist having two elements - the pattern and headers
to set.
"""
with self._lock:
self._headers = headers
@headers.deleter
def headers(self):
"""Clears the headers being used to override request headers.
After this is called, request headers will pass through unmodified.
"""
with self._lock:
self._headers.clear()
@property
def rewrite_rules(self):
"""The rules used to rewrite request URLs.
The value of the rewrite rules should be a list of sublists (or tuples)
with each sublist containing the pattern and replacement.
For example:
rewrite_rules = [
('pattern', 'replacement'),
('pattern', 'replacement'),
]
"""
with self._lock:
return [(pat.pattern, repl) for pat, repl in self._rewrite_rules]
@rewrite_rules.setter
def rewrite_rules(self, rewrite_rules):
"""Sets the rewrite rules used to modify request URLs.
Args:
rewrite_rules: The list of rewrite rules, which should
be a list of sublists, with each sublist having two
elements - the pattern and replacement.
"""
compiled = []
for pattern, replacement in rewrite_rules:
compiled.append((re.compile(pattern), replacement))
with self._lock:
self._rewrite_rules = compiled
@rewrite_rules.deleter
def rewrite_rules(self):
"""Clears the rewrite rules being used to modify request URLs.
After this is called, request URLs will no longer be modified.
"""
with self._lock:
self._rewrite_rules.clear()
def modify(self, request):
"""Performs modifications to the request.
Args:
request: The request (a BaseHTTPHandler instance) to modify.
"""
self._modify_headers(request)
self._rewrite_url(request)
def _modify_headers(self, request):
with self._lock:
# If self._headers is tuple or list, need to use the pattern matching
if is_list_alike(self._headers):
headers = self._matched_headers(self._headers, request.path)
else:
headers = self._headers
if not headers:
return
headers_lc = {h.lower(): (h, v) for h, v in headers.items()}
# Remove/replace any header that already exists in the request
for header in list(request.headers):
try:
value = headers_lc.pop(header.lower())[1]
except KeyError:
pass
else:
del request.headers[header]
if value is not None:
request.headers[header] = value
# Add new headers to the request that don't already exist
for header, value in headers_lc.values():
request.headers[header] = value
def _rewrite_url(self, request):
with self._lock:
rewrite_rules = self._rewrite_rules[:]
original_netloc = urlsplit(request.path).netloc
for pattern, replacement in rewrite_rules:
modified, count = pattern.subn(replacement, request.path)
if count > 0:
request.path = modified
break
modified_netloc = urlsplit(request.path).netloc
if original_netloc != modified_netloc:
# Modify the Host header if it exists
if 'Host' in request.headers:
request.headers['Host'] = modified_netloc
def _matched_headers(self, header_rules, path):
results = {}
for rule in header_rules:
pattern = rule[0]
headers = rule[1]
match = re.search(pattern, path)
if match:
results.update(headers)
return results | /robotframework-seleniumproxy-0.0.4.tar.gz/robotframework-seleniumproxy-0.0.4/src/SeleniumProxy/proxy/modifier.py | 0.77586 | 0.348756 | modifier.py | pypi |
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
import os.path
import re
def resource(name):
return os.path.join(
os.path.dirname(__file__),
'resources',
name,
)
class Image(object):
@keyword('Crop image')
def crop_image(self, output_dir, filename, left, top, width, height):
"""Crop the saved image at the given ``output_dir`` with the given
``filename`` down to the given dimensions.
This keyword is primarily for the internal use of this keyword library.
"""
from PIL import Image
img = Image.open(os.path.join(output_dir, filename))
box = (int(left), int(top), int(left + width), int(top + height))
area = img.crop(box)
with open(os.path.join(output_dir, filename), 'wb') as output:
area.save(output, 'png')
return os.path.join(output_dir, filename)
class SeleniumScreenshots(Image):
"""SeleniumScreenshots library for Robot Framework provides keywords for
annotating and cropping screenshots taken with SeleniumLibrary.
The library requires SeleniumLibrary 3.2 or later.
"""
crop_margin = 10
def __init__(self, crop_margin=10):
"""Accepts the following optional keyword arguments:
``crop_margin``
desired margin added around the selected areas in cropped
screenshots.
"""
self.crop_margin = crop_margin
@property
def selenium_library(self):
return BuiltIn().get_library_instance('SeleniumLibrary')
@keyword('Bootstrap jQuery')
def bootstrap_jquery(self):
"""Injects jQuery into the currently active window when it does not
exist already.
Most of the SeleniumScreenshots library keywords rely on jQuery
being available on the current page. If jQuery is not globally
available on the current page, it can be injected using this
keyword. Otherwise the keywords will fail.
This keyword is primarily for the internal use of this keyword library.
"""
return self.selenium_library.execute_async_javascript(
resource('bootstrap_jquery.js'),
)
@keyword('Normalize annotation locator')
def normalize_annotation_locator(self, locator):
"""Normalizes the given *SeleniumLibrary*-locator into
*Sizzle*-selector, which is the supported selector format in the jQuery
based keywords of this library.
Returns a normalized version of the given locator.
This keyword is primarily for the internal use of this keyword library.
"""
if re.match(r'^jquery[=:]', locator):
locator = locator[len('jquery='):]
elif re.match(r'^css[=:]', locator):
locator = locator[len('css='):]
elif re.match(r'^name[=:]', locator):
locator = '[name="' + locator[len('name='):] + '"]'
elif re.match(r'^link[=:]', locator):
locator = 'a:icontains("' + locator[len('name='):] + '"):eq(0)'
elif re.match(r'^id[=:]', locator):
locator = '#' + locator[len('id='):]
else:
locator = '#' + locator
return locator
@keyword('Add pointer')
def add_pointer(self, locator, size=20, top=50, left=50):
"""Adds a round transparent dot at the center of the given ``locator``.
Accepts the following optional keyword arguments:
``size``
size of the pointer in pixels
``top``
top alignment of the pointer in percents
``left``
left alignment of the pointer in percents.
Returns id of the created element.
"""
assert self.bootstrap_jquery()
selector = self.normalize_annotation_locator(locator)
id_ = self.selenium_library.execute_async_javascript(
resource('add_pointer.js'),
'ARGUMENTS',
selector,
size,
top,
left,
)
if not id_:
raise AssertionError(
selector + ' not found and no pointer was created',
)
return id_
@keyword('Add dot')
def add_dot(
self,
locator,
text='',
color='black',
background='#fcf0ad',
size=20,
top=50,
left=50
):
"""Adds a colored round dot at the center of the given ``locator``
with optional text.
Accepts the following optional keyword arguments:
``text``
text rendered inside the dot
``color``
foreground color of the dot
``background``
background color of the dot
``size``
size of the dot in pixels
``top``
top alignment of the dot in percents
``left``
left alignment of the dot in percents.
Returns id of the created element.
"""
assert self.bootstrap_jquery()
selector = self.normalize_annotation_locator(locator)
id_ = self.selenium_library.execute_async_javascript(
resource('add_dot.js'),
'ARGUMENTS',
selector,
text,
color,
background,
size,
top,
left,
)
if not id_:
raise AssertionError(
selector + ' not found and no dot was created',
)
return id_
@keyword('Add note')
def add_note(
self,
locator,
text,
width=None,
color='black',
background='#fcf0ad',
border='none',
position='center',
display='block'
):
"""Adds a colored note at the given ``locator`` with the given
``text``.
Accepts the following optional keyword arguments:
``width``
width of the note in pixels
``color``
foreground color of note note
``background``
background color of the note
``border``
border style of the note
``position``
position of the note relative to the given ``locator`` and must be
one of the following values: ``center``, ``top``, ``right``,
``bottom`` or ``left``
``display``
display style property value of the note.
Returns id of the created element.
"""
assert self.bootstrap_jquery()
selector = self.normalize_annotation_locator(locator)
id_ = self.selenium_library.execute_async_javascript(
resource('add_note.js'),
'ARGUMENTS',
selector,
text,
width,
color,
background,
border,
position,
False,
self.crop_margin,
display,
)
if not id_:
raise AssertionError(
selector + ' not found and no note was created',
)
return id_
@keyword('Add pointy note')
def add_pointy_note(
self,
locator,
text,
width=None,
color='black',
background='#fcf0ad',
border='none',
position='center',
display='block'
):
"""Adds a colored pointy note at the given ``locator`` with the given
``text``.
Accepts the following optional keyword arguments:
``width``
width of the note in pixels (leave empty for auto)
``color``
foreground color of note note
``background``
background color of the note
``border``
border style of the note
``position``
position of the note relative to the given ``locator`` and must be
one of the following values: ``center``, ``top``, ``right``,
``bottom`` or ``left``
``display``
display style property value of the note.
Returns id of the created element.
"""
assert self.bootstrap_jquery()
selector = self.normalize_annotation_locator(locator)
id_ = self.selenium_library.execute_async_javascript(
resource('add_note.js'),
'ARGUMENTS',
selector,
text,
width,
color,
background,
border,
position,
True,
self.crop_margin,
display,
)
if not id_:
raise AssertionError(
selector + ' not found and no note was created',
)
return id_
@keyword('Remove element')
def remove_element(self, locator):
"""Removes the element at the given ``locator`` from the current
page.
"""
assert self.bootstrap_jquery()
selector = self.normalize_annotation_locator(locator)
return self.selenium_library.execute_async_javascript(
resource('remove_element.js'),
'ARGUMENTS',
selector,
)
@keyword('Remove elements')
def remove_elements(self, *locators):
"""Removes the elements at the given ``locators`` from the current
page.
"""
assert self.bootstrap_jquery()
results = []
for locator in locators:
selector = self.normalize_annotation_locator(locator)
results.append(
self.selenium_library.execute_async_javascript(
resource('remove_element.js'),
'ARGUMENTS',
selector,
)
)
return False not in results
@keyword('Update element style')
def update_element_style(self, locator, name, value):
"""Updates style for elements at the ``locator`` matching the given
``name`` with the given ``value``,
"""
assert self.bootstrap_jquery()
selector = self.normalize_annotation_locator(locator)
return self.selenium_library.execute_async_javascript(
resource('update_element_style.js'),
'ARGUMENTS',
selector,
name,
value,
)
@keyword('Align elements horizontally')
def align_elements_horizontally(self, *locators):
"""Aligns the elements matching the given ``locators`` so that the
subsequent elements are aligned after the first element.
"""
assert self.bootstrap_jquery()
selectors = map(self.normalize_annotation_locator, locators)
return self.selenium_library.execute_async_javascript(
resource('align_elements_horizontally.js'),
'ARGUMENTS',
list(selectors),
self.crop_margin,
)
@keyword('Crop page screenshot')
def crop_page_screenshot(self, filename, *locators):
"""Crops the given ``filename`` to match the combined bounding box of
the elements matching the given ``locators``.
This keyword is primarily for the internal use of this keyword library.
"""
assert self.bootstrap_jquery()
selectors = map(self.normalize_annotation_locator, locators)
dimensions = self.selenium_library.execute_async_javascript(
resource('get_bounding_box.js'),
'ARGUMENTS',
list(selectors),
self.crop_margin,
)
if len(dimensions) != 4:
raise AssertionError(
dimensions[0] + ' not found and no image was cropped',
)
output_dir = BuiltIn().get_variable_value('${OUTPUT_DIR}')
return self.crop_image(output_dir, filename, *dimensions)
@keyword('Capture and crop page screenshot')
def capture_and_crop_page_screenshot(self, filename, *locators):
"""Captures a page screenshot with the given ``filename`` and crops it to
match the combined bounding box of the elements matching the given
``locators``.
"""
self.selenium_library.capture_page_screenshot(filename, )
return self.crop_page_screenshot(filename, *locators)
@keyword('Capture viewport screenshot')
def capture_viewport_screenshot(self, filename):
"""Captures a page screenshot with the given ``filename`` and crops it
to match the current browser window dimensions and scroll position.
"""
assert self.bootstrap_jquery()
dimensions = self.selenium_library.execute_async_javascript(
resource('get_viewport_box.js'),
)
self.selenium_library.capture_page_screenshot(filename, )
output_dir = BuiltIn().get_variable_value('${OUTPUT_DIR}')
return self.crop_image(output_dir, filename, *dimensions)
@keyword('Highlight')
def highlight(self, locator, width=3, style='dotted', color='red'):
"""Adds a simple highlighting for the elements at the given
``locator``.
"""
return self.update_element_style(
locator,
'outline',
str(width) + 'px ' + style + ' ' + color,
)
@keyword('Clear highlight')
def clear_highlight(self, locator):
"""Clears the highlighting from the elements at the given ``locator``.
"""
return self.update_element_style(
locator,
'outline',
'none',
) | /robotframework_seleniumscreenshots-0.9.5-py3-none-any.whl/SeleniumScreenshots/__init__.py | 0.849597 | 0.335596 | __init__.py | pypi |
from SeleniumLibrary.base import LibraryComponent, keyword
from SeleniumLibrary.keywords.element import ElementKeywords
from SeleniumLibrary import SeleniumLibrary
from os.path import abspath, dirname, join
from .listener import TestabilityListener
from .javascript import JS_LOOKUP
from .logger import get_logger, argstr, kwargstr
from .types import (
WebElementType,
LocatorType,
OptionalBoolType,
OptionalStrType,
BrowserLogsType,
OptionalDictType,
is_firefox,
StringArray,
StorageType,
)
from robot.utils import is_truthy, timestr_to_secs, secs_to_timestr
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException, WebDriverException
from http.cookies import SimpleCookie
from furl import furl
from typing import Dict, Callable, Any
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver import FirefoxProfile
import wrapt
import re
import json
from time import time
from pathlib import Path
@wrapt.decorator
def log_wrapper(wrapped: Callable, instance: "SeleniumTestability", args: Any, kwargs: Any) -> Any:
instance.logger.debug("{}({}) [ENTERING]".format(wrapped.__name__, ", ".join([argstr(args), kwargstr(kwargs)])))
ret = wrapped(*args, **kwargs)
instance.logger.debug("{}() [LEAVING]".format(wrapped.__name__))
return ret
class SeleniumTestability(LibraryComponent):
"""
SeleniumTestability is plugin for SeleniumLibrary that provides either manual or automatic waiting asyncronous events within SUT. This works by injecting small javascript snippets that can monitor the web application's state and when any supported events are happening within the sut, execution of SeleniumLibrary's keywords are blocked until timeout or those events are processed.
On top of this, there are some more or less useful utilities for web application testing.
== Usage ==
Example:
| ***** Settings *****
| Library SeleniumLibrary plugins=SeleniumTestability;True;30 Seconds;True
|
| Suite Setup Open Browser https://127.0.0.1:5000/ browser=Firefox
| Suite Teardown Close Browser
|
| ***** Test Cases *****
| Instrument Browser Example
| ${x}= `Testability Loaded`
| Should Be True ${x}
== Parameters ==
Plugin can take parameters when it is initialized. All of these values can be modified at runtim too with corresponding keywords. Here's a list of the parameters:
=== automatic_wait ===
a truthy value, if SeleniumTestabily should automatically wait for sut to be in state that it can accept more actions.
Can be enabled/disable at runtime.
Defaults to True
=== timeout ===
Robot timestring, amount of time to wait for SUT to be in state that it can be safely interacted with.
Can be set at runtime.
Defaults to 30 seconds.
=== error_on_timeout ===
A truthy value, if timeout does occur either in manual or automatic mode, this determines if error should be thrown that marks marks the exection as failure.
Can be enabled/disabled at runtime.
Defaults to True
=== automatic_injection ===
A truthy value. User can choose if he wants to instrument the SUT manually with appropriate keywords (or even, if the SUT is instrumented at build time?) or should SeleniumTestability determinine if SUT has testability features and if not then inject & instrument it automatically.
Can be enabled/disabled at runtime.
Defaults to True
== Waiting ==
There are two modes of waiting, automatic and non-automatic. When automatic waiting is enabled, when SeleniumLibrary keywords are used, plugin waits until all currently running and supported asyncronous events are done before commencing to use the locator.
=== Automatic ===
| ***** Settings *****
| Library SeleniumLibrary plugins=SeleniumTestability;True;30 Seconds;True
|
| Suite Setup Open Browser https://127.0.0.1:5000/ browser=Firefox
| Suite Teardown Close Browser
|
| ***** Test Cases *****
| Basic Example
| Click Element id:fetch-button
| Click Element id:xhr-button
| `Wait For Testability Ready`
In this scenario, test is clicking first element, waits for the fetch call to finish before clicking on the next. Also, do note that in this example, we are calling `Wait For Testability Ready` to also wait for xhr request to finish as there is no other SeleniumLibrary calls after the second click.
=== Non Automatic ===
| ***** Settings *****
| Library SeleniumLibrary plugins=SeleniumTestability;False;30 Seconds;True
|
| Suite Setup Open Browser https://127.0.0.1:5000/ browser=Firefox
| Suite Teardown Close Browser
|
| ***** Test Cases *****
| Basic Example
| Click Element id:fetch-button
| `Wait For Testability Ready`
| Click Element id:xhr-button
| `Wait For Testability Ready`
= Currently supported Asyncronouse features =
- setTimeout & setImmediate calls and wait for them.
- fetch() call and wait for it to finish
- XHR requests and wait for them to finish
- CSS Animations and wait form them to finish
- CSS Transitions and wait form them to finish
- Viewport scrolling.
*Do note* that catching css animations and transitions is browser dependant. In the past
certain browsers did not implement these features as "the standard" would require.
= Other functionality. =
SeleniumTestability also provides other conveniance keywords that do not make sense to incorporate into
SeleniumLibrary itself, mainly due to functionality not being in scope of SeleniumLibrary and Selenium
python bindings. Do check the keyword documentation for up to date list of keywords.
"""
BROWSERS = {
"googlechrome": DesiredCapabilities.CHROME,
"gc": DesiredCapabilities.CHROME,
"chrome": DesiredCapabilities.CHROME,
"headlesschrome": DesiredCapabilities.CHROME,
"ff": DesiredCapabilities.FIREFOX,
"firefox": DesiredCapabilities.FIREFOX,
"headlessfirefox": DesiredCapabilities.FIREFOX,
"ie": DesiredCapabilities.INTERNETEXPLORER,
"internetexplorer": DesiredCapabilities.INTERNETEXPLORER,
"edge": DesiredCapabilities.EDGE,
"safari": DesiredCapabilities.SAFARI,
"htmlunit": DesiredCapabilities.HTMLUNIT,
"htmlunitwithjs": DesiredCapabilities.HTMLUNITWITHJS,
"iphone": DesiredCapabilities.IPHONE,
}
@property
def automatic_wait(self: "SeleniumTestability") -> bool:
return self.ctx.testability_settings["automatic_wait"]
@automatic_wait.setter
def automatic_wait(self: "SeleniumTestability", value: bool) -> None:
self.ctx.testability_settings["automatic_wait"] = value
@property
def error_on_timeout(self: "SeleniumTestability") -> bool:
return self.ctx.testability_settings["error_on_timeout"]
@error_on_timeout.setter
def error_on_timeout(self: "SeleniumTestability", value: bool) -> None:
self.ctx.testability_settings["error_on_timeout"] = value
@property
def timeout(self: "SeleniumTestability") -> float:
return self.ctx.testability_settings["timeout"]
@timeout.setter
def timeout(self: "SeleniumTestability", value: str) -> None:
self.ctx.testability_settings["timeout"] = timestr_to_secs(value)
@property
def automatic_injection(self: "SeleniumTestability") -> bool:
return self.ctx.testability_settings["automatic_injection"]
@automatic_injection.setter
def automatic_injection(self: "SeleniumTestability", value: bool) -> None:
self.ctx.testability_settings["automatic_injection"] = value
def __init__(
self: "SeleniumTestability",
ctx: SeleniumLibrary,
automatic_wait: bool = True,
timeout: str = "30 seconds",
error_on_timeout: bool = True,
automatic_injection: bool = True,
) -> None:
LibraryComponent.__init__(self, ctx)
self.logger = get_logger("SeleniumTestability")
self.logger.debug("__init__({},{},{},{},{})".format(ctx, automatic_wait, timeout, error_on_timeout, automatic_injection))
self.el = ElementKeywords(ctx)
self.CWD = abspath(dirname(__file__))
self.js_bundle = join(self.CWD, "js", "testability.js")
self.ctx.event_firing_webdriver = TestabilityListener
self.ctx.testability_settings = {"testability": self}
self.automatic_wait = is_truthy(automatic_wait)
self.automatic_injection = is_truthy(automatic_injection)
self.error_on_timeout = is_truthy(error_on_timeout)
self.timeout = timeout # type: ignore
self.hidden_elements = {} # type: Dict[str, str]
self.browser_warn_shown = False
self.empty_log_warn_shown = False
self.ff_log_pos = {} # type: Dict[str, int]
self.testability_config = None # type: OptionalDictType
@log_wrapper
def _inject_testability(self: "SeleniumTestability") -> None:
"""
Injects SeleniumTestability javascript bindings into a current browser's current window. This should happen automatically vie SeleniumTestability's internal `Event Firing Webdriver` support but keyword is provided also.
"""
if self.testability_config:
self.ctx.driver.execute_script(JS_LOOKUP["testability_config"], self.testability_config)
with open(self.js_bundle, "r") as f:
buf = f.read()
self.ctx.driver.execute_script("{};".format(buf))
@log_wrapper
@keyword
def set_testability_config(self: "SeleniumTestability", config: Dict) -> None:
"""
Sets configuration that is used by SUT. `config` dictionary should can have following keys: `maxTimeout` and `blacklist`.
Configuration has to be set before opening any browsers or before SUT is instrumented either automatically or manually.
- `maxTimeout` affects affects javascript `setTimeout()` calls and what is the maximum timeout that should be observed and waited. Value is milliseconds and defaults to 5000
- `blacklist` is array of dictionaries where each array element have 2 fields. `url` and `method`. `url` should be a regular expression that matches the actual url or url of the Request object's url field.
Do note that the regular expression should match what is actually passed to the async method - not the fully qualied url.
Parameters:
- ``config`` dictionary of testability.js config options.
Example:
| &{longfetch}= | `Create Dictionary` | url=.*longfetch.* | method=GET |
| @{blacklist}= | `Create List` | ${longfetch} | |
| ${tc}= | `Create Dictionary` | maxTimeout=5000 | blacklist=${blacklist} |
| Set Testability Config | ${tc} | | |
.
"""
self.testability_config = config
@log_wrapper
@keyword
def instrument_browser(self: "SeleniumTestability") -> None:
"""
Instruments the current webpage for testability. This should happen automatically vie SeleniumTestability's internal `Event Firing Webdriver` support but keyword is provided also. Calls `Inject Testability` keyword automatically.
"""
if not self.is_testability_installed():
self._inject_testability()
@log_wrapper
@keyword
def is_testability_installed(self: "SeleniumTestability") -> bool:
"""
Returns True if testability api's are loaded and current browser/window is instrumented, False if not.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["is_installed"])
@log_wrapper
@keyword
def wait_for_document_ready(self: "SeleniumTestability") -> None:
"""
Explicit waits until document.readyState is complete.
"""
self.ctx.driver.execute_async_script(JS_LOOKUP["wait_for_document_ready"])
@log_wrapper
@keyword
def set_testability_automatic_wait(self: "SeleniumTestability", enabled: bool) -> None:
"""
Sets the state to TestabilityListener if it should automically call `Wait For Testability Ready` when interactions are done.
Parameters:
- ``enabled`` state of automatic waits.
"""
self.automatic_wait = enabled
@log_wrapper
@keyword
def enable_testability_automatic_wait(self: "SeleniumTestability") -> None:
"""
Enables TestabilityListener to call `Wait For Testability Ready` onn all interactions that are done.
"""
self.set_testability_automatic_wait(True)
@log_wrapper
@keyword
def disable_testability_automatic_wait(self: "SeleniumTestability") -> None:
"""
Disables TestabilityListener to call `Wait For Testability Ready` onn all interactions that are done.
"""
self.set_testability_automatic_wait(False)
@log_wrapper
@keyword
def wait_for_testability_ready(
self: "SeleniumTestability", timeout: OptionalStrType = None, error_on_timeout: OptionalBoolType = None
) -> None:
"""
Explicitly waits until testability is ready or timeout happens.
Parameters:
- ``timeout`` Amount of time to wait until giving up for testability to be ready. Robot framework timestring
- ``error_on_timeout`` if timeout occurs, should we throw an error
Both parameters are optional, if not provided, default values from plugin initialization time are used.
"""
local_timeout = self.timeout
if timeout is not None:
local_timeout = timestr_to_secs(timeout)
local_error_on_timeout = self.error_on_timeout
if error_on_timeout is not None:
local_error_on_timeout = is_truthy(error_on_timeout)
try:
WebDriverWait(self.ctx.driver, local_timeout, 0.15, ignored_exceptions=[TimeoutException]).until(
lambda x: self.ctx.driver.execute_async_script(JS_LOOKUP["wait_for_testability"])
)
except TimeoutException:
if local_error_on_timeout:
raise TimeoutException("Timed out waiting for testability ready callback to trigger.")
except Exception as e:
self.warn(e)
@log_wrapper
@keyword
def set_testability_timeout(self: "SeleniumTestability", timeout: str) -> str:
"""
Sets the global timeout value for waiting testability ready. Overrides the defaults set from plugin parameters.
Parameters:
- ``timeout`` Amount of time to wait until giving up for testability to be ready. Robot framework timestring
"""
current = self.timeout
self.timeout = timeout # type: ignore
return secs_to_timestr(current)
@log_wrapper
@keyword
def get_testability_timeout(self: "SeleniumTestability") -> str:
"""
Returns the global timeout value in robot framework timestr format for waiting testability ready.
"""
return secs_to_timestr(self.timeout)
@log_wrapper
@keyword
def set_testability_error_on_timeout(self: "SeleniumTestability", error_on_timeout: bool) -> None:
"""Sets the global error_on_timeout value. eg, should SeleniumTestability throw exception when timeout occurs and there are still events in the testability queue.
Parameters:
- ``error_on_timeout`` - any value that robot framework considers truthy can be provided here.
"""
self.error_on_timeout = error_on_timeout
@keyword
@log_wrapper
def get_testability_error_on_timeout(self: "SeleniumTestability") -> bool:
"""Returns error_on_timeout value set via plugin parameters or via `Set Testability Error On Timeout`keyword.
"""
return self.error_on_timeout
@staticmethod
@keyword("Add Basic Authentication To Url")
def add_authentication(url: str, user: str, password: str) -> str:
"""
For websites that require basic auth authentication, add user and password into the given url.
Parameters:
- ``url`` - url where user and password should be added to.
- ``user`` - username
- ``password`` - password
"""
data = furl(url)
data.username = user
data.password = password
return data.tostr()
@staticmethod
@keyword
def split_url_to_host_and_path(url: str) -> dict:
"""
Returs given url as dict with property "base" set to a protocol and hostname and "path" as the trailing path.
This is useful when constructing requests sessions from urls used within SeleniumLibrary.
"""
data = furl(url)
return {"base": str(data.copy().remove(path=True)), "path": str(data.path)}
@log_wrapper
@keyword
def set_testability_automatic_injection(self: "SeleniumTestability", enabled: bool) -> None:
"""
Sets the state to TestabilityListener if it should automically inject testability.
Parameters:
- ``enabled`` state of automatic injection
"""
self.automatic_injection = enabled
@log_wrapper
@keyword
def enable_testability_automatic_injection(self: "SeleniumTestability") -> None:
"""
Enables TestabilityListener to automatically inject testability.
"""
self.set_testability_automatic_injection(True)
@log_wrapper
@keyword
def disable_testability_automatic_injection(self: "SeleniumTestability") -> None:
"""
Disables TestabilityListener to automatically inject testability
"""
self.set_testability_automatic_injection(False)
@staticmethod
@keyword
def cookies_to_dict(cookies: str) -> dict: # FIX: cookies can be dict also
"""
Converts a cookie string into python dict.
"""
ret = {}
cookie = SimpleCookie() # type: SimpleCookie
cookie.load(cookies)
for key, morsel in cookie.items():
ret[key] = morsel.value
return ret
@log_wrapper
@keyword
def get_navigator_useragent(self: "SeleniumTestability") -> str:
"""
Returns useragent string of current browser.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["navigator"], "userAgent")
@log_wrapper
@keyword
def get_navigator_appCodeName(self: "SeleniumTestability") -> str:
"""
Returns appCoedName string of current browser.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["navigator"], "appCodeName")
@log_wrapper
@keyword
def get_navigator_appname(self: "SeleniumTestability") -> str:
"""
Returns appName string of current browser.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["navigator"], "appName")
@log_wrapper
@keyword
def get_navigator_appversion(self: "SeleniumTestability") -> str:
"""
Returns appVersion string of current browser.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["navigator"], "appVersion")
@log_wrapper
@keyword
def get_navigator_cookieenabled(self: "SeleniumTestability") -> bool:
"""
Returns cookieEnabled boolean of current browser.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["navigator"], "cookieEnabled")
@log_wrapper
@keyword
def get_navigator_language(self: "SeleniumTestability") -> str:
"""
Returns language string of current browser.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["navigator"], "language")
@log_wrapper
@keyword
def get_navigator_online(self: "SeleniumTestability") -> bool:
"""
Returns online boolean of current browser.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["navigator"], "onLine")
@log_wrapper
@keyword
def get_navigator_platform(self: "SeleniumTestability") -> str:
"""
Returns platform string of current browser.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["navigator"], "platform")
@log_wrapper
@keyword
def get_navigator_product(self: "SeleniumTestability") -> str:
"""
Returns product string of current browser.
"""
return self.ctx.driver.execute_script(JS_LOOKUP["navigator"], "product")
@log_wrapper
@keyword
def drag_and_drop(self: "SeleniumTestability", locator: LocatorType, target: LocatorType, html5: bool = False) -> None:
"""Drags element identified by ``locator`` into ``target`` element.
The ``locator`` argument is the locator of the dragged element
and the ``target`` is the locator of the target. See the
`Locating elements` section for details about the locator syntax.
If you wish to drag and drop a file from a local filesystem, you can specify the locator as `file:/full/path/to/filename`
and SeleniumTestability will generate a drag'n'drop events to upload a file into a given `target` element.
``html5`` parameter is optional and if provided, `drag_and_drop`will utilize
javascript to trigger the suitable events ensuring that html5 applications
receive the right events. If `locator` starts with file: prefix, html5 defaults to True.
Example:
| `Drag And Drop` | css:div#element | css:div.target | html5=True |
| `Drag And Drop` | file:/home/rasjani/testfile.txt | id:demo-upload |
"""
file_prefix = "file:"
html5 = is_truthy(html5)
if file_prefix in locator:
html5 = True
if not html5:
self.el.drag_and_drop(locator, target)
else:
to_element = self.el.find_element(target)
filename = None
if type(locator) == str and file_prefix in locator:
filename = locator[locator.startswith(file_prefix) and len(file_prefix):]
if filename is not None:
if Path(filename).exists():
file_input = self.driver.execute_script(JS_LOOKUP["drag_and_drop_file"], to_element, 0, 0)
file_input.send_keys(filename)
else:
raise RuntimeError(f"Unable to upload {filename} - its missing")
else:
from_element = self.el.find_element(locator)
self.ctx.driver.execute_script(JS_LOOKUP["dragdrop"], from_element, to_element)
@log_wrapper
@keyword
def scroll_to_bottom(self: "SeleniumTestability", smooth: bool = False) -> None:
"""
Scrolls current window to the bottom of the page
Parameters:
- ``smooth`` if sets to true, enables smooth scrolling, otherwise instant.
"""
smooth = bool(smooth)
behavior = "smooth" if smooth else "instant"
self.ctx.driver.execute_script(JS_LOOKUP["scroll_to_bottom"], behavior)
@log_wrapper
@keyword
def scroll_to_top(self: "SeleniumTestability", smooth: bool = False) -> None:
"""
Scrolls current window to the top of the page
Parameters:
- ``smooth`` if sets to true, enables smooth scrolling, otherwise instant.
"""
smooth = bool(smooth)
behavior = "smooth" if smooth else "instant"
self.ctx.driver.execute_script(JS_LOOKUP["scroll_to_top"], behavior)
@log_wrapper
@keyword
def toggle_element_visibility(self: "SeleniumTestability", locator: LocatorType) -> None:
"""
Toggles visiblity state of element via ``locator``
"""
if locator in self.hidden_elements:
self.hide_element(locator)
else:
self.show_element(locator)
@log_wrapper
@keyword
def hide_element(self: "SeleniumTestability", locator: LocatorType) -> None:
"""
Hides element via ``locator``. Typically one would use this to avoid getting
Toggles visiblity state of element via ``locator``
past overlays that are on top of element that is to be interacted with.
"""
from_element = self.el.find_element(locator)
current_display = self.ctx.driver.execute_script(JS_LOOKUP["get_style_display"], from_element)
self.hidden_elements[locator] = current_display
self.ctx.driver.execute_script(JS_LOOKUP["set_style_display"], from_element, "none")
@log_wrapper
@keyword
def show_element(self: "SeleniumTestability", locator: LocatorType) -> None:
"""
Shows element via ``locator`` that has been previously been hidden with `Hide Element` keyword.
"""
from_element = self.el.find_element(locator)
state = self.hidden_elements.get(locator, "")
self.ctx.driver.execute_script(JS_LOOKUP["set_style_display"], from_element, state)
del self.hidden_elements[locator]
def _element_blocked(self: "SeleniumTestability", locator: LocatorType) -> bool:
from_element = self.el.find_element(locator)
rect = self.ctx.driver.execute_script(JS_LOOKUP["get_rect"], from_element)
y = rect["y"] + (rect["height"] / 2)
x = rect["x"] + (rect["width"] / 2)
elem = self.ctx.driver.execute_script(JS_LOOKUP["get_element_at"], x, y)
try:
return from_element != elem.wrapped_element
except AttributeError:
return from_element != elem
@log_wrapper
@keyword
def get_webelement_at(self: "SeleniumTestability", x: int, y: int) -> WebElementType:
"""Returns a topmost WebElement at given coordinates"""
element = self.ctx.driver.execute_script(JS_LOOKUP["get_element_at"], x, y)
# NOTE: Maybe we should always return just straight element and not
# really care if its event firing or not?
try:
return element.wrapped_element
except AttributeError:
return element
@log_wrapper
@keyword
def is_element_blocked(self: "SeleniumTestability", locator: LocatorType) -> bool:
"""
Returns `True` is ``locator`` is blocked, `False` if it is not.
Example:
| ${blocked}= | Is Element Blocked | id:some_id | |
| Run Keyword If | ${blocked} == True | Hide Element | id:some_other_id |
This will hide the element with id:some_other_id if element id:some_id is being blocked
"""
return self._element_blocked(locator)
@log_wrapper
@keyword
def element_should_be_blocked(self: "SeleniumTestability", locator: LocatorType) -> None:
"""
Throws exception if element found with ``locator`` is not blocked by any overlays.
Example:
| Element Should Be Blocked | id:some_id |
If nothing is on top of of provided element, throws an exception
"""
is_blocked = self._element_blocked(locator)
if not is_blocked:
raise AssertionError("Element with locator {} is not blocked".format(locator))
@log_wrapper
@keyword
def element_should_not_be_blocked(self: "SeleniumTestability", locator: LocatorType) -> None:
"""
Throws exception if element found with ``locator`` is being blocked by overlays.
Example:
| Element Should Not Be Blocked | id:some_id |
If there's element on top of provided selector, throws an exception
"""
is_blocked = self._element_blocked(locator)
if is_blocked:
raise AssertionError("Element with locator {} is blocked".format(locator))
def _get_ff_log(self: "SeleniumTestability", name: str) -> BrowserLogsType:
matcher = (
r"^(?P<source>JavaScript|console)(\s|\.)(?P<level>warn.*?|debug|trace|log|error|info):\s(?P<message>(?!resource:).*)$"
)
LEVEL_LOOKUP = {
"log": "INFO",
"warn": "WARN",
"warning": "WARN",
"error": "SEVERE",
"info": "INFO",
"trace": "SEVERE",
"debug": "DEBUG",
}
SOURCE_LOOKUP = {"JavaScript": "javascript", "console": "console-api"}
log = []
skip_lines = self.ff_log_pos.get(name, 0)
buff: BrowserLogsType = []
with open(name, "r") as f:
buff = f.read().split("\n")
self.ff_log_pos[name] = skip_lines + len(buff)
buff = buff[skip_lines:]
for line in buff:
matches = re.search(matcher, line)
if matches:
row = {
"level": LEVEL_LOOKUP[matches.group("level")],
"message": matches.group("message"),
"source": SOURCE_LOOKUP[matches.group("source")],
"timestamp": int(time() * 1000),
}
log.append(json.dumps(row))
return log
@log_wrapper
@keyword
def get_log(self: "SeleniumTestability", log_type: str = "browser") -> BrowserLogsType:
"""
Returns logs determined by ``log_type`` from the current browser. What is returned
depends on desired_capabilities passed to `Open Browser`.
Note: On firefox, the firefox profile has to have `devtools.console.stdout.content` property to be set.
This can be done automatically with `Generate Firefox Profile` and then pass that to `Open Browser`.
This keyword will mostly likely not work with remote seleniun driver!
"""
ret = [] # type: BrowserLogsType
try:
if is_firefox(self.ctx.driver) and log_type == "browser":
ret = self._get_ff_log(self.ctx.driver.service.log_file.name)
else:
ret = self.ctx.driver.get_log(log_type)
except WebDriverException:
if not self.browser_warn_shown:
self.browser_warn_shown = True
self.warn("Current browser does not support fetching logs from the browser with log_type: {}".format(log_type))
return []
if not ret and not self.empty_log_warn_shown:
self.empty_log_warn_shown = True
self.warn("No logs available - you might need to enable loggingPrefs in desired_capabilities")
return ret
@log_wrapper
@keyword
def get_default_capabilities(self: "SeleniumTestability", browser_name: str) -> OptionalDictType:
"""
Returns a set of default capabilities for given ``browser``.
"""
try:
browser = browser_name.lower().replace(" ", "")
return self.BROWSERS[browser].copy()
except Exception as e:
self.logger.debug(e)
return None
@log_wrapper
@keyword
def set_element_attribute(self: "SeleniumTestability", locator: LocatorType, attribute: str, value: str) -> None:
"""
Sets ``locator`` attribute ``attribute`` to ``value``
"""
from_element = self.el.find_element(locator)
self.ctx.driver.execute_script(JS_LOOKUP["set_element_attribute"], from_element, attribute, value)
@log_wrapper
@keyword
def get_location_hash(self: "SeleniumTestability") -> str:
"""
returns the fragment identifier of the URL prefexed by a '#'
"""
return self.ctx.driver.execute_script(JS_LOOKUP["get_window_location"], "hash")
@log_wrapper
@keyword
def get_location_host(self: "SeleniumTestability") -> str:
"""
returns the hostname and the port of the URL appended by a ':'
"""
return self.ctx.driver.execute_script(JS_LOOKUP["get_window_location"], "host")
@log_wrapper
@keyword
def get_location_hostname(self: "SeleniumTestability") -> str:
"""
return the hostname of the URL
"""
return self.ctx.driver.execute_script(JS_LOOKUP["get_window_location"], "hostname")
@log_wrapper
@keyword
def get_location_href(self: "SeleniumTestability") -> str:
"""
returns the entire URL
"""
return self.ctx.driver.execute_script(JS_LOOKUP["get_window_location"], "href")
@log_wrapper
@keyword
def get_location_origin(self: "SeleniumTestability") -> str:
"""
returns the canonical form of the origin of the specific location
"""
return self.ctx.driver.execute_script(JS_LOOKUP["get_window_location"], "origin")
@log_wrapper
@keyword
def get_location_port(self: "SeleniumTestability") -> str:
"""
returns the port number of the URL
"""
return self.ctx.driver.execute_script(JS_LOOKUP["get_window_location"], "port")
@log_wrapper
@keyword
def get_location_protocol(self: "SeleniumTestability") -> str:
"""
returns the protocol scheme of the URL
"""
return self.ctx.driver.execute_script(JS_LOOKUP["get_window_location"], "protocol")
@log_wrapper
@keyword
def get_location_search(self: "SeleniumTestability") -> str:
"""
returns the sting containing a '?' followed by the parameters or ``querystring`` of the URL
"""
return self.ctx.driver.execute_script(JS_LOOKUP["get_window_location"], "search")
@log_wrapper
@keyword
def generate_firefox_profile(
self: "SeleniumTestability",
preferences: OptionalDictType = None,
accept_untrusted_certs: bool = False,
proxy: OptionalStrType = None,
) -> FirefoxProfile:
"""
Generates a firefox profile that sets up few required preferences for SeleniumTestability to support all necessary features.
Parameters:
- ``preferences`` - firefox profile preferences in dictionary format.
- ``accept_untrusted_certs`` should we accept untrusted/self-signed certificates.
- ``proxy`` proxy options
Note: If you opt out using this keyword, you are not able to get logs with ``Get Logs`` and Firefox.
"""
profile = FirefoxProfile()
if preferences:
for key, value in preferences.items(): # type: ignore
profile.set_preference(key, value)
profile.set_preference("devtools.console.stdout.content", True)
profile.accept_untrusted_certs = accept_untrusted_certs
if proxy:
profile.set_proxy(proxy)
profile.update_preferences()
return profile
@log_wrapper
@keyword
def get_storage_length(self: "SeleniumTestability", storage_type: str = "localStorage") -> int:
"""
Returns a length (# of items) in specified storage.
Parameters:
- ``storage_type`` name of the storage. Valid options: localStorage, sessionStorage
"""
return self.ctx.driver.execute_script(JS_LOOKUP["storage_length"], storage_type)
@log_wrapper
@keyword
def get_storage_keys(self: "SeleniumTestability", storage_type: str = "localStorage") -> StringArray:
"""
Returns a list of keys in specified storage.
Parameters:
- ``storage_type`` name of the storage. Valid options: localStorage, sessionStorage
"""
return self.ctx.driver.execute_script(JS_LOOKUP["storage_keys"], storage_type)
@log_wrapper
@keyword
def get_storage_item(self: "SeleniumTestability", key: str, storage_type: str = "localStorage") -> StorageType:
"""
Returns value of ``key`` from specified storage.
Parameters:
- ``key`` name of the storage key
- ``storage_type`` name of the storage. Valid options: localStorage, sessionStorage
"""
matcher = r"^{.*}$"
storage_item = self.ctx.driver.execute_script(JS_LOOKUP["storage_getitem"], storage_type, key)
if isinstance(storage_item, str) and re.match(matcher, storage_item):
storage_item = json.loads(storage_item)
return storage_item
@log_wrapper
@keyword
def set_storage_item(self: "SeleniumTestability", key: str, value: StorageType, storage_type: str = "localStorage") -> None:
"""
Sets a value to the key in specified storage_type
Parameters:
- ``key`` name of the key
- ``value`` value that should be set to key
- ``storage_type`` name of the storage. Valid options: localStorage, sessionStorage
"""
if isinstance(value, dict):
value = json.dumps(value)
self.ctx.driver.execute_script(JS_LOOKUP["storage_setitem"], storage_type, key, value)
@log_wrapper
@keyword
def clear_storage(self: "SeleniumTestability", storage_type: str = "localStorage") -> None:
"""
Clears all values in specified storage.
Parameters:
- ``storage_type`` name of the storage. Valid options: localStorage, sessionStorage
"""
self.ctx.driver.execute_script(JS_LOOKUP["storage_clear"], storage_type)
@log_wrapper
@keyword
def remove_storage_item(self: "SeleniumTestability", key: str, storage_type: str = "localStorage") -> None:
"""
Removes a key and its value from specified storage
Parameters:
- ``key`` name of the key
- ``storage_type`` name of the storage. Valid options: localStorage, sessionStorage
"""
return self.ctx.driver.execute_script(JS_LOOKUP["storage_removeitem"], storage_type, key)
@log_wrapper
@keyword
def right_click_element(self: "SeleniumTestability", locator: LocatorType) -> None:
""" Sends right-click event to element identified by ``locator``.
This keyword is alias for `Open Context Menu` keyword.
"""
self.el.open_context_menu(locator) | /robotframework-seleniumtestability-2.1.0.tar.gz/robotframework-seleniumtestability-2.1.0/src/SeleniumTestability/plugin.py | 0.790166 | 0.289133 | plugin.py | pypi |
from SeleniumLibrary import SeleniumLibrary
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.events import AbstractEventListener
from robot.libraries.BuiltIn import BuiltIn
from .logger import get_logger, kwargstr, argstr
import wrapt
from typing import Callable, Any
@wrapt.decorator
def log_wrapper(wrapped: Callable, instance: "TestabilityListener", args: Any, kwargs: Any) -> None:
instance.logger.debug("{}({}) [ENTERING]".format(wrapped.__name__, ", ".join([argstr(args), kwargstr(kwargs)])))
wrapped(*args, **kwargs)
instance.logger.debug("{}() [LEAVING]".format(wrapped.__name__))
def auto_injection(func: Callable) -> Callable:
def injection_wrapper(*args: Any, **kwargs: Any) -> Any:
this = args[0]
if this.automatic_injection:
this.testability.instrument_browser()
return func(*args, **kwargs)
return injection_wrapper
class TestabilityListener(AbstractEventListener):
@property
def automatic_wait(self: "TestabilityListener") -> bool:
return self.testability.testability_settings["automatic_wait"]
@property
def automatic_injection(self: "TestabilityListener") -> bool:
return self.testability.testability_settings["automatic_injection"]
def __init__(self: "TestabilityListener") -> None:
AbstractEventListener.__init__(self)
self.testability = self._get_sl()
self.logger = get_logger("TestabilityListener")
self.logger.debug("__init__()")
def _get_sl(self: "TestabilityListener") -> SeleniumLibrary:
libraries = BuiltIn().get_library_instance(all=True)
for library in libraries:
if isinstance(libraries[library], SeleniumLibrary):
return libraries[library]
return None
@log_wrapper
def before_navigate_to(self: "TestabilityListener", url: str, driver: WebDriver) -> None:
pass
@log_wrapper
@auto_injection
def after_navigate_to(self: "TestabilityListener", url: str, driver: WebDriver) -> None:
pass
@log_wrapper
@auto_injection
def before_click(self: "TestabilityListener", element: WebElement, driver: WebDriver) -> None:
pass
@log_wrapper
def after_click(self: "TestabilityListener", element: WebElement, driver: WebDriver) -> None:
pass
@log_wrapper
@auto_injection
def before_change_value_of(self: "TestabilityListener", element: WebElement, driver: WebDriver) -> None:
pass
@log_wrapper
def after_change_value_of(self: "TestabilityListener", element: WebElement, driver: WebDriver) -> None:
pass
@log_wrapper
def after_close(self: "TestabilityListener", driver: WebDriver) -> None:
pass
@log_wrapper
def after_execute_script(self: "TestabilityListener", script: str, driver: WebDriver) -> None:
pass
@log_wrapper
def after_find(self: "TestabilityListener", by: str, value: str, driver: WebDriver) -> None:
pass
@log_wrapper
@auto_injection
def after_navigate_back(self: "TestabilityListener", driver: WebDriver) -> None:
pass
@log_wrapper
@auto_injection
def after_navigate_forward(self: "TestabilityListener", driver: WebDriver) -> None:
pass
@log_wrapper
def after_quit(self: "TestabilityListener", driver: WebDriver) -> None:
pass
@log_wrapper
def before_close(self: "TestabilityListener", driver: WebDriver) -> None:
pass
@log_wrapper
def before_execute_script(self: "TestabilityListener", script: str, driver: WebDriver) -> None:
pass
@log_wrapper
@auto_injection
def before_find(self: "TestabilityListener", by: str, value: str, driver: WebDriver) -> None:
if self.automatic_wait:
self.testability.wait_for_testability_ready()
@log_wrapper
def before_navigate_back(self: "TestabilityListener", driver: WebDriver) -> None:
pass
@log_wrapper
def before_navigate_forward(self: "TestabilityListener", driver: WebDriver) -> None:
pass
@log_wrapper
def before_quit(self: "TestabilityListener", driver: WebDriver) -> None:
pass
@log_wrapper
def on_exception(self: "TestabilityListener", exception: Exception, driver: WebDriver) -> None:
self.logger.warn(str(exception)) | /robotframework-seleniumtestability-2.1.0.tar.gz/robotframework-seleniumtestability-2.1.0/src/SeleniumTestability/listener.py | 0.766337 | 0.223409 | listener.py | pypi |
JS_LOOKUP = {
"wait_for_testability": """
var readyCallback = arguments[arguments.length - 1];
window.testability.when.ready(function() {
readyCallback(true)
});
""",
"wait_for_document_ready": """
var readyCallback = arguments[arguments.length - 1];
var checkReadyState=function() {
document.readyState !== 'complete' ? setTimeout(checkReadyState, 50) : readyCallback(true);
};
checkReadyState();
""",
"is_installed": """
return window.seleniumtestabilityready !== undefined && window.seleniumtestabilityready == true
""",
"navigator": """
return navigator[arguments[0]]
""",
"dragdrop": """
window.simulateDragDrop(arguments[0], arguments[1]);
""",
"scroll_to_bottom": """
window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: arguments[0]})
""",
"scroll_to_top": """
window.scrollTo({ left: 0, top: 0, behavior: arguments[0]})
""",
"get_style_display": """
return arguments[0].style.display
""",
"set_style_display": """
arguments[0].style.display = arguments[1]
""",
"get_rect": """
return arguments[0].getBoundingClientRect()
""",
"get_element_at": """
return document.elementFromPoint(arguments[0], arguments[1])
""",
"set_element_attribute": """
arguments[0].setAttribute(arguments[1], arguments[2])
""",
"get_window_location": """
return window.location[arguments[0]]
""",
"storage_getitem": """
return window[arguments[0]].getItem(arguments[1])
""",
"storage_setitem": """
window[arguments[0]].setItem(arguments[1], arguments[2])
""",
"storage_length": """
return window[arguments[0]].length
""",
"storage_removeitem": """
return window[arguments[0]].removeItem(arguments[1])
""",
"storage_clear": """
return window[arguments[0]].clear()
""",
"storage_keys": """
return Object.keys(window[arguments[0]])
""",
"testability_config": """
window.testability_config = arguments[0]
""",
"drag_and_drop_file": """
var target = arguments[0],
parentElement = target.parentElement
offsetX = arguments[1],
offsetY = arguments[2],
document = target.ownerDocument || document,
window = document.defaultView || window;
var input = document.createElement('INPUT');
input.type = 'file';
input.onchange = function () {
var rect = target.getBoundingClientRect(),
x = rect.left + (offsetX || (rect.width >> 1)),
y = rect.top + (offsetY || (rect.height >> 1)),
dataTransfer = { files: this.files };
['dragenter', 'dragover', 'drop'].forEach(function (name) {
var evt = document.createEvent('MouseEvent');
evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);
evt.dataTransfer = dataTransfer;
target.dispatchEvent(evt);
});
setTimeout(function () { parentElement.removeChild(input); }, 25);
};
parentElement.appendChild(input);
return input;
""",
} | /robotframework-seleniumtestability-2.1.0.tar.gz/robotframework-seleniumtestability-2.1.0/src/SeleniumTestability/javascript.py | 0.432063 | 0.363986 | javascript.py | pypi |
import json
from seleniumwire import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
from robot.api import logger
from .version import VERSION
class SeleniumWireLibrary():
"""
| = Repo = | = URL = |
| SeleniumWire | https://github.com/wkeeling/selenium-wire |
Used to capture browser network traffic in robotframework uses seleniumwire internally
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = VERSION
def __init__(self):
self.driver = None
self.requests = None
@keyword
def open_browser(self, options=None):
"""
Launches chrome browser using selenium wire
| = Attribute = | = Description = |
| options | seleniumwire_options passed as dictionary. |
Supported options - https://github.com/wkeeling/selenium-wire?ref=https://githubhelp.com#all-options |
Example:
| *** Variables *** | | |
| &{options} | disable_encoding=${True} | |
| | | |
| *** Test Cases *** | | |
| Launch SeleniumWire Browser | |
| | Launch Web Browser | options=${options} |
"""
self.driver = webdriver.Chrome(seleniumwire_options=options)
self.driver.maximize_window()
@keyword
def go_to(self, url):
"""
Navigates to mentioned url in launched chrome browser
| = Attribute = | = Description = |
| url | url to be navigated |
"""
self.driver.get(url)
@keyword
def close_all_browsers(self):
"""
Close all browsers. Uses `driver.quit()` internally
"""
self.driver.quit()
@keyword
def close_browser(self):
"""
Close current browser.
"""
self.driver.close()
@keyword
def get_all_requests(self):
"""
Return list of captured requests in chronological order.
"""
self.requests = self.driver.requests
return self.requests
@keyword
def get_last_request(self):
"""
Return the most recently captured request.
"""
return self.driver.last_request
@keyword
def get_request_by_index(self, index):
"""
Return request by index
| = Attribute = | = Description = |
| index | index of request |
"""
return self.requests[int(index)]
@keyword
def wait_for_request(self, pattern, timeout=10):
"""
Keyword will wait until it sees a request matching a `pattern`
- `pattern` can be a simple substring or a regular expression.
- Keyword doesnt make a new request, it wait for previous request
- A `TimeoutException` is raised if no match is found within the timeout period
| = Attribute = | = Description = |
| pattern | substring or regular expression |
| timeout | Wait time before raising timeout exception. Default value is 10 |
Example:
| Wait For Request | /api/products/12345/ |
"""
self.driver.wait_for_request(pattern, timeout=timeout)
@keyword
def clear_requests(self):
"""
Clear all captured requests
"""
del self.driver.requests
@keyword
def set_request_scope(self, scope=[]):
"""
Captures network which matches regular expression. Accepts list of regular expressions.
| = Attribute = | = Description = |
| scope[] | list of regular expression |
Example:
| Set Request Scope | ['.*robot.*', '.*google.*'] |
Changes reflects in new requests made after this keyword
"""
del self.driver.requests
self.driver.scopes = scope
@keyword
def har_archive(self, file):
"""
Save HAR file to specified location
| = Attribute = | = Description = |
| file | file name. ex: `test.har` |
"""
result = self.driver.har
with open(file, 'w') as f:
f.write(result)
@keyword
def get_request_by_name(self, partialText, type="request"):
"""
Return request result matching with `partialText`.
| = Attribute = | = Description = |
| partialText | partial url/text which contains `request.url` context |
| type | Type can be `request` or `response`. Default is `request` |
Note: This keyword doesnt make any new requests. Should be used after `Get All Requests` keywords
"""
result_dict = []
for request in self.requests:
if partialText in request.url:
if type == "response":
if request.response:
result_dict = {
"RequestURL" : request.url,
"StatusCode" : request.response.status_code,
"Reason" : request.response.reason,
"Header" : request.response.headers,
"Host" : request.headers['Host'],
"Date" : request.response.date,
"Body" : request.response.body
}
else:
result_dict = {
"Method" : request.method,
"RequestURL" : request.url,
"Path" : request.path,
"QueryString" : request.querystring,
"Params" : request.params,
"Headers" : request.headers,
"Host" : request.headers['Host'],
"Date" : request.date,
"Body" : request.body,
"Response" : request.response,
}
break
return result_dict
@keyword
def log_request_object(self, type="request"):
"""
Log all requests.
| = Attribute = | = Description = |
| type | Type can be `request` or `response`. Default is `request` |
Note: This keyword doesnt make any new requests. Should be used after `Get All Requests` keywords
"""
result_dict = []
for request in self.requests:
if type == "response":
if request.response:
result_dict = {
"RequestURL" : request.url,
"StatusCode" : request.response.status_code,
"Reason" : request.response.reason,
"Header" : request.response.headers,
"Host" : request.headers['Host'],
"Date" : request.response.date,
"Body" : request.response.body
}
else:
result_dict = {
"Method" : request.method,
"RequestURL" : request.url,
"Path" : request.path,
"QueryString" : request.querystring,
"Params" : request.params,
"Headers" : request.headers,
"Host" : request.headers['Host'],
"Date" : request.date,
"Body" : request.body,
"Response" : request.response,
}
logger.info(result_dict)
@keyword
def click_element(self, locator):
"""
click on webelement
| = Attribute = | = Description = |
| locator | Webelement to click. |
- Locator should be like <startagie>:<locator>
- Uses `driver.find(By.<stratagies>, <locator>)` method internally.
- Refer - https://selenium-python.readthedocs.io/locating-elements.html
Example:
| Click Element | xpath://div[text(),'robot'] |
| Click Element | id:RobotID |
| Click Element | name:Robot |
"""
locs = locator.split(':', 1)
webelement = self.driver.find_element(locs[0].lower(), locs[-1])
webelement.click()
@keyword
def input_text(self, locator, value):
"""
Input text into textbox
| = Attribute = | = Description = |
| locator | textbox locator |
| value | value to be enetered in textbox |
Example:
| Input Text | xpath://div[text(),'robot'] | Demo |
| Input Text | id:RobotID | Demo |
"""
locs = locator.split(':', 1)
webelement = self.driver.find_element(locs[0].lower(), locs[-1])
webelement.send_keys(value)
@keyword
def select_from_list(self, locator, type, value):
"""
Select value from drop down list
| = Attribute = | = Description = |
| locator | drop down locator |
| type | select value based on type. Supported type `index`, `value`, `text` |
| value | value to be selected |
Example:
| Select From List | xpath://div[text(),'robot'] | index | 0 |
| Select From List | id:RobotID | text | Robot |
"""
locs = locator.split(':', 1)
select = Select(self.driver.find_element(locs[0].lower(), locs[-1]))
if type == "index":
select.select_by_index(value)
elif type == "text":
select.select_by_visible_text(value)
elif type == "value":
select.select_by_value(value)
else:
pass
@keyword
def wait_until_page_contains_element(self, locator, timeout=30):
"""
Wait until page contains element.
| = Attribute = | = Description = |
| locator | wait for specific element to be loaded in page |
| timeout | Wait time before throwing exception |
"""
locs = locator.split(':', 1)
element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located((locs[0].lower(), locs[-1])))
@keyword
def wait_until_element_is_visible(self, locator, timeout=30):
"""
Wait until element is visible in page.
| = Attribute = | = Description = |
| locator | wait for specific element to be visible in page |
| timeout | Wait time before throwing exception |
"""
locs = locator.split(':', 1)
element = WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located((locs[0].lower(), locs[-1])))
@keyword
def wait_until_element_is_not_visible(self, locator, timeout=30):
"""
Wait until element is not visible in page.
| = Attribute = | = Description = |
| locator | wait for specific element to be not visible in page |
| timeout | Wait time before throwing exception |
"""
locs = locator.split(':', 1)
element = WebDriverWait(self.driver, timeout).until(EC.invisibility_of_element_located((locs[0].lower(), locs[-1])))
@keyword
def switch_to_window(self, index=0):
"""
Switches to browser window by name
| = Attribute = | = Description = |
| index | index of window |
Example:
| Switch To Window | 1 |
"""
self.driver.switch_to_window(self.driver.window_handles[int(index)])
@keyword
def switch_to_iframe(self, locator):
"""
Switches to iframe
| = Attribute = | = Description = |
| locator | iframe locator |
Example:
| Switch To Frame | xpath://div[@id='iframe'] |
"""
self.driver.switch_to_frame(self.driver.find_element(locs[0].lower(), locs[-1]))
@keyword
def exit_iframe(self):
"""
Exits iframe
"""
self.driver.switch_to_default_content(0) | /robotframework-seleniumwire-0.1.1.tar.gz/robotframework-seleniumwire-0.1.1/src/SeleniumWireLibrary/wire.py | 0.724675 | 0.188399 | wire.py | pypi |
from collections import defaultdict
from robot.api.parsing import ModelVisitor
class PathNode:
def __init__(self, name):
self.name = name
class ComplexityChecker(ModelVisitor):
def __init__(self):
self.nodes = defaultdict(list)
self.graph = None
self.tail = None
def connect(self, node1, node2):
self.nodes[node1].append(node2)
self.nodes[node2] = []
def complexity(self):
"""mccabe V-E+2"""
edges = sum(len(n) for n in self.nodes.values())
nodes = len(self.nodes)
return edges - nodes + 2
def append_path_node(self, name):
if not self.tail:
return
path_node = PathNode(name)
self.connect(self.tail, path_node)
self.tail = path_node
return path_node
def visit_Keyword(self, node): # noqa
name = f"{node.name}:{node.lineno}:{node.col_offset}"
path_node = PathNode(name)
self.tail = path_node
self.generic_visit(node)
def visit_KeywordCall(self, node): # noqa
name = f"KeywordCall {node.lineno}"
self.append_path_node(name)
def visit_For(self, node): # noqa
name = f"FOR {node.lineno}"
path_node = self.append_path_node(name)
self._parse_subgraph(node, path_node)
def visit_If(self, node): # noqa
name = f"IF {node.lineno}"
path_node = self.append_path_node(name)
self._parse_subgraph(node, path_node)
def _parse_subgraph(self, node, path_node):
loose_ends = []
self.tail = path_node
self.generic_visit(node)
loose_ends.append(self.tail)
if getattr(node, "orelse", False):
self.tail = path_node
self.generic_visit(node.orelse)
loose_ends.append(self.tail)
else:
loose_ends.append(path_node)
if path_node:
bottom = PathNode("")
for loose_end in loose_ends:
self.connect(loose_end, bottom)
self.tail = bottom | /robotframework-sherlock-0.3.0.tar.gz/robotframework-sherlock-0.3.0/sherlock/complexity.py | 0.719581 | 0.248711 | complexity.py | pypi |
import difflib
import re
from collections import defaultdict
class RecommendationFinder:
def find_similar(self, name, candidates):
norm_name = self.normalize(name)
norm_cand = self.get_normalized_candidates(candidates)
matches = []
for norm in norm_name:
matches += self.find(norm, norm_cand.keys())
if not matches:
return ""
matches = self.get_original_candidates(matches, norm_cand)
suggestion = "Did you mean:\n"
suggestion += "\n".join(f" {match}" for match in matches)
return suggestion
def find(self, name, candidates, max_matches=5):
"""Return a list of close matches to `name` from `candidates`."""
if not name or not candidates:
return []
cutoff = self._calculate_cutoff(name)
return difflib.get_close_matches(name, candidates, n=max_matches, cutoff=cutoff)
@staticmethod
def _calculate_cutoff(string, min_cutoff=0.5, max_cutoff=0.85, step=0.03):
"""The longer the string the bigger required cutoff."""
cutoff = min_cutoff + len(string) * step
return min(cutoff, max_cutoff)
@staticmethod
def normalize(name):
"""
Return tuple where first element is string created from sorted words in name,
and second element is name without `-` and `_`.
"""
norm = re.split("[-_ ]+", name)
return " ".join(sorted(norm)), name.replace("-", "").replace("_", "")
@staticmethod
def get_original_candidates(candidates, norm_candidates):
"""Map found normalized candidates to unique original candidates."""
return sorted(list(set(c for cand in candidates for c in norm_candidates[cand])))
def get_normalized_candidates(self, candidates):
"""
Thanks for normalizing and sorting we can find cases like this-is, thisis, this-is1 instead of is-this.
Normalized names form dictionary that point to original names - we're using list because several names can
have one common normalized name.
Different normalization methods try to imitate possible mistakes done when typing name - different order,
missing `-` etc.
"""
norm = defaultdict(list)
for cand in candidates:
for norm_cand in self.normalize(cand):
norm[norm_cand].append(cand)
return norm
class SherlockFatalError(ValueError):
pass
class ConfigGeneralError(SherlockFatalError):
pass
class InvalidReportName(ConfigGeneralError):
def __init__(self, report, reports):
report_names = sorted(list(reports.keys()))
msg = (
f"Provided report '{report}' does not exist. "
f"Use comma separated list of values from: {','.join(report_names)}. "
)
similar = RecommendationFinder().find_similar(report, report_names)
msg += similar
super().__init__(msg) | /robotframework-sherlock-0.3.0.tar.gz/robotframework-sherlock-0.3.0/sherlock/exceptions.py | 0.804713 | 0.28262 | exceptions.py | pypi |
from rich.console import Console, Group
from rich.markup import escape
from rich.table import Table
from rich.text import Text
from rich.tree import Tree
import sherlock.report
from sherlock.model import DIRECTORY_TYPE, KeywordTimings
def timings_to_table(timings):
timings_table = Table(title="Elapsed time")
for col in ["Total elapsed [s]", "Shortest execution [s]", "Longest execution [s]", "Average execution [s]"]:
timings_table.add_column(col)
timings_table.add_row(timings.total, timings.min, timings.max, timings.avg)
return timings_table
def keywords_to_table(keywords):
has_complexity = any(kw.complexity for kw in keywords)
table = Table(title="Keywords:")
table.add_column("Name", justify="left", no_wrap=True)
table.add_column("Executions")
if has_complexity:
table.add_column("Complexity")
table.add_column("Average time [s]")
table.add_column("Total time [s]")
for kw in keywords:
name = kw.name if kw.used else f"[cyan]{kw.name}"
row = [name, str(kw.used)]
if has_complexity:
row.append(str(kw.complexity))
if kw.used:
row.extend([str(kw.timings.avg), str(kw.timings.total)])
else:
row.extend(["", ""])
table.add_row(*row)
return table
def log_directory(directory, tree):
for resource in directory.children:
if resource.type == DIRECTORY_TYPE:
style = "dim" if resource.name.startswith("__") else ""
branch = tree.add(
f"[bold magenta][link file://{resource.name}]{escape(resource.name)}",
style=style,
guide_style=style,
)
log_directory(resource, branch)
else:
text = Text(str(resource))
keywords = [kw for kw in resource.keywords]
if keywords:
timings = sum((kw.timings for kw in keywords if kw.used), KeywordTimings())
timings_table = timings_to_table(timings)
keywords_table = keywords_to_table(keywords)
tree.add(Group(text, timings_table, keywords_table))
else:
tree.add(text)
class PrintReport(sherlock.report.Report):
name: str = "print"
description: str = "Simple printed report"
def get_report(self, directory, tree_name, path_root):
tree = Tree(
f"[link file://{directory}]{directory}",
guide_style="bold bright_blue",
)
log_directory(directory, tree)
console = Console()
console.print()
console.print(tree) | /robotframework-sherlock-0.3.0.tar.gz/robotframework-sherlock-0.3.0/sherlock/report/print.py | 0.436382 | 0.215145 | print.py | pypi |
import importlib.util
import inspect
from pathlib import Path
import sherlock.exceptions
class Report:
def get_report(self, tree, tree_name, path_root):
raise NotImplementedError
def _import_module_from_file(file_path):
"""Import Python file as module.
importlib does not support importing Python files directly, and we need to create module specification first."""
spec = importlib.util.spec_from_file_location(file_path.stem, file_path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def modules_from_paths(paths, recursive=True):
for path in paths:
path_object = Path(path)
if path_object.is_dir():
if not recursive or path_object.name in {".git", "__pycache__"}:
continue
yield from modules_from_paths([file for file in path_object.iterdir()])
elif path_object.suffix == ".py":
yield _import_module_from_file(path_object)
def load_reports():
"""
Load all valid reports.
Report is considered valid if it inherits from `Report` class
and contains both `name` and `description` attributes.
"""
reports = {}
for module in modules_from_paths([Path(__file__).parent]):
classes = inspect.getmembers(module, inspect.isclass)
for report_class in classes:
if not issubclass(report_class[1], Report):
continue
report = report_class[1]()
if not hasattr(report, "name") or not hasattr(report, "description"):
continue
reports[report.name] = report
return reports
def get_reports(configured_reports):
"""
Returns dictionary with list of valid, enabled reports (listed in `configured_reports` set of str).
"""
reports = load_reports()
enabled_reports = {}
for report in configured_reports:
if report not in reports:
raise sherlock.exceptions.InvalidReportName(report, reports)
elif report not in enabled_reports:
enabled_reports[report] = reports[report]
return enabled_reports | /robotframework-sherlock-0.3.0.tar.gz/robotframework-sherlock-0.3.0/sherlock/report/__init__.py | 0.574992 | 0.194291 | __init__.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.