code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
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 |
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 |
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 |
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 |
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 |
class PythonVarArgsConstructor:
def __init__(self, mandatory, *varargs):
self.mandatory = mandatory
self.varargs = varargs
def get_args(self):
return self.mandatory, ' '.join(self.varargs)
| 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 ZipLib:
def kw_from_zip(self, arg):
print '*INFO*', arg
return arg * 2
| 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 |
__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 |
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 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 _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 |
class SameNamesAsInBuiltIn:
def noop(self):
"""Using this keyword without libname causes an error""" | 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 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 |
class LibClass1:
def verify_libclass1(self):
return 'LibClass 1 works'
class LibClass2:
def verify_libclass2(self):
return 'LibClass 2 works also'
| 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 |
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 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 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 |
import os
import tempfile
import time
class ListenAll:
ROBOT_LISTENER_API_VERSION = '2'
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, attrs):
metastr = ' '.join(['%s: %s' % (k, v) for k, v
in attrs['metadata'].items()])
self.outfile.write("SUITE START: %s '%s' [%s]\n"
% (name, attrs['doc'], metastr))
def start_test(self, name, attrs):
tags = [ str(tag) for tag in attrs['tags'] ]
self.outfile.write("TEST START: %s '%s' %s\n" % (name, attrs['doc'], tags))
def start_keyword(self, name, attrs):
args = [ str(arg) for arg in attrs['args'] ]
self.outfile.write("KW START: %s %s\n" % (name, args))
def log_message(self, message):
msg, level = self._check_message_validity(message)
if level != 'TRACE' and 'Traceback' not in msg:
self.outfile.write('LOG MESSAGE: [%s] %s\n' % (level, msg))
def message(self, message):
msg, level = self._check_message_validity(message)
if 'Settings' in msg:
self.outfile.write('Got settings on level: %s\n' % level)
def _check_message_validity(self, message):
if message['html'] not in ['yes', 'no']:
self.outfile.write('Log message has invalid `html` attribute %s' %
message['html'])
if not message['timestamp'].startswith(str(time.localtime()[0])):
self.outfile.write('Log message has invalid timestamp %s' %
message['timestamp'])
return message['message'], message['level']
def end_keyword(self, name, attrs):
self.outfile.write("KW END: %s\n" % (attrs['status']))
def end_test(self, name, attrs):
if attrs['status'] == 'PASS':
self.outfile.write('TEST END: PASS\n')
else:
self.outfile.write("TEST END: %s %s\n"
% (attrs['status'], attrs['message']))
def end_suite(self, name, attrs):
self.outfile.write('SUITE END: %s %s\n'
% (attrs['status'], attrs['statistics']))
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')
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
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
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
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 |
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 subprocess
import os
import signal
import ctypes
import time
class ProcessManager(object):
def __init__(self):
self._process = None
self._stdout = ''
self._stderr = ''
def start_process(self, *args):
args = args[0].split() + list(args[1:])
self._process = subprocess.Popen(args, stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
self._stdout = ''
self._stderr = ''
def send_terminate(self, signal_name):
if os.name != 'nt':
os.kill(self._process.pid, getattr(signal, signal_name))
else:
self._set_handler_to_ignore_one_sigint()
ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, 0)
def _set_handler_to_ignore_one_sigint(self):
orig_handler = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, lambda signum, frame:
signal.signal(signal.SIGINT, orig_handler))
def get_stdout(self):
self.wait_until_finished()
return self._stdout
def get_stderr(self):
self.wait_until_finished()
return self._stderr
def log_stdout_and_stderr(self):
print "stdout: ", self._process.stdout.read()
print "stderr: ", self._process.stderr.read()
def wait_until_finished(self):
if self._process.returncode is None:
self._stdout, self._stderr = self._process.communicate()
def busy_sleep(self, seconds):
max_time = time.time() + int(seconds)
while time.time() < max_time:
pass
def get_jython_path(self):
jython_home = os.getenv('JYTHON_HOME')
if not jython_home:
raise RuntimeError('This test requires JYTHON_HOME environment variable to be set.')
return '%s -Dpython.home=%s -classpath %s org.python.util.jython' \
% (self._get_java(), jython_home, self._get_classpath(jython_home))
def _get_java(self):
java_home = os.getenv('JAVA_HOME')
if not java_home:
return 'java'
if java_home.startswith('"') and java_home.endswith('"'):
java_home = java_home[1:-1]
return os.path.join(java_home, 'bin', 'java')
def _get_classpath(self, jython_home):
jython_jar = os.path.join(jython_home, 'jython.jar')
return jython_jar + os.pathsep + os.getenv('CLASSPATH','')
| Python |
from robot.libraries.BuiltIn import BuiltIn
BIN = BuiltIn()
def start_keyword(*args):
if BIN.get_variables()['${TESTNAME}'] == 'Listener Using BuiltIn':
BIN.set_test_variable('${SET BY LISTENER}', 'quux')
| 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.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 |
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 |
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 |
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 |
u"""Module test library.
With some non-ascii stuff:
Hyv\u00E4\u00E4 y\u00F6t\u00E4.
\u0421\u043F\u0430\u0441\u0438\u0431\u043E!
"""
ROBOT_LIBRARY_VERSION = '0.1-alpha'
def keyword():
"""A keyword
See `get hello` for details"""
pass
def get_hello():
"""Get the intialization variables
See `importing` for explanation of arguments
and `introduction` for introduction"""
return 'foo'
| Python |
class no_arg_init:
def __init__(self):
"""This doc not shown because there are no arguments."""
def keyword(self):
"""A keyword.
See `get hello` for details and *never* run this keyword.
"""
1/0
def get_hello(self, arg):
"""Returns 'Hello `arg`!'.
See `importing` for explanation of arguments and `introduction`
for introduction. Neither of them really exist, though.
"""
return 'Hello %s' % arg
| Python |
class dynamic:
def get_keyword_names(self):
return ['Keyword 1', 'KW 2']
def run_keyword(self, name, args):
print name, args
def get_keyword_arguments(self, name):
return [ 'arg%d' % (i+1) for i in range(int(name[-1])) ]
def get_keyword_documentation(self, name):
return '''Dummy documentation for `%s`.
Neither `Keyword 1` or `KW 2` do anything really interesting.
They do, however, accept some `arguments`.
Examples:
| Keyword 1 | arg |
| KW 1 | arg | arg 2 |
| KW 2 | arg | arg 2 |
-------
http://robotframework.org
''' % name
| Python |
class regular:
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
"""This is a very regular test library"""
def __init__(self, arg1='hello', arg2='world'):
"""Constructs a new regular test library
See `keyword`
Examples:
| regular | foo | bar |
| regular | | # default values are used |
"""
self.arg1 = arg1
self.arg2 = arg2
def keyword(self):
"""A "keyword" & it contains 'stuff' to <escape>
See `get hello` for details"""
pass
def get_hello(self):
"""Get the intialization variables
See `importing` for explanation of arguments
and `introduction` for introduction"""
return self.arg1, self.arg2
| Python |
class new_style_no_init(object):
"""No __init__ on this one."""
def kw(self):
"""The only lonely keyword."""
| Python |
class RequiredArgs:
def __init__(self, required, arguments, default="value"):
"""This library always needs two arguments and has one default.
Keyword names are got from the given arguments.
"""
self.__dict__[required] = lambda: None
self.__dict__[arguments] = lambda arg: None
self.__dict__[default] = lambda arg1, arg2: None
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Library and Resource File Documentation Generator
Usage: libdoc.py [options] library_or_resource
This script can generate keyword documentation in HTML and XML formats. The
former is suitable for humans and the latter for RIDE, RFDoc, and other tools.
This script can also upload XML documentation to RFDoc system.
Documentation can be created for both test libraries and resource files. All
library and resource file types are supported, and also earlier generated
documentation in XML format can be used as input.
Options:
-a --argument value * Possible arguments that a library needs.
-f --format HTML|XML Specifies whether to generate HTML or XML output.
The default value is got from the output file
extension and if the output is not specified the
default is HTML.
-o --output path Where to write the generated documentation. Can be
either a directory or a file, or a URL pointing to
RFDoc system's upload page. The default value is the
directory where the script is executed from. If
a URL is given, it must start with 'http://'.
-N --name newname Sets the name of the documented library or resource.
-T --title title Sets the title of the generated HTML documentation.
Underscores in the given title are automatically
converted to spaces.
-S --styles styles Overrides the default styles. If the given 'styles'
is a path to an existing files, styles will be read
from it. If it is string a 'NONE', no styles will be
used. Otherwise the given text is used as-is.
-P --pythonpath path * Additional path(s) to insert into PYTHONPATH.
-E --escape what:with * Escapes characters which are problematic in console.
'what' is the name of the character to escape and
'with' is the string to escape it with.
<-------------------ESCAPES------------------------>
-h --help Print this help.
For more information see either the tool's wiki page at
http://code.google.com/p/robotframework/wiki/LibraryDocumentationTool
or tools/libdoc/doc/libdoc.html file inside source distributions.
"""
from __future__ import with_statement
import sys
import os
import re
import tempfile
from httplib import HTTPConnection
from HTMLParser import HTMLParser
from robot.running import TestLibrary, UserLibrary
from robot.utils.templating import Template, Namespace
from robot.errors import DataError, Information
from robot.parsing import populators
from robot import utils
populators.PROCESS_CURDIR = False
def _uploading(output):
return output.startswith('http://')
def create_html_doc(lib, outpath, title=None, styles=None):
if title:
title = title.replace('_', ' ')
else:
title = lib.name
generated = utils.get_timestamp(daysep='-', millissep=None)
namespace = Namespace(LIB=lib, TITLE=title, STYLES=_get_styles(styles),
GENERATED=generated)
doc = Template(template=HTML_TEMPLATE).generate(namespace) + '\n'
outfile = open(outpath, 'w')
outfile.write(doc.encode('UTF-8'))
outfile.close()
def _get_styles(styles):
if not styles:
return DEFAULT_STYLES
if styles.upper() == 'NONE':
return ''
if os.path.isfile(styles):
with open(styles) as f:
return f.read()
return styles
def create_xml_doc(lib, outpath):
writer = utils.XmlWriter(outpath)
writer.start('keywordspec', {'name': lib.name, 'type': lib.type, 'generated': utils.get_timestamp(millissep=None)})
writer.element('version', lib.version)
writer.element('scope', lib.scope)
writer.element('doc', lib.doc)
_write_keywords_to_xml(writer, 'init', lib.inits)
_write_keywords_to_xml(writer, 'kw', lib.keywords)
writer.end('keywordspec')
writer.close()
def upload_xml_doc(outpath, uploadurl):
RFDocUploader().upload(outpath, uploadurl)
def _write_keywords_to_xml(writer, kwtype, keywords):
for kw in keywords:
attrs = kwtype == 'kw' and {'name': kw.name} or {}
writer.start(kwtype, attrs)
writer.element('doc', kw.doc)
writer.start('arguments')
for arg in kw.args:
writer.element('arg', arg)
writer.end('arguments')
writer.end(kwtype)
def LibraryDoc(libname, arguments=None, newname=None):
ext = os.path.splitext(libname)[1].lower()
if ext in ('.html', '.htm', '.xhtml', '.tsv', '.txt', '.rst', '.rest'):
return ResourceDoc(libname, arguments, newname)
elif ext == '.xml':
return XmlLibraryDoc(libname, newname)
elif ext == '.java':
if not utils.is_jython:
raise DataError('Documenting Java test libraries requires using Jython.')
return JavaLibraryDoc(libname, newname)
else:
return PythonLibraryDoc(libname, arguments, newname)
class _DocHelper:
_name_regexp = re.compile("`(.+?)`")
_list_or_table_regexp = re.compile('^(\d+\.|[-*|]|\[\d+\]) .')
def __getattr__(self, name):
if name == 'htmldoc':
return self._get_htmldoc(self.doc)
if name == 'htmlshortdoc':
return utils.html_attr_escape(self.shortdoc)
if name == 'htmlname':
return utils.html_attr_escape(self.name)
raise AttributeError("Non-existing attribute '%s'" % name)
def _process_doc(self, doc):
ret = ['']
for line in doc.splitlines():
line = line.strip()
ret.append(self._get_doc_line_separator(line, ret[-1]))
ret.append(line)
return ''.join(ret)
def _get_doc_line_separator(self, line, prev):
if prev == '':
return ''
if line == '':
return '\n\n'
if self._list_or_table_regexp.search(line):
return '\n'
if prev.startswith('| ') and prev.endswith(' |'):
return '\n'
if self.type == 'resource':
return '\n\n'
return ' '
def _get_htmldoc(self, doc):
doc = utils.html_escape(doc, formatting=True)
return self._name_regexp.sub(self._link_keywords, doc)
def _link_keywords(self, res):
name = res.group(1)
try:
lib = self.lib
except AttributeError:
lib = self
for kw in lib.keywords:
if utils.eq(name, kw.name):
return '<a href="#%s" class="name">%s</a>' % (kw.name, name)
if utils.eq_any(name, ['introduction', 'library introduction']):
return '<a href="#introduction" class="name">%s</a>' % name
if utils.eq_any(name, ['importing', 'library importing']):
return '<a href="#importing" class="name">%s</a>' % name
return '<span class="name">%s</span>' % name
class PythonLibraryDoc(_DocHelper):
type = 'library'
def __init__(self, name, arguments=None, newname=None):
lib = self._import(name, arguments)
self.supports_named_arguments = lib.supports_named_arguments
self.name = newname or lib.name
self.version = utils.html_escape(getattr(lib, 'version', '<unknown>'))
self.scope = self._get_scope(lib)
self.doc = self._process_doc(self._get_doc(lib))
self.inits = self._get_initializers(lib)
self.keywords = [ KeywordDoc(handler, self)
for handler in lib.handlers.values() ]
self.keywords.sort()
def _import(self, name, args):
return TestLibrary(name, args)
def _get_scope(self, lib):
if hasattr(lib, 'scope'):
return {'TESTCASE': 'test case', 'TESTSUITE': 'test suite',
'GLOBAL': 'global'}[lib.scope]
return ''
def _get_doc(self, lib):
return lib.doc or "Documentation for test library `%s`." % self.name
def _get_initializers(self, lib):
if lib.init.arguments.maxargs == 0:
return []
return [KeywordDoc(lib.init, self)]
class ResourceDoc(PythonLibraryDoc):
type = 'resource'
supports_named_arguments = True
def _import(self, path, arguments):
if arguments:
raise DataError("Resource file cannot take arguments.")
return UserLibrary(self._find_resource_file(path))
def _find_resource_file(self, path):
if os.path.isfile(path):
return path
for dire in [ item for item in sys.path if os.path.isdir(item) ]:
if os.path.isfile(os.path.join(dire, path)):
return os.path.join(dire, path)
raise DataError("Resource file '%s' doesn't exist." % path)
def _get_doc(self, resource):
doc = getattr(resource, 'doc', '') # doc available only in 2.1+
if not doc:
doc = "Documentation for resource file `%s`." % self.name
return utils.unescape(doc)
def _get_initializers(self, lib):
return []
class XmlLibraryDoc(_DocHelper):
def __init__(self, libname, newname):
dom = utils.DomWrapper(libname)
self.name = dom.get_attr('name')
self.type = dom.get_attr('type')
self.version = dom.get_node('version').text
self.scope = dom.get_node('scope').text
self.doc = dom.get_node('doc').text
self.inits = [ XmlKeywordDoc(node, self) for node in dom.get_nodes('init') ]
self.keywords = [ XmlKeywordDoc(node, self) for node in dom.get_nodes('kw') ]
class _BaseKeywordDoc(_DocHelper):
def __init__(self, library):
self.lib = library
self.type = library.type
def __cmp__(self, other):
return cmp(self.name.lower(), other.name.lower())
def __getattr__(self, name):
if name == 'argstr':
return ', '.join(self.args)
return _DocHelper.__getattr__(self, name)
def __repr__(self):
return "'Keyword %s from library %s'" % (self.name, self.lib.name)
class KeywordDoc(_BaseKeywordDoc):
def __init__(self, handler, library):
_BaseKeywordDoc.__init__(self, library)
self.name = handler.name
self.args = self._get_args(handler)
self.doc = self._process_doc(handler.doc)
self.shortdoc = handler.shortdoc
def _get_args(self, handler):
required, defaults, varargs = self._parse_args(handler)
args = required + [ '%s=%s' % item for item in defaults ]
if varargs is not None:
args.append('*%s' % varargs)
return args
def _parse_args(self, handler):
args = [ arg.rstrip('_') for arg in handler.arguments.names ]
# strip ${} from user keywords (args look more consistent e.g. in IDE)
if handler.type == 'user':
args = [ arg[2:-1] for arg in args ]
default_count = len(handler.arguments.defaults)
if default_count == 0:
required = args[:]
defaults = []
else:
required = args[:-default_count]
defaults = zip(args[-default_count:], list(handler.arguments.defaults))
varargs = handler.arguments.varargs
varargs = varargs is not None and varargs.rstrip('_') or varargs
if handler.type == 'user' and varargs is not None:
varargs = varargs[2:-1]
return required, defaults, varargs
class XmlKeywordDoc(_BaseKeywordDoc):
def __init__(self, node, library):
_BaseKeywordDoc.__init__(self, library)
self.name = node.get_attr('name', '')
self.args = [ arg.text for arg in node.get_nodes('arguments/arg') ]
self.doc = node.get_node('doc').text
self.shortdoc = self.doc and self.doc.splitlines()[0] or ''
if utils.is_jython:
class JavaLibraryDoc(_DocHelper):
type = 'library'
supports_named_arguments = False
def __init__(self, path, newname=None):
cls = self._get_class(path)
self.name = newname or cls.qualifiedName()
self.version = self._get_version(cls)
self.scope = self._get_scope(cls)
self.doc = self._process_doc(cls.getRawCommentText())
self.keywords = [ JavaKeywordDoc(method, self)
for method in cls.methods() ]
self.inits = [ JavaKeywordDoc(init, self)
for init in cls.constructors() ]
if len(self.inits) == 1 and not self.inits[0].args:
self.inits = []
self.keywords.sort()
def _get_class(self, path):
"""Processes the given Java source file and returns ClassDoc.
Processing is done using com.sun.tools.javadoc APIs. The usage has
been figured out from sources at
http://www.java2s.com/Open-Source/Java-Document/JDK-Modules-com.sun/tools/com.sun.tools.javadoc.htm
Returned object implements com.sun.javadoc.ClassDoc interface, see
http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/doclet/
"""
try:
from com.sun.tools.javadoc import JavadocTool, Messager, ModifierFilter
from com.sun.tools.javac.util import List, Context
from com.sun.tools.javac.code.Flags import PUBLIC
except ImportError:
raise DataError("Creating documentation from Java source files "
"requires 'tools.jar' to be in CLASSPATH.")
context = Context()
Messager.preRegister(context, 'libdoc.py')
jdoctool = JavadocTool.make0(context)
filter = ModifierFilter(PUBLIC)
java_names = List.of(path)
root = jdoctool.getRootDocImpl('en', 'utf-8', filter, java_names,
List.nil(), False, List.nil(),
List.nil(), False, False, True)
return root.classes()[0]
def _get_version(self, cls):
version = self._get_attr(cls, 'VERSION', '<unknown>')
return utils.html_escape(version)
def _get_scope(self, cls):
scope = self._get_attr(cls, 'SCOPE', 'TEST CASE')
return scope.replace('_', ' ').lower()
def _get_attr(self, cls, name, default):
for field in cls.fields():
if field.name() == 'ROBOT_LIBRARY_' + name \
and field.isPublic() and field.constantValue():
return field.constantValue()
return default
class JavaKeywordDoc(_BaseKeywordDoc):
# TODO: handle keyword default values and varargs.
def __init__(self, method, library):
_BaseKeywordDoc.__init__(self, library)
self.name = utils.printable_name(method.name(), True)
self.args = [ param.name() for param in method.parameters() ]
self.doc = self._process_doc(method.getRawCommentText())
self.shortdoc = self.doc and self.doc.splitlines()[0] or ''
class RFDocUploader(object):
def upload(self, file_path, host):
if host.startswith('http://'):
host = host[len('http://'):]
xml_file = open(file_path, 'rb')
conn = HTTPConnection(host)
try:
resp = self._post_multipart(conn, xml_file)
self._validate_success(resp)
finally:
xml_file.close()
conn.close()
def _post_multipart(self, conn, xml_file):
conn.connect()
content_type, body = self._encode_multipart_formdata(xml_file)
headers = {'User-Agent': 'libdoc.py', 'Content-Type': content_type}
conn.request('POST', '/upload/', body, headers)
return conn.getresponse()
def _encode_multipart_formdata(self, xml_file):
boundary = '----------ThIs_Is_tHe_bouNdaRY_$'
body = """--%(boundary)s
Content-Disposition: form-data; name="override"
on
--%(boundary)s
Content-Disposition: form-data; name="file"; filename="%(filename)s"
Content-Type: text/xml
%(content)s
--%(boundary)s--
""" % {'boundary': boundary, 'filename': xml_file.name, 'content': xml_file.read()}
content_type = 'multipart/form-data; boundary=%s' % boundary
return content_type, body.replace('\n', '\r\n')
def _validate_success(self, resp):
html = resp.read()
if resp.status != 200:
raise DataError(resp.reason.strip())
if 'Successfully uploaded library' not in html:
raise DataError('\n'.join(_ErrorParser(html).errors))
class _ErrorParser(HTMLParser):
def __init__(self, html):
HTMLParser.__init__(self)
self._inside_errors = False
self.errors = []
self.feed(html)
self.close()
def handle_starttag(self, tag, attributes):
if ('class', 'errorlist') in attributes:
self._inside_errors = True
def handle_endtag(self, tag):
if tag == 'ul':
self._inside_errors = False
def handle_data(self, data):
if self._inside_errors and data.strip():
self.errors.append(data)
DEFAULT_STYLES = '''
<style media="all" type="text/css">
body {
background: white;
color: black;
font-size: small;
font-family: sans-serif;
padding: 0.1em 0.5em;
}
a.name, span.name {
font-style: italic;
}
a, a:link, a:visited {
color: #c30;
}
a:hover, a:active {
text-decoration: underline;
color: black;
}
div.shortcuts {
margin: 1em 0em;
font-size: 0.9em;
}
div.shortcuts a {
text-decoration: none;
color: black;
}
div.shortcuts a:hover {
text-decoration: underline;
}
table.keywords {
border: 2px solid black;
border-collapse: collapse;
empty-cells: show;
margin: 0.3em 0em;
width: 100%;
}
table.keywords th, table.keywords td {
border: 2px solid black;
padding: 0.2em;
vertical-align: top;
}
table.keywords th {
background: #bbb;
color: black;
}
table.keywords td.kw {
width: 150px;
font-weight: bold;
}
table.keywords td.arg {
width: 300px;
font-style: italic;
}
table.doc {
border: 1px solid black;
background: transparent;
border-collapse: collapse;
empty-cells: show;
font-size: 0.85em;
}
table.doc td {
border: 1px solid black;
padding: 0.1em 0.3em;
height: 1.2em;
}
#footer {
font-size: 0.9em;
}
</style>
<style media="print" type="text/css">
body {
margin: 0px 1px;
padding: 0px;
font-size: 10px;
}
a {
text-decoration: none;
}
</style>
'''.strip()
HTML_TEMPLATE = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>${TITLE}</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
${STYLES}
</head>
<body>
<h1>${TITLE}</h1>
<!-- IF "${LIB.version}" != "<unknown>" -->
<b>Version:</b> ${LIB.version}<br>
<!-- END IF -->
<!-- IF "${LIB.type}" == "library" -->
<b>Scope:</b> ${LIB.scope}<br>
<!-- END IF -->
<b>Named arguments: </b>
<!-- IF ${LIB.supports_named_arguments} -->
supported
<!-- ELSE -->
not supported
<!-- END IF -->
<h2 id="introduction">Introduction</h2>
<p>${LIB.htmldoc}</p>
<!-- IF ${LIB.inits} -->
<h2 id="importing">Importing</h2>
<table border="1" class="keywords">
<tr>
<th class="arg">Arguments</th>
<th class="doc">Documentation</th>
</tr>
<!-- FOR ${init} IN ${LIB.inits} -->
<tr>
<td class="arg">${init.argstr}</td>
<td class="doc">${init.htmldoc}</td>
</tr>
<!-- END FOR -->
</table>
<!-- END IF -->
<h2>Shortcuts</h2>
<div class='shortcuts'>
<!-- FOR ${kw} IN ${LIB.keywords} -->
<a href="#${kw.htmlname}" title="${kw.htmlshortdoc}">${kw.htmlname.replace(' ',' ')}</a>
<!-- IF ${kw} != ${LIB.keywords[-1]} -->
·
<!-- END IF -->
<!-- END FOR -->
</div>
<h2>Keywords</h2>
<table border="1" class="keywords">
<tr>
<th class="kw">Keyword</th>
<th class="arg">Arguments</th>
<th class="doc">Documentation</th>
</tr>
<!-- FOR ${kw} IN ${LIB.keywords} -->
<tr>
<td class="kw"><a name="${kw.htmlname}"></a>${kw.htmlname}</td>
<td class="arg">${kw.argstr}</td>
<td class="doc">${kw.htmldoc}</td>
</tr>
<!-- END FOR -->
</table>
<p id="footer">
Altogether ${LIB.keywords.__len__()} keywords.<br />
Generated by <a href="http://code.google.com/p/robotframework/wiki/LibraryDocumentationTool">libdoc.py</a>
on ${GENERATED}.
</p>
</body>
</html>
'''
if __name__ == '__main__':
def get_format(format, output):
if format:
return format.upper()
if os.path.splitext(output)[1].upper() == '.XML':
return 'XML'
return 'HTML'
def get_unique_path(base, ext, index=0):
if index == 0:
path = '%s.%s' % (base, ext)
else:
path = '%s-%d.%s' % (base, index, ext)
if os.path.exists(path):
return get_unique_path(base, ext, index+1)
return path
try:
argparser = utils.ArgumentParser(__doc__)
opts, args = argparser.parse_args(sys.argv[1:], pythonpath='pythonpath',
help='help', unescape='escape',
check_args=True)
libname = args[0]
library = LibraryDoc(libname, opts['argument'], opts['name'])
output = opts['output'] or '.'
if _uploading(output):
file_path = os.path.join(tempfile.gettempdir(), 'libdoc_upload.xml')
create_xml_doc(library, file_path)
upload_xml_doc(file_path, output)
os.remove(file_path)
else:
format = get_format(opts['format'], output)
if os.path.isdir(output):
output = get_unique_path(os.path.join(output, library.name), format.lower())
output = os.path.abspath(output)
if format == 'HTML':
create_html_doc(library, output, opts['title'], opts['styles'])
else:
create_xml_doc(library, output)
except Information, msg:
print msg
except DataError, err:
print err, '\n\nTry --help for usage information.'
except Exception, err:
print err
else:
print '%s -> %s' % (library.name, output)
| Python |
#!/usr/bin/env python
# tool2html.py -- Creates HTML version of given tool documentation
#
# First part of this file is Pygments configuration and actual
# documentation generation follows it.
#
# Pygments configuration
#
# This code is from 'external/rst-directive.py' file included in Pygments 0.9
# distribution. For more details see http://pygments.org/docs/rstdirective/
#
"""
The Pygments MoinMoin Parser
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This fragment is a Docutils_ 0.4 directive that renders source code
(to HTML only, currently) via Pygments.
To use it, adjust the options below and copy the code into a module
that you import on initialization. The code then automatically
registers a ``sourcecode`` directive that you can use instead of
normal code blocks like this::
.. sourcecode:: python
My code goes here.
If you want to have different code styles, e.g. one with line numbers
and one without, add formatters with their names in the VARIANTS dict
below. You can invoke them instead of the DEFAULT one by using a
directive option::
.. sourcecode:: python
:linenos:
My code goes here.
Look at the `directive documentation`_ to get all the gory details.
.. _Docutils: http://docutils.sf.net/
.. _directive documentation:
http://docutils.sourceforge.net/docs/howto/rst-directives.html
:copyright: 2007 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
# Options
# ~~~~~~~
# Set to True if you want inline CSS styles instead of classes
INLINESTYLES = False
from pygments.formatters import HtmlFormatter
# The default formatter
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)
# Add name -> formatter pairs for every variant you want to use
VARIANTS = {
# 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
}
import os
from docutils import nodes
from docutils.parsers.rst import directives
from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer
def pygments_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
try:
lexer = get_lexer_by_name(arguments[0])
except ValueError:
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
# take an arbitrary option if more than one is given
formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
filtered = [ line for line in content if line ]
if len(filtered)==1 and os.path.isfile(filtered[0]):
content = open(content[0]).read().splitlines()
parsed = highlight(u'\n'.join(content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
pygments_directive.arguments = (1, 0, 1)
pygments_directive.content = 1
pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
directives.register_directive('sourcecode', pygments_directive)
#
# Creating the documentation
#
# This code is based on rst2html.py distributed with docutils
#
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
import sys
from docutils.core import publish_cmdline
def create_tooldoc(tool_name):
description = 'HTML generator for Robot Framework Tool Documentation.'
stylesheet_path = os.path.join(BASEDIR, '..', 'doc', 'userguide', 'src',
'userguide.css')
base_path = os.path.join(BASEDIR, tool_name, 'doc', tool_name)
arguments = [ '--time', '--stylesheet-path=%s' % stylesheet_path,
base_path+'.txt', base_path+'.html' ]
publish_cmdline(writer_name='html', description=description, argv=arguments)
print os.path.abspath(arguments[-1])
BASEDIR = os.path.dirname(os.path.abspath(__file__))
VALID_TOOLS = [ name for name in os.listdir(BASEDIR) if '.' not in name ]
VALID_TOOLS = [ n for n in VALID_TOOLS if os.path.isdir(os.path.join(BASEDIR, n, 'doc')) ]
if __name__ == '__main__':
try:
tool = sys.argv[1].lower()
if tool == 'all':
for name in sorted(VALID_TOOLS):
create_tooldoc(name)
elif tool in VALID_TOOLS:
create_tooldoc(tool)
else:
raise IndexError
except IndexError:
print 'Usage: tool2html.py [ tool | all ]\n\nTools:'
for tool in sorted(VALID_TOOLS):
print ' %s' % tool
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import inspect
import traceback
from StringIO import StringIO
from SimpleXMLRPCServer import SimpleXMLRPCServer
try:
import signal
except ImportError:
signal = None
class RobotRemoteServer(SimpleXMLRPCServer):
allow_reuse_address = True
def __init__(self, library, host='localhost', port=8270, allow_stop=True):
SimpleXMLRPCServer.__init__(self, (host, int(port)), logRequests=False)
self._library = library
self._allow_stop = allow_stop
self._register_functions()
self._register_signal_handlers()
print 'Robot Framework remote server starting at %s:%s' % (host, port)
self.serve_forever()
def _register_functions(self):
self.register_function(self.get_keyword_names)
self.register_function(self.run_keyword)
self.register_function(self.get_keyword_arguments)
self.register_function(self.get_keyword_documentation)
self.register_function(self.stop_remote_server)
def _register_signal_handlers(self):
def stop_with_signal(signum, frame):
self._allow_stop = True
self.stop_remote_server()
if hasattr(signal, 'SIGHUP'):
signal.signal(signal.SIGHUP, stop_with_signal)
if hasattr(signal, 'SIGINT'):
signal.signal(signal.SIGINT, stop_with_signal)
def serve_forever(self):
self._shutdown = False
while not self._shutdown:
self.handle_request()
def stop_remote_server(self):
prefix = 'Robot Framework remote server at %s:%s ' % self.server_address
if self._allow_stop:
print prefix + 'stopping'
self._shutdown = True
else:
print '*WARN* ' + prefix + 'does not allow stopping'
return True
def get_keyword_names(self):
get_kw_names = getattr(self._library, 'get_keyword_names', None) or \
getattr(self._library, 'getKeywordNames', None)
if inspect.isroutine(get_kw_names):
names = get_kw_names()
else:
names = [attr for attr in dir(self._library) if attr[0] != '_'
and inspect.isroutine(getattr(self._library, attr))]
return names + ['stop_remote_server']
def run_keyword(self, name, args):
result = {'status': 'PASS', 'return': '', 'output': '',
'error': '', 'traceback': ''}
self._intercept_stdout()
try:
return_value = self._get_keyword(name)(*args)
except:
result['status'] = 'FAIL'
result['error'], result['traceback'] = self._get_error_details()
else:
result['return'] = self._handle_return_value(return_value)
result['output'] = self._restore_stdout()
return result
def get_keyword_arguments(self, name):
kw = self._get_keyword(name)
args, varargs, _, defaults = inspect.getargspec(kw)
if inspect.ismethod(kw):
args = args[1:] # drop 'self'
if defaults:
args, names = args[:-len(defaults)], args[-len(defaults):]
args += ['%s=%s' % (n, d) for n, d in zip(names, defaults)]
if varargs:
args.append('*%s' % varargs)
return args
def get_keyword_documentation(self, name):
return inspect.getdoc(self._get_keyword(name)) or ''
def _get_keyword(self, name):
if name == 'stop_remote_server':
return self.stop_remote_server
return getattr(self._library, name)
def _get_error_details(self):
exc_type, exc_value, exc_tb = sys.exc_info()
if exc_type in (SystemExit, KeyboardInterrupt):
self._restore_stdout()
raise
return (self._get_error_message(exc_type, exc_value),
self._get_error_traceback(exc_tb))
def _get_error_message(self, exc_type, exc_value):
name = exc_type.__name__
message = str(exc_value)
if not message:
return name
if name in ('AssertionError', 'RuntimeError', 'Exception'):
return message
return '%s: %s' % (name, message)
def _get_error_traceback(self, exc_tb):
# Latest entry originates from this class so it can be removed
entries = traceback.extract_tb(exc_tb)[1:]
trace = ''.join(traceback.format_list(entries))
return 'Traceback (most recent call last):\n' + trace
def _handle_return_value(self, ret):
if isinstance(ret, (basestring, int, long, float)):
return ret
if isinstance(ret, (tuple, list)):
return [ self._handle_return_value(item) for item in ret ]
if isinstance(ret, dict):
return dict([(self._str(key), self._handle_return_value(value))
for key, value in ret.items()])
return self._str(ret)
def _str(self, item):
if item is None:
return ''
return str(item)
def _intercept_stdout(self):
# TODO: What about stderr?
sys.stdout = StringIO()
def _restore_stdout(self):
output = sys.stdout.getvalue()
sys.stdout.close()
sys.stdout = sys.__stdout__
return output
| Python |
import sys
from SimpleXMLRPCServer import SimpleXMLRPCServer
class SimpleLibrary(SimpleXMLRPCServer):
def __init__(self, port=8270):
SimpleXMLRPCServer.__init__(self, ('localhost', int(port)))
self.register_function(self.get_keyword_names)
self.register_function(self.run_keyword)
self.register_function(self.stop_remote_server)
self.serve_forever()
def serve_forever(self):
self._shutdown = False
while not self._shutdown:
self.handle_request()
def stop_remote_server(self):
self._shutdown = True
return True
def get_keyword_names(self):
return ['kw_1', 'kw_2', 'stop_remote_server']
def run_keyword(self, name, args):
if name == 'kw_1':
return {'status': 'PASS', 'return': ' '.join(args)}
elif name == 'kw_2':
return {'status': 'FAIL', 'error': ' '.join(args)}
else:
self.stop_remote_server()
return {'status': 'PASS'}
if __name__ == '__main__':
SimpleLibrary(*sys.argv[1:])
| Python |
# Can be used in the test data like ${MyObject()} or ${MyObject(1)}
class MyObject:
def __init__(self, index=''):
self.index = index
def __str__(self):
return '<MyObject%s>' % self.index
UNICODE = (u'Hyv\u00E4\u00E4 y\u00F6t\u00E4. '
u'\u0421\u043F\u0430\u0441\u0438\u0431\u043E!')
LIST_WITH_OBJECTS = [MyObject(1), MyObject(2)]
NESTED_LIST = [ [True, False], [[1, None, MyObject(), {}]] ]
NESTED_TUPLE = ( (True, False), [(1, None, MyObject(), {})] )
DICT_WITH_OBJECTS = {'As value': MyObject(1), MyObject(2): 'As key'}
NESTED_DICT = { 1: {None: False},
2: {'A': {'n': None},
'B': {'o': MyObject(), 'e': {}}} }
| Python |
import sys
class RemoteTestLibrary:
_unicode = (u'Hyv\u00E4\u00E4 y\u00F6t\u00E4. '
u'\u0421\u043F\u0430\u0441\u0438\u0431\u043E!')
def get_server_language(self):
lang = sys.platform.startswith('java') and 'jython' or 'python'
return '%s%d%d' % (lang, sys.version_info[0], sys.version_info[1])
# Basic communication (and documenting keywords)
def passing(self):
"""This keyword passes.
See `Failing`, `Logging`, and `Returning` for other basic keywords.
"""
pass
def failing(self, message):
"""This keyword fails with provided `message`"""
raise AssertionError(message)
def logging(self, message, level='INFO'):
"""This keywords logs given `message` with given `level`
Example:
| Logging | Hello, world! | |
| Logging | Warning!!! | WARN |
"""
print '*%s* %s' % (level, message)
def returning(self):
"""This keyword returns a string 'returned string'."""
return 'returned string'
# Logging
def one_message_without_level(self):
print 'Hello, world!'
def multiple_messages_with_different_levels(self):
print 'Info message'
print '*DEBUG* Debug message'
print '*INFO* Second info'
print 'this time with two lines'
print '*INFO* Third info'
print '*TRACE* This is ignored'
print '*WARN* Warning'
def log_unicode(self):
print self._unicode
def logging_and_failing(self):
print '*INFO* This keyword will fail!'
print '*WARN* Run for your lives!!'
raise AssertionError('Too slow')
def logging_and_returning(self):
print 'Logged message'
return 'Returned value'
def log_control_char(self):
print '\x01'
# Failures
def base_exception(self):
raise Exception('My message')
def exception_without_message(self):
raise Exception
def assertion_error(self):
raise AssertionError('Failure message')
def runtime_error(self):
raise RuntimeError('Error message')
def name_error(self):
non_existing
def attribute_error(self):
self.non_existing
def index_error(self):
[][0]
def zero_division(self):
1/0
def custom_exception(self):
raise MyException('My message')
def failure_deeper(self, rounds=10):
if rounds == 1:
raise RuntimeError('Finally failing')
self.failure_deeper(rounds-1)
# Arguments counts
def no_arguments(self):
return 'no arguments'
def one_argument(self, arg):
return arg
def two_arguments(self, arg1, arg2):
return '%s %s' % (arg1, arg2)
def seven_arguments(self, arg1, arg2, arg3, arg4, arg5, arg6, arg7):
return ' '.join((arg1, arg2, arg3, arg4, arg5, arg6, arg7))
def arguments_with_default_values(self, arg1, arg2='2', arg3=3):
return '%s %s %s' % (arg1, arg2, arg3)
def variable_number_of_arguments(self, *args):
return ' '.join(args)
def required_defaults_and_varargs(self, req, default='world', *varargs):
return ' '.join((req, default) + varargs)
# Argument types
def string_as_argument(self, arg):
self._should_be_equal(arg, self.return_string())
def unicode_string_as_argument(self, arg):
self._should_be_equal(arg, self._unicode)
def empty_string_as_argument(self, arg):
self._should_be_equal(arg, '')
def integer_as_argument(self, arg):
self._should_be_equal(arg, self.return_integer())
def negative_integer_as_argument(self, arg):
self._should_be_equal(arg, self.return_negative_integer())
def float_as_argument(self, arg):
self._should_be_equal(arg, self.return_float())
def negative_float_as_argument(self, arg):
self._should_be_equal(arg, self.return_negative_float())
def zero_as_argument(self, arg):
self._should_be_equal(arg, 0)
def boolean_true_as_argument(self, arg):
self._should_be_equal(arg, True)
def boolean_false_as_argument(self, arg):
self._should_be_equal(arg, False)
def none_as_argument(self, arg):
self._should_be_equal(arg, '')
def object_as_argument(self, arg):
self._should_be_equal(arg, '<MyObject>')
def list_as_argument(self, arg):
self._should_be_equal(arg, self.return_list())
def empty_list_as_argument(self, arg):
self._should_be_equal(arg, [])
def list_containing_none_as_argument(self, arg):
self._should_be_equal(arg, [''])
def list_containing_objects_as_argument(self, arg):
self._should_be_equal(arg, ['<MyObject1>', '<MyObject2>'])
def nested_list_as_argument(self, arg):
exp = [ [True, False], [[1, '', '<MyObject>', {}]] ]
self._should_be_equal(arg, exp)
def dictionary_as_argument(self, arg):
self._should_be_equal(arg, self.return_dictionary())
def empty_dictionary_as_argument(self, arg):
self._should_be_equal(arg, {})
def dictionary_with_non_string_keys_as_argument(self, arg):
self._should_be_equal(arg, {'1': 2, '': True})
def dictionary_containing_none_as_argument(self, arg):
self._should_be_equal(arg, {'As value': '', '': 'As key'})
def dictionary_containing_objects_as_argument(self, arg):
self._should_be_equal(arg, {'As value': '<MyObject1>', '<MyObject2>': 'As key'})
def nested_dictionary_as_argument(self, arg):
exp = { '1': {'': False},
'2': {'A': {'n': ''}, 'B': {'o': '<MyObject>', 'e': {}}} }
self._should_be_equal(arg, exp)
def _should_be_equal(self, arg, exp):
if arg != exp:
raise AssertionError('%r != %r' % (arg, exp))
# Return values
def return_string(self):
return 'Hello, world!'
def return_unicode_string(self):
return self._unicode
def return_empty_string(self):
return ''
def return_integer(self):
return 42
def return_negative_integer(self):
return -1
def return_float(self):
return 3.14
def return_negative_float(self):
return -0.5
def return_zero(self):
return 0
def return_boolean_true(self):
return True
def return_boolean_false(self):
return False
def return_nothing(self):
pass
def return_object(self):
return MyObject()
def return_list(self):
return ['One', -2, False]
def return_empty_list(self):
return []
def return_list_containing_none(self):
return [None]
def return_list_containing_objects(self):
return [MyObject(1), MyObject(2)]
def return_nested_list(self):
return [ [True, False], [[1, None, MyObject(), {}]] ]
def return_tuple(self):
return (1, 'two', True)
def return_empty_tuple(self):
return ()
def return_nested_tuple(self):
return ( (True, False), [(1, None, MyObject(), {})] )
def return_dictionary(self):
return {'one': 1, 'spam': 'eggs'}
def return_empty_dictionary(self):
return {}
def return_dictionary_with_non_string_keys(self):
return {1: 2, None: True}
def return_dictionary_containing_none(self):
return {'As value': None, None: 'As key'}
def return_dictionary_containing_objects(self):
return {'As value': MyObject(1), MyObject(2): 'As key'}
def return_nested_dictionary(self):
return { 1: {None: False},
2: {'A': {'n': None}, 'B': {'o': MyObject(), 'e': {}}} }
def return_control_char(self):
return '\x01'
# Not keywords
def _private_method(self):
pass
def __private_method(self):
pass
attribute = 'Not a keyword'
class MyObject:
def __init__(self, index=''):
self.index = index
def __str__(self):
return '<MyObject%s>' % self.index
class MyException(Exception):
pass
if __name__ == '__main__':
import sys
from robotremoteserver import RobotRemoteServer
RobotRemoteServer(RemoteTestLibrary(), *sys.argv[1:])
| Python |
#!/usr/bin/env python
"""Script for running the remote library tests against different servers.
Usage 1: run.py language[:runner] [[options] datasources]
Valid languages are 'python', 'jython' or 'ruby', and runner can
either by 'pybot' (default) or 'jybot'. By default, all tests under
'test/data' directory are run, but this can be changed by providing
options, which can be any Robot Framework command line options.
Usage 2: run.py stop [port]
Stops remote server in specified port. Default port is 8270.
"""
import sys
import xmlrpclib
import time
import os
import subprocess
import shutil
import socket
REMOTEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUTPUTDIR = os.path.join(REMOTEDIR, 'test', 'logs')
if os.path.exists(OUTPUTDIR):
shutil.rmtree(OUTPUTDIR)
os.mkdir(OUTPUTDIR)
class Library:
def __init__(self, language=None):
if language:
self._start_library(language)
if not self.test(attempts=15):
raise RuntimeError("Starting %s library failed" % language)
def _start_library(self, lang):
opts = self._environment_setup(lang)
ext = {'python': 'py', 'jython': 'py', 'ruby': 'rb'}[lang]
lib = os.path.join(REMOTEDIR, 'test', 'libs', 'examplelib.%s' % ext)
stdout = os.path.join(OUTPUTDIR, 'stdout.txt')
stderr = os.path.join(OUTPUTDIR, 'stderr.txt')
cmd = '%s%s%s 1> %s 2> %s' % (lang, opts, lib, stdout, stderr)
print 'Starting %s remote library with command:\n%s' % (lang, cmd)
subprocess.Popen(cmd, shell=True)
def _environment_setup(self, lang):
if lang == 'jython':
return ' -Dpython.path=%s ' % REMOTEDIR
varname = {'python': 'PYTHONPATH', 'ruby': 'LOAD_PATH'}[lang]
os.environ[varname] = REMOTEDIR
print '%s: %s' % (varname, REMOTEDIR)
return ' '
def test(self, port=8270, attempts=1):
url = 'http://localhost:%s' % port
for i in range(attempts):
try:
xmlrpclib.ServerProxy(url).get_keyword_names()
except socket.error, (errno, errmsg):
time.sleep(1)
except xmlrpclib.Error, err:
errmsg = err.faultString
break
else:
print "Remote library is running on port %s" % port
return True
print "Failed to connect to library on port %s: %s" % (port, errmsg)
return False
def stop(self, port=8270):
if self.test(port):
server = xmlrpclib.ServerProxy('http://localhost:%s' % port)
server.stop_remote_server()
print "Remote library on port %s stopped" % port
if __name__ == '__main__':
if len(sys.argv) < 2:
print __doc__
sys.exit(1)
mode = sys.argv[1]
if mode == 'stop':
Library().stop(*sys.argv[2:])
sys.exit()
if ':' in mode:
lang, runner = mode.split(':')
else:
lang, runner = mode, 'pybot'
lib = Library(lang)
include = lang if lang != 'jython' else 'python'
output = os.path.join(OUTPUTDIR, 'output.xml')
args = [runner, '--log', 'NONE', '--report', 'NONE', '--output', output,
'--name', mode, '--include', include, '--noncritical', 'non-critical']
if len(sys.argv) == 2:
args.append(os.path.join(REMOTEDIR, 'test', 'atest'))
else:
args.extend(sys.argv[2:])
print 'Running tests with command:\n%s' % ' '.join(args)
subprocess.call(args)
lib.stop()
print
checker = os.path.join(REMOTEDIR, '..', 'statuschecker', 'statuschecker.py')
subprocess.call(['python', checker, output])
rc = subprocess.call(['rebot', '--noncritical', 'non-critical',
'--outputdir', OUTPUTDIR, output])
if rc == 0:
print 'All tests passed'
else:
print '%d test%s failed' % (rc, 's' if rc != 1 else '')
| Python |
#!/usr/bin/env python
import os
import sys
class ExampleRemoteLibrary:
def count_items_in_directory(self, path):
return len(i for i in os.listdir(path) if not i.startswith('.'))
def strings_should_be_equal(self, str1, str2):
print "Comparing '%s' to '%s'" % (str1, str2)
if str1 != str2:
raise AssertionError("Given strings are not equal")
if __name__ == '__main__':
from robotremoteserver import RobotRemoteServer
RobotRemoteServer(ExampleRemoteLibrary(), *sys.argv[1:])
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Test Data Documentation Tool
Usage: testdoc.py [options] data_sources
This tool generates a high level test documentation from a given test data.
Generated documentation includes the names, documentations and other metadata
of each test suite and test case, as well as the top-level keywords and their
arguments. Most of the options accepted by this tool have exactly same
semantics as same options have when executing test cases.
Options:
-o --output path Where to write the generated documentation. If the
path is a directory, the documentation is
generated there using name '<suitename>-doc.html'.
-T --title title Set the title of the generated documentation.
Underscores in the title are converted to spaces.
-N --name name Set the name of the top level test suite.
-D --doc document Set the document of the top level test suite.
-M --metadata name:value * Set metadata of the top level test suite.
-G --settag tag * Set given tag(s) to all test cases.
-t --test name * Include test cases by name.
-s --suite name * Include test suites by name.
-i --include tag * Include test cases by tags.
-e --exclude tag * Exclude test cases by tags.
-h --help Print this help.
Examples:
$ testdoc.py mytestcases.html
$ testdoc.py --name smoke_test_plan --include smoke path/to/my_tests/
"""
import sys
import os
import time
from robot import utils, version
from robot.common import BaseKeyword, BaseTestSuite
from robot.running import TestSuite, Keyword
from robot.conf import RobotSettings
from robot.result.logserializers import LogSerializer
from robot.result import templates
from robot.result.templating import Namespace, Template
from robot.errors import DataError, Information
from robot.parsing import populators
from robot.variables import Variables
populators.PROCESS_CURDIR = False
Variables.set_from_variable_table = lambda self, varz: None
def generate_test_doc(args):
opts, datasources = process_arguments(args)
suite = TestSuite(datasources, RobotSettings(opts))
outpath = get_outpath(opts['output'], suite.name)
serialize_test_doc(suite, outpath, opts['title'])
exit(msg=outpath)
def serialize_test_doc(suite, outpath, title):
outfile = open(outpath, 'w')
serializer = TestdocSerializer(outfile, suite)
ttuple = time.localtime()
str_time = utils.format_time(ttuple, daytimesep=' ', gmtsep=' ')
int_time = long(time.mktime(ttuple))
if title:
title = title.replace('_', ' ')
else:
title = 'Documentation for %s' % suite.name
namespace = Namespace(gentime_str=str_time, gentime_int=int_time,
version=version.get_full_version('testdoc.py'),
suite=suite, title=title)
Template(template=templates.LOG).generate(namespace, outfile)
suite.serialize(serializer)
outfile.write('</body>\n</html>\n')
outfile.close()
def process_arguments(args_list):
argparser = utils.ArgumentParser(__doc__)
try:
opts, args = argparser.parse_args(args_list, help='help', check_args=True)
except Information, msg:
exit(msg=str(msg))
except DataError, err:
exit(error=str(err))
return opts, args
def exit(msg=None, error=None):
if msg:
sys.stdout.write(msg + '\n')
sys.exit(0)
sys.stderr.write(error + '\n\nTry --help for usage information.\n')
sys.exit(1)
def get_outpath(path, suite_name):
if not path:
path = '.'
if os.path.isdir(path):
path = os.path.join(path, '%s-doc.html' % suite_name.replace(' ', '_'))
return os.path.abspath(path)
class TestdocSerializer(LogSerializer):
def __init__(self, output, suite):
self._writer = utils.HtmlWriter(output)
self._idgen = utils.IdGenerator()
self._split_level = -1
self._suite_level = 0
def start_suite(self, suite):
suite._set_variable_dependent_metadata(NonResolvingContext())
LogSerializer.start_suite(self, suite)
def start_test(self, test):
test._init_test(NonResolvingContext())
LogSerializer.start_test(self, test)
def start_keyword(self, kw):
if isinstance(kw, Keyword): # Doesn't match For
kw.name = kw._get_name(kw.name)
LogSerializer.start_keyword(self, kw)
def _is_element_open(self, item):
return isinstance(item, BaseTestSuite)
def _write_times(self, item):
pass
def _write_suite_metadata(self, suite):
self._start_suite_or_test_metadata(suite)
for name, value in suite.get_metadata(html=True):
self._write_metadata_row(name, value, escape=False, write_empty=True)
self._write_source(suite.source)
self._write_metadata_row('Number of Tests', suite.get_test_count())
self._writer.end('table')
def _start_suite_or_test_metadata(self, suite_or_test):
suite_or_test.doc = utils.unescape(suite_or_test.doc)
LogSerializer._start_suite_or_test_metadata(self, suite_or_test)
def _write_test_metadata(self, test):
self._start_suite_or_test_metadata(test)
if test.timeout.secs < 0:
tout = ''
else:
tout = utils.secs_to_timestr(test.timeout.secs)
if test.timeout.message:
tout += ' | ' + test.timeout.message
self._write_metadata_row('Timeout', tout)
self._write_metadata_row('Tags', ', '.join(test.tags))
self._writer.end('table')
def _write_folding_button(self, item):
if not isinstance(item, BaseKeyword):
LogSerializer._write_folding_button(self, item)
def _write_expand_all(self, item):
if isinstance(item, BaseTestSuite):
LogSerializer._write_expand_all(self, item)
class NonResolvingContext:
def replace_vars_from_setting(self, name, item, errors):
return item
def replace_string(self, item):
return item
def get_current_vars(self):
return NonResolvingContext()
if __name__ == '__main__':
generate_test_doc(sys.argv[1:])
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Debugfile Viewer
Usage: fileviever.py [path]
This tool is mainly targeted for viewing Robot Framework debug files set
with '--debugfile' command line option when running test. The idea is to
provide a tool that has similar functionality as 'tail -f' command in
unixy systems.
The tool has a simple GUI which is updated every time the file opened into
it is updated. File can be given from command line or opened using 'Open'
button in the GUI.
"""
import os
import sys
import time
from FileDialog import LoadFileDialog
import Tkinter as Tk
class FileViewer:
def __init__(self, path=None):
self._path = path is not None and os.path.abspath(path) or None
self._file = self._open_file(path)
self._root = self._create_root()
self._create_components(self._root)
self._last_update_cmd = None
self._update()
def mainloop(self):
self._root.mainloop()
def _create_root(self):
root = Tk.Tk()
root.title('Debug file viewer, v0.1')
root.geometry('750x500+100+100')
return root
def _create_components(self, root):
self._create_toolbar(root)
self._create_statusbar(root)
self._text_area = self._create_scrollable_text_area(root)
def _create_statusbar(self, root):
statusbar = Tk.Frame(root)
self._statusbar_left = Tk.Label(statusbar)
self._statusbar_left.pack(side=Tk.LEFT)
self._statusbar_right = Tk.Label(statusbar)
self._statusbar_right.pack(side=Tk.RIGHT)
statusbar.pack(side=Tk.BOTTOM, fill=Tk.X)
def _create_toolbar(self, root):
toolbar = Tk.Frame(root, width=65)
self._create_button(toolbar, 'Open', self._open_file_dialog)
self._create_button(toolbar, 'Clear', self._clear_text)
self._create_button(toolbar, 'Exit', self._root.destroy)
self._pause_cont_button = self._create_button(toolbar, 'Pause',
self._pause_or_cont, 25)
toolbar.pack_propagate(0)
toolbar.pack(side=Tk.RIGHT, fill=Tk.Y)
def _create_button(self, parent, label, command, pady=2):
button = Tk.Button(parent, text=label, command=command)
button.pack(side=Tk.TOP, padx=2, pady=pady, fill=Tk.X)
return button
def _create_scrollable_text_area(self, root):
scrollbar = Tk.Scrollbar(root)
text = Tk.Text(root, yscrollcommand=scrollbar.set, font=("Courier", 9))
scrollbar.config(command=text.yview)
scrollbar.pack(side=Tk.RIGHT, fill=Tk.Y)
text.pack(fill=Tk.BOTH, expand=1)
return text
def _pause_or_cont(self):
if self._pause_cont_button['text'] == 'Pause':
if self._last_update_cmd is not None:
self._root.after_cancel(self._last_update_cmd)
self._pause_cont_button.configure(text='Continue')
else:
self._pause_cont_button.configure(text='Pause')
self._root.after(50, self._update)
def _update(self):
if self._file is None:
self._file = self._open_file(self._path)
if self._file is not None:
try:
if os.stat(self._path).st_size < self._last_file_size:
self._file.seek(0)
self._clear_text()
self._text_area.insert(Tk.END, self._file.read())
self._last_file_size = self._file.tell()
except (OSError, IOError):
self._file = None
self._clear_text()
self._text_area.yview('moveto', '1.0')
self._set_status_bar_text()
self._last_update_cmd = self._root.after(50, self._update)
def _clear_text(self):
self._text_area.delete(1.0, Tk.END)
def _set_status_bar_text(self):
left, right = self._path, ''
if self._path is None:
left = 'No file opened'
elif self._file is None:
right = 'File does not exist'
else:
timetuple = time.localtime(os.stat(self._path).st_mtime)
timestamp = '%d%02d%02d %02d:%02d:%02d' % timetuple[:6]
right = 'File last modified: %s' % timestamp
self._statusbar_left.configure(text=left)
self._statusbar_right.configure(text=right)
def _open_file(self, path):
if path is not None and os.path.exists(path):
self._last_file_size = os.stat(path).st_size
return open(path)
return None
def _open_file_dialog(self):
dialog = LoadFileDialog(self._root, title='Choose file to view')
fname = dialog.go()
if fname is None:
return
self._path = os.path.abspath(fname)
if self._last_update_cmd is not None:
self._root.after_cancel(self._last_update_cmd)
if self._file is not None:
self._file.close()
self._file = self._open_file(self._path)
self._clear_text()
if self._pause_cont_button['text'] == 'Continue':
self._pause_or_cont()
else:
self._update()
if __name__ == '__main__':
if len(sys.argv) > 2 or '--help' in sys.argv:
print __doc__
sys.exit(1)
app = FileViewer(*sys.argv[1:])
app.mainloop()
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""risto.py -- Robot Framework's Historical Reporting Tool
Version: <VERSION>
Usage: risto.py options input_files
or: risto.py options1 --- options2 --- optionsN --- input files
or: risto.py --argumentfile path
risto.py plots graphs about test execution history based on statistics
read from Robot Framework output files. Actual drawing is handled by
Matplotlib tool, which must be installed separately. More information
about it, including installation instructions, can be found from
http://matplotlib.sourceforge.net.
By default risto.py draws total, passed and failed graphs for critical
tests and all tests, but it is possible to omit some of these graphs
and also to add graphs by tags. Names of test rounds that are shown on
the x-axis are, by default, got from the paths to input files.
Alternatively, names can be got from the metadata of the top level
test suite (see Robot Framework's '--metadata' option for more details).
Graphs are saved to a file specified with '--output' option, and the output
format is got from the file extension. Supported formats depend on
installed Matplotlib back-ends, but at least PNG ought to be always
available. If output file is omitted, the graph is opened into Matplotlib's
image viewer (which requires Matplotlib to be installed with some graphical
front-end).
It is possible to draw multiple graphs with different options at once. This
is done by separating different option groups with three or more hyphens
('---'). Note that in this case also paths to input files need to be
separated from last options similarly.
Instead of giving all options from command line, it is possible to read
them from a file specified with '--argument' option. In an argument file
options and their possible argument are listed one per line, and option
groups are separated with lines of three or more hyphens. Empty lines and
lines starting with a hash mark ('#') are ignored.
Options:
-C --nocritical Do not plot graphs for critical tests.
-A --noall Do not plot graphs for all tests.
-T --nototals Do not plot total graphs.
-P --nopassed Do not plot passed graphs.
-F --nofailed Do not plot failed graphs.
-t --tag name * Add graphs for these tags. Name can contain '*' and
'?' as wildcards. 'AND' in the tag name is converted
to ' & ', to make it easier to plot combined tags.
-o --output path Path to the image file to create. If not given, the
image is opened into Matplotlib's image viewer.
-i --title title Title of the graph. Underscores in the given title
are converted to spaces. By default there is no
title.
-w --width inches Width of the image. Default is 800.
-h --height inches Height of the image. Default is 400.
-f --font size Font size used for legends and labels. Default is 8.
-m --marker size Size of marked used with tag graphs. Default is 5.
-x --xticks num Maximum number of ticks in x-axis. Default is 15.
-n --namemeta name Name of the metadata of the top level test suite
where to get name of the test round. By default names
are got from paths to input files.
--- Used to group options when creating multiple images
at once.
--argumentfile path Read arguments from the specified file.
--verbose Verbose output.
--help Print this help.
--version Print version information.
Examples:
risto.py --output history.png output1.xml output2.xml output3.xml
risto.py --title My_Report --noall --namemeta Date --output out.png *.xml
risto.py --nopassed --tag smoke --tag iter-* results/*/output.xml
risto.py -CAP -t tag1 --- -CAP -t tag2 --- -CAP -t tag3 --- outputs/*.xml
risto.py --argumentfile arguments.txt
====[arguments.txt]===================
--title Overview
--output overview.png
----------------------
--nocritical
--noall
--nopassed
--tag smoke1
--title Smoke Tests
--output smoke.png
----------------------
path/to/*.xml
======================================
"""
__version__ = '1.0'
import os.path
import sys
import glob
try:
import xml.etree.cElementTree as ET
except ImportError:
try:
import cElementTree as ET
except ImportError:
try:
import elementtree.ElementTree as ET
except ImportError:
raise ImportError('Could not import ElementTree module. '
'Upgrade to Python 2.5+ or install ElementTree '
'from http://effbot.org/zone/element-index.htm')
try:
from matplotlib import pylab
from matplotlib.lines import Line2D
from matplotlib.font_manager import FontProperties
from matplotlib.pyplot import get_current_fig_manager
except ImportError:
raise ImportError('Could not import Matplotlib modules. Install it form '
'http://matplotlib.sourceforge.net/')
try:
from robot import utils
from robot.errors import DataError, Information
except ImportError:
raise ImportError('Could not import Robot Framework modules. '
'Make sure you have Robot Framework installed.')
class AllStatistics(object):
def __init__(self, paths, namemeta=None, verbose=False):
self._stats = self._get_stats(paths, namemeta, verbose)
self._tags = self._get_tags()
def _get_stats(self, paths, namemeta, verbose):
paths = self._glob_paths(paths)
if namemeta:
return [ Statistics(path, namemeta=namemeta, verbose=verbose)
for path in paths ]
return [ Statistics(path, name, verbose=verbose)
for path, name in zip(paths, self._get_names(paths)) ]
def _glob_paths(self, orig):
paths = []
for path in orig:
paths.extend(glob.glob(path))
if not paths:
raise DataError("No valid paths given.")
return paths
def _get_names(self, paths):
paths = [ os.path.splitext(os.path.abspath(p))[0] for p in paths ]
path_tokens = [ p.replace('\\','/').split('/') for p in paths ]
min_tokens = min([ len(t) for t in path_tokens ])
index = -1
while self._tokens_are_same_at_index(path_tokens, index):
index -= 1
if abs(index) > min_tokens:
index = -1
break
names = [ tokens[index] for tokens in path_tokens ]
return [ utils.printable_name(n, code_style=True) for n in names ]
def _tokens_are_same_at_index(self, token_list, index):
first = token_list[0][index]
for tokens in token_list[1:]:
if first != tokens[index]:
return False
return len(token_list) > 1
def _get_tags(self):
stats = {}
for statistics in self._stats:
stats.update(statistics.tags)
return [ stat.name for stat in sorted(stats.values()) ]
def plot(self, plotter):
plotter.set_axis(self._stats)
plotter.critical_tests([ s.critical_tests for s in self._stats ])
plotter.all_tests([ s.all_tests for s in self._stats ])
for tag in self._tags:
plotter.tag([ s[tag] for s in self._stats ])
class Statistics(object):
def __init__(self, path, name=None, namemeta=None, verbose=False):
if verbose:
print path
root = ET.ElementTree(file=path).getroot()
self.name = self._get_name(name, namemeta, root)
stats = root.find('statistics')
crit_node, all_node = list(stats.find('total'))
self.critical_tests = Stat(crit_node)
self.all_tests = Stat(all_node)
self.tags = dict([ (n.text, Stat(n)) for n in stats.find('tag') ])
def _get_name(self, name, namemeta, root):
if namemeta is None:
if name is None:
raise TypeError("Either 'name' or 'namemeta' must be given")
return name
metadata = root.find('suite').find('metadata')
if metadata:
for item in metadata:
if item.get('name','').lower() == namemeta.lower():
return item.text
raise DataError("No metadata matching '%s' found" % namemeta)
def __getitem__(self, name):
try:
return self.tags[name]
except KeyError:
return EmptyStat(name)
class Stat(object):
def __init__(self, node):
self.name = node.text
self.passed = int(node.get('pass'))
self.failed = int(node.get('fail'))
self.total = self.passed + self.failed
self.doc = node.get('doc', '')
info = node.get('info', '')
self.critical = info == 'critical'
self.non_critical = info == 'non-critical'
self.combined = info == 'combined'
def __cmp__(self, other):
if self.critical != other.critical:
return self.critical is True and -1 or 1
if self.non_critical != other.non_critical:
return self.non_critical is True and -1 or 1
if self.combined != other.combined:
return self.combined is True and -1 or 1
return cmp(self.name, other.name)
class EmptyStat(Stat):
def __init__(self, name):
self.name = name
self.passed = self.failed = self.total = 0
self.doc = ''
self.critical = self.non_critical = self.combined = False
class Legend(Line2D):
def __init__(self, **attrs):
styles = {'color': '0.5', 'linestyle': '-', 'linewidth': 1}
styles.update(attrs)
Line2D.__init__(self, [], [], **styles)
class Plotter(object):
_total_color = 'blue'
_pass_color = 'green'
_fail_color = 'red'
_background_color = '0.8'
_xtick_rotation = 20
_default_width = 800
_default_height = 400
_default_font = 8
_default_marker = 5
_default_xticks = 15
_dpi = 100
_marker_symbols = 'o s D ^ v < > d p | + x 1 2 3 4 . ,'.split()
def __init__(self, tags=None, critical=True, all=True, totals=True,
passed=True, failed=True, width=None, height=None, font=None,
marker=None, xticks=None):
self._xtick_limit, self._font_size, self._marker_size, width, height \
= self._get_sizes(xticks, font, marker, width, height)
self._figure = pylab.figure(figsize=(width, height))
self._axes = self._figure.add_axes([0.05, 0.15, 0.65, 0.70])
# axes2 is used only for getting ytick labels also on right side
self._axes2 = self._axes.twinx()
self._axes2.set_xticklabels([], visible=False)
self._tags = self._get_tags(tags)
self._critical = critical
self._all = all
self._totals = totals
self._passed = passed
self._failed = failed
self._legends = []
self._markers = iter(self._marker_symbols)
def _get_sizes(self, xticks, font, marker, width, height):
xticks = xticks or self._default_xticks
font = font or self._default_font
marker = marker or self._default_marker
width = width or self._default_width
height = height or self._default_height
try:
return (int(xticks), int(font), int(marker),
float(width)/self._dpi, float(height)/self._dpi)
except ValueError:
raise DataError('Width, height, font and xticks must be numbers.')
def _get_tags(self, tags):
if tags is None:
return []
return [ t.replace('AND',' & ') for t in tags ]
def set_axis(self, stats):
slen = len(stats)
self._indexes = range(slen)
self._xticks = self._get_xticks(slen, self._xtick_limit)
self._axes.set_xticks(self._xticks)
self._axes.set_xticklabels([ stats[i].name for i in self._xticks ],
rotation=self._xtick_rotation,
size=self._font_size)
self._scale = (slen-1, max([ s.all_tests.total for s in stats ]))
def _get_xticks(self, slen, limit):
if slen <= limit:
return range(slen)
interval, extra = divmod(slen-1, limit-1) # 1 interval less than ticks
if interval < 2:
interval = 2
limit, extra = divmod(slen-1, interval)
limit += 1
return [ self._get_index(i, interval, extra) for i in range(limit) ]
def _get_index(self, count, interval, extra):
if count < extra:
extra = count
return count * interval + extra
def critical_tests(self, stats):
if self._critical:
line = {'linestyle': '--', 'linewidth': 1}
self._plot(self._indexes, stats, **line)
self._legends.append(Legend(label='critical tests', **line))
def all_tests(self, stats):
if self._all:
line = {'linestyle': ':', 'linewidth': 1}
self._plot(self._indexes, stats, **line)
self._legends.append(Legend(label='all tests', **line))
def tag(self, stats):
if utils.matches_any(stats[0].name, self._tags):
line = {'linestyle': '-', 'linewidth': 0.3}
mark = {'marker': self._get_marker(),
'markersize': self._marker_size}
self._plot(self._indexes, stats, **line)
markers = [ stats[index] for index in self._xticks ]
self._plot(self._xticks, markers, linestyle='', **mark)
line.update(mark)
label = self._get_tag_label(stats)
self._legends.append(Legend(label=label, **line))
def _get_tag_label(self, stats):
label = stats[0].name
# need to go through all stats because first can be EmptyStat
for stat in stats:
if stat.critical:
return label + ' (critical)'
if stat.non_critical:
return label + ' (non-critical)'
return label
def _get_marker(self):
try:
return self._markers.next()
except StopIteration:
return ''
def _plot(self, xaxis, stats, **attrs):
total, passed, failed \
= zip(*[ (s.total, s.passed, s.failed) for s in stats ])
if self._totals:
self._axes.plot(xaxis, total, color=self._total_color, **attrs)
if self._passed:
self._axes.plot(xaxis, passed, color=self._pass_color, **attrs)
if self._failed:
self._axes.plot(xaxis, failed, color=self._fail_color, **attrs)
def draw(self, output=None, title=None):
self._set_scale(self._axes)
self._set_scale(self._axes2)
self._set_legends(self._legends[:])
if title:
title = title.replace('_', ' ')
self._axes.set_title(title, fontsize=self._font_size*1.8)
if output:
self._figure.savefig(output, facecolor=self._background_color,
dpi=self._dpi)
else:
if not hasattr(self._figure, 'show'):
raise DataError('Could not find a graphical front-end for '
'Matplotlib.')
self._figure.show()
if title:
figman = get_current_fig_manager()
figman.set_window_title(title)
def _set_scale(self, axes):
width, height = self._scale
axes.axis([-width*0.01, width*1.01, -height*0.04, height*1.04])
def _set_legends(self, legends):
legends.insert(0, Legend(label='Styles:', linestyle=''))
legends.append(Legend(label='', linestyle=''))
legends.append(Legend(label='Colors:', linestyle=''))
if self._totals:
legends.append(Legend(label='total', color=self._total_color))
if self._passed:
legends.append(Legend(label='passed', color=self._pass_color))
if self._failed:
legends.append(Legend(label='failed', color=self._fail_color))
labels = [ l.get_label() for l in legends ]
self._figure.legend(legends, labels, loc='center right',
numpoints=3, borderpad=0.1,
prop=FontProperties(size=self._font_size))
class Ristopy(object):
def __init__(self):
self._arg_parser = utils.ArgumentParser(__doc__, version=__version__)
def main(self, args):
args = self._process_possible_argument_file(args)
try:
opt_groups, paths = self._split_to_option_groups_and_paths(args)
except ValueError:
viewer_open = self._plot_one_graph(args)
else:
viewer_open = self._plot_multiple_graphs(opt_groups, paths)
if viewer_open:
try:
raw_input('Press enter to exit.\n')
except (EOFError, KeyboardInterrupt):
pass
pylab.close('all')
def _plot_one_graph(self, args):
opts, paths = self._arg_parser.parse_args(args, help='help', version='version')
stats = AllStatistics(paths, opts['namemeta'], opts['verbose'])
output = self._plot(stats, opts)
return output is None
def _plot_multiple_graphs(self, opt_groups, paths):
viewer_open = False
stats = AllStatistics(paths, opt_groups[0]['namemeta'],
opt_groups[0]['verbose'])
for opts in opt_groups:
output = self._plot(stats, opts)
viewer_open = output is None or viewer_open
return viewer_open
def _plot(self, stats, opts):
plotter = Plotter(opts['tag'], not opts['nocritical'],
not opts['noall'], not opts['nototals'],
not opts['nopassed'], not opts['nofailed'],
opts['width'], opts['height'], opts['font'],
opts['marker'], opts['xticks'])
stats.plot(plotter)
plotter.draw(opts['output'], opts['title'])
if opts['output']:
print os.path.abspath(opts['output'])
return opts['output']
def _process_possible_argument_file(self, args):
try:
index = args.index('--argumentfile')
except ValueError:
return args
path = args[index+1]
try:
lines = open(path).readlines()
except IOError:
raise DataError("Invalid argument file '%s'" % path)
fargs = []
for line in lines:
line = line.strip()
if line == '' or line.startswith('#'):
continue
elif line.startswith('-'):
fargs.extend(line.split(' ',1))
else:
fargs.append(line)
args[index:index+2] = fargs
return args
def _split_to_option_groups_and_paths(self, args):
opt_groups = []
current = []
for arg in args:
if arg.replace('-','') == '' and len(arg) >= 3:
opts = self._arg_parser.parse_args(current)[0]
opt_groups.append(opts)
current = []
else:
current.append(arg)
if opt_groups:
return opt_groups, current
raise ValueError("Nothing to split")
if __name__ == '__main__':
try:
Ristopy().main(sys.argv[1:])
except Information, msg:
print str(msg)
except DataError, err:
print '%s\n\nTry --help for usage information.' % err
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Diff Tool for Robot Framework Outputs
Usage: robotdiff.py [options] input_files
This script compares two or more Robot Framework output files and creates a
report where possible differences between test case statuses in each file
are highlighted. Main use case is verifying that results from executing same
test cases in different environments are same. For example, it is possible to
test that new Robot Framework version does not affect test results. Another
usage is comparing earlier test results with newer ones to find out possible
status changes and added test cases.
Options:
-r --report file HTML report file (created from the input files).
Default is 'robotdiff.html'.
-n --name name * Name for test run. Different test runs can be named
with this option. However, there must be as many
names as there are input files. By default the name
of the input files are used as names. Input files
having same file name are distinguished by adding
as many parent directories to the names as is needed.
-t --title title Title for the generated diff report. The default
title is 'Diff Report'.
-E --escape what:with * Escape certain characters which are problematic in
console. 'what' is the name of the character to
escape and 'with' is the string to escape it with.
Available character to escape:
<--------------------ESCAPES------------------------>
Example:
--escape space:_ --title My_Fine_Diff_Report
-h -? --help Print this usage instruction.
Options that can be specified multiple times are marked with an asterisk (*).
Examples:
$ robotdiff.py output1.xml output2.xml output3.xml
$ robotdiff.py --name Env1 --name Env2 smoke1.xml smoke2.xml
"""
import os
import sys
from robot import utils
from robot.output import TestSuite
from robot.errors import DataError, Information
def main(args):
opts, paths = _process_args(args)
diff = DiffRobotOutputs(opts['report'], opts['title'])
names = _get_names(opts['name'], paths)
for path, name in zip(paths, names):
try:
diff.add_suite(path, name)
except DataError, err:
exit(error=str(err))
diff.serialize()
print "Report: %s" % diff.close()
def _process_args(cliargs):
ap = utils.ArgumentParser(__doc__, arg_limits=(2, sys.maxint))
try:
opts, paths = ap.parse_args(cliargs, unescape='escape', help='help',
check_args=True)
except Information, msg:
exit(msg=str(msg))
except DataError, err:
exit(error=str(err))
return opts, [ utils.normpath(path) for path in paths ]
def _get_names(names, paths):
if len(names) == 0:
return [None] * len(paths)
if len(names) == len(paths):
return names
exit(error="Different number of names (%d) and inputs (%d)"
% (len(names), len(paths)))
def exit(rc=0, error=None, msg=None):
if error:
print error, "\n\nUse '--help' option to get usage information."
if rc == 0:
rc = 255
if msg:
print msg
rc = 1
sys.exit(rc)
class DiffRobotOutputs:
def __init__(self, outpath=None, title=None):
if outpath is None:
outpath = 'robotdiff.html'
if title is None:
title = 'Diff Report'
self._output = open(utils.normpath(outpath), 'w')
self._writer = utils.HtmlWriter(self._output)
self.title = title
self.column_names = []
self.suites_and_tests = {}
def add_suite(self, path, column_name):
if column_name is None:
column_name = path
column_name = self._get_new_column_name(column_name)
self.column_names.append(column_name)
suite = TestSuite(path)
# Creates links to logs
link = self._get_loglink(path, self._output.name)
self._set_suite_links(suite, link)
self._add_suite(suite, column_name)
def _get_loglink(self, inpath, target):
"""Finds matching log file and return link to it or None."""
indir, infile = os.path.split(inpath)
logname = os.path.splitext(infile.lower())[0]
if logname.endswith('output'):
logname = logname[:-6] + 'log'
for item in os.listdir(indir):
name, ext = os.path.splitext(item.lower())
if name == logname and ext in ['.html','.htm','.xhtml']:
logpath = os.path.join(indir, item)
return utils.get_link_path(logpath, target)
return None
def _set_suite_links(self, suite, link):
suite.link = link
for sub_suite in suite.suites:
self._set_suite_links(sub_suite, link)
for test in suite.tests:
test.link = link
def _get_new_column_name(self, column_name):
if self.column_names.count(column_name) == 0:
return column_name
count = 0
for name in self.column_names:
if name.startswith(column_name):
count += 1
return column_name + '_%d' % (count)
def _add_suite(self, suite, column_name):
self._add_to_dict(suite, column_name)
for sub_suite in suite.suites:
self._add_suite(sub_suite, column_name)
for test in suite.tests:
self._add_to_dict(test, column_name)
def _add_to_dict(self, s_or_t, column_name):
name = s_or_t.longname.replace('_', ' ')
keys = self.suites_and_tests.keys()
found = False
for key in keys:
if utils.normalize(name, caseless=True, spaceless=True) == \
utils.normalize(key, caseless=True, spaceless=True):
found = True
foundkey = key
if not found:
self.suites_and_tests[name] = [(column_name, s_or_t)]
else:
self.suites_and_tests[foundkey].append((column_name, s_or_t))
def serialize(self):
self._write_start()
self._write_headers()
for name, value in self._get_sorted_items(self.suites_and_tests):
self._write_start_of_s_or_t_row(name, value)
for column_name in self.column_names:
#Generates column containg status
s_or_t = self._get_s_or_t_by_column_name(column_name, value)
self._write_s_or_t_status(s_or_t)
self._writer.end('tr', newline=True)
self._writer.end('table', newline=True)
self._write_end()
def close(self):
self._output.close()
return self._output.name
def _write_s_or_t_status(self, s_or_t):
if s_or_t is not None:
self._col_status_content(s_or_t)
else:
col_status = 'col_status not_available'
self._writer.element('td', 'N/A', {'class': col_status})
def _col_status_content(self, s_or_t):
status = s_or_t.status
col_status = 'col_status %s' % status.lower()
self._writer.start('td', {'class': col_status})
if s_or_t.link is not None:
type = self._get_type(s_or_t)
link = '%s#%s_%s' % (s_or_t.link, type, s_or_t.longname)
self._writer.element('a', status, {'class': status.lower(),
'href': link,
'title': s_or_t.longname })
else:
self._writer.content(status)
self._writer.end('td')
def _get_type(self, s_or_t):
if dir(s_or_t).count('tests') == 1:
return 'suite'
else:
return 'test'
def _write_start_of_s_or_t_row(self, name, value):
row_status = self._get_row_status(value)
self._writer.element('th', name, {'class': row_status})
def _get_sorted_items(self, suites_and_tests):
items = suites_and_tests.items()
items.sort(lambda x, y: cmp(x[0], y[0]))
return items
def _get_row_status(self, items):
if len(items) > 0:
status = self._get_status(items[0])
else:
return 'none'
for item in items:
if self._get_status(item) != status:
return 'diff'
return 'all_%s' % (status.lower())
def _get_status(self, item):
return item[1].status
def _get_s_or_t_by_column_name(self, column_name, items):
for item in items:
if column_name == item[0]:
return item[1]
return None
def _write_headers(self):
self._writer.start('table')
self._writer.start('tr')
self._writer.element('th', 'Name', {'class': 'col_name'})
for name in self.column_names:
name = name.replace(self._get_prefix(self.column_names), '')
self._writer.element('th', name, {'class': 'col_status'})
self._writer.end('tr')
def _get_prefix(self, paths):
paths = [os.path.dirname(p) for p in paths ]
dirs = []
for path in paths:
if path.endswith(os.sep):
dirs.append(path)
else:
if path != '' and path[-1] != os.sep:
dirs.append(path + os.sep)
else:
dirs.append(path)
prefix = os.path.commonprefix(dirs)
while len(prefix) > 0:
if prefix.endswith(os.sep):
break
prefix = prefix[:-1]
return prefix
def _write_start(self):
self._output.write(START_HTML)
self._output.write("<title>%s</title>" % (self.title))
self._output.write("</head>\n<body><h1>%s</h1></br>\n" % (self.title))
self._output.write('<div class="spacer"> </div>')
def _write_end(self):
self._writer.end('body')
self._writer.end('html')
START_HTML = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Expires" content="Mon, 20 Jan 2001 20:01:21 GMT" />
<style media="all" type="text/css">
/* Generic Table Styles */
table {
background: white;
border: 1px solid black;
border-collapse: collapse;
empty-cells: show;
margin: 0px 1px;
}
th, td {
border: 1px solid black;
padding: 1px 5px;
}
th {
background: #C6C6C6;
color: black;
}
.diff{
background: red;
}
.all_pass{
background: #00f000;
}
.all_fail{
background: yellow;
}
/* Test by Suite/Tag Tables */
table.tests_by_suite, table.tests_by_tag {
width: 100%;
}
.col_name {
width: 13em;
font-weight: bold;
}
.col_status {
width: 5em;
text-align: center;
}
.pass{
color: #00f000;
}
.fail{
color: red;
}
</style>
<style media="all" type="text/css">
/* Generic styles */
body {
font-family: sans-serif;
font-size: 0.8em;
color: black;
padding: 6px;
}
h2 {
margin-top: 1.2em;
}
/* Misc Styles */
.not_available {
color: gray; /* no grey in IE */
font-weight: normal;
}
a:link, a:visited {
text-decoration: none;
}
a:hover {
text-decoration: underline;
color: purple;
}
/* Headers */
.header {
width: 58em;
margin: 6px 0px;
}
h1 {
margin: 0px;
width: 73%;
float: left;
}
.times {
width: 26%;
float: right;
text-align: right;
}
.generated_time, .generated_ago {
font-size: 0.9em;
}
.spacer {
font-size: 0.8em;
clear: both;
}
</style>
<style media="print" type="text/css">
body {
background: white;
padding: 0px;
font-size: 9pt;
}
a:link, a:visited {
color: black;
}
.header, .failbox, .passbox, table.statistics {
width: 100%;
}
.generated_ago {
display: none;
}
</style>
'''
if __name__ == '__main__':
main(sys.argv[1:])
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""fixml.py -- A tool to fix broken Robot Framework output files
Usage: fixml.py inpath outpath
This tool can fix Robot Framework output files that are not properly finished
or are missing elements from the middle. It should be possible to generate
reports and logs from the fixed output afterwards with the `rebot` tool.
The tool uses BeautifulSoup module which must be installed separately.
See http://www.crummy.com/software/BeautifulSoup for more information.
Additionally, the tool is only compatible with Robot Framework 2.1.3 or newer.
"""
import sys
import os
try:
from BeautifulSoup import BeautifulStoneSoup
except ImportError:
raise ImportError('fixml.py requires BeautifulSoup to be installed: '
'http://www.crummy.com/software/BeautifulSoup/')
class Fixxxer(BeautifulStoneSoup):
NESTABLE_TAGS = {
'suite': ['robot','suite', 'statistics'],
'doc': ['suite', 'test', 'kw'],
'metadata': ['suite'],
'item': ['metadata'],
'status': ['suite', 'test', 'kw'],
'test': ['suite'],
'tags': ['test'],
'tag': ['tags'],
'kw': ['suite', 'test', 'kw'],
'msg': ['kw', 'errors'],
'arguments': ['kw'],
'arg': ['arguments'],
'statistics': ['robot'],
'errors': ['robot'],
}
__close_on_open = None
def unknown_starttag(self, name, attrs, selfClosing=0):
if name == 'robot':
attrs = [ (key, key == 'generator' and 'fixml.py' or value)
for key, value in attrs ]
if name == 'kw' and ('type', 'teardown') in attrs:
while self.tagStack[-1].name not in ['test', 'suite']:
self._popToTag(self.tagStack[-1].name)
if self.__close_on_open:
self._popToTag(self.__close_on_open)
self.__close_on_open = None
BeautifulStoneSoup.unknown_starttag(self, name, attrs, selfClosing)
def unknown_endtag(self, name):
BeautifulStoneSoup.unknown_endtag(self, name)
if name == 'status':
self.__close_on_open = self.tagStack[-1].name
else:
self.__close_on_open = None
def main(inpath, outpath):
outfile = open(outpath, 'w')
outfile.write(str(Fixxxer(open(inpath))))
outfile.close()
return outpath
if __name__ == '__main__':
try:
outpath = main(*sys.argv[1:])
except TypeError:
print __doc__
else:
print os.path.abspath(outpath)
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Test Status Checker
Usage: statuschecker.py infile [outfile]
This tool processes Robot Framework output XML files and checks that test case
statuses and messages are as expected. Main use case is post-processing output
files got when testing Robot Framework test libraries using Robot Framework
itself.
If output file is not given, the input file is considered to be also output
file and it is edited in place.
By default all test cases are expected to 'PASS' and have no message. Changing
the expected status to 'FAIL' is done by having word 'FAIL' (in uppercase)
somewhere in the test case documentation. Expected error message must then be
given after 'FAIL'. Error message can also be specified as a regular
expression by prefixing it with string 'REGEXP:'.
This tool also allows testing the created log messages. They are specified
using a syntax 'LOG x.y:z LEVEL Actual message', which is described in the
tool documentation.
"""
import re
from robot.output import TestSuite
def process_output(inpath, outpath=None):
suite = TestSuite(inpath)
_process_suite(suite)
suite.write_to_file(outpath)
return suite.critical_stats.failed
def _process_suite(suite):
for subsuite in suite.suites:
_process_suite(subsuite)
for test in suite.tests:
_process_test(test)
def _process_test(test):
exp = _Expected(test.doc)
_check_status(test, exp)
if test.status == 'PASS':
_check_logs(test, exp)
def _check_status(test, exp):
if exp.status != test.status:
test.status = 'FAIL'
if exp.status == 'PASS':
test.message = ("Test was expected to PASS but it FAILED. "
"Error message:\n") + test.message
else:
test.message = ("Test was expected to FAIL but it PASSED. "
"Expected message:\n") + exp.message
elif not _message_matches(test.message, exp.message):
test.status = 'FAIL'
test.message = ("Wrong error message.\n\nExpected:\n%s\n\nActual:\n%s\n"
% (exp.message, test.message))
elif test.status == 'FAIL':
test.status = 'PASS'
test.message = 'Original test failed as expected.'
def _message_matches(actual, expected):
if actual == expected:
return True
if expected.startswith('REGEXP:'):
pattern = '^%s$' % expected.replace('REGEXP:', '', 1).strip()
if re.match(pattern, actual, re.DOTALL):
return True
return False
def _check_logs(test, exp):
for kw_indices, msg_index, level, message in exp.logs:
try:
kw = test.keywords[kw_indices[0]]
for index in kw_indices[1:]:
kw = kw.keywords[index]
except IndexError:
indices = '.'.join([ str(i+1) for i in kw_indices ])
test.status = 'FAIL'
test.message = ("Test '%s' does not have keyword with index '%s'"
% (test.name, indices))
return
if len(kw.messages) <= msg_index:
if message != 'NONE':
test.status = 'FAIL'
test.message = ("Keyword '%s' should have had at least %d "
"messages" % (kw.name, msg_index+1))
else:
if _check_log_level(level, test, kw, msg_index):
_check_log_message(message, test, kw, msg_index)
def _check_log_level(expected, test, kw, index):
actual = kw.messages[index].level
if actual == expected:
return True
test.status = 'FAIL'
test.message = ("Wrong level for message %d of keyword '%s'.\n\n"
"Expected: %s\nActual: %s.\n%s"
% (index+1, kw.name, expected, actual, kw.messages[index].message))
return False
def _check_log_message(expected, test, kw, index):
actual = kw.messages[index].message.strip()
if _message_matches(actual, expected):
return True
test.status = 'FAIL'
test.message = ("Wrong content for message %d of keyword '%s'.\n\n"
"Expected:\n%s\n\nActual:\n%s"
% (index+1, kw.name, expected, actual))
return False
class _Expected:
def __init__(self, doc):
self.status, self.message = self._get_status_and_message(doc)
self.logs = self._get_logs(doc)
def _get_status_and_message(self, doc):
if 'FAIL' in doc:
return 'FAIL', doc.split('FAIL', 1)[1].split('LOG', 1)[0].strip()
return 'PASS', ''
def _get_logs(self, doc):
logs = []
for item in doc.split('LOG')[1:]:
index_str, msg_str = item.strip().split(' ', 1)
kw_indices, msg_index = self._get_indices(index_str)
level, message = self._get_log_message(msg_str)
logs.append((kw_indices, msg_index, level, message))
return logs
def _get_indices(self, index_str):
try:
kw_indices, msg_index = index_str.split(':')
except ValueError:
kw_indices, msg_index = index_str, '1'
kw_indices = [ int(index) - 1 for index in kw_indices.split('.') ]
return kw_indices, int(msg_index) - 1
def _get_log_message(self, msg_str):
try:
level, message = msg_str.split(' ', 1)
if level not in ['TRACE', 'DEBUG', 'INFO', 'WARN', 'FAIL']:
raise ValueError
except ValueError:
level, message = 'INFO', msg_str
return level, message
if __name__=='__main__':
import sys
import os
if not 2 <= len(sys.argv) <= 3 or '--help' in sys.argv:
print __doc__
sys.exit(1)
infile = sys.argv[1]
outfile = len(sys.argv) == 3 and sys.argv[2] or None
print "Checking %s" % os.path.abspath(infile)
rc = process_output(infile, outfile)
if outfile:
print "Output %s" % os.path.abspath(outfile)
if rc > 255:
rc = 255
sys.exit(rc)
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Robot Framework Start/End/Elapsed Time Reporter
Usage: times2csv.py input-xml [output-csv] [include-items]
This script reads start, end, and elapsed times from all suites, tests and/or
keywords from the given output file, and writes them into an file in
comma-separated-values (CSV) format. CSV files can then be further processed
with spreadsheet programs. If the CSV output file is not given, its name is
got from the input file by replacing the '.xml' extension with '.csv'.
'include-items' can be used for defining which items to process. Possible
values are 'suite', 'test' and 'keyword', and they can be combined to specify
multiple items e.g. like 'suite-test' or 'test-keyword'.
Examples:
$ times2csv.py output.xml
$ times2csv.py path/results.xml path2/times.csv
$ times2csv.py output.xml times.csv test
$ times2csv.py output.xml times.csv suite-test
"""
import sys
import os
import csv
from robot.output import TestSuite
from robot import utils
def process_file(inpath, outpath, items):
suite = TestSuite(inpath)
outfile = open(outpath, 'wb')
writer = csv.writer(outfile)
writer.writerow(['TYPE','NAME','STATUS','START','END','ELAPSED','ELAPSED SECS'])
process_suite(suite, writer, items.lower())
outfile.close()
def process_suite(suite, writer, items, level=0):
if 'suite' in items:
process_item(suite, writer, level, 'Suite')
if 'keyword' in items:
for kw in suite.setup, suite.teardown:
process_keyword(kw, writer, level+1)
for subsuite in suite.suites:
process_suite(subsuite, writer, items, level+1)
for test in suite.tests:
process_test(test, writer, items, level+1)
def process_test(test, writer, items, level):
if 'test' in items:
process_item(test, writer, level, 'Test', 'suite' not in items)
if 'keyword' in items:
for kw in [test.setup] + test.keywords + [test.teardown]:
process_keyword(kw, writer, level+1)
def process_keyword(kw, writer, level):
if kw is None:
return
if kw.type in ['kw', 'set', 'repeat']:
kw_type = 'Keyword'
else:
kw_type = kw.type.capitalize()
process_item(kw, writer, level, kw_type)
for subkw in kw.keywords:
process_keyword(subkw, writer, level+1)
def process_item(item, writer, level, item_type, long_name=False):
if level == 0:
indent = ''
else:
indent = '| ' * (level-1) + '|- '
if long_name:
name = item.longname
else:
name = item.name
writer.writerow([indent+item_type, name, item.status, item.starttime,
item.endtime, utils.elapsed_time_to_string(item.elapsedtime),
item.elapsedtime/1000.0])
if __name__ == '__main__':
if not (2 <= len(sys.argv) <= 4) or '--help' in sys.argv:
print __doc__
sys.exit(1)
inxml = sys.argv[1]
try:
outcsv = sys.argv[2]
except IndexError:
outcsv = os.path.splitext(inxml)[0] + '.csv'
try:
items = sys.argv[3]
except IndexError:
items = 'suite-test-keyword'
process_file(inxml, outcsv, items)
print os.path.abspath(outcsv)
| Python |
#!/usr/bin/env python
"""Packaging script for Robot Framework
Usage: package.py command version_number [release_tag]
Argument 'command' can have one of the following values:
- sdist : create source distribution
- wininst : create Windows installer
- all : create both packages
- version : update only version information in 'src/robot/version.py'
- jar : create stand-alone jar file containing RF and Jython
'version_number' must be a version number in format '2.x(.y)', 'trunk' or
'keep'. With 'keep', version information is not updated.
'release_tag' must be either 'alpha', 'beta', 'rc' or 'final', where all but
the last one can have a number after the name like 'alpha1' or 'rc2'. When
'version_number' is 'trunk', 'release_tag' is automatically assigned to the
current date.
When creating the jar distribution, jython.jar must be placed in 'ext-lib'
directory, under the project root.
This script uses 'setup.py' internally. Distribution packages are created
under 'dist' directory, which is deleted initially. Depending on your system,
you may need to run this script with administrative rights (e.g. with 'sudo').
Examples:
package.py sdist 2.0 final
package.py wininst keep
package.py all 2.1.13 alpha
package.py sdist trunk
package.py version trunk
"""
import sys
import os
from os.path import abspath, dirname, exists, join
import shutil
import re
import time
import subprocess
import zipfile
from glob import glob
ROOT_PATH = abspath(dirname(__file__))
DIST_PATH = join(ROOT_PATH, 'dist')
BUILD_PATH = join(ROOT_PATH, 'build')
ROBOT_PATH = join(ROOT_PATH, 'src', 'robot')
JAVA_SRC = join(ROOT_PATH, 'src', 'java', 'org', 'robotframework')
JYTHON_JAR = glob(join(ROOT_PATH, 'ext-lib', 'jython-standalone-*.jar'))[0]
SETUP_PATH = join(ROOT_PATH, 'setup.py')
VERSION_PATH = join(ROBOT_PATH, 'version.py')
VERSIONS = [re.compile('^2\.\d+(\.\d+)?$'), 'trunk', 'keep']
RELEASES = [re.compile('^alpha\d*$'), re.compile('^beta\d*$'),
re.compile('^rc\d*$'), 'final']
VERSION_CONTENT = """# Automatically generated by 'package.py' script.
import sys
VERSION = '%(version_number)s'
RELEASE = '%(release_tag)s'
TIMESTAMP = '%(timestamp)s'
def get_version(sep=' '):
if RELEASE == 'final':
return VERSION
return VERSION + sep + RELEASE
def get_full_version(who=''):
sys_version = sys.version.split()[0]
version = '%%s %%s (%%s %%s on %%s)' \\
%% (who, get_version(), _get_interpreter(), sys_version, sys.platform)
return version.strip()
def _get_interpreter():
if sys.platform.startswith('java'):
return 'Jython'
if sys.platform == 'cli':
return 'IronPython'
return 'Python'
"""
def sdist(*version_info):
version(*version_info)
_clean()
_create_sdist()
_announce()
def wininst(*version_info):
version(*version_info)
_clean()
if _verify_platform(*version_info):
_create_wininst()
_announce()
def all(*version_info):
version(*version_info)
_clean()
_create_sdist()
if _verify_platform(*version_info):
_create_wininst()
_announce()
def version(version_number, release_tag=None):
_verify_version(version_number, VERSIONS)
if version_number == 'keep':
_keep_version()
elif version_number =='trunk':
_update_version(version_number, '%d%02d%02d' % time.localtime()[:3])
else:
_update_version(version_number, _verify_version(release_tag, RELEASES))
sys.path.insert(0, ROBOT_PATH)
from version import get_version
return get_version(sep='-')
def _verify_version(given, valid):
for item in valid:
if given == item or (hasattr(item, 'search') and item.search(given)):
return given
raise ValueError
def _update_version(version_number, release_tag):
timestamp = '%d%02d%02d-%02d%02d%02d' % time.localtime()[:6]
vfile = open(VERSION_PATH, 'wb')
vfile.write(VERSION_CONTENT % locals())
vfile.close()
print 'Updated version to %s %s' % (version_number, release_tag)
def _keep_version():
sys.path.insert(0, ROBOT_PATH)
from version import get_version
print 'Keeping version %s' % get_version()
def _clean():
print 'Cleaning up...'
for path in [DIST_PATH, BUILD_PATH]:
if exists(path):
shutil.rmtree(path)
def _verify_platform(version_number, release_tag=None):
if release_tag == 'final' and os.sep != '\\':
print 'Final Windows installers can only be created in Windows.'
print 'Windows installer was not created.'
return False
return True
def _create_sdist():
_create('sdist', 'source distribution')
def _create_wininst():
_create('bdist_wininst', 'Windows installer')
if os.sep != '\\':
print 'Warning: Windows installers created on other platforms may not'
print 'be exactly identical to ones created in Windows.'
def _create(command, name):
print 'Creating %s...' % name
rc = os.system('%s %s %s' % (sys.executable, SETUP_PATH, command))
if rc != 0:
print 'Creating %s failed.' % name
sys.exit(rc)
print '%s created successfully.' % name.capitalize()
def _announce():
print 'Created:'
for path in os.listdir(DIST_PATH):
print abspath(join(DIST_PATH, path))
def jar(*version_info):
ver = version(*version_info)
tmpdir = _create_tmpdir()
_compile_java_classes(tmpdir)
_unzip_jython_jar(tmpdir)
_copy_robot_files(tmpdir)
_compile_all_py_files(tmpdir)
_overwrite_manifest(tmpdir, ver)
jar_path = _create_jar_file(tmpdir, ver)
shutil.rmtree(tmpdir)
print 'Created %s based on %s' % (jar_path, JYTHON_JAR)
def _compile_java_classes(tmpdir):
source_files = [join(JAVA_SRC, f)
for f in os.listdir(JAVA_SRC) if f.endswith('.java')]
print 'Compiling %d source files' % len(source_files)
subprocess.call(['javac', '-d', tmpdir, '-target', '1.5', '-cp', JYTHON_JAR]
+ source_files)
def _create_tmpdir():
tmpdir = join(ROOT_PATH, 'tmp-jar-dir')
if exists(tmpdir):
shutil.rmtree(tmpdir)
os.mkdir(tmpdir)
return tmpdir
def _unzip_jython_jar(tmpdir):
zipfile.ZipFile(JYTHON_JAR).extractall(tmpdir)
def _copy_robot_files(tmpdir):
# pyc files must be excluded so that compileall works properly.
todir = join(tmpdir, 'Lib', 'robot')
shutil.copytree(ROBOT_PATH, todir, ignore=shutil.ignore_patterns('*.pyc*'))
def _compile_all_py_files(tmpdir):
subprocess.call(['java', '-jar', JYTHON_JAR, '-m', 'compileall', tmpdir])
# Jython will not work without its py-files, but robot will
for root, _, files in os.walk(join(tmpdir,'Lib','robot')):
for f in files:
if f.endswith('.py'):
os.remove(join(root, f))
def _overwrite_manifest(tmpdir, version):
with open(join(tmpdir, 'META-INF', 'MANIFEST.MF'), 'w') as mf:
mf.write('''Manifest-Version: 1.0
Main-Class: org.robotframework.RobotFramework
Specification-Version: 2
Implementation-Version: %s
''' % version)
def _create_jar_file(source, version):
path = join(DIST_PATH, 'robotframework-%s.jar' % version)
if not exists(DIST_PATH):
os.mkdir(DIST_PATH)
_fill_jar(source, path)
return path
def _fill_jar(sourcedir, jarpath):
subprocess.call(['jar', 'cvfM', jarpath, '.'], cwd=sourcedir)
if __name__ == '__main__':
try:
globals()[sys.argv[1]](*sys.argv[2:])
except (KeyError, IndexError, TypeError, ValueError):
print __doc__
| Python |
#!/usr/bin/env python
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Install script for Robot Framework source distributions.
Usage: python install.py [ in(stall) | un(install) | re(install) ]
Using 'python install.py install' simply runs 'python setup.py install'
internally. You need to use 'setup.py' directly, if you want to alter the
default installation somehow.
See 'INSTALL.txt' or Robot Framework User Guide for more information.
"""
import glob
import os
import shutil
import sys
def install():
_remove(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'build'))
print 'Installing Robot Framework...'
setup = os.path.join(os.path.dirname(sys.argv[0]), 'setup.py')
rc = os.system('"%s" %s install' % (sys.executable, setup))
if rc != 0:
print 'Installation failed.'
sys.exit(rc)
print 'Installation was successful.'
def uninstall():
print 'Uninstalling Robot Framework...'
try:
instdir = _get_installation_directory()
except Exception:
print 'Robot Framework is not installed or the installation is corrupted.'
sys.exit(1)
_remove(instdir)
if not 'robotframework' in instdir:
_remove_egg_info(instdir)
_remove_runners()
print 'Uninstallation was successful.'
def reinstall():
uninstall()
install()
def _get_installation_directory():
import robot
# Ensure we got correct robot module
if 'Robot' not in robot.pythonpathsetter.__doc__:
raise TypeError
robot_dir = os.path.dirname(robot.__file__)
parent_dir = os.path.dirname(robot_dir)
if 'robotframework' in os.path.basename(parent_dir):
return parent_dir
return robot_dir
def _remove_runners():
runners = ['pybot', 'jybot', 'rebot']
if os.name == 'java':
runners.remove('pybot')
if os.sep == '\\':
runners = [r + '.bat' for r in runners]
for name in runners:
if os.name == 'java':
_remove(os.path.join(sys.prefix, 'bin', name))
elif os.sep == '\\':
_remove(os.path.join(sys.prefix, 'Scripts', name))
else:
for dirpath in ['/bin', '/usr/bin/', '/usr/local/bin']:
_remove(os.path.join(dirpath, name))
def _remove_egg_info(instdir):
pattern = os.path.join(os.path.dirname(instdir), 'robotframework-*.egg-info')
for path in glob.glob(pattern):
_remove(path)
def _remove(path):
if not os.path.exists(path):
return
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except Exception, err:
print "Removing '%s' failed: %s" % (path, err)
else:
print "Removed '%s'" % path
if __name__ == '__main__':
actions = { 'install': install, 'in': install,
'uninstall': uninstall, 'un': uninstall,
'reinstall': reinstall, 're': reinstall }
try:
actions[sys.argv[1]]()
except (KeyError, IndexError):
print __doc__
| Python |
#!/usr/bin/env python
import sys
import os
from distutils.core import setup
import robot_postinstall
execfile(os.path.join(os.path.dirname(__file__),'src','robot','version.py'))
# Maximum width in Windows installer seems to be 70 characters -------|
DESCRIPTION = """
Robot Framework is a generic test automation framework for acceptance
testing and acceptance test-driven development (ATDD). It has
easy-to-use tabular test data syntax and utilizes the keyword-driven
testing approach. Its testing capabilities can be extended by test
libraries implemented either with Python or Java, and users can create
new keywords from existing ones using the same syntax that is used for
creating test cases.
"""[1:-1]
CLASSIFIERS = """
Development Status :: 5 - Production/Stable
License :: OSI Approved :: Apache Software License
Operating System :: OS Independent
Programming Language :: Python
Topic :: Software Development :: Testing
"""[1:-1]
PACKAGES = ['robot', 'robot.api', 'robot.common', 'robot.conf',
'robot.libraries', 'robot.output', 'robot.parsing',
'robot.result', 'robot.running', 'robot.utils',
'robot.variables']
SCRIPT_NAMES = ['pybot', 'jybot', 'rebot']
if os.name == 'java':
SCRIPT_NAMES.remove('pybot')
def main():
inst_scripts = [ os.path.join('src','bin',name) for name in SCRIPT_NAMES ]
if 'bdist_wininst' in sys.argv:
inst_scripts = [ script+'.bat' for script in inst_scripts ]
inst_scripts.append('robot_postinstall.py')
elif os.sep == '\\':
inst_scripts = [ script+'.bat' for script in inst_scripts ]
if 'bdist_egg' in sys.argv:
package_path = os.path.dirname(sys.argv[0])
robot_postinstall.egg_preinstall(package_path, inst_scripts)
# Let distutils take care of most of the setup
dist = setup(
name = 'robotframework',
version = get_version(sep='-'),
author = 'Robot Framework Developers',
author_email = 'robotframework-devel@googlegroups.com',
url = 'http://robotframework.org',
license = 'Apache License 2.0',
description = 'A generic test automation framework',
long_description = DESCRIPTION,
keywords = 'robotframework testing testautomation atdd',
platforms = 'any',
classifiers = CLASSIFIERS.splitlines(),
package_dir = {'': 'src'},
package_data = {'robot': ['webcontent/*.html', 'webcontent/*.css', 'webcontent/*js', 'webcontent/lib/*.js']},
packages = PACKAGES,
scripts = inst_scripts,
)
if 'install' in sys.argv:
absnorm = lambda path: os.path.abspath(os.path.normpath(path))
script_dir = absnorm(dist.command_obj['install_scripts'].install_dir)
module_dir = absnorm(dist.command_obj['install_lib'].install_dir)
robot_dir = os.path.join(module_dir, 'robot')
script_names = [ os.path.basename(name) for name in inst_scripts ]
robot_postinstall.generic_install(script_names, script_dir, robot_dir)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
import fileinput
import os
import sys
import robot
from robot.result.jsparser import create_datamodel_from
BASEDIR = os.path.dirname(__file__)
def run_robot(outputdirectory, testdata, loglevel='INFO'):
robot.run(testdata, log='NONE', report='NONE',
tagstatlink=['force:http://google.com:<kuukkeli>',
'i*:http://%1/:Title of i%1'],
tagdoc=['test:this_is_*my_bold*_test',
'IX:*Combined* & escaped << tag doc'],
tagstatcombine=['fooANDi*:zap', 'i?:IX'],
critical=[], noncritical=[], outputdir=outputdirectory, loglevel=loglevel)
def create_jsdata(output_xml_file, target):
model = create_datamodel_from(output_xml_file)
model.set_settings({'logURL': 'log.html',
'reportURL': 'report.html',
'background': {'fail': 'DeepPink'}})
with open(target, 'w') as output:
model.write_to(output)
def replace_all(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
def create(input, target, targetName, loglevel='INFO'):
run_robot(BASEDIR, input, loglevel)
create_jsdata('output.xml', target)
replace_all(target, 'window.output', 'window.' + targetName)
if __name__ == '__main__':
create('Suite.txt', 'Suite.js', 'suiteOutput')
create('SetupsAndTeardowns.txt', 'SetupsAndTeardowns.js', 'setupsAndTeardownsOutput')
create('Messages.txt', 'Messages.js', 'messagesOutput')
create('teardownFailure', 'TeardownFailure.js', 'teardownFailureOutput')
create(os.path.join('teardownFailure', 'PassingFailing.txt'), 'PassingFailing.js', 'passingFailingOutput')
create('TestsAndKeywords.txt', 'TestsAndKeywords.js', 'testsAndKeywordsOutput')
create('.', 'allData.js', 'allDataOutput')
| Python |
#!/usr/bin/env python
"""Helper script to run all Robot Framework's unit tests.
usage: run_utest.py [options]
options:
-q, --quiet Minimal output
-v, --verbose Verbose output
-d, --doc Show test's doc string instead of name and class
(implies verbosity)
-h, --help Show help
"""
import unittest
import os
import sys
import re
import getopt
base = os.path.abspath(os.path.normpath(os.path.split(sys.argv[0])[0]))
for path in [ "../src", "../src/robot/libraries", "../src/robot",
"../atest/testresources/testlibs" ]:
path = os.path.join(base, path.replace('/', os.sep))
if path not in sys.path:
sys.path.insert(0, path)
testfile = re.compile("^test_.*\.py$", re.IGNORECASE)
def get_tests(directory=None):
if directory is None:
directory = base
sys.path.append(directory)
tests = []
modules = []
for name in os.listdir(directory):
if name.startswith("."): continue
fullname = os.path.join(directory, name)
if os.path.isdir(fullname):
tests.extend(get_tests(fullname))
elif testfile.match(name):
modname = os.path.splitext(name)[0]
modules.append(__import__(modname))
tests.extend([ unittest.defaultTestLoader.loadTestsFromModule(module)
for module in modules ])
return tests
def parse_args(argv):
docs = 0
verbosity = 1
try:
options, args = getopt.getopt(argv, 'hH?vqd',
['help','verbose','quiet','doc'])
if len(args) != 0:
raise getopt.error, 'no arguments accepted, got %s' % (args)
except getopt.error, err:
usage_exit(err)
for opt, value in options:
if opt in ('-h','-H','-?','--help'):
usage_exit()
if opt in ('-q','--quit'):
verbosity = 0
if opt in ('-v', '--verbose'):
verbosity = 2
if opt in ('-d', '--doc'):
docs = 1
verbosity = 2
return docs, verbosity
def usage_exit(msg=None):
print __doc__
if msg is None:
rc = 251
else:
print '\nError:', msg
rc = 252
sys.exit(rc)
if __name__ == '__main__':
docs, vrbst = parse_args(sys.argv[1:])
tests = get_tests()
suite = unittest.TestSuite(tests)
runner = unittest.TextTestRunner(descriptions=docs, verbosity=vrbst)
result = runner.run(suite)
rc = len(result.failures) + len(result.errors)
if rc > 250: rc = 250
sys.exit(rc)
| Python |
import os
THIS_PATH = os.path.dirname(__file__)
GOLDEN_OUTPUT = os.path.join(THIS_PATH, 'golden_suite', 'output.xml')
GOLDEN_OUTPUT2 = os.path.join(THIS_PATH, 'golden_suite', 'output2.xml')
GOLDEN_JS = os.path.join(THIS_PATH, 'golden_suite', 'expected.js')
| Python |
import os, time
class MyException(Exception):
pass
def passing(*args):
pass
def sleeping(s):
time.sleep(s)
os.environ['ROBOT_THREAD_TESTING'] = str(s)
return s
def returning(arg):
return arg
def failing(msg='xxx'):
raise MyException, msg
if os.name == 'java':
from java.lang import Error
def java_failing(msg='zzz'):
raise Error(msg)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Public logging API for test libraries.
This module provides a public API for writing messages to the log file
and the console. Test libraries can use this API like `logger.info('My
message')` instead of logging through the standard output like `print
'*INFO* My message'`. In addition to a programmatic interface being
cleaner to use, this API has a benefit that the log messages have
accurate timestamps.
Log levels
----------
It is possible to log messages using levels `TRACE`, `DEBUG`, `INFO`
and `WARN` either using the `write` method or, more commonly, with the
log level specific `trace`, `debug`, `info` and `warn` methods.
By default the trace and debug messages are not logged but that can be
changed with the `--loglevel` command line option. Warnings are
automatically written also to the `Test Execution Errors` section in
the log file and to the console.
Logging HTML
------------
All methods that are used for writing messages to the log file have an
optional `html` argument. If a message to be logged is supposed to be
shown as HTML, this argument should be set to `True`.
Example
-------
from robot.api import logger
def my_keyword(arg):
logger.debug('Got argument %s' % arg)
do_something()
logger.info('<i>This</i> is a boring example', html=True)
"""
import sys
from robot.output import LOGGER, Message
def write(msg, level, html=False):
"""Writes the message to the log file using the given level.
Valid log levels are `TRACE`, `DEBUG`, `INFO` and `WARN`. Instead
of using this method, it is generally better to use the level
specific methods such as `info` and `debug`.
"""
LOGGER.log_message(Message(msg, level, html))
def trace(msg, html=False):
"""Writes the message to the log file with the TRACE level."""
write(msg, 'TRACE', html)
def debug(msg, html=False):
"""Writes the message to the log file with the DEBUG level."""
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
"""Writes the message to the log file with the INFO level.
If `also_console` argument is set to `True`, the message is written
both to the log file and to the console.
"""
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
"""Writes the message to the log file with the WARN level."""
write(msg, 'WARN', html)
def console(msg, newline=True):
"""Writes the message to the console.
If the `newline` argument is `True`, a newline character is automatically
added to the message.
"""
if newline:
msg += '\n'
sys.__stdout__.write(msg)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""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.
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 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.
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 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.
import os
from robot import utils
from robot.errors import DataError, FrameworkError
from robot.output import LOGGER
class _BaseSettings(object):
_cli_opts = {'Name' : ('name', None),
'Doc' : ('doc', None),
'Metadata' : ('metadata', []),
'TestNames' : ('test', []),
'SuiteNames' : ('suite', []),
'SetTag' : ('settag', []),
'Include' : ('include', []),
'Exclude' : ('exclude', []),
'Critical' : ('critical', None),
'NonCritical' : ('noncritical', None),
'OutputDir' : ('outputdir', '.'),
'Log' : ('log', 'log.html'),
'Report' : ('report', 'report.html'),
'Summary' : ('summary', 'NONE'),
'XUnitFile' : ('xunitfile', 'NONE'),
'SplitOutputs' : ('splitoutputs', -1),
'TimestampOutputs' : ('timestampoutputs', False),
'LogTitle' : ('logtitle', None),
'ReportTitle' : ('reporttitle', None),
'SummaryTitle' : ('summarytitle', None),
'ReportBackground' : ('reportbackground', None),
'SuiteStatLevel' : ('suitestatlevel', -1),
'TagStatInclude' : ('tagstatinclude', []),
'TagStatExclude' : ('tagstatexclude', []),
'TagStatCombine' : ('tagstatcombine', []),
'TagDoc' : ('tagdoc', []),
'TagStatLink' : ('tagstatlink', []),
'NoStatusRC' : ('nostatusrc', False),
'RunEmptySuite' : ('runemptysuite', False),
'MonitorWidth' : ('monitorwidth', 78),
'MonitorColors' : ('monitorcolors', 'AUTO')}
_output_opts = ['Output', 'Log', 'Report', 'Summary', 'DebugFile', 'XUnitFile']
def __init__(self, options={}, log=True):
self._opts = {}
self._cli_opts.update(self._extra_cli_opts)
self._process_cli_opts(options, log)
if log: LOGGER.info('Settings:\n%s' % unicode(self))
def _process_cli_opts(self, opts, log):
for name, (cli_name, default) in self._cli_opts.items():
try:
value = opts[cli_name]
if value in [None, []]:
raise KeyError
except KeyError:
value = default
self[name] = self._process_value(name, value, log)
def __setitem__(self, name, value):
if name not in self._cli_opts:
raise KeyError("Non-existing settings '%s'" % name)
self._opts[name] = value
def _process_value(self, name, value, log):
if value in [None, []]:
return value
if name in ['Name', 'Doc', 'LogTitle', 'ReportTitle', 'SummaryTitle']:
if name == 'Doc': value = self._escape(value)
return value.replace('_', ' ')
if name in ['Metadata', 'TagDoc']:
if name == 'Metadata': value = [self._escape(v) for v in value]
return [self._process_metadata_or_tagdoc(v) for v in value]
if name in ['Include', 'Exclude']:
return [v.replace('AND', '&').replace('_', ' ') for v in value]
if name in self._output_opts and utils.eq(value, 'NONE'):
return 'NONE'
if name == 'OutputDir':
return utils.abspath(value)
if name in ['SuiteStatLevel', 'MonitorWidth']:
return self._convert_to_positive_integer_or_default(name, value)
if name in ['Listeners', 'VariableFiles']:
return [self._split_args_from_name(item) for item in value]
if name == 'TagStatCombine':
return [self._process_tag_stat_combine(v) for v in value]
if name == 'TagStatLink':
return [v for v in [self._process_tag_stat_link(v) for v in value] if v]
if name == 'RemoveKeywords':
return value.upper()
if name == 'SplitOutputs' and value != -1:
if log:
LOGGER.warn('Splitting outputs (--SplitOutputs option) is not '
'supported in Robot Framework 2.6 or newer. This '
'option will be removed altogether in version 2.7.')
return -1
return value
def __getitem__(self, name):
if name not in self._cli_opts:
raise KeyError("Non-existing setting '%s'" % name)
if name in self._output_opts:
return self._get_output_file(name)
return self._opts[name]
def _get_output_file(self, type_):
"""Returns path of the requested output file and creates needed dirs.
`type_` can be 'Output', 'Log', 'Report', 'Summary', 'DebugFile'
or 'XUnitFile'.
"""
name = self._opts[type_]
if self._outputfile_disabled(type_, name):
return 'NONE'
name = self._process_output_name(name, type_)
path = utils.abspath(os.path.join(self['OutputDir'], name))
self._create_output_dir(os.path.dirname(path), type_)
return path
def _process_output_name(self, name, type_):
base, ext = os.path.splitext(name)
if self['TimestampOutputs']:
base = '%s-%s' % (base, utils.get_start_timestamp('', '-', ''))
ext = self._get_output_extension(ext, type_)
return base + ext
def _get_output_extension(self, ext, type_):
if ext != '':
return ext
if type_ in ['Output', 'XUnitFile']:
return '.xml'
if type_ in ['Log', 'Report', 'Summary']:
return '.html'
if type_ == 'DebugFile':
return '.txt'
raise FrameworkError("Invalid output file type: %s" % type_)
def _create_output_dir(self, path, type_):
try:
if not os.path.exists(path):
os.makedirs(path)
except:
raise DataError("Can't create %s file's parent directory '%s': %s"
% (type_.lower(), path, utils.get_error_message()))
def _process_metadata_or_tagdoc(self, value):
value = value.replace('_', ' ')
if ':' in value:
return value.split(':', 1)
return value, ''
def _process_tag_stat_combine(self, value):
for replwhat, replwith in [('_', ' '), ('AND', '&'),
('&', ' & '), ('NOT', ' NOT ')]:
value = value.replace(replwhat, replwith)
if ':' in value:
return value.rsplit(':', 1)
return value, ''
def _process_tag_stat_link(self, value):
tokens = value.split(':')
if len(tokens) >= 3:
return tokens[0], ':'.join(tokens[1:-1]), tokens[-1]
LOGGER.error("Invalid format for option '--tagstatlink'. "
"Expected 'tag:link:title' but got '%s'." % value)
return None
def _convert_to_positive_integer_or_default(self, name, value):
value = self._convert_to_integer(name, value)
return value if value > 0 else self._get_default_value(name)
def _convert_to_integer(self, name, value):
try:
return int(value)
except ValueError:
LOGGER.error("Option '--%s' expected integer value but got '%s'. "
"Default value used instead." % (name.lower(), value))
return self._get_default_value(name)
def _get_default_value(self, name):
return self._cli_opts[name][1]
def _split_args_from_name(self, name):
if ':' not in name or os.path.exists(name):
return name, []
args = name.split(':')
name = args.pop(0)
# Handle absolute Windows paths with arguments
if len(name) == 1 and args[0].startswith(('/', '\\')):
name = name + ':' + args.pop(0)
return name, args
def __contains__(self, setting):
return setting in self._cli_opts
def __unicode__(self):
return '\n'.join('%s: %s' % (name, self._opts[name])
for name in sorted(self._opts))
class RobotSettings(_BaseSettings):
_extra_cli_opts = {'Output' : ('output', 'output.xml'),
'LogLevel' : ('loglevel', 'INFO'),
'RunMode' : ('runmode', []),
'WarnOnSkipped' : ('warnonskippedfiles', False),
'Variables' : ('variable', []),
'VariableFiles' : ('variablefile', []),
'Listeners' : ('listener', []),
'DebugFile' : ('debugfile', 'NONE')}
def is_rebot_needed(self):
return not ('NONE' == self['Log'] == self['Report'] == self['Summary'] == self['XUnitFile'])
def get_rebot_datasource_and_settings(self):
datasource = self['Output']
settings = RebotSettings(log=False)
settings._opts.update(self._opts)
for name in ['Variables', 'VariableFiles', 'Listeners']:
del(settings._opts[name])
for name in ['Include', 'Exclude', 'TestNames', 'SuiteNames', 'Metadata']:
settings._opts[name] = []
for name in ['Output', 'RemoveKeywords']:
settings._opts[name] = 'NONE'
for name in ['Name', 'Doc']:
settings._opts[name] = None
settings._opts['LogLevel'] = 'TRACE'
return datasource, settings
def _outputfile_disabled(self, type_, name):
if name == 'NONE':
return True
return self._opts['Output'] == 'NONE' and type_ != 'DebugFile'
def _escape(self, value):
return utils.escape(value)
class RebotSettings(_BaseSettings):
_extra_cli_opts = {'Output' : ('output', 'NONE'),
'LogLevel' : ('loglevel', 'TRACE'),
'RemoveKeywords' : ('removekeywords', 'NONE'),
'StartTime' : ('starttime', 'N/A'),
'EndTime' : ('endtime', 'N/A')}
def _outputfile_disabled(self, type_, name):
return name == 'NONE'
def _escape(self, value):
return value
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from settings import RobotSettings, RebotSettings
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class _Setting(object):
def __init__(self, setting_name, parent=None, comment=None):
self.setting_name = setting_name
self.parent = parent
self.comment = comment
self.reset()
def reset(self):
self.value = []
@property
def source(self):
return self.parent.source if self.parent else None
@property
def directory(self):
return self.parent.directory if self.parent else None
def populate(self, value, comment=None):
"""Mainly used at parsing time, later attributes can be set directly."""
self._populate(value)
self.comment = comment
def _populate(self, value):
self.value = value
def is_set(self):
return bool(self.value)
def is_for_loop(self):
return False
def report_invalid_syntax(self, message, level='ERROR'):
self.parent.report_invalid_syntax(message, level)
def _string_value(self, value):
return value if isinstance(value, basestring) else ' '.join(value)
def _concat_string_with_value(self, string, value):
if string:
return string + ' ' + self._string_value(value)
return self._string_value(value)
def as_list(self):
ret = self._data_as_list()
if self.comment:
ret.append('# %s' % self.comment)
return ret
def _data_as_list(self):
ret = [self.setting_name]
if self.value:
ret.extend(self.value)
return ret
class Documentation(_Setting):
def reset(self):
self.value = ''
def _populate(self, value):
self.value = self._concat_string_with_value(self.value, value)
def _data_as_list(self):
return [self.setting_name, self.value]
class Template(_Setting):
def reset(self):
self.value = None
def _populate(self, value):
self.value = self._concat_string_with_value(self.value, value)
def is_set(self):
return self.value is not None
def _data_as_list(self):
ret = [self.setting_name]
if self.value:
ret.append(self.value)
return ret
class Fixture(_Setting):
def reset(self):
self.name = None
self.args = []
def _populate(self, value):
if not self.name:
self.name = value[0] if value else ''
value = value[1:]
self.args.extend(value)
def is_set(self):
return self.name is not None
def _data_as_list(self):
ret = [self.setting_name]
if self.name or self.args:
ret.append(self.name or '')
if self.args:
ret.extend(self.args)
return ret
class Timeout(_Setting):
def reset(self):
self.value = None
self.message = ''
def _populate(self, value):
if not self.value:
self.value = value[0] if value else ''
value = value[1:]
self.message = self._concat_string_with_value(self.message, value)
def is_set(self):
return self.value is not None
def _data_as_list(self):
ret = [self.setting_name]
if self.value or self.message:
ret.append(self.value or '')
if self.message:
ret.append(self.message)
return ret
class Tags(_Setting):
def reset(self):
self.value = None
def _populate(self, value):
self.value = (self.value or []) + value
def is_set(self):
return self.value is not None
def __add__(self, other):
if not isinstance(other, Tags):
raise TypeError('Tags can only be added with tags')
tags = Tags('Tags')
tags.value = (self.value or []) + (other.value or [])
return tags
class Arguments(_Setting):
pass
class Return(_Setting):
pass
class Metadata(_Setting):
def __init__(self, setting_name, parent, name, value, comment=None):
self.setting_name = setting_name
self.parent = parent
self.name = name
self.value = self._string_value(value)
self.comment = comment
def is_set(self):
return True
def _data_as_list(self):
return [self.setting_name, self.name, self.value]
class _Import(_Setting):
def __init__(self, parent, name, args=None, alias=None, comment=None):
self.parent = parent
self.name = name
self.args = args or []
self.alias = alias
self.comment = comment
@property
def type(self):
return type(self).__name__
def is_set(self):
return True
def _data_as_list(self):
return [self.type, self.name] + self.args
class Library(_Import):
def __init__(self, parent, name, args=None, alias=None, comment=None):
if args and not alias:
args, alias = self._split_alias(args)
_Import.__init__(self, parent, name, args, alias, comment)
def _split_alias(self, args):
if len(args) >= 2 and args[-2].upper() == 'WITH NAME':
return args[:-2], args[-1]
return args, None
def _data_as_list(self):
alias = ['WITH NAME', self.alias] if self.alias else []
return ['Library', self.name] + self.args + alias
class Resource(_Import):
def __init__(self, parent, name, invalid_args=None, comment=None):
if invalid_args:
name += ' ' + ' '.join(invalid_args)
_Import.__init__(self, parent, name, comment=comment)
class Variables(_Import):
def __init__(self, parent, name, args=None, comment=None):
_Import.__init__(self, parent, name, args, comment=comment)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from tsvreader import TsvReader
class TxtReader(TsvReader):
_space_splitter = re.compile(' {2,}')
_pipe_splitter = re.compile(' \|(?= )')
def _split_row(self, row):
row = row.rstrip().replace('\t', ' ')
if not row.startswith('| '):
return self._space_splitter.split(row)
if row.endswith(' |'):
row = row[1:-1]
else:
row = row[1:]
return self._pipe_splitter.split(row)
def _process(self, cell):
return cell.decode('UTF-8')
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from robot import utils
from robot.output import LOGGER
from robot.errors import DataError
from datarow import DataRow
from tablepopulators import (SettingTablePopulator, VariableTablePopulator,
TestTablePopulator, KeywordTablePopulator,
NullPopulator)
from htmlreader import HtmlReader
from tsvreader import TsvReader
from txtreader import TxtReader
try:
from restreader import RestReader
except ImportError:
def RestReader():
raise DataError("Using reStructuredText test data requires having "
"'docutils' module installed.")
READERS = {'html': HtmlReader, 'htm': HtmlReader, 'xhtml': HtmlReader,
'tsv': TsvReader , 'rst': RestReader, 'rest': RestReader,
'txt': TxtReader}
# Hook for external tools for altering ${CURDIR} processing
PROCESS_CURDIR = True
class FromFilePopulator(object):
_populators = {'setting': SettingTablePopulator,
'variable': VariableTablePopulator,
'testcase': TestTablePopulator,
'keyword': KeywordTablePopulator}
def __init__(self, datafile):
self._datafile = datafile
self._current_populator = NullPopulator()
self._curdir = self._get_curdir(datafile.directory)
def _get_curdir(self, path):
return path.replace('\\','\\\\') if path else None
def populate(self, path):
LOGGER.info("Parsing file '%s'." % path)
source = self._open(path)
try:
self._get_reader(path).read(source, self)
except:
raise DataError(utils.get_error_message())
finally:
source.close()
def _open(self, path):
if not os.path.isfile(path):
raise DataError("Data source does not exist.")
try:
return open(path, 'rb')
except:
raise DataError(utils.get_error_message())
def _get_reader(self, path):
extension = os.path.splitext(path.lower())[-1][1:]
try:
return READERS[extension]()
except KeyError:
raise DataError("Unsupported file format '%s'." % extension)
def start_table(self, header):
self._current_populator.populate()
table = self._datafile.start_table(DataRow(header).all)
self._current_populator = self._populators[table.type](table) \
if table is not None else NullPopulator()
return bool(self._current_populator)
def eof(self):
self._current_populator.populate()
def add(self, row):
if PROCESS_CURDIR and self._curdir:
row = self._replace_curdirs_in(row)
data = DataRow(row)
if data:
self._current_populator.add(data)
def _replace_curdirs_in(self, row):
return [cell.replace('${CURDIR}', self._curdir) for cell in row]
class FromDirectoryPopulator(object):
ignored_prefixes = ('_', '.')
ignored_dirs = ('CVS',)
def populate(self, path, datadir, include_suites, warn_on_skipped):
LOGGER.info("Parsing test data directory '%s'" % path)
include_sub_suites = self._get_include_suites(path, include_suites)
initfile, children = self._get_children(path, include_sub_suites)
datadir.initfile = initfile
if initfile:
try:
FromFilePopulator(datadir).populate(initfile)
except DataError, err:
LOGGER.error(unicode(err))
for child in children:
try:
datadir.add_child(child, include_sub_suites)
except DataError, err:
self._log_failed_parsing("Parsing data source '%s' failed: %s"
% (child, unicode(err)), warn_on_skipped)
def _log_failed_parsing(self, message, warn):
if warn:
LOGGER.warn(message)
else:
LOGGER.info(message)
def _get_include_suites(self, path, include_suites):
# If directory is included also all it children should be included
if self._is_in_incl_suites(os.path.basename(os.path.normpath(path)),
include_suites):
return []
return include_suites
def _get_children(self, dirpath, include_suites):
initfile = None
children = []
for name, path in self._list_dir(dirpath):
if self._is_init_file(name, path):
if not initfile:
initfile = path
else:
LOGGER.error("Ignoring second test suite init file '%s'." % path)
elif self._is_included(name, path, include_suites):
children.append(path)
else:
LOGGER.info("Ignoring file or directory '%s'." % name)
return initfile, children
def _list_dir(self, path):
# os.listdir returns Unicode entries when path is Unicode
names = os.listdir(utils.unic(path))
for name in sorted(names, key=unicode.lower):
# utils.unic needed to handle nfc/nfd normalization on OSX
yield utils.unic(name), utils.unic(os.path.join(path, name))
def _is_init_file(self, name, path):
if not os.path.isfile(path):
return False
base, extension = os.path.splitext(name.lower())
return base == '__init__' and extension[1:] in READERS
def _is_included(self, name, path, include_suites):
if name.startswith(self.ignored_prefixes):
return False
if os.path.isdir(path):
return name not in self.ignored_dirs
base, extension = os.path.splitext(name.lower())
return (extension[1:] in READERS and
self._is_in_incl_suites(base, include_suites))
def _is_in_incl_suites(self, name, include_suites):
if include_suites == []:
return True
# Match only to the last part of name given like '--suite parent.child'
include_suites = [ incl.split('.')[-1] for incl in include_suites ]
name = name.split('__', 1)[-1] # Strip possible prefix
return utils.matches_any(name, include_suites, ignore=['_'])
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from codecs import BOM_UTF8
class TsvReader:
def read(self, tsvfile, populator):
process = False
for index, row in enumerate(tsvfile.readlines()):
if index == 0 and row.startswith(BOM_UTF8):
row = row[len(BOM_UTF8):]
cells = [ self._process(cell) for cell in self._split_row(row) ]
name = cells and cells[0].strip() or ''
if name.startswith('*') and populator.start_table([ c.replace('*','') for c in cells ]):
process = True
elif process:
populator.add(cells)
populator.eof()
def _split_row(self, row):
return row.rstrip().split('\t')
def _process(self, cell):
if len(cell) > 1 and cell[0] == cell[-1] == '"':
cell = cell[1:-1].replace('""','"')
return cell.decode('UTF-8')
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tempfile
import os
from docutils.core import publish_cmdline
from htmlreader import HtmlReader
# Ignore custom sourcecode directives at least we use in reST sources.
# See e.g. ug2html.py for an example how custom directives are created.
from docutils.parsers.rst import directives
ignorer = lambda *args: []
ignorer.content = 1
directives.register_directive('sourcecode', ignorer)
del directives, ignorer
class RestReader(HtmlReader):
def read(self, rstfile, rawdata):
htmlpath = self._rest_to_html(rstfile.name)
htmlfile = None
try:
htmlfile = open(htmlpath, 'rb')
return HtmlReader.read(self, htmlfile, rawdata)
finally:
if htmlfile:
htmlfile.close()
os.remove(htmlpath)
def _rest_to_html(self, rstpath):
filedesc, htmlpath = tempfile.mkstemp('.html')
os.close(filedesc)
publish_cmdline(writer_name='html', argv=[rstpath, htmlpath])
return htmlpath
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class Populator(object):
"""Explicit interface for all populators."""
def add(self, row): raise NotImplementedError()
def populate(self): raise NotImplementedError()
class CommentCacher(object):
def __init__(self):
self._init_comments()
def _init_comments(self):
self._comments = []
def add(self, comment):
self._comments.append(comment)
def consume_comments_with(self, function):
for c in self._comments:
function(c)
self._init_comments()
class _TablePopulator(Populator):
def __init__(self, table):
self._table = table
self._populator = NullPopulator()
self._comments = CommentCacher()
def add(self, row):
if self._is_cacheable_comment_row(row):
self._comments.add(row)
else:
self._add(row)
def _add(self, row):
if not self._is_continuing(row):
self._populator.populate()
self._populator = self._get_populator(row)
self._comments.consume_comments_with(self._populator.add)
self._populator.add(row)
def populate(self):
self._comments.consume_comments_with(self._populator.add)
self._populator.populate()
def _is_continuing(self, row):
return row.is_continuing() and self._populator
def _is_cacheable_comment_row(self, row):
return row.is_commented()
class SettingTablePopulator(_TablePopulator):
def _get_populator(self, row):
row.handle_old_style_metadata()
setter = self._table.get_setter(row.head)
return SettingPopulator(setter) if setter else NullPopulator()
class VariableTablePopulator(_TablePopulator):
def _get_populator(self, row):
return VariablePopulator(self._table.add, row.head)
class _StepContainingTablePopulator(_TablePopulator):
def _is_continuing(self, row):
return row.is_indented() and self._populator or row.is_commented()
def _is_cacheable_comment_row(self, row):
return row.is_commented() and isinstance(self._populator, NullPopulator)
class TestTablePopulator(_StepContainingTablePopulator):
def _get_populator(self, row):
return TestCasePopulator(self._table.add)
class KeywordTablePopulator(_StepContainingTablePopulator):
def _get_populator(self, row):
return UserKeywordPopulator(self._table.add)
class ForLoopPopulator(Populator):
def __init__(self, for_loop_creator):
self._for_loop_creator = for_loop_creator
self._loop = None
self._populator = NullPopulator()
self._declaration = []
def add(self, row):
dedented_row = row.dedent()
if not self._loop:
declaration_ready = self._populate_declaration(row)
if not declaration_ready:
return
self._loop = self._for_loop_creator(self._declaration)
if not row.is_continuing():
self._populator.populate()
self._populator = StepPopulator(self._loop.add_step)
self._populator.add(dedented_row)
def _populate_declaration(self, row):
if row.starts_for_loop() or row.is_continuing():
self._declaration.extend(row.dedent().data)
return False
return True
def populate(self):
if not self._loop:
self._for_loop_creator(self._declaration)
self._populator.populate()
class _TestCaseUserKeywordPopulator(Populator):
def __init__(self, test_or_uk_creator):
self._test_or_uk_creator = test_or_uk_creator
self._test_or_uk = None
self._populator = NullPopulator()
self._comments = CommentCacher()
def add(self, row):
if row.is_commented():
self._comments.add(row)
return
if not self._test_or_uk:
self._test_or_uk = self._test_or_uk_creator(row.head)
dedented_row = row.dedent()
if dedented_row:
self._handle_data_row(dedented_row)
def _handle_data_row(self, row):
if not self._continues(row):
self._populator.populate()
self._populator = self._get_populator(row)
self._flush_comments_with(self._populate_comment_row)
else:
self._flush_comments_with(self._populator.add)
self._populator.add(row)
def _populate_comment_row(self, crow):
populator = StepPopulator(self._test_or_uk.add_step)
populator.add(crow)
populator.populate()
def _flush_comments_with(self, function):
self._comments.consume_comments_with(function)
def populate(self):
self._populator.populate()
self._flush_comments_with(self._populate_comment_row)
def _get_populator(self, row):
if row.starts_test_or_user_keyword_setting():
setter = self._setting_setter(row)
return SettingPopulator(setter) if setter else NullPopulator()
if row.starts_for_loop():
return ForLoopPopulator(self._test_or_uk.add_for_loop)
return StepPopulator(self._test_or_uk.add_step)
def _continues(self, row):
return row.is_continuing() and self._populator or \
(isinstance(self._populator, ForLoopPopulator) and row.is_indented())
def _setting_setter(self, row):
setting_name = row.test_or_user_keyword_setting_name()
return self._test_or_uk.get_setter(setting_name)
class TestCasePopulator(_TestCaseUserKeywordPopulator):
_item_type = 'test case'
class UserKeywordPopulator(_TestCaseUserKeywordPopulator):
_item_type = 'keyword'
class Comments(object):
def __init__(self):
self._crows = []
def add(self, row):
if row.comments:
self._crows.append(row.comments)
def formatted_value(self):
rows = (' '.join(row).strip() for row in self._crows)
return '\n'.join(rows)
class _PropertyPopulator(Populator):
def __init__(self, setter):
self._setter = setter
self._value = []
self._comments = Comments()
def add(self, row):
if not row.is_commented():
self._add(row)
self._comments.add(row)
def _add(self, row):
self._value.extend(row.dedent().data)
class VariablePopulator(_PropertyPopulator):
def __init__(self, setter, name):
_PropertyPopulator.__init__(self, setter)
self._name = name
def populate(self):
self._setter(self._name, self._value,
self._comments.formatted_value())
class SettingPopulator(_PropertyPopulator):
def populate(self):
self._setter(self._value, self._comments.formatted_value())
class StepPopulator(_PropertyPopulator):
def _add(self, row):
self._value.extend(row.data)
def populate(self):
if self._value or self._comments:
self._setter(self._value, self._comments.formatted_value())
class NullPopulator(Populator):
def add(self, row): pass
def populate(self): pass
def __nonzero__(self): return False
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from datarow import DataRow
from model import (TestCaseFile, TestDataDirectory, ResourceFile,
TestCase, UserKeyword)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
class DataRow(object):
_row_continuation_marker = '...'
_whitespace_regexp = re.compile('\s+')
_ye_olde_metadata_prefix = 'meta:'
def __init__(self, cells):
self.cells, self.comments = self._parse(cells)
def _parse(self, row):
data = []
comments = []
for cell in row:
cell = self._collapse_whitespace(cell)
if cell.startswith('#') and not comments:
comments.append(cell[1:])
elif comments:
comments.append(cell)
else:
data.append(cell)
return self._purge_empty_cells(data), self._purge_empty_cells(comments)
def _collapse_whitespace(self, cell):
return self._whitespace_regexp.sub(' ', cell).strip()
def _purge_empty_cells(self, row):
while row and not row[-1]:
row.pop()
# Cells with only a single backslash are considered empty
return [cell if cell != '\\' else '' for cell in row]
@property
def head(self):
return self.cells[0] if self.cells else None
@property
def _tail(self):
return self.cells[1:] if self.cells else None
@property
def all(self):
return self.cells
@property
def data(self):
if self.is_continuing():
index = self.cells.index(self._row_continuation_marker) + 1
return self.cells[index:]
return self.cells
def dedent(self):
datarow = DataRow([])
datarow.cells = self._tail
datarow.comments = self.comments
return datarow
def startswith(self, value):
return self.head() == value
def handle_old_style_metadata(self):
if self._is_metadata_with_olde_prefix(self.head):
self.cells = self._convert_to_new_style_metadata()
def _is_metadata_with_olde_prefix(self, value):
return value.lower().startswith(self._ye_olde_metadata_prefix)
def _convert_to_new_style_metadata(self):
return ['Metadata'] + [self.head.split(':', 1)[1].strip()] + self._tail
def starts_for_loop(self):
if self.head and self.head.startswith(':'):
return self.head.replace(':', '').replace(' ', '').upper() == 'FOR'
return False
def starts_test_or_user_keyword_setting(self):
head = self.head
return head and head[0] == '[' and head[-1] == ']'
def test_or_user_keyword_setting_name(self):
return self.head[1:-1].strip()
def is_indented(self):
return self.head == ''
def is_continuing(self):
for cell in self.cells:
if cell == self._row_continuation_marker:
return True
if cell:
return False
def is_commented(self):
return bool(not self.cells and self.comments)
def __nonzero__(self):
return bool(self.cells or self.comments)
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from robot.errors import DataError
from robot.variables import is_var
from robot.output import LOGGER
from robot import utils
from settings import (Documentation, Fixture, Timeout, Tags, Metadata,
Library, Resource, Variables, Arguments, Return, Template)
from populators import FromFilePopulator, FromDirectoryPopulator
def TestData(parent=None, source=None, include_suites=[], warn_on_skipped=False):
if os.path.isdir(source):
return TestDataDirectory(parent, source, include_suites, warn_on_skipped)
return TestCaseFile(parent, source)
class _TestData(object):
def __init__(self, parent=None, source=None):
self.parent = parent
self.source = utils.abspath(source) if source else None
self.children = []
self._tables = None
def _get_tables(self):
if not self._tables:
self._tables = utils.NormalizedDict({'Setting': self.setting_table,
'Settings': self.setting_table,
'Metadata': self.setting_table,
'Variable': self.variable_table,
'Variables': self.variable_table,
'Keyword': self.keyword_table,
'Keywords': self.keyword_table,
'User Keyword': self.keyword_table,
'User Keywords': self.keyword_table,
'Test Case': self.testcase_table,
'Test Cases': self.testcase_table})
return self._tables
def start_table(self, header_row):
table_name = header_row[0]
try:
table = self._valid_table(self._get_tables()[table_name])
except KeyError:
return None
else:
if table is not None:
table.set_header(header_row)
return table
@property
def name(self):
if not self.source:
return None
name = self._get_basename()
name = name.split('__', 1)[-1] # Strip possible prefix
name = name.replace('_', ' ').strip()
if name.islower():
name = name.title()
return name
def _get_basename(self):
return os.path.splitext(os.path.basename(self.source))[0]
@property
def keywords(self):
return self.keyword_table.keywords
@property
def imports(self):
return self.setting_table.imports
def report_invalid_syntax(self, table, message, level='ERROR'):
initfile = getattr(self, 'initfile', None)
path = os.path.join(self.source, initfile) if initfile else self.source
LOGGER.write("Invalid syntax in file '%s' in table '%s': %s"
% (path, table, message), level)
class TestCaseFile(_TestData):
def __init__(self, parent=None, source=None):
_TestData.__init__(self, parent, source)
self.directory = os.path.dirname(self.source) if self.source else None
self.setting_table = TestCaseFileSettingTable(self)
self.variable_table = VariableTable(self)
self.testcase_table = TestCaseTable(self)
self.keyword_table = KeywordTable(self)
if source: # FIXME: model should be decoupled from populating
FromFilePopulator(self).populate(source)
self._validate()
def _validate(self):
if not self.testcase_table.is_started():
raise DataError('File has no test case table.')
def _valid_table(self, table):
return table
def has_tests(self):
return True
def __iter__(self):
for table in [self.setting_table, self.variable_table,
self.testcase_table, self.keyword_table]:
yield table
class ResourceFile(_TestData):
def __init__(self, source=None):
_TestData.__init__(self, source=source)
self.directory = os.path.dirname(self.source) if self.source else None
self.setting_table = ResourceFileSettingTable(self)
self.variable_table = VariableTable(self)
self.testcase_table = TestCaseTable(self)
self.keyword_table = KeywordTable(self)
if self.source:
FromFilePopulator(self).populate(source)
self._report_status()
def _report_status(self):
if self.setting_table or self.variable_table or self.keyword_table:
LOGGER.info("Imported resource file '%s' (%d keywords)."
% (self.source, len(self.keyword_table.keywords)))
else:
LOGGER.warn("Imported resource file '%s' is empty." % self.source)
def _valid_table(self, table):
if table is self.testcase_table:
raise DataError("Resource file '%s' contains a test case table "
"which is not allowed." % self.source)
return table
def __iter__(self):
for table in [self.setting_table, self.variable_table,
self.keyword_table]:
yield table
class TestDataDirectory(_TestData):
def __init__(self, parent=None, source=None, include_suites=[], warn_on_skipped=False):
_TestData.__init__(self, parent, source)
self.directory = self.source
self.initfile = None
self.setting_table = InitFileSettingTable(self)
self.variable_table = VariableTable(self)
self.testcase_table = TestCaseTable(self)
self.keyword_table = KeywordTable(self)
if self.source:
FromDirectoryPopulator().populate(self.source, self, include_suites, warn_on_skipped)
self.children = [ ch for ch in self.children if ch.has_tests() ]
def _get_basename(self):
return os.path.basename(self.source)
def _valid_table(self, table):
if table is self.testcase_table:
LOGGER.error("Test suite init file in '%s' contains a test case "
"table which is not allowed." % self.source)
return None
return table
def add_child(self, path, include_suites):
self.children.append(TestData(parent=self,source=path,
include_suites=include_suites))
def has_tests(self):
return any(ch.has_tests() for ch in self.children)
def __iter__(self):
for table in [self.setting_table, self.variable_table,
self.keyword_table]:
yield table
class _Table(object):
def __init__(self, parent):
self.parent = parent
self.header = None
def set_header(self, header):
self.header = header
@property
def name(self):
return self.header[0]
@property
def source(self):
return self.parent.source
@property
def directory(self):
return self.parent.directory
def report_invalid_syntax(self, message, level='ERROR'):
self.parent.report_invalid_syntax(self.name, message, level)
class _WithSettings(object):
def get_setter(self, setting_name):
normalized = self.normalize(setting_name)
if normalized in self._setters:
return self._setters[normalized](self)
self.report_invalid_syntax("Non-existing setting '%s'." % setting_name)
def is_setting(self, setting_name):
return self.normalize(setting_name) in self._setters
def normalize(self, setting):
result = utils.normalize(setting)
return result[0:-1] if result and result[-1]==':' else result
class _SettingTable(_Table, _WithSettings):
type = 'setting'
def __init__(self, parent):
_Table.__init__(self, parent)
self.doc = Documentation('Documentation', self)
self.suite_setup = Fixture('Suite Setup', self)
self.suite_teardown = Fixture('Suite Teardown', self)
self.test_setup = Fixture('Test Setup', self)
self.test_teardown = Fixture('Test Teardown', self)
self.force_tags = Tags('Force Tags', self)
self.default_tags = Tags('Default Tags', self)
self.test_template = Template('Test Template', self)
self.test_timeout = Timeout('Test Timeout', self)
self.metadata = []
self.imports = []
def _get_adder(self, adder_method):
def adder(value, comment):
name = value[0] if value else ''
adder_method(name, value[1:], comment)
return adder
def add_metadata(self, name, value='', comment=None):
self.metadata.append(Metadata('Metadata', self, name, value, comment))
return self.metadata[-1]
def add_library(self, name, args=None, comment=None):
self.imports.append(Library(self, name, args, comment=comment))
return self.imports[-1]
def add_resource(self, name, invalid_args=None, comment=None):
self.imports.append(Resource(self, name, invalid_args, comment=comment))
return self.imports[-1]
def add_variables(self, name, args=None, comment=None):
self.imports.append(Variables(self, name, args, comment=comment))
return self.imports[-1]
def __nonzero__(self):
return any(setting.is_set() for setting in self)
class TestCaseFileSettingTable(_SettingTable):
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'suitesetup': lambda s: s.suite_setup.populate,
'suiteprecondition': lambda s: s.suite_setup.populate,
'suiteteardown': lambda s: s.suite_teardown.populate,
'suitepostcondition': lambda s: s.suite_teardown.populate,
'testsetup': lambda s: s.test_setup.populate,
'testprecondition': lambda s: s.test_setup.populate,
'testteardown': lambda s: s.test_teardown.populate,
'testpostcondition': lambda s: s.test_teardown.populate,
'forcetags': lambda s: s.force_tags.populate,
'defaulttags': lambda s: s.default_tags.populate,
'testtemplate': lambda s: s.test_template.populate,
'testtimeout': lambda s: s.test_timeout.populate,
'library': lambda s: s._get_adder(s.add_library),
'resource': lambda s: s._get_adder(s.add_resource),
'variables': lambda s: s._get_adder(s.add_variables),
'metadata': lambda s: s._get_adder(s.add_metadata)}
def __iter__(self):
for setting in [self.doc, self.suite_setup, self.suite_teardown,
self.test_setup, self.test_teardown, self.force_tags,
self.default_tags, self.test_template, self.test_timeout] \
+ self.metadata + self.imports:
yield setting
class ResourceFileSettingTable(_SettingTable):
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'library': lambda s: s._get_adder(s.add_library),
'resource': lambda s: s._get_adder(s.add_resource),
'variables': lambda s: s._get_adder(s.add_variables)}
def __iter__(self):
for setting in [self.doc] + self.imports:
yield setting
class InitFileSettingTable(_SettingTable):
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'suitesetup': lambda s: s.suite_setup.populate,
'suiteprecondition': lambda s: s.suite_setup.populate,
'suiteteardown': lambda s: s.suite_teardown.populate,
'suitepostcondition': lambda s: s.suite_teardown.populate,
'testsetup': lambda s: s.test_setup.populate,
'testprecondition': lambda s: s.test_setup.populate,
'testteardown': lambda s: s.test_teardown.populate,
'testpostcondition': lambda s: s.test_teardown.populate,
'forcetags': lambda s: s.force_tags.populate,
'library': lambda s: s._get_adder(s.add_library),
'resource': lambda s: s._get_adder(s.add_resource),
'variables': lambda s: s._get_adder(s.add_variables),
'metadata': lambda s: s._get_adder(s.add_metadata)}
def __iter__(self):
for setting in [self.doc, self.suite_setup, self.suite_teardown,
self.test_setup, self.test_teardown, self.force_tags] \
+ self.metadata + self.imports:
yield setting
class VariableTable(_Table):
type = 'variable'
def __init__(self, parent):
_Table.__init__(self, parent)
self.variables = []
def add(self, name, value, comment=None):
self.variables.append(Variable(name, value, comment))
def __iter__(self):
return iter(self.variables)
def __nonzero__(self):
return bool(self.variables)
class TestCaseTable(_Table):
type = 'testcase'
def __init__(self, parent):
_Table.__init__(self, parent)
self.tests = []
def add(self, name):
self.tests.append(TestCase(self, name))
return self.tests[-1]
def __iter__(self):
return iter(self.tests)
def __nonzero__(self):
return bool(self.tests)
def is_started(self):
return bool(self.header)
class KeywordTable(_Table):
type = 'keyword'
def __init__(self, parent):
_Table.__init__(self, parent)
self.keywords = []
def add(self, name):
self.keywords.append(UserKeyword(self, name))
return self.keywords[-1]
def __iter__(self):
return iter(self.keywords)
def __nonzero__(self):
return bool(self.keywords)
class Variable(object):
def __init__(self, name, value, comment=None):
self.name = name.rstrip('= ')
if name.startswith('$') and value == []:
value = ''
if isinstance(value, basestring):
value = [value] # Need to support scalar lists until RF 2.6
self.value = value
self.comment = comment
def as_list(self):
ret = [self.name] + self.value
if self.comment:
ret.append('# %s' % self.comment)
return ret
def is_set(self):
return True
def is_for_loop(self):
return False
class _WithSteps(object):
def add_step(self, content, comment=None):
self.steps.append(Step(content, comment))
return self.steps[-1]
class TestCase(_WithSteps, _WithSettings):
def __init__(self, parent, name):
self.parent = parent
self.name = name
self.doc = Documentation('[Documentation]', self)
self.template = Template('[Template]', self)
self.tags = Tags('[Tags]', self)
self.setup = Fixture('[Setup]', self)
self.teardown = Fixture('[Teardown]', self)
self.timeout = Timeout('[Timeout]', self)
self.steps = []
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'template': lambda s: s.template.populate,
'setup': lambda s: s.setup.populate,
'precondition': lambda s: s.setup.populate,
'teardown': lambda s: s.teardown.populate,
'postcondition': lambda s: s.teardown.populate,
'tags': lambda s: s.tags.populate,
'timeout': lambda s: s.timeout.populate}
@property
def source(self):
return self.parent.source
@property
def directory(self):
return self.parent.directory
def add_for_loop(self, data):
self.steps.append(ForLoop(data))
return self.steps[-1]
def report_invalid_syntax(self, message, level='ERROR'):
type_ = 'test case' if type(self) is TestCase else 'keyword'
message = "Invalid syntax in %s '%s': %s" % (type_, self.name, message)
self.parent.report_invalid_syntax(message, level)
def __iter__(self):
for element in [self.doc, self.tags, self.setup,
self.template, self.timeout] \
+ self.steps + [self.teardown]:
yield element
class UserKeyword(TestCase):
def __init__(self, parent, name):
self.parent = parent
self.name = name
self.doc = Documentation('[Documentation]', self)
self.args = Arguments('[Arguments]', self)
self.return_ = Return('[Return]', self)
self.timeout = Timeout('[Timeout]', self)
self.teardown = Fixture('[Teardown]', self)
self.steps = []
_setters = {'documentation': lambda s: s.doc.populate,
'document': lambda s: s.doc.populate,
'arguments': lambda s: s.args.populate,
'return': lambda s: s.return_.populate,
'timeout': lambda s: s.timeout.populate,
'teardown': lambda s: s.teardown.populate}
def __iter__(self):
for element in [self.args, self.doc, self.timeout] \
+ self.steps + [self.teardown, self.return_]:
yield element
class ForLoop(_WithSteps):
def __init__(self, content):
self.range, index = self._get_range_and_index(content)
self.vars = content[:index]
self.items = content[index+1:]
self.steps = []
def _get_range_and_index(self, content):
for index, item in enumerate(content):
item = item.upper().replace(' ', '')
if item in ['IN', 'INRANGE']:
return item == 'INRANGE', index
return False, len(content)
def is_comment(self):
return False
def is_for_loop(self):
return True
def apply_template(self, template):
return self
def as_list(self):
return [': FOR'] + self.vars + ['IN RANGE' if self.range else 'IN'] + self.items
def __iter__(self):
return iter(self.steps)
class Step(object):
def __init__(self, content, comment=None):
self.assign = self._get_assigned_vars(content)
try:
self.keyword = content[len(self.assign)]
except IndexError:
self.keyword = None
self.args = content[len(self.assign)+1:]
self.comment = comment
def _get_assigned_vars(self, content):
vars = []
for item in content:
if not is_var(item.rstrip('= ')):
break
vars.append(item)
return vars
def is_comment(self):
return not (self.assign or self.keyword or self.args)
def is_for_loop(self):
return False
def apply_template(self, template):
if self.is_comment():
return self
return Step([template] + self.as_list(include_comment=False))
def is_set(self):
return True
def as_list(self, indent=False, include_comment=True):
kw = [self.keyword] if self.keyword is not None else []
ret = self.assign + kw + self.args
if indent:
ret.insert(0, '')
if include_comment and self.comment:
ret.append('# %s' % self.comment)
return ret
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import HTMLParser
import sys
from htmlentitydefs import entitydefs
extra_entitydefs = {'nbsp': ' ', 'apos': "'", 'tilde': '~'}
class HtmlReader(HTMLParser.HTMLParser):
IGNORE = 0
INITIAL = 1
PROCESS = 2
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self._encoding = 'ISO-8859-1'
self._handlers = { 'table_start' : self.table_start,
'table_end' : self.table_end,
'tr_start' : self.tr_start,
'tr_end' : self.tr_end,
'td_start' : self.td_start,
'td_end' : self.td_end,
'th_start' : self.td_start,
'th_end' : self.td_end,
'br_start' : self.br_start,
'meta_start' : self.meta_start }
def read(self, htmlfile, populator):
self.populator = populator
self.state = self.IGNORE
self.current_row = None
self.current_cell = None
for line in htmlfile.readlines():
self.feed(line)
# Calling close is required by the HTMLParser but may cause problems
# if the same instance of our HtmlParser is reused. Currently it's
# used only once so there's no problem.
self.close()
self.populator.eof()
def handle_starttag(self, tag, attrs):
handler = self._handlers.get(tag+'_start')
if handler is not None:
handler(attrs)
def handle_endtag(self, tag):
handler = self._handlers.get(tag+'_end')
if handler is not None:
handler()
def handle_data(self, data, decode=True):
if self.state == self.IGNORE or self.current_cell is None:
return
if decode:
data = data.decode(self._encoding)
self.current_cell.append(data)
def handle_entityref(self, name):
value = self._handle_entityref(name)
self.handle_data(value, decode=False)
def _handle_entityref(self, name):
if extra_entitydefs.has_key(name):
return extra_entitydefs[name]
try:
value = entitydefs[name]
except KeyError:
return '&'+name+';'
if value.startswith('&#'):
return unichr(int(value[2:-1]))
return value.decode('ISO-8859-1')
def handle_charref(self, number):
value = self._handle_charref(number)
self.handle_data(value, decode=False)
def _handle_charref(self, number):
try:
return unichr(int(number))
except ValueError:
return '&#'+number+';'
def handle_pi(self, data):
encoding = self._get_encoding_from_pi(data)
if encoding:
self._encoding = encoding
def unknown_decl(self, data):
# Ignore everything even if it's invalid. This kind of stuff comes
# at least from MS Excel
pass
def table_start(self, attrs=None):
self.state = self.INITIAL
self.current_row = None
self.current_cell = None
def table_end(self):
if self.current_row is not None:
self.tr_end()
self.state = self.IGNORE
def tr_start(self, attrs=None):
if self.current_row is not None:
self.tr_end()
self.current_row = []
def tr_end(self):
if self.current_row is None:
return
if self.current_cell is not None:
self.td_end()
if self.state == self.INITIAL:
if len(self.current_row) > 0:
if self.populator.start_table(self.current_row):
self.state = self.PROCESS
else:
self.state = self.IGNORE
else:
self.state = self.IGNORE
elif self.state == self.PROCESS:
self.populator.add(self.current_row)
self.current_row = None
def td_start(self, attrs=None):
if self.current_cell is not None:
self.td_end()
if self.current_row is None:
self.tr_start()
self.current_cell = []
def td_end(self):
if self.current_cell is not None and self.state != self.IGNORE:
cell = ''.join(self.current_cell)
self.current_row.append(cell)
self.current_cell = None
def br_start(self, attrs=None):
if self.current_cell is not None and self.state != self.IGNORE:
self.current_cell.append('\n')
def meta_start(self, attrs):
encoding = self._get_encoding_from_meta(attrs)
if encoding:
self._encoding = encoding
def _get_encoding_from_meta(self, attrs):
valid_http_equiv = False
encoding = None
for name, value in attrs:
name = name.lower()
if name == 'http-equiv' and value.lower() == 'content-type':
valid_http_equiv = True
if name == 'content':
for token in value.split(';'):
token = token.strip()
if token.lower().startswith('charset='):
encoding = token[8:]
return valid_http_equiv and encoding or None
def _get_encoding_from_pi(self, data):
data = data.strip()
if not data.lower().startswith('xml '):
return None
if data.endswith('?'):
data = data[:-1]
for token in data.split():
if token.lower().startswith('encoding='):
encoding = token[9:]
if encoding.startswith("'") or encoding.startswith('"'):
encoding = encoding[1:-1]
return encoding
return None
# Workaround for following bug in Python 2.6: http://bugs.python.org/issue3932
if sys.version_info[:2] > (2, 5):
def unescape_from_py25(self, s):
if '&' not in s:
return s
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("'", "'")
s = s.replace(""", '"')
s = s.replace("&", "&") # Must be last
return s
HTMLParser.HTMLParser.unescape = unescape_from_py25
| Python |
# Copyright 2008-2011 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
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 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.
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.
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 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 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.
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 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 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.
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.
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.
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 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.
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.
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 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.
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 |
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.