code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
import os
import tempfile
class OldListenAll:
def __init__(self, *path):
if not path:
path = os.path.join(tempfile.gettempdir(), 'listen_all.txt')
else:
path = ':'.join(path)
self.outfile = open(path, 'w')
def start_suite(self, name, doc):
self.outfile.write("SUITE START: %s '%s'\n" % (name, doc))
def start_test(self, name, doc, tags):
tags = [ str(tag) for tag in tags ]
self.outfile.write("TEST START: %s '%s' %s\n" % (name, doc, tags))
def start_keyword(self, name, args):
args = [ str(arg) for arg in args ]
self.outfile.write("KW START: %s %s\n" % (name, args))
def end_keyword(self, status):
self.outfile.write("KW END: %s\n" % (status))
def end_test(self, status, message):
if status == 'PASS':
self.outfile.write('TEST END: PASS\n')
else:
self.outfile.write("TEST END: %s %s\n" % (status, message))
def end_suite(self, status, message):
self.outfile.write('SUITE END: %s %s\n' % (status, message))
def output_file(self, path):
self._out_file('Output', path)
def summary_file(self, path):
self._out_file('Summary', path)
def report_file(self, path):
self._out_file('Report', path)
def log_file(self, path):
self._out_file('Log', path)
def debug_file(self, path):
self._out_file('Debug', path)
def _out_file(self, name, path):
assert os.path.isabs(path)
self.outfile.write('%s: %s\n' % (name, os.path.basename(path)))
def close(self):
self.outfile.write('Closing...\n')
self.outfile.close()
| Python |
import os
import tempfile
outpath = os.path.join(tempfile.gettempdir(), 'listen_by_module.txt')
OUTFILE = open(outpath, 'w')
ROBOT_LISTENER_API_VERSION = 2
def start_suite(name, attrs):
metastr = ' '.join(['%s: %s' % (k, v) for k, v
in attrs['metadata'].items()])
OUTFILE.write("SUITE START: %s '%s' [%s]\n"
% (name, attrs['doc'], metastr))
def start_test(name, attrs):
tags = [ str(tag) for tag in attrs['tags'] ]
OUTFILE.write("TEST START: %s '%s' %s\n" % (name, attrs['doc'], tags))
def start_keyword(name, attrs):
args = [ str(arg) for arg in attrs['args'] ]
OUTFILE.write("KW START: %s %s\n" % (name, args))
def log_message(message):
msg, level = message['message'], message['level']
if level != 'TRACE' and 'Traceback' not in msg:
OUTFILE.write('LOG MESSAGE: [%s] %s\n' % (level, msg))
def message(message):
msg, level = message['message'], message['level']
if 'Settings' in msg:
OUTFILE.write('Got settings on level: %s\n' % level)
def end_keyword(name, attrs):
OUTFILE.write("KW END: %s\n" % (attrs['status']))
def end_test(name, attrs):
if attrs['status'] == 'PASS':
OUTFILE.write('TEST END: PASS\n')
else:
OUTFILE.write("TEST END: %s %s\n" % (attrs['status'], attrs['message']))
def end_suite(name, attrs):
OUTFILE.write('SUITE END: %s %s\n' % (attrs['status'], attrs['statistics']))
def output_file(path):
_out_file('Output', path)
def summary_file(path):
_out_file('Summary', path)
def report_file(path):
_out_file('Report', path)
def log_file(path):
_out_file('Log', path)
def debug_file(path):
_out_file('Debug', path)
def _out_file(name, path):
assert os.path.isabs(path)
OUTFILE.write('%s: %s\n' % (name, os.path.basename(path)))
def close():
OUTFILE.write('Closing...\n')
OUTFILE.close()
| Python |
import os
import tempfile
class ListenSome:
def __init__(self):
outpath = os.path.join(tempfile.gettempdir(), 'listen_some.txt')
self.outfile = open(outpath, 'w')
def startTest(self, name, doc, tags):
self.outfile.write(name + '\n')
def endSuite(self, stat, msg):
self.outfile.write(msg + '\n')
def close(self):
self.outfile.close()
class WithArgs(object):
def __init__(self, arg1, arg2='default'):
outpath = os.path.join(tempfile.gettempdir(), 'listener_with_args.txt')
outfile = open(outpath, 'a')
outfile.write("I got arguments '%s' and '%s'\n" % (arg1, arg2))
outfile.close()
class InvalidMethods:
def start_suite(self, wrong, number, of, args, here):
pass
def end_suite(self, *args):
raise RuntimeError("Here comes an exception!")
| Python |
import os
import tempfile
from robot.libraries.BuiltIn import BuiltIn
class ListenSome:
ROBOT_LISTENER_API_VERSION = '2'
def __init__(self):
outpath = os.path.join(tempfile.gettempdir(), 'listen_some.txt')
self.outfile = open(outpath, 'w')
def startTest(self, name, attrs):
self.outfile.write(name + '\n')
def endSuite(self, name, attrs):
self.outfile.write(attrs['statistics'] + '\n')
def close(self):
self.outfile.close()
class WithArgs(object):
ROBOT_LISTENER_API_VERSION = '2'
def __init__(self, arg1, arg2='default'):
outpath = os.path.join(tempfile.gettempdir(), 'listener_with_args.txt')
outfile = open(outpath, 'a')
outfile.write("I got arguments '%s' and '%s'\n" % (arg1, arg2))
outfile.close()
class InvalidMethods:
ROBOT_LISTENER_API_VERSION = '2'
def start_suite(self, wrong, number, of, args, here):
pass
def end_suite(self, *args):
raise RuntimeError("Here comes an exception!")
def message(self, msg):
raise ValueError("This fails continuously!")
class SuiteAndTestCounts(object):
ROBOT_LISTENER_API_VERSION = '2'
exp_data = {
'Subsuites & Subsuites2': ([], ['Subsuites', 'Subsuites2'], 4),
'Subsuites': ([], ['Sub1', 'Sub2'], 2),
'Sub1': (['SubSuite1 First'], [], 1),
'Sub2': (['SubSuite2 First'], [], 1),
'Subsuites2': ([], ['Subsuite3'], 2),
'Subsuite3': (['SubSuite3 First', 'SubSuite3 Second'], [], 2),
}
def start_suite(self, name, attrs):
data = attrs['tests'], attrs['suites'], attrs['totaltests']
if not data == self.exp_data[name]:
raise RuntimeError('Wrong tests or suites in %s, %s != %s' %
(name, self.exp_data[name], data))
class KeywordType(object):
ROBOT_LISTENER_API_VERSION = '2'
def start_keyword(self, name, attrs):
expected = attrs['args'][0] if name == 'BuiltIn.Log' else name
if attrs['type'] != expected:
raise RuntimeError("Wrong keyword type '%s', expected '%s'."
% (attrs['type'], expected))
end_keyword = start_keyword
class KeywordExecutingListener(object):
ROBOT_LISTENER_API_VERSION = '2'
def start_suite(self, name, attrs):
self._start(name)
def end_suite(self, name, attrs):
self._end(name)
def start_test(self, name, attrs):
self._start(name)
def end_test(self, name, attrs):
self._end(name)
def _start(self, name):
self._run_keyword('Start %s' % name)
def _end(self, name):
self._run_keyword('End %s' % name)
def _run_keyword(self, arg):
BuiltIn().run_keyword('Log', arg)
| Python |
import os
import tempfile
outpath = os.path.join(tempfile.gettempdir(), 'listen_by_module.txt')
OUTFILE = open(outpath, 'w')
def start_suite(name, doc):
OUTFILE.write("SUITE START: %s '%s'\n" % (name, doc))
def start_test(name, doc, tags):
tags = [ str(tag) for tag in tags ]
OUTFILE.write("TEST START: %s '%s' %s\n" % (name, doc, tags))
def start_keyword(name, args):
args = [ str(arg) for arg in args ]
OUTFILE.write("KW START: %s %s\n" % (name, args))
def end_keyword(status):
OUTFILE.write("KW END: %s\n" % (status))
def end_test(status, message):
if status == 'PASS':
OUTFILE.write('TEST END: PASS\n')
else:
OUTFILE.write("TEST END: %s %s\n" % (status, message))
def end_suite(status, message):
OUTFILE.write('SUITE END: %s %s\n' % (status, message))
def output_file(path):
_out_file('Output', path)
def summary_file(path):
_out_file('Summary', path)
def report_file(path):
_out_file('Report', path)
def log_file(path):
_out_file('Log', path)
def debug_file(path):
_out_file('Debug', path)
def _out_file(name, path):
assert os.path.isabs(path)
OUTFILE.write('%s: %s\n' % (name, os.path.basename(path)))
def close():
OUTFILE.write('Closing...\n')
OUTFILE.close()
| Python |
import os
import tempfile
ROBOT_LISTENER_API_VERSION = '2'
OUTFILE = open(os.path.join(tempfile.gettempdir(), 'listener_attrs.txt'), 'w')
START_ATTRIBUTES = ['doc', 'starttime']
END_ATTRIBUTES = START_ATTRIBUTES + ['endtime', 'elapsedtime', 'status']
EXPECTED_TYPES = {'elapsedtime': (int, long), 'tags': list, 'args': list,
'metadata': dict, 'tests': list, 'suites': list,
'totaltests': int}
def start_suite(name, attrs):
_verify_attributes('START SUITE', attrs,
START_ATTRIBUTES+['longname', 'metadata', 'tests',
'suites', 'totaltests'])
def end_suite(name, attrs):
_verify_attributes('END SUITE', attrs, END_ATTRIBUTES+['longname', 'statistics', 'message'])
def start_test(name, attrs):
_verify_attributes('START TEST', attrs, START_ATTRIBUTES + ['longname', 'tags'])
def end_test(name, attrs):
_verify_attributes('END TEST', attrs, END_ATTRIBUTES + ['longname', 'tags', 'message'])
def start_keyword(name, attrs):
_verify_attributes('START KEYWORD', attrs, START_ATTRIBUTES + ['args', 'type'])
def end_keyword(name, attrs):
_verify_attributes('END KEYWORD', attrs, END_ATTRIBUTES + ['args', 'type'])
def _verify_attributes(method_name, attrs, names):
OUTFILE.write(method_name + '\n')
if len(names) != len(attrs):
OUTFILE.write('FAILED: wrong number of attributes\n')
OUTFILE.write('Expected: %s\nActual: %s\n' % (names, attrs.keys()))
return
for name in names:
value = attrs[name]
exp_type = EXPECTED_TYPES.get(name, basestring)
if isinstance(value, exp_type):
OUTFILE.write('PASSED | %s: %s\n' % (name, value))
else:
OUTFILE.write('FAILED | %s: %r, Expected: %s, Actual: %s\n'
% (name, value, type(value), exp_type))
def close():
OUTFILE.close()
| Python |
def get_variables(*args):
return { 'PPATH_VARFILE_2' : ' '.join(args),
'LIST__PPATH_VARFILE_2' : args }
| Python |
PPATH_VARFILE = "Variable from varible file in PYTHONPATH" | Python |
list1 = [1, 2, 3, 4, 'foo', 'bar']
dictionary1 = {'a': 1}
dictionary2 = {'a': 1, 'b': 2}
| Python |
class TraceLogArgsLibrary(object):
def only_mandatory(self, mand1, mand2):
pass
def mandatory_and_default(self, mand, default="default value"):
pass
def multiple_default_values(self, a=1, a2=2, a3=3, a4=4):
pass
def mandatory_and_varargs(self, mand, *varargs):
pass
def return_object_with_invalid_repr(self):
return InvalidRepr()
def return_object_with_non_ascii_string_repr(self):
return ByteRepr()
class InvalidRepr:
def __repr__(self):
return u'Hyv\xe4'
class ByteRepr:
def __repr__(self):
return 'Hyv\xe4' | Python |
class FailUntilSucceeds:
ROBOT_LIBRARY_SCOPE = 'TESTCASE'
def __init__(self, times_to_fail=0):
self.times_to_fail = int(times_to_fail)
def fail_until_retried_often_enough(self, message="Hello"):
self.times_to_fail -= 1
if self.times_to_fail >= 0:
raise Exception('Still %d times to fail!' % (self.times_to_fail))
return message
| Python |
import exceptions
class ObjectToReturn:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def exception(self, name, msg=""):
exception = getattr(exceptions, name)
raise exception, msg
| Python |
class SameNamesAsInBuiltIn:
def noop(self):
"""Using this keyword without libname causes an error""" | Python |
class ZipLib:
def kw_from_zip(self, arg):
print '*INFO*', arg
return arg * 2
| Python |
class PythonVarArgsConstructor:
def __init__(self, mandatory, *varargs):
self.mandatory = mandatory
self.varargs = varargs
def get_args(self):
return self.mandatory, ' '.join(self.varargs)
| Python |
import os
_dirs = __file__.split(os.sep)
while True:
if _dirs.pop() == 'atest':
break
_BITMAP = os.path.join(os.sep.join(_dirs), 'robot.bmp')
class BinaryDataLibrary:
def print_bytes(self):
"""Prints all bytes in range 0-255. Many of them are control chars."""
for i in range(256):
print "*INFO* Byte %d: '%s'" % (i, chr(i))
print "*INFO* All bytes printed succesfully"
def raise_byte_error(self):
raise AssertionError, "Bytes 0, 10, 127, 255: '%s', '%s', '%s', '%s'" \
% (chr(0), chr(10), chr(127), chr(255))
def print_binary_data(self):
bitmap = open(_BITMAP, 'rb')
print bitmap.read()
bitmap.close()
print "*INFO* Binary data printed successfully"
| Python |
import ExampleJavaLibrary
import DefaultArgs
class ExtendJavaLib(ExampleJavaLibrary):
def kw_in_java_extender(self, arg):
return arg*2
def javaSleep(self, secs):
raise Exception('Overridden kw executed!')
def using_method_from_java_parent(self):
self.divByZero()
class ExtendJavaLibWithConstructor(DefaultArgs):
def keyword(self):
return None
class ExtendJavaLibWithInit(ExampleJavaLibrary):
def __init__(self, *args):
self.args = args
def get_args(self):
return self.args
class ExtendJavaLibWithInitAndConstructor(DefaultArgs):
def __init__(self, *args):
if len(args) == 1:
DefaultArgs.__init__(self, args[0])
self.kw = lambda self: "Hello, world!"
| Python |
import os # Tests that standard modules can be imported from libraries
import sys
class ImportRobotModuleTestLibrary:
"""Tests that robot internal modules can't be imported accidentally"""
def import_logging(self):
try:
import logging
except ImportError:
if os.name == 'java':
print 'Could not import logging, which is OK in Jython!'
return
raise AssertionError, 'Importing logging module failed with Python!'
try:
logger = logging.getLogger()
except:
raise AssertionError, 'Wrong logging module imported!'
print 'Importing succeeded!'
def importing_robot_module_directly_fails(self):
try:
import serializing
except ImportError:
pass
except:
raise
else:
msg = "'import result' should have failed. Got it from '%s'. sys.path: %s"
raise AssertionError, msg % (serializing.__file__, sys.path)
def importing_robot_module_through_robot_succeeds(self):
try:
import robot.running
except:
raise AssertionError, "'import robot.running' failed"
| Python |
class ArgumentsPython:
# method docs are used in unit tests as expected min and max args
def a_0(self):
"""(0,0)"""
return 'a_0'
def a_1(self, arg):
"""(1,1)"""
return 'a_1: ' + arg
def a_3(self, arg1, arg2, arg3):
"""(3,3)"""
return ' '.join(['a_3:',arg1,arg2,arg3])
def a_0_1(self, arg='default'):
"""(0,1)"""
return 'a_0_1: ' + arg
def a_1_3(self, arg1, arg2='default', arg3='default'):
"""(1,3)"""
return ' '.join(['a_1_3:',arg1,arg2,arg3])
def a_0_n(self, *args):
"""(0,sys.maxint)"""
return ' '.join(['a_0_n:', ' '.join(args)])
def a_1_n(self, arg, *args):
"""(1,sys.maxint)"""
return ' '.join(['a_1_n:', arg, ' '.join(args)])
def a_1_2_n(self, arg1, arg2='default', *args):
"""(1,sys.maxint)"""
return ' '.join(['a_1_2_n:', arg1, arg2, ' '.join(args)])
| Python |
from robot import utils
class RunKeywordLibrary:
ROBOT_LIBRARY_SCOPE = 'TESTCASE'
def __init__(self):
self.kw_names = ['Run Keyword That Passes', 'Run Keyword That Fails']
def get_keyword_names(self):
return self.kw_names
def run_keyword(self, name, args):
try:
method = dict(zip(self.kw_names, [self._passes, self._fails]))[name]
except KeyError:
raise AttributeError
return method(args)
def _passes(self, args):
for arg in args:
print arg,
return ', '.join(args)
def _fails(self, args):
if not args:
raise AssertionError('Failure')
raise AssertionError('Failure: %s' % ' '.join(args))
class GlobalRunKeywordLibrary(RunKeywordLibrary):
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
class RunKeywordButNoGetKeywordNamesLibrary:
def run_keyword(self, *args):
return ' '.join(args)
def some_other_keyword(self, *args):
return ' '.join(args)
| Python |
library = "It should be OK to have an attribute with same name as the module"
def keyword_from_submodule(arg='World'):
return "Hello, %s!" % arg
| Python |
some_string = 'Hello, World!'
class _SomeObject:
pass
some_object = _SomeObject() | Python |
class KwargsLibrary(object):
def __init__(self, arg1=None, arg2=None):
self.arg1 = arg1
self.arg2 = arg2
def check_init_arguments(self, exp_arg1, exp_arg2):
if self.arg1 != exp_arg1 or self.arg2 != exp_arg2:
raise AssertionError('Wrong initialization values. Got (%s, %s), expected (%s, %s)'
% (self.arg1, self.arg2, exp_arg1, exp_arg2))
def one_kwarg(self, kwarg=None):
return kwarg
def two_kwargs(self, fst=None, snd=None):
return '%s, %s' % (fst, snd)
def four_kwargs(self, a=None, b=None, c=None, d=None):
return '%s, %s, %s, %s' % (a, b, c, d)
def mandatory_and_kwargs(self, a, b, c=None):
return '%s, %s, %s' % (a, b, c)
def kwargs_and_mandatory_args(self, mandatory, d1=None, d2=None, *varargs):
return '%s, %s, %s, %s' % (mandatory, d1, d2, '[%s]' % ', '.join(varargs)) | Python |
class ParameterLibrary:
def __init__(self, host='localhost', port='8080'):
self.host = host
self.port = port
def parameters(self):
return self.host, self.port | Python |
from robot import utils
def passing_handler(*args):
for arg in args:
print arg,
return ', '.join(args)
def failing_handler(*args):
if len(args) == 0:
msg = 'Failure'
else:
msg = 'Failure: %s' % ' '.join(args)
raise AssertionError(msg)
class GetKeywordNamesLibrary:
def __init__(self):
self.this_is_not_keyword = 'This is just an attribute!!'
def get_keyword_names(self):
return ['Get Keyword That Passes', 'Get Keyword That Fails',
'keyword_in_library_itself', 'non_existing_kw',
'this_is_not_keyword']
def __getattr__(self, name):
if name == 'Get Keyword That Passes':
return passing_handler
if name == 'Get Keyword That Fails':
return failing_handler
raise AttributeError("Non-existing keyword '%s'" % name)
def keyword_in_library_itself(self):
msg = 'No need for __getattr__ here!!'
print msg
return msg
| Python |
import sys
import time
import exceptions
from robot import utils
from objecttoreturn import ObjectToReturn
class ExampleLibrary:
def print_(self, msg, stream='stdout'):
"""Print given message to selected stream (stdout or stderr)"""
out_stream = getattr(sys, stream)
out_stream.write(msg)
def print_n_times(self, msg, count, delay=0):
"""Print given message n times"""
for i in range(int(count)):
print msg
time.sleep(float(delay))
def print_many(self, *msgs):
"""Print given messages"""
for msg in msgs:
print msg,
print
def print_to_stdout_and_stderr(self, msg):
sys.stdout.write('stdout: ' + msg)
sys.stderr.write('stderr: ' + msg)
def single_line_doc(self):
"""One line keyword documentation."""
pass
def multi_line_doc(self):
"""Only the first line of a multi line keyword doc should be logged.
Thus for example this text here should not be there
and neither should this.
"""
pass
def exception(self, name, msg=""):
"""Raise exception with given name and message"""
exception = getattr(exceptions, name)
raise exception, msg
def external_exception(self, name, msg):
ObjectToReturn('failure').exception(name, msg)
# TODO: Replace these three return_xxx_from_library keywords from test data
# with simple set (from BuiltIn) and remove these
def return_string_from_library(self,string='This is a string from Library'):
return string
def return_list_from_library(self, *args):
return list(args)
def return_three_strings_from_library(self, one='one', two='two', three='three'):
return one, two, three
def return_object(self, name='<noname>'):
return ObjectToReturn(name)
def check_object_name(self, object, name):
assert object.name == name, '%s != %s' % (object.name, name)
def set_object_name(self, object, name):
object.name = name
def set_attribute(self, name, value):
setattr(self, utils.normalize(name), utils.normalize(value))
def get_attribute(self, name):
return getattr(self, utils.normalize(name))
def check_attribute(self, name, expected):
try:
actual = getattr(self, utils.normalize(name))
except AttributeError:
raise AssertionError, "Attribute '%s' not set" % name
if not utils.eq(actual, expected):
raise AssertionError, "Attribute '%s' was '%s', expected '%s'" \
% (name, actual, expected)
def check_attribute_not_set(self, name):
if hasattr(self, utils.normalize(name)):
raise AssertionError, "Attribute '%s' should not be set" % name
def backslashes(self, count=1):
return '\\' * int(count)
def read_and_log_file(self, path, binary=False):
mode = binary and 'rb' or 'r'
_file = open(path, mode)
print _file.read()
_file.close()
def print_control_chars(self):
print '\033[31mRED\033[m\033[32mGREEN\033[m'
def long_message(self, line_length, line_count, chars='a'):
line_length = int(line_length)
line_count = int(line_count)
msg = chars*line_length + '\n'
print msg*line_count
def loop_forever(self, no_print=False):
i = 0
while True:
i += 1
time.sleep(1)
if not no_print:
print 'Looping forever: %d' % i
def write_to_file_after_sleeping(self, path, sec, msg=None):
f = open(path, 'w')
time.sleep(int(sec))
if msg is None:
msg = 'Slept %s seconds' % sec
f.write(msg)
f.close()
def sleep_without_logging(self, timestr):
seconds = utils.timestr_to_secs(timestr)
time.sleep(seconds)
def return_custom_iterable(self, *values):
return _MyIterable(*values)
def return_list_subclass(self, *values):
return _MyList(values)
class _MyIterable(object):
def __init__(self, *values):
self._list = list(values)
def __iter__(self):
return iter(self._list)
class _MyList(list):
pass
| Python |
class Mandatory:
def __init__(self, mandatory1, mandatory2):
self.mandatory1 = mandatory1
self.mandatory2 = mandatory2
def get_args(self):
return self.mandatory1, self.mandatory2
class Defaults(object):
def __init__(self, mandatory, default1='value', default2=None):
self.mandatory = mandatory
self.default1 = default1
self.default2 = default2
def get_args(self):
return self.mandatory, self.default1, self.default2
class Varargs(Mandatory):
def __init__(self, mandatory, *varargs):
Mandatory.__init__(self, mandatory, ' '.join(str(a) for a in varargs))
class Mixed(Defaults):
def __init__(self, mandatory, default=42, *extra):
Defaults.__init__(self, mandatory, default,
' '.join(str(a) for a in extra))
| Python |
messages = [ u'Circle is 360\u00B0',
u'Hyv\u00E4\u00E4 \u00FC\u00F6t\u00E4',
u'\u0989\u09C4 \u09F0 \u09FA \u099F \u09EB \u09EA \u09B9' ]
class UnicodeLibrary:
def print_unicode_strings(self):
"""Prints message containing unicode characters"""
for msg in messages:
print '*INFO*' + msg
def print_and_return_unicode_object(self):
"""Prints unicode object and returns it."""
object = UnicodeObject()
print unicode(object)
return object
def raise_unicode_error(self):
raise AssertionError, ', '.join(messages)
class UnicodeObject:
def __init__(self):
self.message = u', '.join(messages)
def __str__(self):
return self.message
def __repr__(self):
return repr(self.message)
| Python |
from ExampleLibrary import ExampleLibrary
class ExtendPythonLib(ExampleLibrary):
def kw_in_python_extender(self, arg):
return arg/2
def print_many(self, *msgs):
raise Exception('Overridden kw executed!')
def using_method_from_python_parent(self):
self.exception('AssertionError', 'Error message from lib') | Python |
__version__ = 'N/A' # This should be ignored when version is parsed
class NameLibrary:
handler_count = 10
def simple1(self):
"""Simple 1"""
def simple2___(self):
"""Simple 2"""
def underscore_name(self):
"""Underscore Name"""
def underscore_name2_(self):
"""Underscore Name2"""
def un_der__sco_r__e_3(self):
"""Un Der Sco R E 3"""
def MiXeD_CAPS(self):
"""MiXeD CAPS"""
def camelCase(self):
"""Camel Case"""
def camelCase2(self):
"""Camel Case 2"""
def mixedCAPSCamel(self):
"""Mixed CAPS Camel"""
def camelCase_and_underscores_doesNot_work(self):
"""CamelCase And Underscores DoesNot Work"""
def _skipped1(self):
"""Starts with underscore"""
skipped2 = "Not a function"
class DocLibrary:
handler_count = 3
def no_doc(self): pass
no_doc.expected_doc = ''
no_doc.expected_shortdoc = ''
def one_line_doc(self):
"""One line doc"""
one_line_doc.expected_doc = 'One line doc'
one_line_doc.expected_shortdoc = 'One line doc'
def multiline_doc(self):
"""Multiline doc.
Spans multiple lines.
"""
multiline_doc.expected_doc = 'Multiline doc.\n\nSpans multiple lines.'
multiline_doc.expected_shortdoc = 'Multiline doc.'
class ArgInfoLibrary:
handler_count = 11
def no_args(self):
"""[], [], None"""
# Argument inspection had a bug when there was args on function body
# so better keep some of them around here.
a=b=c=1
def required1(self, one):
"""['one',], [], None"""
def required2(self, one, two):
"""['one','two'], [], None"""
def required9(self, one, two, three, four, five, six, seven, eight, nine):
"""['one','two','three','four','five','six','seven','eight','nine'],\
[], None"""
def default1(self, one=1):
"""['one'], [1], None"""
def default5(self, one='', two=None, three=3, four='huh', five=True):
"""['one','two','three','four','five'], ['',None,3,'huh',True], None"""
def required1_default1(self, one, two=''):
"""['one','two'], [''], None"""
def required2_default3(self, one, two, three=3, four=4, five=5):
"""['one','two','three','four','five'], [3,4,5], None"""
def varargs(self,*one):
"""[], [], 'one'"""
def required2_varargs(self, one, two, *three):
"""['one','two'], [], 'three'"""
def req4_def2_varargs(self, one, two, three, four, five=5, six=6, *seven):
"""['one','two','three','four','five','six'], [5,6], 'seven'"""
class GetattrLibrary:
handler_count = 3
keyword_names = ['foo','bar','zap']
def get_keyword_names(self):
return self.keyword_names
def __getattr__(self, name):
def handler(*args):
return name, args
if name not in self.keyword_names:
raise AttributeError
return handler
class SynonymLibrary:
handler_count = 3
def handler(self):
pass
synonym_handler = handler
another_synonym = handler
class VersionLibrary:
ROBOT_LIBRARY_VERSION = '0.1'
kw = lambda x:None
class VersionObjectLibrary:
class _Version:
def __init__(self, ver):
self._ver = ver
def __str__(self):
return self._ver
ROBOT_LIBRARY_VERSION = _Version('ver')
kw = lambda x:None
class RecordingLibrary:
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def __init__(self):
self.calls_to_getattr = 0
def kw(self):
pass
def __getattr__(self, name):
self.calls_to_getattr += 1
if name != 'kw':
raise AttributeError
return self.kw
class ArgDocDynamicLibrary:
def __init__(self):
kws = [('No Arg', []),
('One Arg', ['arg']),
('One or Two Args', ['arg', 'darg=dvalue']),
('Many Args', ['*args'])]
self._keywords = dict((name, _KeywordInfo(name, argspec))
for name, argspec in kws)
def get_keyword_names(self):
return sorted(self._keywords.keys())
def run_keyword(self, name, *args):
print '*INFO* Executed keyword %s with arguments %s' % (name, args)
def get_keyword_documentation(self, name):
return self._keywords[name].doc
def get_keyword_arguments(self, name):
return self._keywords[name].argspec
class _KeywordInfo:
doc_template = 'Keyword documentation for %s'
def __init__(self, name, argspec):
self.doc = self.doc_template % name
self.argspec = argspec
class InvalidGetDocDynamicLibrary(ArgDocDynamicLibrary):
def get_keyword_documentation(self, name, invalid_arg):
pass
class InvalidGetArgsDynamicLibrary(ArgDocDynamicLibrary):
def get_keyword_arguments(self, name):
1/0
class InvalidAttributeDynamicLibrary(ArgDocDynamicLibrary):
get_keyword_documentation = True
get_keyword_arguments = False
| Python |
class NewStyleClassLibrary(object):
def mirror(self, arg):
arg = list(arg)
arg.reverse()
return ''.join(arg)
def _property_getter(self):
raise SystemExit('This should not be called, ever!!!')
prop = property(_property_getter)
class NewStyleClassArgsLibrary(object):
def __init__(self, param):
self.get_param = lambda self: param
class _MyMetaClass(type):
def __new__(cls, name, bases, ns):
ns['kw_created_by_metaclass'] = lambda self, arg: arg.upper()
return type.__new__(cls, name, bases, ns)
def method_in_metaclass(cls):
pass
class MetaClassLibrary(object):
__metaclass__ = _MyMetaClass
def greet(self, name):
return 'Hello %s!' % name
| Python |
class LibClass1:
def verify_libclass1(self):
return 'LibClass 1 works'
class LibClass2:
def verify_libclass2(self):
return 'LibClass 2 works also'
| Python |
class FatalCatastrophyException(RuntimeError):
ROBOT_EXIT_ON_FAILURE = True
class ContinuableApocalypseException(RuntimeError):
ROBOT_CONTINUE_ON_FAILURE = True
def exit_on_failure():
raise FatalCatastrophyException()
def raise_continuable_failure(msg='Can be continued'):
raise ContinuableApocalypseException(msg)
| Python |
ROBOT_LIBRARY_SCOPE = 'Test Suite' # this should be ignored
__version__ = 'test' # this should be used as version of this library
def passing():
pass
def failing():
raise AssertionError('This is a failing keyword from module library')
def logging():
print 'Hello from module library'
print '*WARN* WARNING!'
def returning():
return 'Hello from module library'
def argument(arg):
assert arg == 'Hello', "Expected 'Hello', got '%s'" % arg
def many_arguments(arg1, arg2, arg3):
assert arg1 == arg2 == arg3, ("All arguments should have been equal, got: "
"%s, %s and %s") % (arg1, arg2, arg3)
def default_arguments(arg1, arg2='Hi', arg3='Hello'):
many_arguments(arg1, arg2, arg3)
def variable_arguments(*args):
return sum([int(arg) for arg in args])
attribute = 'This is not a keyword!'
class NotLibrary:
def two_arguments(self, arg1, arg2):
msg = "Arguments should have been unequal, both were '%s'" % arg1
assert arg1 != arg2, msg
def not_keyword(self):
pass
notlib = NotLibrary()
two_arguments_from_class = notlib.two_arguments
lambda_keyword = lambda arg: int(arg) + 1
lambda_keyword_with_two_args = lambda x, y: int(x) / int(y)
def _not_keyword():
pass
def module_library():
return "It should be OK to have an attribute with same name as the module"
| Python |
class _BaseLib:
def __init__(self):
self.registered = {}
def register(self, name):
self.registered[name] = None
def should_be_registered(self, *expected):
exp = dict([ (name, None) for name in expected ])
if self.registered != exp:
raise AssertionError, 'Wrong registered: %s != %s' \
% (self.registered.keys(), exp.keys())
class Global(_BaseLib):
ROBOT_LIBRARY_SCOPE = 'global'
count = 0
def __init__(self):
Global.count += 1
_BaseLib.__init__(self)
def should_be_registered(self, *expected):
if self.count != 1:
raise AssertionError("Global library initialized more than once.")
_BaseLib.should_be_registered(self, *expected)
class Suite(_BaseLib):
ROBOT_LIBRARY_SCOPE = 'TEST_SUITE'
class Test(_BaseLib):
ROBOT_LIBRARY_SCOPE = 'TeSt CAse'
class InvalidValue(_BaseLib):
ROBOT_LIBRARY_SCOPE = 'invalid'
class InvalidEmpty(_BaseLib):
pass
class InvalidMethod(_BaseLib):
def ROBOT_LIBRARY_SCOPE(self):
pass
class InvalidNone(_BaseLib):
ROBOT_LIBRARY_SCOPE = None
| Python |
import os
import re
from robot import utils
from robot.output import readers
from robot.common import Statistics
from robot.libraries.BuiltIn import BuiltIn
class TestCheckerLibrary:
def process_output(self, path):
path = path.replace('/', os.sep)
try:
print "Processing output '%s'" % path
suite, errors = readers.process_output(path)
except:
raise RuntimeError('Processing output failed: %s'
% utils.get_error_message())
setter = BuiltIn().set_suite_variable
setter('$SUITE', process_suite(suite))
setter('$STATISTICS', Statistics(suite))
setter('$ERRORS', process_errors(errors))
def get_test_from_suite(self, suite, name):
tests = self.get_tests_from_suite(suite, name)
if len(tests) == 1:
return tests[0]
elif len(tests) == 0:
err = "No test '%s' found from suite '%s'"
else:
err = "More than one test '%s' found from suite '%s'"
raise RuntimeError(err % (name, suite.name))
def get_tests_from_suite(self, suite, name=None):
tests = [ test for test in suite.tests
if name is None or utils.eq(test.name, name) ]
for subsuite in suite.suites:
tests.extend(self.get_tests_from_suite(subsuite, name))
return tests
def get_suite_from_suite(self, suite, name):
suites = self.get_suites_from_suite(suite, name)
if len(suites) == 1:
return suites[0]
elif len(suites) == 0:
err = "No suite '%s' found from suite '%s'"
else:
err = "More than one suite '%s' found from suite '%s'"
raise RuntimeError(err % (name, suite.name))
def get_suites_from_suite(self, suite, name):
suites = utils.eq(suite.name, name) and [ suite ] or []
for subsuite in suite.suites:
suites.extend(self.get_suites_from_suite(subsuite, name))
return suites
def check_test_status(self, test, status=None, message=None):
"""Verifies that test's status and message are as expected.
Expected status and message can be given as parameters. If expected
status is not given, expected status and message are read from test's
documentation. If documentation doesn't contain any of PASS, FAIL or
ERROR, test's status is expected to be PASS. If status is given that is
used. Expected message is documentation after given status. Expected
message can also be regular expression. In that case expected match
starts with REGEXP: , which is ignored in the regexp match.
"""
if status is not None:
test.exp_status = status
if message is not None:
test.exp_message = message
if test.exp_status != test.status:
if test.exp_status == 'PASS':
msg = "Test was expected to PASS but it FAILED. "
msg += "Error message:\n" + test.message
else:
msg = "Test was expected to FAIL but it PASSED. "
msg += "Expected message:\n" + test.exp_message
raise AssertionError(msg)
if test.exp_message == test.message:
return
if test.exp_message.startswith('REGEXP:'):
pattern = test.exp_message.replace('REGEXP:', '', 1).strip()
if re.match('^%s$' % pattern, test.message, re.DOTALL):
return
if test.exp_message.startswith('STARTS:'):
start = test.exp_message.replace('STARTS:', '', 1).strip()
if start == '':
raise RuntimeError("Empty 'STARTS:' is not allowed")
if test.message.startswith(start):
return
raise AssertionError("Wrong message\n\n"
"Expected:\n%s\n\nActual:\n%s\n"
% (test.exp_message, test.message))
def check_suite_contains_tests(self, suite, *expected_names):
actual_tests = [ test for test in self.get_tests_from_suite(suite) ]
tests_msg = """
Expected tests : %s
Actual tests : %s""" % (str(list(expected_names)), str(actual_tests))
expected_names = [ utils.normalize(name) for name in expected_names ]
if len(actual_tests) != len(expected_names):
raise AssertionError("Wrong number of tests." + tests_msg)
for test in actual_tests:
if utils.eq_any(test.name, expected_names):
print "Verifying test '%s'" % test.name
self.check_test_status(test)
expected_names.remove(utils.normalize(test.name))
else:
raise AssertionError("Test '%s' was not expected to be run.%s"
% (test.name, tests_msg))
if len(expected_names) != 0:
raise Exception("Bug in test library")
def get_node(self, file_path, node_path=None):
dom = utils.DomWrapper(file_path)
return dom.get_node(node_path) if node_path else dom
def get_nodes(self, file_path, node_path):
return utils.DomWrapper(file_path).get_nodes(node_path)
def process_suite(suite):
for subsuite in suite.suites:
process_suite(subsuite)
for test in suite.tests:
process_test(test)
suite.test_count = suite.get_test_count()
process_keyword(suite.setup)
process_keyword(suite.teardown)
return suite
def process_test(test):
if 'FAIL' in test.doc:
test.exp_status = 'FAIL'
test.exp_message = test.doc.split('FAIL', 1)[1].lstrip()
else:
test.exp_status = 'PASS'
test.exp_message = ''
test.kws = test.keywords
test.keyword_count = test.kw_count = len(test.keywords)
for kw in test.keywords:
process_keyword(kw)
process_keyword(test.setup)
process_keyword(test.teardown)
def process_keyword(kw):
if kw is None:
return
kw.kws = kw.keywords
kw.msgs = kw.messages
kw.message_count = kw.msg_count = len(kw.messages)
kw.keyword_count = kw.kw_count = len(kw.keywords)
for subkw in kw.keywords:
process_keyword(subkw)
def process_errors(errors):
errors.msgs = errors.messages
errors.message_count = errors.msg_count = len(errors.messages)
return errors
| Python |
import os.path
import robot
import tempfile
__all__ = ['robotpath', 'javatempdir', 'robotversion']
robotpath = os.path.abspath(os.path.dirname(robot.__file__))
javatempdir = tempfile.gettempdir() # Used to be different on OSX and elsewhere
robotversion = robot.version.get_version()
| Python |
message_list = [ u'Circle is 360\u00B0',
u'Hyv\u00E4\u00E4 \u00FC\u00F6t\u00E4',
u'\u0989\u09C4 \u09F0 \u09FA \u099F \u09EB \u09EA \u09B9' ]
message1 = message_list[0]
message2 = message_list[1]
message3 = message_list[2]
messages = ', '.join(message_list)
sect = unichr(167)
auml = unichr(228)
ouml = unichr(246)
uuml = unichr(252)
yuml = unichr(255)
| Python |
from xml.dom.minidom import parse
def parse_xunit(path):
return parse(path)
def get_root_element_name(dom):
return dom.documentElement.tagName
def get_element_count_by_name(dom, name):
return len(get_elements_by_name(dom, name))
def get_elements_by_name(dom, name):
return dom.getElementsByTagName(name) | Python |
import os
import sys
from stat import S_IREAD, S_IWRITE
class TestHelper:
def set_read_only(self, path):
os.chmod(path, S_IREAD)
def set_read_write(self, path):
os.chmod(path, S_IREAD | S_IWRITE)
def get_output_name(self, *datasources):
if not datasources:
raise RuntimeError('One or more data sources must be given!')
if len(datasources) == 1:
return self._get_name(datasources[0])
return '_'.join(self._get_name(source) for source in datasources)
def _get_name(self, path):
return os.path.splitext(os.path.basename(path))[0]
def should_contain_item_x_times(self, string, item, count):
if string.count(item) != int(count):
raise AssertionError("'%s' does not contain '%s' '%s' "
"times!" % (string, item, count))
def get_splitted_full_name(self, full_name, splitlevel):
splitlevel = int(splitlevel)
parts = full_name.split('.')
if splitlevel > 0 and splitlevel <= len(parts):
parts = parts[splitlevel:]
return '.'.join(parts)
def running_on_jython(self, interpreter):
return 'jython' in interpreter
def running_on_python(self, interpreter):
return not self.running_on_jython(interpreter)
def running_on_linux(self):
return 'linux' in sys.platform | Python |
#!/usr/bin/env python
"""Script to generate atest runners based on data files.
Usage: %s path/to/data.file
"""
from __future__ import with_statement
import sys, os
if len(sys.argv) != 2:
print __doc__ % os.path.basename(sys.argv[0])
sys.exit(1)
inpath = os.path.abspath(sys.argv[1])
outpath = inpath.replace(os.path.join('atest', 'testdata'),
os.path.join('atest', 'robot'))
dirname = os.path.dirname(outpath)
if not os.path.exists(dirname):
os.mkdir(dirname)
with open(inpath) as input:
tests = []
process = False
for line in input.readlines():
line = line.rstrip()
if line.startswith('*'):
name = line.replace('*', '').replace(' ', '').upper()
process = name in ('TESTCASE', 'TESTCASES')
elif process and line and line[0] != ' ':
tests.append(line.split(' ')[0])
with open(outpath, 'w') as output:
path = inpath.split(os.path.join('atest', 'testdata'))[1][1:]
output.write("""*** Settings ***
Suite Setup Run Tests ${EMPTY} %s
Force Tags regression pybot jybot
Resource atest_resource.txt
*** Test Cases ***
""" % path.replace(os.sep, '/'))
for test in tests:
output.write(test + '\n Check Test Case ${TESTNAME}\n\n')
print outpath
| 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 ExecutionFailed, DataError
from keywords import Keyword
class _Fixture(object):
def __init__(self, name, args):
self.name = name or ''
self.args = args
self._keyword = None
def replace_variables(self, variables, errors):
if self.name:
try:
self.name = variables.replace_string(self.name)
except DataError, err:
errors.append('Replacing variables from %s failed: %s'
% (self.__class__.__name__, unicode(err)))
if self.name.upper() != 'NONE':
self._keyword = Keyword(self.name, self.args,
type=type(self).__name__.lower())
def run(self, context, error_listener):
if self._keyword:
try:
self._keyword.run(context)
except ExecutionFailed, err:
error_listener.notify(err)
def serialize(self, serializer):
if self._keyword:
serializer.start_keyword(self._keyword)
serializer.end_keyword(self._keyword)
class Setup(_Fixture): pass
class Teardown(_Fixture): pass
class SuiteTearDownListener(object):
def __init__(self, suite):
self._suite = suite
def notify(self, error):
self._suite.suite_teardown_failed('Suite teardown failed:\n%s'
% unicode(error))
class SuiteSetupListener(object):
def __init__(self, suite):
self._suite = suite
def notify(self, error):
self._suite.run_errors.suite_setup_err(error)
class _TestListener(object):
def __init__(self, test):
self._test = test
def notify(self, error):
self._test.keyword_failed(error)
self._notify_run_errors(error)
class TestSetupListener(_TestListener):
def _notify_run_errors(self, error):
self._test.run_errors.setup_err(unicode(error))
class TestTeardownListener(_TestListener):
def _notify_run_errors(self, error):
self._test.run_errors.teardown_err(unicode(error))
class KeywordTeardownListener(object):
def __init__(self, run_errors):
self._run_errors = run_errors
def notify(self, error):
self._run_errors.teardown_err(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.
import inspect
import sys
from robot import utils
from robot.errors import DataError
from outputcapture import OutputCapturer
from runkwregister import RUN_KW_REGISTER
from keywords import Keywords, Keyword
from arguments import (PythonKeywordArguments, JavaKeywordArguments,
DynamicKeywordArguments, RunKeywordArguments,
PythonInitArguments, JavaInitArguments)
from signalhandler import STOP_SIGNAL_MONITOR
if utils.is_jython:
from org.python.core import PyReflectedFunction, PyReflectedConstructor
def _is_java_init(init):
return isinstance(init, PyReflectedConstructor)
def _is_java_method(method):
return hasattr(method, 'im_func') \
and isinstance(method.im_func, PyReflectedFunction)
else:
_is_java_init = _is_java_method = lambda item: False
def Handler(library, name, method):
if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name):
return _RunKeywordHandler(library, name, method)
if _is_java_method(method):
return _JavaHandler(library, name, method)
else:
return _PythonHandler(library, name, method)
def DynamicHandler(library, name, method, doc, argspec):
if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name):
return _DynamicRunKeywordHandler(library, name, method, doc, argspec)
return _DynamicHandler(library, name, method, doc, argspec)
def InitHandler(library, method):
if method is None:
method = lambda: None
Init = _PythonInitHandler if not _is_java_init(method) else _JavaInitHandler
return Init(library, '__init__', method)
class _BaseHandler(object):
type = 'library'
doc = ''
def __init__(self, library, handler_name, handler_method):
self.library = library
self.name = utils.printable_name(handler_name, code_style=True)
self.arguments = self._parse_arguments(handler_method)
def _parse_arguments(self, handler_method):
raise NotImplementedError(self.__class__.__name__)
@property
def longname(self):
return '%s.%s' % (self.library.name, self.name)
@property
def shortdoc(self):
return self.doc.splitlines()[0] if self.doc else ''
class _RunnableHandler(_BaseHandler):
def __init__(self, library, handler_name, handler_method):
_BaseHandler.__init__(self, library, handler_name, handler_method)
self._handler_name = handler_name
self._method = self._get_initial_handler(library, handler_name,
handler_method)
def _get_initial_handler(self, library, name, method):
if library.scope == 'GLOBAL':
return self._get_global_handler(method, name)
return None
def init_keyword(self, varz):
pass
def run(self, context, args):
if context.dry_run:
return self._dry_run(context, args)
return self._run(context, args)
def _dry_run(self, context, args):
self.arguments.check_arg_limits_for_dry_run(args)
return None
def _run(self, context, args):
output = context.output
positional, named = \
self.arguments.resolve(args, context.get_current_vars(), output)
runner = self._runner_for(self._current_handler(), output, positional,
named, self._get_timeout(context.namespace))
return self._run_with_output_captured_and_signal_monitor(runner, context)
def _runner_for(self, handler, output, positional, named, timeout):
if timeout and timeout.active:
output.debug(timeout.get_message())
return lambda: timeout.run(handler, args=positional, kwargs=named)
return lambda: handler(*positional, **named)
def _run_with_output_captured_and_signal_monitor(self, runner, context):
capturer = OutputCapturer()
try:
return self._run_with_signal_monitoring(runner, context)
finally:
stdout, stderr = capturer.release()
context.output.log_output(stdout)
context.output.log_output(stderr)
if stderr:
sys.__stderr__.write(stderr+'\n')
def _run_with_signal_monitoring(self, runner, context):
try:
STOP_SIGNAL_MONITOR.start_running_keyword(context.teardown)
return runner()
finally:
STOP_SIGNAL_MONITOR.stop_running_keyword()
def _current_handler(self):
if self._method:
return self._method
return self._get_handler(self.library.get_instance(),
self._handler_name)
def _get_global_handler(self, method, name):
return method
def _get_handler(self, lib_instance, handler_name):
return getattr(lib_instance, handler_name)
def _get_timeout(self, namespace):
timeoutable = self._get_timeoutable_items(namespace)
if timeoutable:
return min(item.timeout for item in timeoutable)
return None
def _get_timeoutable_items(self, namespace):
items = namespace.uk_handlers[:]
if self._test_running_and_not_in_teardown(namespace.test):
items.append(namespace.test)
return items
def _test_running_and_not_in_teardown(self, test):
return test and test.status == 'RUNNING'
class _PythonHandler(_RunnableHandler):
def __init__(self, library, handler_name, handler_method):
_RunnableHandler.__init__(self, library, handler_name, handler_method)
self.doc = inspect.getdoc(handler_method) or ''
def _parse_arguments(self, handler_method):
return PythonKeywordArguments(handler_method, self.longname)
class _JavaHandler(_RunnableHandler):
def _parse_arguments(self, handler_method):
return JavaKeywordArguments(handler_method, self.longname)
class _DynamicHandler(_RunnableHandler):
def __init__(self, library, handler_name, handler_method, doc='',
argspec=None):
self._argspec = argspec
_RunnableHandler.__init__(self, library, handler_name, handler_method)
self._run_keyword_method_name = handler_method.__name__
self.doc = doc is not None and utils.unic(doc) or ''
def _parse_arguments(self, handler_method):
return DynamicKeywordArguments(self._argspec, self.longname)
def _get_handler(self, lib_instance, handler_name):
runner = getattr(lib_instance, self._run_keyword_method_name)
return self._get_dynamic_handler(runner, handler_name)
def _get_global_handler(self, method, name):
return self._get_dynamic_handler(method, name)
def _get_dynamic_handler(self, runner, name):
def handler(*args):
return runner(name, list(args))
return handler
class _RunKeywordHandler(_PythonHandler):
def __init__(self, library, handler_name, handler_method):
_PythonHandler.__init__(self, library, handler_name, handler_method)
self._handler_method = handler_method
def _run_with_signal_monitoring(self, runner, context):
# With run keyword variants, only the keyword to be run can fail
# and therefore monitoring should not raise exception yet.
return runner()
def _parse_arguments(self, handler_method):
arg_index = RUN_KW_REGISTER.get_args_to_process(self.library.orig_name,
self.name)
return RunKeywordArguments(handler_method, self.longname, arg_index)
def _get_timeout(self, namespace):
return None
def _dry_run(self, context, args):
_RunnableHandler._dry_run(self, context, args)
keywords = self._get_runnable_keywords(context, args)
keywords.run(context)
def _get_runnable_keywords(self, context, args):
keywords = Keywords([])
for keyword in self._get_keywords(args):
if self._variable_syntax_in(keyword.name, context):
continue
keywords.add_keyword(keyword)
return keywords
def _get_keywords(self, args):
arg_names = self.arguments.names
if 'name' in arg_names:
name_index = arg_names.index('name')
return [ Keyword(args[name_index], args[name_index+1:]) ]
elif self.arguments.varargs == 'names':
return [ Keyword(name, []) for name in args[len(arg_names):] ]
return []
def _variable_syntax_in(self, kw_name, context):
try:
resolved = context.namespace.variables.replace_string(kw_name)
#Variable can contain value, but it might be wrong,
#therefore it cannot be returned
return resolved != kw_name
except DataError:
return True
class _XTimesHandler(_RunKeywordHandler):
def __init__(self, handler, name):
_RunKeywordHandler.__init__(self, handler.library, handler.name,
handler._handler_method)
self.name = name
self.doc = "*DEPRECATED* Replace X times syntax with 'Repeat Keyword'."
def run(self, context, args):
resolved_times = context.namespace.variables.replace_string(self.name)
_RunnableHandler.run(self, context, [resolved_times] + args)
@property
def longname(self):
return self.name
class _DynamicRunKeywordHandler(_DynamicHandler, _RunKeywordHandler):
_parse_arguments = _RunKeywordHandler._parse_arguments
_get_timeout = _RunKeywordHandler._get_timeout
class _PythonInitHandler(_PythonHandler):
def _parse_arguments(self, handler_method):
return PythonInitArguments(handler_method, self.library.name)
class _JavaInitHandler(_BaseHandler):
def _parse_arguments(self, handler_method):
return JavaInitArguments(handler_method, self.library.name)
| 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 SuiteRunErrors(object):
_NO_ERROR = None
_exit_on_failure_error = ('Critical failure occurred and ExitOnFailure '
'option is in use')
_exit_on_fatal_error = 'Test execution is stopped due to a fatal error'
_parent_suite_init_error = 'Initialization of the parent suite failed.'
_parent_suite_setup_error = 'Setup of the parent suite failed.'
def __init__(self, run_mode_is_exit_on_failure=False, run_mode_skip_teardowns_on_exit=False):
self._run_mode_is_exit_on_failure = run_mode_is_exit_on_failure
self._run_mode_skip_teardowns_on_exit = run_mode_skip_teardowns_on_exit
self._earlier_init_errors = []
self._earlier_setup_errors = []
self._earlier_suite_setup_executions = []
self._init_current_errors()
self._exit_runmode = self._exit_fatal = False
self._current_suite_setup_executed = False
@property
def exit(self):
return self._exit_fatal or self._exit_runmode
def _init_current_errors(self):
self._current_init_err = self._current_setup_err = self._NO_ERROR
def start_suite(self):
self._earlier_init_errors.append(self._current_init_err)
self._earlier_setup_errors.append(self._current_setup_err)
self._earlier_suite_setup_executions.append(self._current_suite_setup_executed)
self._init_current_errors()
self._current_suite_setup_executed = False
def end_suite(self):
self._current_setup_err = self._earlier_setup_errors.pop()
self._current_init_err = self._earlier_init_errors.pop()
self._current_suite_setup_executed = self._earlier_suite_setup_executions.pop()
def is_suite_setup_allowed(self):
return self._current_init_err is self._NO_ERROR and \
not self._earlier_errors()
def is_suite_teardown_allowed(self):
if not self.is_test_teardown_allowed():
return False
if self._current_suite_setup_executed:
return True
return self._current_init_err is self._NO_ERROR and \
not self._earlier_errors()
def is_test_teardown_allowed(self):
if not self._run_mode_skip_teardowns_on_exit:
return True
return not (self._exit_fatal or self._exit_runmode)
def _earlier_errors(self):
if self._exit_runmode or self._exit_fatal:
return True
for err in self._earlier_setup_errors + self._earlier_init_errors:
if err is not self._NO_ERROR:
return True
return False
def suite_init_err(self, error_message):
self._current_init_err = error_message
def setup_executed(self):
self._current_suite_setup_executed = True
def suite_setup_err(self, err):
if err.exit:
self._exit_fatal = True
self._current_setup_err = unicode(err)
def suite_error(self):
if self._earlier_init_erros_occurred():
return self._parent_suite_init_error
if self._earlier_setup_errors_occurred():
return self._parent_suite_setup_error
if self._current_init_err:
return self._current_init_err
if self._current_setup_err:
return 'Suite setup failed:\n%s' % self._current_setup_err
return ''
def _earlier_init_erros_occurred(self):
return any(self._earlier_init_errors)
def _earlier_setup_errors_occurred(self):
return any(self._earlier_setup_errors)
def child_error(self):
if self._current_init_err or self._earlier_init_erros_occurred():
return self._parent_suite_init_error
if self._current_setup_err or self._earlier_setup_errors_occurred():
return self._parent_suite_setup_error
if self._exit_runmode:
return self._exit_on_failure_error
if self._exit_fatal:
return self._exit_on_fatal_error
return None
def test_failed(self, exit=False, critical=False):
if critical and self._run_mode_is_exit_on_failure:
self._exit_runmode = True
if exit:
self._exit_fatal = True
class TestRunErrors(object):
def __init__(self, err):
self._parent_err = err.child_error() if err else None
self._init_err = None
self._setup_err = None
self._kw_err = None
self._teardown_err = None
def is_allowed_to_run(self):
return not bool(self._parent_err or self._init_err)
def init_err(self, err):
self._init_err = err
def setup_err(self, err):
self._setup_err = err
def setup_failed(self):
return bool(self._setup_err)
def kw_err(self, error):
self._kw_err = error
def teardown_err(self, err):
self._teardown_err = err
def teardown_failed(self):
return bool(self._teardown_err)
def get_message(self):
if self._setup_err:
return 'Setup failed:\n%s' % self._setup_err
return self._kw_err
def get_teardown_message(self, message):
# TODO: This API is really in need of cleanup
if message == '':
return 'Teardown failed:\n%s' % self._teardown_err
return '%s\n\nAlso teardown failed:\n%s' % (message, self._teardown_err)
def parent_or_init_error(self):
return self._parent_err or self._init_err
class KeywordRunErrors(object):
def __init__(self):
self.teardown_error = None
def get_message(self):
if not self._teardown_err:
return self._kw_err
if not self._kw_err:
return 'Keyword teardown failed:\n%s' % self._teardown_err
return '%s\n\nAlso keyword teardown failed:\n%s' % (self._kw_err,
self._teardown_err)
def teardown_err(self, err):
self.teardown_error = err
| 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.common import BaseTestSuite, BaseTestCase
from robot.parsing import TestCaseFile, TestDataDirectory
from robot.errors import ExecutionFailed, DataError
from robot.variables import GLOBAL_VARIABLES
from robot.output import LOGGER
from fixture import (Setup, Teardown, SuiteSetupListener, SuiteTearDownListener,
TestSetupListener, TestTeardownListener)
from keywords import Keywords
from namespace import Namespace
from runerrors import SuiteRunErrors, TestRunErrors
from userkeyword import UserLibrary
from context import ExecutionContext
from defaultvalues import DefaultValues
def TestSuite(datasources, settings):
datasources = [utils.abspath(path) for path in datasources]
suite = _get_suite(datasources, settings['SuiteNames'], settings['WarnOnSkipped'])
suite.set_options(settings)
_check_suite_contains_tests(suite, settings['RunEmptySuite'])
return suite
def _get_suite(datasources, include_suites, warn_on_skipped):
if not datasources:
raise DataError("No data sources given.")
if len(datasources) > 1:
return _get_multisource_suite(datasources, include_suites, warn_on_skipped)
return RunnableTestSuite(_parse_suite(datasources[0], include_suites, warn_on_skipped))
def _parse_suite(path, include_suites, warn_on_skipped):
try:
if os.path.isdir(path):
return TestDataDirectory(source=path, include_suites=include_suites, warn_on_skipped=warn_on_skipped)
return TestCaseFile(source=path)
except DataError, err:
raise DataError("Parsing '%s' failed: %s" % (path, unicode(err)))
def _get_multisource_suite(datasources, include_suites, warn_on_skipped):
suitedatas = []
for datasource in datasources:
try:
suitedatas.append(_parse_suite(datasource, include_suites, warn_on_skipped))
except DataError, err:
LOGGER.info(err)
suite = RunnableMultiTestSuite(suitedatas)
if suite.get_test_count() == 0:
raise DataError("Data sources %s contain no test cases."
% utils.seq2str(datasources))
return suite
def _check_suite_contains_tests(suite, run_empty_suites=False):
suite.filter_empty_suites()
if not suite.get_test_count() and not run_empty_suites:
raise DataError("Test suite '%s' contains no test cases." % (suite.source))
class RunnableTestSuite(BaseTestSuite):
def __init__(self, data, parent=None, defaults=None):
BaseTestSuite.__init__(self, data.name, data.source, parent)
self.variables = GLOBAL_VARIABLES.copy()
self.variables.set_from_variable_table(data.variable_table)
self.source = data.source
self.doc = data.setting_table.doc.value
self.metadata = self._get_metadata(data.setting_table.metadata)
self.imports = data.imports
self.user_keywords = UserLibrary(data.keywords)
self.setup = Setup(data.setting_table.suite_setup.name,
data.setting_table.suite_setup.args)
self.teardown = Teardown(data.setting_table.suite_teardown.name,
data.setting_table.suite_teardown.args)
defaults = DefaultValues(data.setting_table, defaults)
for suite in data.children:
RunnableTestSuite(suite, parent=self, defaults=defaults)
for test in data.testcase_table:
RunnableTestCase(test, parent=self, defaults=defaults)
self._run_mode_exit_on_failure = False
self._run_mode_dry_run = False
self._run_mode_skip_teardowns_on_exit = False
def filter_empty_suites(self):
for suite in self.suites[:]:
suite.filter_empty_suites()
if suite.get_test_count() == 0:
self.suites.remove(suite)
LOGGER.info("Running test suite '%s' failed: Test suite"
" contains no test cases." % (suite.source))
def _get_metadata(self, metadata):
meta = utils.NormalizedDict()
for item in metadata:
meta[item.name] = item.value
return meta
def run(self, output, parent=None, errors=None):
context = self._start_run(output, parent, errors)
self._run_setup(context)
self._run_sub_suites(context)
self._run_tests(context)
self._report_status(context)
self._run_teardown(context)
self._end_run(context)
def _start_run(self, output, parent, errors):
if not errors:
errors = SuiteRunErrors(self._run_mode_exit_on_failure, self._run_mode_skip_teardowns_on_exit)
self.run_errors = errors
self.run_errors.start_suite()
self.status = 'RUNNING'
self.starttime = utils.get_timestamp()
parent_vars = parent.context.get_current_vars() if parent else None
ns = Namespace(self, parent_vars, skip_imports=errors.exit)
self.context = ExecutionContext(ns, output, self._run_mode_dry_run)
self._set_variable_dependent_metadata(self.context)
output.start_suite(self)
return self.context
def _set_variable_dependent_metadata(self, context):
errors = []
self.doc = context.replace_vars_from_setting('Documentation', self.doc,
errors)
self.setup.replace_variables(context.get_current_vars(), errors)
self.teardown.replace_variables(context.get_current_vars(), errors)
for name, value in self.metadata.items():
self.metadata[name] = context.replace_vars_from_setting(name, value,
errors)
if errors:
self.run_errors.suite_init_err('Suite initialization failed:\n%s'
% '\n'.join(errors))
def _run_setup(self, context):
if self.run_errors.is_suite_setup_allowed():
self.setup.run(context, SuiteSetupListener(self))
self.run_errors.setup_executed()
def _run_teardown(self, context):
if self.run_errors.is_suite_teardown_allowed():
self.teardown.run(context, SuiteTearDownListener(self))
def _run_sub_suites(self, context):
for suite in self.suites:
suite.run(context.output, self, self.run_errors)
def _run_tests(self, context):
executed_tests = []
for test in self.tests:
normname = utils.normalize(test.name)
if normname in executed_tests:
LOGGER.warn("Multiple test cases with name '%s' executed in "
"test suite '%s'"% (test.name, self.longname))
executed_tests.append(normname)
test.run(context, self.run_errors)
context.set_prev_test_variables(test)
def _report_status(self, context):
self.set_status()
self.message = self.run_errors.suite_error()
context.report_suite_status(self.status, self.get_full_message())
def _end_run(self, context):
self.endtime = utils.get_timestamp()
self.elapsedtime = utils.get_elapsed_time(self.starttime, self.endtime)
context.copy_prev_test_vars_to_global()
context.end_suite(self)
self.run_errors.end_suite()
class RunnableMultiTestSuite(RunnableTestSuite):
def __init__(self, suitedatas):
BaseTestSuite.__init__(self, name='')
self.variables = GLOBAL_VARIABLES.copy()
self.doc = ''
self.imports = []
self.setup = Setup(None, None)
self.teardown = Teardown(None, None)
for suite in suitedatas:
RunnableTestSuite(suite, parent=self)
self._run_mode_exit_on_failure = False
self._run_mode_dry_run = False
self._run_mode_skip_teardowns_on_exit = False
class RunnableTestCase(BaseTestCase):
def __init__(self, tc_data, parent, defaults):
BaseTestCase.__init__(self, tc_data.name, parent)
self.doc = tc_data.doc.value
self.setup = defaults.get_setup(tc_data.setup)
self.teardown = defaults.get_teardown(tc_data.teardown)
self.tags = defaults.get_tags(tc_data.tags)
self.timeout = defaults.get_timeout(tc_data.timeout)
template = defaults.get_template(tc_data.template)
self.keywords = Keywords(tc_data.steps, template)
def run(self, context, suite_errors):
self._suite_errors = suite_errors
self._start_run(context)
if self.run_errors.is_allowed_to_run():
self._run(context)
else:
self._not_allowed_to_run()
self._end_run(context)
def _start_run(self, context):
self.run_errors = TestRunErrors(self._suite_errors)
self.status = 'RUNNING'
self.starttime = utils.get_timestamp()
self.run_errors.init_err(self._init_test(context))
context.start_test(self)
def _init_test(self, context):
errors = []
self.doc = context.replace_vars_from_setting('Documentation', self.doc,
errors)
self.setup.replace_variables(context.get_current_vars(), errors)
self.teardown.replace_variables(context.get_current_vars(), errors)
tags = context.replace_vars_from_setting('Tags', self.tags, errors)
self.tags = utils.normalize_tags(t for t in tags if t.upper() != 'NONE')
self.timeout.replace_variables(context.get_current_vars())
if errors:
return 'Test case initialization failed:\n%s' % '\n'.join(errors)
if not self.name:
return 'Test case name is required.'
if not self.keywords:
return 'Test case contains no keywords'
return None
def _run(self, context):
self.timeout.start()
self._run_setup(context)
if not self.run_errors.setup_failed():
try:
self.keywords.run(context)
except ExecutionFailed, err:
self.run_errors.kw_err(unicode(err))
self.keyword_failed(err)
context.set_test_status_before_teardown(*self._report_status())
self._run_teardown(context)
self._report_status_after_teardown()
def keyword_failed(self, err):
self.timeout.set_keyword_timeout(err.timeout)
self._suite_errors.test_failed(exit=err.exit, critical=self.critical=='yes')
def _run_setup(self, context):
self.setup.run(context, TestSetupListener(self))
def _report_status(self):
message = self.run_errors.get_message()
if message:
self.status = 'FAIL'
self.message = message
else:
self.status = 'PASS'
return self.message, self.status
def _run_teardown(self, context):
if self._suite_errors.is_test_teardown_allowed():
self.teardown.run(context, TestTeardownListener(self))
def _report_status_after_teardown(self):
if self.run_errors.teardown_failed():
self.status = 'FAIL'
self.message = self.run_errors.get_teardown_message(self.message)
if self.status == 'PASS' and self.timeout.timed_out():
self.status = 'FAIL'
self.message = self.timeout.get_message()
if self.status == 'FAIL':
self._suite_errors.test_failed(critical=self.critical=='yes')
def _not_allowed_to_run(self):
self.status = 'FAIL'
self.message = self.run_errors.parent_or_init_error()
def _end_run(self, context):
self.endtime = utils.get_timestamp()
self.elapsedtime = utils.get_elapsed_time(self.starttime, self.endtime)
context.end_test(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 sys
from StringIO import StringIO
class OutputCapturer:
def __init__(self):
self._python_out = _PythonCapturer(stdout=True)
self._python_err = _PythonCapturer(stdout=False)
self._java_out = _JavaCapturer(stdout=True)
self._java_err = _JavaCapturer(stdout=False)
def release(self):
py_out = self._python_out.release()
py_err = self._python_err.release()
java_out = self._java_out.release()
java_err = self._java_err.release()
# FIXME: Should return both Python and Java stdout/stderr.
# It is unfortunately not possible to do py_out+java_out here, because
# java_out is always Unicode and py_out is bytes (=str). When py_out
# contains non-ASCII bytes catenation fails with UnicodeError.
# Unfortunately utils.unic(py_out) doesn't work either, because later
# splitting the output to levels and messages fails. Should investigate
# why that happens. It also seems that the byte message are never
# converted to Unicode - at least Message class doesn't do that.
# It's probably safe to leave this code like it is in RF 2.5, because
# a) the earlier versions worked the same way, and b) this code is
# used so that there should never be output both from Python and Java.
return (py_out, py_err) if (py_out or py_err) else (java_out, java_err)
class _PythonCapturer(object):
def __init__(self, stdout=True):
if stdout:
self._original = sys.stdout
self._set_stream = self._set_stdout
else:
self._original = sys.stderr
self._set_stream = self._set_stderr
self._stream = StringIO()
self._set_stream(self._stream)
def _set_stdout(self, stream):
sys.stdout = stream
def _set_stderr(self, stream):
sys.stderr = stream
def release(self):
# Original stream must be restored before closing the current
self._set_stream(self._original)
self._stream.flush()
output = self._stream.getvalue()
self._stream.close()
return output
if not sys.platform.startswith('java'):
class _JavaCapturer(object):
def __init__(self, stdout):
pass
def release(self):
return ''
else:
from java.io import PrintStream, ByteArrayOutputStream
from java.lang import System
class _JavaCapturer(object):
def __init__(self, stdout=True):
if stdout:
self._original = System.out
self._set_stream = System.setOut
else:
self._original = System.err
self._set_stream = System.setErr
self._bytes = ByteArrayOutputStream()
self._stream = PrintStream(self._bytes, False, 'UTF-8')
self._set_stream(self._stream)
def release(self):
# Original stream must be restored before closing the current
self._set_stream(self._original)
self._stream.close()
output = self._bytes.toString('UTF-8')
self._bytes.reset()
return output
| 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 fixture import Setup, Teardown
from timeouts import TestTimeout
class DefaultValues(object):
def __init__(self, settings, parent_default_values=None):
self._parent = parent_default_values
self._setup = settings.test_setup
self._teardown = settings.test_teardown
self._timeout = settings.test_timeout
self._force_tags = settings.force_tags
self._default_tags = settings.default_tags
self._test_template = settings.test_template
def get_setup(self, tc_setup):
setup = tc_setup if tc_setup.is_set() else self._get_default_setup()
return Setup(setup.name, setup.args)
def _get_default_setup(self):
if self._setup.is_set() or not self._parent:
return self._setup
return self._parent._get_default_setup()
def get_teardown(self, tc_teardown):
td = tc_teardown if tc_teardown.is_set() else self._get_default_teardown()
return Teardown(td.name, td.args)
def _get_default_teardown(self):
if self._teardown.is_set() or not self._parent:
return self._teardown
return self._parent._get_default_teardown()
def get_timeout(self, tc_timeout):
timeout = tc_timeout if tc_timeout.is_set() else self._timeout
return TestTimeout(timeout.value, timeout.message)
def get_tags(self, tc_tags):
tags = tc_tags if tc_tags.is_set() else self._default_tags
return (tags + self._get_force_tags()).value
def _get_force_tags(self):
if not self._parent:
return self._force_tags
return self._force_tags + self._parent._get_force_tags()
def get_template(self, template):
return (template if template.is_set() else self._test_template).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.
import sys
import inspect
from array import ArrayType
from robot.errors import DataError, FrameworkError
from robot.variables import is_list_var, is_scalar_var
from robot import utils
if utils.is_jython:
from javaargcoercer import ArgumentCoercer
class _KeywordArguments(object):
_type = 'Keyword'
def __init__(self, argument_source, kw_or_lib_name):
self.names, self.defaults, self.varargs, self.minargs, self.maxargs \
= self._determine_args(argument_source)
self._arg_limit_checker = _ArgLimitChecker(self.minargs, self.maxargs,
kw_or_lib_name, self._type)
def _determine_args(self, handler_or_argspec):
args, defaults, varargs = self._get_arg_spec(handler_or_argspec)
minargs = len(args) - len(defaults)
maxargs = len(args) if not varargs else sys.maxint
return args, defaults, varargs, minargs, maxargs
def resolve(self, args, variables, output=None):
posargs, namedargs = self._resolve(args, variables, output)
self.check_arg_limits(posargs, namedargs)
self._tracelog_args(output, posargs, namedargs)
return posargs, namedargs
def _resolve(self, args, variables, output):
return self._get_argument_resolver().resolve(args, output, variables)
def check_arg_limits(self, args, namedargs={}):
self._arg_limit_checker.check_arg_limits(args, namedargs)
def check_arg_limits_for_dry_run(self, args):
self._arg_limit_checker.check_arg_limits_for_dry_run(args)
def _tracelog_args(self, logger, posargs, namedargs={}):
if self._logger_not_available_during_library_init(logger):
return
args = [utils.safe_repr(a) for a in posargs] \
+ ['%s=%s' % (utils.unic(a), utils.safe_repr(namedargs[a]))
for a in namedargs]
logger.trace('Arguments: [ %s ]' % ' | '.join(args))
def _logger_not_available_during_library_init(self, logger):
return not logger
class PythonKeywordArguments(_KeywordArguments):
def _get_argument_resolver(self):
return PythonKeywordArgumentResolver(self)
def _get_arg_spec(self, handler):
"""Returns info about args in a tuple (args, defaults, varargs)
args - list of all accepted arguments except varargs
defaults - list of default values
varargs - name of the argument accepting varargs or None
"""
args, varargs, _, defaults = inspect.getargspec(handler)
if inspect.ismethod(handler):
args = args[1:] # drop 'self'
defaults = list(defaults) if defaults else []
return args, defaults, varargs
class JavaKeywordArguments(_KeywordArguments):
def __init__(self, handler_method, name):
_KeywordArguments.__init__(self, handler_method, name)
self.arg_coercer = ArgumentCoercer(self._get_signatures(handler_method))
def _get_argument_resolver(self):
return JavaKeywordArgumentResolver(self)
def _determine_args(self, handler_method):
signatures = self._get_signatures(handler_method)
minargs, maxargs = self._get_arg_limits(signatures)
return [], [], None, minargs, maxargs
def _get_signatures(self, handler):
co = self._get_code_object(handler)
return co.argslist[:co.nargs]
def _get_code_object(self, handler):
try:
return handler.im_func
except AttributeError:
return handler
def _get_arg_limits(self, signatures):
if len(signatures) == 1:
return self._get_single_sig_arg_limits(signatures[0])
else:
return self._get_multi_sig_arg_limits(signatures)
def _get_single_sig_arg_limits(self, signature):
args = signature.args
if len(args) > 0 and args[-1].isArray():
mina = len(args) - 1
maxa = sys.maxint
else:
mina = maxa = len(args)
return mina, maxa
def _get_multi_sig_arg_limits(self, signatures):
mina = maxa = None
for sig in signatures:
argc = len(sig.args)
if mina is None or argc < mina:
mina = argc
if maxa is None or argc > maxa:
maxa = argc
return mina, maxa
class DynamicKeywordArguments(_KeywordArguments):
def _get_argument_resolver(self):
return PythonKeywordArgumentResolver(self)
def _get_arg_spec(self, argspec):
if argspec is None:
return [], [], '<unknown>'
try:
if isinstance(argspec, basestring):
raise TypeError
return self._parse_arg_spec(list(argspec))
except TypeError:
raise TypeError('Argument spec should be a list/array of strings')
def _parse_arg_spec(self, argspec):
if argspec == []:
return [], [], None
args = []
defaults = []
vararg = None
for token in argspec:
if vararg is not None:
raise TypeError
if token.startswith('*'):
vararg = token[1:]
continue
if '=' in token:
arg, default = token.split('=', 1)
args.append(arg)
defaults.append(default)
continue
if defaults:
raise TypeError
args.append(token)
return args, defaults, vararg
class RunKeywordArguments(PythonKeywordArguments):
def __init__(self, argument_source, name, arg_resolution_index):
PythonKeywordArguments.__init__(self, argument_source, name)
self._arg_resolution_index = arg_resolution_index
def _resolve(self, args, variables, output):
args = variables.replace_from_beginning(self._arg_resolution_index, args)
return args, {}
class PythonInitArguments(PythonKeywordArguments):
_type = 'Test Library'
class JavaInitArguments(JavaKeywordArguments):
_type = 'Test Library'
def resolve(self, args, variables=None):
if variables:
args = variables.replace_list(args)
self.check_arg_limits(args)
return args, {}
class UserKeywordArguments(object):
def __init__(self, args, name):
self.names, self.defaults, self.varargs = self._get_arg_spec(args)
self.minargs = len(self.names) - len(self.defaults)
maxargs = len(self.names) if not self.varargs else sys.maxint
self._arg_limit_checker = _ArgLimitChecker(self.minargs, maxargs,
name, 'Keyword')
def _get_arg_spec(self, origargs):
"""Returns argument spec in a tuple (args, defaults, varargs).
args - tuple of all accepted arguments
defaults - tuple of default values
varargs - name of the argument accepting varargs or None
Examples:
['${arg1}', '${arg2}']
=> ('${arg1}', '${arg2}'), (), None
['${arg1}', '${arg2}=default', '@{varargs}']
=> ('${arg1}', '${arg2}'), ('default',), '@{varargs}'
"""
args = []
defaults = []
varargs = None
for arg in origargs:
if varargs:
raise DataError('Only last argument can be a list')
if is_list_var(arg):
varargs = arg
continue # should be last round (otherwise DataError in next)
arg, default = self._split_default(arg)
if defaults and default is None:
raise DataError('Non default argument after default arguments')
if not is_scalar_var(arg):
raise DataError("Invalid argument '%s'" % arg)
args.append(arg)
if default is not None:
defaults.append(default)
return args, defaults, varargs
def _split_default(self, arg):
if '=' not in arg:
return arg, None
return arg.split('=', 1)
def resolve_arguments_for_dry_run(self, arguments):
self._arg_limit_checker.check_arg_limits_for_dry_run(arguments)
required_number_of_args = self.minargs + len(self.defaults)
needed_args = required_number_of_args - len(arguments)
if needed_args > 0:
return self._fill_missing_args(arguments, needed_args)
return arguments
def _fill_missing_args(self, arguments, needed):
return arguments + needed * [None]
def resolve(self, arguments, variables, output):
positional, varargs, named = self._resolve_arg_usage(arguments, variables, output)
self._arg_limit_checker.check_arg_limits(positional+varargs, named)
argument_values = self._resolve_arg_values(variables, named, positional)
argument_values += varargs
self._arg_limit_checker.check_missing_args(argument_values, len(arguments))
return argument_values
def _resolve_arg_usage(self, arguments, variables, output):
resolver = UserKeywordArgumentResolver(self)
positional, named = resolver.resolve(arguments, output=output)
positional, named = self._replace_variables(variables, positional, named)
return self._split_args_and_varargs(positional) + (named,)
def _resolve_arg_values(self, variables, named, positional):
template = self._template_for(variables)
for name, value in named.items():
template.set_value(self.names.index(name), value)
for index, value in enumerate(positional):
template.set_value(index, value)
return template.as_list()
def _template_for(self, variables):
defaults = variables.replace_list(list(self.defaults))
return UserKeywordArgsTemplate(self.minargs, defaults)
def _replace_variables(self, variables, positional, named):
for name in named:
named[name] = variables.replace_scalar(named[name])
return variables.replace_list(positional), named
def set_variables(self, arg_values, variables, output):
before_varargs, varargs = self._split_args_and_varargs(arg_values)
for name, value in zip(self.names, before_varargs):
variables[name] = value
if self.varargs:
variables[self.varargs] = varargs
self._tracelog_args(output, variables)
def _split_args_and_varargs(self, args):
if not self.varargs:
return args, []
return args[:len(self.names)], args[len(self.names):]
def _tracelog_args(self, logger, variables):
arguments_string = self._get_arguments_as_string(variables)
logger.trace('Arguments: [ %s ]' % arguments_string)
def _get_arguments_as_string(self, variables):
args = []
for name in self.names + ([self.varargs] if self.varargs else []):
args.append('%s=%s' % (name, utils.safe_repr(variables[name])))
return ' | '.join(args)
class _MissingArg(object):
def __getattr__(self, name):
raise DataError
class UserKeywordArgsTemplate(object):
def __init__(self, minargs, defaults):
self._template = [_MissingArg() for _ in range(minargs)] + defaults
self._already_set = set()
def set_value(self, idx, value):
if idx in self._already_set:
raise FrameworkError
self._already_set.add(idx)
self._template[idx] = value
def as_list(self):
return self._template
class _ArgumentResolver(object):
def __init__(self, arguments):
self._arguments = arguments
self._mand_arg_count = len(arguments.names) - len(arguments.defaults)
def resolve(self, values, output, variables=None):
positional, named = self._resolve_argument_usage(values, output)
return self._resolve_variables(positional, named, variables)
def _resolve_argument_usage(self, values, output):
named = {}
last_positional = self._get_last_positional_idx(values)
used_names = self._arguments.names[:last_positional]
for arg in values[last_positional:]:
name, value = self._parse_named(arg)
if name in named:
raise DataError('Keyword argument %s repeated.' % name)
if name in used_names:
output.warn("Could not resolve named arguments because value "
"for argument '%s' was given twice." % name)
return values, {}
used_names.append(name)
named[name] = value
return values[:last_positional], named
def _get_last_positional_idx(self, values):
last_positional_idx = self._mand_arg_count
named_allowed = True
for arg in reversed(self._optional(values)):
if not (named_allowed and self._is_named(arg)):
named_allowed = False
last_positional_idx += 1
return last_positional_idx
def _optional(self, values):
return values[self._mand_arg_count:]
def _is_named(self, arg):
if self._is_str_with_kwarg_sep(arg):
name, _ = self._split_from_kwarg_sep(arg)
return self._is_arg_name(name)
return False
def _parse_named(self, arg):
name, value = self._split_from_kwarg_sep(arg)
return self._coerce(name), value
def _is_str_with_kwarg_sep(self, arg):
if not isinstance(arg, basestring):
return False
if '=' not in arg:
return False
return True
def _split_from_kwarg_sep(self, arg):
return arg.split('=', 1)
def _is_arg_name(self, name):
return self._arg_name(name) in self._arguments.names
def _resolve_variables(self, posargs, kwargs, variables):
posargs = self._replace_list(posargs, variables)
for name, value in kwargs.items():
kwargs[name] = self._replace_scalar(value, variables)
return posargs, kwargs
def _replace_list(self, values, variables):
return variables.replace_list(values) if variables else values
def _replace_scalar(self, value, variables):
return variables.replace_scalar(value) if variables else value
class UserKeywordArgumentResolver(_ArgumentResolver):
def _arg_name(self, name):
return '${%s}' % name
def _coerce(self, name):
return '${%s}' % name
class PythonKeywordArgumentResolver(_ArgumentResolver):
def _arg_name(self, name):
return name
def _coerce(self, name):
return str(name)
class JavaKeywordArgumentResolver(object):
def __init__(self, arguments):
self._arguments = arguments
self._minargs, self._maxargs = arguments.minargs, arguments.maxargs
def resolve(self, values, output, variables):
values = variables.replace_list(values)
self._arguments.check_arg_limits(values)
if self._expects_varargs() and self._last_is_not_list(values):
values[self._minargs:] = [values[self._minargs:]]
return self._arguments.arg_coercer(values), {}
def _expects_varargs(self):
return self._maxargs == sys.maxint
def _last_is_not_list(self, args):
return not (len(args) == self._minargs + 1
and isinstance(args[-1], (list, tuple, ArrayType)))
class _ArgLimitChecker(object):
def __init__(self, minargs, maxargs, name, type_):
self.minargs = minargs
self.maxargs = maxargs
self._name = name
self._type = type_
def check_arg_limits(self, args, namedargs={}):
self._check_arg_limits(len(args) + len(namedargs))
def check_arg_limits_for_dry_run(self, args):
arg_count = len(args)
scalar_arg_count = len([a for a in args if not is_list_var(a)])
if scalar_arg_count <= self.minargs and arg_count - scalar_arg_count:
arg_count = self.minargs
self._check_arg_limits(arg_count)
def _check_arg_limits(self, arg_count):
if not self.minargs <= arg_count <= self.maxargs:
self._raise_inv_args(arg_count)
def check_missing_args(self, args, arg_count):
for a in args:
if isinstance(a, _MissingArg):
self._raise_inv_args(arg_count)
def _raise_inv_args(self, arg_count):
minend = utils.plural_or_not(self.minargs)
if self.minargs == self.maxargs:
exptxt = "%d argument%s" % (self.minargs, minend)
elif self.maxargs != sys.maxint:
exptxt = "%d to %d arguments" % (self.minargs, self.maxargs)
else:
exptxt = "at least %d argument%s" % (self.minargs, minend)
raise DataError("%s '%s' expected %s, got %d."
% (self._type, self._name, exptxt, arg_count))
| 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
from robot import utils
class _RunKeywordRegister:
def __init__(self):
self._libs = {}
def register_run_keyword(self, libname, keyword, args_to_process=None):
if args_to_process is None:
args_to_process = self._get_args_from_method(keyword)
keyword = keyword.__name__
if libname not in self._libs:
self._libs[libname] = utils.NormalizedDict(ignore=['_'])
self._libs[libname][keyword] = int(args_to_process)
def get_args_to_process(self, libname, kwname):
if libname in self._libs and kwname in self._libs[libname]:
return self._libs[libname][kwname]
return -1
def is_run_keyword(self, libname, kwname):
return self.get_args_to_process(libname, kwname) >= 0
def _get_args_from_method(self, method):
if inspect.ismethod(method):
return method.im_func.func_code.co_argcount -1
elif inspect.isfunction(method):
return method.func_code.co_argcount
raise ValueError("Needs function or method!")
RUN_KW_REGISTER = _RunKeywordRegister()
| 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 threading import currentThread
try:
import signal
except ImportError:
signal = None # IronPython 2.6 doesn't have signal module by default
if sys.platform.startswith('java'):
from java.lang import IllegalArgumentException
else:
IllegalArgumentException = None
from robot.errors import ExecutionFailed
from robot.output import LOGGER
class _StopSignalMonitor(object):
def __init__(self):
self._signal_count = 0
self._running_keyword = False
def __call__(self, signum, frame):
self._signal_count += 1
LOGGER.info('Received signal: %s.' % signum)
if self._signal_count > 1:
sys.__stderr__.write('Execution forcefully stopped.\n')
raise SystemExit()
sys.__stderr__.write('Second signal will force exit.\n')
if self._running_keyword and not sys.platform.startswith('java'):
self._stop_execution_gracefully()
def _stop_execution_gracefully(self):
raise ExecutionFailed('Execution terminated by signal', exit=True)
def start(self):
if signal:
for signum in signal.SIGINT, signal.SIGTERM:
self._register_signal_handler(signum)
def _register_signal_handler(self, signum):
try:
signal.signal(signum, self)
except (ValueError, IllegalArgumentException), err:
# ValueError occurs e.g. if Robot doesn't run on main thread.
# IllegalArgumentException is http://bugs.jython.org/issue1729
if currentThread().getName() == 'MainThread':
self._warn_about_registeration_error(signum, err)
def _warn_about_registeration_error(self, signum, err):
name, ctrlc = {signal.SIGINT: ('INT', 'or with Ctrl-C '),
signal.SIGTERM: ('TERM', '')}[signum]
LOGGER.warn('Registering signal %s failed. Stopping execution '
'gracefully with this signal %sis not possible. '
'Original error was: %s' % (name, ctrlc, err))
def start_running_keyword(self, in_teardown):
self._running_keyword = True
if self._signal_count and not in_teardown:
self._stop_execution_gracefully()
def stop_running_keyword(self):
self._running_keyword = False
STOP_SIGNAL_MONITOR = _StopSignalMonitor()
| 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 sys
import copy
from robot import utils
from robot.errors import FrameworkError, DataError
from robot.variables import GLOBAL_VARIABLES, is_scalar_var
from robot.common import UserErrorHandler
from robot.output import LOGGER
from robot.parsing.settings import Library, Variables, Resource
import robot
from userkeyword import UserLibrary
from importer import Importer, ImportCache
from runkwregister import RUN_KW_REGISTER
from handlers import _XTimesHandler
STDLIB_NAMES = ['BuiltIn', 'Collections', 'Dialogs', 'Easter', 'OperatingSystem',
'Remote', 'Reserved', 'Screenshot', 'String', 'Telnet']
IMPORTER = Importer()
class Namespace:
"""A database for keywords and variables.
A new instance of this class is created for each test suite.
"""
def __init__(self, suite, parent_vars, skip_imports=False):
if suite is not None:
LOGGER.info("Initializing namespace for test suite '%s'" % suite.longname)
self.variables = _VariableScopes(suite, parent_vars)
self.suite = suite
self.test = None
self.uk_handlers = []
self.library_search_order = []
self._testlibs = {}
self._userlibs = []
self._imported_resource_files = ImportCache()
self._imported_variable_files = ImportCache()
self.import_library('BuiltIn')
self.import_library('Reserved')
self.import_library('Easter')
if suite.source and not skip_imports:
self._handle_imports(suite.imports)
robot.running.NAMESPACES.start_suite(self)
self.variables['${SUITE_NAME}'] = suite.longname
self.variables['${SUITE_SOURCE}'] = suite.source
def _handle_imports(self, import_settings):
for item in import_settings:
try:
if not item.name:
raise DataError('%s setting requires a name' % item.type)
self._import(item)
except:
item.report_invalid_syntax(utils.get_error_message())
def _import(self, import_setting):
try:
action = {'Library': self._import_library,
'Resource': self._import_resource,
'Variables': self._import_variables}[import_setting.type]
action(import_setting, self.variables.current)
except KeyError:
raise FrameworkError("Invalid import setting: %s" % import_setting)
def import_resource(self, name):
self._import_resource(Resource(None, name))
def _import_resource(self, import_setting, variables=None):
path = self._resolve_name(import_setting, variables)
if path not in self._imported_resource_files:
self._imported_resource_files.add(path)
resource = IMPORTER.import_resource(path)
self.variables.set_from_variable_table(resource.variable_table)
self._userlibs.append(UserLibrary(resource.keyword_table.keywords,
resource.source))
self._handle_imports(resource.setting_table.imports)
else:
LOGGER.info("Resource file '%s' already imported by suite '%s'"
% (path, self.suite.longname))
def import_variables(self, name, args, overwrite=False, variables=None):
self._import_variables(Variables(None, name, args), variables, overwrite)
def _import_variables(self, import_setting, variables, overwrite=False):
path = self._resolve_name(import_setting, variables)
args = self._resolve_args(import_setting, variables)
if (path, args) not in self._imported_variable_files:
self._imported_variable_files.add((path,args))
self.variables.set_from_file(path, args, overwrite)
else:
msg = "Variable file '%s'" % path
if args:
msg += " with arguments %s" % utils.seq2str2(args)
LOGGER.info("%s already imported by suite '%s'"
% (msg, self.suite.longname))
def import_library(self, name, args=None, alias=None, variables=None):
self._import_library(Library(None, name, args=args, alias=alias), variables)
def _import_library(self, import_setting, variables):
name = self._get_library_name(import_setting, variables)
lib = IMPORTER.import_library(name, import_setting.args,
import_setting.alias, variables)
if lib.name in self._testlibs:
LOGGER.info("Test library '%s' already imported by suite '%s'"
% (lib.name, self.suite.longname))
return
self._testlibs[lib.name] = lib
lib.start_suite()
if self.test:
lib.start_test()
self._import_deprecated_standard_libs(lib.name)
def _get_library_name(self, import_setting, variables):
name = self._resolve_name(import_setting, variables)
if os.path.exists(name):
return name
return name.replace(' ', '')
def _resolve_name(self, import_setting, variables):
"""Resolves variables from the import_setting name
Returns absolute path to file if it exists or resolved import_setting name.
"""
if variables:
try:
name = variables.replace_string(import_setting.name)
except DataError, err:
self._report_replacing_vars_failed(import_setting, err)
else:
name = import_setting.name
basedir = import_setting.directory or ''
return self._get_path(import_setting.type, name, basedir)
def _report_replacing_vars_failed(self, import_setting, err):
raise DataError("Replacing variables from setting '%s' failed: %s"
% (import_setting.type, unicode(err)))
def _resolve_args(self, import_setting, variables):
if not variables:
return import_setting.args
try:
return variables.replace_list(import_setting.args)
except DataError, err:
self._report_replacing_vars_failed(import_setting, err)
def _get_path(self, setting_name, path, basedir):
if setting_name == 'Library' and not self._is_library_by_path(path, basedir):
return path
path = self._resolve_path(setting_name, path.replace('/', os.sep), basedir)
return utils.abspath(path)
def _is_library_by_path(self, path, basedir):
return path.lower().endswith(('.py', '.java', '.class', '/'))
def _resolve_path(self, setting_name, path, basedir):
for base in [basedir] + sys.path:
if not os.path.isdir(base):
continue
ret = os.path.join(base, path)
if os.path.isfile(ret):
return ret
if os.path.isdir(ret) and os.path.isfile(os.path.join(ret, '__init__.py')):
return ret
name = {'Library': 'Test library',
'Variables': 'Variable file',
'Resource': 'Resource file'}[setting_name]
raise DataError("%s '%s' does not exist." % (name, path))
def _import_deprecated_standard_libs(self, name):
if name in ['BuiltIn', 'OperatingSystem']:
self.import_library('Deprecated' + name)
def start_test(self, test):
self.variables.start_test(test)
self.test = test
for lib in self._testlibs.values():
lib.start_test()
self.variables['${TEST_NAME}'] = test.name
self.variables['@{TEST_TAGS}'] = test.tags
def end_test(self):
self.test = None
self.variables.end_test()
self.uk_handlers = []
for lib in self._testlibs.values():
lib.end_test()
def set_test_status_before_teardown(self, message, status):
self.variables['${TEST_MESSAGE}'] = message
self.variables['${TEST_STATUS}'] = status
def end_suite(self):
self.suite = None
self.variables.end_suite()
for lib in self._testlibs.values():
lib.end_suite()
robot.running.NAMESPACES.end_suite()
def start_user_keyword(self, handler):
self.variables.start_uk(handler)
self.uk_handlers.append(handler)
def end_user_keyword(self):
self.variables.end_uk()
self.uk_handlers.pop()
def get_library_instance(self, libname):
try:
return self._testlibs[libname.replace(' ', '')].get_instance()
except KeyError:
raise DataError("No library with name '%s' found." % libname)
def get_handler(self, name):
try:
handler = self._get_handler(name)
if handler is None:
raise DataError("No keyword with name '%s' found." % name)
except:
error = utils.get_error_message()
handler = UserErrorHandler(name, error)
self._replace_variables_from_user_handlers(handler)
return handler
def _replace_variables_from_user_handlers(self, handler):
if hasattr(handler, 'replace_variables'):
handler.replace_variables(self.variables)
def _get_handler(self, name):
handler = None
if not name:
raise DataError('Keyword name cannot be empty.')
if '.' in name:
handler = self._get_explicit_handler(name)
if not handler:
handler = self._get_implicit_handler(name)
if not handler:
handler = self._get_bdd_style_handler(name)
if not handler:
handler = self._get_x_times_handler(name)
return handler
def _get_x_times_handler(self, name):
if not self._is_old_x_times_syntax(name):
return None
return _XTimesHandler(self._get_handler('Repeat Keyword'), name)
def _is_old_x_times_syntax(self, name):
if not name.lower().endswith('x'):
return False
times = name[:-1].strip()
if is_scalar_var(times):
return True
try:
int(times)
except ValueError:
return False
else:
return True
def _get_bdd_style_handler(self, name):
for prefix in ['given ', 'when ', 'then ', 'and ']:
if name.lower().startswith(prefix):
handler = self._get_handler(name[len(prefix):])
if handler:
handler = copy.copy(handler)
handler.name = name
return handler
return None
def _get_implicit_handler(self, name):
for method in [self._get_handler_from_test_case_file_user_keywords,
self._get_handler_from_resource_file_user_keywords,
self._get_handler_from_library_keywords]:
handler = method(name)
if handler:
return handler
return None
def _get_handler_from_test_case_file_user_keywords(self, name):
if self.suite.user_keywords.has_handler(name):
return self.suite.user_keywords.get_handler(name)
def _get_handler_from_resource_file_user_keywords(self, name):
found = [lib.get_handler(name) for lib in self._userlibs
if lib.has_handler(name)]
if not found:
return None
if len(found) == 1:
return found[0]
self._raise_multiple_keywords_found(name, found)
def _get_handler_from_library_keywords(self, name):
found = [lib.get_handler(name) for lib in self._testlibs.values()
if lib.has_handler(name)]
if not found:
return None
if len(found) > 1:
found = self._get_handler_based_on_library_search_order(found)
if len(found) == 2:
found = self._filter_stdlib_handler(found[0], found[1])
if len(found) == 1:
return found[0]
self._raise_multiple_keywords_found(name, found)
def _get_handler_based_on_library_search_order(self, handlers):
for libname in self.library_search_order:
libname = libname.replace(' ', '')
for handler in handlers:
if handler.library.name.replace(' ', '') == libname:
return [handler]
return handlers
def _filter_stdlib_handler(self, handler1, handler2):
if handler1.library.orig_name in STDLIB_NAMES:
standard, external = handler1, handler2
elif handler2.library.orig_name in STDLIB_NAMES:
standard, external = handler2, handler1
else:
return [handler1, handler2]
if not RUN_KW_REGISTER.is_run_keyword(external.library.orig_name, external.name):
LOGGER.warn(
"Keyword '%s' found both from a user created test library "
"'%s' and Robot Framework standard library '%s'. The user "
"created keyword is used. To select explicitly, and to get "
"rid of this warning, use either '%s' or '%s'."
% (standard.name,
external.library.orig_name, standard.library.orig_name,
external.longname, standard.longname))
return [external]
def _get_explicit_handler(self, name):
libname, kwname = self._split_keyword_name(name)
# 1) Find matching lib(s)
libs = [lib for lib in self._userlibs + self._testlibs.values()
if utils.eq(lib.name, libname)]
if not libs:
return None
# 2) Find matching kw from found libs
found = [lib.get_handler(kwname) for lib in libs
if lib.has_handler(kwname)]
if len(found) > 1:
self._raise_multiple_keywords_found(name, found, implicit=False)
return found and found[0] or None
def _split_keyword_name(self, name):
parts = name.split('.')
kwname = parts.pop() # pop last part
libname = '.'.join(parts) # and rejoin rest
return libname, kwname
def _raise_multiple_keywords_found(self, name, found, implicit=True):
error = "Multiple keywords with name '%s' found.\n" % name
if implicit:
error += "Give the full name of the keyword you want to use.\n"
names = sorted(handler.longname for handler in found)
error += "Found: %s" % utils.seq2str(names)
raise DataError(error)
class _VariableScopes:
def __init__(self, suite, parent_vars):
# suite and parent are None only when used by copy_all
if suite is not None:
suite.variables.update(GLOBAL_VARIABLES)
self._suite = self.current = suite.variables
else:
self._suite = self.current = None
self._parents = []
if parent_vars is not None:
self._parents.append(parent_vars.current)
self._parents.extend(parent_vars._parents)
self._test = None
self._uk_handlers = []
def __len__(self):
if self.current:
return len(self.current)
return 0
def copy_all(self):
vs = _VariableScopes(None, None)
vs._suite = self._suite
vs._test = self._test
vs._uk_handlers = self._uk_handlers[:]
vs._parents = self._parents[:]
vs.current = self.current
return vs
def replace_list(self, items):
return self.current.replace_list(items)
def replace_scalar(self, items):
return self.current.replace_scalar(items)
def replace_string(self, string):
return self.current.replace_string(string)
def replace_from_beginning(self, how_many, args):
# There might be @{list} variables and those might have more or less
# arguments that is needed. Therefore we need to go through arguments
# one by one.
processed = []
while len(processed) < how_many and args:
processed += self.current.replace_list([args.pop(0)])
# In case @{list} variable is unpacked, the arguments going further
# needs to be escaped, otherwise those are unescaped twice.
processed[how_many:] = [utils.escape(arg) for arg in processed[how_many:]]
return processed + args
def set_from_file(self, path, args, overwrite=False):
variables = self._suite.set_from_file(path, args, overwrite)
if self._test is not None:
self._test._set_from_file(variables, overwrite=True, path=path)
for varz in self._uk_handlers:
varz._set_from_file(variables, overwrite=True, path=path)
if self._uk_handlers:
self.current._set_from_file(variables, overwrite=True, path=path)
def set_from_variable_table(self, rawvariables):
self._suite.set_from_variable_table(rawvariables)
# TODO: This should be removed so that these objects themselves had
# the capability of resolving variables.
def replace_meta(self, name, item, errors):
error = None
for varz in [self.current] + self._parents:
try:
if name == 'Documentation':
return varz.replace_string(item, ignore_errors=True)
elif isinstance(item, basestring):
return varz.replace_string(item)
return varz.replace_list(item)
except DataError, error:
pass
errors.append("Replacing variables from setting '%s' failed: %s"
% (name, error))
return utils.unescape(item)
def __getitem__(self, name):
return self.current[name]
def __setitem__(self, name, value):
self.current[name] = value
def end_suite(self):
self._suite = self._test = self.current = None
def start_test(self, test):
self._test = self.current = self._suite.copy()
def end_test(self):
self.current = self._suite
def start_uk(self, handler):
self._uk_handlers.append(self.current)
self.current = self.current.copy()
def end_uk(self):
self.current = self._uk_handlers.pop()
def set_global(self, name, value):
GLOBAL_VARIABLES.__setitem__(name, value)
for ns in robot.running.NAMESPACES:
ns.variables.set_suite(name, value)
def set_suite(self, name, value):
self._suite.__setitem__(name, value)
self.set_test(name, value, False)
def set_test(self, name, value, fail_if_no_test=True):
if self._test is not None:
self._test.__setitem__(name, value)
elif fail_if_no_test:
raise DataError("Cannot set test variable when no test is started")
for varz in self._uk_handlers:
varz.__setitem__(name, value)
self.current.__setitem__(name, value)
def keys(self):
return self.current.keys()
def has_key(self, key):
return self.current.has_key(key)
| 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 TestSuite
from keywords import Keyword
from testlibraries import TestLibrary
from runkwregister import RUN_KW_REGISTER
from signalhandler import STOP_SIGNAL_MONITOR
def UserLibrary(path):
"""Create a user library instance from given resource file.
This is used at least by libdoc.py."""
from robot.parsing import ResourceFile
from robot import utils
from arguments import UserKeywordArguments
from userkeyword import UserLibrary as RuntimeUserLibrary
resource = ResourceFile(path)
ret = RuntimeUserLibrary(resource.keyword_table.keywords, path)
for handler in ret.handlers.values(): # This is done normally only at runtime.
handler.arguments = UserKeywordArguments(handler._keyword_args,
handler.longname)
handler.doc = utils.unescape(handler._doc)
ret.doc = resource.setting_table.doc.value
return ret
class _Namespaces:
def __init__(self):
self._namespaces = []
self.current = None
def start_suite(self, namespace):
self._namespaces.append(self.current)
self.current = namespace
def end_suite(self):
self.current = self._namespaces.pop()
def __iter__(self):
namespaces = self._namespaces + [self.current]
return iter([ns for ns in namespaces if ns is not None])
# Hook to namespaces
NAMESPACES = _Namespaces()
| 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 java.lang import Byte, Short, Integer, Long, Boolean, Float, Double
class ArgumentCoercer:
def __init__(self, signatures):
types = self._parse_types(signatures)
self._coercers = [_CoercionFunction(t, i+1) for i, t in types]
def _parse_types(self, signatures):
types = {}
for sig in signatures:
for index, arg in enumerate(sig.args):
types.setdefault(index, []).append(arg)
return sorted(types.items())
def __call__(self, args):
return [coercer(arg) for coercer, arg in zip(self._coercers, args)]
class _CoercionFunction:
_bool_types = [Boolean]
_int_types = [Byte, Short, Integer, Long]
_float_types = [Float, Double]
_bool_primitives = ['boolean']
_int_primitives = ['byte', 'short', 'int', 'long']
_float_primitives = ['float', 'double']
_bool_primitives = ["<type 'boolean'>"]
_int_primitives = ["<type '%s'>" % p for p in _int_primitives]
_float_primitives = ["<type '%s'>" % p for p in _float_primitives]
def __init__(self, arg_types, position):
self._position = position
self.__coercer = None
for arg in arg_types:
if not (self._set_bool(arg) or
self._set_int(arg) or
self._set_float(arg)):
self.__coercer = self._no_coercion
def __call__(self, arg):
if not isinstance(arg, basestring):
return arg
return self.__coercer(arg)
def _set_bool(self, arg):
return self._set_coercer(arg, self._bool_types,
self._bool_primitives, self._to_bool)
def _set_int(self, arg):
return self._set_coercer(arg, self._int_types,
self._int_primitives, self._to_int)
def _set_float(self, arg):
return self._set_coercer(arg, self._float_types,
self._float_primitives, self._to_float)
def _set_coercer(self, arg, type_list, primitive_list, coercer):
if arg in type_list or str(arg) in primitive_list:
if self.__coercer is None:
self.__coercer = coercer
elif self.__coercer != coercer:
self.__coercer = self._no_coercion
return True
return False
def _to_bool(self, arg):
try:
return {'false': False, 'true': True}[arg.lower()]
except KeyError:
self._coercion_failed('boolean')
def _to_int(self, arg):
try:
return int(arg)
except ValueError:
self._coercion_failed('integer')
def _to_float(self, arg):
try:
return float(arg)
except ValueError:
self._coercion_failed('floating point number')
def _no_coercion(self, arg):
return arg
def _coercion_failed(self, arg_type):
raise ValueError('Argument at position %d cannot be coerced to %s'
% (self._position, arg_type))
| 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.variables import GLOBAL_VARIABLES
class ExecutionContext(object):
def __init__(self, namespace, output, dry_run=False):
self.namespace = namespace
self.output = output
self.dry_run = dry_run
self._in_teardown = 0
@property
def teardown(self):
if self._in_teardown:
return True
# TODO: tests and suites should also call start/end_teardown()
test_or_suite = self.namespace.test or self.namespace.suite
return test_or_suite.status != 'RUNNING'
def start_teardown(self):
self._in_teardown += 1
def end_teardown(self):
self._in_teardown -= 1
def get_current_vars(self):
return self.namespace.variables
def end_test(self, test):
self.output.end_test(test)
self.namespace.end_test()
def end_suite(self, suite):
self.output.end_suite(suite)
self.namespace.end_suite()
def output_file_changed(self, filename):
self._set_global_variable('${OUTPUT_FILE}', filename)
def replace_vars_from_setting(self, name, value, errors):
return self.namespace.variables.replace_meta(name, value, errors)
def log_file_changed(self, filename):
self._set_global_variable('${LOG_FILE}', filename)
def set_prev_test_variables(self, test):
self._set_prev_test_variables(self.get_current_vars(), test.name,
test.status, test.message)
def copy_prev_test_vars_to_global(self):
varz = self.get_current_vars()
name, status, message = varz['${PREV_TEST_NAME}'], \
varz['${PREV_TEST_STATUS}'], varz['${PREV_TEST_MESSAGE}']
self._set_prev_test_variables(GLOBAL_VARIABLES, name, status, message)
def _set_prev_test_variables(self, destination, name, status, message):
destination['${PREV_TEST_NAME}'] = name
destination['${PREV_TEST_STATUS}'] = status
destination['${PREV_TEST_MESSAGE}'] = message
def _set_global_variable(self, name, value):
self.namespace.variables.set_global(name, value)
def report_suite_status(self, status, message):
self.get_current_vars()['${SUITE_STATUS}'] = status
self.get_current_vars()['${SUITE_MESSAGE}'] = message
def start_test(self, test):
self.namespace.start_test(test)
self.output.start_test(test)
def set_test_status_before_teardown(self, message, status):
self.namespace.set_test_status_before_teardown(message, status)
def get_handler(self, name):
return self.namespace.get_handler(name)
def start_keyword(self, keyword):
self.output.start_keyword(keyword)
def end_keyword(self, keyword):
self.output.end_keyword(keyword)
def warn(self, message):
self.output.warn(message)
def trace(self, message):
self.output.trace(message)
| 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
from robot.common import BaseLibrary, UserErrorHandler
from robot.errors import DataError, ExecutionFailed, UserKeywordExecutionFailed
from robot.variables import is_list_var, VariableSplitter
from robot.output import LOGGER
from robot import utils
from keywords import Keywords
from fixture import Teardown, KeywordTeardownListener
from timeouts import KeywordTimeout
from arguments import UserKeywordArguments
from runerrors import KeywordRunErrors
class UserLibrary(BaseLibrary):
supports_named_arguments = True # this attribute is for libdoc
def __init__(self, user_keywords, path=None):
self.name = self._get_name_for_resource_file(path)
self.handlers = utils.NormalizedDict(ignore=['_'])
self.embedded_arg_handlers = []
for kw in user_keywords:
try:
handler = EmbeddedArgsTemplate(kw, self.name)
except DataError, err:
LOGGER.error("Creating user keyword '%s' failed: %s"
% (kw.name, unicode(err)))
continue
except TypeError:
handler = UserKeywordHandler(kw, self.name)
else:
self.embedded_arg_handlers.append(handler)
if handler.name in self.handlers:
err = "Keyword '%s' defined multiple times" % handler.name
handler = UserErrorHandler(handler.name, err)
self.handlers[handler.name] = handler
def _get_name_for_resource_file(self, path):
if path is None:
return None
return os.path.splitext(os.path.basename(path))[0]
def has_handler(self, name):
if BaseLibrary.has_handler(self, name):
return True
for template in self.embedded_arg_handlers:
try:
EmbeddedArgs(name, template)
except TypeError:
pass
else:
return True
return False
def get_handler(self, name):
try:
return BaseLibrary.get_handler(self, name)
except DataError, error:
found = self._get_embedded_arg_handlers(name)
if not found:
raise error
if len(found) == 1:
return found[0]
self._raise_multiple_matching_keywords_found(name, found)
def _get_embedded_arg_handlers(self, name):
found = []
for template in self.embedded_arg_handlers:
try:
found.append(EmbeddedArgs(name, template))
except TypeError:
pass
return found
def _raise_multiple_matching_keywords_found(self, name, found):
names = utils.seq2str([f.origname for f in found])
if self.name is None:
where = "Test case file"
else:
where = "Resource file '%s'" % self.name
raise DataError("%s contains multiple keywords matching name '%s'\n"
"Found: %s" % (where, name, names))
class UserKeywordHandler(object):
type = 'user'
def __init__(self, keyword, libname):
self.name = keyword.name
self.keywords = Keywords(keyword.steps)
self.return_value = keyword.return_.value
self.teardown = keyword.teardown
self._libname = libname
self.doc = self._doc = keyword.doc.value
self._timeout = keyword.timeout
self._keyword_args = keyword.args.value
@property
def longname(self):
return '%s.%s' % (self._libname, self.name) if self._libname else self.name
@property
def shortdoc(self):
return self.doc.splitlines()[0] if self.doc else ''
def init_keyword(self, varz):
self._errors = []
self.doc = varz.replace_meta('Documentation', self._doc, self._errors)
self.timeout = KeywordTimeout(self._timeout.value, self._timeout.message)
self.timeout.replace_variables(varz)
def run(self, context, arguments):
context.namespace.start_user_keyword(self)
try:
return self._run(context, arguments)
finally:
context.namespace.end_user_keyword()
def _run(self, context, argument_values):
args_spec = UserKeywordArguments(self._keyword_args, self.longname)
variables = context.get_current_vars()
if context.dry_run:
return self._dry_run(context, variables, args_spec, argument_values)
return self._variable_resolving_run(context, variables, args_spec, argument_values)
def _dry_run(self, context, variables, args_spec, argument_values):
resolved_arguments = args_spec.resolve_arguments_for_dry_run(argument_values)
self._execute(context, variables, args_spec, resolved_arguments)
return None
def _variable_resolving_run(self, context, variables, args_spec, argument_values):
resolved_arguments = args_spec.resolve(argument_values, variables,
context.output)
self._execute(context, variables, args_spec, resolved_arguments)
return self._get_return_value(variables)
def _execute(self, context, variables, args_spec, resolved_arguments):
args_spec.set_variables(resolved_arguments, variables, context.output)
self._verify_keyword_is_valid()
self.timeout.start()
try:
self.keywords.run(context)
except ExecutionFailed, error:
pass
else:
error = None
td_error = self._run_teardown(context)
if error or td_error:
raise UserKeywordExecutionFailed(error, td_error)
def _run_teardown(self, context):
if not self.teardown:
return
teardown = Teardown(self.teardown.name, self.teardown.args)
teardown.replace_variables(context.get_current_vars(), [])
context.start_teardown()
run_errors = KeywordRunErrors()
teardown.run(context, KeywordTeardownListener(run_errors))
context.end_teardown()
return run_errors.teardown_error
def _verify_keyword_is_valid(self):
if self._errors:
raise DataError('User keyword initialization failed:\n%s'
% '\n'.join(self._errors))
if not (self.keywords or self.return_value):
raise DataError("User keyword '%s' contains no keywords"
% self.name)
def _get_return_value(self, variables):
if not self.return_value:
return None
try:
ret = variables.replace_list(self.return_value)
except DataError, err:
raise DataError('Replacing variables from keyword return value '
'failed: %s' % unicode(err))
if len(ret) != 1 or is_list_var(self.return_value[0]):
return ret
return ret[0]
class EmbeddedArgsTemplate(UserKeywordHandler):
_regexp_extension = re.compile(r'(?<!\\)\(\?.+\)')
_regexp_group_start = re.compile(r'(?<!\\)\((.*?)\)')
_regexp_group_escape = r'(?:\1)'
_default_pattern = '.*?'
_variable_pattern = r'\$\{[^\}]+\}'
def __init__(self, keyword, libname):
if keyword.args.value:
raise TypeError('Cannot have normal arguments')
self.embedded_args, self.name_regexp \
= self._read_embedded_args_and_regexp(keyword.name)
if not self.embedded_args:
raise TypeError('Must have embedded arguments')
UserKeywordHandler.__init__(self, keyword, libname)
def _read_embedded_args_and_regexp(self, string):
args = []
full_pattern = ['^']
while True:
before, variable, rest = self._split_from_variable(string)
if before is None:
break
variable, pattern = self._get_regexp_pattern(variable)
args.append('${%s}' % variable)
full_pattern.extend([re.escape(before), '(%s)' % pattern])
string = rest
full_pattern.extend([re.escape(rest), '$'])
return args, self._compile_regexp(full_pattern)
def _split_from_variable(self, string):
var = VariableSplitter(string, identifiers=['$'])
if var.identifier is None:
return None, None, string
return string[:var.start], var.base, string[var.end:]
def _get_regexp_pattern(self, variable):
if ':' not in variable:
return variable, self._default_pattern
variable, pattern = variable.split(':', 1)
return variable, self._format_custom_regexp(pattern)
def _format_custom_regexp(self, pattern):
for formatter in (self._regexp_extensions_are_not_allowed,
self._make_groups_non_capturing,
self._unescape_closing_curly,
self._add_automatic_variable_pattern):
pattern = formatter(pattern)
return pattern
def _regexp_extensions_are_not_allowed(self, pattern):
if not self._regexp_extension.search(pattern):
return pattern
raise DataError('Regexp extensions are not allowed in embedded '
'arguments.')
def _make_groups_non_capturing(self, pattern):
return self._regexp_group_start.sub(self._regexp_group_escape, pattern)
def _unescape_closing_curly(self, pattern):
return pattern.replace('\\}', '}')
def _add_automatic_variable_pattern(self, pattern):
return '%s|%s' % (pattern, self._variable_pattern)
def _compile_regexp(self, pattern):
try:
return re.compile(''.join(pattern), re.IGNORECASE)
except:
raise DataError("Compiling embedded arguments regexp failed: %s"
% utils.get_error_message())
class EmbeddedArgs(UserKeywordHandler):
def __init__(self, name, template):
match = template.name_regexp.match(name)
if not match:
raise TypeError('Does not match given name')
self.embedded_args = zip(template.embedded_args, match.groups())
self.name = name
self.teardown = None
self.origname = template.name
self._copy_attrs_from_template(template)
def run(self, context, args):
if not context.dry_run:
for name, value in self.embedded_args:
context.get_current_vars()[name] = \
context.get_current_vars().replace_scalar(value)
return UserKeywordHandler.run(self, context, args)
def _copy_attrs_from_template(self, template):
self._libname = template._libname
self.keywords = template.keywords
self._keyword_args = template._keyword_args
self.return_value = template.return_value
self.doc = template.doc
self._doc = template._doc
self._timeout = template._timeout
| 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
import copy
from robot.output import LOGGER
from robot.parsing import ResourceFile
from robot.errors import FrameworkError
from robot import utils
from testlibraries import TestLibrary
class Importer:
def __init__(self):
self._library_cache = ImportCache()
self._resource_cache = ImportCache()
def import_library(self, name, args, alias, variables):
lib = TestLibrary(name, args, variables, create_handlers=False)
positional, named = lib.positional_args, lib.named_args
lib = self._import_library(name, positional, named, lib)
if alias and name != alias:
lib = self._copy_library(lib, alias)
LOGGER.info("Imported library '%s' with name '%s'" % (name, alias))
return lib
def import_resource(self, path):
if path in self._resource_cache:
LOGGER.info("Found resource file '%s' from cache" % path)
else:
resource = ResourceFile(path)
self._resource_cache[path] = resource
return self._resource_cache[path]
def _import_library(self, name, positional, named, lib):
key = (name, positional, named)
if key in self._library_cache:
LOGGER.info("Found test library '%s' with arguments %s from cache"
% (name, utils.seq2str2(positional)))
return self._library_cache[key]
lib.create_handlers()
self._library_cache[key] = lib
libtype = lib.__class__.__name__.replace('Library', '').lower()[1:]
LOGGER.info("Imported library '%s' with arguments %s (version %s, "
"%s type, %s scope, %d keywords, source %s)"
% (name, utils.seq2str2(positional), lib.version, libtype,
lib.scope.lower(), len(lib), lib.source))
if len(lib) == 0:
LOGGER.warn("Imported library '%s' contains no keywords" % name)
return lib
def _copy_library(self, lib, newname):
libcopy = copy.copy(lib)
libcopy.name = newname
libcopy.init_scope_handling()
libcopy.handlers = utils.NormalizedDict(ignore=['_'])
for handler in lib.handlers.values():
handcopy = copy.copy(handler)
handcopy.library = libcopy
libcopy.handlers[handler.name] = handcopy
return libcopy
class ImportCache:
"""Keeps track on and optionally caches imported items.
Handles paths in keys case-insensitively on case-insensitive OSes.
Unlike dicts, this storage accepts mutable values in keys.
"""
def __init__(self):
self._keys = []
self._items = []
def __setitem__(self, key, item):
if not isinstance(key, (basestring, tuple)):
raise FrameworkError('Invalid key for ImportCache')
self._keys.append(self._norm_path_key(key))
self._items.append(item)
def add(self, key, item=None):
self.__setitem__(key, item)
def __getitem__(self, key):
key = self._norm_path_key(key)
if key not in self._keys:
raise KeyError
return self._items[self._keys.index(key)]
def __contains__(self, key):
return self._norm_path_key(key) in self._keys
def _norm_path_key(self, key):
if isinstance(key, tuple):
return tuple(self._norm_path_key(k) for k in key)
if isinstance(key, basestring) and os.path.exists(key):
return utils.normpath(key)
return key
| 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 inspect
from robot import utils
from robot.errors import DataError
from robot.common import BaseLibrary
from robot.output import LOGGER
from handlers import Handler, InitHandler, DynamicHandler
if utils.is_jython:
from org.python.core import PyReflectedFunction, PyReflectedConstructor
from java.lang import Object
else:
Object = None
def TestLibrary(name, args=None, variables=None, create_handlers=True):
libcode, source = utils.import_(name)
libclass = _get_lib_class(libcode)
lib = libclass(libcode, source, name, args or [], variables)
if create_handlers:
lib.create_handlers()
return lib
def _get_lib_class(libcode):
if inspect.ismodule(libcode):
return _ModuleLibrary
if _DynamicMethod(libcode, 'get_keyword_names'):
if _DynamicMethod(libcode, 'run_keyword'):
return _DynamicLibrary
else:
return _HybridLibrary
return _ClassLibrary
class _DynamicMethod(object):
def __init__(self, libcode, underscore_name, default=None):
self._method = self._get_method(libcode, underscore_name)
self._default = default
def __call__(self, *args):
if not self._method:
return self._default
try:
return self._method(*args)
except:
raise DataError("Calling dynamic method '%s' failed: %s"
% (self._method.__name__, utils.get_error_message()))
def __nonzero__(self):
return self._method is not None
def _get_method(self, libcode, underscore_name):
for name in underscore_name, self._getCamelCaseName(underscore_name):
method = getattr(libcode, name, None)
if callable(method):
return method
return None
def _getCamelCaseName(self, underscore_name):
tokens = underscore_name.split('_')
return ''.join([tokens[0]] + [t.capitalize() for t in tokens[1:]])
class _BaseTestLibrary(BaseLibrary):
supports_named_arguments = False # this attribute is for libdoc
_log_success = LOGGER.debug
_log_failure = LOGGER.info
_log_failure_details = LOGGER.debug
def __init__(self, libcode, source, name, args, variables):
if os.path.exists(name):
name = os.path.splitext(os.path.basename(os.path.abspath(name)))[0]
self.source = source
self.version = self._get_version(libcode)
self.name = name
self.orig_name = name # Stores original name also after copying
self.positional_args = []
self.named_args = {}
self._instance_cache = []
self._libinst = None
if libcode is not None:
self.doc = inspect.getdoc(libcode) or ''
self.scope = self._get_scope(libcode)
self._libcode = libcode
self.init = self._create_init_handler(libcode)
self.positional_args, self.named_args = self.init.arguments.resolve(args, variables)
def create_handlers(self):
if self._libcode:
self._libinst = self.get_instance()
self.handlers = self._create_handlers(self._libinst)
self.init_scope_handling()
def start_suite(self):
pass
def end_suite(self):
pass
def start_test(self):
pass
def end_test(self):
pass
def _get_version(self, code):
try:
return str(code.ROBOT_LIBRARY_VERSION)
except AttributeError:
try:
return str(code.__version__)
except AttributeError:
return '<unknown>'
def _create_init_handler(self, libcode):
init_method = getattr(libcode, '__init__', None)
if not self._valid_init(init_method):
init_method = None
return InitHandler(self, init_method)
def _valid_init(self, init_method):
if inspect.ismethod(init_method):
return True
if utils.is_jython and isinstance(init_method, PyReflectedConstructor):
return True
return False
def init_scope_handling(self):
if self.scope == 'GLOBAL':
return
self._libinst = None
self.start_suite = self._caching_start
self.end_suite = self._restoring_end
if self.scope == 'TESTCASE':
self.start_test = self._caching_start
self.end_test = self._restoring_end
def _caching_start(self):
self._instance_cache.append(self._libinst)
self._libinst = None
def _restoring_end(self):
self._libinst = self._instance_cache.pop()
def _get_scope(self, libcode):
try:
scope = libcode.ROBOT_LIBRARY_SCOPE
scope = utils.normalize(scope, ignore=['_']).upper()
except (AttributeError, TypeError):
scope = 'TESTCASE'
return scope if scope in ['GLOBAL','TESTSUITE'] else 'TESTCASE'
def get_instance(self):
if self._libinst is None:
self._libinst = self._get_instance()
return self._libinst
def _get_instance(self):
try:
return self._libcode(*self.positional_args, **self.named_args)
except:
self._raise_creating_instance_failed()
def _create_handlers(self, libcode):
handlers = utils.NormalizedDict(ignore=['_'])
for name in self._get_handler_names(libcode):
method = self._try_to_get_handler_method(libcode, name)
if method:
handler = self._try_to_create_handler(name, method)
if handler:
handlers[name] = handler
self._log_success("Created keyword '%s'" % handler.name)
return handlers
def _get_handler_names(self, libcode):
return [name for name in dir(libcode)
if not name.startswith(('_', 'ROBOT_LIBRARY_'))]
def _try_to_get_handler_method(self, libcode, name):
try:
return self._get_handler_method(libcode, name)
except:
self._report_adding_keyword_failed(name)
def _report_adding_keyword_failed(self, name):
msg, details = utils.get_error_details()
self._log_failure("Adding keyword '%s' to library '%s' failed: %s"
% (name, self.name, msg))
if details:
self._log_failure_details('Details:\n%s' % details)
def _get_handler_method(self, libcode, name):
method = getattr(libcode, name)
if not inspect.isroutine(method):
raise DataError('Not a method or function')
return method
def _try_to_create_handler(self, name, method):
try:
return self._create_handler(name, method)
except:
self._report_adding_keyword_failed(name)
def _create_handler(self, handler_name, handler_method):
return Handler(self, handler_name, handler_method)
def _raise_creating_instance_failed(self):
msg, details = utils.get_error_details()
if self.positional_args:
args = "argument%s %s" % (utils.plural_or_not(self.positional_args),
utils.seq2str(self.positional_args))
else:
args = "no arguments"
raise DataError("Creating an instance of the test library '%s' with %s "
"failed: %s\n%s" % (self.name, args, msg, details))
class _ClassLibrary(_BaseTestLibrary):
supports_named_arguments = True # this attribute is for libdoc
def _get_handler_method(self, libinst, name):
# Type is checked before using getattr to avoid calling properties,
# most importantly bean properties generated by Jython (issue 188).
for item in (libinst,) + inspect.getmro(libinst.__class__):
if item in (object, Object):
continue
if not (hasattr(item, '__dict__') and name in item.__dict__):
continue
self._validate_handler(item.__dict__[name])
return getattr(libinst, name)
raise DataError('No non-implicit implementation found')
def _validate_handler(self, handler):
if not self._is_routine(handler):
raise DataError('Not a method or function')
if self._is_implicit_java_or_jython_method(handler):
raise DataError('Implicit methods are ignored')
def _is_routine(self, handler):
# inspect.isroutine doesn't work with methods from Java classes
# prior to Jython 2.5.2: http://bugs.jython.org/issue1223
return inspect.isroutine(handler) or self._is_java_method(handler)
def _is_java_method(self, handler):
return utils.is_jython and isinstance(handler, PyReflectedFunction)
def _is_implicit_java_or_jython_method(self, handler):
if not self._is_java_method(handler):
return False
for signature in handler.argslist[:handler.nargs]:
cls = signature.declaringClass
if not (cls is Object or self._is_created_by_jython(handler, cls)):
return False
return True
def _is_created_by_jython(self, handler, cls):
proxy_methods = getattr(cls, '__supernames__', []) + ['classDictInit']
return handler.__name__ in proxy_methods
class _ModuleLibrary(_BaseTestLibrary):
supports_named_arguments = True # this attribute is for libdoc
def _get_scope(self, libcode):
return 'GLOBAL'
def _get_handler_method(self, libcode, name):
method = _BaseTestLibrary._get_handler_method(self, libcode, name)
if hasattr(libcode, '__all__') and name not in libcode.__all__:
raise DataError('Not exposed as a keyword')
return method
def get_instance(self):
self.init.arguments.check_arg_limits(self.positional_args)
return self._libcode
def _create_init_handler(self, libcode):
return InitHandler(self, None)
class _HybridLibrary(_BaseTestLibrary):
_log_failure = LOGGER.warn
def _get_handler_names(self, instance):
try:
return instance.get_keyword_names()
except AttributeError:
return instance.getKeywordNames()
class _DynamicLibrary(_BaseTestLibrary):
_log_failure = LOGGER.warn
def __init__(self, libcode, source, name, args, variables=None):
_BaseTestLibrary.__init__(self, libcode, source, name, args, variables)
self._get_kw_doc = \
_DynamicMethod(libcode, 'get_keyword_documentation', default='')
self._get_kw_args = \
_DynamicMethod(libcode, 'get_keyword_arguments', default=None)
def _get_handler_names(self, instance):
try:
return instance.get_keyword_names()
except AttributeError:
return instance.getKeywordNames()
def _get_handler_method(self, instance, name_is_ignored):
try:
return instance.run_keyword
except AttributeError:
return instance.runKeyword
def _create_handler(self, handler_name, handler_method):
doc = self._get_kw_doc(self._libinst, handler_name)
argspec = self._get_kw_args(self._libinst, handler_name)
return DynamicHandler(self, handler_name, handler_method, doc, argspec)
| 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
from robot.utils.robotthread import ThreadedRunner
from robot.errors import TimeoutError, DataError, FrameworkError
class _Timeout(object):
def __init__(self, timeout=None, message='', variables=None):
self.string = timeout or ''
self.message = message
self.secs = -1
self.starttime = -1
self.error = None
if variables:
self.replace_variables(variables)
@property
def type(self):
return type(self).__name__.replace('Timeout', ' timeout')
@property
def active(self):
return self.starttime > 0
def replace_variables(self, variables):
try:
self.string = variables.replace_string(self.string)
if not self.string or self.string.upper() == 'NONE':
return
self.secs = utils.timestr_to_secs(self.string)
self.string = utils.secs_to_timestr(self.secs)
self.message = variables.replace_string(self.message)
except (DataError, ValueError), err:
self.secs = 0.000001 # to make timeout active
self.error = 'Setting %s failed: %s' % (self.type.lower(), unicode(err))
def start(self):
if self.secs > 0:
self.starttime = time.time()
def time_left(self):
if not self.active:
return -1
elapsed = time.time() - self.starttime
# Timeout granularity is 1ms. Without rounding some timeout tests fail
# intermittently on Windows, probably due to threading.Event.wait().
return round(self.secs - elapsed, 3)
def timed_out(self):
return self.active and self.time_left() <= 0
def __str__(self):
return self.string
def __cmp__(self, other):
return cmp(not self.active, not other.active) \
or cmp(self.time_left(), other.time_left())
def run(self, runnable, args=None, kwargs=None):
if self.error:
raise DataError(self.error)
if not self.active:
raise FrameworkError('Timeout is not active')
timeout = self.time_left()
if timeout <= 0:
raise TimeoutError(self.get_message())
runner = ThreadedRunner(runnable, args, kwargs)
if runner.run_in_thread(timeout):
return runner.get_result()
try:
runner.stop_thread()
except:
raise TimeoutError('Stopping keyword after %s failed: %s'
% (self.type.lower(), utils.get_error_message()))
raise TimeoutError(self._get_timeout_error())
def get_message(self):
if not self.active:
return '%s not active.' % self.type
if not self.timed_out():
return '%s %s active. %s seconds left.' % (self.type, self.string,
self.time_left())
return self._get_timeout_error()
def _get_timeout_error(self):
if self.message:
return self.message
return '%s %s exceeded.' % (self.type, self.string)
class TestTimeout(_Timeout):
_keyword_timeouted = False
def set_keyword_timeout(self, timeout_occurred):
self._keyword_timeouted = self._keyword_timeouted or timeout_occurred
def any_timeout_occurred(self):
return self.timed_out() or self._keyword_timeouted
class KeywordTimeout(_Timeout):
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 import utils
from robot.errors import (DataError, ExecutionFailed, ExecutionFailures,
HandlerExecutionFailed)
from robot.common import BaseKeyword
from robot.variables import is_list_var, is_scalar_var
class Keywords(object):
def __init__(self, steps, template=None):
self._keywords = []
self._templated = template and template.upper() != 'NONE'
if self._templated:
steps = [s.apply_template(template) for s in steps]
for s in steps:
self._add_step(s, template)
def _add_step(self, step, template):
if step.is_comment():
return
if step.is_for_loop():
keyword = ForLoop(step, template)
else:
keyword = Keyword(step.keyword, step.args, step.assign)
self.add_keyword(keyword)
def add_keyword(self, keyword):
self._keywords.append(keyword)
def run(self, context):
errors = []
for kw in self._keywords:
try:
kw.run(context)
except ExecutionFailed, err:
errors.extend(err.get_errors())
if not err.can_continue(context.teardown, self._templated,
context.dry_run):
break
if errors:
raise ExecutionFailures(errors)
def __nonzero__(self):
return bool(self._keywords)
def __iter__(self):
return iter(self._keywords)
class Keyword(BaseKeyword):
def __init__(self, name, args, assign=None, type='kw'):
BaseKeyword.__init__(self, name, args, type=type)
self.assign = assign or []
self.handler_name = name
def run(self, context):
handler = self._start(context)
try:
return_value = self._run(handler, context)
except ExecutionFailed, err:
self.status = 'FAIL' if not err.exit_for_loop else 'PASS'
self._end(context, error=err)
raise
else:
if not (context.dry_run and handler.type == 'library'):
self.status = 'PASS'
self._end(context, return_value)
return return_value
def _start(self, context):
handler = context.get_handler(self.handler_name)
handler.init_keyword(context.get_current_vars())
self.name = self._get_name(handler.longname)
self.doc = handler.shortdoc
self.timeout = getattr(handler, 'timeout', '')
self.starttime = utils.get_timestamp()
context.start_keyword(self)
if self.doc.startswith('*DEPRECATED*'):
msg = self.doc.replace('*DEPRECATED*', '', 1).strip()
name = self.name.split('} = ', 1)[-1] # Remove possible variable
context.warn("Keyword '%s' is deprecated. %s" % (name, msg))
return handler
def _get_name(self, handler_longname):
if not self.assign:
return handler_longname
return '%s = %s' % (', '.join(a.rstrip('= ') for a in self.assign),
handler_longname)
def _run(self, handler, context):
try:
return handler.run(context, self.args[:])
except ExecutionFailed:
raise
except:
self._report_failure(context)
def _end(self, context, return_value=None, error=None):
self.endtime = utils.get_timestamp()
self.elapsedtime = utils.get_elapsed_time(self.starttime, self.endtime)
try:
if not error or error.can_continue(context.teardown):
self._set_variables(context, return_value)
finally:
context.end_keyword(self)
def _set_variables(self, context, return_value):
try:
_VariableAssigner(self.assign).assign(context, return_value)
except DataError, err:
self.status = 'FAIL'
msg = unicode(err)
context.output.fail(msg)
raise ExecutionFailed(msg, syntax=True)
def _report_failure(self, context):
failure = HandlerExecutionFailed()
if not failure.exit_for_loop:
context.output.fail(failure.full_message)
if failure.traceback:
context.output.debug(failure.traceback)
raise failure
class _VariableAssigner(object):
def __init__(self, assign):
ap = _AssignParser(assign)
self.scalar_vars = ap.scalar_vars
self.list_var = ap.list_var
def assign(self, context, return_value):
context.trace('Return: %s' % utils.safe_repr(return_value))
if not (self.scalar_vars or self.list_var):
return
for name, value in self._get_vars_to_set(return_value):
context.get_current_vars()[name] = value
context.output.info(utils.format_assign_message(name, value))
def _get_vars_to_set(self, ret):
if ret is None:
return self._get_vars_to_set_when_ret_is_none()
if not self.list_var:
return self._get_vars_to_set_with_only_scalars(ret)
if self._is_non_string_iterable(ret):
return self._get_vars_to_set_with_scalars_and_list(list(ret))
self._raise_invalid_return_value(ret, wrong_type=True)
def _is_non_string_iterable(self, value):
if isinstance(value, basestring):
return False
try:
iter(value)
except TypeError:
return False
else:
return True
def _get_vars_to_set_when_ret_is_none(self):
ret = [ (var, None) for var in self.scalar_vars ]
if self.list_var:
ret.append((self.list_var, []))
return ret
def _get_vars_to_set_with_only_scalars(self, ret):
needed = len(self.scalar_vars)
if needed == 1:
return [(self.scalar_vars[0], ret)]
if not self._is_non_string_iterable(ret):
self._raise_invalid_return_value(ret, wrong_type=True)
ret = list(ret)
if len(ret) < needed:
self._raise_invalid_return_value(ret)
if len(ret) == needed:
return zip(self.scalar_vars, ret)
return zip(self.scalar_vars[:-1], ret) \
+ [(self.scalar_vars[-1], ret[needed-1:])]
def _get_vars_to_set_with_scalars_and_list(self, ret):
needed_scalars = len(self.scalar_vars)
if needed_scalars == 0:
return [(self.list_var, ret)]
if len(ret) < needed_scalars:
self._raise_invalid_return_value(ret)
return zip(self.scalar_vars, ret) \
+ [(self.list_var, ret[needed_scalars:])]
def _raise_invalid_return_value(self, ret, wrong_type=False):
if wrong_type:
err = 'Expected list-like object, got %s instead' \
% type(ret).__name__
else:
err = 'Need more values than %d' % len(ret)
raise DataError("Cannot assign return values: %s." % err)
class _AssignParser(object):
def __init__(self, assign):
self.scalar_vars = []
self.list_var = None
self._assign_mark_used = False
for var in assign:
self._verify_items_allowed_only_on_last_round()
var = self._strip_possible_assign_mark(var)
self._set(var)
def _verify_items_allowed_only_on_last_round(self):
if self._assign_mark_used:
raise DataError("Assign mark '=' can be used only with the last variable.")
if self.list_var:
raise DataError('Only the last variable to assign can be a list variable.')
def _strip_possible_assign_mark(self, variable):
if not variable.endswith('='):
return variable
self._assign_mark_used = True
return variable.rstrip('= ')
def _set(self, variable):
if is_scalar_var(variable):
self.scalar_vars.append(variable)
elif is_list_var(variable):
self.list_var = variable
else:
raise DataError('Invalid variable to assign: %s' % variable)
class ForLoop(BaseKeyword):
def __init__(self, forstep, template=None):
BaseKeyword.__init__(self, self._get_name(forstep), type='for')
self.vars = forstep.vars
self.items = forstep.items
self.range = forstep.range
self.keywords = Keywords(forstep.steps, template)
self._templated = bool(template)
def _get_name(self, data):
return '%s %s [ %s ]' % (' | '.join(data.vars),
'IN' if not data.range else 'IN RANGE',
' | '.join(data.items))
def run(self, context):
self.starttime = utils.get_timestamp()
context.output.start_keyword(self)
try:
self._validate()
self._run(context)
except ExecutionFailed, err:
error = err
except DataError, err:
msg = unicode(err)
context.output.fail(msg)
error = ExecutionFailed(msg, syntax=True)
else:
error = None
self.status = 'PASS' if not error else 'FAIL'
self.endtime = utils.get_timestamp()
self.elapsedtime = utils.get_elapsed_time(self.starttime, self.endtime)
context.output.end_keyword(self)
if error:
raise error
def _validate(self):
if not self.vars:
raise DataError('FOR loop has no loop variables.')
for var in self.vars:
if not is_scalar_var(var):
raise DataError("Invalid FOR loop variable '%s'." % var)
if not self.items:
raise DataError('FOR loop has no loop values.')
if not self.keywords:
raise DataError('FOR loop contains no keywords.')
def _run(self, context):
errors = []
items, iteration_steps = self._get_items_and_iteration_steps(context)
for i in iteration_steps:
values = items[i:i+len(self.vars)]
err = self._run_one_round(context, self.vars, values)
if err:
if err.exit_for_loop:
break
errors.extend(err.get_errors())
if not err.can_continue(context.teardown, self._templated,
context.dry_run):
break
if errors:
raise ExecutionFailures(errors)
def _get_items_and_iteration_steps(self, context):
if context.dry_run:
return self.vars, [0]
items = self._replace_vars_from_items(context.get_current_vars())
return items, range(0, len(items), len(self.vars))
def _run_one_round(self, context, variables, values):
foritem = _ForItem(variables, values)
context.output.start_keyword(foritem)
for var, value in zip(variables, values):
context.get_current_vars()[var] = value
try:
self.keywords.run(context)
except ExecutionFailed, err:
error = err
else:
error = None
foritem.end('PASS' if not error or error.exit_for_loop else 'FAIL')
context.output.end_keyword(foritem)
return error
def _replace_vars_from_items(self, variables):
items = variables.replace_list(self.items)
if self.range:
items = self._get_range_items(items)
if len(items) % len(self.vars) == 0:
return items
raise DataError('Number of FOR loop values should be multiple of '
'variables. Got %d variables but %d value%s.'
% (len(self.vars), len(items), utils.plural_or_not(items)))
def _get_range_items(self, items):
try:
items = [ self._to_int(item) for item in items ]
except:
raise DataError('Converting argument of FOR IN RANGE failed: %s'
% utils.get_error_message())
if not 1 <= len(items) <= 3:
raise DataError('FOR IN RANGE expected 1-3 arguments, '
'got %d instead.' % len(items))
return range(*items)
def _to_int(self, item):
return int(eval(str(item)))
class _ForItem(BaseKeyword):
def __init__(self, vars, items):
name = ', '.join(utils.format_assign_message(var, item)
for var, item in zip(vars, items))
BaseKeyword.__init__(self, name, type='foritem')
self.starttime = utils.get_timestamp()
def end(self, status):
self.status = status
self.endtime = utils.get_timestamp()
self.elapsedtime = utils.get_elapsed_time(self.starttime, self.endtime)
| 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 VariableSplitter:
def __init__(self, string, identifiers):
self.identifier = None
self.base = None
self.index = None
self.start = -1
self.end = -1
self._identifiers = identifiers
self._may_have_internal_variables = False
try:
self._split(string)
except ValueError:
pass
else:
self._finalize()
def get_replaced_base(self, variables):
if self._may_have_internal_variables:
return variables.replace_string(self.base)
return self.base
def _finalize(self):
self.identifier = self._variable_chars[0]
self.base = ''.join(self._variable_chars[2:-1])
self.end = self.start + len(self._variable_chars)
if self._has_list_variable_index():
self.index = ''.join(self._list_variable_index_chars[1:-1])
self.end += len(self._list_variable_index_chars)
def _has_list_variable_index(self):
return self._list_variable_index_chars \
and self._list_variable_index_chars[-1] == ']'
def _split(self, string):
start_index, max_index = self._find_variable(string)
self.start = start_index
self._open_curly = 1
self._state = self._variable_state
self._variable_chars = [string[start_index], '{']
self._list_variable_index_chars = []
self._string = string
start_index += 2
for index, char in enumerate(string[start_index:]):
index += start_index # Giving start to enumerate only in Py 2.6+
try:
self._state(char, index)
except StopIteration:
return
if index == max_index and not self._scanning_list_variable_index():
return
def _scanning_list_variable_index(self):
return self._state in [self._waiting_list_variable_index_state,
self._list_variable_index_state]
def _find_variable(self, string):
max_end_index = string.rfind('}')
if max_end_index == -1:
return ValueError('No variable end found')
if self._is_escaped(string, max_end_index):
return self._find_variable(string[:max_end_index])
start_index = self._find_start_index(string, 1, max_end_index)
if start_index == -1:
return ValueError('No variable start found')
return start_index, max_end_index
def _find_start_index(self, string, start, end):
index = string.find('{', start, end) - 1
if index < 0:
return -1
if self._start_index_is_ok(string, index):
return index
return self._find_start_index(string, index+2, end)
def _start_index_is_ok(self, string, index):
return string[index] in self._identifiers \
and not self._is_escaped(string, index)
def _is_escaped(self, string, index):
escaped = False
while index > 0 and string[index-1] == '\\':
index -= 1
escaped = not escaped
return escaped
def _variable_state(self, char, index):
self._variable_chars.append(char)
if char == '}' and not self._is_escaped(self._string, index):
self._open_curly -= 1
if self._open_curly == 0:
if not self._is_list_variable():
raise StopIteration
self._state = self._waiting_list_variable_index_state
elif char in self._identifiers:
self._state = self._internal_variable_start_state
def _is_list_variable(self):
return self._variable_chars[0] == '@'
def _internal_variable_start_state(self, char, index):
self._state = self._variable_state
if char == '{':
self._variable_chars.append(char)
self._open_curly += 1
self._may_have_internal_variables = True
else:
self._variable_state(char, index)
def _waiting_list_variable_index_state(self, char, index):
if char != '[':
raise StopIteration
self._list_variable_index_chars.append(char)
self._state = self._list_variable_index_state
def _list_variable_index_state(self, char, index):
self._list_variable_index_chars.append(char)
if char == ']':
raise StopIteration
| 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
import os
from UserDict import UserDict
if os.name == 'java':
from java.lang.System import getProperty as getJavaSystemProperty
from java.util import Map
else:
class Map: pass
getJavaSystemProperty = lambda name: None
from robot import utils
from robot.errors import DataError
from robot.output import LOGGER
from isvar import is_var, is_scalar_var
from variablesplitter import VariableSplitter
class Variables(utils.NormalizedDict):
"""Represents a set of variables including both ${scalars} and @{lists}.
Contains methods for replacing variables from list, scalars, and strings.
On top of ${scalar} and @{list} variables these methods handle also
%{environment} variables.
"""
_extended_var_re = re.compile(r'''
^\${ # start of the string and "${"
(.+?) # base name (group 1)
([^\s\w].+) # extended part (group 2)
}$ # "}" and end of the string
''', re.VERBOSE)
def __init__(self, identifiers=['$','@','%','&','*']):
utils.NormalizedDict.__init__(self, ignore=['_'])
self._identifiers = identifiers
def __setitem__(self, name, value, path=None):
self._validate_var_name(name)
utils.NormalizedDict.__setitem__(self, name, value)
def update(self, dict=None, **kwargs):
if dict:
self._validate_var_dict(dict)
UserDict.update(self, dict)
for key in dict:
self._add_key(key)
if kwargs:
self.update(kwargs)
def __getitem__(self, name):
self._validate_var_name(name)
try: return utils.NormalizedDict.__getitem__(self, name)
except KeyError:
try: return self._get_number_var(name)
except ValueError:
try: return self._get_list_var_as_scalar(name)
except ValueError:
try: return self._get_extended_var(name)
except ValueError:
raise DataError("Non-existing variable '%s'." % name)
def _validate_var_name(self, name):
if not is_var(name):
raise DataError("Invalid variable name '%s'." % name)
def _validate_var_dict(self, dict):
for name in dict:
self._validate_var_name(name)
def _get_list_var_as_scalar(self, name):
if is_scalar_var(name):
try:
return self['@'+name[1:]]
except DataError:
pass
raise ValueError
def _get_extended_var(self, name):
err_pre = "Resolving variable '%s' failed: " % name
res = self._extended_var_re.search(name)
if res is None:
raise ValueError
base_name = res.group(1)
expression = res.group(2)
try:
variable = self['${%s}' % base_name]
except DataError, err:
raise DataError(err_pre + unicode(err))
try:
return eval('_BASE_VAR_' + expression, {'_BASE_VAR_': variable})
except:
raise DataError(err_pre + utils.get_error_message())
def _get_number_var(self, name):
if name[0] != '$':
raise ValueError
number = self._normalize(name)[2:-1]
try:
return self._get_int_var(number)
except ValueError:
return float(number)
def _get_int_var(self, number):
bases = {'0b': 2, '0o': 8, '0x': 16}
if number.startswith(tuple(bases)):
return int(number[2:], bases[number[:2]])
return int(number)
def replace_list(self, items):
"""Replaces variables from a list of items.
If an item in a list is a @{list} variable its value is returned.
Possible variables from other items are replaced using 'replace_scalar'.
Result is always a list.
"""
results = []
for item in items or []:
listvar = self._replace_variables_inside_possible_list_var(item)
if listvar:
results.extend(self[listvar])
else:
results.append(self.replace_scalar(item))
return results
def _replace_variables_inside_possible_list_var(self, item):
if not (isinstance(item, basestring)
and item.startswith('@{') and item.endswith('}')):
return None
var = VariableSplitter(item, self._identifiers)
if var.start != 0 or var.end != len(item):
return None
return '@{%s}' % var.get_replaced_base(self)
def replace_scalar(self, item):
"""Replaces variables from a scalar item.
If the item is not a string it is returned as is. If it is a ${scalar}
variable its value is returned. Otherwise variables are replaced with
'replace_string'. Result may be any object.
"""
if self._cannot_have_variables(item):
return utils.unescape(item)
var = VariableSplitter(item, self._identifiers)
if var.identifier and var.base and \
var.start == 0 and var.end == len(item):
return self._get_variable(var)
return self.replace_string(item, var)
def _cannot_have_variables(self, item):
return (not isinstance(item, basestring)) or '{' not in item
def replace_string(self, string, splitted=None, ignore_errors=False):
"""Replaces variables from a string. Result is always a string."""
if self._cannot_have_variables(string):
return utils.unescape(string)
result = []
if splitted is None:
splitted = VariableSplitter(string, self._identifiers)
while True:
if splitted.identifier is None:
result.append(utils.unescape(string))
break
result.append(utils.unescape(string[:splitted.start]))
try:
value = self._get_variable(splitted)
except DataError:
if not ignore_errors:
raise
value = string[splitted.start:splitted.end]
if not isinstance(value, basestring):
value = utils.unic(value)
result.append(value)
string = string[splitted.end:]
splitted = VariableSplitter(string, self._identifiers)
result = ''.join(result)
return result
def _get_variable(self, var):
"""'var' is an instance of a VariableSplitter"""
# 1) Handle reserved syntax
if var.identifier not in ['$','@','%']:
value = '%s{%s}' % (var.identifier, var.base)
LOGGER.warn("Syntax '%s' is reserved for future use. Please "
"escape it like '\\%s'." % (value, value))
return value
# 2) Handle environment variables and Java system properties
elif var.identifier == '%':
name = var.get_replaced_base(self).strip()
if name == '':
return '%%{%s}' % var.base
try:
return os.environ[name]
except KeyError:
property = getJavaSystemProperty(name)
if property:
return property
raise DataError("Environment variable '%s' does not exist" % name)
# 3) Handle ${scalar} variables and @{list} variables without index
elif var.index is None:
name = '%s{%s}' % (var.identifier, var.get_replaced_base(self))
return self[name]
# 4) Handle items from list variables e.g. @{var}[1]
else:
try:
index = int(self.replace_string(var.index))
name = '@{%s}' % var.get_replaced_base(self)
return self[name][index]
except (ValueError, DataError, IndexError):
raise DataError("Non-existing variable '@{%s}[%s]'"
% (var.base, var.index))
def set_from_file(self, path, args, overwrite=False):
LOGGER.info("Importing varible file '%s' with args %s" % (path, args))
args = args or []
try:
module = utils.simple_import(path)
variables = self._get_variables_from_module(module, args)
self._set_from_file(variables, overwrite, path)
except:
amsg = args and 'with arguments %s ' % utils.seq2str2(args) or ''
raise DataError("Processing variable file '%s' %sfailed: %s"
% (path, amsg, utils.get_error_message()))
return variables
# This can be used with variables got from set_from_file directly to
# prevent importing same file multiple times
def _set_from_file(self, variables, overwrite, path):
list_prefix = 'LIST__'
for name, value in variables:
if name.startswith(list_prefix):
name = '@{%s}' % name[len(list_prefix):]
try:
if isinstance(value, basestring):
raise TypeError
value = list(value)
except TypeError:
raise DataError("List variable '%s' cannot get a non-list "
"value '%s'" % (name, utils.unic(value)))
else:
name = '${%s}' % name
if overwrite or not utils.NormalizedDict.has_key(self, name):
self.__setitem__(name, value, path)
def set_from_variable_table(self, variable_table):
for variable in variable_table:
try:
name, value = self._get_var_table_name_and_value(variable.name,
variable.value,
variable_table.source)
# self.has_key would also match if name matches extended syntax
if not utils.NormalizedDict.has_key(self, name):
self.__setitem__(name, value, variable_table.source)
except DataError, err:
variable_table.report_invalid_syntax("Setting variable '%s' failed: %s"
% (variable.name, unicode(err)))
def _get_var_table_name_and_value(self, name, value, path=None):
self._validate_var_name(name)
value = [ self._unescape_leading_trailing_spaces(cell) for cell in value ]
if name[0] == '@':
return name, self.replace_list(value)
return name, self._get_var_table_scalar_value(name, value, path)
def _unescape_leading_trailing_spaces(self, item):
if item.endswith(' \\'):
item = item[:-1]
if item.startswith('\\ '):
item = item[1:]
return item
def _get_var_table_scalar_value(self, name, value, path=None):
if len(value) == 1:
return self.replace_scalar(value[0])
msg = ("Creating a scalar variable with a list value in the Variable "
"table is deprecated and this functionality will be removed in "
"Robot Framework 2.7. Create a list variable '@%s' and use "
"it as a scalar variable '%s' instead" % (name[1:], name))
if path:
msg += " in file '%s'" % path
LOGGER.warn(msg + '.')
return self.replace_list(value)
def _get_variables_from_module(self, module, args):
variables = self._get_dynamical_variables(module, args)
if variables is not None:
return variables
names = [ attr for attr in dir(module) if not attr.startswith('_') ]
try:
names = [ name for name in names if name in module.__all__ ]
except AttributeError:
pass
return [ (name, getattr(module, name)) for name in names ]
def _get_dynamical_variables(self, module, args):
try:
try:
get_variables = getattr(module, 'get_variables')
except AttributeError:
get_variables = getattr(module, 'getVariables')
except AttributeError:
return None
variables = get_variables(*args)
if isinstance(variables, (dict, UserDict)):
return variables.items()
if isinstance(variables, Map):
return [(entry.key, entry.value) for entry in variables.entrySet()]
raise DataError("Expected mapping but %s returned %s."
% (get_variables.__name__, type(variables).__name__))
def has_key(self, key):
try:
self[key]
except DataError:
return False
else:
return True
__contains__ = has_key
| 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.
def is_var(string):
if not isinstance(string, basestring):
return False
length = len(string)
return length > 3 and string[0] in ['$','@'] and string.rfind('{') == 1 \
and string.find('}') == length - 1
def is_scalar_var(string):
return is_var(string) and string[0] == '$'
def is_list_var(string):
return is_var(string) and string[0] == '@'
| 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 tempfile
from robot import utils
from robot.output import LOGGER
from variables import Variables
from variablesplitter import VariableSplitter
from isvar import is_var, is_scalar_var, is_list_var
GLOBAL_VARIABLES = Variables()
def init_global_variables(settings):
_set_cli_vars(settings)
for name, value in [ ('${TEMPDIR}', utils.abspath(tempfile.gettempdir())),
('${EXECDIR}', utils.abspath('.')),
('${/}', os.sep),
('${:}', os.pathsep),
('${SPACE}', ' '),
('${EMPTY}', ''),
('${True}', True),
('${False}', False),
('${None}', None),
('${null}', None),
('${OUTPUT_DIR}', settings['OutputDir']),
('${OUTPUT_FILE}', settings['Output']),
('${SUMMARY_FILE}', settings['Summary']),
('${REPORT_FILE}', settings['Report']),
('${LOG_FILE}', settings['Log']),
('${DEBUG_FILE}', settings['DebugFile']),
('${PREV_TEST_NAME}', ''),
('${PREV_TEST_STATUS}', ''),
('${PREV_TEST_MESSAGE}', '') ]:
GLOBAL_VARIABLES[name] = value
def _set_cli_vars(settings):
for path, args in settings['VariableFiles']:
try:
GLOBAL_VARIABLES.set_from_file(path, args)
except:
msg, details = utils.get_error_details()
LOGGER.error(msg)
LOGGER.info(details)
for varstr in settings['Variables']:
try:
name, value = varstr.split(':', 1)
except ValueError:
name, value = varstr, ''
GLOBAL_VARIABLES['${%s}' % 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.
"""Module that adds directories needed by Robot to sys.path when imported."""
import sys
import os
import fnmatch
def add_path(path, to_beginning=False, force=False):
if _should_be_added(path, force):
if to_beginning:
sys.path.insert(0, path)
else:
sys.path.append(path)
def remove_path(path):
path = _normpath(path)
sys.path = [p for p in sys.path if _normpath(p) != path]
def _should_be_added(path, force):
if (not path) or _find_in_syspath_normalized(path):
return False
return force or os.path.exists(path)
def _find_in_syspath_normalized(path):
path = _normpath(path)
for element in sys.path:
if _normpath(element) == path:
return element
return None
def _normpath(path):
return os.path.normcase(os.path.normpath(path))
ROBOTDIR = os.path.dirname(os.path.abspath(__file__))
PARENTDIR = os.path.dirname(ROBOTDIR)
add_path(os.path.join(ROBOTDIR, 'libraries'), to_beginning=True,
force=True)
add_path(PARENTDIR, to_beginning=True)
# Handles egg installations
if fnmatch.fnmatchcase(os.path.basename(PARENTDIR), 'robotframework-*.egg'):
add_path(os.path.dirname(PARENTDIR), to_beginning=True)
# Remove ROBOTDIR dir to disallow importing robot internal modules directly
remove_path(ROBOTDIR)
# Elements from PYTHONPATH. By default it is not processed in Jython and in
# Python valid non-absolute paths may be ignored.
PYPATH = os.environ.get('PYTHONPATH')
if PYPATH:
for path in PYPATH.split(os.pathsep):
add_path(path)
del path
# Current dir (it seems to be in Jython by default so let's be consistent)
add_path('.')
del _find_in_syspath_normalized, _normpath, add_path, remove_path, ROBOTDIR, PARENTDIR, PYPATH
| 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 threading
class Thread(threading.Thread):
"""A subclass of threading.Thread, with a stop() method.
Original version posted by Connelly Barnes to python-list and available at
http://mail.python.org/pipermail/python-list/2004-May/219465.html
This version mainly has kill() changed to stop() to match java.lang.Thread.
This is a hack but seems to be the best way the get this done. Only used
in Python because in Jython we can use java.lang.Thread.
"""
def __init__(self, runner):
threading.Thread.__init__(self, target=runner)
self._stopped = False
def start(self):
self.__run_backup = self.run
self.run = self.__run
threading.Thread.start(self)
def stop(self):
self._stopped = True
def __run(self):
"""Hacked run function, which installs the trace."""
sys.settrace(self._globaltrace)
self.__run_backup()
self.run = self.__run_backup
def _globaltrace(self, frame, why, arg):
if why == 'call':
return self._localtrace
else:
return None
def _localtrace(self, frame, why, arg):
if self._stopped:
if why == 'line':
raise SystemExit()
return self._localtrace
| 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 unic import unic
def html_escape(text, formatting=False):
# TODO: Remove formatting attribute after RIDE does not use it anymore
if formatting:
return html_format(text)
return _HtmlEscaper().format(text)
def html_format(text):
return _HtmlFormatter().format(text)
def html_attr_escape(attr):
for name, value in [('&', '&'), ('"', '"'),
('<', '<'), ('>', '>')]:
attr = attr.replace(name, value)
for wspace in ['\n', '\r', '\t']:
attr = attr.replace(wspace, ' ')
return attr
class _Formatter(object):
def format(self, text):
text = self._html_escape(unic(text))
for line in text.splitlines():
self.add_line(line)
return self.get_result()
def _html_escape(self, text):
for name, value in [('&', '&'), ('<', '<'), ('>', '>')]:
text = text.replace(name, value)
return text
class _HtmlEscaper(_Formatter):
def __init__(self):
self._lines = []
self._line_formatter = _UrlFormatter()
def add_line(self, line):
self._lines.append(self._line_formatter.format(line))
def get_result(self):
return '\n'.join(self._lines)
class _HtmlFormatter(_Formatter):
_hr_re = re.compile('^-{3,} *$')
def __init__(self):
self._result = _Formatted()
self._table = _TableFormatter()
self._line_formatter = _LineFormatter()
def add_line(self, line):
if self._add_table_row(line):
return
if self._table.is_started():
self._result.add(self._table.end(), join_after=False)
if self._is_hr(line):
self._result.add('<hr />\n', join_after=False)
return
self._result.add(self._line_formatter.format(line))
def _add_table_row(self, row):
if self._table.is_table_row(row):
self._table.add_row(row)
return True
return False
def _is_hr(self, line):
return bool(self._hr_re.match(line))
def get_result(self):
if self._table.is_started():
self._result.add(self._table.end())
return self._result.get_result()
class _Formatted(object):
def __init__(self):
self._result = []
self._joiner = ''
def add(self, line, join_after=True):
self._result.extend([self._joiner, line])
self._joiner = '\n' if join_after else ''
def get_result(self):
return ''.join(self._result)
class _UrlFormatter(object):
_formatting = False
_image_exts = ('.jpg', '.jpeg', '.png', '.gif', '.bmp')
_url = re.compile('''
( (^|\ ) ["'([]* ) # begin of line or space and opt. any char "'([
(\w{3,9}://[\S]+?) # url (protocol is any alphanum 3-9 long string)
(?= [])"'.,!?:;]* ($|\ ) ) # opt. any char ])"'.,!?:; and end of line or space
''', re.VERBOSE)
def format(self, line):
return self._format_url(line)
def _format_url(self, line):
return self._url.sub(self._repl_url, line) if ':' in line else line
def _repl_url(self, match):
pre = match.group(1)
url = match.group(3).replace('"', '"')
if self._format_as_image(url):
tmpl = '<img src="%s" title="%s" style="border: 1px solid gray" />'
else:
tmpl = '<a href="%s">%s</a>'
return pre + tmpl % (url, url)
def _format_as_image(self, url):
return self._formatting and url.lower().endswith(self._image_exts)
class _LineFormatter(_UrlFormatter):
_formatting = True
_bold = re.compile('''
( # prefix (group 1)
(^|\ ) # begin of line or space
["'(]* _? # optionally any char "'( and optional begin of italic
) #
\* # start of bold
([^\ ].*?) # no space and then anything (group 3)
\* # end of bold
(?= # start of postfix (non-capturing group)
_? ["').,!?:;]* # optional end of italic and any char "').,!?:;
($|\ ) # end of line or space
)
''', re.VERBOSE)
_italic = re.compile('''
( (^|\ ) ["'(]* ) # begin of line or space and opt. any char "'(
_ # start of italic
([^\ _].*?) # no space or underline and then anything
_ # end of italic
(?= ["').,!?:;]* ($|\ ) ) # opt. any char "').,!?:; and end of line or space
''', re.VERBOSE)
def format(self, line):
return self._format_url(self._format_italic(self._format_bold(line)))
def _format_bold(self, line):
return self._bold.sub('\\1<b>\\3</b>', line) if '*' in line else line
def _format_italic(self, line):
return self._italic.sub('\\1<i>\\3</i>', line) if '_' in line else line
class _TableFormatter(object):
_is_table_line = re.compile('^\s*\| (.* |)\|\s*$')
_line_splitter = re.compile(' \|(?= )')
def __init__(self):
self._rows = []
self._line_formatter = _LineFormatter()
def is_table_row(self, row):
return bool(self._is_table_line.match(row))
def is_started(self):
return bool(self._rows)
def add_row(self, text):
text = text.strip()[1:-1] # remove outer whitespace and pipes
cells = [cell.strip() for cell in self._line_splitter.split(text)]
self._rows.append(cells)
def end(self):
ret = self._format_table(self._rows)
self._rows = []
return ret
def _format_table(self, rows):
maxlen = max(len(row) for row in rows)
table = ['<table border="1" class="doc">']
for row in rows:
row += [''] * (maxlen - len(row)) # fix ragged tables
table.append('<tr>')
table.extend(['<td>%s</td>' % self._line_formatter.format(cell)
for cell in row])
table.append('</tr>')
table.append('</table>\n')
return '\n'.join(table)
| 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
from unic import unic
def decode_output(string):
"""Decodes string from console encoding to Unicode."""
if _output_encoding:
return unic(string, _output_encoding)
return string
def encode_output(string, errors='replace'):
"""Encodes string from Unicode to console encoding."""
# http://ironpython.codeplex.com/workitem/29487
if sys.platform == 'cli':
return string
return string.encode(_output_encoding, errors)
def decode_from_file_system(string):
"""Decodes path from file system to Unicode."""
encoding = sys.getfilesystemencoding()
if sys.platform.startswith('java'):
# http://bugs.jython.org/issue1592
from java.lang import String
string = String(string)
return unic(string, encoding) if encoding else unic(string)
def _get_output_encoding():
# Jython is buggy on Windows: http://bugs.jython.org/issue1568
if os.sep == '\\' and sys.platform.startswith('java'):
return 'cp437' # Default DOS encoding
encoding = _get_encoding_from_std_streams()
if encoding:
return encoding
if os.sep == '/':
return _read_encoding_from_unix_env()
return 'cp437' # Default DOS encoding
def _get_encoding_from_std_streams():
# Stream may not have encoding attribute if it is intercepted outside RF
# in Python. Encoding is None if process's outputs are redirected.
return getattr(sys.__stdout__, 'encoding', None) \
or getattr(sys.__stderr__, 'encoding', None) \
or getattr(sys.__stdin__, 'encoding', None)
def _read_encoding_from_unix_env():
for name in 'LANG', 'LC_CTYPE', 'LANGUAGE', 'LC_ALL':
try:
# Encoding can be in format like `UTF-8` or `en_US.UTF-8`
encoding = os.environ[name].split('.')[-1]
'testing that encoding is valid'.encode(encoding)
except (KeyError, LookupError):
pass
else:
return encoding
return 'ascii'
_output_encoding = _get_output_encoding()
| 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 java.io import FileOutputStream
from javax.xml.transform.sax import SAXTransformerFactory
from javax.xml.transform.stream import StreamResult
from org.xml.sax.helpers import AttributesImpl
from abstractxmlwriter import AbstractXmlWriter
class XmlWriter(AbstractXmlWriter):
def __init__(self, path):
self.path = path
self._output = FileOutputStream(path)
self._writer = SAXTransformerFactory.newInstance().newTransformerHandler()
self._writer.setResult(StreamResult(self._output))
self._writer.startDocument()
self.content('\n')
self.closed = False
def _start(self, name, attrs):
self._writer.startElement('', '', name, self._get_attrs_impl(attrs))
def _get_attrs_impl(self, attrs):
ai = AttributesImpl()
for name, value in attrs.items():
ai.addAttribute('', '', name, '', value)
return ai
def _content(self, content):
self._writer.characters(content, 0, len(content))
def _end(self, name):
self._writer.endElement('', '', name)
| 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
import sys
import re
import traceback
from unic import unic
from robot.errors import DataError, TimeoutError, RemoteError
RERAISED_EXCEPTIONS = (KeyboardInterrupt, SystemExit, MemoryError)
if sys.platform.startswith('java'):
from java.io import StringWriter, PrintWriter
from java.lang import Throwable, OutOfMemoryError
RERAISED_EXCEPTIONS += (OutOfMemoryError,)
_java_trace_re = re.compile('^\s+at (\w.+)')
_ignored_java_trace = ('org.python.', 'robot.running.', 'robot$py.',
'sun.reflect.', 'java.lang.reflect.')
_ignore_trace_until = (os.path.join('robot','running','handlers.py'), '<lambda>')
_generic_exceptions = ('AssertionError', 'AssertionFailedError', 'Exception',
'Error', 'RuntimeError', 'RuntimeException',
'DataError', 'TimeoutError', 'RemoteError')
def get_error_message():
"""Returns error message of the last occurred exception.
This method handles also exceptions containing unicode messages. Thus it
MUST be used to get messages from all exceptions originating outside the
framework.
"""
return ErrorDetails().message
def get_error_details():
"""Returns error message and details of the last occurred exception.
"""
dets = ErrorDetails()
return dets.message, dets.traceback
class ErrorDetails(object):
"""This class wraps the last occurred exception
It has attributes message, traceback and error, where message contains
type and message of the original error, traceback it's contains traceback
(or stack trace in case of Java exception) and error contains the original
error instance
This class handles also exceptions containing unicode messages. Thus it
MUST be used to get messages from all exceptions originating outside the
framework.
"""
def __init__(self):
exc_type, exc_value, exc_traceback = sys.exc_info()
if exc_type in RERAISED_EXCEPTIONS:
raise exc_value
if _is_java_exception(exc_value):
self.message = _get_java_message(exc_type, exc_value)
self.traceback = _get_java_details(exc_value)
else:
self.message = _get_python_message(exc_type, exc_value)
self.traceback = _get_python_details(exc_value, exc_traceback)
self.error = exc_value
def _is_java_exception(exc):
return sys.platform.startswith('java') and isinstance(exc, Throwable)
def _get_name(exc_type):
try:
return exc_type.__name__
except AttributeError:
return unic(exc_type)
def _get_java_message(exc_type, exc_value):
exc_name = _get_name(exc_type)
# OOME.getMessage and even toString seem to throw NullPointerException
if exc_type is OutOfMemoryError:
exc_msg = str(exc_value)
else:
exc_msg = exc_value.getMessage()
return _format_message(exc_name, exc_msg, java=True)
def _get_java_details(exc_value):
# OOME.printStackTrace seems to throw NullPointerException
if isinstance(exc_value, OutOfMemoryError):
return ''
output = StringWriter()
exc_value.printStackTrace(PrintWriter(output))
lines = [ line for line in output.toString().splitlines()
if line and not _is_ignored_stacktrace_line(line) ]
details = '\n'.join(lines)
msg = unic(exc_value.getMessage() or '')
if msg:
details = details.replace(msg, '', 1)
return details
def _is_ignored_stacktrace_line(line):
res = _java_trace_re.match(line)
if res is None:
return False
location = res.group(1)
for entry in _ignored_java_trace:
if location.startswith(entry):
return True
return False
def _get_python_message(exc_type, exc_value):
# If exception is a "string exception" without a message exc_value is None
if exc_value is None:
return unic(exc_type)
name = _get_name(exc_type)
try:
msg = unicode(exc_value)
except UnicodeError: # Happens if message is Unicode and version < 2.6
msg = ' '.join(unic(a) for a in exc_value.args)
return _format_message(name, msg)
def _get_python_details(exc_value, exc_tb):
if isinstance(exc_value, (DataError, TimeoutError)):
return ''
if isinstance(exc_value, RemoteError):
return exc_value.traceback
tb = traceback.extract_tb(exc_tb)
for row, (path, _, func, _) in enumerate(tb):
if path.endswith(_ignore_trace_until[0]) and func == _ignore_trace_until[1]:
tb = tb[row+1:]
break
details = 'Traceback (most recent call last):\n' \
+ ''.join(traceback.format_list(tb))
return details.strip()
def _format_message(name, message, java=False):
message = unic(message or '')
if java:
message = _clean_up_java_message(message, name)
name = name.split('.')[-1] # Use only last part of the name
if message == '':
return name
if name in _generic_exceptions:
return message
return '%s: %s' % (name, message)
def _clean_up_java_message(msg, name):
# Remove possible stack trace from messages
lines = msg.splitlines()
while lines:
if _java_trace_re.match(lines[-1]):
lines.pop()
else:
break
msg = '\n'.join(lines)
# Remove possible exception name from the message
tokens = msg.split(':', 1)
if len(tokens) == 2 and tokens[0] == name:
msg = tokens[1]
return msg.strip()
| 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 unic import unic
_ILLEGAL_CHARS_IN_XML = u'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e' \
+ u'\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\ufffe'
class AbstractXmlWriter:
def start(self, name, attributes={}, newline=True):
self._start(name, self._escape_attrs(attributes))
if newline:
self.content('\n')
def _start(self, name, attrs):
raise NotImplementedError
def _escape_attrs(self, attrs):
return dict((n, self._escape(v)) for n, v in attrs.items())
def _escape(self, content):
content = unic(content)
for char in _ILLEGAL_CHARS_IN_XML:
# Avoid bug http://ironpython.codeplex.com/workitem/29402
if char in content:
content = content.replace(char, '')
return content
def content(self, content):
if content is not None:
self._content(self._escape(content))
def _content(self, content):
raise NotImplementedError
def end(self, name, newline=True):
self._end(name)
if newline:
self.content('\n')
def _end(self, name):
raise NotImplementedError
def element(self, name, content=None, attributes={}, newline=True):
self.start(name, attributes, newline=False)
self.content(content)
self.end(name, newline)
def close(self):
self._close()
self.closed = True
def _close(self):
self._writer.endDocument()
self._output.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.
import os
import sys
import inspect
from robot.errors import DataError
from error import get_error_message, get_error_details
from robotpath import normpath, abspath
def simple_import(path_to_module):
err_prefix = "Importing '%s' failed: " % path_to_module
if not os.path.exists(path_to_module):
raise DataError(err_prefix + 'File does not exist')
try:
return _import_module_by_path(path_to_module)
except:
raise DataError(err_prefix + get_error_message())
def _import_module_by_path(path):
moddir, modname = _split_path_to_module(path)
sys.path.insert(0, moddir)
try:
module = __import__(modname)
if hasattr(module, '__file__'):
impdir = os.path.dirname(module.__file__)
if normpath(impdir) != normpath(moddir):
del sys.modules[modname]
module = __import__(modname)
return module
finally:
sys.path.pop(0)
def _split_path_to_module(path):
moddir, modfile = os.path.split(abspath(path))
modname = os.path.splitext(modfile)[0]
return moddir, modname
def import_(name, type_='test library'):
"""Imports Python class/module or Java class with given name.
'name' can also be a path to the library and in that case the directory
containing the lib is automatically put into sys.path and removed there
afterwards.
'type_' is used in error message if importing fails.
Class can either live in a module/package or be 'standalone'. In the former
case tha name is something like 'MyClass' and in the latter it could be
'your.package.YourLibrary'). Python classes always live in a module but if
the module name is exactly same as the class name the former also works in
Python.
Example: If you have a Python class 'MyLibrary' in a module 'mymodule'
it must be imported with name 'mymodule.MyLibrary'. If the name of
the module is also 'MyLibrary' then it is possible to use only
name 'MyLibrary'.
"""
if '.' not in name or os.path.exists(name):
code, module = _non_dotted_import(name, type_)
else:
code, module = _dotted_import(name, type_)
source = _get_module_source(module)
return code, source
def _non_dotted_import(name, type_):
try:
if os.path.exists(name):
module = _import_module_by_path(name)
else:
module = __import__(name)
except:
_raise_import_failed(type_, name)
try:
code = getattr(module, module.__name__)
if not inspect.isclass(code):
raise AttributeError
except AttributeError:
code = module
return code, module
def _dotted_import(name, type_):
parentname, libname = name.rsplit('.', 1)
try:
try:
module = __import__(parentname, fromlist=[str(libname)])
except ImportError:
# Hack to support standalone Jython:
# http://code.google.com/p/robotframework/issues/detail?id=515
if not sys.platform.startswith('java'):
raise
__import__(name)
module = __import__(parentname, fromlist=[str(libname)])
except:
_raise_import_failed(type_, name)
try:
code = getattr(module, libname)
except AttributeError:
_raise_no_lib_in_module(type_, parentname, libname)
if not (inspect.ismodule(code) or inspect.isclass(code)):
_raise_invalid_type(type_, code)
return code, module
def _get_module_source(module):
source = getattr(module, '__file__', None)
return abspath(source) if source else '<unknown>'
def _raise_import_failed(type_, name):
error_msg, error_details = get_error_details()
msg = ["Importing %s '%s' failed: %s" % (type_, name, error_msg),
"PYTHONPATH: %s" % sys.path, error_details]
if sys.platform.startswith('java'):
from java.lang import System
msg.insert(-1, 'CLASSPATH: %s' % System.getProperty('java.class.path'))
raise DataError('\n'.join(msg))
def _raise_no_lib_in_module(type_, modname, libname):
raise DataError("%s module '%s' does not contain '%s'."
% (type_.capitalize(), modname, libname))
def _raise_invalid_type(type_, code):
raise DataError("Imported %s should be a class or module, got %s."
% (type_, type(code).__name__))
| 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 urllib
from encoding import decode_from_file_system
if os.sep == '\\':
_CASE_INSENSITIVE_FILESYSTEM = True
else:
try:
_CASE_INSENSITIVE_FILESYSTEM = os.listdir('/tmp') == os.listdir('/TMP')
except OSError:
_CASE_INSENSITIVE_FILESYSTEM = False
def normpath(path):
"""Returns path in normalized and absolute format.
On case-insensitive file systems the path is also case normalized.
If that is not desired, abspath should be used instead.
"""
path = abspath(path)
if _CASE_INSENSITIVE_FILESYSTEM:
path = path.lower()
return path
def abspath(path):
"""Replacement for os.path.abspath with some bug fixes and enhancements.
1) Converts non-Unicode paths to Unicode using file system encoding
2) At least Jython 2.5.1 on Windows returns wrong path with 'c:'.
3) Python until 2.6.5 and at least Jython 2.5.1 don't handle non-ASCII
characters in the working directory: http://bugs.python.org/issue3426
"""
if not isinstance(path, unicode):
path = decode_from_file_system(path)
if os.sep == '\\' and len(path) == 2 and path[1] == ':':
return path + '\\'
return os.path.normpath(os.path.join(os.getcwdu(), path))
def get_link_path(target, base):
"""Returns a relative path to a target from a base.
If base is an existing file, then its parent directory is considered.
Otherwise, base is assumed to be a directory.
Rationale: os.path.relpath is not available before Python 2.6
"""
pathname = _get_pathname(target, base)
url = urllib.pathname2url(pathname.encode('UTF-8'))
if os.path.isabs(pathname):
pre = url.startswith('/') and 'file:' or 'file:///'
url = pre + url
# Want consistent url on all platforms/interpreters
return url.replace('%5C', '/').replace('%3A', ':').replace('|', ':')
def _get_pathname(target, base):
target = abspath(target)
base = abspath(base)
if os.path.isfile(base):
base = os.path.dirname(base)
if base == target:
return os.path.basename(target)
base_drive, base_path = os.path.splitdrive(base)
# if in Windows and base and link on different drives
if os.path.splitdrive(target)[0] != base_drive:
return target
common_len = len(_common_path(base, target))
if base_path == os.sep:
return target[common_len:]
if common_len == len(base_drive) + len(os.sep):
common_len -= len(os.sep)
dirs_up = os.sep.join([os.pardir] * base[common_len:].count(os.sep))
return os.path.join(dirs_up, target[common_len + len(os.sep):])
def _common_path(p1, p2):
"""Returns the longest path common to p1 and p2.
Rationale: as os.path.commonprefix is character based, it doesn't consider
path separators as such, so it may return invalid paths:
commonprefix(('/foo/bar/', '/foo/baz.txt')) -> '/foo/ba' (instead of /foo)
"""
while p1 and p2:
if p1 == p2:
return p1
if len(p1) > len(p2):
p1 = os.path.dirname(p1)
else:
p2 = os.path.dirname(p2)
return ''
| 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 threading import Event
if sys.platform.startswith('java'):
from java.lang import Thread, Runnable
else:
from stoppablethread import Thread
Runnable = object
class ThreadedRunner(Runnable):
def __init__(self, runnable, args=None, kwargs=None, notifier=None):
self._runnable = lambda: runnable(*(args or ()), **(kwargs or {}))
self._notifier = Event()
self._result = None
self._error = None
self._traceback = None
self._thread = None
def run(self):
try:
self._result = self._runnable()
except:
self._error, self._traceback = sys.exc_info()[1:]
self._notifier.set()
__call__ = run
def run_in_thread(self, timeout):
self._thread = Thread(self)
self._thread.setDaemon(True)
self._thread.start()
self._notifier.wait(timeout)
return self._notifier.isSet()
def get_result(self):
if self._error:
raise self._error, None, self._traceback
return self._result
def stop_thread(self):
self._thread.stop()
| 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 abstractxmlwriter import AbstractXmlWriter
from htmlutils import html_escape, html_attr_escape
from unic import unic
class HtmlWriter(AbstractXmlWriter):
def __init__(self, output):
"""'output' is an open file object.
Given 'output' must have been opened with 'wb' to be able to
write into it with UTF-8 encoding.
'self.output.name' is later used by serializers
"""
self.output = output
def start(self, name, attrs=None, newline=True):
self._start(name, attrs, close=False, newline=newline)
def start_and_end(self, name, attrs=None, newline=True):
self._start(name, attrs, close=True, newline=newline)
def content(self, content=None, escape=True):
"""Given content doesn't need to be a string"""
if content is not None:
if escape:
content = self._escape_content(content)
self._write(content)
def end(self, name, newline=True):
elem = '</%s>' % name
if newline:
elem += '\n'
self._write(elem)
def element(self, name, content=None, attrs=None, escape=True,
newline=True):
self.start(name, attrs, newline=False)
self.content(content, escape)
self.end(name, newline)
def start_many(self, names, newline=True):
for name in names:
self.start(name, newline=newline)
def end_many(self, names, newline=True):
for name in names:
self.end(name, newline)
def _start(self, name, attrs, close=False, newline=True):
elem = '<%s' % name
elem = self._add_attrs(elem, attrs)
elem += (close and ' />' or '>')
if newline:
elem += '\n'
self._write(elem)
def _add_attrs(self, elem, attrs):
if not attrs:
return elem
attrs = attrs.items()
attrs.sort()
attrs = [ '%s="%s"' % (name, html_attr_escape(value))
for name, value in attrs ]
return '%s %s' % (elem, ' '.join(attrs))
def _escape_content(self, content):
return html_escape(unic(content))
def _write(self, text):
self.output.write(text.encode('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 unic import unic
from misc import seq2str2
from charwidth import get_char_width
_MAX_ASSIGN_LENGTH = 200
_MAX_ERROR_LINES = 40
_MAX_ERROR_LINE_LENGTH = 78
_ERROR_CUT_EXPLN = (' [ Message content over the limit has been removed. ]')
def cut_long_message(msg):
lines = msg.splitlines()
lengths = _count_line_lenghts(lines)
if sum(lengths) <= _MAX_ERROR_LINES:
return msg
start = _prune_excess_lines(lines, lengths)
end = _prune_excess_lines(lines, lengths, True)
return '\n'.join(start + [_ERROR_CUT_EXPLN] + end)
def _prune_excess_lines(lines, lengths, from_end=False):
if from_end:
lines.reverse()
lengths.reverse()
ret = []
total = 0
limit = _MAX_ERROR_LINES/2
for line, length in zip(lines[:limit], lengths[:limit]):
if total + length >= limit:
ret.append(_cut_long_line(line, total, from_end))
break
total += length
ret.append(line)
if from_end:
ret.reverse()
return ret
def _cut_long_line(line, used, from_end):
available_lines = _MAX_ERROR_LINES/2 - used
available_chars = available_lines * _MAX_ERROR_LINE_LENGTH - 3
if len(line) > available_chars:
if not from_end:
line = line[:available_chars] + '...'
else:
line = '...' + line[-available_chars:]
return line
def _count_line_lenghts(lines):
return [ _count_virtual_line_length(line) for line in lines ]
def _count_virtual_line_length(line):
length = len(line) / _MAX_ERROR_LINE_LENGTH
if not len(line) % _MAX_ERROR_LINE_LENGTH == 0 or len(line) == 0:
length += 1
return length
def format_assign_message(variable, value, cut_long=True):
value = unic(value) if variable.startswith('$') else seq2str2(value)
if cut_long and len(value) > _MAX_ASSIGN_LENGTH:
value = value[:_MAX_ASSIGN_LENGTH] + '...'
return '%s = %s' % (variable, value)
def get_console_length(text):
return sum(get_char_width(char) for char in text)
def pad_console_length(text, width, cut_left=False):
if width < 5:
width = 5
diff = get_console_length(text) - width
if diff <= 0:
return _pad_width(text, width)
if cut_left:
return _pad_width('...'+_lose_width_left(text, diff+3), width)
return _pad_width(_lose_width_right(text, diff+3)+'...', width)
def _pad_width(text, width):
more = width - get_console_length(text)
return text + ' ' * more
def _lose_width_right(text, diff):
return _lose_width(text, diff, -1, slice(None, -1))
def _lose_width_left(text, diff):
return _lose_width(text, diff, 0, slice(1, None))
def _lose_width(text, diff, index, slice):
lost = 0
while lost < diff:
lost += get_console_length(text[index])
text = text[slice]
return text | 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 StringIO import StringIO
try:
import xml.etree.cElementTree as ET
except ImportError:
try:
import cElementTree as ET
except ImportError:
try:
import xml.etree.ElementTree as ET
# Raises ImportError due to missing expat on IronPython by default
ET.parse(StringIO('<test/>'))
except ImportError:
try:
import elementtree.ElementTree as ET
except ImportError:
raise ImportError('No valid ElementTree XML parser module found')
def get_root(path, string=None, node=None):
# This should NOT be changed to 'if not node:'. See chapter Truth Testing
# from http://effbot.org/zone/element.htm#the-element-type
if node is not None:
return node
source = _get_source(path, string)
try:
return ET.parse(source).getroot()
finally:
if hasattr(source, 'close'):
source.close()
def _get_source(path, string):
if not path:
return StringIO(string)
# ElementTree 1.2.7 preview (first ET with IronPython support) doesn't
# handler non-ASCII chars correctly if an open file given to it.
if sys.platform == 'cli':
return path
# ET.parse doesn't close files it opens, which causes serious problems
# with Jython 2.5(.1) on Windows: http://bugs.jython.org/issue1598
return open(path, 'rb')
| 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 getopt # optparse not supported by Jython 2.2
import os
import re
import sys
import glob
import string
import codecs
import textwrap
from robot.errors import DataError, Information, FrameworkError
from misc import plural_or_not
from unic import unic
from encoding import decode_output, decode_from_file_system
ESCAPES = dict(
space = ' ', apos = "'", quot = '"', lt = '<', gt = '>',
pipe = '|', star = '*', comma = ',', slash = '/', semic = ';',
colon = ':', quest = '?', hash = '#', amp = '&', dollar = '$',
percent = '%', at = '@', exclam = '!', paren1 = '(', paren2 = ')',
square1 = '[', square2 = ']', curly1 = '{', curly2 = '}', bslash = '\\'
)
class ArgumentParser:
_opt_line_re = re.compile('''
^\s{,4} # max 4 spaces in the beginning of the line
((-\S\s)*) # all possible short options incl. spaces (group 1)
--(\S{2,}) # required long option (group 3)
(\s\S+)? # optional value (group 4)
(\s\*)? # optional '*' telling option allowed multiple times (group 5)
''', re.VERBOSE)
_usage_line_re = re.compile('''
^usage:.*
\[options\]\s*
(.*?) # arguments (group 1)
\s*$
''', re.VERBOSE | re.IGNORECASE)
def __init__(self, usage, version=None, arg_limits=None):
"""Available options and tool name are read from the usage.
Tool name is got from the first row of the usage. It is either the
whole row or anything before first ' -- '.
See for example 'runner.py' and 'rebot.py' for examples.
"""
if not usage:
raise FrameworkError('Usage cannot be empty')
self._usage = usage
self._name = usage.splitlines()[0].split(' -- ')[0].strip()
self._version = version
self._arg_limits = arg_limits
self._short_opts = ''
self._long_opts = []
self._multi_opts = []
self._toggle_opts = []
self._names = []
self._short_to_long = {}
self._expected_args = ()
self._parse_usage(usage)
def parse_args(self, args_list, unescape=None, argfile=None, pythonpath=None,
help=None, version=None, check_args=False):
"""Parse given arguments and return options and positional arguments.
Arguments must be given as a list and are typically sys.argv[1:].
Options are retuned as a dictionary where long options are keys. Value
is a string for those options that can be given only one time (if they
are given multiple times the last value is used) or None if the option
is not used at all. Value for options that can be given multiple times
(denoted with '*' in the usage) is a list which contains all the given
values and is empty if options are not used. Options not taken
arguments have value False when they are not set and True otherwise.
Positional arguments are returned as a list in the order they are given.
'unescape' option can be used to automatically unescape problematic
characters given in an escaped format. Given value must be the name of
the long option used for escaping. Typically usage is having
'--escape name:value *' in usage doc and specifying 'enescape="escape"'
when calling this method.
'argfile' can be used to automatically read arguments from specified
file. Given value must be the name of the long option used for giving
the argument file. Typical usage is '--argumentfile path *' in usage doc
and calling this method with 'argfile="argumentfile"'. If 'argfile' is
used, it can always be given multiple times and thus it is recommended
to use '*' to denote that. Special value 'stdin' can be used to read
arguments from stdin instead of a file.
'pythonpath' can be used to specify option(s) containing extra paths to
be added into 'sys.path'. Value can be either a string containing the
name of the long option used for this purpose or a list containing
all such long options (i.e. the latter format allows aliases).
'help' and 'version' make it possible to automatically generate help
and version messages. Version is generated based on the tool name
and version -- see __init__ for information how to set them. Help
contains the whole usage given to __init__. Possible <VERSION> text
in the usage is replaced with the given version. Possible <--ESCAPES-->
is replaced with available escapes so that they are wrapped to multiple
lines but take the same amount of horizontal space as <---ESCAPES--->.
The numer of hyphens can be used to contrl the horizontal space. Both
help and version are wrapped to Information exception.
If 'check_args' is True, this method will automatically check that
correct number of arguments, as parsed from the usage line, are given.
If the last argument in the usage line ends with the character 's',
the maximum number of arguments is infinite.
Possible errors in processing arguments are reported using DataError.
"""
args_list = [decode_from_file_system(a) for a in args_list]
if argfile:
args_list = self._add_args_from_file(args_list, argfile)
opts, args = self._parse_args(args_list)
if unescape:
opts, args = self._unescape_opts_and_args(opts, args, unescape)
if help and opts[help]:
self._raise_help()
if version and opts[version]:
self._raise_version()
if pythonpath:
sys.path = self._get_pythonpath(opts[pythonpath]) + sys.path
if check_args:
self._check_args(args)
return opts, args
def _parse_args(self, args):
args = [self._lowercase_long_option(a) for a in args]
try:
opts, args = getopt.getopt(args, self._short_opts, self._long_opts)
except getopt.GetoptError, err:
raise DataError(err.args[0])
return self._process_opts(opts), self._glob_args(args)
def _lowercase_long_option(self, opt):
if not opt.startswith('--'):
return opt
if '=' not in opt:
return opt.lower()
opt, value = opt.split('=', 1)
return '%s=%s' % (opt.lower(), value)
def _check_args(self, args):
if not self._arg_limits:
raise FrameworkError('No argument information specified.')
minargs, maxargs = self._arg_limits
if minargs <= len(args) <= maxargs:
return
minend = plural_or_not(minargs)
if minargs == maxargs:
exptxt = "%d argument%s" % (minargs, minend)
elif maxargs != sys.maxint:
exptxt = "%d to %d arguments" % (minargs, maxargs)
else:
exptxt = "at least %d argument%s" % (minargs, minend)
raise DataError("Expected %s, got %d." % (exptxt, len(args)))
def _unescape_opts_and_args(self, opts, args, escape_opt):
try:
escape_strings = opts[escape_opt]
except KeyError:
raise FrameworkError("No escape option '%s' in given options")
escapes = self._get_escapes(escape_strings)
for name, value in opts.items():
if name != escape_opt:
opts[name] = self._unescape(value, escapes)
return opts, [self._unescape(arg, escapes) for arg in args]
def _add_args_from_file(self, args, argfile_opt):
argfile_opts = ['--'+argfile_opt]
for sopt, lopt in self._short_to_long.items():
if lopt == argfile_opt:
argfile_opts.append('-'+sopt)
while True:
try:
index = self._get_argfile_index(args, argfile_opts)
path = args[index+1]
except IndexError:
break
args[index:index+2] = self._get_args_from_file(path)
return args
def _get_argfile_index(self, args, argfile_opts):
for opt in argfile_opts:
if opt in args:
return args.index(opt)
raise IndexError
def _get_args_from_file(self, path):
if path.upper() != 'STDIN':
content = self._read_argfile(path)
else:
content = decode_output(sys.__stdin__.read())
return self._process_argfile(content)
def _read_argfile(self, path):
try:
with codecs.open(path, encoding='UTF-8') as f:
content = f.read()
except (IOError, UnicodeError), err:
raise DataError("Opening argument file '%s' failed: %s"
% (path, err))
if content.startswith(codecs.BOM_UTF8.decode('UTF-8')):
content = content[1:]
return content
def _process_argfile(self, content):
args = []
for line in content.splitlines():
line = line.strip()
if line.startswith('-'):
args.extend(line.split(' ', 1))
elif line and not line.startswith('#'):
args.append(line)
return args
def _get_escapes(self, escape_strings):
escapes = {}
for estr in escape_strings:
try:
name, value = estr.split(':', 1)
except ValueError:
raise DataError("Invalid escape string syntax '%s'. "
"Expected: what:with" % estr)
try:
escapes[value] = ESCAPES[name.lower()]
except KeyError:
raise DataError("Invalid escape '%s'. Available: %s"
% (name, self._get_available_escapes()))
return escapes
def _unescape(self, value, escapes):
if value in [None, True, False]:
return value
if isinstance(value, list):
return [self._unescape(item, escapes) for item in value]
for esc_name, esc_value in escapes.items():
value = value.replace(esc_name, esc_value)
return value
def _process_opts(self, opt_tuple):
opts = self._init_opts()
for name, value in opt_tuple:
name = self._get_name(name)
if name in self._multi_opts:
opts[name].append(value)
elif name in self._toggle_opts:
opts[name] = not opts[name]
else:
opts[name] = value
return opts
def _glob_args(self, args):
temp = []
for path in args:
paths = sorted(glob.glob(path))
if paths:
temp.extend(paths)
else:
temp.append(path)
return temp
def _init_opts(self):
opts = {}
for name in self._names:
if name in self._multi_opts:
opts[name] = []
elif name in self._toggle_opts:
opts[name] = False
else:
opts[name] = None
return opts
def _get_name(self, name):
name = name.lstrip('-')
try:
return self._short_to_long[name]
except KeyError:
return name
def _parse_usage(self, usage):
for line in usage.splitlines():
if not self._parse_opt_line(line) and not self._arg_limits:
self._parse_usage_line(line)
def _parse_usage_line(self, line):
res = self._usage_line_re.match(line)
if res:
args = res.group(1).split()
if not args:
self._arg_limits = (0, 0)
else:
maxargs = args[-1].endswith('s') and sys.maxint or len(args)
self._arg_limits = (len(args), maxargs)
def _parse_opt_line(self, line):
res = self._opt_line_re.match(line)
if not res:
return False
long_opt = res.group(3).lower()
if long_opt in self._names:
self._raise_option_multiple_times_in_usage('--' + long_opt)
self._names.append(long_opt)
short_opts = [ opt[1] for opt in res.group(1).split() ]
for sopt in short_opts:
if self._short_to_long.has_key(sopt):
self._raise_option_multiple_times_in_usage('-' + sopt)
self._short_to_long[sopt] = long_opt
# options allowed multiple times
if res.group(5):
self._multi_opts.append(long_opt)
# options with arguments
if res.group(4):
long_opt += '='
short_opts = [ sopt + ':' for sopt in short_opts ]
else:
self._toggle_opts.append(long_opt)
self._long_opts.append(long_opt)
self._short_opts += (''.join(short_opts))
return True
def _get_pythonpath(self, paths):
if isinstance(paths, basestring):
paths = [paths]
temp = []
for path in self._split_pythonpath(paths):
temp.extend(glob.glob(path))
return [os.path.abspath(path) for path in temp if path]
def _split_pythonpath(self, paths):
# paths may already contain ':' as separator
tokens = ':'.join(paths).split(':')
if os.sep == '/':
return tokens
# Fix paths split like 'c:\temp' -> 'c', '\temp'
ret = []
drive = ''
for item in tokens:
item = item.replace('/', '\\')
if drive and item.startswith('\\'):
ret.append('%s:%s' % (drive, item))
drive = ''
continue
if drive:
ret.append(drive)
drive = ''
if len(item) == 1 and item in string.letters:
drive = item
else:
ret.append(item)
if drive:
ret.append(drive)
return ret
def _get_available_escapes(self):
names = sorted(ESCAPES.keys(), key=str.lower)
return ', '.join('%s (%s)' % (n, ESCAPES[n]) for n in names)
def _raise_help(self):
msg = self._usage
if self._version:
msg = msg.replace('<VERSION>', self._version)
def replace_escapes(res):
escapes = 'Available escapes: ' + self._get_available_escapes()
lines = textwrap.wrap(escapes, width=len(res.group(2)))
indent = ' ' * len(res.group(1))
return '\n'.join(indent + line for line in lines)
msg = re.sub('( *)(<-+ESCAPES-+>)', replace_escapes, msg)
raise Information(msg)
def _raise_version(self):
if not self._version:
raise FrameworkError('Version not set')
raise Information('%s %s' % (self._name, self._version))
def _raise_option_multiple_times_in_usage(self, opt):
raise FrameworkError("Option '%s' multiple times in usage" % opt)
| 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 abstractxmlwriter import AbstractXmlWriter
def XmlWriter(path):
if path == 'NONE':
return FakeXMLWriter()
if os.name == 'java':
from jyxmlwriter import XmlWriter
else:
from pyxmlwriter import XmlWriter
return XmlWriter(path)
class FakeXMLWriter(AbstractXmlWriter):
closed = False
_start = _content = _end = _close = lambda self, *args: 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 time
from normalizing import normalize
from misc import plural_or_not
def _get_timetuple(epoch_secs=None):
if _CURRENT_TIME:
return _CURRENT_TIME
if epoch_secs is None: # can also be 0 (at least in unit tests)
epoch_secs = time.time()
secs, millis = _float_secs_to_secs_and_millis(epoch_secs)
timetuple = time.localtime(secs)[:6] # from year to secs
return timetuple + (millis,)
def _float_secs_to_secs_and_millis(secs):
isecs = int(secs)
millis = int(round((secs - isecs) * 1000))
return (isecs, millis) if millis < 1000 else (isecs+1, 0)
_CURRENT_TIME = None # Seam for mocking time-dependent tests
START_TIME = _get_timetuple()
def timestr_to_secs(timestr):
"""Parses time in format like '1h 10s' and returns time in seconds (float).
Given time must be in format '1d 2h 3m 4s 5ms' with following rules.
- Time parts having zero value can be ignored (e.g. '3m 4s' is ok)
- Format is case and space insensitive
- Instead of 'd' it is also possible to use 'day' or 'days'
- Instead of 'h' also 'hour' and 'hours' are ok
- Instead of 'm' also 'minute', 'minutes', 'min' and 'mins' are ok
- Instead of 's' also 'second', 'seconds', 'sec' and 'secs' are ok
- Instead of 'ms' also 'millisecond', 'milliseconds' and 'millis' are ok
- It is possible to give time only as a float and then it is considered
to be seconds (e.g. '123', '123.0', '123s', '2min 3s' are all equivelant)
"""
try:
secs = _timestr_to_secs(timestr)
except (ValueError, TypeError):
raise ValueError("Invalid time string '%s'" % timestr)
return round(secs, 3)
def _timestr_to_secs(timestr):
timestr = _normalize_timestr(timestr)
if timestr == '':
raise ValueError
try:
return float(timestr)
except ValueError:
pass
millis = secs = mins = hours = days = 0
if timestr[0] == '-':
sign = -1
timestr = timestr[1:]
else:
sign = 1
temp = []
for c in timestr:
if c == 'x': millis = float(''.join(temp)); temp = []
elif c == 's': secs = float(''.join(temp)); temp = []
elif c == 'm': mins = float(''.join(temp)); temp = []
elif c == 'h': hours = float(''.join(temp)); temp = []
elif c == 'p': days = float(''.join(temp)); temp = []
else: temp.append(c)
if temp:
raise ValueError
return sign * (millis/1000 + secs + mins*60 + hours*60*60 + days*60*60*24)
def _normalize_timestr(timestr):
if isinstance(timestr, (int, long, float)):
return timestr
timestr = normalize(timestr)
for item in 'milliseconds', 'millisecond', 'millis':
timestr = timestr.replace(item, 'ms')
for item in 'seconds', 'second', 'secs', 'sec':
timestr = timestr.replace(item, 's')
for item in 'minutes', 'minute', 'mins', 'min':
timestr = timestr.replace(item, 'm')
for item in 'hours', 'hour':
timestr = timestr.replace(item, 'h')
for item in 'days', 'day':
timestr = timestr.replace(item, 'd')
# 1) 'ms' -> 'x' to ease processing later
# 2) 'd' -> 'p' because float('1d') returns 1.0 in Jython (bug submitted)
return timestr.replace('ms','x').replace('d','p')
def secs_to_timestr(secs, compact=False):
"""Converts time in seconds to a string representation.
Returned string is in format like
'1 day 2 hours 3 minutes 4 seconds 5 milliseconds' with following rules.
- Time parts having zero value are not included (e.g. '3 minutes 4 seconds'
instead of '0 days 0 hours 3 minutes 4 seconds')
- Hour part has a maximun of 23 and minutes and seconds both have 59
(e.g. '1 minute 40 seconds' instead of '100 seconds')
If compact has value 'True', short suffixes are used.
(e.g. 1d 2h 3min 4s 5ms)
"""
return _SecsToTimestrHelper(secs, compact).get_value()
class _SecsToTimestrHelper:
def __init__(self, float_secs, compact):
self._compact = compact
self._ret = []
self._sign, millis, secs, mins, hours, days \
= self._secs_to_components(float_secs)
self._add_item(days, 'd', 'day')
self._add_item(hours, 'h', 'hour')
self._add_item(mins, 'min', 'minute')
self._add_item(secs, 's', 'second')
self._add_item(millis, 'ms', 'millisecond')
def get_value(self):
if len(self._ret) > 0:
return self._sign + ' '.join(self._ret)
return '0s' if self._compact else '0 seconds'
def _add_item(self, value, compact_suffix, long_suffix):
if value == 0:
return
if self._compact:
suffix = compact_suffix
else:
suffix = ' %s%s' % (long_suffix, plural_or_not(value))
self._ret.append('%d%s' % (value, suffix))
def _secs_to_components(self, float_secs):
if float_secs < 0:
sign = '- '
float_secs = abs(float_secs)
else:
sign = ''
int_secs, millis = _float_secs_to_secs_and_millis(float_secs)
secs = int_secs % 60
mins = int(int_secs / 60) % 60
hours = int(int_secs / (60*60)) % 24
days = int(int_secs / (60*60*24))
return sign, millis, secs, mins, hours, days
def format_time(timetuple_or_epochsecs, daysep='', daytimesep=' ', timesep=':',
millissep=None, gmtsep=None):
"""Returns a timestamp formatted from given time using separators.
Time can be given either as a timetuple or seconds after epoch.
Timetuple is (year, month, day, hour, min, sec[, millis]), where parts must
be integers and millis is required only when millissep is not None.
Notice that this is not 100% compatible with standard Python timetuples
which do not have millis.
Seconds after epoch can be either an integer or a float.
"""
if isinstance(timetuple_or_epochsecs, (int, long, float)):
timetuple = _get_timetuple(timetuple_or_epochsecs)
else:
timetuple = timetuple_or_epochsecs
daytimeparts = ['%02d' % t for t in timetuple[:6]]
day = daysep.join(daytimeparts[:3])
time_ = timesep.join(daytimeparts[3:6])
millis = millissep and '%s%03d' % (millissep, timetuple[6]) or ''
return day + daytimesep + time_ + millis + _diff_to_gmt(gmtsep)
def _diff_to_gmt(sep):
if not sep:
return ''
if time.altzone == 0:
sign = ''
elif time.altzone > 0:
sign = '-'
else:
sign = '+'
minutes = abs(time.altzone) / 60.0
hours, minutes = divmod(minutes, 60)
return '%sGMT%s%s%02d:%02d' % (sep, sep, sign, hours, minutes)
def get_time(format='timestamp', time_=None):
"""Return the given or current time in requested format.
If time is not given, current time is used. How time is returned is
is deternined based on the given 'format' string as follows. Note that all
checks are case insensitive.
- If 'format' contains word 'epoch' the time is returned in seconds after
the unix epoch.
- If 'format' contains any of the words 'year', 'month', 'day', 'hour',
'min' or 'sec' only selected parts are returned. The order of the returned
parts is always the one in previous sentence and order of words in
'format' is not significant. Parts are returned as zero padded strings
(e.g. May -> '05').
- Otherwise (and by default) the time is returned as a timestamp string in
format '2006-02-24 15:08:31'
"""
if time_ is None:
time_ = time.time()
format = format.lower()
# 1) Return time in seconds since epoc
if 'epoch' in format:
return int(time_)
timetuple = time.localtime(time_)
parts = []
for i, match in enumerate('year month day hour min sec'.split()):
if match in format:
parts.append('%.2d' % timetuple[i])
# 2) Return time as timestamp
if not parts:
return format_time(timetuple, daysep='-')
# Return requested parts of the time
elif len(parts) == 1:
return parts[0]
else:
return parts
def parse_time(timestr):
"""Parses the time string and returns its value as seconds since epoch.
Time can be given in four different formats:
1) Numbers are interpreted as time since epoch directly. It is possible to
use also ints and floats, not only strings containing numbers.
2) Valid timestamp ('YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss').
3) 'NOW' (case-insensitive) is the current time rounded down to the
closest second.
4) Format 'NOW - 1 day' or 'NOW + 1 hour 30 min' is the current time
plus/minus the time specified with the time string.
"""
try:
ret = int(timestr)
except ValueError:
pass
else:
if ret < 0:
raise ValueError("Epoch time must be positive (got %s)" % timestr)
return ret
try:
return timestamp_to_secs(timestr, (' ', ':', '-', '.'))
except ValueError:
pass
normtime = timestr.lower().replace(' ', '')
now = int(time.time())
if normtime == 'now':
return now
if normtime.startswith('now'):
if normtime[3] == '+':
return now + timestr_to_secs(normtime[4:])
if normtime[3] == '-':
return now - timestr_to_secs(normtime[4:])
raise ValueError("Invalid time format '%s'" % timestr)
def get_timestamp(daysep='', daytimesep=' ', timesep=':', millissep='.'):
return format_time(_get_timetuple(), daysep, daytimesep, timesep, millissep)
def timestamp_to_secs(timestamp, seps=('', ' ', ':', '.'), millis=False):
try:
secs = _timestamp_to_millis(timestamp, seps) / 1000.0
except (ValueError, OverflowError):
raise ValueError("Invalid timestamp '%s'" % timestamp)
if millis:
return round(secs, 3)
return int(round(secs))
def secs_to_timestamp(secs, seps=None, millis=False):
if not seps:
seps = ('', ' ', ':', '.' if millis else None)
ttuple = time.localtime(secs)[:6]
if millis:
millis = (secs - int(secs)) * 1000
ttuple = ttuple + (int(millis),)
return format_time(ttuple, *seps)
def get_start_timestamp(daysep='', daytimesep=' ', timesep=':', millissep=None):
return format_time(START_TIME, daysep, daytimesep, timesep, millissep)
def get_elapsed_time(start_time, end_time=None, seps=('', ' ', ':', '.')):
"""Returns the time between given timestamps in milliseconds.
If 'end_time' is not given current timestamp is got with
get_timestamp using given 'seps'.
'seps' is a tuple containing 'daysep', 'daytimesep', 'timesep' and
'millissep' used in given timestamps.
"""
if start_time == 'N/A' or end_time == 'N/A':
return 0
if not end_time:
end_time = get_timestamp(*seps)
start_millis = _timestamp_to_millis(start_time, seps)
end_millis = _timestamp_to_millis(end_time, seps)
# start/end_millis can be long but we want to return int when possible
return int(end_millis - start_millis)
def elapsed_time_to_string(elapsed_millis):
"""Converts elapsed time in millisecods to format 'hh:mm:ss.mil'"""
elapsed_millis = round(elapsed_millis)
if elapsed_millis < 0:
pre = '-'
elapsed_millis = abs(elapsed_millis)
else:
pre = ''
millis = elapsed_millis % 1000
secs = int(elapsed_millis / 1000) % 60
mins = int(elapsed_millis / 60000) % 60
hours = int(elapsed_millis / 3600000)
return '%s%02d:%02d:%02d.%03d' % (pre, hours, mins, secs, millis)
def _timestamp_to_millis(timestamp, seps):
Y, M, D, h, m, s, millis = _split_timestamp(timestamp, seps)
secs = time.mktime((Y, M, D, h, m, s, 0, 0, time.daylight))
return int(round(1000*secs + millis))
def _split_timestamp(timestamp, seps):
for sep in seps:
if sep:
timestamp = timestamp.replace(sep, '')
timestamp = timestamp.ljust(17, '0')
years = int(timestamp[:4])
mons = int(timestamp[4:6])
days = int(timestamp[6:8])
hours = int(timestamp[8:10])
mins = int(timestamp[10:12])
secs = int(timestamp[12:14])
millis = int(timestamp[14:17])
return years, mons, days, hours, mins, secs, millis
| 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.variables import Variables
from robot.errors import DataError, FrameworkError
from robot import utils
PRE = '<!-- '
POST = ' -->'
class Namespace(Variables):
def __init__(self, **kwargs):
Variables.__init__(self, ['$'])
for key, value in kwargs.items():
self['${%s}' % key] = value
class Template:
def __init__(self, path=None, template=None, functions=None):
if path is None and template is None:
raise FrameworkError("Either 'path' or 'template' must be given")
if template is None:
tfile = open(path)
template = tfile.read()
tfile.close()
self.parent_dir = os.path.dirname(utils.abspath(path))
else:
self.parent_dir = None
self._template = template
self._functions = functions or utils.NormalizedDict()
# True means handlers for more than single line
self._handlers = { 'INCLUDE': (self._handle_include, False),
'IMPORT': (self._handle_import, False),
'CALL': (self._handle_call, False),
'IF': (self._handle_if, True),
'FOR': (self._handle_for, True),
'FUNCTION': (self._handle_function, True) }
def generate(self, namespace, output=None):
self._namespace = namespace
return self._process(self._template, output)
def _process(self, template, output=None):
result = Result(output)
lines = template.splitlines()
while lines:
line = lines.pop(0)
try:
result.add(self._process_line(line.strip(), lines))
except ValueError:
result.add(self._handle_variables(line))
return result.get_result()
def _process_line(self, line, lines):
if not line.startswith(PRE) and line.endswith(POST):
raise ValueError
name, expression = line[len(PRE):-len(POST)].split(' ', 1)
try:
handler, multiline = self._handlers[name]
except KeyError:
raise ValueError
if multiline:
block_lines = self._get_multi_line_block(name, lines)
return handler(expression, block_lines)
return handler(expression)
def _get_multi_line_block(self, name, lines):
"""Returns string containing lines before END matching given name.
Removes the returned lines from given 'lines'.
"""
block_lines = []
endline = '%sEND %s%s' % (PRE, name, POST)
while True:
try:
line = lines.pop(0)
except IndexError:
raise DataError('Invalid template: No END for %s' % name)
if line.strip() == endline:
break
block_lines.append(line)
return block_lines
def _handle_variables(self, template):
return self._namespace.replace_string(template)
def _handle_include(self, path):
included_file = open(self._get_full_path(path))
include = included_file.read()
included_file.close()
return self._handle_variables(include)
def _handle_import(self, path):
imported_file = open(self._get_full_path(path))
self._process(imported_file.read())
imported_file.close()
return None
def _handle_for(self, expression, block_lines):
block = '\n'.join(block_lines)
result = []
var_name, _, value_list = expression.split(' ', 2)
namespace = self._namespace.copy()
for value in namespace.replace_scalar(value_list):
namespace[var_name] = value
temp = Template(template=block, functions=self._functions)
ret = temp.generate(namespace)
if ret:
result.append(ret)
if not result:
return None
return '\n'.join(result)
def _handle_if(self, expression, block_lines):
expression = self._handle_variables(expression)
if_block, else_block = self._get_if_and_else_blocks(block_lines)
result = eval(expression) and if_block or else_block
if not result:
return None
return self._process('\n'.join(result))
def _get_if_and_else_blocks(self, block_lines):
else_line = PRE + 'ELSE' + POST
if_block = []
else_block = []
block = if_block
for line in block_lines:
if line.strip() == else_line:
block = else_block
else:
block.append(line)
return if_block, else_block
def _handle_call(self, expression):
func_tokens = expression.split()
name = func_tokens[0]
args = func_tokens[1:]
namespace = self._namespace.copy()
try:
func_args, func_body = self._functions[name]
except KeyError:
raise DataError("Non-existing function '%s', available: %s"
% (name, self._functions.keys()))
for key, value in zip(func_args, args):
namespace[key] = namespace.replace_string(value)
temp = Template(template=func_body, functions=self._functions)
return temp.generate(namespace)
def _handle_function(self, signature, block_lines):
signature_tokens = signature.split()
name = signature_tokens[0]
args = signature_tokens[1:]
self._functions[name] = (args, '\n'.join(block_lines))
def _get_full_path(self, path):
if self.parent_dir is None:
raise FrameworkError('Parent directory is None. Probably template '
'was string and other files was referred. '
'That is not supported.')
abs_path = os.path.join(self.parent_dir, path)
if os.path.exists(abs_path):
return abs_path
else:
raise DataError("File '%s' does not exist." % abs_path)
class Result:
def __init__(self, output=None):
self._output = output
self._result = []
def add(self, text):
if text is not None:
if self._output is None:
self._result.append(text)
else:
self._output.write(text.encode('UTF-8') + '\n')
def get_result(self):
if not self._result:
return None
return '\n'.join(self._result)
| 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
_ESCAPE_RE = re.compile(r'(\\+)([^\\]{0,2})') # escapes and nextchars
_SEQS_TO_BE_ESCAPED = ('\\', '${', '@{', '%{', '&{', '*{' , '=')
def escape(item):
if not isinstance(item, basestring):
return item
for seq in _SEQS_TO_BE_ESCAPED:
item = item.replace(seq, '\\' + seq)
return item
def unescape(item):
if not isinstance(item, basestring):
return item
result = []
unprocessed = item
while True:
res = _ESCAPE_RE.search(unprocessed)
# If no escapes found append string to result and exit loop
if res is None:
result.append(unprocessed)
break
# Split string to pre match, escapes, nextchars and unprocessed parts
# (e.g. '<pre><esc><nc><unproc>') where nextchars contains 0-2 chars
# and unprocessed may contain more escapes. Pre match part contains
# no escapes can is appended directly to result.
result.append(unprocessed[:res.start()])
escapes = res.group(1)
nextchars = res.group(2)
unprocessed = unprocessed[res.end():]
# Append every second escape char to result
result.append('\\' * (len(escapes) / 2))
# Handle '\n', '\r' and '\t'. Note that both '\n' and '\n ' are
# converted to '\n'
if len(escapes) % 2 == 0 or len(nextchars) == 0 \
or nextchars[0] not in ['n','r','t']:
result.append(nextchars)
elif nextchars[0] == 'n':
if len(nextchars) == 1 or nextchars[1] == ' ':
result.append('\n')
else:
result.append('\n' + nextchars[1])
elif nextchars[0] == 'r':
result.append('\r' + nextchars[1:])
else:
result.append('\t' + nextchars[1:])
return ''.join(result)
| 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 etreewrapper
class DomWrapper(object):
def __init__(self, path=None, string=None, node=None):
"""Initialize by giving 'path' to an xml file or xml as a 'string'.
Alternative initialization by giving dom 'node' ment to be used only
internally. 'path' may actually also be an already opened file object
(or anything accepted by ElementTree.parse).
"""
node = etreewrapper.get_root(path, string, node)
self.source = path
self.name = node.tag
self.attrs = dict(node.items())
self.text = node.text or ''
self.children = [DomWrapper(path, node=child) for child in list(node)]
def get_nodes(self, path):
"""Returns a list of descendants matching given 'path'.
Path must be a string in format 'child_name/grandchild_name/etc'. No
slash is allowed at the beginning or end of the path string. Returns an
empty list if no matching descendants found and raises AttributeError
if path is invalid.
"""
if not isinstance(path, basestring) \
or path == '' or path[0] == '/' or path[-1] == '/':
raise AttributeError("Invalid path '%s'" % path)
matches = []
for child in self.children:
matches += child._get_matching_elements(path.split('/'))
return matches
def _get_matching_elements(self, tokens):
if self.name != tokens[0]:
return []
elif len(tokens) == 1:
return [self]
else:
matches = []
for child in self.children:
matches += child._get_matching_elements(tokens[1:])
return matches
def get_node(self, path):
"""Similar as get_nodes but checks that exactly one node is found.
Node is returned as is (i.e. not in a list) and AttributeError risen if
no match or more than one match found.
"""
nodes = self.get_nodes(path)
if len(nodes) == 0:
raise AttributeError("No nodes matching path '%s' found" % path)
if len(nodes) > 1:
raise AttributeError("Multiple nodes matching path '%s' found" % path)
return nodes[0]
def get_attr(self, name, default=None):
"""Helper for getting node's attributes.
Otherwise equivalent to 'node.attrs.get(name, default)' but raises
an AttributeError if no value found and no default given.
"""
ret = self.attrs.get(name, default)
if ret is None:
raise AttributeError("No attribute '%s' found" % name)
return ret
def __getattr__(self, name):
"""Syntactic sugar for get_nodes (e.g. dom.elem[0].subelem).
Differs from get_nodes so that if not matching nodes are found an
AttributeError is risen instead of returning an empty list.
"""
nodes = self.get_nodes(name)
if not nodes:
raise AttributeError("No nodes matching path '%s' found" % name)
return nodes
def __getitem__(self, name):
"""Syntactic sugar for get_node (e.g. dom['elem/subelem'])"""
try:
return self.get_node(name)
except AttributeError:
raise IndexError("No node '%s' found" % name)
def __repr__(self):
"""Return node name. Mainly for debugging purposes."""
return self.name
| 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 unic import unic
"""Convenience functions for testing both in unit and higher levels.
Benefits:
- Integrates 100% with unittest (see example below)
- Can be easily used without unittest (using unittest.TestCase when you
only need convenient asserts is not so nice)
- Saved typing and shorter lines because no need to have 'self.' before
asserts. These are static functions after all so that is OK.
- All 'equals' methods (by default) report given values even if optional
message given. This behavior can be controlled with the optional values
argument.
Drawbacks:
- unittest is not able to filter as much non-interesting traceback away
as with its own methods because AssertionErrors occur outside
Most of the functions are copied more or less directly from unittest.TestCase
which comes with the following license. Further information about unittest in
general can be found from http://pyunit.sourceforge.net/. This module can be
used freely in same terms as unittest.
----[unittest licence]------------------------------------------------
Copyright (c) 1999-2003 Steve Purcell
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.
IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
----[example usage]---------------------------------------------------
import unittest
from robot.util.asserts import *
class MyTests(unittest.TestCase):
def test_old_style(self):
self.assertEquals(1, 2, 'my msg')
def test_new_style(self):
assert_equals(1, 2, 'my msg')
----[example output]--------------------------------------------------
FF
======================================================================
FAIL: test_old_style (__main__.MyTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "example.py", line 7, in test_old_style
self.assertEquals(1, 2, 'my msg')
AssertionError: my msg
======================================================================
FAIL: test_new_style (__main__.MyTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "example.py", line 10, in test_new_style
assert_equals(1, 2, 'my msg')
File "/path/to/robot/asserts.py", line 142, in fail_unless_equal
_report_unequality_failure(first, second, msg, values, '!=')
File "/path/to/robot/src/robot/asserts.py", line 209, in _report_unequality_failure
raise _report_failure(msg)
File "/path/to/robot/src/robot/asserts.py", line 200, in _report_failure
raise AssertionError(msg)
AssertionError: my msg: 1 != 2
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=2)
"""
def fail(msg=None):
"""Fail test immediately with the given message."""
_report_failure(msg)
def error(msg=None):
"""Error test immediately with the given message."""
_report_error(msg)
def fail_if(expr, msg=None):
"""Fail the test if the expression is True."""
if expr: _report_failure(msg)
def fail_unless(expr, msg=None):
"""Fail the test unless the expression is True."""
if not expr: _report_failure(msg)
def fail_if_none(obj, msg=None, values=True):
"""Fail the test if given object is None."""
_msg = 'is None'
if obj is None:
if msg is None:
msg = _msg
elif values is True:
msg = '%s: %s' % (msg, _msg)
_report_failure(msg)
def fail_unless_none(obj, msg=None, values=True):
"""Fail the test if given object is not None."""
_msg = '%r is not None' % obj
if obj is not None:
if msg is None:
msg = _msg
elif values is True:
msg = '%s: %s' % (msg, _msg)
_report_failure(msg)
def fail_unless_raises(exc_class, callable_obj, *args, **kwargs):
"""Fail unless an exception of class exc_class is thrown by callable_obj.
callable_obj is invoked with arguments args and keyword arguments
kwargs. If a different type of exception is thrown, it will not be
caught, and the test case will be deemed to have suffered an
error, exactly as for an unexpected exception.
"""
try:
callable_obj(*args, **kwargs)
except exc_class:
return
else:
if hasattr(exc_class,'__name__'):
exc_name = exc_class.__name__
else:
exc_name = str(exc_class)
_report_failure('%s not raised' % exc_name)
def fail_unless_raises_with_msg(exc_class, expected_msg, callable_obj, *args,
**kwargs):
"""Similar to fail_unless_raises but also checks the exception message."""
try:
callable_obj(*args, **kwargs)
except exc_class, err:
assert_equal(expected_msg, unic(err), 'Correct exception but wrong message')
else:
if hasattr(exc_class,'__name__'):
exc_name = exc_class.__name__
else:
exc_name = str(exc_class)
_report_failure('%s not raised' % exc_name)
def fail_unless_equal(first, second, msg=None, values=True):
"""Fail if given objects are unequal as determined by the '==' operator."""
if not first == second:
_report_unequality_failure(first, second, msg, values, '!=')
def fail_if_equal(first, second, msg=None, values=True):
"""Fail if given objects are equal as determined by the '==' operator."""
if first == second:
_report_unequality_failure(first, second, msg, values, '==')
def fail_unless_almost_equal(first, second, places=7, msg=None, values=True):
"""Fail if the two objects are unequal after rounded to given places.
Unequality is determined by object's difference rounded to the
given number of decimal places (default 7) and comparing to zero.
Note that decimal places (from zero) are usually not the same as
significant digits (measured from the most signficant digit).
"""
if round(second - first, places) != 0:
extra = 'within %r places' % places
_report_unequality_failure(first, second, msg, values, '!=', extra)
def fail_if_almost_equal(first, second, places=7, msg=None, values=True):
"""Fail if the two objects are unequal after rounded to given places.
Equality is determined by object's difference rounded to to the
given number of decimal places (default 7) and comparing to zero.
Note that decimal places (from zero) are usually not the same as
significant digits (measured from the most signficant digit).
"""
if round(second-first, places) == 0:
extra = 'within %r places' % places
_report_unequality_failure(first, second, msg, values, '==', extra)
# Synonyms for assertion methods
assert_equal = assert_equals = fail_unless_equal
assert_not_equal = assert_not_equals = fail_if_equal
assert_almost_equal = assert_almost_equals = fail_unless_almost_equal
assert_not_almost_equal = assert_not_almost_equals = fail_if_almost_equal
assert_raises = fail_unless_raises
assert_raises_with_msg = fail_unless_raises_with_msg
assert_ = assert_true = fail_unless
assert_false = fail_if
assert_none = fail_unless_none
assert_not_none = fail_if_none
# Helpers
def _report_failure(msg):
if msg is None:
raise AssertionError()
raise AssertionError(msg)
def _report_error(msg):
if msg is None:
raise Exception()
raise Exception(msg)
def _report_unequality_failure(obj1, obj2, msg, values, delim, extra=None):
if not msg:
msg = _get_default_message(obj1, obj2, delim)
elif values:
msg = '%s: %s' % (msg, _get_default_message(obj1, obj2, delim))
if values and extra:
msg += ' ' + extra
_report_failure(msg)
def _get_default_message(obj1, obj2, delim):
if delim == '!=' and unicode(obj1) == unicode(obj2):
return '%s (%s) != %s (%s)' % (obj1, _type_name(obj1),
obj2, _type_name(obj2))
return '%s %s %s' % (obj1, delim, obj2)
def _type_name(val):
known_types = {int: 'number', long: 'number', float: 'number',
str: 'string', unicode: 'string', bool: 'boolean'}
return known_types.get(type(val), type(val).__name__)
| 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 unic import unic
def printable_name(string, code_style=False):
"""Generates and returns printable name from the given string.
Examples:
'simple' -> 'Simple'
'name with spaces' -> 'Name With Spaces'
'more spaces' -> 'More Spaces'
'Cases AND spaces' -> 'Cases AND Spaces'
'' -> ''
If 'code_style' is True:
'mixedCAPSCamel' -> 'Mixed CAPS Camel'
'camelCaseName' -> 'Camel Case Name'
'under_score_name' -> 'Under Score Name'
'under_and space' -> 'Under And Space'
'miXed_CAPS_nAMe' -> 'MiXed CAPS NAMe'
'' -> ''
"""
if code_style:
string = string.replace('_', ' ')
parts = string.split()
if len(parts) == 0:
return ''
elif len(parts) == 1 and code_style:
parts = _splitCamelCaseString(parts[0])
parts = [ part[0].upper() + part[1:] for part in parts if part != '' ]
return ' '.join(parts)
def _splitCamelCaseString(string):
parts = []
current_part = []
string = ' ' + string + ' ' # extra spaces make going through string easier
for i in range(1, len(string)-1):
# on 1st/last round prev/next is ' ' and char is 1st/last real char
prev, char, next = string[i-1:i+2]
if _isWordBoundary(prev, char, next):
parts.append(''.join(current_part))
current_part = [ char ]
else:
current_part.append(char)
parts.append(''.join(current_part)) # append last part
return parts
def _isWordBoundary(prev, char, next):
if char.isupper():
return (prev.islower() or next.islower()) and prev.isalnum()
if char.isdigit():
return prev.isalpha()
return prev.isdigit()
def plural_or_not(item):
count = item if isinstance(item, (int, long)) else len(item)
return '' if count == 1 else 's'
def seq2str(sequence, quote="'", sep=', ', lastsep=' and '):
"""Returns sequence in format 'item 1', 'item 2' and 'item 3'"""
quote_elem = lambda string: quote + unic(string) + quote
if len(sequence) == 0:
return ''
if len(sequence) == 1:
return quote_elem(sequence[0])
elems = [quote_elem(s) for s in sequence[:-2]]
elems.append(quote_elem(sequence[-2]) + lastsep + quote_elem(sequence[-1]))
return sep.join(elems)
def seq2str2(sequence):
"""Returns sequence in format [ item 1 | item 2 | ... ] """
if not sequence:
return '[ ]'
return '[ %s ]' % ' | '.join(unic(item) for item in sequence)
| 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.
"""A module to handle different character widths on the console.
Some East Asian characters have width of two on console, and combining
characters themselves take no extra space.
See issue 604 [1] for more details. It also contains `generate_wild_chars.py`
script that was originally used to create the East Asian wild character map.
Big thanks for xieyanbo for the script and the original patch.
Note that Python's `unicodedata` module is not used here because importing
it takes several seconds on Jython.
[1] http://code.google.com/p/robotframework/issues/detail?id=604
"""
def get_char_width(char):
char = ord(char)
if _char_in_map(char, _COMBINING_CHARS):
return 0
if _char_in_map(char, _EAST_ASIAN_WILD_CHARS):
return 2
return 1
def _char_in_map(char, map):
for begin, end in map:
if char < begin:
break
if begin <= char <= end:
return True
return False
_COMBINING_CHARS = [(768,879)]
_EAST_ASIAN_WILD_CHARS = [
(888, 889), (896, 899), (909, 909), (1316, 1328), (1368, 1368),
(1416, 1416), (1420, 1424), (1481, 1487), (1516, 1519),
(1526, 1535), (1541, 1541), (1565, 1565), (1631, 1631),
(1867, 1868), (1971, 1983), (2044, 2304), (2363, 2363),
(2383, 2383), (2390, 2391), (2420, 2426), (2436, 2436),
(2446, 2446), (2450, 2450), (2481, 2481), (2484, 2485),
(2491, 2491), (2502, 2502), (2506, 2506), (2512, 2518),
(2521, 2523), (2532, 2533), (2556, 2560), (2571, 2574),
(2578, 2578), (2609, 2609), (2615, 2615), (2619, 2619),
(2627, 2630), (2634, 2634), (2639, 2640), (2643, 2648),
(2655, 2661), (2679, 2688), (2702, 2702), (2729, 2729),
(2740, 2740), (2747, 2747), (2762, 2762), (2767, 2767),
(2770, 2783), (2789, 2789), (2802, 2816), (2829, 2830),
(2834, 2834), (2865, 2865), (2874, 2875), (2886, 2886),
(2890, 2890), (2895, 2901), (2905, 2907), (2916, 2917),
(2931, 2945), (2955, 2957), (2966, 2968), (2973, 2973),
(2977, 2978), (2982, 2983), (2988, 2989), (3003, 3005),
(3012, 3013), (3022, 3023), (3026, 3030), (3033, 3045),
(3068, 3072), (3085, 3085), (3113, 3113), (3130, 3132),
(3145, 3145), (3151, 3156), (3162, 3167), (3173, 3173),
(3185, 3191), (3201, 3201), (3213, 3213), (3241, 3241),
(3258, 3259), (3273, 3273), (3279, 3284), (3288, 3293),
(3300, 3301), (3315, 3329), (3341, 3341), (3369, 3369),
(3387, 3388), (3401, 3401), (3407, 3414), (3417, 3423),
(3429, 3429), (3447, 3448), (3457, 3457), (3479, 3481),
(3516, 3516), (3519, 3519), (3528, 3529), (3532, 3534),
(3543, 3543), (3553, 3569), (3574, 3584), (3644, 3646),
(3677, 3712), (3717, 3718), (3723, 3724), (3727, 3731),
(3744, 3744), (3750, 3750), (3753, 3753), (3770, 3770),
(3775, 3775), (3783, 3783), (3791, 3791), (3803, 3803),
(3807, 3839), (3949, 3952), (3981, 3983), (4029, 4029),
(4053, 4095), (4251, 4253), (4295, 4303), (4350, 4447),
(4516, 4519), (4603, 4607), (4686, 4687), (4697, 4697),
(4703, 4703), (4750, 4751), (4790, 4791), (4801, 4801),
(4807, 4807), (4881, 4881), (4887, 4887), (4956, 4958),
(4990, 4991), (5019, 5023), (5110, 5120), (5752, 5759),
(5790, 5791), (5874, 5887), (5909, 5919), (5944, 5951),
(5973, 5983), (6001, 6001), (6005, 6015), (6111, 6111),
(6123, 6127), (6139, 6143), (6170, 6175), (6265, 6271),
(6316, 6399), (6430, 6431), (6445, 6447), (6461, 6463),
(6466, 6467), (6511, 6511), (6518, 6527), (6571, 6575),
(6603, 6607), (6619, 6621), (6685, 6685), (6689, 6911),
(6989, 6991), (7038, 7039), (7084, 7085), (7099, 7167),
(7225, 7226), (7243, 7244), (7297, 7423), (7656, 7677),
(7959, 7959), (7967, 7967), (8007, 8007), (8015, 8015),
(8026, 8026), (8030, 8030), (8063, 8063), (8133, 8133),
(8149, 8149), (8176, 8177), (8191, 8191), (8294, 8297),
(8307, 8307), (8341, 8351), (8375, 8399), (8434, 8447),
(8529, 8530), (8586, 8591), (9002, 9002), (9193, 9215),
(9256, 9279), (9292, 9311), (9887, 9887), (9918, 9919),
(9925, 9984), (9994, 9995), (10060, 10060), (10067, 10069),
(10079, 10080), (10134, 10135), (10175, 10175), (10189, 10191),
(11086, 11087), (11094, 11263), (11359, 11359), (11390, 11391),
(11500, 11512), (11559, 11567), (11623, 11630), (11633, 11647),
(11672, 11679), (11695, 11695), (11711, 11711), (11727, 11727),
(11743, 11743), (11826, 12350), (12353, 19903), (19969, 42239),
(42541, 42559), (42593, 42593), (42613, 42619), (42649, 42751),
(42894, 43002), (43053, 43071), (43129, 43135), (43206, 43213),
(43227, 43263), (43349, 43358), (43361, 43519), (43576, 43583),
(43599, 43599), (43611, 43611), (43617, 55295), (63745, 64255),
(64264, 64274), (64281, 64284), (64317, 64317), (64322, 64322),
(64434, 64466), (64833, 64847), (64913, 64913), (64969, 65007),
(65023, 65023), (65041, 65055), (65064, 65135), (65277, 65278),
(65281, 65376), (65472, 65473), (65481, 65481), (65489, 65489),
(65497, 65497), (65502, 65511), (65520, 65528), (65535, 65535),
]
| 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
# Need different unic implementations for different Pythons because:
# 1) Importing unicodedata module on Jython takes a very long time, and doesn't
# seem to be necessary as Java probably already handles normalization.
# Furthermore, Jython on Java 1.5 doesn't even have unicodedata.normalize.
# 2) IronPython 2.6 doesn't have unicodedata and probably doesn't need it.
# 3) CPython doesn't automatically normalize Unicode strings.
if sys.platform.startswith('java'):
from java.lang import Object, Class
def unic(item, *args):
# http://bugs.jython.org/issue1564
if isinstance(item, Object) and not isinstance(item, Class):
item = item.toString() # http://bugs.jython.org/issue1563
return _unic(item, *args)
elif sys.platform == 'cli':
def unic(item, *args):
return _unic(item, *args)
else:
from unicodedata import normalize
def unic(item, *args):
return normalize('NFC', _unic(item, *args))
def _unic(item, *args):
# Based on a recipe from http://code.activestate.com/recipes/466341
try:
return unicode(item, *args)
except UnicodeError:
try:
ascii_text = str(item).encode('string_escape')
except UnicodeError:
return u"<unrepresentable object '%s'>" % item.__class__.__name__
else:
return unicode(ascii_text)
def safe_repr(item):
try:
return unic(repr(item))
except UnicodeError:
return repr(unic(item))
| 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 UserDict import UserDict
_WHITESPACE_REGEXP = re.compile('\s+')
def normalize(string, ignore=[], caseless=True, spaceless=True):
if spaceless:
string = _WHITESPACE_REGEXP.sub('', string)
if caseless:
string = string.lower()
ignore = [ ign.lower() for ign in ignore ]
for ign in ignore:
string = string.replace(ign, '')
return string
def normalize_tags(tags):
"""Removes duplicates (normalized) and empty tags and sorts tags"""
ret = []
dupes = NormalizedDict({'': 1})
for tag in tags:
if not dupes.has_key(tag):
ret.append(tag)
dupes[tag] = 1
ret.sort(lambda x, y: cmp(normalize(x), normalize(y)))
return ret
class NormalizedDict(UserDict):
def __init__(self, initial={}, ignore=[], caseless=True, spaceless=True):
UserDict.__init__(self)
self._keys = {}
self._normalize = lambda s: normalize(s, ignore, caseless, spaceless)
for key, value in initial.items():
self[key] = value
def update(self, dict=None, **kwargs):
if dict:
UserDict.update(self, dict)
for key in dict:
self._add_key(key)
if kwargs:
self.update(kwargs)
def _add_key(self, key):
nkey = self._normalize(key)
self._keys.setdefault(nkey, key)
return nkey
def __setitem__(self, key, value):
nkey = self._add_key(key)
self.data[nkey] = value
set = __setitem__
def __getitem__(self, key):
return self.data[self._normalize(key)]
def __delitem__(self, key):
nkey = self._normalize(key)
del self.data[nkey]
del self._keys[nkey]
def get(self, key, default=None):
try:
return self.__getitem__(key)
except KeyError:
return default
def has_key(self, key):
return self.data.has_key(self._normalize(key))
__contains__ = has_key
def keys(self):
return self._keys.values()
def __iter__(self):
return self._keys.itervalues()
def items(self):
return [ (key, self[key]) for key in self.keys() ]
def copy(self):
copy = UserDict.copy(self)
copy._keys = self._keys.copy()
return copy
def __str__(self):
return str(dict(self.items()))
| 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 argumentparser import ArgumentParser
from connectioncache import ConnectionCache
from domwrapper import DomWrapper
from encoding import decode_output, encode_output, decode_from_file_system
from error import (get_error_message, get_error_details, ErrorDetails,
RERAISED_EXCEPTIONS)
from escaping import escape, unescape
from htmlutils import html_format, html_escape, html_attr_escape
from htmlwriter import HtmlWriter
from importing import simple_import, import_
from match import eq, eq_any, matches, matches_any
from misc import plural_or_not, printable_name, seq2str, seq2str2
from normalizing import normalize, normalize_tags, NormalizedDict
from robotpath import normpath, abspath, get_link_path
from robottime import (get_timestamp, get_start_timestamp, format_time,
get_time, get_elapsed_time, elapsed_time_to_string,
timestr_to_secs, secs_to_timestr, secs_to_timestamp,
timestamp_to_secs, parse_time)
from text import (cut_long_message, format_assign_message,
pad_console_length, get_console_length)
from unic import unic, safe_repr
from xmlwriter import XmlWriter
import sys
is_jython = sys.platform.startswith('java')
del sys
| 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 normalizing import NormalizedDict
class ConnectionCache:
"""Connection cache for different Robot test libraries that use connections.
This cache stores connections and allows switching between them using
generated indexes or user given aliases. Can be used for example by web
testing libraries where there's need for multiple concurrent connections.
Note that in most cases there should be only one instance of this class but
this is not enforced.
"""
def __init__(self, no_current_msg='No open connection'):
self.current = self._no_current = _NoConnection(no_current_msg)
self.current_index = None
self._connections = []
self._aliases = NormalizedDict()
self._no_current_msg = no_current_msg
def register(self, connection, alias=None):
"""Registers given connection with optional alias and returns its index.
Given connection is set to be the current connection. Alias must be
a string. The index of the first connection after initialization or
close_all or empty_cache is 1, second is 2, etc.
"""
self.current = connection
self._connections.append(connection)
self.current_index = len(self._connections)
if isinstance(alias, basestring):
self._aliases[alias] = self.current_index
return self.current_index
def switch(self, index_or_alias):
"""Switches to the connection specified by given index or alias.
If alias is given it must be a string. Indexes can be either integers
or strings that can be converted into integer. Raises RuntimeError
if no connection with given index or alias found.
"""
try:
index = self._get_index(index_or_alias)
except ValueError:
raise RuntimeError("Non-existing index or alias '%s'" % index_or_alias)
self.current = self._connections[index-1]
self.current_index = index
return self.current
def close_all(self, closer_method='close'):
"""Closes connections using given closer method and empties cache.
If simply calling the closer method is not adequate for closing
connections, clients should close connections themselves and use
empty_cache afterwards.
"""
for conn in self._connections:
getattr(conn, closer_method)()
self.empty_cache()
return self.current
def empty_cache(self):
"""Empties the connections cache.
Indexes of new connections starts from 1 after this."""
self.current = self._no_current
self.current_index = None
self._connections = []
self._aliases = NormalizedDict()
def _get_index(self, index_or_alias):
try:
return self._resolve_alias(index_or_alias)
except ValueError:
return self._resolve_index(index_or_alias)
def _resolve_alias(self, alias):
if isinstance(alias, basestring):
try:
return self._aliases[alias]
except KeyError:
pass
raise ValueError
def _resolve_index(self, index):
index = int(index)
if not 0 < index <= len(self._connections):
raise ValueError
return index
class _NoConnection:
def __init__(self, msg):
self._msg = msg
def __getattr__(self, name):
if name.startswith('__') and name.endswith('__'):
raise AttributeError
raise RuntimeError(self._msg)
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 re
from normalizing import normalize
_match_pattern_tokenizer = re.compile('(\*|\?)')
def eq(str1, str2, ignore=[], caseless=True, spaceless=True):
str1 = normalize(str1, ignore, caseless, spaceless)
str2 = normalize(str2, ignore, caseless, spaceless)
return str1 == str2
def eq_any(str_, str_list, ignore=[], caseless=True, spaceless=True):
str_ = normalize(str_, ignore, caseless, spaceless)
for s in str_list:
if str_ == normalize(s, ignore, caseless, spaceless):
return True
return False
def matches(string, pattern, ignore=[], caseless=True, spaceless=True):
string = normalize(string, ignore, caseless, spaceless)
pattern = normalize(pattern, ignore, caseless, spaceless)
regexp = _get_match_regexp(pattern)
return re.match(regexp, string, re.DOTALL) is not None
def _get_match_regexp(pattern):
regexp = []
for token in _match_pattern_tokenizer.split(pattern):
if token == '*':
regexp.append('.*')
elif token == '?':
regexp.append('.')
else:
regexp.append(re.escape(token))
return '^%s$' % ''.join(regexp)
def matches_any(string, patterns, ignore=[], caseless=True, spaceless=True):
for pattern in patterns:
if matches(string, pattern, ignore, caseless, spaceless):
return True
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 sys
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import AttributesImpl
from abstractxmlwriter import AbstractXmlWriter
class XmlWriter(AbstractXmlWriter):
def __init__(self, path):
self.path = path
self._output = open(path, 'wb')
self._writer = XMLGenerator(self._output, encoding='UTF-8')
self._writer.startDocument()
self.closed = False
def _start(self, name, attrs):
self._writer.startElement(name, AttributesImpl(attrs))
def _content(self, content):
self._writer.characters(content)
def _end(self, name):
self._writer.endElement(name)
# Workaround for http://ironpython.codeplex.com/workitem/29474
if sys.platform == 'cli':
def _escape(self, content):
return AbstractXmlWriter._escape(self, content).encode('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 robot.version import get_version
from robot import utils
class _List:
def convert_to_list(self, item):
"""Converts the given `item` to a list.
Mainly useful for converting tuples and other iterable to lists.
Use `Create List` from the BuiltIn library for constructing new lists.
"""
return list(item)
def append_to_list(self, list_, *values):
"""Adds `values` to the end of `list`.
Example:
| Append To List | ${L1} | xxx | | |
| Append To List | ${L2} | x | y | z |
=>
- ${L1} = ['a', 'xxx']
- ${L2} = ['a', 'b', 'x', 'y', 'z']
"""
for value in values:
list_.append(value)
def insert_into_list(self, list_, index, value):
"""Inserts `value` into `list` to the position specified with `index`.
Index '0' adds the value into the first position, '1' to the second,
and so on. Inserting from right works with negative indices so that
'-1' is the second last position, '-2' third last, and so on. Use
`Append To List` to add items to the end of the list.
If the absolute value of the index is greater than
the length of the list, the value is added at the end
(positive index) or the beginning (negative index). An index
can be given either as an integer or a string that can be
converted to an integer.
Example:
| Insert Into List | ${L1} | 0 | xxx |
| Insert Into List | ${L2} | ${-1} | xxx |
=>
- ${L1} = ['xxx', 'a']
- ${L2} = ['a', 'xxx', 'b']
"""
list_.insert(self._index_to_int(index), value)
def combine_lists(self, *lists):
"""Combines the given `lists` together and returns the result.
The given lists are never altered by this keyword.
Example:
| ${x} = | Combine List | ${L1} | ${L2} | |
| ${y} = | Combine List | ${L1} | ${L2} | ${L1} |
=>
- ${x} = ['a', 'a', 'b']
- ${y} = ['a', 'a', 'b', 'a']
- ${L1} and ${L2} are not changed.
"""
ret = []
for item in lists:
ret.extend(item)
return ret
def set_list_value(self, list_, index, value):
"""Sets the value of `list` specified by `index` to the given `value`.
Index '0' means the first position, '1' the second and so on.
Similarly, '-1' is the last position, '-2' second last, and so on.
Using an index that does not exist on the list causes an error.
The index can be either an integer or a string that can be converted to
an integer.
Example:
| Set List Value | ${L3} | 1 | xxx |
| Set List Value | ${L3} | -1 | yyy |
=>
- ${L3} = ['a', 'xxx', 'yyy']
"""
try:
list_[self._index_to_int(index)] = value
except IndexError:
self._index_error(list_, index)
def remove_values_from_list(self, list_, *values):
"""Removes all occurences of given `values` from `list`.
It is not an error is a value does not exist in the list at all.
Example:
| Remove Values From List | ${L4} | a | c | e | f |
=>
- ${L4} = ['b', 'd']
"""
for value in values:
while value in list_:
list_.remove(value)
def remove_from_list(self, list_, index):
"""Removes and returns the value specified with an `index` from `list`.
Index '0' means the first position, '1' the second and so on.
Similarly, '-1' is the last position, '-2' the second last, and so on.
Using an index that does not exist on the list causes an error.
The index can be either an integer or a string that can be converted
to an integer.
Example:
| ${x} = | Remove From List | ${L2} | 0 |
=>
- ${x} = 'a'
- ${L2} = ['b']
"""
try:
return list_.pop(self._index_to_int(index))
except IndexError:
self._index_error(list_, index)
def get_from_list(self, list_, index):
"""Returns the value specified with an `index` from `list`.
The given list is never altered by this keyword.
Index '0' means the first position, '1' the second, and so on.
Similarly, '-1' is the last position, '-2' the second last, and so on.
Using an index that does not exist on the list causes an error.
The index can be either an integer or a string that can be converted
to an integer.
Examples (including Python equivalents in comments):
| ${x} = | Get From List | ${L5} | 0 | # L5[0] |
| ${y} = | Get From List | ${L5} | -2 | # L5[-2] |
=>
- ${x} = 'a'
- ${y} = 'd'
- ${L5} is not changed
"""
try:
return list_[self._index_to_int(index)]
except IndexError:
self._index_error(list_, index)
def get_slice_from_list(self, list_, start=0, end=None):
"""Returns a slice of the given list between `start` and `end` indexes.
The given list is never altered by this keyword.
If both `start` and `end` are given, a sublist containing values from
`start` to `end` is returned. This is the same as 'list[start:end]' in
Python. To get all items from the beginning, use 0 as the start value,
and to get all items until the end, use 'None' as the end value. 'None'
is also a default value, so in this case, it is enough to give only
`start`. If only `end` is given, `start` gets the value 0.
Using `start` or `end` not found on the list is the same as using the
largest (or smallest) available index.
Examples (incl. Python equivelants in comments):
| ${x} = | Get Slice From List | ${L5} | 2 | 4 | # L5[2:4] |
| ${y} = | Get Slice From List | ${L5} | 1 | | # L5[1:None] |
| ${z} = | Get Slice From List | ${L5} | | -2 | # L5[0:-2] |
=>
- ${x} = ['c', 'd']
- ${y} = ['b', 'c', 'd', 'e']
- ${z} = ['a', 'b', 'c']
- ${L5} is not changed
"""
start = self._index_to_int(start, True)
if end is not None:
end = self._index_to_int(end)
return list_[start:end]
def count_values_in_list(self, list_, value, start=0, end=None):
"""Returns the number of occurrences of the given `value` in `list`.
The search can be narrowed to the selected sublist by the `start` and
`end` indexes having the same semantics as in the `Get Slice From List`
keyword. The given list is never altered by this keyword.
Example:
| ${x} = | Count Values In List | ${L3} | b |
=>
- ${x} = 1
- ${L3} is not changed
"""
return self.get_slice_from_list(list_, start, end).count(value)
def get_index_from_list(self, list_, value, start=0, end=None):
"""Returns the index of the first occurrence of the `value` on the list.
The search can be narrowed to the selected sublist by the `start` and
`end` indexes having the same semantics as in the `Get Slice From List`
keyword. In case the value is not found, -1 is returned. The given list
is never altered by this keyword.
Example:
| ${x} = | Get Index From List | ${L5} | d |
=>
- ${x} = 3
- ${L5} is not changed
"""
if start == '':
start = 0
list_ = self.get_slice_from_list(list_, start, end)
try:
return int(start) + list_.index(value)
except ValueError:
return -1
def copy_list(self, list_):
"""Returns a copy of the given list.
The given list is never altered by this keyword.
"""
return list_[:]
def reverse_list(self, list_):
"""Reverses the given list in place.
Note that the given list is changed and nothing is returned. Use
`Copy List` first, if you need to keep also the original order.
| Reverse List | ${L3} |
=>
- ${L3} = ['c', 'b', 'a']
"""
list_.reverse()
def sort_list(self, list_):
"""Sorts the given list in place.
The strings are sorted alphabetically and the numbers numerically.
Note that the given list is changed and nothing is returned. Use
`Copy List` first, if you need to keep also the original order.
${L} = [2,1,'a','c','b']
| Sort List | ${L} |
=>
- ${L} = [1, 2, 'a', 'b', 'c']
"""
list_.sort()
def list_should_contain_value(self, list_, value, msg=None):
"""Fails if the `value` is not found from `list`.
If `msg` is not given, the default error message "[ a | b | c ] does
not contain the value 'x'" is shown in case of a failure. Otherwise,
the given `msg` is used in case of a failure.
"""
default = "%s does not contain value '%s'" % (utils.seq2str2(list_),
value)
_verify_condition(value in list_, default, msg)
def list_should_not_contain_value(self, list_, value, msg=None):
"""Fails if the `value` is not found from `list`.
See `List Should Contain Value` for an explanation of `msg`.
"""
default = "%s contains value '%s'" % (utils.seq2str2(list_), value)
_verify_condition(value not in list_, default, msg)
def list_should_not_contain_duplicates(self, list_, msg=None):
"""Fails if any element in the `list` is found from it more than once.
The default error message lists all the elements that were found
from the `list` multiple times, but it can be overridden by giving
a custom `msg`. All multiple times found items and their counts are
also logged.
This keyword works with all iterables that can be converted to a list.
The original iterable is never altered.
"""
if not isinstance(list_, list):
list_ = list(list_)
dupes = []
for item in list_:
if item not in dupes:
count = list_.count(item)
if count > 1:
print "*INFO* '%s' found %d times" % (item, count)
dupes.append(item)
if dupes:
if not msg:
msg = '%s found multiple times' % utils.seq2str(dupes)
raise AssertionError(msg)
def lists_should_be_equal(self, list1, list2, msg=None, values=True):
"""Fails if given lists are unequal.
The keyword first verifies that the lists have equal lengths, and
then it checks are all the values equal. Possible differences between
the values are listed in the default error message.
- If `msg` is not given, the default error message is used.
- If `msg` is given and `values` is either Boolean False or a string
'False' or 'No Values', the error message is simply `msg`.
- Otherwise the error message is `msg` + 'new line' + default.
"""
len1 = len(list1); len2 = len(list2)
default = 'Lengths are different: %d != %d' % (len1, len2)
_verify_condition(len1 == len2, default, msg, values)
diffs = [ 'Index %d: %s != %s' % (i, list1[i], list2[i])
for i in range(len1) if list1[i] != list2[i] ]
default = 'Lists are different:\n' + '\n'.join(diffs)
_verify_condition(diffs == [], default, msg, values)
def list_should_contain_sub_list(self, list1, list2, msg=None, values=True):
"""Fails if not all of the elements in `list2` are found in `list1`.
The order of values and the number of values are not taken into
account.
See the use of `msg` and `values` from the `Lists Should Be Equal`
keyword.
"""
diffs = ', '.join([ utils.unic(item) for item in list2 if item not in list1 ])
default = 'Following values were not found from first list: ' + diffs
_verify_condition(diffs == '', default, msg, values)
def log_list(self, list_, level='INFO'):
"""Logs the length and contents of the `list` using given `level`.
Valid levels are TRACE, DEBUG, INFO (default), and WARN.
If you only want to the length, use keyword `Get Length` from
the BuiltIn library.
"""
print '*%s* ' % level.upper(),
if len(list_) == 0:
print 'List is empty'
elif len(list_) == 1:
print 'List has one item:\n%s' % list_[0]
else:
print 'List length is %d and it contains following items:' \
% len(list_)
for index, item in enumerate(list_):
print '%s: %s' % (index, item)
def _index_to_int(self, index, empty_to_zero=False):
if empty_to_zero and not index:
return 0
try:
return int(index)
except ValueError:
raise ValueError("Cannot convert index '%s' to an integer" % index)
def _index_error(self, list_, index):
raise IndexError('Given index %s is out of the range 0-%d'
% (index, len(list_)-1))
class _Dictionary:
def create_dictionary(self, *key_value_pairs):
"""Creates and returns a dictionary from the given `key_value_pairs`.
Examples:
| ${x} = | Create Dictionary | name | value | | |
| ${y} = | Create Dictionary | a | 1 | b | 2 |
| ${z} = | Create Dictionary | a | ${1} | b | ${2} |
=>
- ${x} = {'name': 'value'}
- ${y} = {'a': '1', 'b': '2'}
- ${z} = {'a': 1, 'b': 2}
"""
if len(key_value_pairs) % 2 != 0:
raise ValueError("Creating a dictionary failed. There should be "
"an even number of key-value-pairs.")
return self.set_to_dictionary({}, *key_value_pairs)
def set_to_dictionary(self, dictionary, *key_value_pairs):
"""Adds the given `key_value_pairs` to the `dictionary`.
Example:
| Set To Dictionary | ${D1} | key | value |
=>
- ${D1} = {'a': 1, 'key': 'value'}
"""
if len(key_value_pairs) % 2 != 0:
raise ValueError("Adding data to a dictionary failed. There "
"should be an even number of key-value-pairs.")
for i in range(0, len(key_value_pairs), 2):
dictionary[key_value_pairs[i]] = key_value_pairs[i+1]
return dictionary
def remove_from_dictionary(self, dictionary, *keys):
"""Removes the given `keys` from the `dictionary`.
If the given `key` cannot be found from the `dictionary`, it
is ignored.
Example:
| Remove From Dictionary | ${D3} | b | x | y |
=>
- ${D3} = {'a': 1, 'c': 3}
"""
for key in keys:
try:
value = dictionary.pop(key)
print "Removed item with key '%s' and value '%s'" % (key, value)
except KeyError:
print "Key '%s' not found" % (key)
def keep_in_dictionary(self, dictionary, *keys):
"""Keeps the given `keys` in the `dictionary` and removes all other.
If the given `key` cannot be found from the `dictionary`, it
is ignored.
Example:
| Keep In Dictionary | ${D5} | b | x | d |
=>
- ${D5} = {'b': 2, 'd': 4}
"""
remove_keys = [ key for key in dictionary.keys() if not key in keys ]
self.remove_from_dictionary(dictionary, *remove_keys)
def copy_dictionary(self, dictionary):
"""Returns a copy of the given dictionary.
The given dictionary is never altered by this keyword.
"""
return dictionary.copy()
def get_dictionary_keys(self, dictionary):
"""Returns `keys` of the given `dictionary`.
`Keys` are returned in sorted order. The given `dictionary` is never
altered by this keyword.
Example:
| ${keys} = | Get Dictionary Keys | ${D3} |
=>
- ${keys} = ['a', 'b', 'c']
"""
keys = dictionary.keys()
keys.sort()
return keys
def get_dictionary_values(self, dictionary):
"""Returns values of the given dictionary.
Values are returned sorted according to keys. The given dictionary is
never altered by this keyword.
Example:
| ${values} = | Get Dictionary Values | ${D3} |
=>
- ${values} = [1, 2, 3]
"""
return [ dictionary[k] for k in self.get_dictionary_keys(dictionary) ]
def get_dictionary_items(self, dictionary):
"""Returns items of the given `dictionary`.
Items are returned sorted by keys. The given `dictionary` is never
altered by this keyword.
Example:
| ${items} = | Get Dictionary Items | ${D3} |
=>
- ${items} = ['a', 1, 'b', 2, 'c', 3]
"""
ret = []
for key in self.get_dictionary_keys(dictionary):
ret.extend((key, dictionary[key]))
return ret
def get_from_dictionary(self, dictionary, key):
"""Returns a value from the given `dictionary` based on the given `key`.
If the given `key` cannot be found from the `dictionary`, this keyword
fails.
The given dictionary is never altered by this keyword.
Example:
| ${value} = | Get From Dictionary | ${D3} | b |
=>
- ${value} = 2
"""
try:
return dictionary[key]
except KeyError:
raise RuntimeError("Dictionary does not contain key '%s'" % key)
def dictionary_should_contain_key(self, dictionary, key, msg=None):
"""Fails if `key` is not found from `dictionary`.
See `List Should Contain Value` for an explanation of `msg`.
The given dictionary is never altered by this keyword.
"""
default = "Dictionary does not contain key '%s'" % key
_verify_condition(dictionary.has_key(key), default, msg)
def dictionary_should_not_contain_key(self, dictionary, key, msg=None):
"""Fails if `key` is found from `dictionary`.
See `List Should Contain Value` for an explanation of `msg`.
The given dictionary is never altered by this keyword.
"""
default = "Dictionary contains key '%s'" % key
_verify_condition(not dictionary.has_key(key), default, msg)
def dictionary_should_contain_value(self, dictionary, value, msg=None):
"""Fails if `value` is not found from `dictionary`.
See `List Should Contain Value` for an explanation of `msg`.
The given dictionary is never altered by this keyword.
"""
default = "Dictionary does not contain value '%s'" % value
_verify_condition(value in dictionary.values(), default, msg)
def dictionary_should_not_contain_value(self, dictionary, value, msg=None):
"""Fails if `value` is found from `dictionary`.
See `List Should Contain Value` for an explanation of `msg`.
The given dictionary is never altered by this keyword.
"""
default = "Dictionary contains value '%s'" % value
_verify_condition(not value in dictionary.values(), default, msg)
def dictionaries_should_be_equal(self, dict1, dict2, msg=None, values=True):
"""Fails if the given dictionaries are not equal.
First the equality of dictionaries' keys is checked and after that all
the key value pairs. If there are differences between the values, those
are listed in the error message.
See `Lists Should Be Equal` for an explanation of `msg`.
The given dictionaries are never altered by this keyword.
"""
keys = self._keys_should_be_equal(dict1, dict2, msg, values)
self._key_values_should_be_equal(keys, dict1, dict2, msg, values)
def dictionary_should_contain_sub_dictionary(self, dict1, dict2, msg=None,
values=True):
"""Fails unless all items in `dict2` are found from `dict1`.
See `Lists Should Be Equal` for an explanation of `msg`.
The given dictionaries are never altered by this keyword.
"""
keys = self.get_dictionary_keys(dict2)
diffs = [ utils.unic(k) for k in keys if k not in dict1 ]
default = "Following keys missing from first dictionary: %s" \
% ', '.join(diffs)
_verify_condition(diffs == [], default, msg, values)
self._key_values_should_be_equal(keys, dict1, dict2, msg, values)
def log_dictionary(self, dictionary, level='INFO'):
"""Logs the size and contents of the `dictionary` using given `level`.
Valid levels are TRACE, DEBUG, INFO (default), and WARN.
If you only want to log the size, use keyword `Get Length` from
the BuiltIn library.
"""
print '*%s* ' % level.upper(),
if len(dictionary) == 0:
print 'Dictionary is empty'
elif len(dictionary) == 1:
print 'Dictionary has one item:'
else:
print 'Dictionary size is %d and it contains following items:' \
% len(dictionary)
for key in self.get_dictionary_keys(dictionary):
print '%s: %s' % (key, dictionary[key])
def _keys_should_be_equal(self, dict1, dict2, msg, values):
keys1 = self.get_dictionary_keys(dict1)
keys2 = self.get_dictionary_keys(dict2)
miss1 = [ utils.unic(k) for k in keys2 if k not in dict1 ]
miss2 = [ utils.unic(k) for k in keys1 if k not in dict2 ]
error = []
if miss1:
error += [ 'Following keys missing from first dictionary: %s'
% ', '.join(miss1) ]
if miss2:
error += [ 'Following keys missing from second dictionary: %s'
% ', '.join(miss2) ]
_verify_condition(error == [], '\n'.join(error), msg, values)
return keys1
def _key_values_should_be_equal(self, keys, dict1, dict2, msg, values):
diffs = [ 'Key %s: %s != %s' % (k, dict1[k], dict2[k])
for k in keys if dict1[k] != dict2[k] ]
default = 'Following keys have different values:\n' + '\n'.join(diffs)
_verify_condition(diffs == [], default, msg, values)
class Collections(_List, _Dictionary):
"""A test library providing keywords for handling lists and dictionaries.
`Collections` is Robot Framework's standard library that provides a
set of keywords for handling Python lists and dictionaries. This
library has keywords, for example, for modifying and getting
values from lists and dictionaries (e.g. `Append To List`, `Get
From Dictionary`) and for verifying their contents (e.g. `Lists
Should Be Equal`, `Dictionary Should Contain Value`).
Following keywords from the BuiltIn library can also be used with
lists and dictionaries:
| *Keyword Name* | *Applicable With* |
| `Create List` | lists |
| `Get Length` | both |
| `Length Should Be` | both |
| `Should Be Empty` | both |
| `Should Not Be Empty` | both |
| `Should Contain` | lists |
| `Should Not Contain` | lists |
| `Should Contain X Times` | lists |
| `Should Not Contain X Times` | lists |
| `Get Count` | lists |
All list keywords expect a scalar variable (e.g. ${list}) as an
argument. It is, however, possible to use list variables
(e.g. @{list}) as scalars simply by replacing '@' with '$'.
List keywords that do not alter the given list can also be used
with tuples, and to some extend also with other iterables.
`Convert To List` can be used to convert tuples and other iterables
to lists.
-------
List related keywords use variables in format ${Lx} in their examples,
which means a list with as many alphabetic characters as specified by 'x'.
For example ${L1} means ['a'] and ${L3} means ['a', 'b', 'c'].
Dictionary keywords use similar ${Dx} variables. For example ${D1} means
{'a': 1} and ${D3} means {'a': 1, 'b': 2, 'c': 3}.
--------
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = get_version()
def _verify_condition(condition, default_msg, given_msg, include_default=False):
if not condition:
if not given_msg:
raise AssertionError(default_msg)
if _include_default_message(include_default):
raise AssertionError(given_msg + '\n' + default_msg)
raise AssertionError(given_msg)
def _include_default_message(include):
if isinstance(include, basestring):
return include.lower() not in ['no values', 'false']
return bool(include)
| 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.
RESERVED_KEYWORDS = [ 'for', 'while', 'break', 'continue', 'end',
'if', 'else', 'elif', 'else if', 'return' ]
class Reserved:
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
def get_keyword_names(self):
return RESERVED_KEYWORDS
def run_keyword(self, name, args):
raise Exception("'%s' is a reserved keyword" % name.title())
| 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.
def none_shall_pass(who):
if who is not None:
raise AssertionError('None shall pass!')
print '*HTML* <object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/dhRUe-gz690&hl=en_US&fs=1&rel=0&color1=0x234900&color2=0x4e9e00"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/dhRUe-gz690&hl=en_US&fs=1&rel=0&color1=0x234900&color2=0x4e9e00" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>'
| 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 sys.platform.startswith('java'):
from java.awt import Toolkit, Robot, Rectangle
from javax.imageio import ImageIO
from java.io import File
else:
try:
import wx
_wx_app_reference = wx.PySimpleApp()
except ImportError:
wx = None
try:
from gtk import gdk
except ImportError:
gdk = None
try:
from PIL import ImageGrab # apparently available only on Windows
except ImportError:
ImageGrab = None
from robot.version import get_version
from robot import utils
from robot.libraries.BuiltIn import BuiltIn
class Screenshot(object):
"""A test library for taking screenshots and embedding them into log files.
*Using with Jython*
On Jython this library uses Java AWT APIs. They are always available
and thus no external modules are needed.
*Using with Python*
On Python you need to have one of the following modules installed to be
able to use this library. The first module that is found will be used.
- wxPython :: http://wxpython.org :: Required also by RIDE so many Robot
Framework users already have this module installed.
- PyGTK :: http://pygtk.org :: This module is available by default on most
Linux distributions.
- Python Imaging Library (PIL) :: http://www.pythonware.com/products/pil ::
This module can take screenshots only on Windows.
Python support was added in Robot Framework 2.5.5.
*Where screenshots are saved*
By default screenshots are saved into the same directory where the Robot
Framework log file is written. If no log is created, screenshots are saved
into the directory where the XML output file is written.
It is possible to specify a custom location for screenshots using
`screenshot_directory` argument in `importing` and `Set Screenshot Directory`
keyword during execution. It is also possible to save screenshots using
an absolute path.
Note that prior to Robot Framework 2.5.5 the default screenshot location
was system's temporary directory.
*Changes in Robot Framework 2.5.5 and Robot Framework 2.6*
This library was heavily enhanced in Robot Framework 2.5.5 release. The
changes are listed below and explained more thoroughly in affected places.
- The support for using this library on Python (see above) was added.
- The default location where screenshots are saved was changed (see above).
- New `Take Screenshot` and `Take Screenshot Without Embedding` keywords
were added. These keywords should be used for taking screenshots in
the future. Other screenshot taking keywords will be deprecated and
removed later.
- `log_file_directory` argument was deprecated everywhere it was used.
In Robot Framework 2.6, following additional changes were made:
- `log_file_directory` argument was removed altogether.
- `Set Screenshot Directories` keyword was removed.
- `Save Screenshot`, `Save Screenshot To` and `Log Screenshot`
keywords were deprecated. They will be removed in 2.7 version.
"""
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
ROBOT_LIBRARY_VERSION = get_version()
def __init__(self, screenshot_directory=None):
"""Configure where screenshots are saved.
If `screenshot_directory` is not given, screenshots are saved into
same directory as the log file. The directory can also be set using
`Set Screenshot Directory` keyword.
Examples (use only one of these):
| *Setting* | *Value* | *Value* | *Value* |
| Library | Screenshot | | # Default location |
| Library | Screenshot | ${TEMPDIR} | # System temp (this was default prior to 2.5.5) |
"""
self._given_screenshot_dir = self._norm_path(screenshot_directory)
self._screenshot_taker = ScreenshotTaker()
def _norm_path(self, path):
if not path:
return path
return os.path.normpath(path.replace('/', os.sep))
@property
def _screenshot_dir(self):
return self._given_screenshot_dir or self._log_dir
@property
def _log_dir(self):
variables = BuiltIn().get_variables()
outdir = variables['${OUTPUTDIR}']
log = variables['${LOGFILE}']
log = os.path.dirname(log) if log != 'NONE' else '.'
return self._norm_path(os.path.join(outdir, log))
def set_screenshot_directory(self, path):
"""Sets the directory where screenshots are saved.
It is possible to use `/` as a path separator in all operating systems.
Path to the old directory is returned.
The directory can also be set in `importing`.
"""
path = self._norm_path(path)
if not os.path.isdir(path):
raise RuntimeError("Directory '%s' does not exist." % path)
old = self._screenshot_dir
self._given_screenshot_dir = path
return old
def save_screenshot_to(self, path):
"""*DEPRECATED* Use `Take Screenshot` or `Take Screenshot Without Embedding` instead."""
path = self._screenshot_to_file(path)
self._link_screenshot(path)
return path
def save_screenshot(self, basename="screenshot", directory=None):
"""*DEPRECATED* Use `Take Screenshot` or `Take Screenshot Without Embedding` instead."""
path = self._save_screenshot(basename, directory)
self._link_screenshot(path)
return path
def log_screenshot(self, basename='screenshot', directory=None,
width='100%'):
"""*DEPRECATED* Use `Take Screenshot` or `Take Screenshot Without Embedding` instead."""
path = self._save_screenshot(basename, directory)
self._embed_screenshot(path, width)
return path
def take_screenshot(self, name="screenshot", width="800px"):
"""Takes a screenshot and embeds it into the log file.
Name of the file where the screenshot is stored is derived from `name`.
If `name` ends with extension `.jpg` or `.jpeg`, the screenshot will be
stored with that name. Otherwise a unique name is created by adding
underscore, a running index and extension to the `name`.
The name will be interpreted to be relative to the directory where
the log file is written. It is also possible to use absolute paths.
`width` specifies the size of the screenshot in the log file.
The path where the screenshot is saved is returned.
Examples: (LOGDIR is determined automatically by the library)
| Take Screenshot | | | # LOGDIR/screenshot_1.jpg (index automatically incremented) |
| Take Screenshot | mypic | | # LOGDIR/mypic_1.jpg (index automatically incremented) |
| Take Screenshot | ${TEMPDIR}/mypic | | # /tmp/mypic_1.jpg (index automatically incremented) |
| Take Screenshot | pic.jpg | | # LOGDIR/pic.jpg (always uses this file) |
| Take Screenshot | images/login.jpg | 80% | # Specify both name and width. |
| Take Screenshot | width=550px | | # Specify only width. |
Screenshots can be only taken in JPEG format. It is possible to use `/`
as a path separator in all operating systems.
"""
path = self._save_screenshot(name)
self._embed_screenshot(path, width)
return path
def take_screenshot_without_embedding(self, name="screenshot"):
"""Takes a screenshot and links it from the log file.
This keyword is otherwise identical to `Take Screenshot` but the saved
screenshot is not embedded into the log file. The screenshot is linked
so it is nevertheless easily available.
"""
path = self._save_screenshot(name)
self._link_screenshot(path)
return path
def _save_screenshot(self, basename, directory=None):
path = self._get_screenshot_path(basename, directory)
return self._screenshot_to_file(path)
def _screenshot_to_file(self, path):
path = utils.abspath(self._norm_path(path))
self._validate_screenshot_path(path)
print '*DEBUG* Using %s modules for taking screenshot.' \
% self._screenshot_taker.module
self._screenshot_taker(path)
return path
def _validate_screenshot_path(self, path):
if not os.path.exists(os.path.dirname(path)):
raise RuntimeError("Directory '%s' where to save the screenshot does "
"not exist" % os.path.dirname(path))
def _get_screenshot_path(self, basename, directory):
directory = self._norm_path(directory) if directory else self._screenshot_dir
if basename.lower().endswith(('.jpg', '.jpeg')):
return os.path.join(directory, basename)
index = 0
while True:
index += 1
path = os.path.join(directory, "%s_%d.jpg" % (basename, index))
if not os.path.exists(path):
return path
def _embed_screenshot(self, path, width):
link = utils.get_link_path(path, self._log_dir)
print '*HTML* <a href="%s"><img src="%s" width="%s" /></a>' \
% (link, link, width)
def _link_screenshot(self, path):
link = utils.get_link_path(path, self._log_dir)
print "*HTML* Screenshot saved to '<a href=\"%s\">%s</a>'." % (link, path)
class ScreenshotTaker(object):
def __init__(self, module_name=None):
self._screenshot = self._get_screenshot_taker(module_name)
self.module = self._screenshot.__name__.split('_')[1]
def __call__(self, path):
self._screenshot(path)
def _get_screenshot_taker(self, module_name):
if sys.platform.startswith('java'):
return self._java_screenshot
if module_name:
method_name = '_%s_screenshot' % module_name.lower()
if hasattr(self, method_name):
return getattr(self, method_name)
return self._get_default_screenshot_taker()
def _get_default_screenshot_taker(self):
for module, screenshot_taker in [(wx, self._wx_screenshot),
(gdk, self._gtk_screenshot),
(ImageGrab, self._pil_screenshot),
(True, self._no_screenshot)]:
if module:
return screenshot_taker
def _java_screenshot(self, path):
size = Toolkit.getDefaultToolkit().getScreenSize()
rectangle = Rectangle(0, 0, size.width, size.height)
image = Robot().createScreenCapture(rectangle)
ImageIO.write(image, 'jpg', File(path))
def _wx_screenshot(self, path):
context = wx.ScreenDC()
width, height = context.GetSize()
bitmap = wx.EmptyBitmap(width, height, -1)
memory = wx.MemoryDC()
memory.SelectObject(bitmap)
memory.Blit(0, 0, width, height, context, -1, -1)
memory.SelectObject(wx.NullBitmap)
bitmap.SaveFile(path, wx.BITMAP_TYPE_JPEG)
def _gtk_screenshot(self, path):
window = gdk.get_default_root_window()
if not window:
raise RuntimeError('Taking screenshot failed')
width, height = window.get_size()
pb = gdk.Pixbuf(gdk.COLORSPACE_RGB, False, 8, width, height)
pb = pb.get_from_drawable(window, window.get_colormap(),
0, 0, 0, 0, width, height)
if not pb:
raise RuntimeError('Taking screenshot failed')
pb.save(path, 'jpeg')
def _pil_screenshot(self, path):
ImageGrab.grab().save(path, 'JPEG')
def _no_screenshot(self, path):
raise RuntimeError('Taking screenshots is not supported on this platform '
'by default. See library documentation for details.')
if __name__ == "__main__":
if len(sys.argv) not in [2, 3]:
print "Usage: %s path [wx|gtk|pil]" % os.path.basename(sys.argv[0])
sys.exit(1)
path = utils.abspath(sys.argv[1])
module = sys.argv[2] if len(sys.argv) == 3 else None
shooter = ScreenshotTaker(module)
print 'Using %s modules' % shooter.module
shooter(path)
print 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.
"""A test library providing dialogs for interacting with users.
`Dialogs` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.
Note: Dialogs library cannot be used with timeouts on Windows with Python.
"""
__all__ = ['execute_manual_step', 'get_value_from_user',
'get_selection_from_user', 'pause_execution']
import sys
try:
from robot.version import get_version as _get_version
except ImportError:
__version__ = 'unknown'
else:
__version__ = _get_version()
DIALOG_TITLE = 'Robot Framework'
def pause_execution(message='Test execution paused. Press OK to continue.'):
"""Pauses the test execution and shows dialog with the text `message`. """
MessageDialog(message)
def execute_manual_step(message, default_error=''):
"""Pauses the test execution until user sets the keyword status.
`message` is the instruction shown in the dialog. User can select
PASS or FAIL, and in the latter case an additional dialog is
opened for defining the error message. `default_error` is the
possible default value shown in the error message dialog.
"""
if not PassFailDialog(message).result:
msg = get_value_from_user('Give error message:', default_error)
raise AssertionError(msg)
def get_value_from_user(message, default_value=''):
"""Pauses the test execution and asks user to input a value.
`message` is the instruction shown in the dialog. `default_value` is the
possible default value shown in the input field. Selecting 'Cancel' fails
the keyword.
"""
return _validate_user_input(InputDialog(message, default_value).result)
def get_selection_from_user(message, *values):
"""Pauses the test execution and asks user to select value
`message` is the instruction shown in the dialog. and `values` are
the options given to the user. Selecting 'Cancel' fails the keyword.
This keyword was added into Robot Framework 2.1.2.
"""
return _validate_user_input(SelectionDialog(message, values).result)
def _validate_user_input(value):
if value is None:
raise ValueError('No value provided by user')
return value
if not sys.platform.startswith('java'):
from Tkinter import (Tk, Toplevel, Frame, Listbox, Label, Button,
BOTH, END, LEFT)
import tkMessageBox
import tkSimpleDialog
from threading import currentThread
def prevent_execution_with_timeouts(method):
def check_timeout(*args):
if 'linux' not in sys.platform \
and currentThread().getName() != 'MainThread':
raise RuntimeError('Dialogs library is not supported with '
'timeouts on Python on this platform.')
return method(*args)
return check_timeout
class _AbstractTkDialog(Toplevel):
@prevent_execution_with_timeouts
def __init__(self, title):
parent = Tk()
parent.withdraw()
Toplevel.__init__(self, parent)
self._init_dialog(parent, title)
self._create_body()
self._create_buttons()
self.result = None
self._initial_focus.focus_set()
self.wait_window(self)
def _init_dialog(self, parent, title):
self.title(title)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self._right_clicked)
self.geometry("+%d+%d" % (parent.winfo_rootx()+150,
parent.winfo_rooty()+150))
def _create_body(self):
frame = Frame(self)
self._initial_focus = self.create_components(frame)
frame.pack(padx=5, pady=5, expand=1, fill=BOTH)
def _create_buttons(self):
frame = Frame(self)
self._create_button(frame, self._left_button, self._left_clicked)
self._create_button(frame, self._right_button, self._right_clicked)
self.bind("<Escape>", self._right_clicked)
frame.pack()
def _create_button(self, parent, label, command):
w = Button(parent, text=label, width=10, command=command)
w.pack(side=LEFT, padx=5, pady=5)
def _left_clicked(self, event=None):
if not self.validate():
self._initial_focus.focus_set()
return
self.withdraw()
self.apply()
self.destroy()
def _right_clicked(self, event=None):
self.destroy()
def create_components(self, parent):
raise NotImplementedError()
def validate(self):
raise NotImplementedError()
def apply(self):
raise NotImplementedError()
class MessageDialog(object):
@prevent_execution_with_timeouts
def __init__(self, message):
Tk().withdraw()
tkMessageBox.showinfo(DIALOG_TITLE, message)
class InputDialog(object):
@prevent_execution_with_timeouts
def __init__(self, message, default):
Tk().withdraw()
self.result = tkSimpleDialog.askstring(DIALOG_TITLE, message,
initialvalue=default)
class SelectionDialog(_AbstractTkDialog):
_left_button = 'OK'
_right_button = 'Cancel'
def __init__(self, message, values):
self._message = message
self._values = values
_AbstractTkDialog.__init__(self, "Select one option")
def create_components(self, parent):
Label(parent, text=self._message).pack(fill=BOTH)
self._listbox = Listbox(parent)
self._listbox.pack(fill=BOTH)
for item in self._values:
self._listbox.insert(END, item)
return self._listbox
def validate(self):
return bool(self._listbox.curselection())
def apply(self):
self.result = self._listbox.get(self._listbox.curselection())
class PassFailDialog(_AbstractTkDialog):
_left_button = 'PASS'
_right_button = 'FAIL'
def __init__(self, message):
self._message = message
_AbstractTkDialog.__init__(self, DIALOG_TITLE)
def create_components(self, parent):
label = Label(parent, text=self._message)
label.pack(fill=BOTH)
return label
def validate(self):
return True
def apply(self):
self.result = True
else:
import time
from javax.swing import JOptionPane
from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \
YES_NO_OPTION, OK_CANCEL_OPTION, DEFAULT_OPTION
class _AbstractSwingDialog:
def __init__(self, message):
self.result = self._show_dialog(message)
def _show_dialog(self, message):
self._init_dialog(message)
self._show_dialog_and_wait_it_to_be_closed()
return self._get_value()
def _show_dialog_and_wait_it_to_be_closed(self):
dialog = self._pane.createDialog(None, DIALOG_TITLE)
dialog.setModal(0);
dialog.show()
while dialog.isShowing():
time.sleep(0.2)
dialog.dispose()
def _get_value(self):
value = self._pane.getInputValue()
if value == UNINITIALIZED_VALUE:
return None
return value
class MessageDialog(_AbstractSwingDialog):
def _init_dialog(self, message):
self._pane = JOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION)
class InputDialog(_AbstractSwingDialog):
def __init__(self, message, default):
self._default = default
_AbstractSwingDialog.__init__(self, message)
def _init_dialog(self, message):
self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
self._pane.setWantsInput(True)
self._pane.setInitialSelectionValue(self._default)
class SelectionDialog(_AbstractSwingDialog):
def __init__(self, message, options):
self._options = options
_AbstractSwingDialog.__init__(self, message)
def _init_dialog(self, message):
self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
self._pane.setWantsInput(True)
self._pane.setSelectionValues(self._options)
class PassFailDialog(_AbstractSwingDialog):
def _init_dialog(self, message):
self._buttons = ['PASS', 'FAIL']
self._pane = JOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION,
None, self._buttons, 'PASS')
def _get_value(self):
value = self._pane.getValue()
if value in self._buttons and self._buttons.index(value) == 0:
return True
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 telnetlib
import time
import re
import inspect
from robot.version import get_version
from robot import utils
class Telnet:
"""A test library providing communication over Telnet connections.
`Telnet` is Robot Framework's standard library that makes it
possible to connect to Telnet servers and execute commands on the
opened connections.
See `Open Connection` and `Switch Connection` for details on how
to handle multiple simultaneous connections. The responses are
expected to be ASCII encoded and all non-ASCII characters are
silently ignored.
"""
ROBOT_LIBRARY_SCOPE = 'TEST_SUITE'
ROBOT_LIBRARY_VERSION = get_version()
def __init__(self, timeout=3.0, newline='CRLF', prompt=None, prompt_is_regexp=False):
"""Telnet library can be imported with optional arguments.
Initialization parameters are used as default values when new
connections are opened with `Open Connection` keyword. They can also be
set after opening the connection using the `Set Timeout`, `Set Newline` and
`Set Prompt` keywords. See these keywords for more information.
Examples (use only one of these):
| *Setting* | *Value* | *Value* | *Value* | *Value* | *Value* | *Comment* |
| Library | Telnet | | | | | # default values |
| Library | Telnet | 0.5 | | | | # set only timeout |
| Library | Telnet | | LF | | | # set only newline |
| Library | Telnet | 2.0 | LF | | | # set timeout and newline |
| Library | Telnet | 2.0 | CRLF | $ | | # set also prompt |
| Library | Telnet | 2.0 | LF | ($|~) | True | # set prompt with simple regexp |
"""
self._timeout = timeout == '' and 3.0 or timeout
self._newline = newline == '' and 'CRLF' or newline
self._prompt = (prompt, prompt_is_regexp)
self._cache = utils.ConnectionCache()
self._conn = None
self._conn_kws = self._lib_kws = None
def get_keyword_names(self):
return self._get_library_keywords() + self._get_connection_keywords()
def _get_library_keywords(self):
if self._lib_kws is None:
self._lib_kws = [ name for name in dir(self)
if not name.startswith('_') and name != 'get_keyword_names'
and inspect.ismethod(getattr(self, name)) ]
return self._lib_kws
def _get_connection_keywords(self):
if self._conn_kws is None:
conn = self._get_connection()
excluded = [ name for name in dir(telnetlib.Telnet())
if name not in ['write', 'read', 'read_until'] ]
self._conn_kws = [ name for name in dir(conn)
if not name.startswith('_') and name not in excluded
and inspect.ismethod(getattr(conn, name)) ]
return self._conn_kws
def __getattr__(self, name):
if name not in self._get_connection_keywords():
raise AttributeError(name)
# If no connection is initialized, get attributes from a non-active
# connection. This makes it possible for Robot to create keyword
# handlers when it imports the library.
conn = self._conn is None and self._get_connection() or self._conn
return getattr(conn, name)
def open_connection(self, host, alias=None, port=23, timeout=None,
newline=None, prompt=None, prompt_is_regexp=False):
"""Opens a new Telnet connection to the given host and port.
Possible already opened connections are cached.
Returns the index of this connection, which can be used later
to switch back to the connection. The index starts from 1 and
is reset back to it when the `Close All Connections` keyword
is used.
The optional `alias` is a name for the connection, and it can
be used for switching between connections, similarly as the
index. See `Switch Connection` for more details about that.
The `timeout`, `newline`, `prompt` and `prompt_is_regexp` arguments get
default values when the library is taken into use, but setting them
here overrides those values for this connection. See `importing` for
more information.
"""
if timeout is None or timeout == '':
timeout = self._timeout
if newline is None:
newline = self._newline
if prompt is None:
prompt, prompt_is_regexp = self._prompt
print '*INFO* Opening connection to %s:%s with prompt: %s' \
% (host, port, self._prompt)
self._conn = self._get_connection(host, port, timeout, newline,
prompt, prompt_is_regexp)
return self._cache.register(self._conn, alias)
def _get_connection(self, *args):
"""Can be overridden to use a custom connection."""
return TelnetConnection(*args)
def switch_connection(self, index_or_alias):
"""Switches between active connections using an index or alias.
The index is got from `Open Connection` keyword, and an alias
can be given to it.
Returns the index of previously active connection.
Example:
| Open Connection | myhost.net | | |
| Login | john | secret | |
| Write | some command | | |
| Open Connection | yourhost.com | 2nd conn | |
| Login | root | password | |
| Write | another cmd | | |
| ${old index}= | Switch Connection | 1 | # index |
| Write | something | | |
| Switch Connection | 2nd conn | # alias | |
| Write | whatever | | |
| Switch Connection | ${old index} | # back to original again |
| [Teardown] | Close All Connections | |
The example above expects that there were no other open
connections when opening the first one, because it used index
'1' when switching to the connection later. If you are not
sure about that, you can store the index into a variable as
shown below.
| ${id} = | Open Connection | myhost.net |
| # Do something ... | | |
| Switch Connection | ${id} | |
"""
old_index = self._cache.current_index
self._conn = self._cache.switch(index_or_alias)
return old_index
def close_all_connections(self):
"""Closes all open connections and empties the connection cache.
After this keyword, new indexes got from the `Open Connection`
keyword are reset to 1.
This keyword should be used in a test or suite teardown to
make sure all connections are closed.
"""
self._conn = self._cache.close_all()
class TelnetConnection(telnetlib.Telnet):
def __init__(self, host=None, port=23, timeout=3.0, newline='CRLF',
prompt=None, prompt_is_regexp=False):
port = port == '' and 23 or int(port)
telnetlib.Telnet.__init__(self, host, port)
self.set_timeout(timeout)
self.set_newline(newline)
self.set_prompt(prompt, prompt_is_regexp)
self._default_log_level = 'INFO'
self.set_option_negotiation_callback(self._negotiate_echo_on)
def set_timeout(self, timeout):
"""Sets the timeout used in read operations to the given value.
`timeout` is given in Robot Framework's time format
(e.g. 1 minute 20 seconds) that is explained in the User Guide.
Read operations that expect some output to appear (`Read
Until`, `Read Until Regexp`, `Read Until Prompt`) use this
timeout and fail if the expected output has not appeared when
this timeout expires.
The old timeout is returned and can be used to restore it later.
Example:
| ${tout} = | Set Timeout | 2 minute 30 seconds |
| Do Something |
| Set Timeout | ${tout} |
"""
old = getattr(self, '_timeout', 3.0)
self._timeout = utils.timestr_to_secs(timeout)
return utils.secs_to_timestr(old)
def set_newline(self, newline):
"""Sets the newline used by the `Write` keyword.
Newline can be given either in escaped format using '\\n' and
'\\r', or with special 'LF' and 'CR' syntax.
Examples:
| Set Newline | \\n |
| Set Newline | CRLF |
Correct newline to use depends on the system and the default
value is 'CRLF'.
The old newline is returned and can be used to restore it later.
See `Set Prompt` or `Set Timeout` for an example.
"""
old = getattr(self, '_newline', 'CRLF')
self._newline = newline.upper().replace('LF','\n').replace('CR','\r')
return old
def close_connection(self, loglevel=None):
"""Closes the current Telnet connection and returns any remaining output.
See `Read` for more information on `loglevel`.
"""
telnetlib.Telnet.close(self)
ret = self.read_all().decode('ASCII', 'ignore')
self._log(ret, loglevel)
return ret
def login(self, username, password, login_prompt='login: ',
password_prompt='Password: '):
"""Logs in to the Telnet server with the given user information.
The login keyword reads from the connection until login_prompt
is encountered and then types the user name. Then it reads
until password_prompt is encountered and types the
password. The rest of the output (if any) is also read, and
all the text that has been read is returned as a single
string.
If a prompt has been set to this connection, either with `Open
Connection` or `Set Prompt`, this keyword reads the output
until the prompt is found. Otherwise, the keyword sleeps for a
second and reads everything that is available.
"""
ret = self.read_until(login_prompt, 'TRACE').decode('ASCII', 'ignore')
self.write_bare(username + self._newline)
ret += username + '\n'
ret += self.read_until(password_prompt, 'TRACE').decode('ASCII', 'ignore')
self.write_bare(password + self._newline)
ret += '*' * len(password) + '\n'
if self._prompt_is_set():
try:
ret += self.read_until_prompt('TRACE')
except AssertionError:
self._verify_login(ret)
raise
else:
ret += self._verify_login(ret)
self._log(ret)
return ret
def _verify_login(self, ret):
# It is necessary to wait for the 'login incorrect' message to appear.
time.sleep(1)
while True:
try:
ret += self.read_until('\n', 'TRACE').decode('ASCII', 'ignore')
except AssertionError:
return ret
else:
if 'Login incorrect' in ret:
self._log(ret)
raise AssertionError("Login incorrect")
def write(self, text, loglevel=None):
"""Writes the given text over the connection and appends a newline.
Consumes the written text (until the appended newline) from
the output and returns it. The given text must not contain
newlines.
Note: This keyword does not return the possible output of the
executed command. To get the output, one of the `Read XXX`
keywords must be used.
See `Read` for more information on `loglevel`.
"""
if self._newline in text:
raise RuntimeError("Write cannot be used with string containing "
"newlines. Use 'Write Bare' instead.")
text += self._newline
self.write_bare(text)
# Can't read until 'text' because long lines are cut strangely in the output
return self.read_until(self._newline, loglevel)
def write_bare(self, text):
"""Writes the given text over the connection without appending a newline.
Does not consume the written text.
"""
try:
text = str(text)
except UnicodeError:
raise ValueError('Only ASCII characters are allowed in Telnet. '
'Got: %s' % text)
telnetlib.Telnet.write(self, text)
def write_until_expected_output(self, text, expected, timeout,
retry_interval, loglevel=None):
"""Writes the given text repeatedly, until `expected` appears in the output.
`text` is written without appending a
newline. `retry_interval` defines the time waited before
writing `text` again. `text` is consumed from the output
before `expected` is tried to be read.
If `expected` does not appear in the output within `timeout`,
this keyword fails.
See `Read` for more information on `loglevel`.
Example:
| Write Until Expected Output | ps -ef| grep myprocess\\n | myprocess |
| ... | 5s | 0.5s |
This writes the 'ps -ef | grep myprocess\\n', until
'myprocess' appears on the output. The command is written
every 0.5 seconds and the keyword ,fails if 'myprocess' does
not appear in the output in 5 seconds.
"""
timeout = utils.timestr_to_secs(timeout)
retry_interval = utils.timestr_to_secs(retry_interval)
starttime = time.time()
while time.time() - starttime < timeout:
self.write_bare(text)
self.read_until(text, loglevel)
ret = telnetlib.Telnet.read_until(self, expected,
retry_interval).decode('ASCII', 'ignore')
self._log(ret, loglevel)
if ret.endswith(expected):
return ret
raise AssertionError("No match found for '%s' in %s"
% (expected, utils.secs_to_timestr(timeout)))
def read(self, loglevel=None):
"""Reads and returns/logs everything that is currently available in the output.
The read message is always returned and logged. The default
log level is either 'INFO', or the level set with `Set Default
Log Level`. `loglevel` can be used to override the default
log level, and the available levels are TRACE, DEBUG, INFO,
and WARN.
"""
ret = self.read_very_eager().decode('ASCII', 'ignore')
self._log(ret, loglevel)
return ret
def read_until(self, expected, loglevel=None):
"""Reads from the current output, until expected is encountered.
Text up to and including the match is returned. If no match is
found, the keyword fails.
See `Read` for more information on `loglevel`.
"""
ret = telnetlib.Telnet.read_until(self, expected,
self._timeout).decode('ASCII', 'ignore')
self._log(ret, loglevel)
if not ret.endswith(expected):
raise AssertionError("No match found for '%s' in %s"
% (expected, utils.secs_to_timestr(self._timeout)))
return ret
def read_until_regexp(self, *expected):
"""Reads from the current output, until a match to a regexp in expected.
Expected is a list of regular expression patterns as strings,
or compiled regular expressions. The keyword returns the text
up to and including the first match to any of the regular
expressions.
If the last argument in `*expected` is a valid log level, it
is used as `loglevel` in the keyword `Read`.
Examples:
| Read Until Regexp | (#|$) |
| Read Until Regexp | first_regexp | second_regexp |
| Read Until Regexp | some regexp | DEBUG |
"""
expected = list(expected)
if self._is_valid_log_level(expected[-1]):
loglevel = expected[-1]
expected = expected[:-1]
else:
loglevel = 'INFO'
try:
index, _, ret = self.expect(expected, self._timeout)
except TypeError:
index, ret = -1, ''
ret = ret.decode('ASCII', 'ignore')
self._log(ret, loglevel)
if index == -1:
expected = [ exp if isinstance(exp, basestring) else exp.pattern
for exp in expected ]
raise AssertionError("No match found for %s in %s"
% (utils.seq2str(expected, lastsep=' or '),
utils.secs_to_timestr(self._timeout)))
return ret
def read_until_prompt(self, loglevel=None):
"""Reads from the current output, until a prompt is found.
The prompt must have been set, either in the library import or
at login time, or by using the `Set Prompt` keyword.
See `Read` for more information on `loglevel`.
"""
if not self._prompt_is_set():
raise RuntimeError('Prompt is not set')
prompt, regexp = self._prompt
if regexp:
return self.read_until_regexp(prompt, loglevel)
return self.read_until(prompt, loglevel)
def execute_command(self, command, loglevel=None):
"""Executes given command and reads and returns everything until prompt.
This is a convenience keyword; following two are functionally
identical:
| ${out} = | Execute Command | Some command |
| Write | Some command |
| ${out} = | Read Until Prompt |
This keyword expects a prompt to be set, see `Read Until
Prompt` for details.
See `Read` for more information on `loglevel`.
"""
self.write(command, loglevel)
return self.read_until_prompt(loglevel)
def set_prompt(self, prompt, prompt_is_regexp=False):
"""Sets the prompt used in this connection to `prompt`.
If `prompt_is_regexp` is a non-empty string, the given prompt is
considered to be a regular expression.
The old prompt is returned and can be used to restore it later.
Example:
| ${prompt} | ${regexp} = | Set Prompt | $ |
| Do Something |
| Set Prompt | ${prompt} | ${regexp} |
"""
old = hasattr(self, '_prompt') and self._prompt or (None, False)
if prompt_is_regexp:
self._prompt = (re.compile(prompt), True)
else:
self._prompt = (prompt, False)
if old[1]:
return old[0].pattern, True
return old
def _prompt_is_set(self):
return self._prompt[0] is not None
def set_default_log_level(self, level):
"""Sets the default log level used by all read keywords.
The possible values are TRACE, DEBUG, INFO and WARN. The default is
INFO. The old value is returned and can be used to restore it later,
similarly as with `Set Timeout`.
"""
self._is_valid_log_level(level, raise_if_invalid=True)
old = self._default_log_level
self._default_log_level = level.upper()
return old
def _log(self, msg, level=None):
self._is_valid_log_level(level, raise_if_invalid=True)
msg = msg.strip()
if level is None:
level = self._default_log_level
if msg != '':
print '*%s* %s' % (level.upper(), msg)
def _is_valid_log_level(self, level, raise_if_invalid=False):
if level is None:
return True
if isinstance(level, basestring) and \
level.upper() in ['TRACE', 'DEBUG', 'INFO', 'WARN']:
return True
if not raise_if_invalid:
return False
raise AssertionError("Invalid log level '%s'" % level)
def _negotiate_echo_on(self, sock, cmd, opt):
# This is supposed to turn server side echoing on and turn other options off.
if opt == telnetlib.ECHO and cmd in (telnetlib.WILL, telnetlib.WONT):
self.sock.sendall(telnetlib.IAC + telnetlib.DO + opt)
elif opt != telnetlib.NOOPT:
if cmd in (telnetlib.DO, telnetlib.DONT):
self.sock.sendall(telnetlib.IAC + telnetlib.WONT + opt)
elif cmd in (telnetlib.WILL, telnetlib.WONT):
self.sock.sendall(telnetlib.IAC + telnetlib.DONT + opt)
| 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 OperatingSystem
OPSYS = OperatingSystem.OperatingSystem()
class DeprecatedOperatingSystem:
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
delete_environment_variable = OPSYS.remove_environment_variable
environment_variable_is_set = OPSYS.environment_variable_should_be_set
environment_variable_is_not_set = OPSYS.environment_variable_should_not_be_set
fail_unless_exists = OPSYS.should_exist
fail_if_exists = OPSYS.should_not_exist
fail_unless_file_exists = OPSYS.file_should_exist
fail_if_file_exists = OPSYS.file_should_not_exist
fail_unless_dir_exists = OPSYS.directory_should_exist
fail_if_dir_exists = OPSYS.directory_should_not_exist
fail_unless_dir_empty = OPSYS.directory_should_be_empty
fail_if_dir_empty = OPSYS.directory_should_not_be_empty
fail_unless_file_empty = OPSYS.file_should_be_empty
fail_if_file_empty = OPSYS.file_should_not_be_empty
empty_dir = OPSYS.empty_directory
remove_dir = OPSYS.remove_directory
copy_dir = OPSYS.copy_directory
move_dir = OPSYS.move_directory
create_dir = OPSYS.create_directory
list_dir = OPSYS.list_directory
list_files_in_dir = OPSYS.list_files_in_directory
list_dirs_in_dir = OPSYS.list_directories_in_directory
count_items_in_dir = OPSYS.count_items_in_directory
count_files_in_dir = OPSYS.count_files_in_directory
count_dirs_in_dir = OPSYS.count_directories_in_directory
| 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 sys
import time
import glob
import fnmatch
import shutil
try:
from robot.output import LOGGER
from robot.version import get_version
from robot.utils import (ConnectionCache, seq2str, timestr_to_secs,
secs_to_timestr, plural_or_not, get_time, abspath,
secs_to_timestamp, parse_time, unic, decode_output)
__version__ = get_version()
PROCESSES = ConnectionCache('No active processes')
except ImportError:
from os.path import abspath
__version__ = '<unknown>'
seq2str = lambda items: ', '.join("'%s'" % item for item in items)
timestr_to_secs = int
plural_or_not = lambda count: count != 1 and 's' or ''
secs_to_timestr = lambda secs: '%d second%s' % (secs, plural_or_not(secs))
unic = unicode
decode_output = lambda string: string
class _NotImplemented:
def __getattr__(self, name):
raise NotImplementedError('This usage requires Robot Framework '
'to be installed.')
LOGGER = get_time = secs_to_timestamp = parse_time = PROCESSES \
= _NotImplemented()
class OperatingSystem:
"""A test library providing keywords for OS related tasks.
`OperatingSystem` is Robot Framework's standard library that
enables various operating system related tasks to be performed in
the system where Robot Framework is running. It can, among other
things, execute commands (e.g. `Run`), create and remove files and
directories (e.g. `Create File`, `Remove Directory`), check
whether files or directories exists or contain something
(e.g. `File Should Exist`, `Directory Should Be Empty`) and
manipulate environment variables (e.g. `Set Environment Variable`).
*Pattern matching*
Some keywords allow their arguments to be specified as _glob patterns_
where:
| * | matches anything, even an empty string |
| ? | 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 |
Unless otherwise noted, matching is case-insensitive on
case-insensitive operating systems such as Windows. Pattern
matching is implemented using Python's `fnmatch` module:
http://docs.python.org/library/fnmatch.html
*Path separators*
All keywords expecting paths as arguments accept a forward slash
(`/`) as a path separator regardless the operating system. Notice
that this *does not work when the path is part of an argument*,
like it often is with `Run` and `Start Process` keywords. In such
cases the built-in variable `${/}` can be used to keep the test
data platform independent.
*Example*
| *Setting* | *Value* |
| Library | OperatingSystem |
| *Variable* | *Value* |
| ${PATH} | ${CURDIR}/example.txt |
| *Test Case* | *Action* | *Argument* | *Argument* |
| Example | Create File | ${PATH} | Some text |
| | File Should Exist | ${PATH} | |
| | Copy File | ${PATH} | ${TEMPDIR}/stuff |
| | ${output} = | Run | ${CURDIR}${/}script.py arg |
"""
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = __version__
def run(self, command):
"""Runs the given command in the system and returns the output.
The execution status of the command *is not checked* by this
keyword, and it must be done separately based on the returned
output. If the execution return code is needed, either `Run
And Return RC` or `Run And Return RC And Output` can be used.
The standard error stream is automatically redirected to the standard
output stream by adding `2>&1` after the executed command. This
automatic redirection is done only when the executed command does not
contain additional output redirections. You can thus freely forward
the standard error somewhere else, for example, like
`my_command 2>stderr.txt`.
The returned output contains everything written into the standard
output or error streams by the command (unless either of them
is redirected explicitly). Many commands add an extra newline
(`\\n`) after the output to make it easier to read in the
console. To ease processing the returned output, this possible
trailing newline is stripped by this keyword.
Examples:
| ${output} = | Run | ls -lhF /tmp |
| Log | ${output} |
| ${result} = | Run | ${CURDIR}${/}tester.py arg1 arg2 |
| Should Not Contain | ${result} | FAIL |
| ${stdout} = | Run | /opt/script.sh 2>/tmp/stderr.txt |
| Should Be Equal | ${stdout} | TEST PASSED |
| File Should Be Empty | /tmp/stderr.txt |
"""
return self._run(command)[1]
def run_and_return_rc(self, command):
"""Runs the given command in the system and returns the return code.
The return code (RC) is returned as a positive integer in
range from 0 to 255 as returned by the executed command. On
some operating systems (notable Windows) original return codes
can be something else, but this keyword always maps them to
the 0-255 range. Since the RC is an integer, it must be
checked e.g. with the keyword `Should Be Equal As Integers`
instead of `Should Be Equal` (both are built-in keywords).
Examples:
| ${rc} = | Run and Return RC | ${CURDIR}${/}script.py arg |
| Should Be Equal As Integers | ${rc} | 0 |
| ${rc} = | Run and Return RC | /path/to/example.rb arg1 arg2 |
| Should Be True | 0 < ${rc} < 42 |
See `Run` and `Run And Return RC And Output` if you need to get the
output of the executed command.
"""
return self._run(command)[0]
def run_and_return_rc_and_output(self, command):
"""Runs the given command in the system and returns the RC and output.
The return code (RC) is returned similarly as with `Run And Return RC`
and the output similarly as with `Run`.
Examples:
| ${rc} | ${output} = | Run and Return RC and Output | ${CURDIR}${/}mytool |
| Should Be Equal As Integers | ${rc} | 0 |
| Should Not Contain | ${output} | FAIL |
| ${rc} | ${stdout} = | Run and Return RC and Output | /opt/script.sh 2>/tmp/stderr.txt |
| Should Be True | ${rc} > 42 |
| Should Be Equal | ${stdout} | TEST PASSED |
| File Should Be Empty | /tmp/stderr.txt |
"""
return self._run(command)
def _run(self, command):
process = _Process(command)
self._info("Running command '%s'" % process)
stdout = process.read()
rc = process.close()
return rc, stdout
def start_process(self, command, stdin=None, alias=None):
"""Starts the given command as a background process.
Starts the process in the background and sets this process as
the current process. The following calls of the keywords `Read
Process Output` or `Stop Process` affect this process, unless
the keyword `Switch Process` is used.
If the command needs input through the standard input stream,
it can be defined with the `stdin` argument. It is not
possible to give input to the command later. Possible command
line arguments must be given as part of the command like
'/tmp/script.sh arg1 arg2'.
Returns the index of this process. The indexing starts from 1, and it
can be used to switch between the processes with the `Switch Process`
keyword. To end all processes and reset indexing, the
`Stop All Processes` keyword must be used.
The optional `alias` is a name for this process that may be used with
`Switch Process` instead of the returned index.
The standard error stream is redirected to the standard input
stream automatically by adding '2>&1' after the executed
command. This is done the same way, and for the same reasons,
as with `Run` keyword.
Example:
| Start Process | /path/longlasting.sh |
| Do Something | |
| ${output} = | Read Process Output |
| Should Contain | ${output} | Expected text |
| [Teardown] | Stop All Processes |
"""
process = _Process2(command, stdin)
self._info("Running command '%s'" % process)
return PROCESSES.register(process, alias)
def switch_process(self, index_or_alias):
"""Switches the active process to the specified process.
The index is the return value of the `Start Process` keyword and an
alias may have been defined to it.
Example:
| Start Process | /path/script.sh arg | | 1st process |
| ${2nd} = | Start Process | /path/script2.sh |
| Switch Process | 1st process |
| ${out1} = | Read Process Output |
| Switch Process | ${2nd} |
| ${out2} = | Read Process Output |
| Log Many | 1st process: ${out1} | 2nd process: ${out1} |
| [Teardown] | Stop All Processes |
"""
PROCESSES.switch(index_or_alias)
def read_process_output(self):
"""Waits for the process to finish and returns its output.
As mentioned in the documentation of `Start Process` keyword,
and documented thoroughly in `Run` keyword, the standard error
stream is automatically redirected to the standard
output. This keyword thus always returns all the output
procuded by the command.
Note that although the process is finished, it is not removed
from the process list. Trying to read from a stopped process
nevertheless fails. To reset the process list (and indexes and
aliases), `Stop All Processes` must be used.
See `Start Process` and `Switch Process` for more information
and examples about running processes.
"""
output = PROCESSES.current.read()
PROCESSES.current.close()
return output
def stop_process(self):
"""Stops the current process without reading from it.
Stopping a process does not remove it from the process list. To reset
the process list (and indexes and aliases), `Stop All Processes` must
be used. Stopping an already stopped process has no effect.
See `Start Process` and `Switch Process` for more information.
"""
PROCESSES.current.close()
def stop_all_processes(self):
"""Stops all the processes and removes them from the process list.
Resets the indexing that `Start Process` uses. All aliases are
also deleted. It does not matter have some of the processes
already been closed or not.
It is highly recommended to use this keyword in test or suite level
teardown to make sure all the started processes are closed.
"""
PROCESSES.close_all()
def get_file(self, path, encoding='UTF-8'):
"""Returns the contents of a specified file.
This keyword reads the specified file and returns the contents.
Line breaks in content are converted to platform independent form.
See also `Get Binary File`.
`encoding` defines the encoding of the file. By default the value is
'UTF-8', which means that UTF-8 and ASCII-encoded files are read
correctly.
"""
content = self.get_binary_file(path)
return unicode(content, encoding).replace('\r\n', '\n')
def get_binary_file(self, path):
"""Returns the contents of a specified file.
This keyword reads the specified file and returns the contents as is.
See also `Get File`.
New in Robot Framework 2.5.5.
"""
path = self._absnorm(path)
self._link("Getting file '%s'", path)
f = open(path, 'rb')
try:
return f.read()
finally:
f.close()
def grep_file(self, path, pattern, encoding='UTF-8'):
"""Returns the lines of the specified file that match the `pattern`.
This keyword reads a file from the file system using the defined
`path` and `encoding` similarly as `Get File`. A difference is
that only the lines that match the given `pattern` are returned.
Lines are returned as a single string catenated back together with
newlines and the number of matched lines is automatically logged.
Possible trailing newline is never returned.
A line matches if it contains the `pattern` anywhere in it and
it *does not need to match the pattern fully*. The pattern
matching syntax is explained in `introduction`, and in this
case matching is case-sensitive. Support for different pattern types
were removed in Robot Framework 2.5.
Examples:
| ${errors} = | Grep File | /var/log/myapp.log | ERROR |
| ${ret} = | Grep File | ${CURDIR}/file.txt | [Ww]ildc??d ex*ple |
If more complex pattern matching is needed, it is possible to use
`Get File` in combination with String library keywords like `Get
Lines Matching Regexp`.
"""
pattern = '*%s*' % pattern
orig = self.get_file(path, encoding).splitlines()
lines = [ line for line in orig if fnmatch.fnmatchcase(line, pattern) ]
self._info('%d out of %d lines matched' % (len(lines), len(orig)))
return '\n'.join(lines)
def log_file(self, path, encoding='UTF-8'):
"""Wrapper for `Get File` that also logs the returned file.
The file is logged with the INFO level. If you want something else,
just use `Get File` and the built-in keyword `Log` with the desired
level.
"""
content = self.get_file(path, encoding)
self._info(content)
return content
# File and directory existence
def should_exist(self, path, msg=None):
"""Fails unless the given path (file or directory) exists.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
if not glob.glob(path):
self._fail(msg, "Path '%s' does not match any file or directory" % path)
self._link("Path '%s' exists", path)
def should_not_exist(self, path, msg=None):
"""Fails if the given path (file or directory) exists.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
matches = glob.glob(path)
if not matches:
self._link("Path '%s' does not exist", path)
return
if not msg:
if self._is_pattern_path(path):
matches.sort()
msg = "Path '%s' matches %s" % (path, seq2str(matches))
else:
msg = "Path '%s' exists" % path
raise AssertionError(msg)
def file_should_exist(self, path, msg=None):
"""Fails unless the given `path` points to an existing file.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
matches = [ p for p in glob.glob(path) if os.path.isfile(p) ]
if not matches:
self._fail(msg, "Path '%s' does not match any file" % path)
self._link("File '%s' exists", path)
def file_should_not_exist(self, path, msg=None):
"""Fails if the given path points to an existing file.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
matches = [ p for p in glob.glob(path) if os.path.isfile(p) ]
if not matches:
self._link("File '%s' does not exist", path)
return
if not msg:
if self._is_pattern_path(path):
matches.sort()
name = len(matches) == 1 and 'file' or 'files'
msg = "Path '%s' matches %s %s" % (path, name, seq2str(matches))
else:
msg = "File '%s' exists" % path
raise AssertionError(msg)
def directory_should_exist(self, path, msg=None):
"""Fails unless the given path points to an existing directory.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
matches = [ p for p in glob.glob(path) if os.path.isdir(p) ]
if not matches:
self._fail(msg, "Path '%s' does not match any directory" % path)
self._link("Directory '%s' exists", path)
def directory_should_not_exist(self, path, msg=None):
"""Fails if the given path points to an existing file.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
matches = [ p for p in glob.glob(path) if os.path.isdir(p) ]
if not matches:
self._link("Directory '%s' does not exist", path)
return
if not msg:
if self._is_pattern_path(path):
matches.sort()
name = len(matches) == 1 and 'directory' or 'directories'
msg = "Path '%s' matches %s %s" % (path, name, seq2str(matches))
else:
msg = "Directory '%s' exists" % path
raise AssertionError(msg)
def _is_pattern_path(self, path):
return '*' in path or '?' in path or ('[' in path and ']' in path)
# Waiting file/dir to appear/disappear
def wait_until_removed(self, path, timeout='1 minute'):
"""Waits until the given file or directory is removed.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
If the path is a pattern, the keyword waits until all matching
items are removed.
The optional `timeout` can be used to control the maximum time of
waiting. The timeout is given as a timeout string, e.g. in a format
'15 seconds', '1min 10s' or just '10'. The time string format is
described in an appendix of Robot Framework User Guide.
If the timeout is negative, the keyword is never timed-out. The keyword
returns immediately, if the path does not exist in the first place.
"""
path = self._absnorm(path)
timeout = timestr_to_secs(timeout)
maxtime = time.time() + timeout
while glob.glob(path):
time.sleep(0.1)
if timeout >= 0 and time.time() > maxtime:
raise AssertionError("'%s' was not removed in %s"
% (path, secs_to_timestr(timeout)))
self._link("'%s' was removed", path)
def wait_until_created(self, path, timeout='1 minute'):
"""Waits until the given file or directory is created.
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
If the path is a pattern, the keyword returns when an item matching
it is created.
The optional `timeout` can be used to control the maximum time of
waiting. The timeout is given as a timeout string, e.g. in a format
'15 seconds', '1min 10s' or just '10'. The time string format is
described in an appendix of Robot Framework User Guide.
If the timeout is negative, the keyword is never timed-out. The keyword
returns immediately, if the path already exists.
"""
path = self._absnorm(path)
timeout = timestr_to_secs(timeout)
maxtime = time.time() + timeout
while not glob.glob(path):
time.sleep(0.1)
if timeout >= 0 and time.time() > maxtime:
raise AssertionError("'%s' was not created in %s"
% (path, secs_to_timestr(timeout)))
self._link("'%s' was created", path)
# Dir/file empty
def directory_should_be_empty(self, path, msg=None):
"""Fails unless the specified directory is empty.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
items = self._list_dir(path)
if items:
if not msg:
msg = "Directory '%s' is not empty. Contents: %s" \
% (path, seq2str(items, lastsep=', '))
raise AssertionError(msg)
self._link("Directory '%s' is empty.", path)
def directory_should_not_be_empty(self, path, msg=None):
"""Fails if the specified directory is empty.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
count = len(self._list_dir(path))
if count == 0:
self._fail(msg, "Directory '%s' is empty." % path)
plural = plural_or_not(count)
self._link("Directory '%%s' contains %d item%s." % (count, plural),
path)
def file_should_be_empty(self, path, msg=None):
"""Fails unless the specified file is empty.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
if not os.path.isfile(path):
raise AssertionError("File '%s' does not exist" % path)
size = os.stat(path).st_size
if size > 0:
self._fail(msg, "File '%s' is not empty. Size: %d bytes" % (path, size))
self._link("File '%s' is empty", path)
def file_should_not_be_empty(self, path, msg=None):
"""Fails if the specified directory is empty.
The default error message can be overridden with the `msg` argument.
"""
path = self._absnorm(path)
if not os.path.isfile(path):
raise AssertionError("File '%s' does not exist" % path)
size = os.stat(path).st_size
if size == 0:
self._fail(msg, "File '%s' is empty." % path)
self._link("File '%%s' contains %d bytes" % size, path)
# Creating and removing files and directory
def create_file(self, path, content='', encoding='UTF-8'):
"""Creates a file with the given content and encoding.
If the directory where to create file does not exist it, and possible
intermediate missing directories, are created.
Use `Append To File` if you want to append to an existing file,
and use `File Should Not Exist` if you want to avoid overwriting
existing files.
"""
path = self._write_to_file(path, content, encoding, 'w')
self._link("Created file '%s'", path)
def append_to_file(self, path, content, encoding='UTF-8'):
"""Appends the given contend to the specified file.
If the file does not exists, this keyword works exactly the same
way as `Create File With Encoding`.
"""
path = self._write_to_file(path, content, encoding, 'a')
self._link("Appended to file '%s'", path)
def _write_to_file(self, path, content, encoding, mode):
path = self._absnorm(path)
parent = os.path.dirname(path)
if not os.path.exists(parent):
os.makedirs(parent)
f = open(path, mode+'b')
try:
f.write(content.encode(encoding))
finally:
f.close()
return path
def remove_file(self, path):
"""Removes a file with the given path.
Passes if the file does not exist, but fails if the path does
not point to a regular file (e.g. it points to a directory).
The path can be given as an exact path or as a glob pattern.
The pattern matching syntax is explained in `introduction`.
If the path is a pattern, all files matching it are removed.
"""
path = self._absnorm(path)
matches = glob.glob(path)
if not matches:
self._link("File '%s' does not exist", path)
for match in matches:
if not os.path.isfile(match):
raise RuntimeError("Path '%s' is not a file" % match)
os.remove(match)
self._link("Removed file '%s'", match)
def remove_files(self, *paths):
"""Uses `Remove File` to remove multiple files one-by-one.
Example:
| Remove Files | ${TEMPDIR}${/}foo.txt | ${TEMPDIR}${/}bar.txt | ${TEMPDIR}${/}zap.txt |
"""
for path in paths:
self.remove_file(path)
def empty_directory(self, path):
"""Deletes all the content (incl. subdirectories) from the given directory."""
path = self._absnorm(path)
items = [ os.path.join(path, item) for item in self._list_dir(path) ]
for item in items:
if os.path.isdir(item):
shutil.rmtree(item)
else:
os.remove(item)
self._link("Emptied directory '%s'", path)
def create_directory(self, path):
"""Creates the specified directory.
Also possible intermediate directories are created. Passes if the
directory already exists, and fails if the path points to a regular
file.
"""
path = self._absnorm(path)
if os.path.isdir(path):
self._link("Directory '%s' already exists", path )
return
if os.path.exists(path):
raise RuntimeError("Path '%s' already exists but is not a directory" % path)
os.makedirs(path)
self._link("Created directory '%s'", path)
def remove_directory(self, path, recursive=False):
"""Removes the directory pointed to by the given `path`.
If the second argument `recursive` is set to any non-empty string,
the directory is removed recursively. Otherwise removing fails if
the directory is not empty.
If the directory pointed to by the `path` does not exist, the keyword
passes, but it fails, if the `path` points to a file.
"""
path = self._absnorm(path)
if not os.path.exists(path):
self._link("Directory '%s' does not exist", path)
return
if os.path.isfile(path):
raise RuntimeError("Path '%s' is not a directory" % path)
if recursive:
shutil.rmtree(path)
else:
msg = "Directory '%s' is not empty." % path
self.directory_should_be_empty(path, msg)
os.rmdir(path)
self._link("Removed directory '%s'", path)
# Moving and copying files and directories
def copy_file(self, source, destination):
"""Copies the source file into a new destination.
1) If the destination is an existing file, the source file is copied
over it.
2) If the destination is an existing directory, the source file is
copied into it. A possible file with the same name is overwritten.
3) If the destination does not exist and it ends with a path
separator ('/' or '\\'), it is considered a directory. That
directory is created and a source file copied into it.
Possible missing intermediate directories are also created.
4) If the destination does not exist and it does not end with a path
separator, it is considered a file. If the path to the file does not
exist, it is created.
"""
source, destination = self._copy_file(source, destination)
self._link("Copied file from '%s' to '%s'", source, destination)
def move_file(self, source, destination):
"""Moves the source file into a new destination.
Uses `Copy File` keyword internally, and `source` and `destination`
arguments have exactly same semantics as with that keyword.
"""
source, destination = self._copy_file(source, destination)
os.remove(source)
self._link("Moved file from '%s' to '%s'", source, destination)
def _copy_file(self, source, dest):
source = self._absnorm(source)
dest = dest.replace('/', os.sep)
dest_is_dir = dest.endswith(os.sep)
dest = self._absnorm(dest)
if not os.path.exists(source):
raise RuntimeError("Source file '%s' does not exist" % source)
if not os.path.isfile(source):
raise RuntimeError("Source file '%s' is not a regular file" % source)
if not os.path.exists(dest):
if dest_is_dir:
parent = dest
else:
parent = os.path.dirname(dest)
if not os.path.exists(parent):
os.makedirs(parent)
shutil.copy(source, dest)
return source, dest
def copy_directory(self, source, destination):
"""Copies the source directory into the destination.
If the destination exists, the source is copied under it. Otherwise
the destination directory and the possible missing intermediate
directories are created.
"""
source, destination = self._copy_dir(source, destination)
self._link("Copied directory from '%s' to '%s'", source, destination)
def move_directory(self, source, destination):
"""Moves the source directory into a destination.
Uses `Copy Directory` keyword internally, and `source` and
`destination` arguments have exactly same semantics as with
that keyword.
"""
source, destination = self._copy_dir(source, destination)
shutil.rmtree(source)
self._link("Moved directory from '%s' to '%s'", source, destination)
def _copy_dir(self, source, dest):
source = self._absnorm(source)
dest = self._absnorm(dest)
if not os.path.exists(source):
raise RuntimeError("Source directory '%s' does not exist" % source)
if not os.path.isdir(source):
raise RuntimeError("Source directory '%s' is not a directory" % source)
if os.path.exists(dest) and not os.path.isdir(dest):
raise RuntimeError("Destination '%s' exists but is not a directory" % dest)
if os.path.exists(dest):
base = os.path.basename(source)
dest = os.path.join(dest, base)
else:
parent = os.path.dirname(dest)
if not os.path.exists(parent):
os.makedirs(parent)
shutil.copytree(source, dest)
return source, dest
# Environment Variables
def get_environment_variable(self, name, default=None):
"""Returns the value of an environment variable with the given name.
If no such environment variable is set, returns the default value, if
given. Otherwise fails the test case.
Note that you can also access environment variables directly using
the variable syntax `%{ENV_VAR_NAME}`.
"""
ret = os.environ.get(name, default)
if ret is None:
raise RuntimeError("Environment variable '%s' does not exist" % name)
return ret
def set_environment_variable(self, name, value):
"""Sets an environment variable to a specified value.
Starting from Robot Framework 2.1.1, values are converted to strings
automatically.
"""
# Cannot convert to Unicode because they aren't generally supported in
# environment variables, but don't want to change deliberately given
# Unicode strings either.
if not isinstance(value, basestring):
value = str(value)
os.environ[name] = value
self._info("Environment variable '%s' set to value '%s'" % (name, value))
def remove_environment_variable(self, name):
"""Deletes the specified environment variable.
Does nothing if the environment variable is not set.
"""
if os.environ.has_key(name):
del os.environ[name]
self._info("Environment variable '%s' deleted" % name)
else:
self._info("Environment variable '%s' does not exist" % name)
def environment_variable_should_be_set(self, name, msg=None):
"""Fails if the specified environment variable is not set.
The default error message can be overridden with the `msg` argument.
"""
try:
value = os.environ[name]
except KeyError:
self._fail(msg, "Environment variable '%s' is not set" % name)
else:
self._info("Environment variable '%s' is set to '%s'" % (name, value))
def environment_variable_should_not_be_set(self, name, msg=None):
"""Fails if the specified environment variable is set.
The default error message can be overridden with the `msg` argument.
"""
try:
value = os.environ[name]
except KeyError:
self._info("Environment variable '%s' is not set" % name)
else:
self._fail(msg, "Environment variable '%s' is set to '%s'" % (name, value))
# Path
def join_path(self, base, *parts):
"""Joins the given path part(s) to the given base path.
The path separator ('/' or '\\') is inserted when needed and
the possible absolute paths handled as expected. The resulted
path is also normalized.
Examples:
| ${path} = | Join Path | my | path |
| ${p2} = | Join Path | my/ | path/ |
| ${p3} = | Join Path | my | path | my | file.txt |
| ${p4} = | Join Path | my | /path |
| ${p5} = | Join Path | /my/path/ | .. | path2 |
=>
- ${path} = 'my/path'
- ${p2} = 'my/path'
- ${p3} = 'my/path/my/file.txt'
- ${p4} = '/path'
- ${p5} = '/my/path2'
"""
base = base.replace('/', os.sep)
parts = [ p.replace('/', os.sep) for p in parts ]
return self.normalize_path(os.path.join(base, *parts))
def join_paths(self, base, *paths):
"""Joins given paths with base and returns resulted paths.
See `Join Path` for more information.
Examples:
| @{p1} = | Join Path | base | example | other | |
| @{p2} = | Join Path | /my/base | /example | other | |
| @{p3} = | Join Path | my/base | example/path/ | other | one/more |
=>
- @{p1} = ['base/example', 'base/other']
- @{p2} = ['/example', '/my/base/other']
- @{p3} = ['my/base/example/path', 'my/base/other', 'my/base/one/more']
"""
return [ self.join_path(base, path) for path in paths ]
def normalize_path(self, path):
"""Normalizes the given path.
Examples:
| ${path} = | Normalize Path | abc |
| ${p2} = | Normalize Path | abc/ |
| ${p3} = | Normalize Path | abc/../def |
| ${p4} = | Normalize Path | abc/./def |
| ${p5} = | Normalize Path | abc//def |
=>
- ${path} = 'abc'
- ${p2} = 'abc'
- ${p3} = 'def'
- ${p4} = 'abc/def'
- ${p5} = 'abc/def'
"""
ret = os.path.normpath(path.replace('/', os.sep))
if ret == '': return '.'
return ret
def split_path(self, path):
"""Splits the given path from the last path separator ('/' or '\\').
The given path is first normalized (e.g. a possible trailing
path separator is removed, special directories '..' and '.'
removed). The parts that are split are returned as separate
components.
Examples:
| ${path1} | ${dir} = | Split Path | abc/def |
| ${path2} | ${file} = | Split Path | abc/def/ghi.txt |
| ${path3} | ${d2} = | Split Path | abc/../def/ghi/ |
=>
- ${path1} = 'abc' & ${dir} = 'def'
- ${path2} = 'abc/def' & ${file} = 'ghi.txt'
- ${path3} = 'def' & ${d2} = 'ghi'
"""
return os.path.split(self.normalize_path(path))
def split_extension(self, path):
"""Splits the extension from the given path.
The given path is first normalized (e.g. possible trailing
path separators removed, special directories '..' and '.'
removed). The base path and extension are returned as separate
components so that the dot used as an extension separator is
removed. If the path contains no extension, an empty string is
returned for it. Possible leading and trailing dots in the file
name are never considered to be extension separators.
Examples:
| ${path} | ${ext} = | Split Extension | file.extension |
| ${p2} | ${e2} = | Split Extension | path/file.ext |
| ${p3} | ${e3} = | Split Extension | path/file |
| ${p4} | ${e4} = | Split Extension | p1/../p2/file.ext |
| ${p5} | ${e5} = | Split Extension | path/.file.ext |
| ${p6} | ${e6} = | Split Extension | path/.file |
=>
- ${path} = 'file' & ${ext} = 'extension'
- ${p2} = 'path/file' & ${e2} = 'ext'
- ${p3} = 'path/file' & ${e3} = ''
- ${p4} = 'p2/file' & ${e4} = 'ext'
- ${p5} = 'path/.file' & ${e5} = 'ext'
- ${p6} = 'path/.file' & ${e6} = ''
"""
path = self.normalize_path(path)
basename = os.path.basename(path)
if basename.startswith('.' * basename.count('.')):
return path, ''
if path.endswith('.'):
path2 = path.rstrip('.')
trailing_dots = '.' * (len(path) - len(path2))
path = path2
else:
trailing_dots = ''
basepath, ext = os.path.splitext(path)
if ext.startswith('.'):
ext = ext[1:]
if ext:
ext += trailing_dots
else:
basepath += trailing_dots
return basepath, ext
# Misc
def get_modified_time(self, path, format='timestamp'):
"""Returns the last modification time of a file or directory.
How time is returned is determined based on the given `format`
string as follows. Note that all checks are case-insensitive.
Returned time is also automatically logged.
1) If `format` contains the word 'epoch', the time is returned
in seconds after the UNIX epoch. The return value is always
an integer.
2) If `format` contains any of the words 'year', 'month',
'day', 'hour', 'min' or 'sec', only the selected parts are
returned. The order of the returned parts is always the one
in the previous sentence and the order of the words in
`format` is not significant. The parts are returned as
zero-padded strings (e.g. May -> '05').
3) Otherwise, and by default, the time is returned as a
timestamp string in the format '2006-02-24 15:08:31'.
Examples (when the modified time of the ${CURDIR} is
2006-03-29 15:06:21):
| ${time} = | Get Modified Time | ${CURDIR} |
| ${secs} = | Get Modified Time | ${CURDIR} | epoch |
| ${year} = | Get Modified Time | ${CURDIR} | return year |
| ${y} | ${d} = | Get Modified Time | ${CURDIR} | year,day |
| @{time} = | Get Modified Time | ${CURDIR} | year,month,day,hour,min,sec |
=>
- ${time} = '2006-03-29 15:06:21'
- ${secs} = 1143637581
- ${year} = '2006'
- ${y} = '2006' & ${d} = '29'
- @{time} = ['2006', '03', '29', '15', '06', '21']
"""
path = self._absnorm(path)
if not os.path.exists(path):
raise RuntimeError("Getting modified time of '%s' failed: "
"Path does not exist" % path)
mtime = get_time(format, os.stat(path).st_mtime)
self._link("Last modified time of '%%s' is %s" % mtime, path)
return mtime
def set_modified_time(self, path, mtime):
"""Sets the file modification time.
Changes the modification and access times of the given file to the
value determined by `mtime`, which can be given in four different ways.
1) If `mtime` is a floating point number, it is interpreted as
seconds since epoch (Jan 1, 1970 0:00:00). This
documentation is written about 1177654467 seconds since
epoch.
2) If `mtime` is a valid timestamp, that time will be used. Valid
timestamp formats are 'YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss'.
3) If `mtime` is equal to 'NOW' (case-insensitive), the
current time is used.
4) If `mtime` 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:
| Set Modified Time | /path/file | 1177654467 | #(2007-04-27 9:14:27) |
| Set Modified Time | /path/file | 2007-04-27 9:14:27 |
| Set Modified Time | /path/file | NOW | # The time of execution |
| Set Modified Time | /path/file | NOW - 1d | # 1 day subtracted from NOW |
| Set Modified Time | /path/file | NOW + 1h 2min 3s | # 1h 2min 3s added to NOW |
"""
path = self._absnorm(path)
try:
if not os.path.exists(path):
raise ValueError('File does not exist')
if not os.path.isfile(path):
raise ValueError('Modified time can only be set to regular files')
mtime = parse_time(mtime)
except ValueError, err:
raise RuntimeError("Setting modified time of '%s' failed: %s"
% (path, unicode(err)))
os.utime(path, (mtime, mtime))
time.sleep(0.1) # Give os some time to really set these times
tstamp = secs_to_timestamp(mtime, ('-',' ',':'))
self._link("Set modified time of '%%s' to %s" % tstamp, path)
def get_file_size(self, path):
"""Returns and logs file size as an integer in bytes"""
path = self._absnorm(path)
if not os.path.isfile(path):
raise RuntimeError("File '%s' does not exist." % path)
size = os.stat(path).st_size
plural = plural_or_not(size)
self._link("Size of file '%%s' is %d byte%s" % (size, plural), path)
return size
def list_directory(self, path, pattern=None, absolute=False):
"""Returns and logs items in a directory, optionally filtered with `pattern`.
File and directory names are returned in case-sensitive alphabetical
order, e.g. ['A Name', 'Second', 'a lower case name', 'one more'].
Implicit directories '.' and '..' are not returned. The returned items
are automatically logged.
By default, the file and directory names are returned relative to the
given path (e.g. 'file.txt'). If you want them be returned in the
absolute format (e.g. '/home/robot/file.txt'), set the `absolute`
argument to any non-empty string.
If `pattern` is given, only items matching it are returned. The pattern
matching syntax is explained in `introduction`, and in this case
matching is case-sensitive.
Examples (using also other `List Directory` variants):
| @{items} = | List Directory | ${TEMPDIR} |
| @{files} = | List Files In Directory | /tmp | *.txt | absolute |
| ${count} = | Count Files In Directory | ${CURDIR} | ??? |
"""
items = self._list_dir(path, pattern, absolute)
self._info('%d item%s:\n%s' % (len(items), plural_or_not(items), '\n'.join(items)))
return items
def list_files_in_directory(self, path, pattern=None, absolute=False):
"""A wrapper for `List Directory` that returns only files."""
files = self._list_files_in_dir(path, pattern, absolute)
self._info('%d file%s:\n%s' % (len(files), plural_or_not(files), '\n'.join(files)))
return files
def list_directories_in_directory(self, path, pattern=None, absolute=False):
"""A wrapper for `List Directory` that returns only directories."""
dirs = self._list_dirs_in_dir(path, pattern, absolute)
self._info('%d director%s:\n%s' % (len(dirs), 'y' if len(dirs) == 1 else 'ies', '\n'.join(dirs)))
return dirs
def count_items_in_directory(self, path, pattern=None):
"""Returns and logs the number of all items in the given directory.
The argument `pattern` has the same semantics as in the `List Directory`
keyword. The count is returned as an integer, so it must be checked e.g.
with the built-in keyword `Should Be Equal As Integers`.
"""
count = len(self._list_dir(path, pattern))
self._info("%s item%s." % (count, plural_or_not(count)))
return count
def count_files_in_directory(self, path, pattern=None):
"""A wrapper for `Count Items In Directory` returning onlyt directory count."""
count = len(self._list_files_in_dir(path, pattern))
self._info("%s file%s." % (count, plural_or_not(count)))
return count
def count_directories_in_directory(self, path, pattern=None):
"""A wrapper for `Count Items In Directory` returning only file count."""
count = len(self._list_dirs_in_dir(path, pattern))
self._info("%s director%s." % (count, 'y' if count == 1 else 'ies'))
return count
def _list_dir(self, path, pattern=None, absolute=False):
path = self._absnorm(path)
self._link("Listing contents of directory '%s'.", path)
if not os.path.isdir(path):
raise RuntimeError("Directory '%s' does not exist" % path)
# result is already unicode but unic also handles NFC normalization
items = sorted(unic(item) for item in os.listdir(path))
if pattern:
items = [i for i in items if fnmatch.fnmatchcase(i, pattern)]
if absolute:
path = os.path.normpath(path)
items = [os.path.join(path,item) for item in items]
return items
def _list_files_in_dir(self, path, pattern=None, absolute=False):
return [item for item in self._list_dir(path, pattern, absolute)
if os.path.isfile(os.path.join(path, item))]
def _list_dirs_in_dir(self, path, pattern=None, absolute=False):
return [item for item in self._list_dir(path, pattern, absolute)
if os.path.isdir(os.path.join(path, item))]
def touch(self, path):
"""Emulates the UNIX touch command.
Creates a file, if it does not exist. Otherwise changes its access and
modification times to the current time.
Fails if used with the directories or the parent directory of the given
file does not exist.
"""
path = self._absnorm(path)
if os.path.isdir(path):
raise RuntimeError("Cannot touch '%s' because it is a directory" % path)
if not os.path.exists(os.path.dirname(path)):
raise RuntimeError("Cannot touch '%s' because its parent directory "
"does not exist" % path)
if os.path.exists(path):
mtime = round(time.time())
os.utime(path, (mtime, mtime))
self._link("Touched existing file '%s'", path)
else:
open(path, 'w').close()
self._link("Touched new file '%s'", path)
def _absnorm(self, path):
try:
return abspath(path.replace('/', os.sep))
except ValueError: # http://ironpython.codeplex.com/workitem/29489
return os.path.normpath(path.replace('/', os.sep))
def _fail(self, error, default):
raise AssertionError(error or default)
def _info(self, msg):
self._log(msg, 'INFO')
def _link(self, msg, *paths):
paths = tuple('<a href="file://%s">%s</a>' % (p, p) for p in paths)
self._log(msg % paths, 'HTML')
def _warn(self, msg):
self._log(msg, 'WARN')
def _log(self, msg, level):
print '*%s* %s' % (level, msg)
class _Process:
def __init__(self, command):
self._command = self._process_command(command)
self._process = os.popen(self._command)
def __str__(self):
return self._command
def read(self):
return self._process_output(self._process.read())
def close(self):
try:
rc = self._process.close()
except IOError: # Has occurred sometimes in Windows
return 255
if rc is None:
return 0
# In Windows (Python and Jython) return code is value returned by
# command (can be almost anything)
# In other OS:
# In Jython return code can be between '-255' - '255'
# In Python return code must be converted with 'rc >> 8' and it is
# between 0-255 after conversion
if os.sep == '\\' or sys.platform.startswith('java'):
return rc % 256
return rc >> 8
def _process_command(self, command):
if self._is_jython(2, 2):
# os.popen doesn't handle Unicode in Jython 2.2 as explained in
# http://jython.org/bugs/1735774.
command = str(command)
if '>' not in command:
if command.endswith('&'):
command = command[:-1] + ' 2>&1 &'
else:
command += ' 2>&1'
return self._encode_to_file_system(command)
def _encode_to_file_system(self, string):
enc = sys.getfilesystemencoding()
return string.encode(enc) if enc else string
def _process_output(self, stdout):
stdout = stdout.replace('\r\n', '\n') # http://bugs.jython.org/issue1566
if stdout.endswith('\n'):
stdout = stdout[:-1]
if self._is_jython(2, 2):
return stdout
return decode_output(stdout)
def _is_jython(self, *version):
return sys.platform.startswith('java') and sys.version_info[:2] == version
class _Process2(_Process):
def __init__(self, command, input_):
self._command = self._process_command(command)
stdin, self.stdout = os.popen2(self._command)
if input_:
stdin.write(input_)
stdin.close()
self.closed = False
def read(self):
if self.closed:
raise RuntimeError('Cannot read from a closed process')
return self._process_output(self.stdout.read())
def close(self):
if not self.closed:
self.stdout.close()
self.closed = True
| 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 xmlrpclib
import socket
import time
import sys
try:
from xml.parsers.expat import ExpatError
except ImportError:
ExpatError = None # Support for Jython 2.2(.x)
from robot import utils
from robot.errors import RemoteError
class Remote:
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, uri='http://localhost:8270'):
if '://' not in uri:
uri = 'http://' + uri
self._client = XmlRpcRemoteClient(uri)
def get_keyword_names(self, attempts=5):
for i in range(attempts):
try:
return self._client.get_keyword_names()
except TypeError, err:
time.sleep(1)
raise RuntimeError('Connecting remote server failed: %s' % err)
def get_keyword_arguments(self, name):
try:
return self._client.get_keyword_arguments(name)
except TypeError:
return ['*args']
def get_keyword_documentation(self, name):
try:
return self._client.get_keyword_documentation(name)
except TypeError:
return ''
def run_keyword(self, name, args):
args = [ self._handle_argument(arg) for arg in args ]
result = RemoteResult(self._client.run_keyword(name, args))
sys.stdout.write(result.output)
if result.status != 'PASS':
raise RemoteError(result.error, result.traceback)
return result.return_
def _handle_argument(self, arg):
if isinstance(arg, (basestring, int, long, float)):
return arg
if isinstance(arg, (tuple, list)):
return [ self._handle_argument(item) for item in arg ]
if isinstance(arg, dict):
return dict([ (self._str(key), self._handle_argument(value))
for key, value in arg.items() ])
return self._str(arg)
def _str(self, item):
if item is None:
return ''
return utils.unic(item)
class RemoteResult:
def __init__(self, result):
try:
self.status = result['status']
self.output = result.get('output', '')
self.return_ = result.get('return', '')
self.error = result.get('error', '')
self.traceback = result.get('traceback', '')
except (KeyError, AttributeError):
raise RuntimeError('Invalid remote result dictionary: %s' % result)
class XmlRpcRemoteClient:
def __init__(self, uri):
self._server = xmlrpclib.ServerProxy(uri, encoding='UTF-8')
def get_keyword_names(self):
try:
return self._server.get_keyword_names()
except socket.error, (errno, err):
raise TypeError(err)
except xmlrpclib.Error, err:
raise TypeError(err)
def get_keyword_arguments(self, name):
try:
return self._server.get_keyword_arguments(name)
except xmlrpclib.Error:
raise TypeError
def get_keyword_documentation(self, name):
try:
return self._server.get_keyword_documentation(name)
except xmlrpclib.Error:
raise TypeError
def run_keyword(self, name, args):
try:
return self._server.run_keyword(name, args)
except xmlrpclib.Error, err:
raise RuntimeError(err.faultString)
except socket.error, (errno, err):
raise RuntimeError('Connection to remote server broken: %s' % err)
except ExpatError, err:
raise RuntimeError('Processing XML-RPC return value failed. '
'Most often this happens when the return value '
'contains characters that are not valid in XML. '
'Original error was: ExpatError: %s' % err)
| 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.