code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import fnmatch
from robot.utils import asserts
import BuiltIn
BUILTIN = BuiltIn.BuiltIn()
class DeprecatedBuiltIn:
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
integer = BUILTIN.convert_to_integer
float = BUILTIN.convert_to_number
string = BUILTIN.convert_to_string
boolean = BUILTIN.convert_to_boolean
list = BUILTIN.create_list
equal = equals = fail_unless_equal = BUILTIN.should_be_equal
not_equal = not_equals = fail_if_equal = BUILTIN.should_not_be_equal
is_true = fail_unless = BUILTIN.should_be_true
is_false = fail_if = BUILTIN.should_not_be_true
fail_if_ints_equal = ints_not_equal = BUILTIN.should_not_be_equal_as_integers
ints_equal = fail_unless_ints_equal = BUILTIN.should_be_equal_as_integers
floats_not_equal = fail_if_floats_equal = BUILTIN.should_not_be_equal_as_numbers
floats_equal = fail_unless_floats_equal = BUILTIN.should_be_equal_as_numbers
does_not_start = fail_if_starts = BUILTIN.should_not_start_with
starts = fail_unless_starts = BUILTIN.should_start_with
does_not_end = fail_if_ends = BUILTIN.should_not_end_with
ends = fail_unless_ends = BUILTIN.should_end_with
does_not_contain = fail_if_contains = BUILTIN.should_not_contain
contains = fail_unless_contains = BUILTIN.should_contain
does_not_match = fail_if_matches = BUILTIN.should_not_match
matches = fail_unless_matches = BUILTIN.should_match
does_not_match_regexp = fail_if_regexp_matches = BUILTIN.should_not_match_regexp
matches_regexp = fail_unless_regexp_matches = BUILTIN.should_match_regexp
noop = BUILTIN.no_operation
set_ = BUILTIN.set_variable
message = BUILTIN.comment
variable_exists = fail_unless_variable_exists = BUILTIN.variable_should_exist
variable_does_not_exist = fail_if_variable_exists = BUILTIN.variable_should_not_exist
def error(self, msg=None):
"""Errors the test immediately with the given message."""
asserts.error(msg)
def grep(self, text, pattern, pattern_type='literal string'):
lines = self._filter_lines(text.splitlines(), pattern, pattern_type)
return '\n'.join(lines)
def _filter_lines(self, lines, pattern, ptype):
ptype = ptype.lower().replace(' ','').replace('-','')
if not pattern:
filtr = lambda line: True
elif 'simple' in ptype or 'glob' in ptype:
if 'caseinsensitive' in ptype:
pattern = pattern.lower()
filtr = lambda line: fnmatch.fnmatchcase(line.lower(), pattern)
else:
filtr = lambda line: fnmatch.fnmatchcase(line, pattern)
elif 'regularexpression' in ptype or 'regexp' in ptype:
pattern = re.compile(pattern)
filtr = lambda line: pattern.search(line)
elif 'caseinsensitive' in ptype:
pattern = pattern.lower()
filtr = lambda line: pattern in line.lower()
else:
filtr = lambda line: pattern in line
return [ line for line in lines if filtr(line) ]
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from fnmatch import fnmatchcase
from random import randint
from string import ascii_lowercase, ascii_uppercase, digits
from robot.version import get_version
class String:
"""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 the BuiltIn library can also be used with
strings:
- `Catenate`
- `Get Length`
- `Length Should Be`
- `Should (Not) Match (Regexp)`
- `Should (Not) Be Empty`
- `Should (Not) Be Equal (As Strings/Integers/Numbers)`
- `Should (Not) Contain`
- `Should (Not) Start With`
- `Should (Not) End With`
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = get_version()
def get_line_count(self, string):
"""Returns and logs the number of lines in the given `string`."""
count = len(string.splitlines())
print '*INFO* %d lines' % count
return count
def split_to_lines(self, string, start=0, end=None):
"""Converts the `string` into a list of lines.
It is possible to get only a selection of lines from `start`
to `end` so that `start` index is inclusive and `end` is
exclusive. Line numbering starts from 0, and it is possible to
use negative indices to refer to lines from the end.
Lines are returned without the newlines. The number of
returned lines is automatically logged.
Examples:
| @{lines} = | Split To Lines | ${manylines} | | |
| @{ignore first} = | Split To Lines | ${manylines} | 1 | |
| @{ignore last} = | Split To Lines | ${manylines} | | -1 |
| @{5th to 10th} = | Split To Lines | ${manylines} | 4 | 10 |
| @{first two} = | Split To Lines | ${manylines} | | 1 |
| @{last two} = | Split To Lines | ${manylines} | -2 | |
Use `Get Line` if you only need to get a single line.
"""
start = self._convert_to_index(start, 'start')
end = self._convert_to_index(end, 'end')
lines = string.splitlines()[start:end]
print '*INFO* %d lines returned' % len(lines)
return lines
def get_line(self, string, line_number):
"""Returns the specified line from the given `string`.
Line numbering starts from 0 and it is possible to use
negative indices to refer to lines from the end. The line is
returned without the newline character.
Examples:
| ${first} = | Get Line | ${string} | 0 |
| ${2nd last} = | Get Line | ${string} | -2 |
"""
line_number = self._convert_to_integer(line_number, 'line_number')
return string.splitlines()[line_number]
def get_lines_containing_string(self, string, pattern, case_insensitive=False):
"""Returns lines of the given `string` that contain the `pattern`.
The `pattern` is always considered to be a normal string and a
line matches if the `pattern` is found anywhere in it. By
default the match is case-sensitive, but setting
`case_insensitive` to any value makes it case-insensitive.
Lines are returned as one string catenated back together with
newlines. Possible trailing newline is never returned. The
number of matching lines is automatically logged.
Examples:
| ${lines} = | Get Lines Containing String | ${result} | An example |
| ${ret} = | Get Lines Containing String | ${ret} | FAIL | case-insensitive |
See `Get Lines Matching Pattern` and `Get Lines Matching Regexp`
if you need more complex pattern matching.
"""
if case_insensitive:
pattern = pattern.lower()
contains = lambda line: pattern in line.lower()
else:
contains = lambda line: pattern in line
return self._get_matching_lines(string, contains)
def get_lines_matching_pattern(self, string, pattern, case_insensitive=False):
"""Returns lines of the given `string` that match the `pattern`.
The `pattern` is a _glob pattern_ where:
| * | matches everything |
| ? | matches any single character |
| [chars] | matches any character inside square brackets (e.g. '[abc]' matches either 'a', 'b' or 'c') |
| [!chars] | matches any character not inside square brackets |
A line matches only if it matches the `pattern` fully. By
default the match is case-sensitive, but setting
`case_insensitive` to any value makes it case-insensitive.
Lines are returned as one string catenated back together with
newlines. Possible trailing newline is never returned. The
number of matching lines is automatically logged.
Examples:
| ${lines} = | Get Lines Matching Pattern | ${result} | Wild???? example |
| ${ret} = | Get Lines Matching Pattern | ${ret} | FAIL: * | case-insensitive |
See `Get Lines Matching Regexp` if you need more complex
patterns and `Get Lines Containing String` if searching
literal strings is enough.
"""
if case_insensitive:
pattern = pattern.lower()
matches = lambda line: fnmatchcase(line.lower(), pattern)
else:
matches = lambda line: fnmatchcase(line, pattern)
return self._get_matching_lines(string, matches)
def get_lines_matching_regexp(self, string, pattern):
"""Returns lines of the given `string` that match the regexp `pattern`.
See `BuiltIn.Should Match Regexp` for more information about
Python regular expression syntax in general and how to use it
in Robot Framework test data in particular. A line matches
only if it matches the `pattern` fully. Notice that to make
the match case-insensitive, you need to embed case-insensitive
flag into the pattern.
Lines are returned as one string catenated back together with
newlines. Possible trailing newline is never returned. The
number of matching lines is automatically logged.
Examples:
| ${lines} = | Get Lines Matching Regexp | ${result} | Reg\\\\w{3} example |
| ${ret} = | Get Lines Matching Regexp | ${ret} | (?i)FAIL: .* |
See `Get Lines Matching Pattern` and `Get Lines Containing
String` if you do not need full regular expression powers (and
complexity).
"""
regexp = re.compile('^%s$' % pattern)
return self._get_matching_lines(string, regexp.match)
def _get_matching_lines(self, string, matches):
lines = string.splitlines()
matching = [ line for line in lines if matches(line) ]
print '*INFO* %d out of %d lines matched' % (len(matching), len(lines))
return '\n'.join(matching)
def replace_string(self, string, search_for, replace_with, count=-1):
"""Replaces `search_for` in the given `string` with `replace_with`.
`search_for` is used as a literal string. See `Replace String
Using Regexp` if more powerful pattern matching is needed.
If 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 | ${str} | Hello | Hi | |
| ${str} = | Replace String | ${str} | world | tellus | 1 |
"""
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.
Examples:
| ${str} = | Replace String Using Regexp | ${str} | (Hello|Hi) | Hei | |
| ${str} = | Replace String Using Regexp | ${str} | 20\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d | <DATE> | 2 |
"""
count = self._convert_to_integer(count, 'count')
# re.sub handles 0 and negative counts differently than string.replace
if count < 0:
count = 0
elif count == 0:
count = -1
return re.sub(pattern, replace_with, string, count)
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} | ${others} = | Split String | ${string} | - | 1 |
| ${others} | ${last} = | Split String From Right | ${string} | - | 1 |
"""
# Strings in Jython 2.2 don't have 'rsplit' methods
reversed = self.split_string(string[::-1], separator, max_split)
return [ r[::-1] for r in reversed ][::-1]
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:
| _[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 i in xrange(length) ])
def get_substring(self, string, start, end=None):
"""Returns a substring from `start` index to `end` index.
The `start` index is inclusive and `end` is exclusive.
Indexing starts from 0, and it is possible to use
negative indices to refer to characters from the end.
Examples:
| ${ignore first} = | Get Substring | ${string} | 1 | |
| ${ignore last} = | Get Substring | ${string} | | -1 |
| ${5th to 10th} = | Get Substring | ${string} | 4 | 10 |
| ${first two} = | Get Substring | ${string} | | 1 |
| ${last two} = | Get Substring | ${string} | -2 | |
"""
start = self._convert_to_index(start, 'start')
end = self._convert_to_index(end, 'end')
return string[start:end]
def should_be_string(self, item, msg=None):
"""Fails if the given `item` is not a string.
The default error message can be overridden with the optional
`msg` argument.
"""
if not isinstance(item, basestring):
if not msg:
msg = "Given item '%s' is not a string" % item
raise AssertionError(msg)
def should_not_be_string(self, item, msg=None):
"""Fails if the given `item` is a string.
The default error message can be overridden with the optional
`msg` argument.
"""
if isinstance(item, basestring):
if not msg:
msg = "Given item '%s' is a string" % item
raise AssertionError(msg)
def should_be_lowercase(self, string, msg=None):
"""Fails if the given `string` is not in lowercase.
The default error message can be overridden with the optional
`msg` argument.
For example 'string' and 'with specials!' would pass, and 'String', ''
and ' ' would fail.
See also `Should Be Uppercase` and `Should Be Titlecase`.
All these keywords were added in Robot Framework 2.1.2.
"""
if not string.islower():
raise AssertionError(msg or "'%s' is not lowercase" % string)
def should_be_uppercase(self, string, msg=None):
"""Fails if the given `string` is not in uppercase.
The default error message can be overridden with the optional
`msg` argument.
For example 'STRING' and 'WITH SPECIALS!' would pass, and 'String', ''
and ' ' would fail.
See also `Should Be Titlecase` and `Should Be Lowercase`.
All these keywords were added in Robot Framework 2.1.2.
"""
if not string.isupper():
raise AssertionError(msg or "'%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.
The default error message can be overridden with the optional
`msg` argument.
For example 'This Is Title' would pass, and 'Word In UPPER',
'Word In lower', '' and ' ' would fail.
See also `Should Be Uppercase` and `Should Be Lowercase`.
All theses keyword were added in Robot Framework 2.1.2.
"""
if not string.istitle():
raise AssertionError(msg or "'%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))
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import time
from robot.output import LOGGER, Message
from robot.errors import DataError, ExecutionFailed, ExecutionFailures
from robot import utils
from robot.utils import asserts
from robot.variables import is_var, is_list_var
from robot.running import Keyword, NAMESPACES, RUN_KW_REGISTER
from robot.running.model import ExecutionContext
from robot.version import get_version
if utils.is_jython:
from java.lang import String, Number
try:
bin # available since Python 2.6
except NameError:
def bin(integer):
if not isinstance(integer, (int, long)):
raise TypeError
if integer >= 0:
prefix = '0b'
else:
prefix = '-0b'
integer = abs(integer)
bins = []
while integer > 1:
integer, remainder = divmod(integer, 2)
bins.append(str(remainder))
bins.append(str(integer))
return prefix + ''.join(reversed(bins))
class _Converter:
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. Starting from Robot Framework 2.6 there are two
ways to convert from other bases:
1) Give base explicitly to the keyword as `base` argument.
2) 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`
and `Convert To Hex`.
"""
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, utils.get_error_message()))
def _handle_java_numbers(self, item):
if not utils.is_jython:
return item
if isinstance(item, String):
return utils.unic(item)
if isinstance(item, Number):
return item.doubleValue()
return item
def _get_base(self, item, base):
if not isinstance(item, basestring):
return item, base
item = utils.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 |
This keyword was added in Robot Framework 2.6. See also
`Convert To Integer`, `Convert To Octal` and `Convert To Hex`.
"""
return self._convert_to_bin_oct_hex(bin, item, base, prefix, length)
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 |
This keyword was added in Robot Framework 2.6. See also
`Convert To Integer`, `Convert To Binary` and `Convert To Hex`.
"""
return self._convert_to_bin_oct_hex(oct, item, base, prefix, length)
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
giving any non-empty value to the `lowercase` argument turns
the value (but not the 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 |
This keyword was added in Robot Framework 2.6. See also
`Convert To Integer`, `Convert To Binary` and `Convert To Octal`.
"""
return self._convert_to_bin_oct_hex(hex, item, base, prefix, length,
lowercase)
def _convert_to_bin_oct_hex(self, method, item, base, prefix, length,
lowercase=False):
self._log_types(item)
ret = method(self._convert_to_integer(item, base)).upper()
prefix = prefix or ''
if ret[0] == '-':
prefix = '-' + prefix
ret = ret[1:]
if len(ret) > 1: # oct(0) -> '0' (i.e. has no prefix)
prefix_length = {bin: 2, oct: 1, hex: 2}[method]
ret = ret[prefix_length:]
if length:
ret = ret.rjust(self._convert_to_integer(length), '0')
if lowercase:
ret = ret.lower()
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. The support for precision was added in
Robot Framework 2.6.
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,
this floating point arithmetic tutorial:
http://docs.python.org/tutorial/floatingpoint.html
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:
number = round(number, self._convert_to_integer(precision))
return number
def _convert_to_number_without_precision(self, item):
try:
if utils.is_jython:
item = self._handle_java_numbers(item)
return float(item)
except:
error = utils.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.
Uses '__unicode__' or '__str__' method with Python objects and
'toString' with Java objects.
"""
self._log_types(item)
return self._convert_to_string(item)
def _convert_to_string(self, item):
return utils.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 truth value using Python's 'bool' method.
For more information about truth values, see
http://docs.python.org/lib/truth.html.
"""
self._log_types(item)
if isinstance(item, basestring):
if utils.eq(item, 'True'):
return True
if utils.eq(item, 'False'):
return False
return bool(item)
def create_list(self, *items):
"""Returns a list containing given items.
The returned list can be assigned both to ${scalar} and @{list}
variables. The earlier can be used e.g. with Java keywords expecting
an array as an argument.
Examples:
| @{list} = | Create List | a | b | c |
| ${scalar} = | Create List | a | b | c |
| ${ints} = | Create List | ${1} | ${2} | ${3} |
"""
return list(items)
class _Verify:
def fail(self, msg=None):
"""Fails the test immediately with the given (optional) message.
See `Fatal Error` if you need to stop the whole test execution.
"""
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 exit_for_loop(self):
"""Immediately stops executing the enclosing for loop.
This keyword can be used directly in a for loop or in a keyword that
the for loop uses. In both cases the test execution continues after
the for loop. If executed outside of a for loop, the test fails.
Example:
| :FOR | ${var} | IN | @{SOME LIST} |
| | Run Keyword If | '${var}' == 'EXIT' | Exit For Loop |
| | Do Something | ${var} |
New in Robot Framework 2.5.2.
"""
# Error message is shown only if there is no enclosing for loop
error = AssertionError('Exit for loop without enclosing for loop.')
error.ROBOT_EXIT_FOR_LOOP = 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 not msg:
msg = "'%s' should not be true" % condition
asserts.fail_if(self._is_true(condition), msg)
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 using the built-in 'eval' function and the keyword
status is decided based on the result. If a non-string item is given,
the status is got directly from its truth value as explained at
http://docs.python.org/lib/truth.html.
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 |
"""
if not msg:
msg = "'%s' should be true" % condition
asserts.fail_unless(self._is_true(condition), msg)
def should_be_equal(self, first, second, msg=None, values=True):
"""Fails if the given objects are unequal.
- If `msg` is not given, the error message is 'first != second'.
- If `msg` is given and `values` is either Boolean False or the
string 'False' or 'No Values', the error message is simply `msg`.
- Otherwise the error message is '`msg`: `first` != `second`'.
"""
self._log_types(first, second)
self._should_be_equal(first, second, msg, values)
def _should_be_equal(self, first, second, msg, values):
asserts.fail_unless_equal(first, second, msg,
self._include_values(values))
def _log_types(self, *args):
msg = ["Argument types are:"] + [str(type(a)) for a in args]
self.log('\n'.join(msg))
def _include_values(self, values):
if isinstance(values, basestring):
return values.lower() not in ['no values', 'false']
return bool(values)
def should_not_be_equal(self, first, second, msg=None, values=True):
"""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`.
"""
self._log_types(first, second)
self._should_not_be_equal(first, second, msg, values)
def _should_not_be_equal(self, first, second, msg, values):
asserts.fail_if_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(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(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`. The support for giving precision was added in
Robot Framework 2.6, in earlier versions it was hard-coded to 6.
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(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`. The support for giving precision was added in
Robot Framework 2.6, in earlier versions it was hard-coded to 6.
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 this great article:
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
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(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):
"""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`.
"""
self._log_types(first, second)
first, second = [self._convert_to_string(i) for i in first, second]
self._should_not_be_equal(first, second, msg, values)
def should_be_equal_as_strings(self, first, second, msg=None, values=True):
"""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` and `values`.
"""
self._log_types(first, second)
first, second = [self._convert_to_string(i) for i in first, second]
self._should_be_equal(first, second, msg, values)
def should_not_start_with(self, str1, str2, msg=None, values=True):
"""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`.
"""
msg = self._get_string_msg(str1, str2, msg, values, 'starts with')
asserts.fail_if(str1.startswith(str2), msg)
def should_start_with(self, str1, str2, msg=None, values=True):
"""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`.
"""
msg = self._get_string_msg(str1, str2, msg, values, 'does not start with')
asserts.fail_unless(str1.startswith(str2), msg)
def should_not_end_with(self, str1, str2, msg=None, values=True):
"""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`.
"""
msg = self._get_string_msg(str1, str2, msg, values, 'ends with')
asserts.fail_if(str1.endswith(str2), msg)
def should_end_with(self, str1, str2, msg=None, values=True):
"""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`.
"""
msg = self._get_string_msg(str1, str2, msg, values, 'does not end with')
asserts.fail_unless(str1.endswith(str2), msg)
def should_not_contain(self, item1, item2, msg=None, values=True):
"""Fails if `item1` contains `item2` one or more times.
Works with strings, lists, and anything that supports Python's 'in'
keyword. See `Should Be Equal` for an explanation on how to override
the default error message with `msg` and `values`.
Examples:
| Should Not Contain | ${output} | FAILED |
| Should Not Contain | ${some_list} | value |
"""
msg = self._get_string_msg(item1, item2, msg, values, 'contains')
asserts.fail_if(item2 in item1, msg)
def should_contain(self, item1, item2, msg=None, values=True):
"""Fails if `item1` does not contain `item2` one or more times.
Works with strings, lists, and anything that supports Python's 'in'
keyword. See `Should Be Equal` for an explanation on how to override
the default error message with `msg` and `values`.
Examples:
| Should Contain | ${output} | PASS |
| Should Contain | ${some_list} | value |
"""
msg = self._get_string_msg(item1, item2, msg, values, 'does not contain')
asserts.fail_unless(item2 in item1, msg)
def should_contain_x_times(self, item1, item2, count, msg=None):
"""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.
Examples:
| Should Contain X Times | ${output} | hello | 2 |
| Should Contain X Times | ${some list} | value | 3 |
"""
if not msg:
msg = "'%s' does not contain '%s' %s times" % (item1, item2, count)
self.should_be_equal_as_integers(self.get_count(item1, item2),
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, utils.get_error_message()))
count = item1.count(item2)
self.log('Item found from the first item %d time%s'
% (count, utils.plural_or_not(count)))
return count
def should_not_match(self, string, pattern, msg=None, values=True):
"""Fails if the given `string` matches the given `pattern`.
Pattern matching is similar as matching files in a shell, and it is
always case-sensitive. In the pattern '*' matches to anything and '?'
matches to any single character.
See `Should Be Equal` for an explanation on how to override the default
error message with `msg` and `values`.
"""
msg = self._get_string_msg(string, pattern, msg, values, 'matches')
asserts.fail_if(self._matches(string, pattern), msg)
def should_match(self, string, pattern, msg=None, values=True):
"""Fails unless the given `string` matches the given `pattern`.
Pattern matching is similar as matching files in a shell, and it is
always case-sensitive. In the pattern, '*' matches to anything and '?'
matches to any single character.
See `Should Be Equal` for an explanation on how to override the default
error message with `msg` and `values`.
"""
msg = self._get_string_msg(string, pattern, msg, values,
'does not match')
asserts.fail_unless(self._matches(string, pattern), msg)
def should_match_regexp(self, string, pattern, msg=None, values=True):
"""Fails if `string` does not match `pattern` as a regular expression.
Regular expression check is done using the Python 're' module, which
has a pattern syntax derived from Perl, and thus also very similar to
the one in Java. See the following documents for more details about
regular expressions in general and Python implementation in particular.
* http://docs.python.org/lib/module-re.html
* http://www.amk.ca/python/howto/regex/
Things to note about the regexp syntax in Robot Framework test data:
1) Backslash is an escape character in the test data, and possible
backslashes in the pattern must thus be escaped with another backslash
(e.g. '\\\\d\\\\w+').
2) Strings that may contain special characters, but should be handled
as literal strings, can be escaped with the `Regexp Escape` keyword.
3) 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'.
4) Possible flags altering how the expression is parsed (e.g.
re.IGNORECASE, re.MULTILINE) can be set by prefixing the pattern with
the '(?iLmsux)' group (e.g. '(?im)pattern'). The available flags are
'IGNORECASE': 'i', 'MULTILINE': 'm', 'DOTALL': 's', 'VERBOSE': 'x',
'UNICODE': 'u', and 'LOCALE': 'L'.
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'
"""
msg = self._get_string_msg(string, pattern, msg, values,
'does not match')
res = re.search(pattern, string)
asserts.fail_if_none(res, msg, False)
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.
"""
msg = self._get_string_msg(string, pattern, msg, values, 'matches')
asserts.fail_unless_none(re.search(pattern, string), msg, False)
def get_length(self, item):
"""Returns and logs the length of the given item.
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.
It is possible to use this keyword also with list variables (e.g.
`@{LIST}`), but you need to use them as scalars (e.g. `${LIST}`).
"""
length = self._get_length(item)
self.log('Length is %d' % length)
return length
def _get_length(self, item):
try: return len(item)
except utils.RERAISED_EXCEPTIONS: raise
except:
try: return item.length()
except utils.RERAISED_EXCEPTIONS: raise
except:
try: return item.size()
except utils.RERAISED_EXCEPTIONS: raise
except:
try: return item.length
except utils.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)
if self.get_length(item) != length:
if not msg:
msg = "Length of '%s' should be %d but it is %d" \
% (item, length, self.get_length(item))
raise AssertionError(msg)
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, str1, str2, msg, values, delim):
default = "'%s' %s '%s'" % (str1, delim, str2)
if not msg:
msg = default
elif values is True:
msg = '%s: %s' % (msg, default)
return msg
class _Variables:
def get_variables(self):
"""Returns a dictionary containing all variables in the current scope."""
return self._namespace.variables
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
This keyword was added in Robot Framework 2.6. See `Set Variable If`
for another keyword to set variables dynamically.
"""
name = self._get_var_name(name)
variables = self.get_variables()
try:
return variables[name]
except DataError:
return 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.keys(), key=lambda s: s.lower()):
msg = utils.format_assign_message(name, variables[name],
cut_long=False)
self.log(msg, level)
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.
"""
name = self._get_var_name(name)
variables = self.get_variables()
msg = variables.replace_string(msg) if msg \
else "Variable %s does not exist" % name
asserts.fail_unless(variables.has_key(name), msg)
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.
"""
name = self._get_var_name(name)
variables = self.get_variables()
msg = variables.replace_string(msg) if msg \
else "Variable %s exists" % name
asserts.fail_if(variables.has_key(name), 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.
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! |
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.
"""
return self.get_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)
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.get_variables().set_test(name, value)
self._log_set_variable(name, value)
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.
Other test suites, including possible child test suites, will not 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`.
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 | ${GREET} | Hello, world! |
| ${ID} = | Get ID |
| Set Suite Variable | ${ID} |
*NOTE:* If the variable has value which itself is a variable (escaped
or not), you must always use the escaped format to reset 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/Suite/Global Variable`,
`Variable Should (Not) Exist`, and `Get Variable Value` keywords.
"""
name = self._get_var_name(name)
value = self._get_var_value(name, values)
self.get_variables().set_suite(name, value)
self._log_set_variable(name, value)
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 test
cases and suites executed after setting them. Setting variables with
this keyword thus has the same effect as creating from the command line
using the options '--variable' or '--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.get_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.get_variables()[name]
return self._unescape_variable_if_needed(resolved)
except (KeyError, ValueError, DataError):
return name
def _unescape_variable_if_needed(self, name):
if not (isinstance(name, basestring) and len(name) > 1):
raise ValueError
if name.startswith('\\'):
name = name[1:]
elif 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):
variables = self.get_variables()
if not values:
return variables[name]
values = variables.replace_list(values)
if len(values) == 1 and name[0] == '$':
return values[0]
return list(values)
def _log_set_variable(self, name, value):
self.log(utils.format_assign_message(name, value))
class _RunKeyword:
# 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.
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 isinstance(name, basestring):
raise RuntimeError('Keyword name must be a string')
kw = Keyword(name, list(args))
return kw.run(ExecutionContext(self._namespace, self._output))
def run_keywords(self, *names):
"""Executes all the given keywords in a sequence without arguments.
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 is overkill. User keywords must nevertheless be used if the
executed keywords need to take arguments.
Example:
| *Setting* | *Value* | *Value* | *Value* |
| Suite Setup | Run Keywords | Initialize database | Start servers |
"""
errors = []
for kw in self.get_variables().replace_list(names):
try:
self.run_keyword(kw)
except ExecutionFailed, err:
errors.extend(err.get_errors())
context = ExecutionContext(self._namespace, self._output)
if not err.can_continue(context.teardown):
break
if errors:
raise ExecutionFailures(errors)
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 similarly as with `Should Be
True` keyword, 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 |
| 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'.
"""
if self._is_true(condition):
return self.run_keyword(name, *args)
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.
"""
if not self._is_true(condition):
return self.run_keyword(name, *args)
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 '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.
The keyword name and arguments work as in `Run Keyword`. See
`Run Keyword If` for a usage example.
Starting from Robot Framework 2.5 errors caused by invalid syntax,
timeouts, or fatal exceptions are not caught by this keyword.
"""
try:
return 'PASS', self.run_keyword(name, *args)
except ExecutionFailed, err:
if err.dont_cont:
raise
return 'FAIL', unicode(err)
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 |
This keyword was added in Robot Framework 2.5. The execution is not
continued if the failure is caused by invalid syntax, timeout, or
fatal exception.
"""
try:
return self.run_keyword(name, *args)
except ExecutionFailed, err:
if not err.dont_cont:
err.cont = True
raise err
def run_keyword_and_expect_error(self, expected_error, name, *args):
"""Runs the keyword and checks that the expected error occurred.
The expected error must be given in the same format as in
Robot Framework reports. It can be a pattern containing
characters '?', which matches to any single character and
'*', which matches to any number of any characters. `name` and
`*args` have same semantics as with `Run Keyword`.
If the expected error occurs, the error message is returned and it can
be further processed/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 | Some Keyword | arg1 | arg2 |
| ${msg} = | Run Keyword And Expect Error | * | My KW |
| Should Start With | ${msg} | Once upon a time in |
Starting from Robot Framework 2.5 errors caused by invalid syntax,
timeouts, or fatal exceptions are not caught by this keyword.
"""
try:
self.run_keyword(name, *args)
except ExecutionFailed, err:
if err.dont_cont:
raise
else:
raise AssertionError("Expected error '%s' did not occur"
% expected_error)
if not self._matches(unicode(err), expected_error):
raise AssertionError("Expected error '%s' but got '%s'"
% (expected_error, err))
return unicode(err)
def repeat_keyword(self, times, name, *args):
"""Executes the specified keyword multiple times.
`name` and `args` define the keyword that is executed
similarly as with `Run Keyword`, and `times` specifies how many
the keyword should be executed. `times` can be given as an
integer or as a string that can be converted to an integer. It
can also have postfix 'times' or 'x' (case and space
insensitive) to make the expression easier to read.
If `times` 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 | Goto Previous Page |
| Repeat Keyword | ${var} | Some Keyword | arg1 | arg2 |
"""
times = utils.normalize(str(times))
if times.endswith('times'):
times = times[:-5]
elif times.endswith('x'):
times = times[:-1]
times = self._convert_to_integer(times)
if times <= 0:
self.log("Keyword '%s' repeated zero times" % name)
for i in xrange(times):
self.log("Repeating keyword, round %d/%d" % (i+1, times))
self.run_keyword(name, *args)
def wait_until_keyword_succeeds(self, timeout, retry_interval, name, *args):
"""Waits until the specified keyword succeeds or the given timeout expires.
`name` and `args` define the keyword that is executed
similarly as with `Run Keyword`. If the specified keyword does
not succeed within `timeout`, this keyword fails.
`retry_interval` is the time to wait before trying to run the
keyword again after the previous run has failed.
Both `timeout` and `retry_interval` must be given in Robot Framework's
time format (e.g. '1 minute', '2 min 3 s', '4.5').
Example:
| Wait Until Keyword Succeeds | 2 min | 5 sec | My keyword | arg1 | arg2 |
Starting from Robot Framework 2.5 errors caused by invalid syntax,
timeouts, or fatal exceptions are not caught by this keyword.
"""
timeout = utils.timestr_to_secs(timeout)
retry_interval = utils.timestr_to_secs(retry_interval)
maxtime = time.time() + timeout
error = None
while not error:
try:
return self.run_keyword(name, *args)
except ExecutionFailed, err:
if err.dont_cont:
raise
if time.time() > maxtime:
error = unicode(err)
else:
time.sleep(retry_interval)
raise AssertionError("Timeout %s exceeded. The last error was: %s"
% (utils.secs_to_timestr(timeout), error))
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._namespace.variables.replace_scalar(values[0])
values = self._verify_values_for_set_variable_if(values[1:], True)
if len(values) == 1:
return self._namespace.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] = [utils.escape(item) for item in
self._namespace.variables[values[0]]]
return self._verify_values_for_set_variable_if(values)
return values
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.
"""
test = self._get_test_in_teardown('Run Keyword If Test Failed')
if test.status == 'FAIL':
return self.run_keyword(name, *args)
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.
"""
test = self._get_test_in_teardown('Run Keyword If Test Passed')
if test.status == 'PASS':
return self.run_keyword(name, *args)
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.
Available in Robot Framework 2.5 and newer.
"""
test = self._get_test_in_teardown('Run Keyword If Timeout Occurred')
if test.timeout.any_timeout_occurred():
return self.run_keyword(name, *args)
def _get_test_in_teardown(self, kwname):
test = self._namespace.test
if test and test.status != 'RUNNING':
return test
raise RuntimeError("Keyword '%s' can only be used in test teardown"
% kwname)
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.critical_stats.failed == 0:
return self.run_keyword(name, *args)
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.critical_stats.failed > 0:
return self.run_keyword(name, *args)
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.all_stats.failed == 0:
return self.run_keyword(name, *args)
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.all_stats.failed > 0:
return self.run_keyword(name, *args)
def _get_suite_in_teardown(self, kwname):
if self._namespace.suite.status == 'RUNNING':
raise RuntimeError("Keyword '%s' can only be used in suite teardown"
% kwname)
return self._namespace.suite
class _Misc:
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 = utils.timestr_to_secs(time_)
# Python hangs with negative values
if seconds < 0:
seconds = 0
time.sleep(seconds)
self.log('Slept %s' % utils.secs_to_timestr(seconds))
if reason:
self.log(reason)
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.
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 = [utils.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"):
"""Logs the given message with the given level.
Valid levels are TRACE, DEBUG, INFO (default), HTML and WARN.
The HTML level is special because it allows writing messages
without HTML code in them being escaped. For example, logging
a message '<img src="image.png">' using the HTML level creates
an image, but with other levels the message would be that exact
string. Notice that invalid HTML can easily corrupt the whole
log file so this feature should be used with care. The
actual log level used for HTML messages is INFO.
Messages logged with the WARN level will be visible also in
the console and in the Test Execution Errors section in the
log file.
"""
LOGGER.log_message(Message(message, level))
def log_many(self, *messages):
"""Logs the given messages as separate entries with the INFO level."""
for msg in messages:
self.log(msg)
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 and NONE (no
logging).
"""
try:
old = self._output.set_log_level(level)
except DataError, err:
raise RuntimeError(unicode(err))
self.log('Log level changed from %s to %s' % (old, level.upper()))
return old
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 path are used, they must be
given in absolute format. Forward slashes can be used as path
separators in all operating systems. It is possible to use
arguments as well as to give a custom name with 'WITH NAME'
syntax. For more information about importing libraries, see
Robot Framework User Guide.
Examples:
| Import Library | MyLibrary |
| Import Library | ${CURDIR}/Library.py | some | args |
| Import Library | ${CURDIR}/../libs/Lib.java | arg | WITH NAME | JavaLib |
"""
try:
self._namespace.import_library(name.replace('/', os.sep), list(args))
except DataError, err:
raise RuntimeError(unicode(err))
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 and this functionality can thus be used to import new
variables, e.g. for each test in a test suite.
The given path must be absolute. 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 |
New in Robot Framework 2.5.4.
"""
try:
self._namespace.import_variables(path.replace('/', os.sep),
list(args), overwrite=True)
except DataError, err:
raise RuntimeError(unicode(err))
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. Forward slashes can be used as path
separator regardless the operating system.
Examples:
| Import Resource | ${CURDIR}/resource.txt |
| Import Resource | ${CURDIR}/../resources/resource.html |
"""
try:
self._namespace.import_resource(path.replace('/', os.sep))
except DataError, err:
raise RuntimeError(unicode(err))
def set_library_search_order(self, *libraries):
"""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 containing the keyword is selected and that
keyword implementation used. If keyword is not found from any
library, or the library search order is not set, executing the
specified keyword fails.
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 |
The library search order is valid only in the suite where this
keyword is used in. The old order is returned and can be used
to reset the search order later.
"""
old_order = self._namespace.library_search_order
self._namespace.library_search_order = libraries
return old_order
def get_time(self, format='timestamp', time_='NOW'):
"""Returns the given time in the requested format.
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 (Jan 1, 1970 0:00:00).
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 time, but that can be
altered using `time` argument as explained below.
1) If `time` is a floating point number, it is interpreted as
seconds since the epoch. This documentation is written about
1177654467 seconds after the epoch.
2) If `time` is a valid 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' (case-insensitive), the
current time is used.
4) If `time` is in the format 'NOW - 1 day' or 'NOW + 1 hour
30 min', the current 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 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'
| ${time} = | Get Time | | 1177654467 |
| ${secs} = | Get Time | sec | 2007-04-27 09:14:27 |
| ${year} = | Get Time | year | NOW | # The time of execution |
| ${day} = | Get Time | day | NOW - 1d | # 1 day subtraced from NOW |
| @{time} = | Get Time | hour min sec | NOW + 1h 2min 3s | # 1h 2min 3s added to NOW |
=>
- ${time} = '2007-04-27 09:14:27'
- ${secs} = 27
- ${year} = '2006'
- ${day} = '28'
- @{time} = ['16', '08', '24']
"""
return utils.get_time(format, utils.parse_time(time_))
def evaluate(self, expression, modules=None):
"""Evaluates the given expression in Python and returns the results.
`modules` argument can be used to specify a comma separated
list of Python modules to be imported and added to the
namespace of the evaluated `expression`.
Examples (expecting ${result} is 3.14):
| ${status} = | Evaluate | 0 < ${result} < 10 |
| ${down} = | Evaluate | int(${result}) |
| ${up} = | Evaluate | math.ceil(${result}) | math |
| ${random} = | Evaluate | random.randint(0, sys.maxint) | random,sys |
=>
- ${status} = True
- ${down} = 3
- ${up} = 4.0
- ${random} = <random integer>
Notice that instead of creating complicated expressions, it is
recommended to move the logic into a test library.
"""
modules = modules.replace(' ','').split(',') if modules else []
namespace = dict((m, __import__(m)) for m in modules if m != '')
try:
return eval(expression, namespace)
except:
raise RuntimeError("Evaluating expression '%s' failed: %s"
% (expression, utils.get_error_message()))
def call_method(self, object, method_name, *args):
"""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.
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 | | |
"""
try:
method = getattr(object, method_name)
except AttributeError:
raise RuntimeError("Object '%s' does not have a method '%s'"
% (object, method_name))
return method(*args)
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):
"""Sets message for for the current test.
This is overridden by possible failure message, except when this keyword
is used in test case teardown. In test case teardown this overrides
messages even for failed tests.
This keyword can not be used in suite setup or suite teardown.
"""
test = self._namespace.test
if not test:
raise RuntimeError("'Set Test Message' keyword cannot be used in "
"suite setup or teardown")
test.message = message
self.log('Set test message to:\n%s' % message)
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.
See `Remove Tags` for another keyword to modify tags at test
execution time.
"""
tags = utils.normalize_tags(tags)
handler = lambda test: utils.normalize_tags(test.tags + tags)
self._set_or_remove_tags(handler)
self.log('Set tag%s %s.' % (utils.plural_or_not(tags),
utils.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 where '*' matches
anything and '?' matches one character.
This keyword can affect either one test case or all test cases in a
test suite similarly as `Set Tags` keyword.
Example:
| Remove Tags | mytag | something-* | ?ython |
"""
tags = utils.normalize_tags(tags)
handler = lambda test: [t for t in test.tags
if not utils.matches_any(t, tags)]
self._set_or_remove_tags(handler)
self.log('Removed tag%s %s.' % (utils.plural_or_not(tags),
utils.seq2str(tags)))
def _set_or_remove_tags(self, handler, suite=None, test=None):
if not (suite or test):
ns = self._namespace
if ns.test is None:
if ns.suite.status != 'RUNNING':
raise RuntimeError("'Set Tags' and 'Remove Tags' keywords "
"cannot be used in suite teardown.")
self._set_or_remove_tags(handler, suite=ns.suite)
else:
self._set_or_remove_tags(handler, test=ns.test)
ns.variables.set_test('@{TEST_TAGS}', ns.test.tags)
ns.suite._set_critical_tags(ns.suite.critical)
elif suite:
for sub in suite.suites:
self._set_or_remove_tags(handler, suite=sub)
for test in suite.tests:
self._set_or_remove_tags(handler, test=test)
else:
test.tags = handler(test)
def get_library_instance(self, name):
"""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 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.
"""
try:
return self._namespace.get_library_instance(name)
except DataError, err:
raise RuntimeError(unicode(err))
class BuiltIn(_Verify, _Converter, _Variables, _RunKeyword, _Misc):
"""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`).
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = get_version()
@property
def _output(self):
# OUTPUT is initially set to None and gets real value only when actual
# execution starts. If BuiltIn is used externally before that, OUTPUT
# gets None value. For more information see this bug report:
# http://code.google.com/p/robotframework/issues/detail?id=654
# TODO: Refactor running so that OUTPUT is available via context
from robot.output import OUTPUT
return OUTPUT
@property
def _namespace(self):
return NAMESPACES.current
def _matches(self, string, pattern):
# Must use this instead of fnmatch when string may contain newlines.
return utils.matches(string, pattern, caseless=False, spaceless=False)
def _is_true(self, condition):
if isinstance(condition, basestring):
try:
condition = eval(condition)
except:
raise RuntimeError("Evaluating condition '%s' failed: %s"
% (condition, utils.get_error_message()))
return bool(condition)
def register_run_keyword(library, keyword, args_to_process=None):
"""Registers 'run keyword' so that its arguments can be handled correctly.
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).
Starting from Robot Framework 2.5.2, keywords executed by registered run
keywords can be tested with dryrun runmode with following limitations:
- Registered keyword must have 'name' argument which takes keyword's name or
Registered keyword must have '*names' argument which takes keywords' names
- Keyword name does not contain variables
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 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 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)
for name in [attr for attr in dir(_RunKeyword) if not attr.startswith('_')]:
register_run_keyword('BuiltIn', getattr(_RunKeyword, name))
for name in ['set_test_variable', 'set_suite_variable', 'set_global_variable',
'variable_should_exist', 'variable_should_not_exist', 'comment',
'get_variable_value']:
register_run_keyword('BuiltIn', name, 0)
del name, attr
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from robot import utils
from robot.output import LOGGER
from robot.errors import DataError
from datarow import DataRow
from tablepopulators import (SettingTablePopulator, VariableTablePopulator,
TestTablePopulator, KeywordTablePopulator,
NullPopulator)
from htmlreader import HtmlReader
from tsvreader import TsvReader
from txtreader import TxtReader
try:
from restreader import RestReader
except ImportError:
def RestReader():
raise DataError("Using reStructuredText test data requires having "
"'docutils' module installed.")
READERS = {'html': HtmlReader, 'htm': HtmlReader, 'xhtml': HtmlReader,
'tsv': TsvReader , 'rst': RestReader, 'rest': RestReader,
'txt': TxtReader}
# Hook for external tools for altering ${CURDIR} processing
PROCESS_CURDIR = True
class FromFilePopulator(object):
_populators = {'setting': SettingTablePopulator,
'variable': VariableTablePopulator,
'testcase': TestTablePopulator,
'keyword': KeywordTablePopulator}
def __init__(self, datafile):
self._datafile = datafile
self._current_populator = NullPopulator()
self._curdir = self._get_curdir(datafile.directory)
def _get_curdir(self, path):
return path.replace('\\','\\\\') if path else None
def populate(self, path):
LOGGER.info("Parsing file '%s'." % path)
source = self._open(path)
try:
self._get_reader(path).read(source, self)
except:
raise DataError(utils.get_error_message())
finally:
source.close()
def _open(self, path):
if not os.path.isfile(path):
raise DataError("Data source does not exist.")
try:
return open(path, 'rb')
except:
raise DataError(utils.get_error_message())
def _get_reader(self, path):
extension = os.path.splitext(path.lower())[-1][1:]
try:
return READERS[extension]()
except KeyError:
raise DataError("Unsupported file format '%s'." % extension)
def start_table(self, header):
self._current_populator.populate()
table = self._datafile.start_table(DataRow(header).all)
self._current_populator = self._populators[table.type](table) \
if table is not None else NullPopulator()
return bool(self._current_populator)
def eof(self):
self._current_populator.populate()
def add(self, row):
if PROCESS_CURDIR and self._curdir:
row = self._replace_curdirs_in(row)
data = DataRow(row)
if data:
self._current_populator.add(data)
def _replace_curdirs_in(self, row):
return [cell.replace('${CURDIR}', self._curdir) for cell in row]
class FromDirectoryPopulator(object):
ignored_prefixes = ('_', '.')
ignored_dirs = ('CVS',)
def populate(self, path, datadir, include_suites, warn_on_skipped):
LOGGER.info("Parsing test data directory '%s'" % path)
include_sub_suites = self._get_include_suites(path, include_suites)
initfile, children = self._get_children(path, include_sub_suites)
datadir.initfile = initfile
if initfile:
try:
FromFilePopulator(datadir).populate(initfile)
except DataError, err:
LOGGER.error(unicode(err))
for child in children:
try:
datadir.add_child(child, include_sub_suites)
except DataError, err:
self._log_failed_parsing("Parsing data source '%s' failed: %s"
% (child, unicode(err)), warn_on_skipped)
def _log_failed_parsing(self, message, warn):
if warn:
LOGGER.warn(message)
else:
LOGGER.info(message)
def _get_include_suites(self, path, include_suites):
# If directory is included also all it children should be included
if self._is_in_incl_suites(os.path.basename(os.path.normpath(path)),
include_suites):
return []
return include_suites
def _get_children(self, dirpath, include_suites):
initfile = None
children = []
for name, path in self._list_dir(dirpath):
if self._is_init_file(name, path):
if not initfile:
initfile = path
else:
LOGGER.error("Ignoring second test suite init file '%s'." % path)
elif self._is_included(name, path, include_suites):
children.append(path)
else:
LOGGER.info("Ignoring file or directory '%s'." % name)
return initfile, children
def _list_dir(self, path):
# os.listdir returns Unicode entries when path is Unicode
names = os.listdir(utils.unic(path))
for name in sorted(names, key=unicode.lower):
# utils.unic needed to handle nfc/nfd normalization on OSX
yield utils.unic(name), utils.unic(os.path.join(path, name))
def _is_init_file(self, name, path):
if not os.path.isfile(path):
return False
base, extension = os.path.splitext(name.lower())
return base == '__init__' and extension[1:] in READERS
def _is_included(self, name, path, include_suites):
if name.startswith(self.ignored_prefixes):
return False
if os.path.isdir(path):
return name not in self.ignored_dirs
base, extension = os.path.splitext(name.lower())
return (extension[1:] in READERS and
self._is_in_incl_suites(base, include_suites))
def _is_in_incl_suites(self, name, include_suites):
if include_suites == []:
return True
# Match only to the last part of name given like '--suite parent.child'
include_suites = [ incl.split('.')[-1] for incl in include_suites ]
name = name.split('__', 1)[-1] # Strip possible prefix
return utils.matches_any(name, include_suites, ignore=['_'])
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class Populator(object):
"""Explicit interface for all populators."""
def add(self, row): raise NotImplementedError()
def populate(self): raise NotImplementedError()
class CommentCacher(object):
def __init__(self):
self._init_comments()
def _init_comments(self):
self._comments = []
def add(self, comment):
self._comments.append(comment)
def consume_comments_with(self, function):
for c in self._comments:
function(c)
self._init_comments()
class _TablePopulator(Populator):
def __init__(self, table):
self._table = table
self._populator = NullPopulator()
self._comments = CommentCacher()
def add(self, row):
if self._is_cacheable_comment_row(row):
self._comments.add(row)
else:
self._add(row)
def _add(self, row):
if not self._is_continuing(row):
self._populator.populate()
self._populator = self._get_populator(row)
self._comments.consume_comments_with(self._populator.add)
self._populator.add(row)
def populate(self):
self._comments.consume_comments_with(self._populator.add)
self._populator.populate()
def _is_continuing(self, row):
return row.is_continuing() and self._populator
def _is_cacheable_comment_row(self, row):
return row.is_commented()
class SettingTablePopulator(_TablePopulator):
def _get_populator(self, row):
row.handle_old_style_metadata()
setter = self._table.get_setter(row.head)
return SettingPopulator(setter) if setter else NullPopulator()
class VariableTablePopulator(_TablePopulator):
def _get_populator(self, row):
return VariablePopulator(self._table.add, row.head)
class _StepContainingTablePopulator(_TablePopulator):
def _is_continuing(self, row):
return row.is_indented() and self._populator or row.is_commented()
def _is_cacheable_comment_row(self, row):
return row.is_commented() and isinstance(self._populator, NullPopulator)
class TestTablePopulator(_StepContainingTablePopulator):
def _get_populator(self, row):
return TestCasePopulator(self._table.add)
class KeywordTablePopulator(_StepContainingTablePopulator):
def _get_populator(self, row):
return UserKeywordPopulator(self._table.add)
class ForLoopPopulator(Populator):
def __init__(self, for_loop_creator):
self._for_loop_creator = for_loop_creator
self._loop = None
self._populator = NullPopulator()
self._declaration = []
def add(self, row):
dedented_row = row.dedent()
if not self._loop:
declaration_ready = self._populate_declaration(row)
if not declaration_ready:
return
self._loop = self._for_loop_creator(self._declaration)
if not row.is_continuing():
self._populator.populate()
self._populator = StepPopulator(self._loop.add_step)
self._populator.add(dedented_row)
def _populate_declaration(self, row):
if row.starts_for_loop() or row.is_continuing():
self._declaration.extend(row.dedent().data)
return False
return True
def populate(self):
if not self._loop:
self._for_loop_creator(self._declaration)
self._populator.populate()
class _TestCaseUserKeywordPopulator(Populator):
def __init__(self, test_or_uk_creator):
self._test_or_uk_creator = test_or_uk_creator
self._test_or_uk = None
self._populator = NullPopulator()
self._comments = CommentCacher()
def add(self, row):
if row.is_commented():
self._comments.add(row)
return
if not self._test_or_uk:
self._test_or_uk = self._test_or_uk_creator(row.head)
dedented_row = row.dedent()
if dedented_row:
self._handle_data_row(dedented_row)
def _handle_data_row(self, row):
if not self._continues(row):
self._populator.populate()
self._populator = self._get_populator(row)
self._flush_comments_with(self._populate_comment_row)
else:
self._flush_comments_with(self._populator.add)
self._populator.add(row)
def _populate_comment_row(self, crow):
populator = StepPopulator(self._test_or_uk.add_step)
populator.add(crow)
populator.populate()
def _flush_comments_with(self, function):
self._comments.consume_comments_with(function)
def populate(self):
self._populator.populate()
self._flush_comments_with(self._populate_comment_row)
def _get_populator(self, row):
if row.starts_test_or_user_keyword_setting():
setter = self._setting_setter(row)
return SettingPopulator(setter) if setter else NullPopulator()
if row.starts_for_loop():
return ForLoopPopulator(self._test_or_uk.add_for_loop)
return StepPopulator(self._test_or_uk.add_step)
def _continues(self, row):
return row.is_continuing() and self._populator or \
(isinstance(self._populator, ForLoopPopulator) and row.is_indented())
def _setting_setter(self, row):
setting_name = row.test_or_user_keyword_setting_name()
return self._test_or_uk.get_setter(setting_name)
class TestCasePopulator(_TestCaseUserKeywordPopulator):
_item_type = 'test case'
class UserKeywordPopulator(_TestCaseUserKeywordPopulator):
_item_type = 'keyword'
class Comments(object):
def __init__(self):
self._crows = []
def add(self, row):
if row.comments:
self._crows.append(row.comments)
def formatted_value(self):
rows = (' '.join(row).strip() for row in self._crows)
return '\n'.join(rows)
class _PropertyPopulator(Populator):
def __init__(self, setter):
self._setter = setter
self._value = []
self._comments = Comments()
def add(self, row):
if not row.is_commented():
self._add(row)
self._comments.add(row)
def _add(self, row):
self._value.extend(row.dedent().data)
class VariablePopulator(_PropertyPopulator):
def __init__(self, setter, name):
_PropertyPopulator.__init__(self, setter)
self._name = name
def populate(self):
self._setter(self._name, self._value,
self._comments.formatted_value())
class SettingPopulator(_PropertyPopulator):
def populate(self):
self._setter(self._value, self._comments.formatted_value())
class StepPopulator(_PropertyPopulator):
def _add(self, row):
self._value.extend(row.data)
def populate(self):
if self._value or self._comments:
self._setter(self._value, self._comments.formatted_value())
class NullPopulator(Populator):
def add(self, row): pass
def populate(self): pass
def __nonzero__(self): return False
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from robot.errors import DataError
from robot.variables import is_var
from robot.output import LOGGER
from robot import utils
from settings import (Documentation, Fixture, Timeout, Tags, Metadata,
Library, Resource, Variables, Arguments, Return, Template)
from populators import FromFilePopulator, FromDirectoryPopulator
def TestData(parent=None, source=None, include_suites=[], warn_on_skipped=False):
if os.path.isdir(source):
return TestDataDirectory(parent, source, include_suites, warn_on_skipped)
return TestCaseFile(parent, source)
class _TestData(object):
def __init__(self, parent=None, source=None):
self.parent = parent
self.source = utils.abspath(source) if source else None
self.children = []
self._tables = None
def _get_tables(self):
if not self._tables:
self._tables = utils.NormalizedDict({'Setting': self.setting_table,
'Settings': self.setting_table,
'Metadata': self.setting_table,
'Variable': self.variable_table,
'Variables': self.variable_table,
'Keyword': self.keyword_table,
'Keywords': self.keyword_table,
'User Keyword': self.keyword_table,
'User Keywords': self.keyword_table,
'Test Case': self.testcase_table,
'Test Cases': self.testcase_table})
return self._tables
def start_table(self, header_row):
table_name = header_row[0]
try:
table = self._valid_table(self._get_tables()[table_name])
except KeyError:
return None
else:
if table is not None:
table.set_header(header_row)
return table
@property
def name(self):
if not self.source:
return None
name = self._get_basename()
name = name.split('__', 1)[-1] # Strip possible prefix
name = name.replace('_', ' ').strip()
if name.islower():
name = name.title()
return name
def _get_basename(self):
return os.path.splitext(os.path.basename(self.source))[0]
@property
def keywords(self):
return self.keyword_table.keywords
@property
def imports(self):
return self.setting_table.imports
def report_invalid_syntax(self, table, message, level='ERROR'):
initfile = getattr(self, 'initfile', None)
path = os.path.join(self.source, initfile) if initfile else self.source
LOGGER.write("Invalid syntax in file '%s' in table '%s': %s"
% (path, table, message), level)
class TestCaseFile(_TestData):
def __init__(self, parent=None, source=None):
_TestData.__init__(self, parent, source)
self.directory = os.path.dirname(self.source) if self.source else None
self.setting_table = TestCaseFileSettingTable(self)
self.variable_table = VariableTable(self)
self.testcase_table = TestCaseTable(self)
self.keyword_table = KeywordTable(self)
if source: # FIXME: model should be decoupled from populating
FromFilePopulator(self).populate(source)
self._validate()
def _validate(self):
if not self.testcase_table.is_started():
raise DataError('File has no test case table.')
def _valid_table(self, table):
return table
def has_tests(self):
return True
def __iter__(self):
for table in [self.setting_table, self.variable_table,
self.testcase_table, self.keyword_table]:
yield table
class ResourceFile(_TestData):
def __init__(self, source=None):
_TestData.__init__(self, source=source)
self.directory = os.path.dirname(self.source) if self.source else None
self.setting_table = ResourceFileSettingTable(self)
self.variable_table = VariableTable(self)
self.testcase_table = TestCaseTable(self)
self.keyword_table = KeywordTable(self)
if self.source:
FromFilePopulator(self).populate(source)
self._report_status()
def _report_status(self):
if self.setting_table or self.variable_table or self.keyword_table:
LOGGER.info("Imported resource file '%s' (%d keywords)."
% (self.source, len(self.keyword_table.keywords)))
else:
LOGGER.warn("Imported resource file '%s' is empty." % self.source)
def _valid_table(self, table):
if table is self.testcase_table:
raise DataError("Resource file '%s' contains a test case table "
"which is not allowed." % self.source)
return table
def __iter__(self):
for table in [self.setting_table, self.variable_table,
self.keyword_table]:
yield table
class TestDataDirectory(_TestData):
def __init__(self, parent=None, source=None, include_suites=[], warn_on_skipped=False):
_TestData.__init__(self, parent, source)
self.directory = self.source
self.initfile = None
self.setting_table = InitFileSettingTable(self)
self.variable_table = VariableTable(self)
self.testcase_table = TestCaseTable(self)
self.keyword_table = KeywordTable(self)
if self.source:
FromDirectoryPopulator().populate(self.source, self, include_suites, warn_on_skipped)
self.children = [ ch for ch in self.children if ch.has_tests() ]
def _get_basename(self):
return os.path.basename(self.source)
def _valid_table(self, table):
if table is self.testcase_table:
LOGGER.error("Test suite init file in '%s' contains a test case "
"table which is not allowed." % self.source)
return None
return table
def add_child(self, path, include_suites):
self.children.append(TestData(parent=self,source=path,
include_suites=include_suites))
def has_tests(self):
return any(ch.has_tests() for ch in self.children)
def __iter__(self):
for table in [self.setting_table, self.variable_table,
self.keyword_table]:
yield table
class _Table(object):
def __init__(self, parent):
self.parent = parent
self.header = None
def set_header(self, header):
self.header = header
@property
def name(self):
return self.header[0]
@property
def source(self):
return self.parent.source
@property
def directory(self):
return self.parent.directory
def report_invalid_syntax(self, message, level='ERROR'):
self.parent.report_invalid_syntax(self.name, message, level)
class _WithSettings(object):
def get_setter(self, setting_name):
normalized = self.normalize(setting_name)
if normalized in self._setters:
return self._setters[normalized](self)
self.report_invalid_syntax("Non-existing setting '%s'." % setting_name)
def is_setting(self, setting_name):
return self.normalize(setting_name) in self._setters
def normalize(self, setting):
result = utils.normalize(setting)
return result[0:-1] if result and result[-1]==':' else result
class _SettingTable(_Table, _WithSettings):
type = 'setting'
def __init__(self, parent):
_Table.__init__(self, parent)
self.doc = Documentation('Documentation', self)
self.suite_setup = Fixture('Suite Setup', self)
self.suite_teardown = Fixture('Suite Teardown', self)
self.test_setup = Fixture('Test Setup', self)
self.test_teardown = Fixture('Test Teardown', self)
self.force_tags = Tags('Force Tags', self)
self.default_tags = Tags('Default Tags', self)
self.test_template = Template('Test Template', self)
self.test_timeout = Timeout('Test Timeout', self)
self.metadata = []
self.imports = []
def _get_adder(self, adder_method):
def adder(value, comment):
name = value[0] if value else ''
adder_method(name, value[1:], comment)
return adder
def add_metadata(self, name, value='', comment=None):
self.metadata.append(Metadata('Metadata', self, name, value, comment))
return self.metadata[-1]
def add_library(self, name, args=None, comment=None):
self.imports.append(Library(self, name, args, comment=comment))
return self.imports[-1]
def add_resource(self, name, invalid_args=None, comment=None):
self.imports.append(Resource(self, name, invalid_args, comment=comment))
return self.imports[-1]
def add_variables(self, name, args=None, comment=None):
self.imports.append(Variables(self, name, args, comment=comment))
return self.imports[-1]
def __nonzero__(self):
return any(setting.is_set() for setting in self)
class TestCaseFileSettingTable(_SettingTable):
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'suitesetup': lambda s: s.suite_setup.populate,
'suiteprecondition': lambda s: s.suite_setup.populate,
'suiteteardown': lambda s: s.suite_teardown.populate,
'suitepostcondition': lambda s: s.suite_teardown.populate,
'testsetup': lambda s: s.test_setup.populate,
'testprecondition': lambda s: s.test_setup.populate,
'testteardown': lambda s: s.test_teardown.populate,
'testpostcondition': lambda s: s.test_teardown.populate,
'forcetags': lambda s: s.force_tags.populate,
'defaulttags': lambda s: s.default_tags.populate,
'testtemplate': lambda s: s.test_template.populate,
'testtimeout': lambda s: s.test_timeout.populate,
'library': lambda s: s._get_adder(s.add_library),
'resource': lambda s: s._get_adder(s.add_resource),
'variables': lambda s: s._get_adder(s.add_variables),
'metadata': lambda s: s._get_adder(s.add_metadata)}
def __iter__(self):
for setting in [self.doc, self.suite_setup, self.suite_teardown,
self.test_setup, self.test_teardown, self.force_tags,
self.default_tags, self.test_template, self.test_timeout] \
+ self.metadata + self.imports:
yield setting
class ResourceFileSettingTable(_SettingTable):
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'library': lambda s: s._get_adder(s.add_library),
'resource': lambda s: s._get_adder(s.add_resource),
'variables': lambda s: s._get_adder(s.add_variables)}
def __iter__(self):
for setting in [self.doc] + self.imports:
yield setting
class InitFileSettingTable(_SettingTable):
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'suitesetup': lambda s: s.suite_setup.populate,
'suiteprecondition': lambda s: s.suite_setup.populate,
'suiteteardown': lambda s: s.suite_teardown.populate,
'suitepostcondition': lambda s: s.suite_teardown.populate,
'testsetup': lambda s: s.test_setup.populate,
'testprecondition': lambda s: s.test_setup.populate,
'testteardown': lambda s: s.test_teardown.populate,
'testpostcondition': lambda s: s.test_teardown.populate,
'forcetags': lambda s: s.force_tags.populate,
'library': lambda s: s._get_adder(s.add_library),
'resource': lambda s: s._get_adder(s.add_resource),
'variables': lambda s: s._get_adder(s.add_variables),
'metadata': lambda s: s._get_adder(s.add_metadata)}
def __iter__(self):
for setting in [self.doc, self.suite_setup, self.suite_teardown,
self.test_setup, self.test_teardown, self.force_tags] \
+ self.metadata + self.imports:
yield setting
class VariableTable(_Table):
type = 'variable'
def __init__(self, parent):
_Table.__init__(self, parent)
self.variables = []
def add(self, name, value, comment=None):
self.variables.append(Variable(name, value, comment))
def __iter__(self):
return iter(self.variables)
def __nonzero__(self):
return bool(self.variables)
class TestCaseTable(_Table):
type = 'testcase'
def __init__(self, parent):
_Table.__init__(self, parent)
self.tests = []
def add(self, name):
self.tests.append(TestCase(self, name))
return self.tests[-1]
def __iter__(self):
return iter(self.tests)
def __nonzero__(self):
return bool(self.tests)
def is_started(self):
return bool(self.header)
class KeywordTable(_Table):
type = 'keyword'
def __init__(self, parent):
_Table.__init__(self, parent)
self.keywords = []
def add(self, name):
self.keywords.append(UserKeyword(self, name))
return self.keywords[-1]
def __iter__(self):
return iter(self.keywords)
def __nonzero__(self):
return bool(self.keywords)
class Variable(object):
def __init__(self, name, value, comment=None):
self.name = name.rstrip('= ')
if name.startswith('$') and value == []:
value = ''
if isinstance(value, basestring):
value = [value] # Need to support scalar lists until RF 2.6
self.value = value
self.comment = comment
def as_list(self):
ret = [self.name] + self.value
if self.comment:
ret.append('# %s' % self.comment)
return ret
def is_set(self):
return True
def is_for_loop(self):
return False
class _WithSteps(object):
def add_step(self, content, comment=None):
self.steps.append(Step(content, comment))
return self.steps[-1]
class TestCase(_WithSteps, _WithSettings):
def __init__(self, parent, name):
self.parent = parent
self.name = name
self.doc = Documentation('[Documentation]', self)
self.template = Template('[Template]', self)
self.tags = Tags('[Tags]', self)
self.setup = Fixture('[Setup]', self)
self.teardown = Fixture('[Teardown]', self)
self.timeout = Timeout('[Timeout]', self)
self.steps = []
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'template': lambda s: s.template.populate,
'setup': lambda s: s.setup.populate,
'precondition': lambda s: s.setup.populate,
'teardown': lambda s: s.teardown.populate,
'postcondition': lambda s: s.teardown.populate,
'tags': lambda s: s.tags.populate,
'timeout': lambda s: s.timeout.populate}
@property
def source(self):
return self.parent.source
@property
def directory(self):
return self.parent.directory
def add_for_loop(self, data):
self.steps.append(ForLoop(data))
return self.steps[-1]
def report_invalid_syntax(self, message, level='ERROR'):
type_ = 'test case' if type(self) is TestCase else 'keyword'
message = "Invalid syntax in %s '%s': %s" % (type_, self.name, message)
self.parent.report_invalid_syntax(message, level)
def __iter__(self):
for element in [self.doc, self.tags, self.setup,
self.template, self.timeout] \
+ self.steps + [self.teardown]:
yield element
class UserKeyword(TestCase):
def __init__(self, parent, name):
self.parent = parent
self.name = name
self.doc = Documentation('[Documentation]', self)
self.args = Arguments('[Arguments]', self)
self.return_ = Return('[Return]', self)
self.timeout = Timeout('[Timeout]', self)
self.teardown = Fixture('[Teardown]', self)
self.steps = []
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'arguments': lambda s: s.args.populate,
'return': lambda s: s.return_.populate,
'timeout': lambda s: s.timeout.populate,
'teardown': lambda s: s.teardown.populate}
def __iter__(self):
for element in [self.args, self.doc, self.timeout] \
+ self.steps + [self.teardown, self.return_]:
yield element
class ForLoop(_WithSteps):
def __init__(self, content):
self.range, index = self._get_range_and_index(content)
self.vars = content[:index]
self.items = content[index+1:]
self.steps = []
def _get_range_and_index(self, content):
for index, item in enumerate(content):
item = item.upper().replace(' ', '')
if item in ['IN', 'INRANGE']:
return item == 'INRANGE', index
return False, len(content)
def is_comment(self):
return False
def is_for_loop(self):
return True
def apply_template(self, template):
return self
def as_list(self):
return [': FOR'] + self.vars + ['IN RANGE' if self.range else 'IN'] + self.items
def __iter__(self):
return iter(self.steps)
class Step(object):
def __init__(self, content, comment=None):
self.assign = self._get_assigned_vars(content)
try:
self.keyword = content[len(self.assign)]
except IndexError:
self.keyword = None
self.args = content[len(self.assign)+1:]
self.comment = comment
def _get_assigned_vars(self, content):
vars = []
for item in content:
if not is_var(item.rstrip('= ')):
break
vars.append(item)
return vars
def is_comment(self):
return not (self.assign or self.keyword or self.args)
def is_for_loop(self):
return False
def apply_template(self, template):
if self.is_comment():
return self
return Step([template] + self.as_list(include_comment=False))
def is_set(self):
return True
def as_list(self, indent=False, include_comment=True):
kw = [self.keyword] if self.keyword is not None else []
ret = self.assign + kw + self.args
if indent:
ret.insert(0, '')
if include_comment and self.comment:
ret.append('# %s' % self.comment)
return ret
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from tsvreader import TsvReader
class TxtReader(TsvReader):
_space_splitter = re.compile(' {2,}')
_pipe_splitter = re.compile(' \|(?= )')
def _split_row(self, row):
row = row.rstrip().replace('\t', ' ')
if not row.startswith('| '):
return self._space_splitter.split(row)
if row.endswith(' |'):
row = row[1:-1]
else:
row = row[1:]
return self._pipe_splitter.split(row)
def _process(self, cell):
return cell.decode('UTF-8')
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from codecs import BOM_UTF8
class TsvReader:
def read(self, tsvfile, populator):
process = False
for index, row in enumerate(tsvfile.readlines()):
if index == 0 and row.startswith(BOM_UTF8):
row = row[len(BOM_UTF8):]
cells = [ self._process(cell) for cell in self._split_row(row) ]
name = cells and cells[0].strip() or ''
if name.startswith('*') and populator.start_table([ c.replace('*','') for c in cells ]):
process = True
elif process:
populator.add(cells)
populator.eof()
def _split_row(self, row):
return row.rstrip().split('\t')
def _process(self, cell):
if len(cell) > 1 and cell[0] == cell[-1] == '"':
cell = cell[1:-1].replace('""','"')
return cell.decode('UTF-8')
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class _Setting(object):
def __init__(self, setting_name, parent=None, comment=None):
self.setting_name = setting_name
self.parent = parent
self.comment = comment
self.reset()
def reset(self):
self.value = []
@property
def source(self):
return self.parent.source if self.parent else None
@property
def directory(self):
return self.parent.directory if self.parent else None
def populate(self, value, comment=None):
"""Mainly used at parsing time, later attributes can be set directly."""
self._populate(value)
self.comment = comment
def _populate(self, value):
self.value = value
def is_set(self):
return bool(self.value)
def is_for_loop(self):
return False
def report_invalid_syntax(self, message, level='ERROR'):
self.parent.report_invalid_syntax(message, level)
def _string_value(self, value):
return value if isinstance(value, basestring) else ' '.join(value)
def _concat_string_with_value(self, string, value):
if string:
return string + ' ' + self._string_value(value)
return self._string_value(value)
def as_list(self):
ret = self._data_as_list()
if self.comment:
ret.append('# %s' % self.comment)
return ret
def _data_as_list(self):
ret = [self.setting_name]
if self.value:
ret.extend(self.value)
return ret
class Documentation(_Setting):
def reset(self):
self.value = ''
def _populate(self, value):
self.value = self._concat_string_with_value(self.value, value)
def _data_as_list(self):
return [self.setting_name, self.value]
class Template(_Setting):
def reset(self):
self.value = None
def _populate(self, value):
self.value = self._concat_string_with_value(self.value, value)
def is_set(self):
return self.value is not None
def _data_as_list(self):
ret = [self.setting_name]
if self.value:
ret.append(self.value)
return ret
class Fixture(_Setting):
def reset(self):
self.name = None
self.args = []
def _populate(self, value):
if not self.name:
self.name = value[0] if value else ''
value = value[1:]
self.args.extend(value)
def is_set(self):
return self.name is not None
def _data_as_list(self):
ret = [self.setting_name]
if self.name or self.args:
ret.append(self.name or '')
if self.args:
ret.extend(self.args)
return ret
class Timeout(_Setting):
def reset(self):
self.value = None
self.message = ''
def _populate(self, value):
if not self.value:
self.value = value[0] if value else ''
value = value[1:]
self.message = self._concat_string_with_value(self.message, value)
def is_set(self):
return self.value is not None
def _data_as_list(self):
ret = [self.setting_name]
if self.value or self.message:
ret.append(self.value or '')
if self.message:
ret.append(self.message)
return ret
class Tags(_Setting):
def reset(self):
self.value = None
def _populate(self, value):
self.value = (self.value or []) + value
def is_set(self):
return self.value is not None
def __add__(self, other):
if not isinstance(other, Tags):
raise TypeError('Tags can only be added with tags')
tags = Tags('Tags')
tags.value = (self.value or []) + (other.value or [])
return tags
class Arguments(_Setting):
pass
class Return(_Setting):
pass
class Metadata(_Setting):
def __init__(self, setting_name, parent, name, value, comment=None):
self.setting_name = setting_name
self.parent = parent
self.name = name
self.value = self._string_value(value)
self.comment = comment
def is_set(self):
return True
def _data_as_list(self):
return [self.setting_name, self.name, self.value]
class _Import(_Setting):
def __init__(self, parent, name, args=None, alias=None, comment=None):
self.parent = parent
self.name = name
self.args = args or []
self.alias = alias
self.comment = comment
@property
def type(self):
return type(self).__name__
def is_set(self):
return True
def _data_as_list(self):
return [self.type, self.name] + self.args
class Library(_Import):
def __init__(self, parent, name, args=None, alias=None, comment=None):
if args and not alias:
args, alias = self._split_alias(args)
_Import.__init__(self, parent, name, args, alias, comment)
def _split_alias(self, args):
if len(args) >= 2 and args[-2].upper() == 'WITH NAME':
return args[:-2], args[-1]
return args, None
def _data_as_list(self):
alias = ['WITH NAME', self.alias] if self.alias else []
return ['Library', self.name] + self.args + alias
class Resource(_Import):
def __init__(self, parent, name, invalid_args=None, comment=None):
if invalid_args:
name += ' ' + ' '.join(invalid_args)
_Import.__init__(self, parent, name, comment=comment)
class Variables(_Import):
def __init__(self, parent, name, args=None, comment=None):
_Import.__init__(self, parent, name, args, comment=comment)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
class DataRow(object):
_row_continuation_marker = '...'
_whitespace_regexp = re.compile('\s+')
_ye_olde_metadata_prefix = 'meta:'
def __init__(self, cells):
self.cells, self.comments = self._parse(cells)
def _parse(self, row):
data = []
comments = []
for cell in row:
cell = self._collapse_whitespace(cell)
if cell.startswith('#') and not comments:
comments.append(cell[1:])
elif comments:
comments.append(cell)
else:
data.append(cell)
return self._purge_empty_cells(data), self._purge_empty_cells(comments)
def _collapse_whitespace(self, cell):
return self._whitespace_regexp.sub(' ', cell).strip()
def _purge_empty_cells(self, row):
while row and not row[-1]:
row.pop()
# Cells with only a single backslash are considered empty
return [cell if cell != '\\' else '' for cell in row]
@property
def head(self):
return self.cells[0] if self.cells else None
@property
def _tail(self):
return self.cells[1:] if self.cells else None
@property
def all(self):
return self.cells
@property
def data(self):
if self.is_continuing():
index = self.cells.index(self._row_continuation_marker) + 1
return self.cells[index:]
return self.cells
def dedent(self):
datarow = DataRow([])
datarow.cells = self._tail
datarow.comments = self.comments
return datarow
def startswith(self, value):
return self.head() == value
def handle_old_style_metadata(self):
if self._is_metadata_with_olde_prefix(self.head):
self.cells = self._convert_to_new_style_metadata()
def _is_metadata_with_olde_prefix(self, value):
return value.lower().startswith(self._ye_olde_metadata_prefix)
def _convert_to_new_style_metadata(self):
return ['Metadata'] + [self.head.split(':', 1)[1].strip()] + self._tail
def starts_for_loop(self):
if self.head and self.head.startswith(':'):
return self.head.replace(':', '').replace(' ', '').upper() == 'FOR'
return False
def starts_test_or_user_keyword_setting(self):
head = self.head
return head and head[0] == '[' and head[-1] == ']'
def test_or_user_keyword_setting_name(self):
return self.head[1:-1].strip()
def is_indented(self):
return self.head == ''
def is_continuing(self):
for cell in self.cells:
if cell == self._row_continuation_marker:
return True
if cell:
return False
def is_commented(self):
return bool(not self.cells and self.comments)
def __nonzero__(self):
return bool(self.cells or self.comments)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from datarow import DataRow
from model import (TestCaseFile, TestDataDirectory, ResourceFile,
TestCase, UserKeyword)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tempfile
import os
from docutils.core import publish_cmdline
from htmlreader import HtmlReader
# Ignore custom sourcecode directives at least we use in reST sources.
# See e.g. ug2html.py for an example how custom directives are created.
from docutils.parsers.rst import directives
ignorer = lambda *args: []
ignorer.content = 1
directives.register_directive('sourcecode', ignorer)
del directives, ignorer
class RestReader(HtmlReader):
def read(self, rstfile, rawdata):
htmlpath = self._rest_to_html(rstfile.name)
htmlfile = None
try:
htmlfile = open(htmlpath, 'rb')
return HtmlReader.read(self, htmlfile, rawdata)
finally:
if htmlfile:
htmlfile.close()
os.remove(htmlpath)
def _rest_to_html(self, rstpath):
filedesc, htmlpath = tempfile.mkstemp('.html')
os.close(filedesc)
publish_cmdline(writer_name='html', argv=[rstpath, htmlpath])
return htmlpath
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import HTMLParser
import sys
from htmlentitydefs import entitydefs
extra_entitydefs = {'nbsp': ' ', 'apos': "'", 'tilde': '~'}
class HtmlReader(HTMLParser.HTMLParser):
IGNORE = 0
INITIAL = 1
PROCESS = 2
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self._encoding = 'ISO-8859-1'
self._handlers = { 'table_start' : self.table_start,
'table_end' : self.table_end,
'tr_start' : self.tr_start,
'tr_end' : self.tr_end,
'td_start' : self.td_start,
'td_end' : self.td_end,
'th_start' : self.td_start,
'th_end' : self.td_end,
'br_start' : self.br_start,
'meta_start' : self.meta_start }
def read(self, htmlfile, populator):
self.populator = populator
self.state = self.IGNORE
self.current_row = None
self.current_cell = None
for line in htmlfile.readlines():
self.feed(line)
# Calling close is required by the HTMLParser but may cause problems
# if the same instance of our HtmlParser is reused. Currently it's
# used only once so there's no problem.
self.close()
self.populator.eof()
def handle_starttag(self, tag, attrs):
handler = self._handlers.get(tag+'_start')
if handler is not None:
handler(attrs)
def handle_endtag(self, tag):
handler = self._handlers.get(tag+'_end')
if handler is not None:
handler()
def handle_data(self, data, decode=True):
if self.state == self.IGNORE or self.current_cell is None:
return
if decode:
data = data.decode(self._encoding)
self.current_cell.append(data)
def handle_entityref(self, name):
value = self._handle_entityref(name)
self.handle_data(value, decode=False)
def _handle_entityref(self, name):
if extra_entitydefs.has_key(name):
return extra_entitydefs[name]
try:
value = entitydefs[name]
except KeyError:
return '&'+name+';'
if value.startswith('&#'):
return unichr(int(value[2:-1]))
return value.decode('ISO-8859-1')
def handle_charref(self, number):
value = self._handle_charref(number)
self.handle_data(value, decode=False)
def _handle_charref(self, number):
try:
return unichr(int(number))
except ValueError:
return '&#'+number+';'
def handle_pi(self, data):
encoding = self._get_encoding_from_pi(data)
if encoding:
self._encoding = encoding
def unknown_decl(self, data):
# Ignore everything even if it's invalid. This kind of stuff comes
# at least from MS Excel
pass
def table_start(self, attrs=None):
self.state = self.INITIAL
self.current_row = None
self.current_cell = None
def table_end(self):
if self.current_row is not None:
self.tr_end()
self.state = self.IGNORE
def tr_start(self, attrs=None):
if self.current_row is not None:
self.tr_end()
self.current_row = []
def tr_end(self):
if self.current_row is None:
return
if self.current_cell is not None:
self.td_end()
if self.state == self.INITIAL:
if len(self.current_row) > 0:
if self.populator.start_table(self.current_row):
self.state = self.PROCESS
else:
self.state = self.IGNORE
else:
self.state = self.IGNORE
elif self.state == self.PROCESS:
self.populator.add(self.current_row)
self.current_row = None
def td_start(self, attrs=None):
if self.current_cell is not None:
self.td_end()
if self.current_row is None:
self.tr_start()
self.current_cell = []
def td_end(self):
if self.current_cell is not None and self.state != self.IGNORE:
cell = ''.join(self.current_cell)
self.current_row.append(cell)
self.current_cell = None
def br_start(self, attrs=None):
if self.current_cell is not None and self.state != self.IGNORE:
self.current_cell.append('\n')
def meta_start(self, attrs):
encoding = self._get_encoding_from_meta(attrs)
if encoding:
self._encoding = encoding
def _get_encoding_from_meta(self, attrs):
valid_http_equiv = False
encoding = None
for name, value in attrs:
name = name.lower()
if name == 'http-equiv' and value.lower() == 'content-type':
valid_http_equiv = True
if name == 'content':
for token in value.split(';'):
token = token.strip()
if token.lower().startswith('charset='):
encoding = token[8:]
return valid_http_equiv and encoding or None
def _get_encoding_from_pi(self, data):
data = data.strip()
if not data.lower().startswith('xml '):
return None
if data.endswith('?'):
data = data[:-1]
for token in data.split():
if token.lower().startswith('encoding='):
encoding = token[9:]
if encoding.startswith("'") or encoding.startswith('"'):
encoding = encoding[1:-1]
return encoding
return None
# Workaround for following bug in Python 2.6: http://bugs.python.org/issue3932
if sys.version_info[:2] > (2, 5):
def unescape_from_py25(self, s):
if '&' not in s:
return s
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("'", "'")
s = s.replace(""", '"')
s = s.replace("&", "&") # Must be last
return s
HTMLParser.HTMLParser.unescape = unescape_from_py25
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# TODO: Various tasks
# - Rename this module so that it is not confused with standard json module
# - Consider moving under utils
# - Cleanup
def encode_basestring(string):
def get_matching_char(c):
val = ord(c)
if val < 127 and val > 31:
return c
return '\\u' + hex(val)[2:].rjust(4,'0')
# TODO: Our log doesn't contain all these control chars
string = string.replace('\\', '\\\\')
string = string.replace('"', '\\"')
string = string.replace('\b', '\\b')
string = string.replace('\f', '\\f')
string = string.replace('\n', '\\n')
string = string.replace('\r', '\\r')
string = string.replace('\t', '\\t')
return '"%s"' % ''.join(get_matching_char(c) for c in string)
def json_dump(data, output, mappings=None):
if data is None:
output.write('null')
elif isinstance(data, dict):
output.write('{')
for index, key in enumerate(data):
json_dump(key, output, mappings)
output.write(':')
json_dump(data[key], output, mappings)
if index < len(data)-1:
output.write(',')
output.write('}')
elif isinstance(data, (list, tuple)):
output.write('[')
for index, item in enumerate(data):
json_dump(item, output, mappings)
if index < len(data)-1:
output.write(',')
output.write(']')
elif mappings and data in mappings:
output.write(mappings[data])
elif isinstance(data, (int, long)):
output.write(str(data))
elif isinstance(data, basestring):
output.write(encode_basestring(data))
else:
raise Exception('Data type (%s) serialization not supported' % type(data))
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot import utils
class XUnitWriter:
"""Provides an xUnit-compatible result file.
Attempts to adhere to the de facto schema guessed by Peter Reilly, see:
http://marc.info/?l=ant-dev&m=123551933508682
"""
def __init__(self, output):
self._writer = utils.XmlWriter(output)
self._root_suite = None
self._detail_serializer = _NopSerializer()
def close(self):
self._writer.close()
def start_suite(self, suite):
if self._root_suite:
return
self._root_suite = suite
attrs = {'name': suite.name,
'tests': str(suite.get_test_count()),
'errors': '0',
'failures': str(suite.all_stats.failed),
'skip': '0'}
self._writer.start('testsuite', attrs)
def end_suite(self, suite):
if suite is self._root_suite:
self._writer.end('testsuite')
def start_test(self, test):
attrs = {'classname': test.parent.get_long_name(),
'name': test.name,
'time': self._time_as_seconds(test.elapsedtime)}
self._writer.start('testcase', attrs)
if test.status == 'FAIL':
self._detail_serializer = _FailedTestSerializer(self._writer, test)
def _time_as_seconds(self, millis):
return str(int(round(millis, -3) / 1000))
def end_test(self, test):
self._detail_serializer.end_test()
self._detail_serializer = _NopSerializer()
self._writer.end('testcase')
def start_keyword(self, kw):
pass
def end_keyword(self, kw):
pass
def message(self, msg):
self._detail_serializer.message(msg)
class _FailedTestSerializer:
"""Specific policy to serialize a failed test case details"""
def __init__(self, writer, test):
self._writer = writer
self._writer.start('failure',
{'message': test.message, 'type': 'AssertionError'})
def end_test(self):
self._writer.end('failure')
def message(self, msg):
"""Populates the <failure> section, normally only with a 'Stacktrace'.
There is a weakness here because filtering is based on message level:
- DEBUG level is used by RF for 'Tracebacks' (what is expected here)
- INFO and TRACE are used for keywords and arguments (not errors)
- first FAIL message is already reported as <failure> attribute
"""
if msg.level == 'DEBUG':
self._writer.content(msg.message)
class _NopSerializer:
"""Default policy when there's no detail to serialize"""
def end_test(self):
pass
def message(self, msg):
pass
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot.common import Statistics
from robot.output import LOGGER, process_outputs
from outputwriter import OutputWriter
from xunitwriter import XUnitWriter
from builders import LogBuilder, ReportBuilder, XUnitBuilder, OutputBuilder
import jsparser
class ResultWriter(object):
def __init__(self, settings):
self._xml_result = None
self._suite = None
self._settings = settings
def write_robot_results(self, data_source):
data_model = jsparser.create_datamodel_from(data_source)
LogBuilder(data_model, self._settings).build()
ReportBuilder(data_model, self._settings).build()
XUnitBuilder(self._result_from_xml([data_source]),
self._settings).build()
def _result_from_xml(self, data_sources):
if not self._xml_result:
self._suite, errs = process_outputs(data_sources, self._settings)
self._suite.set_options(self._settings)
self._xml_result = ResultFromXML(self._suite, errs, self._settings)
return self._xml_result
def write_rebot_results(self, *data_sources):
builder = OutputBuilder(self._result_from_xml(data_sources),
self._settings)
self.write_robot_results(builder.build())
builder.finalize()
return self._suite
class ResultFromXML(object):
def __init__(self, suite, exec_errors, settings=None):
self.suite = suite
self.exec_errors = exec_errors
if settings:
params = (settings['SuiteStatLevel'], settings['TagStatInclude'],
settings['TagStatExclude'], settings['TagStatCombine'],
settings['TagDoc'], settings['TagStatLink'])
else:
params = ()
self.statistics = Statistics(suite, *params)
self._generator = 'Robot'
def serialize_output(self, path, log=True):
if path == 'NONE':
return
serializer = OutputWriter(path)
self.suite.serialize(serializer)
self.statistics.serialize(serializer)
self.exec_errors.serialize(serializer)
serializer.close()
if log:
LOGGER.output_file('Output', path)
def serialize_xunit(self, path):
if path == 'NONE':
return
serializer = XUnitWriter(path)
try:
self.suite.serialize(serializer)
finally:
serializer.close()
LOGGER.output_file('XUnit', path)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import zlib
import base64
from operator import itemgetter
from robot import utils
class _Handler(object):
def __init__(self, context, attrs=None):
self._context = context
self._data_from_children = []
self._handlers = {
'robot' : _RobotHandler,
'suite' : _SuiteHandler,
'test' : _TestHandler,
'statistics' : _StatisticsHandler,
'stat' : _StatItemHandler,
'errors' : _Handler,
'doc' : _HtmlTextHandler,
'kw' : _KeywordHandler,
'arg' : _ArgumentHandler,
'arguments' : _ArgumentsHandler,
'tag' : _TextHandler,
'tags' : _Handler,
'msg' : _MsgHandler,
'status' : _StatusHandler,
'metadata' : _MetadataHandler,
'item' : _MetadataItemHandler,
}
def get_handler_for(self, name, attrs):
return self._handlers[name](self._context, attrs)
def add_child_data(self, data):
self._data_from_children.append(data)
def end_element(self, text):
return self._data_from_children
def _get_id(self, item):
return self._context.get_id(item)
def _get_ids(self, items):
return [self._context.get_id(i) for i in items]
class RootHandler(_Handler):
# TODO: Combine _RootHandler and _RobotHandler
@property
def data(self):
return self._data_from_children[0]
class _RobotHandler(_Handler):
def __init__(self, context, attrs):
_Handler.__init__(self, context)
self._generator = attrs.get('generator')
def end_element(self, text):
return {'generator': self._generator,
'suite': self._data_from_children[0],
'stats': self._data_from_children[1],
'errors': self._data_from_children[2],
'baseMillis': self._context.basemillis,
'strings': self._context.dump_texts()}
class _SuiteHandler(_Handler):
def __init__(self, context, attrs):
_Handler.__init__(self, context)
self._name = attrs.get('name')
self._source = attrs.get('source') or ''
self._suites = []
self._tests = []
self._keywords = []
self._current_children = None
self._context.start_suite(self._name)
self._context.collect_stats()
def get_handler_for(self, name, attrs):
self._current_children = {
'suite': self._suites,
'test': self._tests,
'kw': self._keywords
}.get(name, self._data_from_children)
return _Handler.get_handler_for(self, name, attrs)
def add_child_data(self, data):
self._current_children.append(data)
def end_element(self, text):
result = self._get_ids([self._source, self._name]) + \
self._data_from_children + [self._suites] + \
[self._tests] + [self._keywords] + \
[self._get_ids(self._context.dump_stats())]
self._context.end_suite()
return result
class _TestHandler(_Handler):
def __init__(self, context, attrs):
_Handler.__init__(self, context)
self._name = attrs.get('name')
self._timeout = attrs.get('timeout')
self._keywords = []
self._current_children = None
self._context.start_test(self._name)
def get_handler_for(self, name, attrs):
if name == 'status':
# TODO: Use 1/0 instead of Y/N. Possibly also 1/0/-1 instead of P/F/N.
self._critical = 'Y' if attrs.get('critical') == 'yes' else 'N'
self._current_children = {
'kw': self._keywords
}.get(name, self._data_from_children)
return _Handler.get_handler_for(self, name, attrs)
def add_child_data(self, data):
self._current_children.append(data)
def end_element(self, text):
result = self._get_ids([self._name, self._timeout, self._critical]) + \
self._data_from_children + [self._keywords]
# TODO: refactor
self._context.add_test(self._critical == 'Y', result[-2][0] == self._get_id('P'))
self._context.end_test()
return result
class _KeywordHandler(_Handler):
def __init__(self, context, attrs):
_Handler.__init__(self, context)
self._context.start_keyword()
self._type = attrs.get('type')
if self._type == 'for': self._type = 'forloop'
self._name = attrs.get('name')
self._timeout = attrs.get('timeout')
self._keywords = []
self._messages = []
self._current_children = None
def get_handler_for(self, name, attrs):
if name == 'status':
# TODO: Use 1/0 instead of Y/N. Possibly also 1/0/-1 instead of P/F/N.
self._critical = 'Y' if attrs.get('critical') == 'yes' else 'N'
self._current_children = {
'kw': self._keywords,
'msg': self._messages
}.get(name, self._data_from_children)
return _Handler.get_handler_for(self, name, attrs)
def add_child_data(self, data):
self._current_children.append(data)
def end_element(self, text):
if self._type == 'teardown' and self._data_from_children[-1][0] == self._get_id('F'):
self._context.teardown_failed()
self._context.end_keyword()
return self._get_ids([self._type, self._name, self._timeout]) + \
self._data_from_children + [self._keywords] + [self._messages]
# TODO: StatisticsHandler and StatItemHandler should be separated somehow from suite handlers
class _StatisticsHandler(_Handler):
def get_handler_for(self, name, attrs):
return _Handler(self._context, attrs)
class _StatItemHandler(_Handler):
def __init__(self, context, attrs):
_Handler.__init__(self, context)
self._attrs = dict(attrs)
self._attrs['pass'] = int(self._attrs['pass'])
self._attrs['fail'] = int(self._attrs['fail'])
if 'doc' in self._attrs:
self._attrs['doc'] = utils.html_format(self._attrs['doc'])
# TODO: Should we only dump attrs that have value?
# Tag stats have many attrs that are normally empty
def end_element(self, text):
self._attrs.update(label=text)
return self._attrs
class _StatusHandler(_Handler):
def __init__(self, context, attrs):
self._context = context
self._status = attrs.get('status')[0]
self._starttime = self._context.timestamp(attrs.get('starttime'))
endtime = self._context.timestamp(attrs.get('endtime'))
self._elapsed = self._calculate_elapsed(endtime)
def _calculate_elapsed(self, endtime):
# Both start and end may be 0 so must compare against None
if self._starttime is None or endtime is None:
return None
return endtime - self._starttime
def end_element(self, text):
result = [self._status,
self._starttime,
self._elapsed]
if text:
result.append(text)
return self._get_ids(result)
class _ArgumentHandler(_Handler):
def end_element(self, text):
return text
class _ArgumentsHandler(_Handler):
def end_element(self, text):
return self._get_id(', '.join(self._data_from_children))
class _TextHandler(_Handler):
def end_element(self, text):
return self._get_id(text)
class _HtmlTextHandler(_Handler):
def end_element(self, text):
return self._get_id(utils.html_format(text))
class _MetadataHandler(_Handler):
def __init__(self, context, attrs):
_Handler.__init__(self, context)
self._metadata = []
def add_child_data(self, data):
self._metadata.extend(data)
def end_element(self, text):
return self._metadata
class _MetadataItemHandler(_Handler):
def __init__(self, context, attrs):
_Handler.__init__(self, context)
self._name = attrs.get('name')
def end_element(self, text):
return self._get_ids([self._name, utils.html_format(text)])
class _MsgHandler(_Handler):
def __init__(self, context, attrs):
_Handler.__init__(self, context)
self._msg = [self._context.timestamp(attrs.get('timestamp')),
attrs.get('level')[0]]
self._is_html = attrs.get('html')
self._is_linkable = attrs.get("linkable") == "yes"
def end_element(self, text):
self._msg.append(text if self._is_html else utils.html_escape(text))
self._handle_warning_linking()
return self._get_ids(self._msg)
def _handle_warning_linking(self):
# TODO: should perhaps use the id version of this list for indexing?
if self._is_linkable:
self._msg.append(self._context.link_to(self._msg))
elif self._msg[1] == 'W':
self._context.create_link_to_current_location(self._msg)
class Context(object):
def __init__(self):
self._texts = TextCache()
self._basemillis = 0
self._stats = Stats()
self._current_place = []
self._kw_index = []
self._links = {}
@property
def basemillis(self):
return self._basemillis
def collect_stats(self):
self._stats = self._stats.new_child()
return self
def dump_stats(self):
try:
return self._stats.dump()
finally:
self._stats = self._stats.parent
def get_id(self, value):
if value is None:
return None
if isinstance(value, basestring):
return self._get_text_id(value)
if isinstance(value, (int, long)):
return value
raise AssertionError('Unsupported type of value '+str(type(value)))
def _get_text_id(self, text):
return self._texts.add(text)
def dump_texts(self):
return self._texts.dump()
def timestamp(self, time):
if time == 'N/A':
return None
millis = int(utils.timestamp_to_secs(time, millis=True) * 1000)
if not self._basemillis:
self._basemillis = millis
return millis - self.basemillis
def start_suite(self, name):
self._current_place.append(('suite', name))
self._kw_index.append(0)
def end_suite(self):
self._current_place.pop()
self._kw_index.pop()
def start_test(self, name):
self._current_place.append(('test', name))
self._kw_index.append(0)
def end_test(self):
self._current_place.pop()
self._kw_index.pop()
def start_keyword(self):
self._current_place.append(('keyword', self._kw_index[-1]))
self._kw_index[-1] += 1
self._kw_index.append(0)
def end_keyword(self):
self._current_place.pop()
self._kw_index.pop()
def create_link_to_current_location(self, key):
self._links[tuple(key)] = self._create_link()
def _create_link(self):
return "keyword_"+".".join(str(v) for _, v in self._current_place)
def link_to(self, key):
return self._links[tuple(key)]
def add_test(self, critical, passed):
self._stats.add_test(critical, passed)
def teardown_failed(self):
self._stats.fail_all()
class Stats(object):
TOTAL = 0
TOTAL_PASSED = 1
CRITICAL = 2
CRITICAL_PASSED = 3
def __init__(self, parent=None):
self.parent = parent
self._stats = [0,0,0,0]
self._children = []
def new_child(self):
self._children.append(Stats(self))
return self._children[-1]
def add_test(self, critical, passed):
self._stats[Stats.TOTAL] += 1
if passed:
self._stats[Stats.TOTAL_PASSED] +=1
if critical:
self._stats[Stats.CRITICAL] += 1
if passed:
self._stats[Stats.CRITICAL_PASSED] += 1
def dump(self):
if self.parent:
for i in range(4):
self.parent._stats[i] += self._stats[i]
return self._stats
def fail_all(self):
self._stats[1] = 0
self._stats[3] = 0
for child in self._children:
child.fail_all()
class TextIndex(int):
pass
ZERO_TEXT_INDEX = TextIndex(0)
class TextCache(object):
# TODO: Tune compressing thresholds
_compress_threshold = 20
_use_compressed_threshold = 1.1
def __init__(self):
self.texts = {'*': ZERO_TEXT_INDEX}
self.index = 1
def add(self, text):
if not text:
return 0
text = self._encode(text)
if text not in self.texts:
self.texts[text] = TextIndex(self.index)
self.index += 1
return self.texts[text]
def _encode(self, text):
raw = self._raw(text)
if raw in self.texts or len(raw) < self._compress_threshold:
return raw
compressed = self._compress(text)
if len(compressed) * self._use_compressed_threshold < len(raw):
return compressed
return raw
def _compress(self, text):
return base64.b64encode(zlib.compress(text.encode('UTF-8'), 9))
def _raw(self, text):
return '*'+text
def dump(self):
# TODO: Could we yield or return an iterator?
# TODO: Duplicate with IntegerCache.dump
return [item[0] for item in sorted(self.texts.iteritems(),
key=itemgetter(1))]
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import with_statement
import os
import re
import codecs
import tempfile
import robot
from robot.output import LOGGER
from robot import utils
WEBCONTENT_PATH = os.path.join(os.path.dirname(robot.__file__), 'webcontent')
class _Builder(object):
def __init__(self, data, settings):
self._settings = settings
self._data = data
self._path = self._parse_file(self._type)
def build(self):
raise NotImplementedError(self.__class__.__name__)
def _parse_file(self, name):
value = self._settings[name]
return value if value != 'NONE' else None
class OutputBuilder(_Builder):
_type = 'Output'
_temp_file = None
def build(self):
output_file = self._output_file()
self._data.serialize_output(output_file, log=not self._temp_file)
return output_file
def _output_file(self):
if self._path:
return self._path
handle, output_file = tempfile.mkstemp(suffix='.xml', prefix='rebot-')
os.close(handle)
self._temp_file = output_file
return output_file
def finalize(self):
if self._temp_file:
os.remove(self._temp_file)
class XUnitBuilder(_Builder):
_type = 'XUnitFile'
def build(self):
if self._path:
self._data.serialize_xunit(self._path)
class _HTMLFileBuilder(_Builder):
_type = NotImplemented
def build(self):
if self._path:
self._data.set_settings(self._get_settings())
self._build()
LOGGER.output_file(self._type, self._path)
def _url_from_path(self, source, destination):
if not destination:
return None
return utils.get_link_path(destination, os.path.dirname(source))
def _write_file(self):
with codecs.open(self._path, 'w', encoding='UTF-8') as outfile:
writer = HTMLFileWriter(outfile, self._data)
with open(self._template, 'r') as tmpl:
for line in tmpl:
writer.line(line)
class LogBuilder(_HTMLFileBuilder):
_type = 'Log'
_template = os.path.join(WEBCONTENT_PATH,'log.html')
def _build(self):
self._write_file()
def _get_settings(self):
return {
'title': self._settings['LogTitle'],
'reportURL': self._url_from_path(self._path,
self._parse_file('Report'))
}
class ReportBuilder(_HTMLFileBuilder):
_type = 'Report'
_template = os.path.join(WEBCONTENT_PATH, 'report.html')
def _build(self):
self._data.remove_errors()
self._data.remove_keywords()
self._write_file()
def _get_settings(self):
return {
'title': self._settings['ReportTitle'],
'background' : self._resolve_background_colors(),
'logURL': self._url_from_path(self._path,
self._parse_file('Log'))
}
def _resolve_background_colors(self):
color_str = self._settings['ReportBackground']
if color_str and color_str.count(':') not in [1, 2]:
LOGGER.error("Invalid background color '%s'." % color_str)
color_str = None
if not color_str:
color_str = '#99FF66:#FF3333'
colors = color_str.split(':', 2)
if len(colors) == 2:
colors.insert(1, colors[0])
return {'pass': colors[0], 'nonCriticalFail': colors[1], 'fail': colors[2]}
class HTMLFileWriter(object):
_js_file_matcher = re.compile('src=\"([^\"]+)\"')
_css_file_matcher = re.compile('href=\"([^\"]+)\"')
_css_media_matcher = re.compile('media=\"([^\"]+)\"')
def __init__(self, outfile, output):
self._outfile = outfile
self._output = output
def line(self, line):
if self._is_output_js(line):
self._write_output_js()
elif self._is_js_line(line):
self._inline_js_file(line)
elif self._is_css_line(line):
self._inline_css_file(line)
else:
self._write(line)
def _is_output_js(self, line):
return line.startswith('<!-- OUTPUT JS -->')
def _is_css_line(self, line):
return line.startswith('<link rel')
def _is_js_line(self, line):
return line.startswith('<script type="text/javascript" src=')
def _write_output_js(self):
separator = '</script>\n<script type="text/javascript">\n'
self._write_tag('script', 'type="text/javascript"',
lambda: self._output.write_to(self._outfile, separator))
def _inline_js_file(self, line):
self._write_tag('script', 'type="text/javascript"',
lambda: self._inline_file(line, self._js_file_matcher))
def _inline_css_file(self, line):
attrs = 'type="text/css" media="%s"' % self._parse_css_media_type(line)
self._write_tag('style', attrs,
lambda: self._inline_file(line, self._css_file_matcher))
def _parse_css_media_type(self, line):
return self._css_media_matcher.search(line).group(1)
def _inline_file(self, line, filename_matcher):
file_name = self._file_name(line, filename_matcher)
self._write_file_content(file_name)
def _file_name(self, line, filename_regexp):
return self._relative_path(filename_regexp.search(line).group(1))
def _relative_path(self, filename):
return os.path.join(WEBCONTENT_PATH, filename.replace('/', os.path.sep))
def _write(self, content):
self._outfile.write(content)
def _write_tag(self, tag_name, attrs, content_writer):
self._write('<%s %s>\n' % (tag_name, attrs))
content_writer()
self._write('</%s>\n\n' % tag_name)
def _write_file_content(self, source):
with codecs.open(source, 'r', encoding='UTF-8') as content:
for line in content:
self._write(line)
self._write('\n')
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
from robot import utils
import json
from robot.result.elementhandlers import TextIndex
class DataModel(object):
def __init__(self, robot_data):
self._robot_data = robot_data
self._settings = None
self._set_generated(time.localtime())
def _set_generated(self, timetuple):
genMillis = long(time.mktime(timetuple) * 1000) -\
self._robot_data['baseMillis']
self._set_attr('generatedMillis', genMillis)
self._set_attr('generatedTimestamp',
utils.format_time(timetuple, gmtsep=' '))
def _set_attr(self, name, value):
self._robot_data[name] = value
def set_settings(self, settings):
self._settings = settings
def write_to(self, output, separator='', split_threshold=9500):
output.write('window.output = {};\n')
output.write(separator)
for key, value in self._robot_data.items():
self._write_output_element(key, output, separator, split_threshold, value)
output.write(separator)
self._dump_json('window.settings = ', self._settings, output)
def _write_output_element(self, key, output, separator, split_threshold, value):
if key == 'suite':
splitWriter = SplittingSuiteWriter(self, output, separator,
split_threshold)
data, mapping = splitWriter.write(self._robot_data['suite'])
self._dump_json('window.output["suite"] = ', data, output, mapping)
elif key in ['integers', 'strings']:
self._dump_and_split_list(key, output, separator, split_threshold)
else:
self._dump_json('window.output["%s"] = ' % key, value, output)
def _dump_and_split_list(self, name, output, separator, split_threshold):
lst = self._robot_data[name]
output.write('window.output["%s"] = [];\n' % name)
while lst:
output.write(separator)
output.write('window.output["%s"] = window.output["%s"].concat(' % (name, name))
json.json_dump(lst[:split_threshold], output)
output.write(');\n')
lst = lst[split_threshold:]
def _dump_json(self, name, data, output, mappings=None):
output.write(name)
json.json_dump(data, output, mappings=mappings)
output.write(';\n')
def remove_keywords(self):
self._robot_data['suite'] = self._remove_keywords_from(self._robot_data['suite'])
self._prune_unused_indices()
# TODO: this and remove_keywords should be removed
# instead there should be a reportify or write_for_report_to method
def remove_errors(self):
self._robot_data.pop('errors')
def _remove_keywords_from(self, data):
if not isinstance(data, list):
return data
return [self._remove_keywords_from(item) for item in data
if not self._is_ignorable_keyword(item)]
def _is_ignorable_keyword(self, item):
# Top level teardown is kept to make tests fail if suite teardown failed
# TODO: Could we store information about failed suite teardown otherwise?
# TODO: Cleanup?
return item and \
isinstance(item, list) and \
(isinstance(item[0], TextIndex)) and \
self._robot_data['strings'][item[0]] in \
['*kw', '*setup', '*forloop', '*foritem']
def _prune_unused_indices(self):
used = self._collect_used_indices(self._robot_data['suite'], set())
remap = {}
self._robot_data['strings'] = \
list(self._prune(self._robot_data['strings'], used, remap))
self._remap_indices(self._robot_data['suite'], remap)
def _prune(self, data, used, index_remap, map_index=None, offset_increment=1):
offset = 0
for index, text in enumerate(data):
index = map_index(index) if map_index else index
if index in used:
index_remap[index] = index - offset
yield text
else:
offset += offset_increment
def _remap_indices(self, data, remap):
for i, item in enumerate(data):
if isinstance(item, TextIndex):
data[i] = remap[item]
elif isinstance(item, list):
self._remap_indices(item, remap)
def _collect_used_indices(self, data, result):
for item in data:
if isinstance(item, (int, long)):
result.add(item)
elif isinstance(item, list):
self._collect_used_indices(item, result)
elif isinstance(item, dict):
self._collect_used_indices(item.values(), result)
self._collect_used_indices(item.keys(), result)
return result
class _SubResult(object):
def __init__(self, data_block, size, mapping):
self.data_block = data_block
self.size = size
self.mapping = mapping
def update(self, subresult):
self.data_block += [subresult.data_block]
self.size += subresult.size
if subresult.mapping:
self.mapping.update(subresult.mapping)
def link(self, name):
key = object()
return _SubResult(key, 1, {key:name})
class SplittingSuiteWriter(object):
def __init__(self, writer, output, separator, split_threshold):
self._index = 0
self._output = output
self._writer = writer
self._separator = separator
self._split_threshold = split_threshold
def write(self, data_block):
result = self._write(data_block)
return result.data_block, result.mapping
def _write(self, data_block):
if not isinstance(data_block, list):
return _SubResult(data_block, 1, None)
result = _SubResult([], 1, {})
for item in data_block:
result.update(self._write(item))
if result.size > self._split_threshold:
result = self._dump_suite_part(result)
return result
def _list_name(self):
return 'window.sPart%s' % self._index
def _dump_suite_part(self, result):
self._writer._dump_json(self._list_name()+' = ', result.data_block, self._output, result.mapping)
self._write_separator()
new_result = result.link(self._list_name())
self._index += 1
return new_result
def _write_separator(self):
self._output.write(self._separator)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import with_statement
from xml import sax
from robot.result.elementhandlers import RootHandler, Context
from robot.result.jsondatamodel import DataModel
def create_datamodel_from(input_filename):
robot = _RobotOutputHandler(Context())
with open(input_filename, 'r') as input:
sax.parse(input, robot)
return robot.datamodel
def parse_js(input_filename, output):
create_datamodel_from(input_filename).write_to(output)
class _RobotOutputHandler(sax.handler.ContentHandler):
def __init__(self, context):
self._context = context
self._root_handler = RootHandler(context)
self._handler_stack = [self._root_handler]
@property
def datamodel(self):
return DataModel(self._root_handler.data)
def startElement(self, name, attrs):
handler = self._handler_stack[-1].get_handler_for(name, attrs)
self._charbuffer = []
self._handler_stack.append(handler)
def endElement(self, name):
handler = self._handler_stack.pop()
self._handler_stack[-1].add_child_data(handler.end_element(self.text))
def characters(self, content):
self._charbuffer += [content]
@property
def text(self):
return ''.join(self._charbuffer)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from resultwriter import ResultWriter
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot.output import XmlLogger
class OutputWriter(XmlLogger):
def __init__(self, path):
XmlLogger.__init__(self, path, generator='Rebot')
def message(self, msg):
self._write_message(msg)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Public logging API for test libraries.
This module provides a public API for writing messages to the log file
and the console. Test libraries can use this API like `logger.info('My
message')` instead of logging through the standard output like `print
'*INFO* My message'`. In addition to a programmatic interface being
cleaner to use, this API has a benefit that the log messages have
accurate timestamps.
Log levels
----------
It is possible to log messages using levels `TRACE`, `DEBUG`, `INFO`
and `WARN` either using the `write` method or, more commonly, with the
log level specific `trace`, `debug`, `info` and `warn` methods.
By default the trace and debug messages are not logged but that can be
changed with the `--loglevel` command line option. Warnings are
automatically written also to the `Test Execution Errors` section in
the log file and to the console.
Logging HTML
------------
All methods that are used for writing messages to the log file have an
optional `html` argument. If a message to be logged is supposed to be
shown as HTML, this argument should be set to `True`.
Example
-------
from robot.api import logger
def my_keyword(arg):
logger.debug('Got argument %s' % arg)
do_something()
logger.info('<i>This</i> is a boring example', html=True)
"""
import sys
from robot.output import LOGGER, Message
def write(msg, level, html=False):
"""Writes the message to the log file using the given level.
Valid log levels are `TRACE`, `DEBUG`, `INFO` and `WARN`. Instead
of using this method, it is generally better to use the level
specific methods such as `info` and `debug`.
"""
LOGGER.log_message(Message(msg, level, html))
def trace(msg, html=False):
"""Writes the message to the log file with the TRACE level."""
write(msg, 'TRACE', html)
def debug(msg, html=False):
"""Writes the message to the log file with the DEBUG level."""
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
"""Writes the message to the log file with the INFO level.
If `also_console` argument is set to `True`, the message is written
both to the log file and to the console.
"""
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
"""Writes the message to the log file with the WARN level."""
write(msg, 'WARN', html)
def console(msg, newline=True):
"""Writes the message to the console.
If the `newline` argument is `True`, a newline character is automatically
added to the message.
"""
if newline:
msg += '\n'
sys.__stdout__.write(msg)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import utils
# Return codes from Robot and Rebot.
# RC below 250 is the number of failed critical tests and exactly 250
# means that number or more such failures.
INFO_PRINTED = 251 # --help or --version
DATA_ERROR = 252 # Invalid data or cli args
STOPPED_BY_USER = 253 # KeyboardInterrupt or SystemExit
FRAMEWORK_ERROR = 255 # Unexpected error
class RobotError(Exception):
"""Base class for Robot Framework errors.
Do not raise this method but use more specific errors instead.
"""
def __init__(self, message=''):
Exception.__init__(self, message)
def __unicode__(self):
# Needed to handle exceptions w/ Unicode correctly on Python 2.5
return unicode(self.args[0]) if self.args else u''
class FrameworkError(RobotError):
"""Can be used when the core framework goes to unexpected state.
It is good to explicitly raise a FrameworkError if some framework
component is used incorrectly. This is pretty much same as
'Internal Error' and should of course never happen.
"""
class DataError(RobotError):
"""Used when the provided test data is invalid.
DataErrors are not be caught by keywords that run other keywords
(e.g. `Run Keyword And Expect Error`). Libraries should thus use
this exception with care.
"""
class TimeoutError(RobotError):
"""Used when a test or keyword timeout occurs.
This exception is handled specially so that execution of the
current test is always stopped immediately and it is not caught by
keywords executing other keywords (e.g. `Run Keyword And Expect
Error`). Libraries should thus NOT use this exception themselves.
"""
class Information(RobotError):
"""Used by argument parser with --help or --version."""
class ExecutionFailed(RobotError):
"""Used for communicating failures in test execution."""
def __init__(self, message, timeout=False, syntax=False, exit=False,
cont=False, exit_for_loop=False):
RobotError.__init__(self, utils.cut_long_message(message))
self.timeout = timeout
self.syntax = syntax
self.exit = exit
self.cont = cont
self.exit_for_loop = exit_for_loop
@property
def dont_cont(self):
return self.timeout or self.syntax or self.exit
# Python 2.6 property decorators would have nice `setter` attribute:
# http://docs.python.org/library/functions.html#property
cont = property(lambda self: self._cont and not self.dont_cont,
lambda self, cont: setattr(self, '_cont', cont))
def can_continue(self, teardown=False, templated=False, dry_run=False):
if dry_run:
return True
if self.dont_cont and not (teardown and self.syntax):
return False
if teardown or templated:
return True
return self.cont
def get_errors(self):
return [self]
class HandlerExecutionFailed(ExecutionFailed):
def __init__(self):
details = utils.ErrorDetails()
timeout = isinstance(details.error, TimeoutError)
syntax = isinstance(details.error, DataError)
exit = bool(getattr(details.error, 'ROBOT_EXIT_ON_FAILURE', False))
cont = bool(getattr(details.error, 'ROBOT_CONTINUE_ON_FAILURE', False))
exit_for_loop = bool(getattr(details.error, 'ROBOT_EXIT_FOR_LOOP', False))
ExecutionFailed.__init__(self, details.message, timeout, syntax,
exit, cont, exit_for_loop)
self.full_message = details.message
self.traceback = details.traceback
class ExecutionFailures(ExecutionFailed):
def __init__(self, errors):
msg = self._format_message([unicode(e) for e in errors])
ExecutionFailed.__init__(self, msg, **self._get_attrs(errors))
self._errors = errors
def _format_message(self, messages):
if len(messages) == 1:
return messages[0]
lines = ['Several failures occurred:'] \
+ ['%d) %s' % (i+1, m) for i, m in enumerate(messages)]
return '\n\n'.join(lines)
def _get_attrs(self, errors):
return {'timeout': any(err.timeout for err in errors),
'syntax': any(err.syntax for err in errors),
'exit': any(err.exit for err in errors),
'cont': all(err.cont for err in errors),
'exit_for_loop': all(err.exit_for_loop for err in errors)}
def get_errors(self):
return self._errors
class UserKeywordExecutionFailed(ExecutionFailures):
def __init__(self, run_errors=None, teardown_errors=None):
no_errors = ExecutionFailed('', cont=True, exit_for_loop=True)
ExecutionFailures.__init__(self, [run_errors or no_errors,
teardown_errors or no_errors])
if run_errors and not teardown_errors:
self._errors = run_errors.get_errors()
else:
self._errors = [self]
def _format_message(self, messages):
run_msg, td_msg = messages
if not td_msg:
return run_msg
if not run_msg:
return 'Keyword teardown failed:\n%s' % td_msg
return '%s\n\nAlso keyword teardown failed:\n%s' % (run_msg, td_msg)
class RemoteError(RobotError):
"""Used by Remote library to report remote errors."""
def __init__(self, message, traceback):
RobotError.__init__(self, message)
self.traceback = traceback
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from robot import utils
from robot.errors import DataError, FrameworkError
from robot.output import LOGGER
class _BaseSettings(object):
_cli_opts = {'Name' : ('name', None),
'Doc' : ('doc', None),
'Metadata' : ('metadata', []),
'TestNames' : ('test', []),
'SuiteNames' : ('suite', []),
'SetTag' : ('settag', []),
'Include' : ('include', []),
'Exclude' : ('exclude', []),
'Critical' : ('critical', None),
'NonCritical' : ('noncritical', None),
'OutputDir' : ('outputdir', '.'),
'Log' : ('log', 'log.html'),
'Report' : ('report', 'report.html'),
'Summary' : ('summary', 'NONE'),
'XUnitFile' : ('xunitfile', 'NONE'),
'SplitOutputs' : ('splitoutputs', -1),
'TimestampOutputs' : ('timestampoutputs', False),
'LogTitle' : ('logtitle', None),
'ReportTitle' : ('reporttitle', None),
'SummaryTitle' : ('summarytitle', None),
'ReportBackground' : ('reportbackground', None),
'SuiteStatLevel' : ('suitestatlevel', -1),
'TagStatInclude' : ('tagstatinclude', []),
'TagStatExclude' : ('tagstatexclude', []),
'TagStatCombine' : ('tagstatcombine', []),
'TagDoc' : ('tagdoc', []),
'TagStatLink' : ('tagstatlink', []),
'NoStatusRC' : ('nostatusrc', False),
'RunEmptySuite' : ('runemptysuite', False),
'MonitorWidth' : ('monitorwidth', 78),
'MonitorColors' : ('monitorcolors', 'AUTO')}
_output_opts = ['Output', 'Log', 'Report', 'Summary', 'DebugFile', 'XUnitFile']
def __init__(self, options={}, log=True):
self._opts = {}
self._cli_opts.update(self._extra_cli_opts)
self._process_cli_opts(options, log)
if log: LOGGER.info('Settings:\n%s' % unicode(self))
def _process_cli_opts(self, opts, log):
for name, (cli_name, default) in self._cli_opts.items():
try:
value = opts[cli_name]
if value in [None, []]:
raise KeyError
except KeyError:
value = default
self[name] = self._process_value(name, value, log)
def __setitem__(self, name, value):
if name not in self._cli_opts:
raise KeyError("Non-existing settings '%s'" % name)
self._opts[name] = value
def _process_value(self, name, value, log):
if value in [None, []]:
return value
if name in ['Name', 'Doc', 'LogTitle', 'ReportTitle', 'SummaryTitle']:
if name == 'Doc': value = self._escape(value)
return value.replace('_', ' ')
if name in ['Metadata', 'TagDoc']:
if name == 'Metadata': value = [self._escape(v) for v in value]
return [self._process_metadata_or_tagdoc(v) for v in value]
if name in ['Include', 'Exclude']:
return [v.replace('AND', '&').replace('_', ' ') for v in value]
if name in self._output_opts and utils.eq(value, 'NONE'):
return 'NONE'
if name == 'OutputDir':
return utils.abspath(value)
if name in ['SuiteStatLevel', 'MonitorWidth']:
return self._convert_to_positive_integer_or_default(name, value)
if name in ['Listeners', 'VariableFiles']:
return [self._split_args_from_name(item) for item in value]
if name == 'TagStatCombine':
return [self._process_tag_stat_combine(v) for v in value]
if name == 'TagStatLink':
return [v for v in [self._process_tag_stat_link(v) for v in value] if v]
if name == 'RemoveKeywords':
return value.upper()
if name == 'SplitOutputs' and value != -1:
if log:
LOGGER.warn('Splitting outputs (--SplitOutputs option) is not '
'supported in Robot Framework 2.6 or newer. This '
'option will be removed altogether in version 2.7.')
return -1
return value
def __getitem__(self, name):
if name not in self._cli_opts:
raise KeyError("Non-existing setting '%s'" % name)
if name in self._output_opts:
return self._get_output_file(name)
return self._opts[name]
def _get_output_file(self, type_):
"""Returns path of the requested output file and creates needed dirs.
`type_` can be 'Output', 'Log', 'Report', 'Summary', 'DebugFile'
or 'XUnitFile'.
"""
name = self._opts[type_]
if self._outputfile_disabled(type_, name):
return 'NONE'
name = self._process_output_name(name, type_)
path = utils.abspath(os.path.join(self['OutputDir'], name))
self._create_output_dir(os.path.dirname(path), type_)
return path
def _process_output_name(self, name, type_):
base, ext = os.path.splitext(name)
if self['TimestampOutputs']:
base = '%s-%s' % (base, utils.get_start_timestamp('', '-', ''))
ext = self._get_output_extension(ext, type_)
return base + ext
def _get_output_extension(self, ext, type_):
if ext != '':
return ext
if type_ in ['Output', 'XUnitFile']:
return '.xml'
if type_ in ['Log', 'Report', 'Summary']:
return '.html'
if type_ == 'DebugFile':
return '.txt'
raise FrameworkError("Invalid output file type: %s" % type_)
def _create_output_dir(self, path, type_):
try:
if not os.path.exists(path):
os.makedirs(path)
except:
raise DataError("Can't create %s file's parent directory '%s': %s"
% (type_.lower(), path, utils.get_error_message()))
def _process_metadata_or_tagdoc(self, value):
value = value.replace('_', ' ')
if ':' in value:
return value.split(':', 1)
return value, ''
def _process_tag_stat_combine(self, value):
for replwhat, replwith in [('_', ' '), ('AND', '&'),
('&', ' & '), ('NOT', ' NOT ')]:
value = value.replace(replwhat, replwith)
if ':' in value:
return value.rsplit(':', 1)
return value, ''
def _process_tag_stat_link(self, value):
tokens = value.split(':')
if len(tokens) >= 3:
return tokens[0], ':'.join(tokens[1:-1]), tokens[-1]
LOGGER.error("Invalid format for option '--tagstatlink'. "
"Expected 'tag:link:title' but got '%s'." % value)
return None
def _convert_to_positive_integer_or_default(self, name, value):
value = self._convert_to_integer(name, value)
return value if value > 0 else self._get_default_value(name)
def _convert_to_integer(self, name, value):
try:
return int(value)
except ValueError:
LOGGER.error("Option '--%s' expected integer value but got '%s'. "
"Default value used instead." % (name.lower(), value))
return self._get_default_value(name)
def _get_default_value(self, name):
return self._cli_opts[name][1]
def _split_args_from_name(self, name):
if ':' not in name or os.path.exists(name):
return name, []
args = name.split(':')
name = args.pop(0)
# Handle absolute Windows paths with arguments
if len(name) == 1 and args[0].startswith(('/', '\\')):
name = name + ':' + args.pop(0)
return name, args
def __contains__(self, setting):
return setting in self._cli_opts
def __unicode__(self):
return '\n'.join('%s: %s' % (name, self._opts[name])
for name in sorted(self._opts))
class RobotSettings(_BaseSettings):
_extra_cli_opts = {'Output' : ('output', 'output.xml'),
'LogLevel' : ('loglevel', 'INFO'),
'RunMode' : ('runmode', []),
'WarnOnSkipped' : ('warnonskippedfiles', False),
'Variables' : ('variable', []),
'VariableFiles' : ('variablefile', []),
'Listeners' : ('listener', []),
'DebugFile' : ('debugfile', 'NONE')}
def is_rebot_needed(self):
return not ('NONE' == self['Log'] == self['Report'] == self['Summary'] == self['XUnitFile'])
def get_rebot_datasource_and_settings(self):
datasource = self['Output']
settings = RebotSettings(log=False)
settings._opts.update(self._opts)
for name in ['Variables', 'VariableFiles', 'Listeners']:
del(settings._opts[name])
for name in ['Include', 'Exclude', 'TestNames', 'SuiteNames', 'Metadata']:
settings._opts[name] = []
for name in ['Output', 'RemoveKeywords']:
settings._opts[name] = 'NONE'
for name in ['Name', 'Doc']:
settings._opts[name] = None
settings._opts['LogLevel'] = 'TRACE'
return datasource, settings
def _outputfile_disabled(self, type_, name):
if name == 'NONE':
return True
return self._opts['Output'] == 'NONE' and type_ != 'DebugFile'
def _escape(self, value):
return utils.escape(value)
class RebotSettings(_BaseSettings):
_extra_cli_opts = {'Output' : ('output', 'NONE'),
'LogLevel' : ('loglevel', 'TRACE'),
'RemoveKeywords' : ('removekeywords', 'NONE'),
'StartTime' : ('starttime', 'N/A'),
'EndTime' : ('endtime', 'N/A')}
def _outputfile_disabled(self, type_, name):
return name == 'NONE'
def _escape(self, value):
return value
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from settings import RobotSettings, RebotSettings
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot import utils
from robot.errors import DataError
LEVELS = {
"NONE" : 100,
"ERROR" : 60,
"FAIL" : 50,
"WARN" : 40,
"INFO" : 30,
"DEBUG" : 20,
"TRACE" : 10,
}
class AbstractLogger:
def __init__(self, level='TRACE'):
self._is_logged = IsLogged(level)
def set_level(self, level):
return self._is_logged.set_level(level)
def trace(self, msg):
self.write(msg, 'TRACE')
def debug(self, msg):
self.write(msg, 'DEBUG')
def info(self, msg):
self.write(msg, 'INFO')
def warn(self, msg):
self.write(msg, 'WARN')
def fail(self, msg):
self.write(msg, 'FAIL')
def error(self, msg):
self.write(msg, 'ERROR')
def write(self, message, level, html=False):
self.message(Message(message, level, html))
def message(self, msg):
raise NotImplementedError(self.__class__)
class Message(object):
def __init__(self, message, level='INFO', html=False, timestamp=None, linkable=False):
self.message = self._get_message(message)
self.level, self.html = self._get_level_and_html(level, html)
self.timestamp = self._get_timestamp(timestamp)
self.linkable = linkable
def _get_message(self, msg):
if not isinstance(msg, basestring):
msg = utils.unic(msg)
return msg.replace('\r\n', '\n')
def _get_level_and_html(self, level, html):
level = level.upper()
if level == 'HTML':
return 'INFO', True
if level not in LEVELS:
raise DataError("Invalid log level '%s'" % level)
return level, html
def _get_timestamp(self, timestamp):
if timestamp:
return timestamp
return utils.get_timestamp(daysep='', daytimesep=' ',
timesep=':', millissep='.')
def get_timestamp(self, sep=' '):
return self.timestamp.replace(' ', sep)
@property
def time(self):
if ' ' not in self.timestamp:
return self.timestamp
return self.timestamp.split()[1]
class IsLogged:
def __init__(self, level):
self._str_level = level
self._int_level = self._level_to_int(level)
def __call__(self, level):
return self._level_to_int(level) >= self._int_level
def set_level(self, level):
old = self._str_level.upper()
self.__init__(level)
return old
def _level_to_int(self, level):
try:
return LEVELS[level.upper()]
except KeyError:
raise DataError("Invalid log level '%s'" % level)
class AbstractLoggerProxy:
_methods = NotImplemented
def __init__(self, logger):
self.logger = logger
default = lambda *args: None
for name in self._methods:
try:
method = getattr(logger, name)
except AttributeError:
method = getattr(logger, self._toCamelCase(name), default)
setattr(self, name, method)
def _toCamelCase(self, name):
parts = name.split('_')
return ''.join([parts[0]] + [part.capitalize() for part in parts[1:]])
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot import utils
from robot.errors import DataError
from robot.version import get_full_version
from loggerhelper import IsLogged
class XmlLogger:
def __init__(self, path, log_level='TRACE', generator='Robot'):
self._log_message_is_logged = IsLogged(log_level)
self._error_message_is_logged = IsLogged('WARN')
self._writer = None
self._writer_args = (path, {'generator': get_full_version(generator),
'generated': utils.get_timestamp()})
self._errors = []
def _get_writer(self, path, attrs={}):
try:
writer = utils.XmlWriter(path)
except:
raise DataError("Opening output file '%s' for writing failed: %s"
% (path, utils.get_error_message()))
writer.start('robot', attrs)
return writer
def _close_writer(self, writer):
if not writer.closed:
writer.end('robot')
writer.close()
def close(self):
self.start_errors()
for msg in self._errors:
self._write_message(msg)
self.end_errors()
self._close_writer(self._writer)
def message(self, msg):
if self._error_message_is_logged(msg.level):
self._errors.append(msg)
def log_message(self, msg):
if self._log_message_is_logged(msg.level):
self._write_message(msg)
def set_log_level(self, level):
return self._log_message_is_logged.set_level(level)
def _write_message(self, msg):
attrs = {'timestamp': msg.timestamp, 'level': msg.level}
if msg.html:
attrs['html'] = 'yes'
if msg.linkable:
attrs['linkable'] = 'yes'
self._writer.element('msg', msg.message, attrs)
def start_keyword(self, kw):
attrs = {'name': kw.name, 'type': kw.type, 'timeout': kw.timeout}
self._writer.start('kw', attrs)
self._writer.element('doc', kw.doc)
self._write_list('arg', [utils.unic(a) for a in kw.args], 'arguments')
def end_keyword(self, kw):
self._write_status(kw)
self._writer.end('kw')
def start_test(self, test):
attrs = {'name': test.name, 'timeout': str(test.timeout)}
self._writer.start('test', attrs)
self._writer.element('doc', test.doc)
def end_test(self, test):
self._write_list('tag', test.tags, 'tags')
self._write_status(test, test.message,
extra_attrs={'critical': test.critical})
self._writer.end('test')
def start_suite(self, suite):
if not self._writer:
self._writer = self._get_writer(*self._writer_args)
del self._writer_args
self._start_suite(suite)
def _start_suite(self, suite, extra_attrs=None):
attrs = extra_attrs is not None and extra_attrs or {}
attrs['name'] = suite.name
if suite.source:
attrs['source'] = suite.source
self._writer.start('suite', attrs)
self._writer.element('doc', suite.doc)
self._writer.start('metadata')
for name, value in suite.get_metadata():
self._writer.element('item', value, {'name': name})
self._writer.end('metadata')
def end_suite(self, suite):
self._write_status(suite, suite.message)
self._writer.end('suite')
def start_statistics(self, stats):
self._writer.start('statistics')
def end_statistics(self, stats):
self._writer.end('statistics')
def start_total_stats(self, total_stats):
self._writer.start('total')
def end_total_stats(self, total_stats):
self._writer.end('total')
def start_tag_stats(self, tag_stats):
self._writer.start('tag')
def end_tag_stats(self, tag_stats):
self._writer.end('tag')
def start_suite_stats(self, tag_stats):
self._writer.start('suite')
def end_suite_stats(self, tag_stats):
self._writer.end('suite')
def total_stat(self, stat):
self._stat(stat)
def suite_stat(self, stat):
self._stat(stat, stat.long_name, attrs={'name': stat.name})
def tag_stat(self, stat):
self._stat(stat, attrs={'info': self._get_tag_stat_info(stat),
'links': self._get_tag_links(stat),
'doc': stat.doc,
'combined': stat.combined})
def _get_tag_links(self, stat):
return ':::'.join(':'.join([title, url]) for url, title in stat.links)
def _stat(self, stat, name=None, attrs=None):
name = name or stat.name
attrs = attrs or {}
attrs['pass'] = str(stat.passed)
attrs['fail'] = str(stat.failed)
self._writer.element('stat', name, attrs)
def _get_tag_stat_info(self, stat):
if stat.critical:
return 'critical'
if stat.non_critical:
return 'non-critical'
if stat.combined:
return 'combined'
return ''
def start_errors(self):
self._writer.start('errors')
def end_errors(self):
self._writer.end('errors')
def _write_list(self, tag, items, container=None):
if container:
self._writer.start(container)
for item in items:
self._writer.element(tag, item)
if container:
self._writer.end(container)
def _write_status(self, item, message=None, extra_attrs=None):
attrs = {'status': item.status, 'starttime': item.starttime,
'endtime': item.endtime}
if extra_attrs:
attrs.update(extra_attrs)
self._writer.element('status', message, attrs)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot.common.statistics import Statistics
from loggerhelper import AbstractLogger
from logger import LOGGER
from xmllogger import XmlLogger
from listeners import Listeners
from debugfile import DebugFile
from stdoutlogsplitter import StdoutLogSplitter
class Output(AbstractLogger):
def __init__(self, settings):
AbstractLogger.__init__(self)
self._xmllogger = XmlLogger(settings['Output'], settings['LogLevel'])
self._register_loggers(settings['Listeners'], settings['DebugFile'])
self._settings = settings
self._set_global_output()
def _register_loggers(self, listeners, debugfile):
LOGGER.register_context_changing_logger(self._xmllogger)
for logger in Listeners(listeners), DebugFile(debugfile):
if logger: LOGGER.register_logger(logger)
LOGGER.disable_message_cache()
def _set_global_output(self):
# This is a hack. Hopefully we get rid of it at some point.
from robot import output
output.OUTPUT = self
def close(self, suite):
stats = Statistics(suite, self._settings['SuiteStatLevel'],
self._settings['TagStatInclude'],
self._settings['TagStatExclude'],
self._settings['TagStatCombine'],
self._settings['TagDoc'],
self._settings['TagStatLink'])
stats.serialize(self._xmllogger)
self._xmllogger.close()
LOGGER.unregister_logger(self._xmllogger)
LOGGER.output_file('Output', self._settings['Output'])
def start_suite(self, suite):
LOGGER.start_suite(suite)
def end_suite(self, suite):
LOGGER.end_suite(suite)
def start_test(self, test):
LOGGER.start_test(test)
def end_test(self, test):
LOGGER.end_test(test)
def start_keyword(self, kw):
LOGGER.start_keyword(kw)
def end_keyword(self, kw):
LOGGER.end_keyword(kw)
def log_output(self, output):
for msg in StdoutLogSplitter(output):
self.message(msg)
def message(self, msg):
LOGGER.log_message(msg)
def set_log_level(self, level):
return self._xmllogger.set_log_level(level)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from robot import utils
from highlighting import Highlighter, NoHighlighting
from loggerhelper import IsLogged
class CommandLineMonitor:
def __init__(self, width=78, colors='AUTO'):
self._width = width
self._highlighter = StatusHighlighter(colors)
self._is_logged = IsLogged('WARN')
self._started = False
def start_suite(self, suite):
if not self._started:
self._write_separator('=')
self._started = True
self._write_info(suite.longname, suite.doc, start_suite=True)
self._write_separator('=')
def end_suite(self, suite):
self._write_info(suite.longname, suite.doc)
self._write_status(suite.status)
self._write_message(suite.get_full_message())
self._write_separator('=')
def start_test(self, test):
self._write_info(test.name, test.doc)
def end_test(self, test):
self._write_status(test.status)
self._write_message(test.message)
self._write_separator('-')
def message(self, msg):
if self._is_logged(msg.level):
self._write_with_highlighting('[ ', msg.level, ' ] ' + msg.message,
stream=sys.__stderr__)
def output_file(self, name, path):
self._write('%-8s %s' % (name+':', path))
def _write_info(self, name, doc, start_suite=False):
maxwidth = self._width
if not start_suite:
maxwidth -= len(' | PASS |')
info = self._get_info(name, doc, maxwidth)
self._write(info, newline=start_suite)
def _get_info(self, name, doc, maxwidth):
if utils.get_console_length(name) > maxwidth:
return utils.pad_console_length(name, maxwidth, cut_left=True)
info = name if not doc else '%s :: %s' % (name, doc.splitlines()[0])
return utils.pad_console_length(info, maxwidth)
def _write_status(self, status):
self._write_with_highlighting(' | ', status, ' |')
def _write_message(self, message):
if message:
self._write(message.strip())
def _write_separator(self, sep_char):
self._write(sep_char * self._width)
def _write(self, message, newline=True, stream=sys.__stdout__):
if newline:
message += '\n'
stream.write(utils.encode_output(message).replace('\t', ' '*8))
stream.flush()
def _write_with_highlighting(self, before, highlighted, after,
newline=True, stream=sys.__stdout__):
self._write(before, newline=False, stream=stream)
self._highlighter.start(highlighted, stream)
self._write(highlighted, newline=False, stream=stream)
self._highlighter.end()
self._write(after, newline=newline, stream=stream)
class StatusHighlighter:
def __init__(self, colors):
self._current = None
self._highlighters = {
sys.__stdout__: self._get_highlighter(sys.__stdout__, colors),
sys.__stderr__: self._get_highlighter(sys.__stderr__, colors)
}
def start(self, message, stream=sys.__stdout__):
self._current = self._highlighters[stream]
{'PASS': self._current.green,
'FAIL': self._current.red,
'ERROR': self._current.red,
'WARN': self._current.yellow}[message]()
def end(self):
self._current.reset()
def _get_highlighter(self, stream, colors):
auto = hasattr(stream, 'isatty') and stream.isatty()
enable = {'AUTO': auto,
'ON': True,
'FORCE': True, # compatibility with 2.5.5 and earlier
'OFF': False}.get(colors.upper(), auto)
return Highlighter(stream) if enable else NoHighlighting(stream)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os.path
from robot import utils
from robot.errors import DataError
from robot.common import BaseTestSuite, BaseTestCase, BaseKeyword
from robot.output import LOGGER
from robot.output.loggerhelper import IsLogged, Message
def process_outputs(paths, settings):
if not paths:
raise DataError('No output files given.')
if len(paths) == 1:
return process_output(paths[0], log_level=settings['LogLevel'],
settings=settings)
suite = CombinedTestSuite(settings)
exec_errors = CombinedExecutionErrors()
for path in paths:
subsuite, suberrors = process_output(path, log_level=settings['LogLevel'])
suite.add_suite(subsuite)
exec_errors.add(suberrors)
return suite, exec_errors
def process_output(path, log_level=None, settings=None):
"""Process one output file and return TestSuite and ExecutionErrors"""
if not os.path.isfile(path):
raise DataError("Output file '%s' does not exist." % path)
LOGGER.info("Processing output file '%s'." % path)
try:
root = utils.etreewrapper.get_root(path)
except:
raise DataError("Opening XML file '%s' failed: %s"
% (path, utils.get_error_message()))
suite = TestSuite(_get_suite_node(root, path), log_level=log_level,
settings=settings)
errors = ExecutionErrors(_get_errors_node(root))
return suite, errors
def _get_suite_node(root, path):
if root.tag != 'robot':
raise DataError("File '%s' is not Robot Framework output file." % path)
node = root.find('suite')
node.set('generator', root.get('generator', 'notset').split()[0].lower())
node.set('path', path)
return node
def _get_errors_node(root):
return root.find('errors')
class _MissingStatus:
"""If XML was fixed for example by fixml.py, status tag may be missing"""
text = 'Could not find status.'
get = lambda self, name, default: name == 'status' and 'FAIL' or 'N/A'
class _BaseReader:
def __init__(self, node):
self.doc = self._get_doc(node)
stnode = node.find('status')
if stnode is None:
stnode = _MissingStatus()
self.status = stnode.get('status','').upper()
if self.status not in ['PASS','FAIL', 'NOT_RUN']:
raise DataError("Item '%s' has invalid status '%s'"
% (self.name, self.status))
self.message = stnode.text or ''
self.starttime = stnode.get('starttime', 'N/A')
self.endtime = stnode.get('endtime', 'N/A')
self.elapsedtime = utils.get_elapsed_time(self.starttime, self.endtime)
def _get_doc(self, node):
docnode = node.find('doc')
if docnode is not None:
return docnode.text or ''
return ''
class _TestAndSuiteReader(_BaseReader):
def __init__(self, node, log_level=None):
_BaseReader.__init__(self, node)
self.keywords = [Keyword(kw, log_level) for kw in node.findall('kw')]
if self.keywords and self.keywords[0].type == 'setup':
self.setup = self.keywords.pop(0)
if self.keywords and self.keywords[-1].type == 'teardown':
self.teardown = self.keywords.pop(-1)
class _SuiteReader(_TestAndSuiteReader):
def __init__(self, node, log_level=None):
_TestAndSuiteReader.__init__(self, node, log_level)
del(self.keywords)
for metanode in node.findall('metadata/item'):
self.metadata[metanode.get('name')] = metanode.text
def _get_texts(self, node, path):
return [item.text for item in node.findall(path)]
class _TestReader(_TestAndSuiteReader):
def __init__(self, node, log_level=None):
_TestAndSuiteReader.__init__(self, node, log_level)
self.tags = [tag.text for tag in node.findall('tags/tag')]
self.timeout = node.get('timeout', '')
class _KeywordReader(_BaseReader):
def __init__(self, node, log_level=None):
_BaseReader.__init__(self, node)
del(self.message)
self.args = [(arg.text or '') for arg in node.findall('arguments/arg')]
self.type = node.get('type', 'kw')
self.timeout = node.get('timeout', '')
self.keywords = []
self.messages = []
self.children = []
log_filter = IsLogged(log_level or 'TRACE')
for child in node:
if child.tag == 'kw':
kw = Keyword(child, log_level)
self.keywords.append(kw)
self.children.append(kw)
elif child.tag == 'msg' and log_filter(child.get('level', 'INFO')):
msg = MessageFromXml(child)
self.messages.append(msg)
self.children.append(msg)
class TestSuite(BaseTestSuite, _SuiteReader):
def __init__(self, node, parent=None, log_level=None, settings=None):
BaseTestSuite.__init__(self, node.get('name'),
node.get('source', None), parent)
_SuiteReader.__init__(self, node, log_level=log_level)
self._set_times_from_settings(settings)
for snode in node.findall('suite'):
snode.set('generator', node.get('generator'))
snode.set('path', node.get('path'))
TestSuite(snode, parent=self, log_level=log_level)
for tnode in node.findall('test'):
TestCase(tnode, parent=self, log_level=log_level)
self.set_status()
if node.get('generator') == 'robot' and \
self.teardown and self.teardown.status == 'FAIL':
self.suite_teardown_failed()
def _set_times_from_settings(self, settings):
starttime, endtime = self._times_from_settings(settings)
if not self.starttime or starttime != 'N/A':
self.starttime = starttime
if not self.endtime or endtime != 'N/A':
self.endtime = endtime
self.elapsedtime = utils.get_elapsed_time(self.starttime, self.endtime)
def _times_from_settings(self, settings):
if not settings:
return 'N/A', 'N/A'
return (self._get_time(settings['StartTime']),
self._get_time(settings['EndTime']))
def _get_time(self, timestamp):
if not timestamp or utils.eq(timestamp, 'N/A'):
return 'N/A'
try:
secs = utils.timestamp_to_secs(timestamp, seps=list(' :.-_'),
millis=True)
except ValueError:
return 'N/A'
return utils.secs_to_timestamp(secs, millis=True)
def set_status(self):
BaseTestSuite.set_status(self)
if self.starttime == 'N/A' or self.endtime == 'N/A':
subitems = self.suites + self.tests + [self.setup, self.teardown]
self.elapsedtime = sum(item.elapsedtime for item in subitems
if item is not None )
def _set_critical_tags(self, critical):
BaseTestSuite._set_critical_tags(self, critical)
self.set_status()
def _filter_by_tags(self, incls, excls):
ret = BaseTestSuite._filter_by_tags(self, incls, excls)
self.starttime = self.endtime = 'N/A'
self.set_status()
return ret
def _filter_by_names(self, suites, tests):
ret = BaseTestSuite._filter_by_names(self, suites, tests)
self.starttime = self.endtime = 'N/A'
self.set_status()
return ret
def remove_keywords(self, how):
should_remove = ShouldRemoveCallable(how)
if not should_remove:
return
self._remove_fixture_keywords(should_remove)
for suite in self.suites:
suite.remove_keywords(how)
for test in self.tests:
test.remove_keywords(should_remove)
def _remove_fixture_keywords(self, should_remove):
critical_failures = self.critical_stats.failed != 0
for kw in self.setup, self.teardown:
if should_remove(kw, critical_failures):
kw.remove_data()
class CombinedTestSuite(TestSuite):
def __init__(self, settings):
BaseTestSuite.__init__(self, name='')
self.starttime = self.endtime = None
self._set_times_from_settings(settings)
def add_suite(self, suite):
self.suites.append(suite)
suite.parent = self
self._add_suite_to_stats(suite)
self.status = self.critical_stats.failed == 0 and 'PASS' or 'FAIL'
if self.starttime == 'N/A' or self.endtime == 'N/A':
self.elapsedtime += suite.elapsedtime
class TestCase(BaseTestCase, _TestReader):
def __init__(self, node, parent, log_level=None):
BaseTestCase.__init__(self, node.get('name'), parent)
_TestReader.__init__(self, node, log_level=log_level)
self.set_criticality(parent.critical)
def remove_keywords(self, should_remove):
if should_remove(self, (self.status != 'PASS')):
for kw in self.keywords + [self.setup, self.teardown]:
if kw is not None:
kw.remove_data()
def contains_warnings(self):
return any(kw.contains_warnings() for kw in self.keywords)
class Keyword(BaseKeyword, _KeywordReader):
def __init__(self, node, log_level=None):
self._init_data()
BaseKeyword.__init__(self, node.get('name'))
_KeywordReader.__init__(self, node, log_level)
def _init_data(self):
self.messages = []
self.keywords = []
self.children = []
def remove_data(self):
self._init_data()
def contains_warnings(self):
return any(msg.level == 'WARN' for msg in self.messages) or \
any(kw.contains_warnings() for kw in self.keywords)
def __str__(self):
return self.name
def __repr__(self):
return "'%s'" % self.name
def serialize(self, serializer):
serializer.start_keyword(self)
for child in self.children:
child.serialize(serializer)
serializer.end_keyword(self)
class MessageFromXml(Message):
def __init__(self, node):
Message.__init__(self, node.text,
level=node.get('level', 'INFO'),
html=node.get('html', 'no') == 'yes',
timestamp=node.get('timestamp', 'N/A'),
linkable=node.get('linkable', 'no') == 'yes')
def serialize(self, serializer):
serializer.message(self)
def __str__(self):
return '%s %s %s' % (self.timestamp, self.level, self.message)
def __repr__(self):
lines = self.message.split('\n')
msg = len(lines) > 1 and lines[0] + '...' or lines[0]
return "'%s %s'" % (self.level, msg.replace("'",'"'))
class ExecutionErrors:
def __init__(self, node):
if node is None:
self.messages = []
else:
self.messages = [MessageFromXml(msg) for msg in node.findall('msg')]
def serialize(self, serializer):
serializer.start_errors()
for msg in self.messages:
msg.serialize(serializer)
serializer.end_errors()
class CombinedExecutionErrors(ExecutionErrors):
def __init__(self):
self.messages = []
def add(self, other):
self.messages += other.messages
def ShouldRemoveCallable(how):
def _removes_all(item, critical_failures):
return item is not None
def _removes_passed_not_containing_warnings(item, critical_failures):
if item is None:
return False
if critical_failures:
return False
return not item.contains_warnings()
how = how.upper()
if how == 'ALL':
return _removes_all
return _removes_passed_not_containing_warnings if how == 'PASSED' else None
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from loggerhelper import AbstractLogger
class FileLogger(AbstractLogger):
def __init__(self, path, level):
AbstractLogger.__init__(self, level)
self._writer = self._get_writer(path)
def _get_writer(self, path):
# Hook for unittests
return open(path, 'wb')
def message(self, msg):
if self._is_logged(msg.level):
entry = '%s | %s | %s\n' % (msg.timestamp, msg.level.ljust(5),
msg.message)
self._writer.write(entry.replace('\n', os.linesep).encode('UTF-8'))
def start_suite(self, suite):
self.info("Started test suite '%s'" % suite.name)
def end_suite(self, suite):
self.info("Ended test suite '%s'" % suite.name)
def start_test(self, test):
self.info("Started test case '%s'" % test.name)
def end_test(self, test):
self.info("Ended test case '%s'" % test.name)
def start_keyword(self, kw):
self.debug("Started keyword '%s'" % kw.name)
def end_keyword(self, kw):
self.debug("Ended keyword '%s'" % kw.name)
def output_file(self, name, path):
self.info('%s: %s' % (name, path))
def close(self):
self._writer.close()
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot import utils
from logger import LOGGER
from loggerhelper import IsLogged
def DebugFile(path):
if path == 'NONE':
LOGGER.info('No debug file')
return None
try:
LOGGER.info('Debug file: %s' % path)
return _DebugFileWriter(path)
except:
LOGGER.error("Opening debug file '%s' failed and writing to debug file "
"is disabled. Error: %s" % (path, utils.get_error_message()))
return None
class _DebugFileWriter:
_separators = {'SUITE': '=', 'TEST': '-', 'KW': '~'}
def __init__(self, path):
self._indent = 0
self._kw_level = 0
self._separator_written_last = False
self._file = open(path, 'wb')
self._is_logged = IsLogged('DEBUG')
def start_suite(self, suite):
self._separator('SUITE')
self._start('SUITE', suite.longname)
self._separator('SUITE')
def end_suite(self, suite):
self._separator('SUITE')
self._end('SUITE', suite.longname, suite.elapsedtime)
self._separator('SUITE')
if self._indent == 0:
LOGGER.output_file('Debug', self._file.name)
self.close()
def start_test(self, test):
self._separator('TEST')
self._start('TEST', test.name)
self._separator('TEST')
def end_test(self, test):
self._separator('TEST')
self._end('TEST', test.name, test.elapsedtime)
self._separator('TEST')
def start_keyword(self, kw):
if self._kw_level == 0:
self._separator('KW')
self._start(self._get_kw_type(kw), kw.name, kw.args)
self._kw_level += 1
def end_keyword(self, kw):
self._end(self._get_kw_type(kw), kw.name, kw.elapsedtime)
self._kw_level -= 1
def log_message(self, msg):
if self._is_logged(msg.level):
self._write(msg.message)
def close(self):
if not self._file.closed:
self._file.close()
def _get_kw_type(self, kw):
if kw.type in ['setup','teardown']:
return kw.type.upper()
return 'KW'
def _start(self, type_, name, args=''):
args = ' ' + utils.seq2str2(args)
self._write('+%s START %s: %s%s' % ('-'*self._indent, type_, name, args))
self._indent += 1
def _end(self, type_, name, elapsed):
self._indent -= 1
self._write('+%s END %s: %s (%s)' % ('-'*self._indent, type_, name, elapsed))
def _separator(self, type_):
self._write(self._separators[type_] * 78, True)
def _write(self, text, separator=False):
if self._separator_written_last and separator:
return
self._file.write(utils.unic(text).encode('UTF-8').rstrip() + '\n')
self._file.flush()
self._separator_written_last = separator
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
import sys
from robot import utils
from robot.errors import DataError
from loggerhelper import AbstractLoggerProxy
from logger import LOGGER
if utils.is_jython:
from java.lang import Object
from java.util import HashMap
class Listeners:
_start_attrs = ['doc', 'starttime', 'longname']
_end_attrs = _start_attrs + ['endtime', 'elapsedtime', 'status', 'message']
def __init__(self, listeners):
self._listeners = self._import_listeners(listeners)
self._running_test = False
self._setup_or_teardown_type = None
def __nonzero__(self):
return bool(self._listeners)
def _import_listeners(self, listener_data):
listeners = []
for name, args in listener_data:
try:
listeners.append(_ListenerProxy(name, args))
except:
message, details = utils.get_error_details()
if args:
name += ':' + ':'.join(args)
LOGGER.error("Taking listener '%s' into use failed: %s"
% (name, message))
LOGGER.info("Details:\n%s" % details)
return listeners
def start_suite(self, suite):
for li in self._listeners:
if li.version == 1:
li.call_method(li.start_suite, suite.name, suite.doc)
else:
attrs = self._get_start_attrs(suite, 'metadata')
attrs.update({'tests' : [t.name for t in suite.tests ],
'suites': [s.name for s in suite.suites],
'totaltests': suite.get_test_count()})
li.call_method(li.start_suite, suite.name, attrs)
def end_suite(self, suite):
for li in self._listeners:
if li.version == 1:
li.call_method(li.end_suite, suite.status,
suite.get_full_message())
else:
attrs = self._get_end_attrs(suite)
attrs.update({'statistics': suite.get_stat_message()})
li.call_method(li.end_suite, suite.name, attrs)
def start_test(self, test):
self._running_test = True
for li in self._listeners:
if li.version == 1:
li.call_method(li.start_test, test.name, test.doc, test.tags)
else:
attrs = self._get_start_attrs(test, 'tags')
li.call_method(li.start_test, test.name, attrs)
def end_test(self, test):
self._running_test = False
for li in self._listeners:
if li.version == 1:
li.call_method(li.end_test, test.status, test.message)
else:
attrs = self._get_end_attrs(test, 'tags')
li.call_method(li.end_test, test.name, attrs)
def start_keyword(self, kw):
for li in self._listeners:
if li.version == 1:
li.call_method(li.start_keyword, kw.name, kw.args)
else:
attrs = self._get_start_attrs(kw, 'args', '-longname')
attrs['type'] = self._get_keyword_type(kw, start=True)
li.call_method(li.start_keyword, kw.name, attrs)
def end_keyword(self, kw):
for li in self._listeners:
if li.version == 1:
li.call_method(li.end_keyword, kw.status)
else:
attrs = self._get_end_attrs(kw, 'args', '-longname', '-message')
attrs['type'] = self._get_keyword_type(kw, start=False)
li.call_method(li.end_keyword, kw.name, attrs)
def _get_keyword_type(self, kw, start=True):
# When running setup or teardown, only the top level keyword has type
# set to setup/teardown but we want to pass that type also to all
# start/end_keyword listener methods called below that keyword.
if kw.type == 'kw':
return self._setup_or_teardown_type or 'Keyword'
kw_type = self._get_setup_or_teardown_type(kw)
self._setup_or_teardown_type = kw_type if start else None
return kw_type
def _get_setup_or_teardown_type(self, kw):
return '%s %s' % (('Test' if self._running_test else 'Suite'),
kw.type.title())
def log_message(self, msg):
for li in self._listeners:
if li.version == 2:
li.call_method(li.log_message, self._create_msg_dict(msg))
def message(self, msg):
for li in self._listeners:
if li.version == 2:
li.call_method(li.message, self._create_msg_dict(msg))
def _create_msg_dict(self, msg):
return {'timestamp': msg.timestamp, 'message': msg.message,
'level': msg.level, 'html': 'yes' if msg.html else 'no'}
def output_file(self, name, path):
for li in self._listeners:
li.call_method(getattr(li, '%s_file' % name.lower()), path)
def close(self):
for li in self._listeners:
li.call_method(li.close)
def _get_start_attrs(self, item, *names):
return self._get_attrs(item, self._start_attrs, names)
def _get_end_attrs(self, item, *names):
return self._get_attrs(item, self._end_attrs, names)
def _get_attrs(self, item, defaults, extras):
names = self._get_attr_names(defaults, extras)
return dict((n, self._get_attr_value(item, n)) for n in names)
def _get_attr_names(self, defaults, extras):
names = list(defaults)
for name in extras:
if name.startswith('-'):
names.remove(name[1:])
else:
names.append(name)
return names
def _get_attr_value(self, item, name):
value = getattr(item, name)
return self._take_copy_of_mutable_value(value)
def _take_copy_of_mutable_value(self, value):
if isinstance(value, (dict, utils.NormalizedDict)):
return dict(value)
if isinstance(value, list):
return list(value)
return value
class _ListenerProxy(AbstractLoggerProxy):
_methods = ['start_suite', 'end_suite', 'start_test', 'end_test',
'start_keyword', 'end_keyword', 'log_message', 'message',
'output_file', 'summary_file', 'report_file', 'log_file',
'debug_file', 'xunit_file', 'close']
def __init__(self, name, args):
listener = self._import_listener(name, args)
AbstractLoggerProxy.__init__(self, listener)
self.name = name
self.version = self._get_version(listener)
self.is_java = utils.is_jython and isinstance(listener, Object)
self._failed = []
def _import_listener(self, name, args):
listener, source = utils.import_(name, 'listener')
if not inspect.ismodule(listener):
listener = listener(*args)
elif args:
raise DataError("Listeners implemented as modules do not take arguments")
LOGGER.info("Imported listener '%s' with arguments %s (source %s)"
% (name, utils.seq2str2(args), source))
return listener
def _get_version(self, listener):
try:
return int(getattr(listener, 'ROBOT_LISTENER_API_VERSION', 1))
except ValueError:
return 1
def call_method(self, method, *args):
if method in self._failed:
return
if self.is_java:
args = [self._to_map(a) if isinstance(a, dict) else a for a in args]
try:
method(*args)
except:
self._failed.append(method)
self._report_error(method)
def _report_error(self, method):
message, details = utils.get_error_details()
LOGGER.error("Method '%s' of listener '%s' failed and is disabled: %s"
% (method.__name__, self.name, message))
LOGGER.info("Details:\n%s" % details)
def _to_map(self, dictionary):
map = HashMap()
for key, value in dictionary.iteritems():
map.put(key, value)
return map
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module to configure Python's standard `logging` module.
After this module is imported, messages logged with `logging` module
are, by default, propagated to Robot's log file.
"""
import logging
from robot.api import logger
class RobotHandler(logging.Handler):
def emit(self, record):
method = self._get_logger_method(record.levelno)
method(record.getMessage())
def _get_logger_method(self, level):
if level >= logging.WARNING:
return logger.warn
if level <= logging.DEBUG:
return logger.debug
return logger.info
class NullStream(object):
def write(self, message):
pass
def close(self):
pass
def flush(self):
pass
logging.basicConfig(level=logging.NOTSET, stream=NullStream())
logging.getLogger().addHandler(RobotHandler())
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from robot import utils
from loggerhelper import AbstractLogger, AbstractLoggerProxy, Message
from filelogger import FileLogger
from monitor import CommandLineMonitor
class Logger(AbstractLogger):
"""A global logger proxy to which new loggers may be registered.
Whenever something is written to LOGGER in code, all registered loggers are
notified. Messages are also cached and cached messages written to new
loggers when they are registered.
Tools using Robot Framework's internal modules should register their own
loggers at least to get notifications about errors and warnings. A shortcut
to get errors/warnings into console is using 'register_console_logger'.
"""
def __init__(self):
self._loggers = LoggerCollection()
self._message_cache = []
self._register_console_logger()
self._console_logger_disabled = False
def disable_message_cache(self):
self._message_cache = None
def disable_automatic_console_logger(self):
if not self._console_logger_disabled:
self._console_logger_disabled = True
return self._loggers.remove_first_regular_logger()
def register_logger(self, *loggers):
for log in loggers:
logger = self._loggers.register_regular_logger(log)
self._relay_cached_messages_to(logger)
def register_context_changing_logger(self, logger):
log = self._loggers.register_context_changing_logger(logger)
self._relay_cached_messages_to(log)
def _relay_cached_messages_to(self, logger):
if self._message_cache:
for msg in self._message_cache:
logger.message(msg)
def unregister_logger(self, *loggers):
for log in loggers:
self._loggers.unregister_logger(log)
def register_console_logger(self, width=78, colors='AUTO'):
self.disable_automatic_console_logger()
self._register_console_logger(width, colors)
def _register_console_logger(self, width=78, colors='AUTO'):
monitor = CommandLineMonitor(width, colors)
self._loggers.register_regular_logger(monitor)
def register_file_logger(self, path=None, level='INFO'):
if not path:
path = os.environ.get('ROBOT_SYSLOG_FILE', 'NONE')
level = os.environ.get('ROBOT_SYSLOG_LEVEL', level)
if path.upper() == 'NONE':
return
try:
logger = FileLogger(path, level)
except:
self.error("Opening syslog file '%s' failed: %s"
% (path, utils.get_error_message()))
else:
self.register_logger(logger)
def message(self, msg):
"""Messages about what the framework is doing, warnings, errors, ..."""
for logger in self._loggers.all_loggers():
logger.message(msg)
if self._message_cache is not None:
self._message_cache.append(msg)
def log_message(self, msg):
"""Log messages written (mainly) by libraries"""
for logger in self._loggers.all_loggers():
logger.log_message(msg)
if msg.level == 'WARN':
msg.linkable = True
self.message(msg)
def warn(self, msg, log=False):
method = self.log_message if log else self.message
method(Message(msg, 'WARN'))
def output_file(self, name, path):
"""Finished output, report, log, summary, debug, or xunit file"""
for logger in self._loggers.all_loggers():
logger.output_file(name, path)
def close(self):
for logger in self._loggers.all_loggers():
logger.close()
self._loggers = LoggerCollection()
self._message_cache = []
def start_suite(self, suite):
for logger in self._loggers.starting_loggers():
logger.start_suite(suite)
def end_suite(self, suite):
for logger in self._loggers.ending_loggers():
logger.end_suite(suite)
def start_test(self, test):
for logger in self._loggers.starting_loggers():
logger.start_test(test)
def end_test(self, test):
for logger in self._loggers.ending_loggers():
logger.end_test(test)
def start_keyword(self, keyword):
for logger in self._loggers.starting_loggers():
logger.start_keyword(keyword)
def end_keyword(self, keyword):
for logger in self._loggers.ending_loggers():
logger.end_keyword(keyword)
def __iter__(self):
return iter(self._loggers)
class LoggerCollection(object):
def __init__(self):
self._regular_loggers = []
self._context_changing_loggers = []
def register_regular_logger(self, logger):
self._regular_loggers.append(_LoggerProxy(logger))
return self._regular_loggers[-1]
def register_context_changing_logger(self, logger):
self._context_changing_loggers.append(_LoggerProxy(logger))
return self._context_changing_loggers[-1]
def remove_first_regular_logger(self):
return self._regular_loggers.pop(0)
def unregister_logger(self, logger):
self._regular_loggers = [proxy for proxy in self._regular_loggers
if proxy.logger is not logger]
self._context_changing_loggers = [proxy for proxy
in self._context_changing_loggers
if proxy.logger is not logger]
def starting_loggers(self):
return self.all_loggers()
def ending_loggers(self):
return self._regular_loggers + self._context_changing_loggers
def all_loggers(self):
return self._context_changing_loggers + self._regular_loggers
def __iter__(self):
return iter(self.all_loggers())
class _LoggerProxy(AbstractLoggerProxy):
_methods = ['message', 'log_message', 'output_file', 'close',
'start_suite', 'end_suite', 'start_test', 'end_test',
'start_keyword', 'end_keyword']
LOGGER = Logger()
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Windows highlighting code adapted from color_console.py. It is copyright
# Andre Burgaud, licensed under the MIT License, and available here:
# http://www.burgaud.com/bring-colors-to-the-windows-console-with-python/
import os
import sys
try:
from ctypes import windll, Structure, c_short, c_ushort, byref
except ImportError: # Not on Windows or using Jython
windll = None
def Highlighter(stream):
if os.sep == '/':
return UnixHighlighter(stream)
return DosHighlighter(stream) if windll else NoHighlighting(stream)
class UnixHighlighter(object):
_ANSI_GREEN = '\033[32m'
_ANSI_RED = '\033[31m'
_ANSI_YELLOW = '\033[33m'
_ANSI_RESET = '\033[0m'
def __init__(self, stream):
self._stream = stream
def green(self):
self._set_color(self._ANSI_GREEN)
def red(self):
self._set_color(self._ANSI_RED)
def yellow(self):
self._set_color(self._ANSI_YELLOW)
def reset(self):
self._set_color(self._ANSI_RESET)
def _set_color(self, color):
self._stream.write(color)
class NoHighlighting(UnixHighlighter):
def _set_color(self, color):
pass
class DosHighlighter(object):
_FOREGROUND_GREEN = 0x2
_FOREGROUND_RED = 0x4
_FOREGROUND_YELLOW = 0x6
_FOREGROUND_GREY = 0x7
_FOREGROUND_INTENSITY = 0x8
_BACKGROUND_MASK = 0xF0
_STDOUT_HANDLE = -11
_STDERR_HANDLE = -12
def __init__(self, stream):
self._handle = self._get_std_handle(stream)
self._orig_colors = self._get_colors()
self._background = self._orig_colors & self._BACKGROUND_MASK
def green(self):
self._set_foreground_colors(self._FOREGROUND_GREEN)
def red(self):
self._set_foreground_colors(self._FOREGROUND_RED)
def yellow(self):
self._set_foreground_colors(self._FOREGROUND_YELLOW)
def reset(self):
self._set_colors(self._orig_colors)
def _get_std_handle(self, stream):
handle = self._STDOUT_HANDLE \
if stream is sys.__stdout__ else self._STDERR_HANDLE
return windll.kernel32.GetStdHandle(handle)
def _get_colors(self):
csbi = _CONSOLE_SCREEN_BUFFER_INFO()
ok = windll.kernel32.GetConsoleScreenBufferInfo(self._handle, byref(csbi))
if not ok: # Call failed, return default console colors (gray on black)
return self._FOREGROUND_GREY
return csbi.wAttributes
def _set_foreground_colors(self, colors):
self._set_colors(colors | self._FOREGROUND_INTENSITY | self._background)
def _set_colors(self, colors):
windll.kernel32.SetConsoleTextAttribute(self._handle, colors)
if windll:
class _COORD(Structure):
_fields_ = [("X", c_short),
("Y", c_short)]
class _SMALL_RECT(Structure):
_fields_ = [("Left", c_short),
("Top", c_short),
("Right", c_short),
("Bottom", c_short)]
class _CONSOLE_SCREEN_BUFFER_INFO(Structure):
_fields_ = [("dwSize", _COORD),
("dwCursorPosition", _COORD),
("wAttributes", c_ushort),
("srWindow", _SMALL_RECT),
("dwMaximumWindowSize", _COORD)]
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from robot.output.loggerhelper import Message, LEVELS
from robot import utils
class StdoutLogSplitter(object):
"""Splits messages logged through stdout (or stderr) into Message objects"""
_split_from_levels = re.compile('^(?:\*'
'(%s|HTML)' # Level
'(:\d+(?:\.\d+)?)?' # Optional timestamp
'\*)' % '|'.join(LEVELS), re.MULTILINE)
def __init__(self, output):
self._messages = list(self._get_messages(output.strip()))
def _get_messages(self, output):
for level, timestamp, msg in self._split_output(output):
if timestamp:
timestamp = self._format_timestamp(timestamp[1:])
yield Message(msg.strip(), level, timestamp=timestamp)
def _split_output(self, output):
tokens = self._split_from_levels.split(output)
tokens = self._add_initial_level_and_time_if_needed(tokens)
for i in xrange(0, len(tokens), 3):
yield tokens[i:i+3]
def _add_initial_level_and_time_if_needed(self, tokens):
if self._output_started_with_level(tokens):
return tokens[1:]
return ['INFO', None] + tokens
def _output_started_with_level(self, tokens):
return tokens[0] == ''
def _format_timestamp(self, millis):
return utils.format_time(float(millis)/1000, millissep='.')
def __iter__(self):
return iter(self._messages)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from output import Output
from logger import LOGGER
from monitor import CommandLineMonitor
from xmllogger import XmlLogger
from loggerhelper import LEVELS, Message
from readers import process_output, process_outputs
# Hooks to output. Set by Output.
# Use only if no other way available (e.g. from BuiltIn library)
OUTPUT = None
def TestSuite(outpath):
"""Factory method for getting test suite from an xml output file.
If you want statistics get suite first and say Statistics(suite).
"""
suite, errors = process_output(outpath)
def write_to_file(path=None):
"""Write processed suite (incl. statistics and errors) back to xml.
If path is not given the suite is written into the same file as it
originally was read from.
"""
from robot.result import RobotTestOutput
if path is None:
path = outpath
suite.set_status()
testoutput = RobotTestOutput(suite, errors)
testoutput.serialize_output(path, suite)
suite.write_to_file = write_to_file
return suite
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from org.robotframework import RobotRunner
from robot import runner, run_from_cli, rebot, rebot_from_cli
class JarRunner(RobotRunner):
"""Used for Java-Jython interop when RF is executed from .jar file"""
def run(self, args):
try:
if args and args[0] == 'rebot':
rebot_from_cli(args[1:], rebot.__doc__)
else:
run_from_cli(args, runner.__doc__)
except SystemExit, err:
return err.code
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
if __name__ == '__main__':
sys.stderr.write("Use 'runner' or 'rebot' for executing.\n")
sys.exit(252) # 252 == DATA_ERROR
# Global workaround for os.listdir bug http://bugs.jython.org/issue1593
# This bug has been fixed in Jython 2.5.2 RC 2
if sys.platform.startswith('java') and sys.version_info[:3] < (2,5,2):
from java.lang import String
def listdir(path):
items = os._listdir(path)
if isinstance(path, unicode):
items = [unicode(String(i).toString()) for i in items]
return items
os._listdir = os.listdir
os.listdir = listdir
# Global workaround for os.stat bug http://bugs.jython.org/issue1658
# Jython 2.5.2 RC 2 still contains this bug, but additionally the workaround used
# here does not work on that version either.
if sys.platform.startswith('java') and os.sep == '\\' and sys.version_info < (2,5,2):
os._posix = os.JavaPOSIX(os.PythonPOSIXHandler())
os._native_posix = False
if 'pythonpathsetter' not in sys.modules:
import pythonpathsetter
from output import Output, LOGGER, pyloggingconf
from conf import RobotSettings, RebotSettings
from running import TestSuite, STOP_SIGNAL_MONITOR
from robot.result import ResultWriter
from errors import (DataError, Information, INFO_PRINTED, DATA_ERROR,
STOPPED_BY_USER, FRAMEWORK_ERROR)
from variables import init_global_variables
from version import get_version, get_full_version
import utils
__version__ = get_version()
def run_from_cli(args, usage):
LOGGER.info(get_full_version('Robot Framework'))
return _run_or_rebot_from_cli(run, args, usage, pythonpath='pythonpath')
def rebot_from_cli(args, usage):
LOGGER.info(get_full_version('Rebot'))
return _run_or_rebot_from_cli(run_rebot, args, usage)
def _run_or_rebot_from_cli(method, cliargs, usage, **argparser_config):
LOGGER.register_file_logger()
try:
options, datasources = _parse_arguments(cliargs, usage,
**argparser_config)
except Information, msg:
print utils.encode_output(unicode(msg))
return INFO_PRINTED
except DataError, err:
_report_error(unicode(err), help=True)
return DATA_ERROR
LOGGER.info('Data sources: %s' % utils.seq2str(datasources))
return _execute(method, datasources, options)
def _parse_arguments(cliargs, usage, **argparser_config):
ap = utils.ArgumentParser(usage, get_full_version())
return ap.parse_args(cliargs, argfile='argumentfile', unescape='escape',
help='help', version='version', check_args=True,
**argparser_config)
def _execute(method, datasources, options):
try:
suite = method(*datasources, **options)
except DataError, err:
_report_error(unicode(err), help=True)
return DATA_ERROR
except (KeyboardInterrupt, SystemExit):
_report_error('Execution stopped by user.')
return STOPPED_BY_USER
except:
error, details = utils.get_error_details()
_report_error('Unexpected error: %s' % error, details)
return FRAMEWORK_ERROR
else:
return suite.return_code
def run(*datasources, **options):
"""Executes given Robot data sources with given options.
Data sources are paths to files and directories, similarly as when running
pybot/jybot from command line. Options are given as keywords arguments and
their names are same as long command line options without hyphens.
Examples:
run('/path/to/tests.html')
run('/path/to/tests.html', '/path/to/tests2.html', log='mylog.html')
Equivalent command line usage:
pybot /path/to/tests.html
pybot --log mylog.html /path/to/tests.html /path/to/tests2.html
"""
STOP_SIGNAL_MONITOR.start()
settings = RobotSettings(options)
LOGGER.register_console_logger(settings['MonitorWidth'],
settings['MonitorColors'])
output = Output(settings)
init_global_variables(settings)
suite = TestSuite(datasources, settings)
suite.run(output)
LOGGER.info("Tests execution ended. Statistics:\n%s"
% suite.get_stat_message())
output.close(suite)
if settings.is_rebot_needed():
output, settings = settings.get_rebot_datasource_and_settings()
ResultWriter(settings).write_robot_results(output)
LOGGER.close()
return suite
def run_rebot(*datasources, **options):
"""Creates reports/logs from given Robot output files with given options.
Given input files are paths to Robot output files similarly as when running
rebot from command line. Options are given as keywords arguments and
their names are same as long command line options without hyphens.
Examples:
run_rebot('/path/to/output.xml')
run_rebot('/path/out1.xml', '/path/out2.xml', report='myrep.html', log='NONE')
Equivalent command line usage:
rebot /path/to/output.xml
rebot --report myrep.html --log NONE /path/out1.xml /path/out2.xml
"""
settings = RebotSettings(options)
LOGGER.register_console_logger(colors=settings['MonitorColors'])
LOGGER.disable_message_cache()
suite = ResultWriter(settings).write_rebot_results(*datasources)
LOGGER.close()
return suite
def _report_error(message, details=None, help=False):
if help:
message += '\n\nTry --help for usage information.'
LOGGER.error(message)
if details:
LOGGER.info(details)
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Rebot -- Robot Framework Report and Log Generator
Version: <VERSION>
Usage: rebot [options] robot_outputs
or: interpreter /path/robot/rebot.py [options] robot_outputs
or python -m robot.rebot [options] robot_outputs
Inputs to Rebot are XML output files generated by Robot Framework test runs or
earlier Rebot executions. Rebot can be used to generate logs, reports and
summary reports in HTML format. It can also produce new XML output files which
can be further processed with Rebot or other tools.
When more than one input file is given, a new combined test suite containing
information from given files is created. This allows combining multiple outputs
together to create higher level reports.
For more information about Robot Framework run 'pybot --help' or go to
http://robotframework.org.
Options:
-N --name name Set the name of the top level test suite. Underscores
in the name are converted to spaces. Default name is
created from the name of the executed data source.
-D --doc documentation Set the documentation of the top level test suite.
Underscores in the documentation are converted to
spaces and it may also contain simple HTML formatting
(e.g. *bold* and http://url/).
-M --metadata name:value * Set metadata of the top level test suite.
Underscores in the name and value are converted to
spaces. Value can contain same HTML formatting as
--doc. Example: '--metadata version:1.2'
-G --settag tag * Sets given tag(s) to all executed test cases.
-t --test name * Select test cases to run by name or long name. Name
is case and space insensitive and it can also be a
simple pattern where '*' matches anything and '?'
matches any char. If using '*' and '?' in the console
is problematic see --escape and --argumentfile.
-s --suite name * Select test suites by name. When this option is used
with --test, --include or --exclude, only test cases
in matching suites and also matching other filtering
criteria are selected. Given name can be a simple
pattern similarly as with --test.
-i --include tag * Select test cases to run by tag. Similarly as name in
--test, tag is case and space insensitive. There are
three ways to include test based on tags:
1) One tag as a simple pattern. Tests having a tag
matching the pattern are included. Example: 'it-*'
2) Two or more tags (or patterns) separated by '&' or
'AND'. Only tests having all these tags are included.
Examples: 'tag1&tag2', 'smokeANDowner-*ANDit-10'
3) Two or more tags (or patterns) separated by 'NOT'.
Tests having the first tag but not any of the latter
ones are included. Example: 'it-10NOTsmoke'
-e --exclude tag * Select test cases not to run by tag. These tests are
not run even if they are included with --include.
Tags are excluded using the rules explained in
--include.
-c --critical tag * Tests having given tag are considered critical. If no
critical tags are set, all tags are critical. Tags
can be given as a pattern like e.g. with --test.
Resets possible critical tags set earlier.
-n --noncritical tag * Tests with given tag are not critical even if they
have a tag set with --critical. Tag can be a pattern.
Resets possible non critical tags set earlier.
-d --outputdir dir Where to create output files. The default is the
directory where Rebot is run from and the given path
is considered relative to that unless it is absolute.
-o --output file XML output file. Not created unless this option is
specified. Given path, similarly as paths given to
--log, --report and --summary, is relative to
--outputdir unless given as an absolute path.
Default is 'output.xml'. Example: '--output out.xml'
-l --log file HTML log file. Can be disabled by giving a special
name 'NONE'. Examples: '--log mylog.html', '-l none'
-r --report file HTML report file. Can be disabled with 'NONE'
similarly as --log. Default is 'report.html'.
-S --summary file HTML summary report. Not created unless this option
is specified. Example: '--summary summary.html'
-x --xunitfile file xUnit compatible result file. Not created unless this
option is specified.
-T --timestampoutputs When this option is used, timestamp in a format
'YYYYMMDD-hhmmss' is added to all generated output
files between their basename and extension. For
example '-T -o output.xml -r report.html -l none'
creates files like 'output-20070503-154410.xml' and
'report-20070503-154410.html'.
--splitoutputs level Splitting outputs is not supported in version 2.6 or
newer. This option will be removed altogether in 2.7.
--logtitle title Title for the generated test log. The default title
is '<Name Of The Suite> Test Log'. Underscores in
the title are converted into spaces in all titles.
--reporttitle title Title for the generated test report. The default
title is '<Name Of The Suite> Test Report'.
--summarytitle title Title for the generated summary report. The default
title is '<Name Of The Suite> Summary Report'.
--reportbackground colors Background colors to use in report and summary.
Either 'all_passed:critical_passed:failed' or
'passed:failed'. Both color names and codes work.
Examples: --reportbackground green:yellow:red
--reportbackground #00E:#E00
-L --loglevel level Threshold for selecting messages. Available levels:
TRACE (default), DEBUG, INFO, WARN, NONE (no msgs)
--suitestatlevel level How many levels to show in 'Statistics by Suite'
in log and report. By default all suite levels are
shown. Example: --suitestatlevel 3
--tagstatinclude tag * Include only matching tags in 'Statistics by Tag'
and 'Test Details' in log and report. By default all
tags set in test cases are shown. Given 'tag' can
also be a simple pattern (see e.g. --test).
--tagstatexclude tag * Exclude matching tags from 'Statistics by Tag' and
'Test Details'. This option can be used with
--tagstatinclude similarly as --exclude is used with
--include.
--tagstatcombine tags:name * Create combined statistics based on tags.
These statistics are added into 'Statistics by Tag'
and matching tests into 'Test Details'. If optional
'name' is not given, name of the combined tag is got
from the specified tags. Tags are combined using the
rules explained in --include.
Examples: --tagstatcombine tag1ANDtag2:My_name
--tagstatcombine requirement-*
--tagdoc pattern:doc * Add documentation to tags matching given pattern.
Documentation is shown in 'Test Details' and also as
a tooltip in 'Statistics by Tag'. Pattern can contain
characters '*' (matches anything) and '?' (matches
any char). Documentation can contain formatting
similarly as with --doc option.
Examples: --tagdoc mytag:My_documentation
--tagdoc regression:*See*_http://info.html
--tagdoc owner-*:Original_author
--tagstatlink pattern:link:title * Add external links into 'Statistics by
Tag'. Pattern can contain characters '*' (matches
anything) and '?' (matches any char). Characters
matching to wildcard expressions can be used in link
and title with syntax %N, where N is index of the
match (starting from 1). In title underscores are
automatically converted to spaces.
Examples: --tagstatlink mytag:http://my.domain:Link
--tagstatlink bug-*:http://tracker/id=%1:Bug_Tracker
--removekeywords all|passed Remove keyword data from generated outputs.
Keyword data is not needed when creating reports and
removing it can make the size of an output file
considerably smaller.
'all' - remove data from all keywords
'passed' - remove data only from keywords in passed
test cases and suites
--starttime timestamp Set starting time of test execution when creating
reports. Timestamp must be given in format
'2007-10-01 15:12:42.268' where all separators are
optional (e.g. '20071001151242268' is ok too) and
parts from milliseconds to hours can be omitted if
they are zero (e.g. '2007-10-01'). This can be used
to override starttime of the suite when reports are
created from a single suite or to set starttime for
combined suite, which is otherwise set to 'N/A'.
--endtime timestamp Same as --starttime but for ending time. If both
options are used, elapsed time of the suite is
calculated based on them. For combined suites,
it is otherwise calculated by adding elapsed times
of combined test suites together.
--nostatusrc Sets the return code to zero regardless of failures
in test cases. Error codes are returned normally.
-C --monitorcolors on|off|force Using ANSI colors in console. Normally colors
work in unixes but not in Windows. Default is 'on'.
'on' - use colors in unixes but not in Windows
'off' - never use colors
'force' - always use colors (also in Windows)
-E --escape what:with * Escape characters which are problematic in console.
'what' is the name of the character to escape and
'with' is the string to escape it with. Note that
all given arguments, incl. data sources, are escaped
so escape characters ought to be selected carefully.
<---------------------ESCAPES----------------------->
Examples:
--escape space:_ --metadata X:Value_with_spaces
-E space:SP -E quot:Q -v var:QhelloSPworldQ
-A --argumentfile path * Text file to read more arguments from. File can have
both options and data sources one per line. Contents
don't need to be escaped but spaces in the beginning
and end of lines are removed. Empty lines and lines
starting with a hash character (#) are ignored.
Example file:
| --include regression
| --name Regression Tests
| # This is a comment line
| my_tests.html
| path/to/test/directory/
-h -? --help Print usage instructions.
--version Print version information.
Options that are marked with an asterisk (*) can be specified multiple times.
For example '--test first --test third' selects test cases with name 'first'
and 'third'. If other options are given multiple times, the last value is used.
Long option format is case-insensitive. For example --SuiteStatLevel is
equivalent to, but easier to read than, --suitestatlevel. Long options can
also be shortened as long as they are unique. For example '--logti Title' works
while '--lo log.html' does not because the former matches only --logtitle but
latter matches both --log and --logtitle.
Environment Variables:
ROBOT_SYSLOG_FILE Path to the syslog file. If not specified, or set to
special value 'NONE', writing to syslog file is
disabled. Path must be absolute.
ROBOT_SYSLOG_LEVEL Log level to use when writing to the syslog file.
Available levels are the same as for --loglevel
option to Robot and the default is INFO.
Examples:
# Simple Rebot run that creates log and report with default names.
$ rebot output.xml
# Using options. Note that this is one long command split into multiple lines.
$ rebot --log none --report myreport.html --reporttitle My_Report
--summary mysummary.html --summarytitle My_Summary
--TagStatCombine smokeANDmytag path/to/myoutput.xml
# Running 'robot/rebot.py' directly and creating combined outputs.
$ python /path/robot/rebot.py -N Project_X -l x.html -r x.html outputs/*.xml
"""
import sys
try:
import pythonpathsetter
except ImportError:
# Get here when run as 'python -m robot.rebot' and then importing robot
# works without this and pythonpathsetter is imported again later.
pass
import robot
if __name__ == '__main__':
rc = robot.rebot_from_cli(sys.argv[1:], __doc__)
sys.exit(rc)
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework -- A keyword-driven test automation framework
Version: <VERSION>
Usage: pybot [options] data_sources
or: jybot [options] data_sources
or: interpreter /path/robot/runner.py [options] data_sources
or: python -m robot.runner [options] data_sources
Robot Framework is a Python-based keyword-driven test automation framework for
acceptance level testing and acceptance test-driven development (ATDD). It has
an easy-to-use tabular syntax for creating test cases and its testing
capabilities can be extended by test libraries implemented either with Python
or Java. Users can also create new keywords from existing ones using the same
simple syntax that is used for creating test cases.
Robot Framework has two start-up scripts, 'pybot' and 'jybot', which run it on
Python and Jython interpreters, respectively. Alternatively it is possible to
directly call 'robot/runner.py' script using a selected interpreter.
Data sources given to Robot Framework are either test case files or directories
containing them and/or other directories. Single test case file creates a test
suite containing all the test cases in it and a directory containing test case
files creates a higher level test suite with test case files or other
directories as sub test suites. If multiple data sources are given, a virtual
test suite containing suites generated from given data sources is created.
By default Robot Framework creates an XML output file and a log and a report in
HTML format, but this can be configured using various options listed below.
Outputs in HTML format are for human consumption and XML output for integration
with other systems. XML outputs can also be combined and otherwise further
processed with Rebot tool. Run 'rebot --help' for more information.
Robot Framework is open source software released under Apache License 2.0.
Its copyrights are owned and development supported by Nokia Siemens Networks.
For more information about the framework see http://robotframework.org.
Options:
-N --name name Set the name of the top level test suite. Underscores
in the name are converted to spaces. Default name is
created from the name of the executed data source.
-D --doc documentation Set the documentation of the top level test suite.
Underscores in the documentation are converted to
spaces and it may also contain simple HTML formatting
(e.g. *bold* and http://url/).
-M --metadata name:value * Set metadata of the top level test suite.
Underscores in the name and value are converted to
spaces. Value can contain same HTML formatting as
--doc. Example: '--metadata version:1.2'
-G --settag tag * Sets given tag(s) to all executed test cases.
-t --test name * Select test cases to run by name or long name. Name
is case and space insensitive and it can also be a
simple pattern where '*' matches anything and '?'
matches any char. If using '*' and '?' in the console
is problematic see --escape and --argumentfile.
-s --suite name * Select test suites to run by name. When this option
is used with --test, --include or --exclude, only
test cases in matching suites and also matching other
filtering criteria are selected. Name can be a simple
pattern similarly as with --test and it can contain
parent name separated with a dot. For example
'-s X.Y' selects suite 'Y' only if its parent is 'X'.
-i --include tag * Select test cases to run by tag. Similarly as name in
--test, tag is case and space insensitive. There are
three ways to include test based on tags:
1) One tag as a simple pattern. Tests having a tag
matching the pattern are included. Example: 'it-*'
2) Two or more tags (or patterns) separated by '&' or
'AND'. Only tests having all these tags are included.
Examples: 'tag1&tag2', 'smokeANDowner-*ANDit-10'
3) Two or more tags (or patterns) separated by 'NOT'.
Tests having the first tag but not any of the latter
ones are included. Example: 'it-10NOTsmoke'
-e --exclude tag * Select test cases not to run by tag. These tests are
not run even if they are included with --include.
Tags are excluded using the rules explained in
--include.
-c --critical tag * Tests having given tag are considered critical. If no
critical tags are set, all tags are critical. Tags
can be given as a pattern like e.g. with --test.
-n --noncritical tag * Tests with given tag are not critical even if they
have a tag set with --critical. Tag can be a pattern.
-v --variable name:value * Set variables in the test data. Only scalar
variables are supported and name is given without
'${}'. See --escape for how to use special characters
and --variablefile for a more powerful variable
setting mechanism that allows also list variables.
Examples:
--variable str:Hello => ${str} = 'Hello'
-v str:Hi_World -E space:_ => ${str} = 'Hi World'
-v x: -v y:42 => ${x} = '', ${y} = '42'
-V --variablefile path * File to read variables from (e.g. 'path/vars.py').
Example file:
| import random
| __all__ = ['scalar','LIST__var','integer']
| scalar = 'Hello world!'
| LIST__var = ['Hello','list','world']
| integer = random.randint(1,10)
=>
${scalar} = 'Hello world!'
@{var} = ['Hello','list','world']
${integer} = <random integer from 1 to 10>
-d --outputdir dir Where to create output files. The default is the
directory where tests are run from and the given path
is considered relative to that unless it is absolute.
-o --output file XML output file. Given path, similarly as paths given
to --log, --report, --summary, --debugfile and
--xunitfile, is relative to --outputdir unless given
as an absolute path. Other output files are created
from XML output file after the test execution and XML
output can also be further processed with Rebot tool
(e.g. combined with other XML output files). Can be
disabled by giving a special value 'NONE'. In this
case, also log and report are automatically disabled.
Default: output.xml
-l --log file HTML log file. Can be disabled by giving a special
value 'NONE'. Default: log.html
Examples: '--log mylog.html', '-l NONE'
-r --report file HTML report file. Can be disabled with 'NONE'
similarly as --log. Default: report.html
-S --summary file HTML summary report. Not created unless this option
is specified. Example: '--summary summary.html'
-x --xunitfile file xUnit compatible result file. Not created unless this
option is specified.
-b --debugfile file Debug file written during execution. Not created
unless this option is specified.
-T --timestampoutputs When this option is used, timestamp in a format
'YYYYMMDD-hhmmss' is added to all generated output
files between their basename and extension. For
example '-T -o output.xml -r report.html -l none'
creates files like 'output-20070503-154410.xml' and
'report-20070503-154410.html'.
--splitoutputs level Splitting outputs is not supported in version 2.6 or
newer. This option will be removed altogether in 2.7.
--logtitle title Title for the generated test log. The default title
is '<Name Of The Suite> Test Log'. Underscores in
the title are converted into spaces in all titles.
--reporttitle title Title for the generated test report. The default
title is '<Name Of The Suite> Test Report'.
--summarytitle title Title for the generated summary report. The default
title is '<Name Of The Suite> Summary Report'.
--reportbackground colors Background colors to use in report and summary.
Either 'all_passed:critical_passed:failed' or
'passed:failed'. Both color names and codes work.
Examples: --reportbackground green:yellow:red
--reportbackground #00E:#E00
-L --loglevel level Threshold level for logging. Available levels:
TRACE, DEBUG, INFO (default), WARN, NONE (no logging)
--suitestatlevel level How many levels to show in 'Statistics by Suite'
in log and report. By default all suite levels are
shown. Example: --suitestatlevel 3
--tagstatinclude tag * Include only matching tags in 'Statistics by Tag'
and 'Test Details' in log and report. By default all
tags set in test cases are shown. Given 'tag' can
also be a simple pattern (see e.g. --test).
--tagstatexclude tag * Exclude matching tags from 'Statistics by Tag' and
'Test Details'. This option can be used with
--tagstatinclude similarly as --exclude is used with
--include.
--tagstatcombine tags:name * Create combined statistics based on tags.
These statistics are added into 'Statistics by Tag'
and matching tests into 'Test Details'. If optional
'name' is not given, name of the combined tag is got
from the specified tags. Tags are combined using the
rules explained in --include.
Examples: --tagstatcombine tag1ANDtag2:My_name
--tagstatcombine requirement-*
--tagdoc pattern:doc * Add documentation to tags matching given pattern.
Documentation is shown in 'Test Details' and also as
a tooltip in 'Statistics by Tag'. Pattern can contain
characters '*' (matches anything) and '?' (matches
any char). Documentation can contain formatting
similarly as with --doc option.
Examples: --tagdoc mytag:My_documentation
--tagdoc regression:*See*_http://info.html
--tagdoc owner-*:Original_author
--tagstatlink pattern:link:title * Add external links into 'Statistics by
Tag'. Pattern can contain characters '*' (matches
anything) and '?' (matches any char). Characters
matching to wildcard expressions can be used in link
and title with syntax %N, where N is index of the
match (starting from 1). In title underscores are
automatically converted to spaces.
Examples: --tagstatlink mytag:http://my.domain:Link
--tagstatlink bug-*:http://tracker/id=%1:Bug_Tracker
--listener class * A class for monitoring test execution. Gets
notifications e.g. when a test case starts and ends.
Arguments to listener class can be given after class
name, using colon as separator. For example:
--listener MyListenerClass:arg1:arg2
--warnonskippedfiles If this option is used, skipped files will cause a
warning that is visible to console output and log
files. By default skipped files only cause an info
level syslog message.
--nostatusrc Sets the return code to zero regardless of failures
in test cases. Error codes are returned normally.
--runemptysuite Executes tests also if the top level test suite is
empty. Useful e.g. with --include/--exclude when it
is not an error that no test matches the condition.
--runmode mode * Possible values are 'Random:Test', 'Random:Suite',
'Random:All', 'ExitOnFailure', 'SkipTeardownOnExit',
and 'DryRun' (case-insensitive). First three change
the execution order of tests, suites, or both.
'ExitOnFailure' stops test execution if a critical
test fails. 'SkipTeardownOnExit' causes teardowns to
be skipped if test execution is stopped prematurely.
In the 'DryRun' test data is verified and tests run
so that library keywords are not executed.
-W --monitorwidth chars Width of the monitor output. Default is 78.
-C --monitorcolors auto|on|off Use colors on console output or not.
auto: use colors when output not redirected (default)
on: always use colors
off: never use colors
Note that colors do not work with Jython on Windows.
-P --pythonpath path * Additional locations (directories, ZIPs, JARs) where
to search test libraries from when they are imported.
Multiple paths can be given by separating them with a
colon (':') or using this option several times. Given
path can also be a glob pattern matching multiple
paths but then it normally must be escaped or quoted.
Examples:
--pythonpath libs/
--pythonpath /opt/testlibs:mylibs.zip:yourlibs
-E star:STAR -P lib/STAR.jar -P mylib.jar
-E --escape what:with * Escape characters which are problematic in console.
'what' is the name of the character to escape and
'with' is the string to escape it with. Note that
all given arguments, incl. data sources, are escaped
so escape characters ought to be selected carefully.
<--------------------ESCAPES------------------------>
Examples:
--escape space:_ --metadata X:Value_with_spaces
-E space:SP -E quot:Q -v var:QhelloSPworldQ
-A --argumentfile path * Text file to read more arguments from. Use special
path 'STDIN' to read contents from the standard input
stream. File can have both options and data sources
one per line. Contents do not need to be escaped but
spaces in the beginning and end of lines are removed.
Empty lines and lines starting with a hash character
(#) are ignored.
Example file:
| --include regression
| --name Regression Tests
| # This is a comment line
| my_tests.html
| path/to/test/directory/
Examples:
--argumentfile argfile.txt --argumentfile STDIN
-h -? --help Print usage instructions.
--version Print version information.
Options that are marked with an asterisk (*) can be specified multiple times.
For example '--test first --test third' selects test cases with name 'first'
and 'third'. If other options are given multiple times, the last value is used.
Long option format is case-insensitive. For example --SuiteStatLevel is
equivalent to, but easier to read than, --suitestatlevel. Long options can
also be shortened as long as they are unique. For example '--logle DEBUG' works
while '--lo log.html' does not because the former matches only --loglevel but
latter matches --log, --logtitle and --loglevel.
Environment Variables:
ROBOT_SYSLOG_FILE Path to the syslog file. If not specified, or set to
special value 'NONE', writing to syslog file is
disabled. Path must be absolute.
ROBOT_SYSLOG_LEVEL Log level to use when writing to the syslog file.
Available levels are the same as for --loglevel
option and the default is INFO.
Examples:
# Simple test run with 'pybot' without options.
$ pybot tests.html
# Using options and running with 'jybot'.
$ jybot --include smoke --name Smoke_Tests /path/to/tests.html
# Running 'robot/runner.py' directly and using test data in TSV format.
$ python /path/to/robot/runner.py tests.tsv
# Using custom start-up script, giving multiple options and executing a dir.
$ runtests.sh --test test1 --test test2 testdir/
# Executing multiple data sources and using case-insensitive long options.
$ pybot --SuiteStatLevel 2 /my/tests/*.html /your/tests.html
# Setting syslog file before running tests.
$ export ROBOT_SYSLOG_FILE=/tmp/syslog.txt
$ pybot tests.html
"""
import sys
try:
import pythonpathsetter
except ImportError:
# Get here when run as 'python -m robot.runner' and then importing robot
# works without this and pythonpathsetter is imported again later.
pass
import robot
if __name__ == '__main__':
rc = robot.run_from_cli(sys.argv[1:], __doc__)
sys.exit(rc)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot.errors import DataError
class UserErrorHandler:
"""Created if creating handlers fail -- running raises DataError.
The idea is not to raise DataError at processing time and prevent all
tests in affected test case file from executing. Instead UserErrorHandler
is created and if it is ever run DataError is raised then.
"""
type = 'error'
def __init__(self, name, error):
self.name = self.longname = name
self.doc = self.shortdoc = ''
self._error = error
self.timeout = ''
def init_keyword(self, varz):
pass
def run(self, *args):
raise DataError(self._error)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class BaseKeyword:
def __init__(self, name='', args=None, doc='', timeout='', type='kw'):
self.name = name
self.args = args or []
self.doc = doc
self.timeout = timeout
self.type = type
self.status = 'NOT_RUN'
def serialize(self, serializer):
serializer.start_keyword(self)
serializer.end_keyword(self)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import random
from statistics import Stat
from robot import utils
from robot.errors import DataError
class _TestAndSuiteHelper:
def __init__(self, name, parent=None):
self.name = name
self.doc = ''
self.parent = parent
self.setup = None
self.teardown = None
self.status = 'NOT_RUN'
self.message = ''
# TODO: Is this property and other html/serialize stuff here used anymore?
@property
def htmldoc(self):
return utils.html_format(self.doc)
# TODO: Replace with simple @property in 2.7.
# Cannot do that now because Mabot assigns longname.
_longname = None
longname = property(lambda self: self._longname or self.get_long_name(),
lambda self, name: setattr(self, '_longname', name))
# TODO: Is separator still used?
def get_long_name(self, separator='.'):
"""Returns long name. If separator is None, list of names is returned."""
names = self.parent and self.parent.get_long_name(separator=None) or []
names.append(self.name)
if separator:
return separator.join(names)
return names
def _set_teardown_fail_msg(self, message):
if self.message == '':
self.message = message
else:
self.message += '\n\nAlso ' + message[0].lower() + message[1:]
def __str__(self):
return self.name
def __repr__(self):
return repr(self.name)
class BaseTestSuite(_TestAndSuiteHelper):
"""Base class for TestSuite used in runtime and by rebot."""
def __init__(self, name, source=None, parent=None):
_TestAndSuiteHelper.__init__(self, name, parent)
self.source = source is not None and utils.abspath(source) or None
self.metadata = utils.NormalizedDict()
self.suites = []
self.tests = []
self.critical = _Critical()
self.critical_stats = Stat()
self.all_stats = Stat()
if parent:
parent.suites.append(self)
def set_name(self, name):
if name:
self.name = name
elif not self.parent and self.name == '': # MultiSourceSuite
self.name = ' & '.join([suite.name for suite in self.suites])
def set_critical_tags(self, critical, non_critical):
if critical is not None or non_critical is not None:
self.critical.set(critical, non_critical)
self._set_critical_tags(self.critical)
def _set_critical_tags(self, critical):
self.critical = critical
for suite in self.suites:
suite._set_critical_tags(critical)
for test in self.tests:
test.set_criticality(critical)
def set_doc(self, doc):
if doc:
self.doc = doc
def set_metadata(self, metalist):
for name, value in metalist:
self.metadata[name] = value
def get_metadata(self, html=False):
names = sorted(self.metadata.keys())
values = [self.metadata[n] for n in names]
if html:
values = [utils.html_format(v) for v in values]
return zip(names, values)
def get_test_count(self):
count = len(self.tests)
for suite in self.suites:
count += suite.get_test_count()
return count
def get_full_message(self, html=False):
"""Returns suite's message including statistics message"""
stat_msg = self.get_stat_message(html)
if not self.message:
return stat_msg
if not html:
return '%s\n\n%s' % (self.message, stat_msg)
return '%s<br /><br />%s' % (utils.html_escape(self.message), stat_msg)
def get_stat_message(self, html=False):
ctotal, cend, cpass, cfail = self._get_counts(self.critical_stats)
atotal, aend, apass, afail = self._get_counts(self.all_stats)
msg = ('%%d critical test%%s, %%d passed, %(cfail)s%%d failed%(end)s\n'
'%%d test%%s total, %%d passed, %(afail)s%%d failed%(end)s')
if html:
msg = msg.replace(' ', ' ').replace('\n', '<br />')
msg = msg % {'cfail': '<span%s>' % (cfail and ' class="fail"' or ''),
'afail': '<span%s>' % (afail and ' class="fail"' or ''),
'end': '</span>'}
else:
msg = msg % {'cfail': '', 'afail': '', 'end': ''}
return msg % (ctotal, cend, cpass, cfail, atotal, aend, apass, afail)
def _get_counts(self, stat):
total = stat.passed + stat.failed
ending = utils.plural_or_not(total)
return total, ending, stat.passed, stat.failed
def set_status(self):
"""Sets status and statistics based on subsuite and test statuses.
Can/should be used when statuses have been changed somehow.
"""
self.status = self._set_stats()
def _set_stats(self):
self.critical_stats = Stat()
self.all_stats = Stat()
for suite in self.suites:
suite.set_status()
self._add_suite_to_stats(suite)
for test in self.tests:
self._add_test_to_stats(test)
return self._get_status()
def _get_status(self):
return 'PASS' if not self.critical_stats.failed else 'FAIL'
def _add_test_to_stats(self, test):
self.all_stats.add_test(test)
if test.critical == 'yes':
self.critical_stats.add_test(test)
def _add_suite_to_stats(self, suite):
self.critical_stats.add_stat(suite.critical_stats)
self.all_stats.add_stat(suite.all_stats)
def suite_teardown_failed(self, message=None):
if message:
self._set_teardown_fail_msg(message)
self.critical_stats.fail_all()
self.all_stats.fail_all()
self.status = self._get_status()
sub_message = 'Teardown of the parent suite failed.'
for suite in self.suites:
suite.suite_teardown_failed(sub_message)
for test in self.tests:
test.suite_teardown_failed(sub_message)
def set_tags(self, tags):
if tags:
for test in self.tests:
test.tags = utils.normalize_tags(test.tags + tags)
for suite in self.suites:
suite.set_tags(tags)
def filter(self, suites=None, tests=None, includes=None, excludes=None,
zero_tests_ok=False):
self.filter_by_names(suites, tests, zero_tests_ok)
self.filter_by_tags(includes, excludes, zero_tests_ok)
def filter_by_names(self, suites=None, tests=None, zero_tests_ok=False):
if not (suites or tests):
return
suites = [([], name.split('.')) for name in suites or []]
tests = tests or []
if not self._filter_by_names(suites, tests) and not zero_tests_ok:
self._raise_no_tests_filtered_by_names(suites, tests)
def _filter_by_names(self, suites, tests):
suites = self._filter_suite_names(suites)
self.suites = [suite for suite in self.suites
if suite._filter_by_names(suites, tests)]
if not suites:
self.tests = [test for test in self.tests if tests == [] or
any(utils.matches_any(name, tests, ignore=['_'])
for name in [test.name, test.get_long_name()])]
else:
self.tests = []
return bool(self.suites or self.tests)
def _filter_suite_names(self, suites):
try:
return [self._filter_suite_name(p, s) for p, s in suites]
except StopIteration:
return []
def _filter_suite_name(self, parent, suite):
if utils.matches(self.name, suite[0], ignore=['_']):
if len(suite) == 1:
raise StopIteration('Match found')
return (parent + [suite[0]], suite[1:])
return ([], parent + suite)
def _raise_no_tests_filtered_by_names(self, suites, tests):
tests = utils.seq2str(tests, lastsep=' or ')
suites = utils.seq2str(['.'.join(p + s) for p, s in suites],
lastsep=' or ')
if not suites:
msg = 'test cases named %s.' % tests
elif not tests:
msg = 'test suites named %s.' % suites
else:
msg = 'test cases %s in suites %s.' % (tests, suites)
raise DataError("Suite '%s' contains no %s" % (self.name, msg))
def filter_by_tags(self, includes=None, excludes=None, zero_tests_ok=False):
if not (includes or excludes):
return
includes = includes or []
excludes = excludes or []
if not self._filter_by_tags(includes, excludes) and not zero_tests_ok:
self._raise_no_tests_filtered_by_tags(includes, excludes)
def _filter_by_tags(self, incls, excls):
self.suites = [suite for suite in self.suites
if suite._filter_by_tags(incls, excls)]
self.tests = [test for test in self.tests
if test.is_included(incls, excls)]
return bool(self.suites or self.tests)
def _raise_no_tests_filtered_by_tags(self, incls, excls):
incl = utils.seq2str(incls)
excl = utils.seq2str(excls)
msg = "Suite '%s' with " % self.name
if incl:
msg += 'includes %s ' % incl
if excl:
msg += 'and '
if excl:
msg += 'excludes %s ' % excl
raise DataError(msg + 'contains no test cases.')
def set_runmode(self, runmode):
runmode = runmode.upper()
if runmode == 'EXITONFAILURE':
self._run_mode_exit_on_failure = True
elif runmode == 'SKIPTEARDOWNONEXIT':
self._run_mode_skip_teardowns_on_exit = True
elif runmode == 'DRYRUN':
self._run_mode_dry_run = True
elif runmode == 'RANDOM:TEST':
random.shuffle(self.tests)
elif runmode == 'RANDOM:SUITE':
random.shuffle(self.suites)
elif runmode == 'RANDOM:ALL':
random.shuffle(self.suites)
random.shuffle(self.tests)
else:
return
for suite in self.suites:
suite.set_runmode(runmode)
def set_options(self, settings):
self.set_tags(settings['SetTag'])
self.filter(settings['SuiteNames'], settings['TestNames'],
settings['Include'], settings['Exclude'],
settings['RunEmptySuite'])
self.set_name(settings['Name'])
self.set_doc(settings['Doc'])
self.set_metadata(settings['Metadata'])
self.set_critical_tags(settings['Critical'], settings['NonCritical'])
self._return_status_rc = not settings['NoStatusRC']
if 'RunMode' in settings:
map(self.set_runmode, settings['RunMode'])
if 'RemoveKeywords' in settings:
self.remove_keywords(settings['RemoveKeywords'])
def serialize(self, serializer):
serializer.start_suite(self)
if self.setup is not None:
self.setup.serialize(serializer)
if self.teardown is not None:
self.teardown.serialize(serializer)
for suite in self.suites:
suite.serialize(serializer)
for test in self.tests:
test.serialize(serializer)
serializer.end_suite(self)
@property
def return_code(self):
rc = min(self.critical_stats.failed, 250)
return rc if self._return_status_rc else 0
class BaseTestCase(_TestAndSuiteHelper):
def __init__(self, name, parent):
_TestAndSuiteHelper.__init__(self, name, parent)
self.critical = 'yes'
if parent:
parent.tests.append(self)
def suite_teardown_failed(self, message):
self.status = 'FAIL'
self._set_teardown_fail_msg(message)
def set_criticality(self, critical):
self.critical = 'yes' if critical.are_critical(self.tags) else 'no'
def is_included(self, incl_tags, excl_tags):
"""Returns True if this test case is included but not excluded.
If no 'incl_tags' are given all tests are considered to be included.
"""
included = not incl_tags or self._matches_any_tag_rule(incl_tags)
excluded = self._matches_any_tag_rule(excl_tags)
return included and not excluded
def _matches_any_tag_rule(self, tag_rules):
"""Returns True if any of tag_rules matches self.tags
Matching equals supporting AND, & and NOT boolean operators and simple
pattern matching. NOT is 'or' operation meaning if any of the NOTs is
matching, False is returned.
"""
return any(self._matches_tag_rule(rule) for rule in tag_rules)
def _matches_tag_rule(self, tag_rule):
if 'NOT' not in tag_rule:
return self._matches_tag(tag_rule)
nots = tag_rule.split('NOT')
should_match = nots.pop(0)
return self._matches_tag(should_match) \
and not any(self._matches_tag(n) for n in nots)
def _matches_tag(self, tag):
"""Returns True if given tag matches any tag from self.tags.
Note that given tag may be ANDed combination of multiple tags (e.g.
tag1&tag2) and then all of them must match some tag from self.tags.
"""
for item in tag.split('&'):
if not any(utils.matches(t, item, ignore=['_']) for t in self.tags):
return False
return True
def __cmp__(self, other):
if self.status != other.status:
return -1 if self.status == 'FAIL' else 1
if self.critical != other.critical:
return -1 if self.critical == 'yes' else 1
try:
return cmp(self.longname, other.longname)
except AttributeError:
return cmp(self.name, other.name)
def serialize(self, serializer):
serializer.start_test(self)
if self.setup is not None:
self.setup.serialize(serializer)
for kw in self.keywords:
kw.serialize(serializer)
if self.teardown is not None:
self.teardown.serialize(serializer)
serializer.end_test(self)
class _Critical:
def __init__(self, tags=None, nons=None):
self.set(tags, nons)
def set(self, tags, nons):
self.tags = utils.normalize_tags(tags or [])
self.nons = utils.normalize_tags(nons or [])
def is_critical(self, tag):
return utils.matches_any(tag, self.tags)
def is_non_critical(self, tag):
return utils.matches_any(tag, self.nons)
def are_critical(self, tags):
for tag in tags:
if self.is_non_critical(tag):
return False
for tag in tags:
if self.is_critical(tag):
return True
return not self.tags
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from robot import utils
class Statistics:
def __init__(self, suite, suite_stat_level=-1, tag_stat_include=None,
tag_stat_exclude=None, tag_stat_combine=None, tag_doc=None,
tag_stat_link=None):
self.tags = TagStatistics(tag_stat_include, tag_stat_exclude,
tag_stat_combine, tag_doc, tag_stat_link)
self.suite = SuiteStatistics(suite, self.tags, suite_stat_level)
self.total = TotalStatistics(self.suite)
self.tags.sort()
def serialize(self, serializer):
serializer.start_statistics(self)
self.total.serialize(serializer)
self.tags.serialize(serializer)
self.suite.serialize(serializer)
serializer.end_statistics(self)
class Stat:
def __init__(self, name=''):
self.name = name
self.passed = 0
self.failed = 0
def add_stat(self, other):
self.passed += other.passed
self.failed += other.failed
def add_test(self, test):
if test.status == 'PASS':
self.passed += 1
else:
self.failed += 1
def fail_all(self):
self.failed += self.passed
self.passed = 0
def __cmp__(self, other):
return cmp(self.name, other.name)
def __nonzero__(self):
return self.failed == 0
class SuiteStat(Stat):
type = 'suite'
def __init__(self, suite):
Stat.__init__(self, suite.name)
self.long_name = suite.get_long_name()
def serialize(self, serializer):
serializer.suite_stat(self)
class TagStat(Stat):
type = 'tag'
def __init__(self, name, doc='', links=[], critical=False,
non_critical=False, combined=''):
Stat.__init__(self, name)
self.doc = doc
self.links = links
self.critical = critical
self.non_critical = non_critical
self.combined = combined
self.tests = []
def add_test(self, test):
Stat.add_test(self, test)
self.tests.append(test)
def __cmp__(self, other):
if self.critical != other.critical:
return cmp(other.critical, self.critical)
if self.non_critical != other.non_critical:
return cmp(other.non_critical, self.non_critical)
if bool(self.combined) != bool(other.combined):
return cmp(bool(other.combined), bool(self.combined))
return cmp(self.name, other.name)
def serialize(self, serializer):
serializer.tag_stat(self)
class TotalStat(Stat):
type = 'total'
def __init__(self, name, suite_stat):
Stat.__init__(self, name)
self.passed = suite_stat.passed
self.failed = suite_stat.failed
def serialize(self, serializer):
serializer.total_stat(self)
class SuiteStatistics:
def __init__(self, suite, tag_stats, suite_stat_level=-1):
self.all = SuiteStat(suite)
self.critical = SuiteStat(suite)
self.suites = []
self._process_suites(suite, tag_stats)
self._process_tests(suite, tag_stats)
self._suite_stat_level = suite_stat_level
def _process_suites(self, suite, tag_stats):
for subsuite in suite.suites:
substat = SuiteStatistics(subsuite, tag_stats)
self.suites.append(substat)
self.all.add_stat(substat.all)
self.critical.add_stat(substat.critical)
def _process_tests(self, suite, tag_stats):
for test in suite.tests:
self.all.add_test(test)
if test.critical == 'yes':
self.critical.add_test(test)
tag_stats.add_test(test, suite.critical)
def serialize(self, serializer):
serializer.start_suite_stats(self)
self._serialize(serializer, self._suite_stat_level)
serializer.end_suite_stats(self)
def _serialize(self, serializer, max_suite_level, suite_level=1):
self.all.serialize(serializer)
if max_suite_level < 0 or max_suite_level > suite_level:
for suite in self.suites:
suite._serialize(serializer, max_suite_level, suite_level+1)
class TagStatistics:
def __init__(self, include=None, exclude=None, combine=None, docs=None,
links=None):
self.stats = utils.NormalizedDict()
self._include = include or []
self._exclude = exclude or []
self._combine = combine or []
info = TagStatInfo(docs or [], links or [])
self._get_doc = info.get_doc
self._get_links = info.get_links
def add_test(self, test, critical):
self._add_tags_statistics(test, critical)
self._add_combined_statistics(test)
def _add_tags_statistics(self, test, critical):
for tag in test.tags:
if not self._is_included(tag):
continue
if tag not in self.stats:
self.stats[tag] = TagStat(tag, self._get_doc(tag),
self._get_links(tag),
critical.is_critical(tag),
critical.is_non_critical(tag))
self.stats[tag].add_test(test)
def _is_included(self, tag):
if self._include and not utils.matches_any(tag, self._include):
return False
return not utils.matches_any(tag, self._exclude)
def _add_combined_statistics(self, test):
for pattern, name in self._combine:
name = name or pattern
if name not in self.stats:
self.stats[name] = TagStat(name, self._get_doc(name),
self._get_links(name),
combined=pattern)
if test.is_included([pattern], []):
self.stats[name].add_test(test)
def serialize(self, serializer):
serializer.start_tag_stats(self)
for stat in sorted(self.stats.values()):
stat.serialize(serializer)
serializer.end_tag_stats(self)
def sort(self):
for stat in self.stats.values():
stat.tests.sort()
class TotalStatistics:
def __init__(self, suite):
self.critical = TotalStat('Critical Tests', suite.critical)
self.all = TotalStat('All Tests', suite.all)
def serialize(self, serializer):
serializer.start_total_stats(self)
self.critical.serialize(serializer)
self.all.serialize(serializer)
serializer.end_total_stats(self)
class TagStatInfo:
def __init__(self, docs, links):
self._docs = [TagStatDoc(*doc) for doc in docs]
self._links = [TagStatLink(*link) for link in links]
def get_doc(self, tag):
return ' & '.join(doc.text for doc in self._docs if doc.matches(tag))
def get_links(self, tag):
return [link.get_link(tag) for link in self._links if link.matches(tag)]
class TagStatDoc:
def __init__(self, pattern, doc):
self.text = doc
self._pattern = pattern
def matches(self, tag):
return utils.matches(tag, self._pattern)
class TagStatLink:
_match_pattern_tokenizer = re.compile('(\*|\?)')
def __init__(self, pattern, link, title):
self._regexp = self._get_match_regexp(pattern)
self._link = link
self._title = title.replace('_', ' ')
def matches(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
def _replace_groups(self, link, title, match):
for index, group in enumerate(match.groups()):
placefolder = '%' + str(index+1)
link = link.replace(placefolder, group)
title = title.replace(placefolder, group)
return link, title
def _get_match_regexp(self, pattern):
regexp = []
open_parenthesis = False
for token in self._match_pattern_tokenizer.split(pattern):
if token == '':
continue
if token == '?':
if not open_parenthesis:
regexp.append('(')
open_parenthesis = True
regexp.append('.')
continue
if open_parenthesis:
regexp.append(')')
open_parenthesis = False
if token == '*':
regexp.append('(.*)')
continue
regexp.append(re.escape(token))
if open_parenthesis:
regexp.append(')')
return re.compile('^%s$' % ''.join(regexp), re.IGNORECASE)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from robot.errors import DataError
class BaseLibrary:
def get_handler(self, name):
try:
return self.handlers[name]
except KeyError:
raise DataError("No keyword handler with name '%s' found" % name)
def has_handler(self, name):
return self.handlers.has_key(name)
def __len__(self):
return len(self.handlers)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from model import BaseTestSuite, BaseTestCase
from keyword import BaseKeyword
from handlers import UserErrorHandler
from libraries import BaseLibrary
from statistics import Statistics
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""fixml.py -- A tool to fix broken Robot Framework output files
Usage: fixml.py inpath outpath
This tool can fix Robot Framework output files that are not properly finished
or are missing elements from the middle. It should be possible to generate
reports and logs from the fixed output afterwards with the `rebot` tool.
The tool uses BeautifulSoup module which must be installed separately.
See http://www.crummy.com/software/BeautifulSoup for more information.
Additionally, the tool is only compatible with Robot Framework 2.1.3 or newer.
"""
import sys
import os
try:
from BeautifulSoup import BeautifulStoneSoup
except ImportError:
raise ImportError('fixml.py requires BeautifulSoup to be installed: '
'http://www.crummy.com/software/BeautifulSoup/')
class Fixxxer(BeautifulStoneSoup):
NESTABLE_TAGS = {
'suite': ['robot','suite', 'statistics'],
'doc': ['suite', 'test', 'kw'],
'metadata': ['suite'],
'item': ['metadata'],
'status': ['suite', 'test', 'kw'],
'test': ['suite'],
'tags': ['test'],
'tag': ['tags'],
'kw': ['suite', 'test', 'kw'],
'msg': ['kw', 'errors'],
'arguments': ['kw'],
'arg': ['arguments'],
'statistics': ['robot'],
'errors': ['robot'],
}
__close_on_open = None
def unknown_starttag(self, name, attrs, selfClosing=0):
if name == 'robot':
attrs = [ (key, key == 'generator' and 'fixml.py' or value)
for key, value in attrs ]
if name == 'kw' and ('type', 'teardown') in attrs:
while self.tagStack[-1].name not in ['test', 'suite']:
self._popToTag(self.tagStack[-1].name)
if self.__close_on_open:
self._popToTag(self.__close_on_open)
self.__close_on_open = None
BeautifulStoneSoup.unknown_starttag(self, name, attrs, selfClosing)
def unknown_endtag(self, name):
BeautifulStoneSoup.unknown_endtag(self, name)
if name == 'status':
self.__close_on_open = self.tagStack[-1].name
else:
self.__close_on_open = None
def main(inpath, outpath):
outfile = open(outpath, 'w')
outfile.write(str(Fixxxer(open(inpath))))
outfile.close()
return outpath
if __name__ == '__main__':
try:
outpath = main(*sys.argv[1:])
except TypeError:
print __doc__
else:
print os.path.abspath(outpath)
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Start/End/Elapsed Time Reporter
Usage: times2csv.py input-xml [output-csv] [include-items]
This script reads start, end, and elapsed times from all suites, tests and/or
keywords from the given output file, and writes them into an file in
comma-separated-values (CSV) format. CSV files can then be further processed
with spreadsheet programs. If the CSV output file is not given, its name is
got from the input file by replacing the '.xml' extension with '.csv'.
'include-items' can be used for defining which items to process. Possible
values are 'suite', 'test' and 'keyword', and they can be combined to specify
multiple items e.g. like 'suite-test' or 'test-keyword'.
Examples:
$ times2csv.py output.xml
$ times2csv.py path/results.xml path2/times.csv
$ times2csv.py output.xml times.csv test
$ times2csv.py output.xml times.csv suite-test
"""
import sys
import os
import csv
from robot.output import TestSuite
from robot import utils
def process_file(inpath, outpath, items):
suite = TestSuite(inpath)
outfile = open(outpath, 'wb')
writer = csv.writer(outfile)
writer.writerow(['TYPE','NAME','STATUS','START','END','ELAPSED','ELAPSED SECS'])
process_suite(suite, writer, items.lower())
outfile.close()
def process_suite(suite, writer, items, level=0):
if 'suite' in items:
process_item(suite, writer, level, 'Suite')
if 'keyword' in items:
for kw in suite.setup, suite.teardown:
process_keyword(kw, writer, level+1)
for subsuite in suite.suites:
process_suite(subsuite, writer, items, level+1)
for test in suite.tests:
process_test(test, writer, items, level+1)
def process_test(test, writer, items, level):
if 'test' in items:
process_item(test, writer, level, 'Test', 'suite' not in items)
if 'keyword' in items:
for kw in [test.setup] + test.keywords + [test.teardown]:
process_keyword(kw, writer, level+1)
def process_keyword(kw, writer, level):
if kw is None:
return
if kw.type in ['kw', 'set', 'repeat']:
kw_type = 'Keyword'
else:
kw_type = kw.type.capitalize()
process_item(kw, writer, level, kw_type)
for subkw in kw.keywords:
process_keyword(subkw, writer, level+1)
def process_item(item, writer, level, item_type, long_name=False):
if level == 0:
indent = ''
else:
indent = '| ' * (level-1) + '|- '
if long_name:
name = item.longname
else:
name = item.name
writer.writerow([indent+item_type, name, item.status, item.starttime,
item.endtime, utils.elapsed_time_to_string(item.elapsedtime),
item.elapsedtime/1000.0])
if __name__ == '__main__':
if not (2 <= len(sys.argv) <= 4) or '--help' in sys.argv:
print __doc__
sys.exit(1)
inxml = sys.argv[1]
try:
outcsv = sys.argv[2]
except IndexError:
outcsv = os.path.splitext(inxml)[0] + '.csv'
try:
items = sys.argv[3]
except IndexError:
items = 'suite-test-keyword'
process_file(inxml, outcsv, items)
print os.path.abspath(outcsv)
| Python |
#!/usr/bin/env python
# tool2html.py -- Creates HTML version of given tool documentation
#
# First part of this file is Pygments configuration and actual
# documentation generation follows it.
#
# Pygments configuration
#
# This code is from 'external/rst-directive.py' file included in Pygments 0.9
# distribution. For more details see http://pygments.org/docs/rstdirective/
#
"""
The Pygments MoinMoin Parser
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This fragment is a Docutils_ 0.4 directive that renders source code
(to HTML only, currently) via Pygments.
To use it, adjust the options below and copy the code into a module
that you import on initialization. The code then automatically
registers a ``sourcecode`` directive that you can use instead of
normal code blocks like this::
.. sourcecode:: python
My code goes here.
If you want to have different code styles, e.g. one with line numbers
and one without, add formatters with their names in the VARIANTS dict
below. You can invoke them instead of the DEFAULT one by using a
directive option::
.. sourcecode:: python
:linenos:
My code goes here.
Look at the `directive documentation`_ to get all the gory details.
.. _Docutils: http://docutils.sf.net/
.. _directive documentation:
http://docutils.sourceforge.net/docs/howto/rst-directives.html
:copyright: 2007 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
# Options
# ~~~~~~~
# Set to True if you want inline CSS styles instead of classes
INLINESTYLES = False
from pygments.formatters import HtmlFormatter
# The default formatter
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)
# Add name -> formatter pairs for every variant you want to use
VARIANTS = {
# 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
}
import os
from docutils import nodes
from docutils.parsers.rst import directives
from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer
def pygments_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
try:
lexer = get_lexer_by_name(arguments[0])
except ValueError:
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
# take an arbitrary option if more than one is given
formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
filtered = [ line for line in content if line ]
if len(filtered)==1 and os.path.isfile(filtered[0]):
content = open(content[0]).read().splitlines()
parsed = highlight(u'\n'.join(content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
pygments_directive.arguments = (1, 0, 1)
pygments_directive.content = 1
pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
directives.register_directive('sourcecode', pygments_directive)
#
# Creating the documentation
#
# This code is based on rst2html.py distributed with docutils
#
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
import sys
from docutils.core import publish_cmdline
def create_tooldoc(tool_name):
description = 'HTML generator for Robot Framework Tool Documentation.'
stylesheet_path = os.path.join(BASEDIR, '..', 'doc', 'userguide', 'src',
'userguide.css')
base_path = os.path.join(BASEDIR, tool_name, 'doc', tool_name)
arguments = [ '--time', '--stylesheet-path=%s' % stylesheet_path,
base_path+'.txt', base_path+'.html' ]
publish_cmdline(writer_name='html', description=description, argv=arguments)
print os.path.abspath(arguments[-1])
BASEDIR = os.path.dirname(os.path.abspath(__file__))
VALID_TOOLS = [ name for name in os.listdir(BASEDIR) if '.' not in name ]
VALID_TOOLS = [ n for n in VALID_TOOLS if os.path.isdir(os.path.join(BASEDIR, n, 'doc')) ]
if __name__ == '__main__':
try:
tool = sys.argv[1].lower()
if tool == 'all':
for name in sorted(VALID_TOOLS):
create_tooldoc(name)
elif tool in VALID_TOOLS:
create_tooldoc(tool)
else:
raise IndexError
except IndexError:
print 'Usage: tool2html.py [ tool | all ]\n\nTools:'
for tool in sorted(VALID_TOOLS):
print ' %s' % tool
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import inspect
import traceback
from StringIO import StringIO
from SimpleXMLRPCServer import SimpleXMLRPCServer
try:
import signal
except ImportError:
signal = None
class RobotRemoteServer(SimpleXMLRPCServer):
allow_reuse_address = True
def __init__(self, library, host='localhost', port=8270, allow_stop=True):
SimpleXMLRPCServer.__init__(self, (host, int(port)), logRequests=False)
self._library = library
self._allow_stop = allow_stop
self._register_functions()
self._register_signal_handlers()
print 'Robot Framework remote server starting at %s:%s' % (host, port)
self.serve_forever()
def _register_functions(self):
self.register_function(self.get_keyword_names)
self.register_function(self.run_keyword)
self.register_function(self.get_keyword_arguments)
self.register_function(self.get_keyword_documentation)
self.register_function(self.stop_remote_server)
def _register_signal_handlers(self):
def stop_with_signal(signum, frame):
self._allow_stop = True
self.stop_remote_server()
if hasattr(signal, 'SIGHUP'):
signal.signal(signal.SIGHUP, stop_with_signal)
if hasattr(signal, 'SIGINT'):
signal.signal(signal.SIGINT, stop_with_signal)
def serve_forever(self):
self._shutdown = False
while not self._shutdown:
self.handle_request()
def stop_remote_server(self):
prefix = 'Robot Framework remote server at %s:%s ' % self.server_address
if self._allow_stop:
print prefix + 'stopping'
self._shutdown = True
else:
print '*WARN* ' + prefix + 'does not allow stopping'
return True
def get_keyword_names(self):
get_kw_names = getattr(self._library, 'get_keyword_names', None) or \
getattr(self._library, 'getKeywordNames', None)
if inspect.isroutine(get_kw_names):
names = get_kw_names()
else:
names = [attr for attr in dir(self._library) if attr[0] != '_'
and inspect.isroutine(getattr(self._library, attr))]
return names + ['stop_remote_server']
def run_keyword(self, name, args):
result = {'status': 'PASS', 'return': '', 'output': '',
'error': '', 'traceback': ''}
self._intercept_stdout()
try:
return_value = self._get_keyword(name)(*args)
except:
result['status'] = 'FAIL'
result['error'], result['traceback'] = self._get_error_details()
else:
result['return'] = self._handle_return_value(return_value)
result['output'] = self._restore_stdout()
return result
def get_keyword_arguments(self, name):
kw = self._get_keyword(name)
args, varargs, _, defaults = inspect.getargspec(kw)
if inspect.ismethod(kw):
args = args[1:] # drop 'self'
if defaults:
args, names = args[:-len(defaults)], args[-len(defaults):]
args += ['%s=%s' % (n, d) for n, d in zip(names, defaults)]
if varargs:
args.append('*%s' % varargs)
return args
def get_keyword_documentation(self, name):
return inspect.getdoc(self._get_keyword(name)) or ''
def _get_keyword(self, name):
if name == 'stop_remote_server':
return self.stop_remote_server
return getattr(self._library, name)
def _get_error_details(self):
exc_type, exc_value, exc_tb = sys.exc_info()
if exc_type in (SystemExit, KeyboardInterrupt):
self._restore_stdout()
raise
return (self._get_error_message(exc_type, exc_value),
self._get_error_traceback(exc_tb))
def _get_error_message(self, exc_type, exc_value):
name = exc_type.__name__
message = str(exc_value)
if not message:
return name
if name in ('AssertionError', 'RuntimeError', 'Exception'):
return message
return '%s: %s' % (name, message)
def _get_error_traceback(self, exc_tb):
# Latest entry originates from this class so it can be removed
entries = traceback.extract_tb(exc_tb)[1:]
trace = ''.join(traceback.format_list(entries))
return 'Traceback (most recent call last):\n' + trace
def _handle_return_value(self, ret):
if isinstance(ret, (basestring, int, long, float)):
return ret
if isinstance(ret, (tuple, list)):
return [ self._handle_return_value(item) for item in ret ]
if isinstance(ret, dict):
return dict([(self._str(key), self._handle_return_value(value))
for key, value in ret.items()])
return self._str(ret)
def _str(self, item):
if item is None:
return ''
return str(item)
def _intercept_stdout(self):
# TODO: What about stderr?
sys.stdout = StringIO()
def _restore_stdout(self):
output = sys.stdout.getvalue()
sys.stdout.close()
sys.stdout = sys.__stdout__
return output
| Python |
#!/usr/bin/env python
import os
import sys
class ExampleRemoteLibrary:
def count_items_in_directory(self, path):
return len(i for i in os.listdir(path) if not i.startswith('.'))
def strings_should_be_equal(self, str1, str2):
print "Comparing '%s' to '%s'" % (str1, str2)
if str1 != str2:
raise AssertionError("Given strings are not equal")
if __name__ == '__main__':
from robotremoteserver import RobotRemoteServer
RobotRemoteServer(ExampleRemoteLibrary(), *sys.argv[1:])
| Python |
import sys
from SimpleXMLRPCServer import SimpleXMLRPCServer
class SimpleLibrary(SimpleXMLRPCServer):
def __init__(self, port=8270):
SimpleXMLRPCServer.__init__(self, ('localhost', int(port)))
self.register_function(self.get_keyword_names)
self.register_function(self.run_keyword)
self.register_function(self.stop_remote_server)
self.serve_forever()
def serve_forever(self):
self._shutdown = False
while not self._shutdown:
self.handle_request()
def stop_remote_server(self):
self._shutdown = True
return True
def get_keyword_names(self):
return ['kw_1', 'kw_2', 'stop_remote_server']
def run_keyword(self, name, args):
if name == 'kw_1':
return {'status': 'PASS', 'return': ' '.join(args)}
elif name == 'kw_2':
return {'status': 'FAIL', 'error': ' '.join(args)}
else:
self.stop_remote_server()
return {'status': 'PASS'}
if __name__ == '__main__':
SimpleLibrary(*sys.argv[1:])
| Python |
# Can be used in the test data like ${MyObject()} or ${MyObject(1)}
class MyObject:
def __init__(self, index=''):
self.index = index
def __str__(self):
return '<MyObject%s>' % self.index
UNICODE = (u'Hyv\u00E4\u00E4 y\u00F6t\u00E4. '
u'\u0421\u043F\u0430\u0441\u0438\u0431\u043E!')
LIST_WITH_OBJECTS = [MyObject(1), MyObject(2)]
NESTED_LIST = [ [True, False], [[1, None, MyObject(), {}]] ]
NESTED_TUPLE = ( (True, False), [(1, None, MyObject(), {})] )
DICT_WITH_OBJECTS = {'As value': MyObject(1), MyObject(2): 'As key'}
NESTED_DICT = { 1: {None: False},
2: {'A': {'n': None},
'B': {'o': MyObject(), 'e': {}}} }
| Python |
#!/usr/bin/env python
"""Script for running the remote library tests against different servers.
Usage 1: run.py language[:runner] [[options] datasources]
Valid languages are 'python', 'jython' or 'ruby', and runner can
either by 'pybot' (default) or 'jybot'. By default, all tests under
'test/data' directory are run, but this can be changed by providing
options, which can be any Robot Framework command line options.
Usage 2: run.py stop [port]
Stops remote server in specified port. Default port is 8270.
"""
import sys
import xmlrpclib
import time
import os
import subprocess
import shutil
import socket
REMOTEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUTPUTDIR = os.path.join(REMOTEDIR, 'test', 'logs')
if os.path.exists(OUTPUTDIR):
shutil.rmtree(OUTPUTDIR)
os.mkdir(OUTPUTDIR)
class Library:
def __init__(self, language=None):
if language:
self._start_library(language)
if not self.test(attempts=15):
raise RuntimeError("Starting %s library failed" % language)
def _start_library(self, lang):
opts = self._environment_setup(lang)
ext = {'python': 'py', 'jython': 'py', 'ruby': 'rb'}[lang]
lib = os.path.join(REMOTEDIR, 'test', 'libs', 'examplelib.%s' % ext)
stdout = os.path.join(OUTPUTDIR, 'stdout.txt')
stderr = os.path.join(OUTPUTDIR, 'stderr.txt')
cmd = '%s%s%s 1> %s 2> %s' % (lang, opts, lib, stdout, stderr)
print 'Starting %s remote library with command:\n%s' % (lang, cmd)
subprocess.Popen(cmd, shell=True)
def _environment_setup(self, lang):
if lang == 'jython':
return ' -Dpython.path=%s ' % REMOTEDIR
varname = {'python': 'PYTHONPATH', 'ruby': 'LOAD_PATH'}[lang]
os.environ[varname] = REMOTEDIR
print '%s: %s' % (varname, REMOTEDIR)
return ' '
def test(self, port=8270, attempts=1):
url = 'http://localhost:%s' % port
for i in range(attempts):
try:
xmlrpclib.ServerProxy(url).get_keyword_names()
except socket.error, (errno, errmsg):
time.sleep(1)
except xmlrpclib.Error, err:
errmsg = err.faultString
break
else:
print "Remote library is running on port %s" % port
return True
print "Failed to connect to library on port %s: %s" % (port, errmsg)
return False
def stop(self, port=8270):
if self.test(port):
server = xmlrpclib.ServerProxy('http://localhost:%s' % port)
server.stop_remote_server()
print "Remote library on port %s stopped" % port
if __name__ == '__main__':
if len(sys.argv) < 2:
print __doc__
sys.exit(1)
mode = sys.argv[1]
if mode == 'stop':
Library().stop(*sys.argv[2:])
sys.exit()
if ':' in mode:
lang, runner = mode.split(':')
else:
lang, runner = mode, 'pybot'
lib = Library(lang)
include = lang if lang != 'jython' else 'python'
output = os.path.join(OUTPUTDIR, 'output.xml')
args = [runner, '--log', 'NONE', '--report', 'NONE', '--output', output,
'--name', mode, '--include', include, '--noncritical', 'non-critical']
if len(sys.argv) == 2:
args.append(os.path.join(REMOTEDIR, 'test', 'atest'))
else:
args.extend(sys.argv[2:])
print 'Running tests with command:\n%s' % ' '.join(args)
subprocess.call(args)
lib.stop()
print
checker = os.path.join(REMOTEDIR, '..', 'statuschecker', 'statuschecker.py')
subprocess.call(['python', checker, output])
rc = subprocess.call(['rebot', '--noncritical', 'non-critical',
'--outputdir', OUTPUTDIR, output])
if rc == 0:
print 'All tests passed'
else:
print '%d test%s failed' % (rc, 's' if rc != 1 else '')
| Python |
import sys
class RemoteTestLibrary:
_unicode = (u'Hyv\u00E4\u00E4 y\u00F6t\u00E4. '
u'\u0421\u043F\u0430\u0441\u0438\u0431\u043E!')
def get_server_language(self):
lang = sys.platform.startswith('java') and 'jython' or 'python'
return '%s%d%d' % (lang, sys.version_info[0], sys.version_info[1])
# Basic communication (and documenting keywords)
def passing(self):
"""This keyword passes.
See `Failing`, `Logging`, and `Returning` for other basic keywords.
"""
pass
def failing(self, message):
"""This keyword fails with provided `message`"""
raise AssertionError(message)
def logging(self, message, level='INFO'):
"""This keywords logs given `message` with given `level`
Example:
| Logging | Hello, world! | |
| Logging | Warning!!! | WARN |
"""
print '*%s* %s' % (level, message)
def returning(self):
"""This keyword returns a string 'returned string'."""
return 'returned string'
# Logging
def one_message_without_level(self):
print 'Hello, world!'
def multiple_messages_with_different_levels(self):
print 'Info message'
print '*DEBUG* Debug message'
print '*INFO* Second info'
print 'this time with two lines'
print '*INFO* Third info'
print '*TRACE* This is ignored'
print '*WARN* Warning'
def log_unicode(self):
print self._unicode
def logging_and_failing(self):
print '*INFO* This keyword will fail!'
print '*WARN* Run for your lives!!'
raise AssertionError('Too slow')
def logging_and_returning(self):
print 'Logged message'
return 'Returned value'
def log_control_char(self):
print '\x01'
# Failures
def base_exception(self):
raise Exception('My message')
def exception_without_message(self):
raise Exception
def assertion_error(self):
raise AssertionError('Failure message')
def runtime_error(self):
raise RuntimeError('Error message')
def name_error(self):
non_existing
def attribute_error(self):
self.non_existing
def index_error(self):
[][0]
def zero_division(self):
1/0
def custom_exception(self):
raise MyException('My message')
def failure_deeper(self, rounds=10):
if rounds == 1:
raise RuntimeError('Finally failing')
self.failure_deeper(rounds-1)
# Arguments counts
def no_arguments(self):
return 'no arguments'
def one_argument(self, arg):
return arg
def two_arguments(self, arg1, arg2):
return '%s %s' % (arg1, arg2)
def seven_arguments(self, arg1, arg2, arg3, arg4, arg5, arg6, arg7):
return ' '.join((arg1, arg2, arg3, arg4, arg5, arg6, arg7))
def arguments_with_default_values(self, arg1, arg2='2', arg3=3):
return '%s %s %s' % (arg1, arg2, arg3)
def variable_number_of_arguments(self, *args):
return ' '.join(args)
def required_defaults_and_varargs(self, req, default='world', *varargs):
return ' '.join((req, default) + varargs)
# Argument types
def string_as_argument(self, arg):
self._should_be_equal(arg, self.return_string())
def unicode_string_as_argument(self, arg):
self._should_be_equal(arg, self._unicode)
def empty_string_as_argument(self, arg):
self._should_be_equal(arg, '')
def integer_as_argument(self, arg):
self._should_be_equal(arg, self.return_integer())
def negative_integer_as_argument(self, arg):
self._should_be_equal(arg, self.return_negative_integer())
def float_as_argument(self, arg):
self._should_be_equal(arg, self.return_float())
def negative_float_as_argument(self, arg):
self._should_be_equal(arg, self.return_negative_float())
def zero_as_argument(self, arg):
self._should_be_equal(arg, 0)
def boolean_true_as_argument(self, arg):
self._should_be_equal(arg, True)
def boolean_false_as_argument(self, arg):
self._should_be_equal(arg, False)
def none_as_argument(self, arg):
self._should_be_equal(arg, '')
def object_as_argument(self, arg):
self._should_be_equal(arg, '<MyObject>')
def list_as_argument(self, arg):
self._should_be_equal(arg, self.return_list())
def empty_list_as_argument(self, arg):
self._should_be_equal(arg, [])
def list_containing_none_as_argument(self, arg):
self._should_be_equal(arg, [''])
def list_containing_objects_as_argument(self, arg):
self._should_be_equal(arg, ['<MyObject1>', '<MyObject2>'])
def nested_list_as_argument(self, arg):
exp = [ [True, False], [[1, '', '<MyObject>', {}]] ]
self._should_be_equal(arg, exp)
def dictionary_as_argument(self, arg):
self._should_be_equal(arg, self.return_dictionary())
def empty_dictionary_as_argument(self, arg):
self._should_be_equal(arg, {})
def dictionary_with_non_string_keys_as_argument(self, arg):
self._should_be_equal(arg, {'1': 2, '': True})
def dictionary_containing_none_as_argument(self, arg):
self._should_be_equal(arg, {'As value': '', '': 'As key'})
def dictionary_containing_objects_as_argument(self, arg):
self._should_be_equal(arg, {'As value': '<MyObject1>', '<MyObject2>': 'As key'})
def nested_dictionary_as_argument(self, arg):
exp = { '1': {'': False},
'2': {'A': {'n': ''}, 'B': {'o': '<MyObject>', 'e': {}}} }
self._should_be_equal(arg, exp)
def _should_be_equal(self, arg, exp):
if arg != exp:
raise AssertionError('%r != %r' % (arg, exp))
# Return values
def return_string(self):
return 'Hello, world!'
def return_unicode_string(self):
return self._unicode
def return_empty_string(self):
return ''
def return_integer(self):
return 42
def return_negative_integer(self):
return -1
def return_float(self):
return 3.14
def return_negative_float(self):
return -0.5
def return_zero(self):
return 0
def return_boolean_true(self):
return True
def return_boolean_false(self):
return False
def return_nothing(self):
pass
def return_object(self):
return MyObject()
def return_list(self):
return ['One', -2, False]
def return_empty_list(self):
return []
def return_list_containing_none(self):
return [None]
def return_list_containing_objects(self):
return [MyObject(1), MyObject(2)]
def return_nested_list(self):
return [ [True, False], [[1, None, MyObject(), {}]] ]
def return_tuple(self):
return (1, 'two', True)
def return_empty_tuple(self):
return ()
def return_nested_tuple(self):
return ( (True, False), [(1, None, MyObject(), {})] )
def return_dictionary(self):
return {'one': 1, 'spam': 'eggs'}
def return_empty_dictionary(self):
return {}
def return_dictionary_with_non_string_keys(self):
return {1: 2, None: True}
def return_dictionary_containing_none(self):
return {'As value': None, None: 'As key'}
def return_dictionary_containing_objects(self):
return {'As value': MyObject(1), MyObject(2): 'As key'}
def return_nested_dictionary(self):
return { 1: {None: False},
2: {'A': {'n': None}, 'B': {'o': MyObject(), 'e': {}}} }
def return_control_char(self):
return '\x01'
# Not keywords
def _private_method(self):
pass
def __private_method(self):
pass
attribute = 'Not a keyword'
class MyObject:
def __init__(self, index=''):
self.index = index
def __str__(self):
return '<MyObject%s>' % self.index
class MyException(Exception):
pass
if __name__ == '__main__':
import sys
from robotremoteserver import RobotRemoteServer
RobotRemoteServer(RemoteTestLibrary(), *sys.argv[1:])
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Library and Resource File Documentation Generator
Usage: libdoc.py [options] library_or_resource
This script can generate keyword documentation in HTML and XML formats. The
former is suitable for humans and the latter for RIDE, RFDoc, and other tools.
This script can also upload XML documentation to RFDoc system.
Documentation can be created for both test libraries and resource files. All
library and resource file types are supported, and also earlier generated
documentation in XML format can be used as input.
Options:
-a --argument value * Possible arguments that a library needs.
-f --format HTML|XML Specifies whether to generate HTML or XML output.
The default value is got from the output file
extension and if the output is not specified the
default is HTML.
-o --output path Where to write the generated documentation. Can be
either a directory or a file, or a URL pointing to
RFDoc system's upload page. The default value is the
directory where the script is executed from. If
a URL is given, it must start with 'http://'.
-N --name newname Sets the name of the documented library or resource.
-T --title title Sets the title of the generated HTML documentation.
Underscores in the given title are automatically
converted to spaces.
-S --styles styles Overrides the default styles. If the given 'styles'
is a path to an existing files, styles will be read
from it. If it is string a 'NONE', no styles will be
used. Otherwise the given text is used as-is.
-P --pythonpath path * Additional path(s) to insert into PYTHONPATH.
-E --escape what:with * Escapes characters which are problematic in console.
'what' is the name of the character to escape and
'with' is the string to escape it with.
<-------------------ESCAPES------------------------>
-h --help Print this help.
For more information see either the tool's wiki page at
http://code.google.com/p/robotframework/wiki/LibraryDocumentationTool
or tools/libdoc/doc/libdoc.html file inside source distributions.
"""
from __future__ import with_statement
import sys
import os
import re
import tempfile
from httplib import HTTPConnection
from HTMLParser import HTMLParser
from robot.running import TestLibrary, UserLibrary
from robot.utils.templating import Template, Namespace
from robot.errors import DataError, Information
from robot.parsing import populators
from robot import utils
populators.PROCESS_CURDIR = False
def _uploading(output):
return output.startswith('http://')
def create_html_doc(lib, outpath, title=None, styles=None):
if title:
title = title.replace('_', ' ')
else:
title = lib.name
generated = utils.get_timestamp(daysep='-', millissep=None)
namespace = Namespace(LIB=lib, TITLE=title, STYLES=_get_styles(styles),
GENERATED=generated)
doc = Template(template=HTML_TEMPLATE).generate(namespace) + '\n'
outfile = open(outpath, 'w')
outfile.write(doc.encode('UTF-8'))
outfile.close()
def _get_styles(styles):
if not styles:
return DEFAULT_STYLES
if styles.upper() == 'NONE':
return ''
if os.path.isfile(styles):
with open(styles) as f:
return f.read()
return styles
def create_xml_doc(lib, outpath):
writer = utils.XmlWriter(outpath)
writer.start('keywordspec', {'name': lib.name, 'type': lib.type, 'generated': utils.get_timestamp(millissep=None)})
writer.element('version', lib.version)
writer.element('scope', lib.scope)
writer.element('doc', lib.doc)
_write_keywords_to_xml(writer, 'init', lib.inits)
_write_keywords_to_xml(writer, 'kw', lib.keywords)
writer.end('keywordspec')
writer.close()
def upload_xml_doc(outpath, uploadurl):
RFDocUploader().upload(outpath, uploadurl)
def _write_keywords_to_xml(writer, kwtype, keywords):
for kw in keywords:
attrs = kwtype == 'kw' and {'name': kw.name} or {}
writer.start(kwtype, attrs)
writer.element('doc', kw.doc)
writer.start('arguments')
for arg in kw.args:
writer.element('arg', arg)
writer.end('arguments')
writer.end(kwtype)
def LibraryDoc(libname, arguments=None, newname=None):
ext = os.path.splitext(libname)[1].lower()
if ext in ('.html', '.htm', '.xhtml', '.tsv', '.txt', '.rst', '.rest'):
return ResourceDoc(libname, arguments, newname)
elif ext == '.xml':
return XmlLibraryDoc(libname, newname)
elif ext == '.java':
if not utils.is_jython:
raise DataError('Documenting Java test libraries requires using Jython.')
return JavaLibraryDoc(libname, newname)
else:
return PythonLibraryDoc(libname, arguments, newname)
class _DocHelper:
_name_regexp = re.compile("`(.+?)`")
_list_or_table_regexp = re.compile('^(\d+\.|[-*|]|\[\d+\]) .')
def __getattr__(self, name):
if name == 'htmldoc':
return self._get_htmldoc(self.doc)
if name == 'htmlshortdoc':
return utils.html_attr_escape(self.shortdoc)
if name == 'htmlname':
return utils.html_attr_escape(self.name)
raise AttributeError("Non-existing attribute '%s'" % name)
def _process_doc(self, doc):
ret = ['']
for line in doc.splitlines():
line = line.strip()
ret.append(self._get_doc_line_separator(line, ret[-1]))
ret.append(line)
return ''.join(ret)
def _get_doc_line_separator(self, line, prev):
if prev == '':
return ''
if line == '':
return '\n\n'
if self._list_or_table_regexp.search(line):
return '\n'
if prev.startswith('| ') and prev.endswith(' |'):
return '\n'
if self.type == 'resource':
return '\n\n'
return ' '
def _get_htmldoc(self, doc):
doc = utils.html_escape(doc, formatting=True)
return self._name_regexp.sub(self._link_keywords, doc)
def _link_keywords(self, res):
name = res.group(1)
try:
lib = self.lib
except AttributeError:
lib = self
for kw in lib.keywords:
if utils.eq(name, kw.name):
return '<a href="#%s" class="name">%s</a>' % (kw.name, name)
if utils.eq_any(name, ['introduction', 'library introduction']):
return '<a href="#introduction" class="name">%s</a>' % name
if utils.eq_any(name, ['importing', 'library importing']):
return '<a href="#importing" class="name">%s</a>' % name
return '<span class="name">%s</span>' % name
class PythonLibraryDoc(_DocHelper):
type = 'library'
def __init__(self, name, arguments=None, newname=None):
lib = self._import(name, arguments)
self.supports_named_arguments = lib.supports_named_arguments
self.name = newname or lib.name
self.version = utils.html_escape(getattr(lib, 'version', '<unknown>'))
self.scope = self._get_scope(lib)
self.doc = self._process_doc(self._get_doc(lib))
self.inits = self._get_initializers(lib)
self.keywords = [ KeywordDoc(handler, self)
for handler in lib.handlers.values() ]
self.keywords.sort()
def _import(self, name, args):
return TestLibrary(name, args)
def _get_scope(self, lib):
if hasattr(lib, 'scope'):
return {'TESTCASE': 'test case', 'TESTSUITE': 'test suite',
'GLOBAL': 'global'}[lib.scope]
return ''
def _get_doc(self, lib):
return lib.doc or "Documentation for test library `%s`." % self.name
def _get_initializers(self, lib):
if lib.init.arguments.maxargs == 0:
return []
return [KeywordDoc(lib.init, self)]
class ResourceDoc(PythonLibraryDoc):
type = 'resource'
supports_named_arguments = True
def _import(self, path, arguments):
if arguments:
raise DataError("Resource file cannot take arguments.")
return UserLibrary(self._find_resource_file(path))
def _find_resource_file(self, path):
if os.path.isfile(path):
return path
for dire in [ item for item in sys.path if os.path.isdir(item) ]:
if os.path.isfile(os.path.join(dire, path)):
return os.path.join(dire, path)
raise DataError("Resource file '%s' doesn't exist." % path)
def _get_doc(self, resource):
doc = getattr(resource, 'doc', '') # doc available only in 2.1+
if not doc:
doc = "Documentation for resource file `%s`." % self.name
return utils.unescape(doc)
def _get_initializers(self, lib):
return []
class XmlLibraryDoc(_DocHelper):
def __init__(self, libname, newname):
dom = utils.DomWrapper(libname)
self.name = dom.get_attr('name')
self.type = dom.get_attr('type')
self.version = dom.get_node('version').text
self.scope = dom.get_node('scope').text
self.doc = dom.get_node('doc').text
self.inits = [ XmlKeywordDoc(node, self) for node in dom.get_nodes('init') ]
self.keywords = [ XmlKeywordDoc(node, self) for node in dom.get_nodes('kw') ]
class _BaseKeywordDoc(_DocHelper):
def __init__(self, library):
self.lib = library
self.type = library.type
def __cmp__(self, other):
return cmp(self.name.lower(), other.name.lower())
def __getattr__(self, name):
if name == 'argstr':
return ', '.join(self.args)
return _DocHelper.__getattr__(self, name)
def __repr__(self):
return "'Keyword %s from library %s'" % (self.name, self.lib.name)
class KeywordDoc(_BaseKeywordDoc):
def __init__(self, handler, library):
_BaseKeywordDoc.__init__(self, library)
self.name = handler.name
self.args = self._get_args(handler)
self.doc = self._process_doc(handler.doc)
self.shortdoc = handler.shortdoc
def _get_args(self, handler):
required, defaults, varargs = self._parse_args(handler)
args = required + [ '%s=%s' % item for item in defaults ]
if varargs is not None:
args.append('*%s' % varargs)
return args
def _parse_args(self, handler):
args = [ arg.rstrip('_') for arg in handler.arguments.names ]
# strip ${} from user keywords (args look more consistent e.g. in IDE)
if handler.type == 'user':
args = [ arg[2:-1] for arg in args ]
default_count = len(handler.arguments.defaults)
if default_count == 0:
required = args[:]
defaults = []
else:
required = args[:-default_count]
defaults = zip(args[-default_count:], list(handler.arguments.defaults))
varargs = handler.arguments.varargs
varargs = varargs is not None and varargs.rstrip('_') or varargs
if handler.type == 'user' and varargs is not None:
varargs = varargs[2:-1]
return required, defaults, varargs
class XmlKeywordDoc(_BaseKeywordDoc):
def __init__(self, node, library):
_BaseKeywordDoc.__init__(self, library)
self.name = node.get_attr('name', '')
self.args = [ arg.text for arg in node.get_nodes('arguments/arg') ]
self.doc = node.get_node('doc').text
self.shortdoc = self.doc and self.doc.splitlines()[0] or ''
if utils.is_jython:
class JavaLibraryDoc(_DocHelper):
type = 'library'
supports_named_arguments = False
def __init__(self, path, newname=None):
cls = self._get_class(path)
self.name = newname or cls.qualifiedName()
self.version = self._get_version(cls)
self.scope = self._get_scope(cls)
self.doc = self._process_doc(cls.getRawCommentText())
self.keywords = [ JavaKeywordDoc(method, self)
for method in cls.methods() ]
self.inits = [ JavaKeywordDoc(init, self)
for init in cls.constructors() ]
if len(self.inits) == 1 and not self.inits[0].args:
self.inits = []
self.keywords.sort()
def _get_class(self, path):
"""Processes the given Java source file and returns ClassDoc.
Processing is done using com.sun.tools.javadoc APIs. The usage has
been figured out from sources at
http://www.java2s.com/Open-Source/Java-Document/JDK-Modules-com.sun/tools/com.sun.tools.javadoc.htm
Returned object implements com.sun.javadoc.ClassDoc interface, see
http://java.sun.com/j2se/1.4.2/docs/tooldocs/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.py')
jdoctool = JavadocTool.make0(context)
filter = ModifierFilter(PUBLIC)
java_names = List.of(path)
root = jdoctool.getRootDocImpl('en', 'utf-8', filter, java_names,
List.nil(), False, List.nil(),
List.nil(), False, False, True)
return root.classes()[0]
def _get_version(self, cls):
version = self._get_attr(cls, 'VERSION', '<unknown>')
return utils.html_escape(version)
def _get_scope(self, cls):
scope = self._get_attr(cls, 'SCOPE', 'TEST CASE')
return scope.replace('_', ' ').lower()
def _get_attr(self, cls, name, default):
for field in cls.fields():
if field.name() == 'ROBOT_LIBRARY_' + name \
and field.isPublic() and field.constantValue():
return field.constantValue()
return default
class JavaKeywordDoc(_BaseKeywordDoc):
# TODO: handle keyword default values and varargs.
def __init__(self, method, library):
_BaseKeywordDoc.__init__(self, library)
self.name = utils.printable_name(method.name(), True)
self.args = [ param.name() for param in method.parameters() ]
self.doc = self._process_doc(method.getRawCommentText())
self.shortdoc = self.doc and self.doc.splitlines()[0] or ''
class RFDocUploader(object):
def upload(self, file_path, host):
if host.startswith('http://'):
host = host[len('http://'):]
xml_file = open(file_path, 'rb')
conn = HTTPConnection(host)
try:
resp = self._post_multipart(conn, xml_file)
self._validate_success(resp)
finally:
xml_file.close()
conn.close()
def _post_multipart(self, conn, xml_file):
conn.connect()
content_type, body = self._encode_multipart_formdata(xml_file)
headers = {'User-Agent': 'libdoc.py', 'Content-Type': content_type}
conn.request('POST', '/upload/', body, headers)
return conn.getresponse()
def _encode_multipart_formdata(self, xml_file):
boundary = '----------ThIs_Is_tHe_bouNdaRY_$'
body = """--%(boundary)s
Content-Disposition: form-data; name="override"
on
--%(boundary)s
Content-Disposition: form-data; name="file"; filename="%(filename)s"
Content-Type: text/xml
%(content)s
--%(boundary)s--
""" % {'boundary': boundary, 'filename': xml_file.name, 'content': xml_file.read()}
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body.replace('\n', '\r\n')
def _validate_success(self, resp):
html = resp.read()
if resp.status != 200:
raise DataError(resp.reason.strip())
if 'Successfully uploaded library' not in html:
raise DataError('\n'.join(_ErrorParser(html).errors))
class _ErrorParser(HTMLParser):
def __init__(self, html):
HTMLParser.__init__(self)
self._inside_errors = False
self.errors = []
self.feed(html)
self.close()
def handle_starttag(self, tag, attributes):
if ('class', 'errorlist') in attributes:
self._inside_errors = True
def handle_endtag(self, tag):
if tag == 'ul':
self._inside_errors = False
def handle_data(self, data):
if self._inside_errors and data.strip():
self.errors.append(data)
DEFAULT_STYLES = '''
<style media="all" type="text/css">
body {
background: white;
color: black;
font-size: small;
font-family: sans-serif;
padding: 0.1em 0.5em;
}
a.name, span.name {
font-style: italic;
}
a, a:link, a:visited {
color: #c30;
}
a:hover, a:active {
text-decoration: underline;
color: black;
}
div.shortcuts {
margin: 1em 0em;
font-size: 0.9em;
}
div.shortcuts a {
text-decoration: none;
color: black;
}
div.shortcuts a:hover {
text-decoration: underline;
}
table.keywords {
border: 2px solid black;
border-collapse: collapse;
empty-cells: show;
margin: 0.3em 0em;
width: 100%;
}
table.keywords th, table.keywords td {
border: 2px solid black;
padding: 0.2em;
vertical-align: top;
}
table.keywords th {
background: #bbb;
color: black;
}
table.keywords td.kw {
width: 150px;
font-weight: bold;
}
table.keywords td.arg {
width: 300px;
font-style: italic;
}
table.doc {
border: 1px solid black;
background: transparent;
border-collapse: collapse;
empty-cells: show;
font-size: 0.85em;
}
table.doc td {
border: 1px solid black;
padding: 0.1em 0.3em;
height: 1.2em;
}
#footer {
font-size: 0.9em;
}
</style>
<style media="print" type="text/css">
body {
margin: 0px 1px;
padding: 0px;
font-size: 10px;
}
a {
text-decoration: none;
}
</style>
'''.strip()
HTML_TEMPLATE = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>${TITLE}</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
${STYLES}
</head>
<body>
<h1>${TITLE}</h1>
<!-- IF "${LIB.version}" != "<unknown>" -->
<b>Version:</b> ${LIB.version}<br>
<!-- END IF -->
<!-- IF "${LIB.type}" == "library" -->
<b>Scope:</b> ${LIB.scope}<br>
<!-- END IF -->
<b>Named arguments: </b>
<!-- IF ${LIB.supports_named_arguments} -->
supported
<!-- ELSE -->
not supported
<!-- END IF -->
<h2 id="introduction">Introduction</h2>
<p>${LIB.htmldoc}</p>
<!-- IF ${LIB.inits} -->
<h2 id="importing">Importing</h2>
<table border="1" class="keywords">
<tr>
<th class="arg">Arguments</th>
<th class="doc">Documentation</th>
</tr>
<!-- FOR ${init} IN ${LIB.inits} -->
<tr>
<td class="arg">${init.argstr}</td>
<td class="doc">${init.htmldoc}</td>
</tr>
<!-- END FOR -->
</table>
<!-- END IF -->
<h2>Shortcuts</h2>
<div class='shortcuts'>
<!-- FOR ${kw} IN ${LIB.keywords} -->
<a href="#${kw.htmlname}" title="${kw.htmlshortdoc}">${kw.htmlname.replace(' ',' ')}</a>
<!-- IF ${kw} != ${LIB.keywords[-1]} -->
·
<!-- END IF -->
<!-- END FOR -->
</div>
<h2>Keywords</h2>
<table border="1" class="keywords">
<tr>
<th class="kw">Keyword</th>
<th class="arg">Arguments</th>
<th class="doc">Documentation</th>
</tr>
<!-- FOR ${kw} IN ${LIB.keywords} -->
<tr>
<td class="kw"><a name="${kw.htmlname}"></a>${kw.htmlname}</td>
<td class="arg">${kw.argstr}</td>
<td class="doc">${kw.htmldoc}</td>
</tr>
<!-- END FOR -->
</table>
<p id="footer">
Altogether ${LIB.keywords.__len__()} keywords.<br />
Generated by <a href="http://code.google.com/p/robotframework/wiki/LibraryDocumentationTool">libdoc.py</a>
on ${GENERATED}.
</p>
</body>
</html>
'''
if __name__ == '__main__':
def get_format(format, output):
if format:
return format.upper()
if os.path.splitext(output)[1].upper() == '.XML':
return 'XML'
return 'HTML'
def get_unique_path(base, ext, index=0):
if index == 0:
path = '%s.%s' % (base, ext)
else:
path = '%s-%d.%s' % (base, index, ext)
if os.path.exists(path):
return get_unique_path(base, ext, index+1)
return path
try:
argparser = utils.ArgumentParser(__doc__)
opts, args = argparser.parse_args(sys.argv[1:], pythonpath='pythonpath',
help='help', unescape='escape',
check_args=True)
libname = args[0]
library = LibraryDoc(libname, opts['argument'], opts['name'])
output = opts['output'] or '.'
if _uploading(output):
file_path = os.path.join(tempfile.gettempdir(), 'libdoc_upload.xml')
create_xml_doc(library, file_path)
upload_xml_doc(file_path, output)
os.remove(file_path)
else:
format = get_format(opts['format'], output)
if os.path.isdir(output):
output = get_unique_path(os.path.join(output, library.name), format.lower())
output = os.path.abspath(output)
if format == 'HTML':
create_html_doc(library, output, opts['title'], opts['styles'])
else:
create_xml_doc(library, output)
except Information, msg:
print msg
except DataError, err:
print err, '\n\nTry --help for usage information.'
except Exception, err:
print err
else:
print '%s -> %s' % (library.name, output)
| Python |
class regular:
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
"""This is a very regular test library"""
def __init__(self, arg1='hello', arg2='world'):
"""Constructs a new regular test library
See `keyword`
Examples:
| regular | foo | bar |
| regular | | # default values are used |
"""
self.arg1 = arg1
self.arg2 = arg2
def keyword(self):
"""A "keyword" & it contains 'stuff' to <escape>
See `get hello` for details"""
pass
def get_hello(self):
"""Get the intialization variables
See `importing` for explanation of arguments
and `introduction` for introduction"""
return self.arg1, self.arg2
| Python |
class RequiredArgs:
def __init__(self, required, arguments, default="value"):
"""This library always needs two arguments and has one default.
Keyword names are got from the given arguments.
"""
self.__dict__[required] = lambda: None
self.__dict__[arguments] = lambda arg: None
self.__dict__[default] = lambda arg1, arg2: None
| Python |
class new_style_no_init(object):
"""No __init__ on this one."""
def kw(self):
"""The only lonely keyword."""
| Python |
class no_arg_init:
def __init__(self):
"""This doc not shown because there are no arguments."""
def keyword(self):
"""A keyword.
See `get hello` for details and *never* run this keyword.
"""
1/0
def get_hello(self, arg):
"""Returns 'Hello `arg`!'.
See `importing` for explanation of arguments and `introduction`
for introduction. Neither of them really exist, though.
"""
return 'Hello %s' % arg
| Python |
class dynamic:
def get_keyword_names(self):
return ['Keyword 1', 'KW 2']
def run_keyword(self, name, args):
print name, args
def get_keyword_arguments(self, name):
return [ 'arg%d' % (i+1) for i in range(int(name[-1])) ]
def get_keyword_documentation(self, name):
return '''Dummy documentation for `%s`.
Neither `Keyword 1` or `KW 2` do anything really interesting.
They do, however, accept some `arguments`.
Examples:
| Keyword 1 | arg |
| KW 1 | arg | arg 2 |
| KW 2 | arg | arg 2 |
-------
http://robotframework.org
''' % name
| Python |
u"""Module test library.
With some non-ascii stuff:
Hyv\u00E4\u00E4 y\u00F6t\u00E4.
\u0421\u043F\u0430\u0441\u0438\u0431\u043E!
"""
ROBOT_LIBRARY_VERSION = '0.1-alpha'
def keyword():
"""A keyword
See `get hello` for details"""
pass
def get_hello():
"""Get the intialization variables
See `importing` for explanation of arguments
and `introduction` for introduction"""
return 'foo'
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Debugfile Viewer
Usage: fileviever.py [path]
This tool is mainly targeted for viewing Robot Framework debug files set
with '--debugfile' command line option when running test. The idea is to
provide a tool that has similar functionality as 'tail -f' command in
unixy systems.
The tool has a simple GUI which is updated every time the file opened into
it is updated. File can be given from command line or opened using 'Open'
button in the GUI.
"""
import os
import sys
import time
from FileDialog import LoadFileDialog
import Tkinter as Tk
class FileViewer:
def __init__(self, path=None):
self._path = path is not None and os.path.abspath(path) or None
self._file = self._open_file(path)
self._root = self._create_root()
self._create_components(self._root)
self._last_update_cmd = None
self._update()
def mainloop(self):
self._root.mainloop()
def _create_root(self):
root = Tk.Tk()
root.title('Debug file viewer, v0.1')
root.geometry('750x500+100+100')
return root
def _create_components(self, root):
self._create_toolbar(root)
self._create_statusbar(root)
self._text_area = self._create_scrollable_text_area(root)
def _create_statusbar(self, root):
statusbar = Tk.Frame(root)
self._statusbar_left = Tk.Label(statusbar)
self._statusbar_left.pack(side=Tk.LEFT)
self._statusbar_right = Tk.Label(statusbar)
self._statusbar_right.pack(side=Tk.RIGHT)
statusbar.pack(side=Tk.BOTTOM, fill=Tk.X)
def _create_toolbar(self, root):
toolbar = Tk.Frame(root, width=65)
self._create_button(toolbar, 'Open', self._open_file_dialog)
self._create_button(toolbar, 'Clear', self._clear_text)
self._create_button(toolbar, 'Exit', self._root.destroy)
self._pause_cont_button = self._create_button(toolbar, 'Pause',
self._pause_or_cont, 25)
toolbar.pack_propagate(0)
toolbar.pack(side=Tk.RIGHT, fill=Tk.Y)
def _create_button(self, parent, label, command, pady=2):
button = Tk.Button(parent, text=label, command=command)
button.pack(side=Tk.TOP, padx=2, pady=pady, fill=Tk.X)
return button
def _create_scrollable_text_area(self, root):
scrollbar = Tk.Scrollbar(root)
text = Tk.Text(root, yscrollcommand=scrollbar.set, font=("Courier", 9))
scrollbar.config(command=text.yview)
scrollbar.pack(side=Tk.RIGHT, fill=Tk.Y)
text.pack(fill=Tk.BOTH, expand=1)
return text
def _pause_or_cont(self):
if self._pause_cont_button['text'] == 'Pause':
if self._last_update_cmd is not None:
self._root.after_cancel(self._last_update_cmd)
self._pause_cont_button.configure(text='Continue')
else:
self._pause_cont_button.configure(text='Pause')
self._root.after(50, self._update)
def _update(self):
if self._file is None:
self._file = self._open_file(self._path)
if self._file is not None:
try:
if os.stat(self._path).st_size < self._last_file_size:
self._file.seek(0)
self._clear_text()
self._text_area.insert(Tk.END, self._file.read())
self._last_file_size = self._file.tell()
except (OSError, IOError):
self._file = None
self._clear_text()
self._text_area.yview('moveto', '1.0')
self._set_status_bar_text()
self._last_update_cmd = self._root.after(50, self._update)
def _clear_text(self):
self._text_area.delete(1.0, Tk.END)
def _set_status_bar_text(self):
left, right = self._path, ''
if self._path is None:
left = 'No file opened'
elif self._file is None:
right = 'File does not exist'
else:
timetuple = time.localtime(os.stat(self._path).st_mtime)
timestamp = '%d%02d%02d %02d:%02d:%02d' % timetuple[:6]
right = 'File last modified: %s' % timestamp
self._statusbar_left.configure(text=left)
self._statusbar_right.configure(text=right)
def _open_file(self, path):
if path is not None and os.path.exists(path):
self._last_file_size = os.stat(path).st_size
return open(path)
return None
def _open_file_dialog(self):
dialog = LoadFileDialog(self._root, title='Choose file to view')
fname = dialog.go()
if fname is None:
return
self._path = os.path.abspath(fname)
if self._last_update_cmd is not None:
self._root.after_cancel(self._last_update_cmd)
if self._file is not None:
self._file.close()
self._file = self._open_file(self._path)
self._clear_text()
if self._pause_cont_button['text'] == 'Continue':
self._pause_or_cont()
else:
self._update()
if __name__ == '__main__':
if len(sys.argv) > 2 or '--help' in sys.argv:
print __doc__
sys.exit(1)
app = FileViewer(*sys.argv[1:])
app.mainloop()
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Diff Tool for Robot Framework Outputs
Usage: robotdiff.py [options] input_files
This script compares two or more Robot Framework output files and creates a
report where possible differences between test case statuses in each file
are highlighted. Main use case is verifying that results from executing same
test cases in different environments are same. For example, it is possible to
test that new Robot Framework version does not affect test results. Another
usage is comparing earlier test results with newer ones to find out possible
status changes and added test cases.
Options:
-r --report file HTML report file (created from the input files).
Default is 'robotdiff.html'.
-n --name name * Name for test run. Different test runs can be named
with this option. However, there must be as many
names as there are input files. By default the name
of the input files are used as names. Input files
having same file name are distinguished by adding
as many parent directories to the names as is needed.
-t --title title Title for the generated diff report. The default
title is 'Diff Report'.
-E --escape what:with * Escape certain characters which are problematic in
console. 'what' is the name of the character to
escape and 'with' is the string to escape it with.
Available character to escape:
<--------------------ESCAPES------------------------>
Example:
--escape space:_ --title My_Fine_Diff_Report
-h -? --help Print this usage instruction.
Options that can be specified multiple times are marked with an asterisk (*).
Examples:
$ robotdiff.py output1.xml output2.xml output3.xml
$ robotdiff.py --name Env1 --name Env2 smoke1.xml smoke2.xml
"""
import os
import sys
from robot import utils
from robot.output import TestSuite
from robot.errors import DataError, Information
def main(args):
opts, paths = _process_args(args)
diff = DiffRobotOutputs(opts['report'], opts['title'])
names = _get_names(opts['name'], paths)
for path, name in zip(paths, names):
try:
diff.add_suite(path, name)
except DataError, err:
exit(error=str(err))
diff.serialize()
print "Report: %s" % diff.close()
def _process_args(cliargs):
ap = utils.ArgumentParser(__doc__, arg_limits=(2, sys.maxint))
try:
opts, paths = ap.parse_args(cliargs, unescape='escape', help='help',
check_args=True)
except Information, msg:
exit(msg=str(msg))
except DataError, err:
exit(error=str(err))
return opts, [ utils.normpath(path) for path in paths ]
def _get_names(names, paths):
if len(names) == 0:
return [None] * len(paths)
if len(names) == len(paths):
return names
exit(error="Different number of names (%d) and inputs (%d)"
% (len(names), len(paths)))
def exit(rc=0, error=None, msg=None):
if error:
print error, "\n\nUse '--help' option to get usage information."
if rc == 0:
rc = 255
if msg:
print msg
rc = 1
sys.exit(rc)
class DiffRobotOutputs:
def __init__(self, outpath=None, title=None):
if outpath is None:
outpath = 'robotdiff.html'
if title is None:
title = 'Diff Report'
self._output = open(utils.normpath(outpath), 'w')
self._writer = utils.HtmlWriter(self._output)
self.title = title
self.column_names = []
self.suites_and_tests = {}
def add_suite(self, path, column_name):
if column_name is None:
column_name = path
column_name = self._get_new_column_name(column_name)
self.column_names.append(column_name)
suite = TestSuite(path)
# Creates links to logs
link = self._get_loglink(path, self._output.name)
self._set_suite_links(suite, link)
self._add_suite(suite, column_name)
def _get_loglink(self, inpath, target):
"""Finds matching log file and return link to it or None."""
indir, infile = os.path.split(inpath)
logname = os.path.splitext(infile.lower())[0]
if logname.endswith('output'):
logname = logname[:-6] + 'log'
for item in os.listdir(indir):
name, ext = os.path.splitext(item.lower())
if name == logname and ext in ['.html','.htm','.xhtml']:
logpath = os.path.join(indir, item)
return utils.get_link_path(logpath, target)
return None
def _set_suite_links(self, suite, link):
suite.link = link
for sub_suite in suite.suites:
self._set_suite_links(sub_suite, link)
for test in suite.tests:
test.link = link
def _get_new_column_name(self, column_name):
if self.column_names.count(column_name) == 0:
return column_name
count = 0
for name in self.column_names:
if name.startswith(column_name):
count += 1
return column_name + '_%d' % (count)
def _add_suite(self, suite, column_name):
self._add_to_dict(suite, column_name)
for sub_suite in suite.suites:
self._add_suite(sub_suite, column_name)
for test in suite.tests:
self._add_to_dict(test, column_name)
def _add_to_dict(self, s_or_t, column_name):
name = s_or_t.longname.replace('_', ' ')
keys = self.suites_and_tests.keys()
found = False
for key in keys:
if utils.normalize(name, caseless=True, spaceless=True) == \
utils.normalize(key, caseless=True, spaceless=True):
found = True
foundkey = key
if not found:
self.suites_and_tests[name] = [(column_name, s_or_t)]
else:
self.suites_and_tests[foundkey].append((column_name, s_or_t))
def serialize(self):
self._write_start()
self._write_headers()
for name, value in self._get_sorted_items(self.suites_and_tests):
self._write_start_of_s_or_t_row(name, value)
for column_name in self.column_names:
#Generates column containg status
s_or_t = self._get_s_or_t_by_column_name(column_name, value)
self._write_s_or_t_status(s_or_t)
self._writer.end('tr', newline=True)
self._writer.end('table', newline=True)
self._write_end()
def close(self):
self._output.close()
return self._output.name
def _write_s_or_t_status(self, s_or_t):
if s_or_t is not None:
self._col_status_content(s_or_t)
else:
col_status = 'col_status not_available'
self._writer.element('td', 'N/A', {'class': col_status})
def _col_status_content(self, s_or_t):
status = s_or_t.status
col_status = 'col_status %s' % status.lower()
self._writer.start('td', {'class': col_status})
if s_or_t.link is not None:
type = self._get_type(s_or_t)
link = '%s#%s_%s' % (s_or_t.link, type, s_or_t.longname)
self._writer.element('a', status, {'class': status.lower(),
'href': link,
'title': s_or_t.longname })
else:
self._writer.content(status)
self._writer.end('td')
def _get_type(self, s_or_t):
if dir(s_or_t).count('tests') == 1:
return 'suite'
else:
return 'test'
def _write_start_of_s_or_t_row(self, name, value):
row_status = self._get_row_status(value)
self._writer.element('th', name, {'class': row_status})
def _get_sorted_items(self, suites_and_tests):
items = suites_and_tests.items()
items.sort(lambda x, y: cmp(x[0], y[0]))
return items
def _get_row_status(self, items):
if len(items) > 0:
status = self._get_status(items[0])
else:
return 'none'
for item in items:
if self._get_status(item) != status:
return 'diff'
return 'all_%s' % (status.lower())
def _get_status(self, item):
return item[1].status
def _get_s_or_t_by_column_name(self, column_name, items):
for item in items:
if column_name == item[0]:
return item[1]
return None
def _write_headers(self):
self._writer.start('table')
self._writer.start('tr')
self._writer.element('th', 'Name', {'class': 'col_name'})
for name in self.column_names:
name = name.replace(self._get_prefix(self.column_names), '')
self._writer.element('th', name, {'class': 'col_status'})
self._writer.end('tr')
def _get_prefix(self, paths):
paths = [os.path.dirname(p) for p in paths ]
dirs = []
for path in paths:
if path.endswith(os.sep):
dirs.append(path)
else:
if path != '' and path[-1] != os.sep:
dirs.append(path + os.sep)
else:
dirs.append(path)
prefix = os.path.commonprefix(dirs)
while len(prefix) > 0:
if prefix.endswith(os.sep):
break
prefix = prefix[:-1]
return prefix
def _write_start(self):
self._output.write(START_HTML)
self._output.write("<title>%s</title>" % (self.title))
self._output.write("</head>\n<body><h1>%s</h1></br>\n" % (self.title))
self._output.write('<div class="spacer"> </div>')
def _write_end(self):
self._writer.end('body')
self._writer.end('html')
START_HTML = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Expires" content="Mon, 20 Jan 2001 20:01:21 GMT" />
<style media="all" type="text/css">
/* Generic Table Styles */
table {
background: white;
border: 1px solid black;
border-collapse: collapse;
empty-cells: show;
margin: 0px 1px;
}
th, td {
border: 1px solid black;
padding: 1px 5px;
}
th {
background: #C6C6C6;
color: black;
}
.diff{
background: red;
}
.all_pass{
background: #00f000;
}
.all_fail{
background: yellow;
}
/* Test by Suite/Tag Tables */
table.tests_by_suite, table.tests_by_tag {
width: 100%;
}
.col_name {
width: 13em;
font-weight: bold;
}
.col_status {
width: 5em;
text-align: center;
}
.pass{
color: #00f000;
}
.fail{
color: red;
}
</style>
<style media="all" type="text/css">
/* Generic styles */
body {
font-family: sans-serif;
font-size: 0.8em;
color: black;
padding: 6px;
}
h2 {
margin-top: 1.2em;
}
/* Misc Styles */
.not_available {
color: gray; /* no grey in IE */
font-weight: normal;
}
a:link, a:visited {
text-decoration: none;
}
a:hover {
text-decoration: underline;
color: purple;
}
/* Headers */
.header {
width: 58em;
margin: 6px 0px;
}
h1 {
margin: 0px;
width: 73%;
float: left;
}
.times {
width: 26%;
float: right;
text-align: right;
}
.generated_time, .generated_ago {
font-size: 0.9em;
}
.spacer {
font-size: 0.8em;
clear: both;
}
</style>
<style media="print" type="text/css">
body {
background: white;
padding: 0px;
font-size: 9pt;
}
a:link, a:visited {
color: black;
}
.header, .failbox, .passbox, table.statistics {
width: 100%;
}
.generated_ago {
display: none;
}
</style>
'''
if __name__ == '__main__':
main(sys.argv[1:])
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Test Data Documentation Tool
Usage: testdoc.py [options] data_sources
This tool generates a high level test documentation from a given test data.
Generated documentation includes the names, documentations and other metadata
of each test suite and test case, as well as the top-level keywords and their
arguments. Most of the options accepted by this tool have exactly same
semantics as same options have when executing test cases.
Options:
-o --output path Where to write the generated documentation. If the
path is a directory, the documentation is
generated there using name '<suitename>-doc.html'.
-T --title title Set the title of the generated documentation.
Underscores in the title are converted to spaces.
-N --name name Set the name of the top level test suite.
-D --doc document Set the document of the top level test suite.
-M --metadata name:value * Set metadata of the top level test suite.
-G --settag tag * Set given tag(s) to all test cases.
-t --test name * Include test cases by name.
-s --suite name * Include test suites by name.
-i --include tag * Include test cases by tags.
-e --exclude tag * Exclude test cases by tags.
-h --help Print this help.
Examples:
$ testdoc.py mytestcases.html
$ testdoc.py --name smoke_test_plan --include smoke path/to/my_tests/
"""
import sys
import os
import time
from robot import utils, version
from robot.common import BaseKeyword, BaseTestSuite
from robot.running import TestSuite, Keyword
from robot.conf import RobotSettings
from robot.result.logserializers import LogSerializer
from robot.result import templates
from robot.result.templating import Namespace, Template
from robot.errors import DataError, Information
from robot.parsing import populators
from robot.variables import Variables
populators.PROCESS_CURDIR = False
Variables.set_from_variable_table = lambda self, varz: None
def generate_test_doc(args):
opts, datasources = process_arguments(args)
suite = TestSuite(datasources, RobotSettings(opts))
outpath = get_outpath(opts['output'], suite.name)
serialize_test_doc(suite, outpath, opts['title'])
exit(msg=outpath)
def serialize_test_doc(suite, outpath, title):
outfile = open(outpath, 'w')
serializer = TestdocSerializer(outfile, suite)
ttuple = time.localtime()
str_time = utils.format_time(ttuple, daytimesep=' ', gmtsep=' ')
int_time = long(time.mktime(ttuple))
if title:
title = title.replace('_', ' ')
else:
title = 'Documentation for %s' % suite.name
namespace = Namespace(gentime_str=str_time, gentime_int=int_time,
version=version.get_full_version('testdoc.py'),
suite=suite, title=title)
Template(template=templates.LOG).generate(namespace, outfile)
suite.serialize(serializer)
outfile.write('</body>\n</html>\n')
outfile.close()
def process_arguments(args_list):
argparser = utils.ArgumentParser(__doc__)
try:
opts, args = argparser.parse_args(args_list, help='help', check_args=True)
except Information, msg:
exit(msg=str(msg))
except DataError, err:
exit(error=str(err))
return opts, args
def exit(msg=None, error=None):
if msg:
sys.stdout.write(msg + '\n')
sys.exit(0)
sys.stderr.write(error + '\n\nTry --help for usage information.\n')
sys.exit(1)
def get_outpath(path, suite_name):
if not path:
path = '.'
if os.path.isdir(path):
path = os.path.join(path, '%s-doc.html' % suite_name.replace(' ', '_'))
return os.path.abspath(path)
class TestdocSerializer(LogSerializer):
def __init__(self, output, suite):
self._writer = utils.HtmlWriter(output)
self._idgen = utils.IdGenerator()
self._split_level = -1
self._suite_level = 0
def start_suite(self, suite):
suite._set_variable_dependent_metadata(NonResolvingContext())
LogSerializer.start_suite(self, suite)
def start_test(self, test):
test._init_test(NonResolvingContext())
LogSerializer.start_test(self, test)
def start_keyword(self, kw):
if isinstance(kw, Keyword): # Doesn't match For
kw.name = kw._get_name(kw.name)
LogSerializer.start_keyword(self, kw)
def _is_element_open(self, item):
return isinstance(item, BaseTestSuite)
def _write_times(self, item):
pass
def _write_suite_metadata(self, suite):
self._start_suite_or_test_metadata(suite)
for name, value in suite.get_metadata(html=True):
self._write_metadata_row(name, value, escape=False, write_empty=True)
self._write_source(suite.source)
self._write_metadata_row('Number of Tests', suite.get_test_count())
self._writer.end('table')
def _start_suite_or_test_metadata(self, suite_or_test):
suite_or_test.doc = utils.unescape(suite_or_test.doc)
LogSerializer._start_suite_or_test_metadata(self, suite_or_test)
def _write_test_metadata(self, test):
self._start_suite_or_test_metadata(test)
if test.timeout.secs < 0:
tout = ''
else:
tout = utils.secs_to_timestr(test.timeout.secs)
if test.timeout.message:
tout += ' | ' + test.timeout.message
self._write_metadata_row('Timeout', tout)
self._write_metadata_row('Tags', ', '.join(test.tags))
self._writer.end('table')
def _write_folding_button(self, item):
if not isinstance(item, BaseKeyword):
LogSerializer._write_folding_button(self, item)
def _write_expand_all(self, item):
if isinstance(item, BaseTestSuite):
LogSerializer._write_expand_all(self, item)
class NonResolvingContext:
def replace_vars_from_setting(self, name, item, errors):
return item
def replace_string(self, item):
return item
def get_current_vars(self):
return NonResolvingContext()
if __name__ == '__main__':
generate_test_doc(sys.argv[1:])
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""risto.py -- Robot Framework's Historical Reporting Tool
Version: <VERSION>
Usage: risto.py options input_files
or: risto.py options1 --- options2 --- optionsN --- input files
or: risto.py --argumentfile path
risto.py plots graphs about test execution history based on statistics
read from Robot Framework output files. Actual drawing is handled by
Matplotlib tool, which must be installed separately. More information
about it, including installation instructions, can be found from
http://matplotlib.sourceforge.net.
By default risto.py draws total, passed and failed graphs for critical
tests and all tests, but it is possible to omit some of these graphs
and also to add graphs by tags. Names of test rounds that are shown on
the x-axis are, by default, got from the paths to input files.
Alternatively, names can be got from the metadata of the top level
test suite (see Robot Framework's '--metadata' option for more details).
Graphs are saved to a file specified with '--output' option, and the output
format is got from the file extension. Supported formats depend on
installed Matplotlib back-ends, but at least PNG ought to be always
available. If output file is omitted, the graph is opened into Matplotlib's
image viewer (which requires Matplotlib to be installed with some graphical
front-end).
It is possible to draw multiple graphs with different options at once. This
is done by separating different option groups with three or more hyphens
('---'). Note that in this case also paths to input files need to be
separated from last options similarly.
Instead of giving all options from command line, it is possible to read
them from a file specified with '--argument' option. In an argument file
options and their possible argument are listed one per line, and option
groups are separated with lines of three or more hyphens. Empty lines and
lines starting with a hash mark ('#') are ignored.
Options:
-C --nocritical Do not plot graphs for critical tests.
-A --noall Do not plot graphs for all tests.
-T --nototals Do not plot total graphs.
-P --nopassed Do not plot passed graphs.
-F --nofailed Do not plot failed graphs.
-t --tag name * Add graphs for these tags. Name can contain '*' and
'?' as wildcards. 'AND' in the tag name is converted
to ' & ', to make it easier to plot combined tags.
-o --output path Path to the image file to create. If not given, the
image is opened into Matplotlib's image viewer.
-i --title title Title of the graph. Underscores in the given title
are converted to spaces. By default there is no
title.
-w --width inches Width of the image. Default is 800.
-h --height inches Height of the image. Default is 400.
-f --font size Font size used for legends and labels. Default is 8.
-m --marker size Size of marked used with tag graphs. Default is 5.
-x --xticks num Maximum number of ticks in x-axis. Default is 15.
-n --namemeta name Name of the metadata of the top level test suite
where to get name of the test round. By default names
are got from paths to input files.
--- Used to group options when creating multiple images
at once.
--argumentfile path Read arguments from the specified file.
--verbose Verbose output.
--help Print this help.
--version Print version information.
Examples:
risto.py --output history.png output1.xml output2.xml output3.xml
risto.py --title My_Report --noall --namemeta Date --output out.png *.xml
risto.py --nopassed --tag smoke --tag iter-* results/*/output.xml
risto.py -CAP -t tag1 --- -CAP -t tag2 --- -CAP -t tag3 --- outputs/*.xml
risto.py --argumentfile arguments.txt
====[arguments.txt]===================
--title Overview
--output overview.png
----------------------
--nocritical
--noall
--nopassed
--tag smoke1
--title Smoke Tests
--output smoke.png
----------------------
path/to/*.xml
======================================
"""
__version__ = '1.0'
import os.path
import sys
import glob
try:
import xml.etree.cElementTree as ET
except ImportError:
try:
import cElementTree as ET
except ImportError:
try:
import elementtree.ElementTree as ET
except ImportError:
raise ImportError('Could not import ElementTree module. '
'Upgrade to Python 2.5+ or install ElementTree '
'from http://effbot.org/zone/element-index.htm')
try:
from matplotlib import pylab
from matplotlib.lines import Line2D
from matplotlib.font_manager import FontProperties
from matplotlib.pyplot import get_current_fig_manager
except ImportError:
raise ImportError('Could not import Matplotlib modules. Install it form '
'http://matplotlib.sourceforge.net/')
try:
from robot import utils
from robot.errors import DataError, Information
except ImportError:
raise ImportError('Could not import Robot Framework modules. '
'Make sure you have Robot Framework installed.')
class AllStatistics(object):
def __init__(self, paths, namemeta=None, verbose=False):
self._stats = self._get_stats(paths, namemeta, verbose)
self._tags = self._get_tags()
def _get_stats(self, paths, namemeta, verbose):
paths = self._glob_paths(paths)
if namemeta:
return [ Statistics(path, namemeta=namemeta, verbose=verbose)
for path in paths ]
return [ Statistics(path, name, verbose=verbose)
for path, name in zip(paths, self._get_names(paths)) ]
def _glob_paths(self, orig):
paths = []
for path in orig:
paths.extend(glob.glob(path))
if not paths:
raise DataError("No valid paths given.")
return paths
def _get_names(self, paths):
paths = [ os.path.splitext(os.path.abspath(p))[0] for p in paths ]
path_tokens = [ p.replace('\\','/').split('/') for p in paths ]
min_tokens = min([ len(t) for t in path_tokens ])
index = -1
while self._tokens_are_same_at_index(path_tokens, index):
index -= 1
if abs(index) > min_tokens:
index = -1
break
names = [ tokens[index] for tokens in path_tokens ]
return [ utils.printable_name(n, code_style=True) for n in names ]
def _tokens_are_same_at_index(self, token_list, index):
first = token_list[0][index]
for tokens in token_list[1:]:
if first != tokens[index]:
return False
return len(token_list) > 1
def _get_tags(self):
stats = {}
for statistics in self._stats:
stats.update(statistics.tags)
return [ stat.name for stat in sorted(stats.values()) ]
def plot(self, plotter):
plotter.set_axis(self._stats)
plotter.critical_tests([ s.critical_tests for s in self._stats ])
plotter.all_tests([ s.all_tests for s in self._stats ])
for tag in self._tags:
plotter.tag([ s[tag] for s in self._stats ])
class Statistics(object):
def __init__(self, path, name=None, namemeta=None, verbose=False):
if verbose:
print path
root = ET.ElementTree(file=path).getroot()
self.name = self._get_name(name, namemeta, root)
stats = root.find('statistics')
crit_node, all_node = list(stats.find('total'))
self.critical_tests = Stat(crit_node)
self.all_tests = Stat(all_node)
self.tags = dict([ (n.text, Stat(n)) for n in stats.find('tag') ])
def _get_name(self, name, namemeta, root):
if namemeta is None:
if name is None:
raise TypeError("Either 'name' or 'namemeta' must be given")
return name
metadata = root.find('suite').find('metadata')
if metadata:
for item in metadata:
if item.get('name','').lower() == namemeta.lower():
return item.text
raise DataError("No metadata matching '%s' found" % namemeta)
def __getitem__(self, name):
try:
return self.tags[name]
except KeyError:
return EmptyStat(name)
class Stat(object):
def __init__(self, node):
self.name = node.text
self.passed = int(node.get('pass'))
self.failed = int(node.get('fail'))
self.total = self.passed + self.failed
self.doc = node.get('doc', '')
info = node.get('info', '')
self.critical = info == 'critical'
self.non_critical = info == 'non-critical'
self.combined = info == 'combined'
def __cmp__(self, other):
if self.critical != other.critical:
return self.critical is True and -1 or 1
if self.non_critical != other.non_critical:
return self.non_critical is True and -1 or 1
if self.combined != other.combined:
return self.combined is True and -1 or 1
return cmp(self.name, other.name)
class EmptyStat(Stat):
def __init__(self, name):
self.name = name
self.passed = self.failed = self.total = 0
self.doc = ''
self.critical = self.non_critical = self.combined = False
class Legend(Line2D):
def __init__(self, **attrs):
styles = {'color': '0.5', 'linestyle': '-', 'linewidth': 1}
styles.update(attrs)
Line2D.__init__(self, [], [], **styles)
class Plotter(object):
_total_color = 'blue'
_pass_color = 'green'
_fail_color = 'red'
_background_color = '0.8'
_xtick_rotation = 20
_default_width = 800
_default_height = 400
_default_font = 8
_default_marker = 5
_default_xticks = 15
_dpi = 100
_marker_symbols = 'o s D ^ v < > d p | + x 1 2 3 4 . ,'.split()
def __init__(self, tags=None, critical=True, all=True, totals=True,
passed=True, failed=True, width=None, height=None, font=None,
marker=None, xticks=None):
self._xtick_limit, self._font_size, self._marker_size, width, height \
= self._get_sizes(xticks, font, marker, width, height)
self._figure = pylab.figure(figsize=(width, height))
self._axes = self._figure.add_axes([0.05, 0.15, 0.65, 0.70])
# axes2 is used only for getting ytick labels also on right side
self._axes2 = self._axes.twinx()
self._axes2.set_xticklabels([], visible=False)
self._tags = self._get_tags(tags)
self._critical = critical
self._all = all
self._totals = totals
self._passed = passed
self._failed = failed
self._legends = []
self._markers = iter(self._marker_symbols)
def _get_sizes(self, xticks, font, marker, width, height):
xticks = xticks or self._default_xticks
font = font or self._default_font
marker = marker or self._default_marker
width = width or self._default_width
height = height or self._default_height
try:
return (int(xticks), int(font), int(marker),
float(width)/self._dpi, float(height)/self._dpi)
except ValueError:
raise DataError('Width, height, font and xticks must be numbers.')
def _get_tags(self, tags):
if tags is None:
return []
return [ t.replace('AND',' & ') for t in tags ]
def set_axis(self, stats):
slen = len(stats)
self._indexes = range(slen)
self._xticks = self._get_xticks(slen, self._xtick_limit)
self._axes.set_xticks(self._xticks)
self._axes.set_xticklabels([ stats[i].name for i in self._xticks ],
rotation=self._xtick_rotation,
size=self._font_size)
self._scale = (slen-1, max([ s.all_tests.total for s in stats ]))
def _get_xticks(self, slen, limit):
if slen <= limit:
return range(slen)
interval, extra = divmod(slen-1, limit-1) # 1 interval less than ticks
if interval < 2:
interval = 2
limit, extra = divmod(slen-1, interval)
limit += 1
return [ self._get_index(i, interval, extra) for i in range(limit) ]
def _get_index(self, count, interval, extra):
if count < extra:
extra = count
return count * interval + extra
def critical_tests(self, stats):
if self._critical:
line = {'linestyle': '--', 'linewidth': 1}
self._plot(self._indexes, stats, **line)
self._legends.append(Legend(label='critical tests', **line))
def all_tests(self, stats):
if self._all:
line = {'linestyle': ':', 'linewidth': 1}
self._plot(self._indexes, stats, **line)
self._legends.append(Legend(label='all tests', **line))
def tag(self, stats):
if utils.matches_any(stats[0].name, self._tags):
line = {'linestyle': '-', 'linewidth': 0.3}
mark = {'marker': self._get_marker(),
'markersize': self._marker_size}
self._plot(self._indexes, stats, **line)
markers = [ stats[index] for index in self._xticks ]
self._plot(self._xticks, markers, linestyle='', **mark)
line.update(mark)
label = self._get_tag_label(stats)
self._legends.append(Legend(label=label, **line))
def _get_tag_label(self, stats):
label = stats[0].name
# need to go through all stats because first can be EmptyStat
for stat in stats:
if stat.critical:
return label + ' (critical)'
if stat.non_critical:
return label + ' (non-critical)'
return label
def _get_marker(self):
try:
return self._markers.next()
except StopIteration:
return ''
def _plot(self, xaxis, stats, **attrs):
total, passed, failed \
= zip(*[ (s.total, s.passed, s.failed) for s in stats ])
if self._totals:
self._axes.plot(xaxis, total, color=self._total_color, **attrs)
if self._passed:
self._axes.plot(xaxis, passed, color=self._pass_color, **attrs)
if self._failed:
self._axes.plot(xaxis, failed, color=self._fail_color, **attrs)
def draw(self, output=None, title=None):
self._set_scale(self._axes)
self._set_scale(self._axes2)
self._set_legends(self._legends[:])
if title:
title = title.replace('_', ' ')
self._axes.set_title(title, fontsize=self._font_size*1.8)
if output:
self._figure.savefig(output, facecolor=self._background_color,
dpi=self._dpi)
else:
if not hasattr(self._figure, 'show'):
raise DataError('Could not find a graphical front-end for '
'Matplotlib.')
self._figure.show()
if title:
figman = get_current_fig_manager()
figman.set_window_title(title)
def _set_scale(self, axes):
width, height = self._scale
axes.axis([-width*0.01, width*1.01, -height*0.04, height*1.04])
def _set_legends(self, legends):
legends.insert(0, Legend(label='Styles:', linestyle=''))
legends.append(Legend(label='', linestyle=''))
legends.append(Legend(label='Colors:', linestyle=''))
if self._totals:
legends.append(Legend(label='total', color=self._total_color))
if self._passed:
legends.append(Legend(label='passed', color=self._pass_color))
if self._failed:
legends.append(Legend(label='failed', color=self._fail_color))
labels = [ l.get_label() for l in legends ]
self._figure.legend(legends, labels, loc='center right',
numpoints=3, borderpad=0.1,
prop=FontProperties(size=self._font_size))
class Ristopy(object):
def __init__(self):
self._arg_parser = utils.ArgumentParser(__doc__, version=__version__)
def main(self, args):
args = self._process_possible_argument_file(args)
try:
opt_groups, paths = self._split_to_option_groups_and_paths(args)
except ValueError:
viewer_open = self._plot_one_graph(args)
else:
viewer_open = self._plot_multiple_graphs(opt_groups, paths)
if viewer_open:
try:
raw_input('Press enter to exit.\n')
except (EOFError, KeyboardInterrupt):
pass
pylab.close('all')
def _plot_one_graph(self, args):
opts, paths = self._arg_parser.parse_args(args, help='help', version='version')
stats = AllStatistics(paths, opts['namemeta'], opts['verbose'])
output = self._plot(stats, opts)
return output is None
def _plot_multiple_graphs(self, opt_groups, paths):
viewer_open = False
stats = AllStatistics(paths, opt_groups[0]['namemeta'],
opt_groups[0]['verbose'])
for opts in opt_groups:
output = self._plot(stats, opts)
viewer_open = output is None or viewer_open
return viewer_open
def _plot(self, stats, opts):
plotter = Plotter(opts['tag'], not opts['nocritical'],
not opts['noall'], not opts['nototals'],
not opts['nopassed'], not opts['nofailed'],
opts['width'], opts['height'], opts['font'],
opts['marker'], opts['xticks'])
stats.plot(plotter)
plotter.draw(opts['output'], opts['title'])
if opts['output']:
print os.path.abspath(opts['output'])
return opts['output']
def _process_possible_argument_file(self, args):
try:
index = args.index('--argumentfile')
except ValueError:
return args
path = args[index+1]
try:
lines = open(path).readlines()
except IOError:
raise DataError("Invalid argument file '%s'" % path)
fargs = []
for line in lines:
line = line.strip()
if line == '' or line.startswith('#'):
continue
elif line.startswith('-'):
fargs.extend(line.split(' ',1))
else:
fargs.append(line)
args[index:index+2] = fargs
return args
def _split_to_option_groups_and_paths(self, args):
opt_groups = []
current = []
for arg in args:
if arg.replace('-','') == '' and len(arg) >= 3:
opts = self._arg_parser.parse_args(current)[0]
opt_groups.append(opts)
current = []
else:
current.append(arg)
if opt_groups:
return opt_groups, current
raise ValueError("Nothing to split")
if __name__ == '__main__':
try:
Ristopy().main(sys.argv[1:])
except Information, msg:
print str(msg)
except DataError, err:
print '%s\n\nTry --help for usage information.' % err
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Test Status Checker
Usage: statuschecker.py infile [outfile]
This tool processes Robot Framework output XML files and checks that test case
statuses and messages are as expected. Main use case is post-processing output
files got when testing Robot Framework test libraries using Robot Framework
itself.
If output file is not given, the input file is considered to be also output
file and it is edited in place.
By default all test cases are expected to 'PASS' and have no message. Changing
the expected status to 'FAIL' is done by having word 'FAIL' (in uppercase)
somewhere in the test case documentation. Expected error message must then be
given after 'FAIL'. Error message can also be specified as a regular
expression by prefixing it with string 'REGEXP:'.
This tool also allows testing the created log messages. They are specified
using a syntax 'LOG x.y:z LEVEL Actual message', which is described in the
tool documentation.
"""
import re
from robot.output import TestSuite
def process_output(inpath, outpath=None):
suite = TestSuite(inpath)
_process_suite(suite)
suite.write_to_file(outpath)
return suite.critical_stats.failed
def _process_suite(suite):
for subsuite in suite.suites:
_process_suite(subsuite)
for test in suite.tests:
_process_test(test)
def _process_test(test):
exp = _Expected(test.doc)
_check_status(test, exp)
if test.status == 'PASS':
_check_logs(test, exp)
def _check_status(test, exp):
if exp.status != test.status:
test.status = 'FAIL'
if exp.status == 'PASS':
test.message = ("Test was expected to PASS but it FAILED. "
"Error message:\n") + test.message
else:
test.message = ("Test was expected to FAIL but it PASSED. "
"Expected message:\n") + exp.message
elif not _message_matches(test.message, exp.message):
test.status = 'FAIL'
test.message = ("Wrong error message.\n\nExpected:\n%s\n\nActual:\n%s\n"
% (exp.message, test.message))
elif test.status == 'FAIL':
test.status = 'PASS'
test.message = 'Original test failed as expected.'
def _message_matches(actual, expected):
if actual == expected:
return True
if expected.startswith('REGEXP:'):
pattern = '^%s$' % expected.replace('REGEXP:', '', 1).strip()
if re.match(pattern, actual, re.DOTALL):
return True
return False
def _check_logs(test, exp):
for kw_indices, msg_index, level, message in exp.logs:
try:
kw = test.keywords[kw_indices[0]]
for index in kw_indices[1:]:
kw = kw.keywords[index]
except IndexError:
indices = '.'.join([ str(i+1) for i in kw_indices ])
test.status = 'FAIL'
test.message = ("Test '%s' does not have keyword with index '%s'"
% (test.name, indices))
return
if len(kw.messages) <= msg_index:
if message != 'NONE':
test.status = 'FAIL'
test.message = ("Keyword '%s' should have had at least %d "
"messages" % (kw.name, msg_index+1))
else:
if _check_log_level(level, test, kw, msg_index):
_check_log_message(message, test, kw, msg_index)
def _check_log_level(expected, test, kw, index):
actual = kw.messages[index].level
if actual == expected:
return True
test.status = 'FAIL'
test.message = ("Wrong level for message %d of keyword '%s'.\n\n"
"Expected: %s\nActual: %s.\n%s"
% (index+1, kw.name, expected, actual, kw.messages[index].message))
return False
def _check_log_message(expected, test, kw, index):
actual = kw.messages[index].message.strip()
if _message_matches(actual, expected):
return True
test.status = 'FAIL'
test.message = ("Wrong content for message %d of keyword '%s'.\n\n"
"Expected:\n%s\n\nActual:\n%s"
% (index+1, kw.name, expected, actual))
return False
class _Expected:
def __init__(self, doc):
self.status, self.message = self._get_status_and_message(doc)
self.logs = self._get_logs(doc)
def _get_status_and_message(self, doc):
if 'FAIL' in doc:
return 'FAIL', doc.split('FAIL', 1)[1].split('LOG', 1)[0].strip()
return 'PASS', ''
def _get_logs(self, doc):
logs = []
for item in doc.split('LOG')[1:]:
index_str, msg_str = item.strip().split(' ', 1)
kw_indices, msg_index = self._get_indices(index_str)
level, message = self._get_log_message(msg_str)
logs.append((kw_indices, msg_index, level, message))
return logs
def _get_indices(self, index_str):
try:
kw_indices, msg_index = index_str.split(':')
except ValueError:
kw_indices, msg_index = index_str, '1'
kw_indices = [ int(index) - 1 for index in kw_indices.split('.') ]
return kw_indices, int(msg_index) - 1
def _get_log_message(self, msg_str):
try:
level, message = msg_str.split(' ', 1)
if level not in ['TRACE', 'DEBUG', 'INFO', 'WARN', 'FAIL']:
raise ValueError
except ValueError:
level, message = 'INFO', msg_str
return level, message
if __name__=='__main__':
import sys
import os
if not 2 <= len(sys.argv) <= 3 or '--help' in sys.argv:
print __doc__
sys.exit(1)
infile = sys.argv[1]
outfile = len(sys.argv) == 3 and sys.argv[2] or None
print "Checking %s" % os.path.abspath(infile)
rc = process_output(infile, outfile)
if outfile:
print "Output %s" % os.path.abspath(outfile)
if rc > 255:
rc = 255
sys.exit(rc)
| Python |
#!/usr/bin/env python
import sys
import os
import tempfile
DATABASE_FILE = os.path.join(tempfile.gettempdir(), 'robotframework-quickstart-db.txt')
class DataBase(object):
def __init__(self, dbfile):
"""This class reads ands writes user data in a 'database'.
dbfile can be either or string or already opened file object. In the
former case, dbfile is considered to be path. If a file object is given
it must be opened in a mode that allows both reading and writing.
"""
self._dbfile, self._users = self._read_users(dbfile)
def _read_users(self, dbfile):
users = {}
if isinstance(dbfile, basestring):
if not os.path.isfile(dbfile):
return open(dbfile, 'w'), users
else:
dbfile = open(dbfile, 'r+')
for row in dbfile.read().splitlines():
user = User(*row.split('\t'))
users[user.username] = user
return dbfile, users
def create_user(self, username, password):
try:
user = User(username, password)
except ValueError, err:
return 'Creating user failed: %s' % err
self._users[user.username] = user
return 'SUCCESS'
def login(self, username, password):
if self._is_valid_user(username, password):
self._users[username].status = 'Active'
return 'Logged In'
return 'Access Denied'
def _is_valid_user(self, username, password):
return username in self._users and \
self._users[username].password == password
def change_password(self, username, old_pwd, new_pwd):
try:
if not self._is_valid_user(username, old_pwd):
raise ValueError('Access Denied')
self._users[username].password = new_pwd
except ValueError, err:
return 'Changing password failed: %s' % err
else:
return 'SUCCESS'
def close(self):
self._dbfile.seek(0)
self._dbfile.truncate()
for user in self._users.values():
user.serialize(self._dbfile)
self._dbfile.close()
class User(object):
def __init__(self, username, password, status='Inactive'):
self.username = username
self.password = password
self.status = status
def _get_password(self):
return self._password
def _set_password(self, password):
self._validate_password(password)
self._password = password
password = property(_get_password, _set_password)
def _validate_password(self, password):
if not (6 < len(password) < 13):
raise ValueError('Password must be 7-12 characters long')
has_lower = has_upper = has_number = has_invalid = False
for char in password:
if char.islower():
has_lower = True
elif char.isupper():
has_upper = True
elif char.isdigit():
has_number = True
else:
has_invalid = True
break
if has_invalid or not (has_lower and has_upper and has_number):
raise ValueError('Password must be a combination of lowercase '
'and uppercase letters and numbers')
def serialize(self, dbfile):
dbfile.write('%s\t%s\t%s\n' %
(self.username, self.password, self.status))
def login(username, password):
db = DataBase(DATABASE_FILE)
print db.login(username, password)
db.close()
def create_user(username, password):
db = DataBase(DATABASE_FILE)
print db.create_user(username, password)
db.close()
def change_password(username, old_pwd, new_pwd):
db = DataBase(DATABASE_FILE)
print db.change_password(username, old_pwd, new_pwd)
db.close()
def help():
print 'Usage: %s { create | login | change-password | help }' \
% os.path.basename(sys.argv[0])
if __name__ == '__main__':
actions = {'create': create_user, 'login': login,
'change-password': change_password, 'help': help}
try:
action = sys.argv[1]
except IndexError:
action = 'help'
args = sys.argv[2:]
try:
actions[action](*args)
except (KeyError, TypeError):
help()
| Python |
#!/usr/bin/env python
"""qs2html.py -- Creates HTML version of Robot Framework Quick Start Guide
Usage: qs2html.py [ cr(eate) | dist | zip ]
create .. Creates the HTML version of the Quick Start Guide.
dist .... Creates the Quick Start Guide and copies it and all its dependencies
under directory named 'robotframework-quickstart-<date>'.
zip ..... Uses 'dist' to create the Quick Start Guide distribution and then
packages it into 'robotframework-quickstart-<date>.zip'.
"""
import sys
import os
import shutil
import time
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'userguide'))
import ug2html # This also initializes docutils and pygments
def create_quickstart():
from docutils.core import publish_cmdline
print 'Creating Quick Start Guide ...'
qsdir = os.path.dirname(os.path.abspath(__file__))
description = 'Quick Start Guide for Robot Framework'
arguments = '''
--time
--stylesheet-path=../userguide/src/userguide.css
quickstart.rst
quickstart.html
'''.split('\n')[1:-1]
os.chdir(qsdir)
publish_cmdline(writer_name='html', description=description, argv=arguments)
qspath = arguments[-1]
print os.path.abspath(qspath)
return qspath
def create_distribution():
qspath = create_quickstart() # we are in doc/quickstart after this
outdir = 'robotframework-quickstart-%d%02d%02d' % time.localtime()[:3]
files = { '': [qspath], 'testlibs': ['LoginLibrary.py'],
'sut': ['login.py', 'test_login.py'] }
print 'Creating distribution directory ...'
if os.path.exists(outdir):
print 'Removing previous distribution'
shutil.rmtree(outdir)
os.mkdir(outdir)
for dirname, files in files.items():
dirpath = os.path.join(outdir, dirname)
if not os.path.exists(dirpath):
print "Creating output directory '%s'" % dirpath
os.mkdir(dirpath)
for name in files:
source = os.path.join(dirname, name)
print "Copying '%s' -> '%s'" % (source, dirpath)
shutil.copy(source, dirpath)
return outdir
def create_zip():
qsdir = create_distribution()
ug2html.zip_distribution(qsdir)
if __name__ == '__main__':
actions = { 'create': create_quickstart, 'cr': create_quickstart,
'dist': create_distribution, 'zip': create_zip }
try:
actions[sys.argv[1]](*sys.argv[2:])
except (KeyError, IndexError, TypeError):
print __doc__
| Python |
import os
import sys
import subprocess
class LoginLibrary:
def __init__(self):
self._sut_path = os.path.join(os.path.dirname(__file__),
'..', 'sut', 'login.py')
self._status = ''
def create_user(self, username, password):
self._run_command('create', username, password)
def change_password(self, username, old_pwd, new_pwd):
self._run_command('change-password', username, old_pwd, new_pwd)
def attempt_to_login_with_credentials(self, username, password):
self._run_command('login', username, password)
def status_should_be(self, expected_status):
if expected_status != self._status:
raise AssertionError("Expected status to be '%s' but was '%s'"
% (expected_status, self._status))
def _run_command(self, command, *args):
if not sys.executable:
raise RuntimeError("Could not find Jython installation")
command = [sys.executable, self._sut_path, command] + list(args)
process = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
self._status = process.communicate()[0].strip()
| Python |
def simple_keyword():
"""Log a message"""
print 'You have used the simplest keyword.'
def greet(name):
"""Logs a friendly greeting to person given as argument"""
print 'Hello %s!' % name
def multiply_by_two(number):
"""Returns the given number multiplied by two
The result is always a floating point number.
This keyword fails if the given `number` cannot be converted to number.
"""
return float(number) * 2
def numbers_should_be_equal(first, second):
print '*DEBUG* Got arguments %s and %s' % (first, second)
if float(first) != float(second):
raise AssertionError('Given numbers are unequal!')
| Python |
#!/usr/bin/env python
"""pt2html.py -- Creates HTML version of Python Tutorial
Usage: pt2html.py
"""
import sys
import os
import shutil
import time
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'userguide'))
import ug2html # This also initializes docutils and pygments
def create_tutorial():
from docutils.core import publish_cmdline
print 'Creating Python Tutorial ...'
os.chdir(os.path.dirname(os.path.abspath(__file__)))
description = 'Python Tutorial for Robot Framework Library Developers'
arguments = '''
--time
--stylesheet-path=../userguide/src/userguide.css
PythonTutorial.rst
PythonTutorial.html
'''.split('\n')[1:-1]
publish_cmdline(writer_name='html', description=description, argv=arguments)
path = arguments[-1]
print os.path.abspath(path)
return path
if __name__ == '__main__':
create_tutorial()
| Python |
#!/usr/bin/env python
"""Usage: lib2html.py [ library | all ]
Libraries:
BuiltIn (bu)
Collections (co)
Dialogs (di)
OperatingSystem (op)
Screenshot (sc)
String (st)
Telnet (te)
"""
import sys
import tempfile
import os
import re
ROOT = os.path.normpath(os.path.join(os.path.abspath(__file__),'..','..','..'))
LIBRARIES = {}
for line in __doc__.splitlines():
res = re.search('(\w+) \((\w\w)\)', line)
if res:
name, alias = res.groups()
LIBRARIES[name.lower()] = LIBRARIES[alias] = name
sys.path.insert(0, os.path.join(ROOT,'tools','libdoc'))
sys.path.insert(0, os.path.join(ROOT,'src'))
from libdoc import LibraryDoc, create_html_doc
def create_libdoc(name):
ipath = os.path.join(ROOT,'src','robot','libraries',name+'.py')
opath = os.path.join(ROOT,'doc','libraries',name+'.html')
create_html_doc(LibraryDoc(ipath), opath)
print opath
if __name__ == '__main__':
try:
name = sys.argv[1].lower()
if name == 'all':
for name in sorted(set(LIBRARIES.values())):
create_libdoc(name)
else:
create_libdoc(LIBRARIES[name])
except (IndexError, KeyError):
print __doc__
| Python |
#!/usr/bin/env python
"""ug2html.py -- Creates HTML version of Robot Framework User Guide
Usage: ug2html.py [ cr(eate) | dist | zip ]
create .. Creates the user guide so that it has relative links to images,
library docs, etc. This version is stored in the version control
and distributed with the source distribution.
dist .... Creates the user guide under 'robotframework-userguide-<version>'
directory and also copies all needed images and other link targets
there. The created output directory can thus be distributed
independently.
zip ..... Uses 'dist' to create a stand-alone distribution and then packages
it into 'robotframework-userguide-<version>.zip'
Version number to use is got automatically from 'src/robot/version.py' file
created by 'package.py'.
"""
import os
import sys
import shutil
# First part of this file is Pygments configuration and actual
# documentation generation follows it.
#
#
# Pygments configuration
# ----------------------
#
# This code is from 'external/rst-directive.py' file included in Pygments 0.9
# distribution. For more details see http://pygments.org/docs/rstdirective/
#
"""
The Pygments MoinMoin Parser
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This fragment is a Docutils_ 0.4 directive that renders source code
(to HTML only, currently) via Pygments.
To use it, adjust the options below and copy the code into a module
that you import on initialization. The code then automatically
registers a ``sourcecode`` directive that you can use instead of
normal code blocks like this::
.. sourcecode:: python
My code goes here.
If you want to have different code styles, e.g. one with line numbers
and one without, add formatters with their names in the VARIANTS dict
below. You can invoke them instead of the DEFAULT one by using a
directive option::
.. sourcecode:: python
:linenos:
My code goes here.
Look at the `directive documentation`_ to get all the gory details.
.. _Docutils: http://docutils.sf.net/
.. _directive documentation:
http://docutils.sourceforge.net/docs/howto/rst-directives.html
:copyright: 2007 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
# Options
# ~~~~~~~
# Set to True if you want inline CSS styles instead of classes
INLINESTYLES = False
from pygments.formatters import HtmlFormatter
# The default formatter
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)
# Add name -> formatter pairs for every variant you want to use
VARIANTS = {
# 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
}
from docutils import nodes
from docutils.parsers.rst import directives
from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer
def pygments_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
try:
lexer = get_lexer_by_name(arguments[0])
except ValueError:
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
# take an arbitrary option if more than one is given
formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
# possibility to read the content from an external file
filtered = [ line for line in content if line.strip() ]
if len(filtered) == 1:
path = filtered[0].replace('/', os.sep)
if os.path.isfile(path):
content = open(path).read().splitlines()
parsed = highlight(u'\n'.join(content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
pygments_directive.arguments = (1, 0, 1)
pygments_directive.content = 1
pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
directives.register_directive('sourcecode', pygments_directive)
#
# Create the user guide using docutils
#
# This code is based on rst2html.py distributed with docutils
#
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
def create_userguide():
from docutils.core import publish_cmdline
print 'Creating user guide ...'
ugdir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(ugdir, '..', '..', 'src', 'robot'))
from version import get_version
print 'Version:', get_version()
vfile = open(os.path.join(ugdir, 'src', 'version.txt'), 'w')
vfile.write('.. |version| replace:: %s\n' % get_version())
vfile.close()
description = 'HTML generator for Robot Framework User Guide.'
arguments = '''
--time
--stylesheet-path=src/userguide.css
src/RobotFrameworkUserGuide.txt
RobotFrameworkUserGuide.html
'''.split('\n')[1:-1]
os.chdir(ugdir)
publish_cmdline(writer_name='html', description=description, argv=arguments)
os.unlink(vfile.name)
ugpath = os.path.abspath(arguments[-1])
print ugpath
return ugpath, get_version(sep='-')
#
# Create user guide distribution directory
#
def create_distribution():
import re
from urlparse import urlparse
ugpath, version = create_userguide() # we are in doc/userguide after this
outdir = 'robotframework-userguide-%s' % version
tools = os.path.join(outdir, 'tools')
templates = os.path.join(outdir, 'templates')
libraries = os.path.join(outdir, 'libraries')
images = os.path.join(outdir, 'images')
print 'Creating distribution directory ...'
if os.path.exists(outdir):
print 'Removing previous user guide distribution'
shutil.rmtree(outdir)
for dirname in [outdir, tools, templates, libraries, images]:
print "Creating output directory '%s'" % dirname
os.mkdir(dirname)
def replace_links(res):
if not res.group(5):
return res.group(0)
scheme, _, path, _, _, fragment = urlparse(res.group(5))
if scheme or (fragment and not path):
return res.group(0)
replaced_link = '%s %s="%%s/%s"' % (res.group(1), res.group(4),
os.path.basename(path))
if path.startswith('../../tools'):
copy(path, tools)
copy_tool_images(path)
replaced_link = replaced_link % 'tools'
elif path.startswith('../../templates'):
copy(path, templates)
replaced_link = replaced_link % 'templates'
elif path.startswith('../libraries'):
copy(path, libraries)
replaced_link = replaced_link % 'libraries'
elif path.startswith('src/'):
copy(path, images)
replaced_link = replaced_link % 'images'
else:
raise ValueError('Invalid link target: %s' % path)
print "Modified link '%s' -> '%s'" % (res.group(0), replaced_link)
return replaced_link
def copy(source, dest):
print "Copying '%s' -> '%s'" % (source, dest)
shutil.copy(source, dest)
def copy_tool_images(path):
indir = os.path.dirname(path)
for line in open(os.path.splitext(path)[0]+'.txt').readlines():
if line.startswith('.. figure::'):
copy(os.path.join(indir, line.strip().split()[-1]), tools)
link_regexp = re.compile('''
(<(a|img)\s+.*?)
(\s+(href|src)="(.*?)"|>)
''', re.VERBOSE | re.DOTALL | re.IGNORECASE)
content = open(ugpath).read()
content = link_regexp.sub(replace_links, content)
outfile = open(os.path.join(outdir, os.path.basename(ugpath)), 'wb')
outfile.write(content)
outfile.close()
print os.path.abspath(outfile.name)
return outdir
#
# Create a zip distribution package
#
def create_zip():
ugdir = create_distribution()
zip_distribution(ugdir)
def zip_distribution(dirpath):
"""Generic zipper. Used also by qs2html.py """
from zipfile import ZipFile, ZIP_DEFLATED
print 'Creating zip package ...'
zippath = os.path.normpath(dirpath) + '.zip'
zipfile = ZipFile(zippath, 'w', compression=ZIP_DEFLATED)
for root, _, files in os.walk(dirpath):
for name in files:
path = os.path.join(root, name)
print "Adding '%s'" % path
zipfile.write(path)
zipfile.close()
print 'Removing distribution directory', dirpath
shutil.rmtree(dirpath)
print os.path.abspath(zippath)
if __name__ == '__main__':
actions = { 'create': create_userguide, 'cr': create_userguide,
'dist': create_distribution, 'zip': create_zip }
try:
actions[sys.argv[1]](*sys.argv[2:])
except (KeyError, IndexError, TypeError):
print __doc__
| Python |
#!/usr/bin/env python
"""Usage: check_test_times.py inpath [outpath]
Reads result of a test run from Robot output file and checks that no test
took longer than 3 minutest to execute. If outpath is not given, the
result is written over the original file.
"""
import sys
from robot.output import TestSuite
def check_tests(inpath, outpath=None):
if not outpath:
outpath = inpath
suite = TestSuite(inpath)
_check_execution_times(suite)
suite.write_to_file(outpath)
def _check_execution_times(suite):
for test in suite.tests:
if test.status == 'PASS' and test.elapsedtime > 1000 * 60 * 3:
test.status = 'FAIL'
test.message = 'Test execution time was too long: %s' % test.elapsedtime
for suite in suite.suites:
_check_execution_times(suite)
if __name__ == '__main__':
try:
check_tests(*sys.argv[1:])
except TypeError:
print __doc__
| Python |
class CheckMultipleItemsLibrary:
def items_should_not_contain(self, value, *items):
"""Checks that none of the given 'items' contains the given 'value'."""
items_containing_value = [ item for item in items if value in item ]
if items_containing_value:
message = "Items '%s' contains '%s'"
message = message % (', '.join(items_containing_value), value)
raise AssertionError(message)
| Python |
"""Robot Framework test library example that calls C code.
This example uses Python's standard `ctypes` module, which requires
that the C code is compiled into a shared library.
It is also possible to execute this file from the command line
to test the C code manually.
"""
from ctypes import CDLL, c_char_p
LIBRARY = CDLL('./liblogin.so') # On Windows we'd use '.dll'
def check_user(username, password):
"""Validates user name and password using imported shared C library."""
if not LIBRARY.validate_user(c_char_p(username), c_char_p(password)):
raise AssertionError('Wrong username/password combination')
if __name__ == '__main__':
import sys
try:
check_user(*sys.argv[1:])
except TypeError:
print 'Usage: %s username password' % sys.argv[0]
except AssertionError, err:
print err
else:
print 'Valid password'
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Install script for Robot Framework source distributions.
Usage: python install.py [ in(stall) | un(install) | re(install) ]
Using 'python install.py install' simply runs 'python setup.py install'
internally. You need to use 'setup.py' directly, if you want to alter the
default installation somehow.
See 'INSTALL.txt' or Robot Framework User Guide for more information.
"""
import glob
import os
import shutil
import sys
def install():
_remove(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'build'))
print 'Installing Robot Framework...'
setup = os.path.join(os.path.dirname(sys.argv[0]), 'setup.py')
rc = os.system('"%s" %s install' % (sys.executable, setup))
if rc != 0:
print 'Installation failed.'
sys.exit(rc)
print 'Installation was successful.'
def uninstall():
print 'Uninstalling Robot Framework...'
try:
instdir = _get_installation_directory()
except Exception:
print 'Robot Framework is not installed or the installation is corrupted.'
sys.exit(1)
_remove(instdir)
if not 'robotframework' in instdir:
_remove_egg_info(instdir)
_remove_runners()
print 'Uninstallation was successful.'
def reinstall():
uninstall()
install()
def _get_installation_directory():
import robot
# Ensure we got correct robot module
if 'Robot' not in robot.pythonpathsetter.__doc__:
raise TypeError
robot_dir = os.path.dirname(robot.__file__)
parent_dir = os.path.dirname(robot_dir)
if 'robotframework' in os.path.basename(parent_dir):
return parent_dir
return robot_dir
def _remove_runners():
runners = ['pybot', 'jybot', 'rebot']
if os.name == 'java':
runners.remove('pybot')
if os.sep == '\\':
runners = [r + '.bat' for r in runners]
for name in runners:
if os.name == 'java':
_remove(os.path.join(sys.prefix, 'bin', name))
elif os.sep == '\\':
_remove(os.path.join(sys.prefix, 'Scripts', name))
else:
for dirpath in ['/bin', '/usr/bin/', '/usr/local/bin']:
_remove(os.path.join(dirpath, name))
def _remove_egg_info(instdir):
pattern = os.path.join(os.path.dirname(instdir), 'robotframework-*.egg-info')
for path in glob.glob(pattern):
_remove(path)
def _remove(path):
if not os.path.exists(path):
return
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except Exception, err:
print "Removing '%s' failed: %s" % (path, err)
else:
print "Removed '%s'" % path
if __name__ == '__main__':
actions = { 'install': install, 'in': install,
'uninstall': uninstall, 'un': uninstall,
'reinstall': reinstall, 're': reinstall }
try:
actions[sys.argv[1]]()
except (KeyError, IndexError):
print __doc__
| Python |
from robot import run as run_robot
import cProfile
import pstats
filename = 'robot.profile'
cProfile.run('run_robot("/home/husa/workspace/robotframework/atest/testdata/misc/")', filename)
p = pstats.Stats(filename)
p.strip_dirs().sort_stats(-1).print_stats()
| Python |
from os.path import dirname, join
import subprocess
basedir = dirname(__file__)
cmd = ['pybot', '--outputdir', join(basedir, 'results'), join(basedir, 'vacalc')]
pythonpath = '%s:%s' % (join(basedir, 'lib'), join(basedir, '..', 'src'))
subprocess.call(' '.join(cmd), shell=True, env={'PYTHONPATH': pythonpath})
| Python |
import os
import sys
import subprocess
import datetime
import tempfile
import vacalc
class VacalcLibrary(object):
def __init__(self):
self._db_file = os.path.join(tempfile.gettempdir(),
'vacalc-atestdb.csv')
def count_vacation(self, startdate, year):
resource = vacalc.Employee('Test Resource', startdate)
return vacalc.Vacation(resource.startdate, int(year)).days
def clear_database(self):
if os.path.isfile(self._db_file):
print 'Removing %s' % self._db_file
os.remove(self._db_file)
def add_employee(self, name, startdate):
self._run('add_employee', name, startdate)
def get_employee(self, name):
self._run('get_employee', name)
def show_vacation(self, name, year):
self._run('show_vacation', name, year)
def _run(self, command, *args):
cmd = [sys.executable, vacalc.__file__, command] + list(args)
print subprocess.list2cmdline(cmd)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env={'VACALC_DB': self._db_file})
self._status = proc.stdout.read().strip()
print self._status
def status_should_be(self, status):
if self._status != status:
raise AssertionError("Expected status to be '%s' but it was '%s'"
% (status, self._status))
| Python |
from __future__ import with_statement
import os
import sys
import csv
import datetime
import tempfile
class VacalcError(Exception): pass
class EmployeeStore(object):
def __init__(self, db_file):
self._db_file = db_file
if self._db_file and os.path.isfile(self._db_file):
self._employees = self._read_employees(self._db_file)
else:
self._employees = {}
def _read_employees(self, path):
employees = {}
with open(path) as db:
for row in csv.reader(db):
employee = Employee(row[0], row[1])
employees[employee.name] = employee
return employees
def get_employee(self, name):
try:
return self._employees[name]
except KeyError:
raise VacalcError("Employee '%s' not found" % name)
def get_all_employees(self):
return self._employees.values()
def add_employee(self, employee):
if employee.name in self._employees:
raise VacalcError("Employee '%s' already exists in the system" %
employee.name)
self._employees[employee.name] = employee
self._serialize(employee)
def _serialize(self, employee):
if not self._db_file:
return
with open(self._db_file, 'a') as db:
writer = csv.writer(db, lineterminator='\n')
writer.writerow([employee.name, employee.startdate])
class Employee(object):
def __init__(self, name, startdate):
self.name = name
self.startdate = self._parse_date(startdate)
def _parse_date(self, datestring):
year, month, day = datestring.split('-')
return datetime.date(int(year), int(month), int(day))
class Vacation(object):
max_vacation = 12 * 2.5
no_vacation = 0
vacation_per_month = 2
credit_start_month = 4
work_days_required= 14
def __init__(self, empstartdate, vacation_year):
self.days = self._calculate_vacation(empstartdate, vacation_year)
def _calculate_vacation(self, start, year):
if self._has_worked_longer_than_year(start, year):
return self.max_vacation
if self._started_after_holiday_credit_year_ended(start, year):
return self.no_vacation
return self._count_working_months(start) * self.vacation_per_month
def _has_worked_longer_than_year(self, start, year):
return year-start.year > 1 or \
(year-start.year == 1 and start.month < self.credit_start_month)
def _started_after_holiday_credit_year_ended(self, start, year):
return start.year-year > 0 or \
(year == start.year and start.month >= self.credit_start_month)
def _count_working_months(self, start):
months = self.credit_start_month - start.month
if months <= 0:
months += 12
if self._first_month_has_too_few_working_days(start):
months -= 1
return months
def _first_month_has_too_few_working_days(self, start):
days = 0
date = start
while date:
if self._is_working_day(date):
days += 1
date = self._next_date(date)
return days < self.work_days_required
def _is_working_day(self, date):
return date.weekday() < 5
def _next_date(self, date):
try:
return date.replace(day=date.day+1)
except ValueError:
return None
class VacationCalculator(object):
def __init__(self, employeestore):
self._employeestore = employeestore
def show_vacation(self, name, year):
employee = self._employeestore.get_employee(name)
vacation = Vacation(employee.startdate, int(year))
return "%s has %d vacation days in year %s" \
% (name, vacation.days, year)
def add_employee(self, name, startdate):
employee = Employee(name, startdate)
self._employeestore.add_employee(employee)
return "Successfully added employee '%s'." % employee.name
def get_employee(self, name):
employee = self._employeestore.get_employee(name)
return '%s: start date %s' % (employee.name, employee.startdate)
def main(args):
db_file = os.environ.get('VACALC_DB', os.path.join(tempfile.gettempdir(),
'vacalcdb.csv'))
try:
cmd = getattr(VacationCalculator(EmployeeStore(db_file)), args[0])
return cmd(*args[1:])
except (AttributeError, TypeError):
raise VacalcError('invalid command or arguments')
if __name__ == '__main__':
try:
print main(sys.argv[1:])
sys.exit(0)
except VacalcError, err:
print err
sys.exit(1)
| Python |
VALUE_FROM_VAR_FILE='Expected Value'
| Python |
def this_keyword_is_in_funnylib():
print 'jee'
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import with_statement
import subprocess
import time
from random import randint
import os
import re
import sys
from robot.libraries import BuiltIn
from robot.utils import html_escape, ArgumentParser
from robot.version import get_version
class Parallel(object):
"""
Library for executing tests in parallel from inside of a robot test case.
Tests are executed in subprocesses.
You can add arguments to all parallel test runs from `library importing`,
for a set of parallel tests with `Add Arguments For Parallel Tests` and
for an individual parallel test by passing the arguments in `Start Parallel Test`.
The following command line arguments (also from argument files) are automatically
passed to parallel tests:
--loglevel, --runmode, --pythonpath, --variable, --variablefile
Example:
| *Settings* |
| Library | Parallel | pybot |
| *Test Cases* |
| Runner |
| | Run Parallel Tests | Hello | World |
| Hello |
| | [Tags] | parallel |
| | Log | Hello ${WORLD} |
| World |
| | [Tags] | parallel |
| | Log | ${HELLO} World |
`pybot --exclude parallel --variable HELLO:Hello --variable WORLD:World .`
"""
def __init__(self, runner_script, *arguments):
"""
`runner_script` is pybot or jybot or a custom script.
`arguments` are default arguments given to every test execution.
Example:
| Library | Parallel | pybot | --variable | variable:value | --loglevel | DEBUG |
"""
self._script = runner_script
self._arguments = self._get_arguments(arguments)
self._processes = []
self._data_source = None
def _get_arguments(self, additional_arguments):
options,_ = ArgumentParser(_get_cmd_arguments()).parse_args(sys.argv[1:], argfile='argumentfile', unescape='escape')
args = []
for arg in ['loglevel', 'runmode', 'pythonpath', 'variable', 'variablefile']:
args += self._get_type_arguments(options, arg)
args += list(additional_arguments)
return args
def _get_type_arguments(self, options, key):
value = options[key]
args = []
if value is not None:
if not isinstance(value, list):
value = [value]
for var in value:
args += ['--%s' % key, var]
return args
def add_arguments_for_parallel_tests(self, *arguments):
"""Adds `arguments` to be used when parallel test is started.
`arguments` is a list of arguments to pass to parallel executions.
In the following example variable my_var is used in both of the tests
started with the keyword `Run Parallel Tests`:
| Add Arguments For Parallel Tests | --variable | my_var:value |
| Run Parallel Tests | Test | Another Test |
"""
self._arguments += list(arguments)
def set_data_source_for_parallel_tests(self, data_source):
"""Sets data source which is used when parallel tests are started.
`data_source` is path to file which contains the test/tests which are
started/executed with keywords `Start Parallel Test` or `Run Parallel
Tests`.
If tests to be executed are in the same suite and Robot Framework 2.5
or later is used, there is no need to use this keyword as `data_source`
can be automatically resolved.
Examples:
| Set Data Source For Parallel Tests | ${CURDIR}${/}my_parallel_suite.txt |
| Start Parallel Test | My Parallel Test |
| Wait All Parallel Tests |
"""
self._data_source = data_source
def start_parallel_test(self, test_name, *arguments):
"""Starts executing test with given `test_name` and `arguments`.
`arguments` is a list of Robot Framework command line arguments passed to
the started test execution. It should not include data source. Use
`Set Data Source For Parallel Tests` keyword for setting the data
source. Additional arguments can also be set in library import and with
`Add Arguments For Parallel Tests` keyword.
Returns a process object that represents this execution.
Example:
| Set Data Source For Parallel Tests | MySuite.txt |
| Start Parallel Test | Test From My Suite |
| Set Data Source For Parallel Tests | MyFriendsSuite.txt |
| Start Parallel Test | Test From My Friends Suite |
| Wait All Parallel Tests |
"""
if self._data_source is None:
self._data_source = BuiltIn.BuiltIn().replace_variables('${SUITE_SOURCE}')
process = _ParaRobo(test_name, self._data_source,
self._arguments+list(arguments))
process.run(self._script)
self._processes.append(process)
return process
def run_parallel_tests(self, *test_names):
"""Executes all given tests parallel and wait those to be ready.
Arguments can be set with keyword `Add Arguments For Parallel Tests`
and data source with keyword `Set Data Source For Parallel Tests`.
Example:
| Add Arguments For Parallel Tests | --variable | SOME_VARIABLE:someValue |
| Set Data Source For Parallel Tests | MySuite.txt |
| Run Parallel Tests | My Parallel Test | My Another Parallel Test |
When the parallel tests are from different data sources see the example in `Start Parallel Test`.
"""
processes = []
for name in test_names:
processes += [self.start_parallel_test(name)]
self.wait_parallel_tests(*processes)
def wait_parallel_tests(self, *processes):
"""Waits given `processes` to be ready and fails if any of the tests failed.
`Processes` are list of test execution processes returned from keyword
`Start Parallel Test`.
Example
| ${test 1}= | Start Parallel Test | First Test |
| ${test 2}= | Start Parallel Test | Test That Runs All The Time |
| Wait Parallel Tests | ${test 1} |
| ${test 3}= | Start Parallel Test | Third Test |
| Wait Parallel Tests | ${test 2} | ${test 3} |
"""
failed = []
for process in processes:
if process.wait() != 0:
failed += [process.test]
process.report()
self._processes.remove(process)
if failed:
raise AssertionError("Following tests failed:\n%s" % "\n".join(failed))
def wait_all_parallel_tests(self):
"""Wait all started test executions to be ready and fails if any of those failed."""
self.wait_parallel_tests(*self._processes)
def stop_all_parallel_tests(self):
"""Forcefully stops all the test executions.
NOTE: Requires Python 2.6 or later.
"""
for process in self._processes:
process.stop_test_execution()
self._processes = []
class _ParaRobo(object):
def __init__(self, test, data_source, arguments):
self.test = test
self._data_source = data_source
self._args = arguments
self._built_in = BuiltIn.BuiltIn()
id = self._create_id()
self._output = 'output_%s.xml' % id
self._log = 'log_%s.html' % id
self._output_dir = self._built_in.replace_variables("${OUTPUT DIR}")
self._monitor_out = os.path.join(self._output_dir, 'monitor_%s.txt' % id)
@property
def _suite_name(self):
name = os.path.splitext(os.path.basename(self._data_source))[0]
name = name.split('__', 1)[-1] # Strip possible prefix
name = name.replace('_', ' ').strip()
if name.islower():
name = name.title()
return name
def _create_id(self):
return "%s_%s" % (randint(0, 10000), time.strftime('%Y%m%d_%H%m%S.')+\
('%03d' % (int(time.time()*1000) % 1000)))
def run(self, script):
self._monitor_file = open(self._monitor_out, 'w')
cmd = [script,
'--outputdir', self._output_dir,
'--output', self._output,
'--report', 'None',
'--log', self._log,
'--monitorcolors', 'off',
'--test', self.test]+\
self._args + [self._data_source]
print "Starting test execution: %s" % " ".join(cmd)
self._process = subprocess.Popen(cmd,
shell=os.sep == '\\',
stdout=self._monitor_file,
stderr=self._monitor_file,
env=self._get_environment_variables())
def _get_environment_variables(self):
environment_variables = os.environ.copy()
if environment_variables.has_key("ROBOT_SYSLOG_FILE"):
del(environment_variables["ROBOT_SYSLOG_FILE"])
return environment_variables
def wait(self):
rc = self._process.wait()
self._monitor_file.close()
return rc
def report(self):
with open(self._monitor_out, 'r') as monitor_file:
monitor_output = monitor_file.read()
try:
os.remove(self._monitor_out)
except:
pass
match = re.search('^Log: (.*)$', monitor_output, re.MULTILINE)
monitor_output = self._replace_stdout_log_message_levels(monitor_output)
monitor_output = html_escape(monitor_output)
if match:
monitor_output = monitor_output.replace(match.group(1), '<a href="%s#test_%s.%s">%s</a>' % (self._log, self._suite_name, self.test, match.group(1)))
monitor_output = self._add_colours(monitor_output)
print "*HTML* %s" % monitor_output
def _replace_stdout_log_message_levels(self, output):
for level in ['TRACE', 'WARN', 'DEBUG', 'INFO', 'HTML']:
output = output.replace('\n*%s*' % level, '\n *%s*' % level)
return output
def _add_colours(self, output):
for name, colour in [("PASS", "pass"), ("FAIL", "fail"), ("ERROR", "fail")]:
output = output.replace(' %s ' % name, ' <span class="%s">%s</span> ' % (colour, name))
return output
def stop_test_execution(self):
try:
self._process.terminate()
except AttributeError:
pass
self.report()
def _get_cmd_arguments():
import robot
runner_path = os.path.join(os.path.dirname(os.path.abspath(robot.__file__)),
'runner.py')
with open(runner_path, 'r') as runner_file:
runner_content = runner_file.read()
return re.search('"""(.+)"""', runner_content, re.DOTALL).groups()[0]
| Python |
from Queue import Queue
from threading import Event
try:
from multiprocessing.managers import BaseManager
except ImportError:
class Python26Required(object):
def __call__(self, *args):
raise RuntimeError('Requires Python > 2.6')
def __getattr__(self, name):
raise RuntimeError('Requires Python > 2.6')
BaseManager = Python26Required()
class _create_caching_getter(object):
def __init__(self, clazz):
self._clazz = clazz
self._objects = {}
def __call__(self, key):
if key not in self._objects:
self._objects[key] = self._clazz()
return self._objects[key]
class Communicate(object):
"""Library for communication between processes.
For example this can be used to handle communication between processes of the Parallel robot library.
Requires Python 2.6
Example:
Process 1 test file:
| *Settings* |
| Library | Communicate |
| *Test Cases* |
| Communicator |
| | [Setup] | Start Communication Service |
| | Send Message To | my message queue | hello world! |
| | ${message}= | Receive Message From | other message queue |
| | Should Be Equal | ${message} | hello! |
| | [Teardown] | Stop Communication Service |
Process 2 test file:
| *Settings* |
| Library | Communicate | ${process 1 ip address if on a different machine} |
| *Test Cases* |
| Helloer |
| | ${message}= | Receive Message From | my message queue |
| | Should Be Equal | ${message} | hello world! |
| | Send Message To | other message queue | hello! |
"""
def __init__(self, address='127.0.0.1', port=2187):
"""
`address` of the communication server.
`port` of the communication server.
"""
self._address = address
self._port = int(port)
self._authkey = 'live long and prosper'
self._queue = None
self._connected = False
def _connect(self):
self._create_manager().connect()
self._connected = True
def start_communication_service(self):
"""Starts a communication server that will be used to share messages and objects between processes.
"""
self._create_manager(_create_caching_getter(Queue),
_create_caching_getter(Event)).start()
self._connected = True
def stop_communication_service(self):
"""Stops a started communication server.
This ensures that the server and the messages that it has don't influence the next tests.
To ensure that this keyword really happens place this in the teardown section.
"""
self._manager.shutdown()
self._connected = False
def _create_manager(self, queue_getter=None, event_getter=None):
BaseManager.register('get_queue', queue_getter)
BaseManager.register('get_event', event_getter)
self._manager = BaseManager((self._address, self._port), self._authkey)
return self._manager
def send_message_to(self, queue_id, value):
"""Send a message to a message queue.
`queue_id` is the identifier for the queue.
`value` is the message. This can be a string, a number or any serializable object.
Example:
In one process
| Send Message To | my queue | hello world! |
...
In another process
| ${message}= | Receive Message From | my queue |
| Should Be Equal | ${message} | hello world! |
"""
self._get_queue(queue_id).put(value)
def receive_message_from(self, queue_id, timeout=None):
"""Receive and consume a message from a message queue.
By default this keyword will block until there is a message in the queue.
`queue_id` is the identifier for the queue.
`timeout` is the time out in seconds to wait.
Returns the value from the message queue. Fails if timeout expires.
Example:
In one process
| Send Message To | my queue | hello world! |
...
In another process
| ${message}= | Receive Message From | my queue |
| Should Be Equal | ${message} | hello world! |
"""
timeout = float(timeout) if timeout is not None else None
return self._get_queue(queue_id).get(timeout=timeout)
def _get_queue(self, queue_id):
if not self._connected:
self._connect()
return self._manager.get_queue(queue_id)
def wait_for_event(self, event_id, timeout=None):
"""Waits until event with `event_id` is signaled.
Fails if optional timeout expires.
`timeout` is the time out in seconds to wait.
Example:
In one process
| Wait For Event | my event |
...
In another process
| Signal Event | my event |
"""
timeout = float(timeout) if timeout is not None else None
self._get_event(event_id).wait(timeout=timeout)
#NOTE! If Event#clear is ever exposed it has to be secured (for example r/w lock) that none
#of the processes can do it while another is at this position.
if not self._get_event(event_id).isSet():
raise Exception('Timeout')
def signal_event(self, event_id):
"""Signals an event.
If a process is waiting for this event it will stop waiting after the signal.
`event` is the identifier for the event.
Example:
In one process
| Wait For Event | my event |
...
In another process
| Signal Event | my event |
"""
return self._get_event(event_id).set()
def _get_event(self, event_id):
if not self._connected:
self._connect()
return self._manager.get_event(event_id)
| Python |
# -*- python -*-
# ex: set syntax=python:
import os
ROBOT_FRAMEWORK_REPOSITORY = 'http://robotframework.googlecode.com/svn/trunk/'
# This is the dictionary that the buildmaster pays attention to. We also use
# a shorter alias to save typing.
c = BuildmasterConfig = {}
####### BUILDSLAVES
from buildbot.buildslave import BuildSlave
c['slaves'] = [BuildSlave("debian-py2.4", "robotci")]
c['slavePortnum'] = 9989
####### CHANGESOURCES
from buildbot.changes.svnpoller import SVNPoller
c['change_source'] = SVNPoller(ROBOT_FRAMEWORK_REPOSITORY, pollinterval=180)
####### SCHEDULERS
from buildbot.scheduler import Scheduler
c['schedulers'] = []
c['schedulers'].append(Scheduler(name="all", branch=None, treeStableTimer=180,
builderNames=["PybotTests"]))
####### BUILDERS
# the 'builders' list defines the Builders. Each one is configured with a
# dictionary, using the following keys:
# name (required): the name used to describe this bilder
# slavename (required): which slave to use, must appear in c['bots']
# builddir (required): which subdirectory to run the builder in
# factory (required): a BuildFactory to define how the build is run
# periodicBuildTime (optional): if set, force a build every N seconds
from buildbot.process import factory
from buildbot.steps.source import SVN
from buildbot.steps.shell import ShellCommand
from buildbot.steps.master import MasterShellCommand
from buildbot.steps.transfer import FileUpload
import glob
OUTPUT_ARCHIVE = 'outputs.zip'
RESULT_DIR = 'results'
class ReportGenerator(MasterShellCommand):
def __init__(self, **kwargs):
command = ['./generate_reports.sh', RESULT_DIR]
MasterShellCommand.__init__(self, command)
self.addFactoryArguments(command=command)
def finished(self, results):
report = open(RESULT_DIR + '/report.html').read().replace('<a href="log.html',
'<a href="log')
self.addHTMLLog('report', report)
self.addHTMLLog('log', open(RESULT_DIR + '/log.html').read())
for sublog in sorted(glob.glob(RESULT_DIR + '/log-*.html')):
self.addHTMLLog(os.path.basename(sublog), open(sublog).read())
return MasterShellCommand.finished(self, results)
f1 = factory.BuildFactory()
f1.addStep(SVN(svnurl=ROBOT_FRAMEWORK_REPOSITORY))
f1.addStep(ShellCommand(command=['python', './install.py', 'in'],
description='Installing',
descriptionDone='Install'))
f1.addStep(ShellCommand(command=['atest/run_atests.py', 'buildbot', 'python',
'--monitorcolors off',
'--exclude manual',
'atest/robot/'],
description='Robot Tests',
descriptionDone='Robot Tests',
timeout=60*60))
f1.addStep(FileUpload(slavesrc='atest/results/' + OUTPUT_ARCHIVE,
masterdest=RESULT_DIR +'/'+ OUTPUT_ARCHIVE))
f1.addStep(ReportGenerator())
b1 = {'name': "PybotTests",
'slavename': "debian-py2.4",
'builddir': "pybot-build",
'factory': f1}
c['builders'] = [b1]
####### STATUS TARGETS
from buildbot.status import html
c['status'] = []
c['status'].append(html.WebStatus(http_port=8010))
from buildbot.status import mail
c['status'].append(mail.MailNotifier(fromaddr="buildbot@robot.radiaatto.ri.fi",
extraRecipients=["robotframework-commit@googlegroups.com"],
sendToInterestedUsers=False,
relayhost='10.127.0.12'))
#
# from buildbot.status import words
# c['status'].append(words.IRC(host="irc.example.com", nick="bb",
# channels=["#example"]))
#
# from buildbot.status import client
# c['status'].append(client.PBListener(9988))
####### DEBUGGING OPTIONS
# if you set 'debugPassword', then you can connect to the buildmaster with
# the diagnostic tool in contrib/debugclient.py . From this tool, you can
# manually force builds and inject changes, which may be useful for testing
# your buildmaster without actually commiting changes to your repository (or
# before you have a functioning 'sources' set up). The debug tool uses the
# same port number as the slaves do: 'slavePortnum'.
c['debugPassword'] = "passwd"
# if you set 'manhole', you can ssh into the buildmaster and get an
# interactive python shell, which may be useful for debugging buildbot
# internals. It is probably only useful for buildbot developers. You can also
# use an authorized_keys file, or plain telnet.
#from buildbot import manhole
#c['manhole'] = manhole.PasswordManhole("tcp:9999:interface=127.0.0.1",
# "admin", "password")
####### PROJECT IDENTITY
# the 'projectName' string will be used to describe the project that this
# buildbot is working on. For example, it is used as the title of the
# waterfall HTML page. The 'projectURL' string will be used to provide a link
# from buildbot HTML pages to your project's home page.
c['projectName'] = "Robot Framework"
c['projectURL'] = "http://robotframework.org/"
# the 'buildbotURL' string should point to the location where the buildbot's
# internal web server (usually the html.Waterfall page) is visible. This
# typically uses the port number set in the Waterfall 'status' entry, but
# with an externally-visible host name which the buildbot cannot figure out
# without some help.
c['buildbotURL'] = "http://robot.radiaatto.ri.fi:8080/"
| Python |
#!/usr/bin/env python
"""A tool for creating data driven test case for Robot Framework
Usage: testgen.py variablefile template output
This script reads the variable and template files and generates a test suite
which has all test cases found in the template multiplied with all the rows of
the variable file. Suite settings, variables and user keywords from the template
file are serialized as is.
Currently, the input files must be in tsv (tab separated values) format. Also
the output file is written in tsv. The variables file must have a format
demonstrated in the example below, e.g. header row, followed by a row with the
names of the variables, and on the subsequent rows the values for the
variables.
Options:
-h -? --help Print this usage instruction.
Example:
<<template.tsv>>
* Settings *
Documentation Example data driven suite
* Test Cases *
Example Test Keyword ${arg1} ${arg2}
* User Keywords *
Keyword [Arguments] ${val1} ${val2}
Log Many ${val1} ${val2}
<<variables.tsv>>
* Variables *
${arg1} ${arg2}
value1 value2
value11 value22
Given above files, command
python testgen.py variables.tsv template.tsv output.tsv
produces following test suite:
<<output.tsv>>
* Settings *
Documentation Example data driven suite
* Test Cases *
Example Test 1 Keyword value1 value2
Example Test 2 Keyword value11 value22
* User Keywords *
Keyword [Arguments] ${val1} ${val2}
Log Many ${val1} ${val2}
"""
import sys
import os
import csv
from robot.parsing.model import FileSuite
from robot.parsing.tsvreader import TsvReader
from robot.errors import DataError, Information
from robot import utils
class TestGeneratingSuite(FileSuite):
def serialize(self, variables, serializer):
self._serialize_settings(serializer)
self._serialize_variables(serializer)
self._serialize_tests(variables, serializer)
self._serialize_keywords(serializer)
def _serialize_settings(self, serializer):
serializer.start_settings()
if self.doc:
serializer.setting('Documentation', self.doc)
for name, value in self.metadata.items():
serializer.setting('Meta: %s' % name, [value])
for name in ['Default Tags', 'Force Tags', 'Suite Setup',
'Suite Teardown', 'Test Setup', 'Test Teardown',
]:
value = self._get_setting(self, name)
if value:
serializer.setting(name, value)
for imp in self.imports:
serializer.setting(imp.name, imp._item.value)
serializer.end_settings()
def _serialize_variables(self, serializer):
serializer.start_variables()
for var in self.variables:
serializer.variable(var.name, var.value)
serializer.end_variables()
def _serialize_tests(self, variables, serializer):
serializer.start_testcases()
for test in self.tests:
orig_name = test.name
for index, vars in enumerate(variables):
test.name = '%s %d' % (orig_name, (index+1))
serializer.start_testcase(test)
if test.doc:
serializer.setting('Documentation', [test.doc])
for name in ['Setup', 'Tags', 'Timeout']:
value = self._get_setting(test, name)
if value is not None:
serializer.setting(name, value)
for kw in test.keywords:
data = self._replace_variables(vars, [kw.name] + kw.args)
serializer.keyword(data)
if test.teardown is not None:
serializer.setting('Teardown', test.teardown)
serializer.end_testcase()
serializer.end_testcases()
def _serialize_keywords(self, serializer):
serializer.start_keywords()
for uk in self.user_keywords:
serializer.start_keyword(uk)
args = self._format_args(uk.args, uk.defaults, uk.varargs)
if args:
serializer.setting('Arguments', args)
if uk.doc:
serializer.setting('Documentation', uk.doc)
if uk.timeout is not None:
serializer.setting('Timeout', uk.timeout)
for kw in uk.keywords:
serializer.keyword([kw.name] + kw.args)
if uk.return_value:
serializer.setting('Return Value', uk.return_value)
serializer.end_keywords()
def _replace_variables(self, variables, data):
replaced = []
for elem in data:
for key in variables:
if key in elem:
elem = elem.replace(key, variables[key])
replaced.append(elem)
return replaced
def _get_setting(self, item, name):
return getattr(item, name.lower().replace(' ', '_'))
def _format_args(self, args, defaults, varargs):
parsed = []
if args:
parsed.extend(list(args))
if defaults:
for i, value in enumerate(defaults):
index = len(args) - len(defaults) + i
parsed[index] = parsed[index] + '=' + value
if varargs:
parsed.append(varargs)
return parsed
class VariableIterator(object):
def __init__(self, varfile):
self._variable_mapping = {}
self._variables = []
TsvReader().read(varfile, self)
def __iter__(self):
while self._variables:
data = self._variables.pop(0)
values = {}
for key in self._variable_mapping:
values[key] = data[self._variable_mapping[key]]
yield values
def start_table(self, name):
return name.lower().strip() == 'variables'
def add_row(self, row):
if not self._variable_mapping:
for pos in range(len(row)):
self._variable_mapping[row[pos]] = pos
else:
self._variables.append(row)
class AbstractFileWriter(object):
def __init__(self, path, cols):
self._output = open(path, 'wb')
self._cols = cols
self._tc_name = None
self._uk_name = None
def start_settings(self):
self._write_header_row(['Setting', 'Value'])
def end_settings(self):
self._write_empty_row()
def start_variables(self):
self._write_header_row(['Variable', 'Value'])
def end_variables(self):
self._write_empty_row()
def start_testcases(self):
self._write_header_row(['Test Case', 'Action', 'Argument'])
def end_testcases(self):
self._write_empty_row()
def start_testcase(self, testcase):
self._tc_name = testcase.name
def end_testcase(self):
if self._tc_name:
self._write_normal_row([self._tc_name])
self._tc_name = None
self._write_empty_row()
def start_keywords(self):
self._write_header_row(['Keyword', 'Action', 'Argument'])
def end_keywords(self):
self._write_empty_row()
self._output.close()
def start_keyword(self, userkeyword):
self._uk_name = userkeyword.name
def end_keyword(self):
if self._uk_name:
self._write_normal_row([self._uk_name])
self._uk_name = None
self._write_empty_row()
def setting(self, name, value):
if self._tc_name is None and self._uk_name is None:
self._write_normal_row([name] + value)
else: # TC and UK settings
row = [self._get_tc_or_uk_name(), '[%s]' % name] + value
self._write_normal_row(row, indent=1)
def variable(self, name, value):
self._write_normal_row([name] + value)
def keyword(self, keyword):
name = self._get_tc_or_uk_name()
# TODO: When adding support for PARALLEL, FOR, etc. need to use
# different indent when inside indented block
self._write_normal_row([name] + keyword, indent=1)
def _write_header_row(self, row):
row += [row[-1]] * (self._cols - len(row))
self._write_header_row_impl(row)
def _write_normal_row(self, row, indent=0):
firstrow = True
while True:
if firstrow:
current = row[:self._cols]
row = row[self._cols:]
firstrow = False
else:
current = ['']*indent + ['...'] + row[:self._cols-indent-1]
row = row[self._cols-indent-1:]
self._escape_empty_trailing_cells(current)
current += [''] * (self._cols - len(current))
self._write_normal_row_impl(current)
if not row:
break
def _write_empty_row(self):
self._write_normal_row([])
def _escape_empty_trailing_cells(self, row):
if len(row) > 0 and row[-1] == '':
row[-1] = '\\'
def _get_title(self, path):
dire, base = os.path.split(path)
if base.lower() == '__init__.html':
path = dire
return utils.printable_name_from_path(path)
def _write_header_row_impl(self, row):
raise NotImplementedError
def _write_normal_row_impl(self, row):
raise NotImplementedError
class TsvFileWriter(AbstractFileWriter):
def __init__(self, path):
AbstractFileWriter.__init__(self, path, 8)
self._writer = csv.writer(self._output, dialect='excel-tab')
def _write_header_row_impl(self, row):
self._writer.writerow(['*%s*' % cell for cell in row])
def _write_normal_row_impl(self, row):
self._writer.writerow([cell.encode('UTF-8') for cell in row])
def _get_tc_or_uk_name(self):
if self._tc_name:
name = self._tc_name
self._tc_name = ''
elif self._uk_name:
name = self._uk_name
self._uk_name = ''
else:
name = ''
return name
def generate_suite(cliargs):
opts, (varfile, templatefile, outfile) = _process_args(cliargs)
suite = TestGeneratingSuite(templatefile)
vars = VariableIterator(open(varfile))
if not outfile.endswith('tsv'):
outfile = outfile + '.tsv'
suite.serialize(vars, TsvFileWriter(outfile))
def _process_args(cliargs):
ap = utils.ArgumentParser(__doc__, arg_limits=(3, sys.maxint))
try:
opts, paths = ap.parse_args(cliargs, help='help', check_args=True)
except Information, msg:
exit(msg=str(msg))
except DataError, err:
exit(error=str(err))
return opts, paths
def exit(rc=0, error=None, msg=None):
if error:
print error, "\n\nUse '--help' option to get usage information."
if rc == 0:
rc = 255
if msg:
print msg
rc = 1
sys.exit(rc)
if __name__ == '__main__':
generate_suite(sys.argv[1:])
| Python |
import datetime
from vacalc.employeestore import Employee
def calculate_vacation(startdate, vacation_year, exp_vacation_days):
try:
sdate = datetime.date(*(int(item) for item in startdate.split('-')))
except Exception, err:
raise AssertionError('Invalid time format %s' % err)
actual_days = Employee('Test Employee', sdate).count_vacation(int(vacation_year))
if actual_days != int(exp_vacation_days):
raise AssertionError('%s != %s' % (exp_vacation_days, actual_days))
| Python |
import os
import tempfile
from org.robotframework.vacalc import VacationCalculator
from vacalc.ui import VacalcFrame
from vacalc.employeestore import EmployeeStore, VacalcError
class VacalcApplication(VacationCalculator):
def create(self):
default_db = os.path.join(tempfile.gettempdir(), 'vacalcdb.csv')
self._db_file= os.environ.get('VACALC_DB', default_db)
self._size = os.stat(self._db_file).st_size if os.path.exists(self._db_file) else 0
self._store = EmployeeStore(self._db_file)
self._frame = VacalcFrame(EmployeeController(self._store))
self._frame.show()
class EmployeeController(object):
def __init__(self, employeestore):
self._store = employeestore
self._change_listeners = []
def all(self):
return self._store.get_all_employees()
def add(self, name, startdate):
try:
employee = self._store.add_employee(name, startdate)
except VacalcError, err:
for l in self._change_listeners:
l.adding_employee_failed(unicode(err))
else:
for l in self._change_listeners:
l.employee_added(employee)
def add_change_listener(self, listener):
self._change_listeners.append(listener)
| Python |
from javax.swing import JFrame, JList, JPanel, JLabel, JTextField, JButton, Box, BoxLayout, JTable
from javax.swing.event import ListSelectionListener
from javax.swing.table import AbstractTableModel
from java.awt.event import ActionListener
from java.awt import FlowLayout, BorderLayout, Dimension, Font, Color
class VacalcFrame(object):
def __init__(self, employees):
self._frame = JFrame('Vacation Calculator',
defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
self._frame.setContentPane(self._create_ui(employees))
self._frame.pack()
def _create_ui(self, employees):
panel = JPanel(layout=FlowLayout())
self._overview = EmployeeOverview(employees, self)
self._details = EmployeeDetails(employees)
self._welcome = Welcome()
panel.add(self._overview)
panel.add(self._welcome)
return panel
def show(self):
self._frame.setVisible(True)
def employee_selected(self, employee):
self._ensure_details_shown()
self._details.show_employee(employee)
def edit_new_employee(self):
self._ensure_details_shown()
self._details.edit_new_employee()
def _ensure_details_shown(self):
if self._welcome:
self._frame.contentPane.remove(self._welcome)
self._frame.contentPane.add(self._details)
self._frame.pack()
self._welcome = None
class EmployeeOverview(JPanel):
def __init__(self, employees, overview_listener):
JPanel.__init__(self, layout=BorderLayout())
self._listener = overview_listener
self._employee_list = self._create_employee_list(employees)
new_emp_btn = self._create_new_employee_button()
self.add(self._employee_list.widget, BorderLayout.PAGE_START)
self.add(new_emp_btn, BorderLayout.PAGE_END)
def _create_employee_list(self, employees):
list = EmployeeList(employees)
list.add_selection_listener(ListenerFactory(ListSelectionListener,
self._list_item_selected))
return list
def _create_new_employee_button(self):
btn = JButton('New Employee', name='new_employee_button')
btn.addActionListener(ListenerFactory(ActionListener, self._new_employee))
return btn
def _list_item_selected(self, event):
self._listener.employee_selected(self._employee_list.selected_employee())
def _new_employee(self, event):
self._employee_list.clear_selection()
self._listener.edit_new_employee()
class EmployeeList(object):
def __init__(self, employees):
self._employees = employees
self._employees.add_change_listener(self)
self._list = JList(preferredSize=(200, 200), name='employee_list')
self._populate_list()
def _populate_list(self):
self._list.setListData(self._employee_names())
def _employee_names(self):
return [e.name for e in self._employees.all()]
def add_selection_listener(self, listener):
self._list.addListSelectionListener(listener)
def selected_employee(self):
return self._employees.all()[self._list.getSelectedIndex()]
def employee_added(self, employee):
self._populate_list()
self._list.setSelectedValue(employee.name, True)
def adding_employee_failed(self, error):
pass
def clear_selection(self):
self._list.clearSelection()
@property
def widget(self):
return self._list
class EmployeeDetails(JPanel):
def __init__(self, employees):
JPanel.__init__(self, preferredSize=(400, 200))
layout = BoxLayout(self, BoxLayout.Y_AXIS)
self.setLayout(layout)
self._employees = employees
employees.add_change_listener(self)
self._create_status_label()
self._create_name_editor()
self._create_start_date_editor()
self._create_save_button()
self._create_vacation_display()
self._adding_employee = False
def _create_status_label(self):
self._status_label = JLabel(name='status_label',
font=Font(Font.SANS_SERIF, Font.PLAIN, 11))
self.add(self._status_label)
self._add_with_padding(self._status_label, 5)
def _create_name_editor(self):
self.add(JLabel(text='Employee Name:'))
self._name_editor = FixedHeightTextField('name_input')
self._add_with_padding(self._name_editor, 5)
def _create_start_date_editor(self):
self.add(JLabel(text='Start Date (yyyy-mm-dd):'))
self._start_date_editor = FixedHeightTextField('start_input')
self._add_with_padding(self._start_date_editor, 5)
def _create_save_button(self):
self._save_button = JButton('Save', name='save_button', visible=False)
self._save_button.addActionListener(ListenerFactory(ActionListener,
self._save_button_pushed))
self._add_with_padding(self._save_button, 5)
def _create_vacation_display(self):
# self._display = JTable()
# self._header = self._display.getTableHeader()
# self.add(self._header)
# self.add(self._display)
pass
def _add_with_padding(self, component, padding):
self.add(component)
self.add(Box.createRigidArea(Dimension(0, padding)))
def show_employee(self, employee):
self._name_editor.setText(employee.name)
self._start_date_editor.setText(str(employee.startdate))
self._name_editor.setEditable(False)
self._start_date_editor.setEditable(False)
self._save_button.setVisible(False)
if self._adding_employee:
self._adding_employee = False
else:
self._status_label.setText('')
# self._display.setVisible(True)
# self._display.setModel(VacationTableModel(employee))
# self._header.setVisible(True)
def edit_new_employee(self):
self._name_editor.setText('')
self._start_date_editor.setText('')
self._name_editor.setEditable(True)
self._start_date_editor.setEditable(True)
self._save_button.setVisible(True)
# self._display.setVisible(False)
# self._header.setVisible(False)
self._adding_employee = True
def _save_button_pushed(self, event):
self._employees.add(self._name_editor.getText(),
self._start_date_editor.getText())
def employee_added(self, employee):
self._status_label.setForeground(Color.BLACK)
self._status_label.setText("Employee '%s' was added successfully." % employee.name)
self._save_button.setVisible(False)
def adding_employee_failed(self, reason):
self._status_label.setForeground(Color.RED)
self._status_label.setText(reason)
class FixedHeightTextField(JTextField):
def __init__(self, name):
JTextField.__init__(self, name=name)
prefsize = self.preferredSize
maxsize = self.maximumSize
self.setMaximumSize(Dimension(maxsize.width, prefsize.height))
class Welcome(JPanel):
def __init__(self):
JPanel.__init__(self, preferredSize=(400,200))
self.add(JLabel('VaCalc v0.1'))
class VacationTableModel(AbstractTableModel):
_columns = ['Year', 'Vacation']
def __init__(self, employee):
self._employee = employee
def getColumnName(self, index):
return self._columns[index]
def getColumnCount(self):
return 2
def getRowCount(self):
return 1
def getValueAt(self, row, col):
if col == 0:
return '2010'
return '%s days' % self._employee.count_vacation(2010)
def ListenerFactory(interface, func):
from java.lang import Object
method = list(set(dir(interface)) - set(dir(Object)))[0]
return type('Listener', (interface,), {method: func})()
| Python |
from vacalcapp import VacalcApplication
| Python |
from __future__ import with_statement
import os
import csv
import datetime
class VacalcError(RuntimeError): pass
class EmployeeStore(object):
def __init__(self, db_file):
self._db_file = db_file
if self._db_file and os.path.isfile(self._db_file):
self._employees = self._read_employees(self._db_file)
else:
self._employees = {}
def _read_employees(self, path):
employees = {}
with open(path) as db:
for row in csv.reader(db):
employee = Employee(row[0], self._parse_date(row[1]))
employees[employee.name] = employee
return employees
def refresh(self):
self.__init__(self._db_file)
def get_employee(self, name):
try:
return self._employees[name]
except KeyError:
raise VacalcError("Employee '%s' not found." % name)
def get_all_employees(self):
return self._employees.values()
def add_employee(self, name, startdate):
if name in self._employees:
raise VacalcError("Employee '%s' already exists in the system."
% name)
employee = Employee(name, self._parse_date(startdate))
self._employees[employee.name] = employee
self._serialize(employee)
return employee
def _serialize(self, employee):
if not self._db_file:
return
with open(self._db_file, 'a') as db:
writer = csv.writer(db, lineterminator='\n')
writer.writerow([employee.name, employee.startdate])
def _parse_date(self, datestring):
if not datestring:
raise VacalcError('No start date given.')
try:
year, month, day = (int(item) for item in datestring.split('-'))
except ValueError:
raise VacalcError('Invalid start date.')
try:
return datetime.date(year, month, day)
except ValueError, err:
raise VacalcError(err.args[0].capitalize() + '.')
class Employee(object):
max_vacation = int(12 * 2.5)
no_vacation = 0
vacation_per_month = 2
credit_start_month = 4
work_days_required= 14
def __init__(self, name, startdate):
self.name = name
self.startdate = startdate
def count_vacation(self, year):
return self._count_vacation(self.startdate, year)
def _count_vacation(self, startdate, year):
if self._has_worked_longer_than_year(startdate, year):
return self.max_vacation
if self._started_after_holiday_credit_year_ended(startdate, year):
return self.no_vacation
return self._count_working_months(startdate) * self.vacation_per_month
def _has_worked_longer_than_year(self, start, year):
return year-start.year > 1 or \
(year-start.year == 1 and start.month < self.credit_start_month)
def _started_after_holiday_credit_year_ended(self, start, year):
return start.year-year > 0 or \
(year == start.year and start.month >= self.credit_start_month)
def _count_working_months(self, start):
months = self.credit_start_month - start.month
if months <= 0:
months += 12
if self._first_month_has_too_few_working_days(start):
months -= 1
return months
def _first_month_has_too_few_working_days(self, start):
days = 0
date = start
while date:
if self._is_working_day(date):
days += 1
date = self._next_date(date)
return days < self.work_days_required
def _is_working_day(self, date):
return date.weekday() < 5
def _next_date(self, date):
try:
return date.replace(day=date.day+1)
except ValueError:
return None
| Python |
#!/usr/bin/env python
"""Packaging script for Robot Framework
Usage: package.py command version_number [release_tag]
Argument 'command' can have one of the following values:
- sdist : create source distribution
- wininst : create Windows installer
- all : create both packages
- version : update only version information in 'src/robot/version.py'
- jar : create stand-alone jar file containing RF and Jython
'version_number' must be a version number in format '2.x(.y)', 'trunk' or
'keep'. With 'keep', version information is not updated.
'release_tag' must be either 'alpha', 'beta', 'rc' or 'final', where all but
the last one can have a number after the name like 'alpha1' or 'rc2'. When
'version_number' is 'trunk', 'release_tag' is automatically assigned to the
current date.
When creating the jar distribution, jython.jar must be placed in 'ext-lib'
directory, under the project root.
This script uses 'setup.py' internally. Distribution packages are created
under 'dist' directory, which is deleted initially. Depending on your system,
you may need to run this script with administrative rights (e.g. with 'sudo').
Examples:
package.py sdist 2.0 final
package.py wininst keep
package.py all 2.1.13 alpha
package.py sdist trunk
package.py version trunk
"""
import sys
import os
from os.path import abspath, dirname, exists, join
import shutil
import re
import time
import subprocess
import zipfile
from glob import glob
ROOT_PATH = abspath(dirname(__file__))
DIST_PATH = join(ROOT_PATH, 'dist')
BUILD_PATH = join(ROOT_PATH, 'build')
ROBOT_PATH = join(ROOT_PATH, 'src', 'robot')
JAVA_SRC = join(ROOT_PATH, 'src', 'java', 'org', 'robotframework')
JYTHON_JAR = glob(join(ROOT_PATH, 'ext-lib', 'jython-standalone-*.jar'))[0]
SETUP_PATH = join(ROOT_PATH, 'setup.py')
VERSION_PATH = join(ROBOT_PATH, 'version.py')
VERSIONS = [re.compile('^2\.\d+(\.\d+)?$'), 'trunk', 'keep']
RELEASES = [re.compile('^alpha\d*$'), re.compile('^beta\d*$'),
re.compile('^rc\d*$'), 'final']
VERSION_CONTENT = """# Automatically generated by 'package.py' script.
import sys
VERSION = '%(version_number)s'
RELEASE = '%(release_tag)s'
TIMESTAMP = '%(timestamp)s'
def get_version(sep=' '):
if RELEASE == 'final':
return VERSION
return VERSION + sep + RELEASE
def get_full_version(who=''):
sys_version = sys.version.split()[0]
version = '%%s %%s (%%s %%s on %%s)' \\
%% (who, get_version(), _get_interpreter(), sys_version, sys.platform)
return version.strip()
def _get_interpreter():
if sys.platform.startswith('java'):
return 'Jython'
if sys.platform == 'cli':
return 'IronPython'
return 'Python'
"""
def sdist(*version_info):
version(*version_info)
_clean()
_create_sdist()
_announce()
def wininst(*version_info):
version(*version_info)
_clean()
if _verify_platform(*version_info):
_create_wininst()
_announce()
def all(*version_info):
version(*version_info)
_clean()
_create_sdist()
if _verify_platform(*version_info):
_create_wininst()
_announce()
def version(version_number, release_tag=None):
_verify_version(version_number, VERSIONS)
if version_number == 'keep':
_keep_version()
elif version_number =='trunk':
_update_version(version_number, '%d%02d%02d' % time.localtime()[:3])
else:
_update_version(version_number, _verify_version(release_tag, RELEASES))
sys.path.insert(0, ROBOT_PATH)
from version import get_version
return get_version(sep='-')
def _verify_version(given, valid):
for item in valid:
if given == item or (hasattr(item, 'search') and item.search(given)):
return given
raise ValueError
def _update_version(version_number, release_tag):
timestamp = '%d%02d%02d-%02d%02d%02d' % time.localtime()[:6]
vfile = open(VERSION_PATH, 'wb')
vfile.write(VERSION_CONTENT % locals())
vfile.close()
print 'Updated version to %s %s' % (version_number, release_tag)
def _keep_version():
sys.path.insert(0, ROBOT_PATH)
from version import get_version
print 'Keeping version %s' % get_version()
def _clean():
print 'Cleaning up...'
for path in [DIST_PATH, BUILD_PATH]:
if exists(path):
shutil.rmtree(path)
def _verify_platform(version_number, release_tag=None):
if release_tag == 'final' and os.sep != '\\':
print 'Final Windows installers can only be created in Windows.'
print 'Windows installer was not created.'
return False
return True
def _create_sdist():
_create('sdist', 'source distribution')
def _create_wininst():
_create('bdist_wininst', 'Windows installer')
if os.sep != '\\':
print 'Warning: Windows installers created on other platforms may not'
print 'be exactly identical to ones created in Windows.'
def _create(command, name):
print 'Creating %s...' % name
rc = os.system('%s %s %s' % (sys.executable, SETUP_PATH, command))
if rc != 0:
print 'Creating %s failed.' % name
sys.exit(rc)
print '%s created successfully.' % name.capitalize()
def _announce():
print 'Created:'
for path in os.listdir(DIST_PATH):
print abspath(join(DIST_PATH, path))
def jar(*version_info):
ver = version(*version_info)
tmpdir = _create_tmpdir()
_compile_java_classes(tmpdir)
_unzip_jython_jar(tmpdir)
_copy_robot_files(tmpdir)
_compile_all_py_files(tmpdir)
_overwrite_manifest(tmpdir, ver)
jar_path = _create_jar_file(tmpdir, ver)
shutil.rmtree(tmpdir)
print 'Created %s based on %s' % (jar_path, JYTHON_JAR)
def _compile_java_classes(tmpdir):
source_files = [join(JAVA_SRC, f)
for f in os.listdir(JAVA_SRC) if f.endswith('.java')]
print 'Compiling %d source files' % len(source_files)
subprocess.call(['javac', '-d', tmpdir, '-target', '1.5', '-cp', JYTHON_JAR]
+ source_files)
def _create_tmpdir():
tmpdir = join(ROOT_PATH, 'tmp-jar-dir')
if exists(tmpdir):
shutil.rmtree(tmpdir)
os.mkdir(tmpdir)
return tmpdir
def _unzip_jython_jar(tmpdir):
zipfile.ZipFile(JYTHON_JAR).extractall(tmpdir)
def _copy_robot_files(tmpdir):
# pyc files must be excluded so that compileall works properly.
todir = join(tmpdir, 'Lib', 'robot')
shutil.copytree(ROBOT_PATH, todir, ignore=shutil.ignore_patterns('*.pyc*'))
def _compile_all_py_files(tmpdir):
subprocess.call(['java', '-jar', JYTHON_JAR, '-m', 'compileall', tmpdir])
# Jython will not work without its py-files, but robot will
for root, _, files in os.walk(join(tmpdir,'Lib','robot')):
for f in files:
if f.endswith('.py'):
os.remove(join(root, f))
def _overwrite_manifest(tmpdir, version):
with open(join(tmpdir, 'META-INF', 'MANIFEST.MF'), 'w') as mf:
mf.write('''Manifest-Version: 1.0
Main-Class: org.robotframework.RobotFramework
Specification-Version: 2
Implementation-Version: %s
''' % version)
def _create_jar_file(source, version):
path = join(DIST_PATH, 'robotframework-%s.jar' % version)
if not exists(DIST_PATH):
os.mkdir(DIST_PATH)
_fill_jar(source, path)
return path
def _fill_jar(sourcedir, jarpath):
subprocess.call(['jar', 'cvfM', jarpath, '.'], cwd=sourcedir)
if __name__ == '__main__':
try:
globals()[sys.argv[1]](*sys.argv[2:])
except (KeyError, IndexError, TypeError, ValueError):
print __doc__
| Python |
#
# Copyright (C) 2008 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
REPO_TRACE = 'REPO_TRACE'
try:
_TRACE = os.environ[REPO_TRACE] == '1'
except KeyError:
_TRACE = False
def IsTrace():
return _TRACE
def SetTrace():
global _TRACE
_TRACE = True
def Trace(fmt, *args):
if IsTrace():
print >>sys.stderr, fmt % args
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.