code
stringlengths
1
1.72M
language
stringclasses
1 value
"""Robot Framework post-install script for Windows. This script is executed as the last part of the graphical Windows installation and during un-installation started from `Add/Remote Programs`. For more details: http://docs.python.org/distutils/builtdist.html#postinstallation-script """ from __future__ import with_statement from os.path import join import os import sys SCRIPT_DIR = join(sys.prefix, 'Scripts') ROBOT_DIR = join(sys.prefix, 'Lib', 'site-packages', 'robot') SUCCESS = '''Robot Framework installation was successful! Add Python and Scripts directories to PATH to be able to use 'pybot' and 'rebot' start-up scripts from the command line. Also add Jython and IronPython installation directories to PATH to be able to use 'jybot' and 'ipybot' scripts, respectively. Python directory: %s Scripts directory: %s ''' % (sys.prefix, SCRIPT_DIR) def windows_install(): """Generates jybot.bat and ipybot.bat scripts.""" try: _create_script('jybot.bat', 'jython') _create_script('ipybot.bat', 'ipy') except Exception, err: print 'Running post-install script failed: %s' % err print 'Robot Framework start-up scripts may not work correctly.' return # Avoid "close failed in file object destructor" error when UAC disabled # http://code.google.com/p/robotframework/issues/detail?id=1331 if sys.stdout.fileno() != -2: print SUCCESS def _create_script(name, interpreter): path = join(SCRIPT_DIR, name) runner = join(ROBOT_DIR, 'run.py') with open(path, 'w') as script: script.write('@echo off\n%s "%s" %%*\n' % (interpreter, runner)) file_created(path) def windows_uninstall(): """Deletes Jython compiled files (*$py.class). Un-installer deletes files only if installer has created them and also deletes directories only if they are empty. Thus compiled files created by Jython must be deleted separately. """ for base, _, files in os.walk(ROBOT_DIR): for name in files: if name.endswith('$py.class'): try: os.remove(join(base, name)) except OSError: pass if __name__ == '__main__': {'-install': windows_install, '-remove': windows_uninstall}[sys.argv[1]]()
Python
#!/usr/bin/env python import sys import os from os.path import join, dirname from distutils.core import setup if 'develop' in sys.argv: import setuptools # support setuptools development mode execfile(join(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. """.strip() CLASSIFIERS = """ Development Status :: 5 - Production/Stable License :: OSI Approved :: Apache Software License Operating System :: OS Independent Programming Language :: Python Topic :: Software Development :: Testing """.strip().splitlines() PACKAGES = ['robot', 'robot.api', 'robot.conf', 'robot.htmldata', 'robot.libdocpkg', 'robot.libraries', 'robot.model', 'robot.output', 'robot.parsing', 'robot.reporting', 'robot.result', 'robot.running', 'robot.running.arguments', 'robot.running.timeouts', 'robot.utils', 'robot.variables', 'robot.writer'] PACKAGE_DATA = [join('htmldata', directory, pattern) for directory in 'rebot', 'libdoc', 'testdoc', 'lib', 'common' for pattern in '*.html', '*.css', '*.js'] if sys.platform.startswith('java'): SCRIPTS = ['jybot', 'jyrebot'] elif sys.platform == 'cli': SCRIPTS = ['ipybot', 'ipyrebot'] else: SCRIPTS = ['pybot', 'rebot'] SCRIPTS = [join('src', 'bin', s) for s in SCRIPTS] if os.sep == '\\': SCRIPTS = [s+'.bat' for s in SCRIPTS] if 'bdist_wininst' in sys.argv: SCRIPTS.append('robot_postinstall.py') setup( name = 'robotframework', version = get_version(sep=''), author = 'Robot Framework Developers', author_email = 'robotframework@gmail.com', url = 'http://robotframework.org', download_url = 'https://pypi.python.org/pypi/robotframework', license = 'Apache License 2.0', description = 'A generic test automation framework', long_description = DESCRIPTION, keywords = 'robotframework testing testautomation atdd bdd', platforms = 'any', classifiers = CLASSIFIERS, package_dir = {'': 'src'}, package_data = {'robot': PACKAGE_DATA}, packages = PACKAGES, scripts = SCRIPTS, )
Python
#!/usr/bin/env python """A script for running Robot Framework's acceptance tests. Usage: run_atests.py interpreter [options] datasource(s) Data sources are paths to directories or files under `robot` folder. Available options are the same that can be used with Robot Framework. See its help (e.g. `pybot --help`) for more information. The specified interpreter is used by acceptance tests under `robot` to run test cases under `testdata`. It can be simply `python` or `jython` (if they are in PATH) or to a path a selected interpreter (e.g. `/usr/bin/python26`). Note that this script itself must always be executed with Python 2.6 or newer. Examples: $ atest/run_atests.py python --test example atest/robot $ atest/run_atests.py /usr/bin/jython25 atest/robot/tags/tag_doc.txt """ import os import shutil import signal import subprocess import sys import tempfile from os.path import abspath, basename, dirname, exists, join, normpath, splitext if sys.version_info < (2, 6): sys.exit('Running this script requires Python 2.6 or newer.') CURDIR = dirname(abspath(__file__)) RUNNER = normpath(join(CURDIR, '..', 'src', 'robot', 'run.py')) ARGUMENTS = ' '.join(''' --doc RobotSPFrameworkSPacceptanceSPtests --reporttitle RobotSPFrameworkSPTestSPReport --logtitle RobotSPFrameworkSPTestSPLog --metadata Interpreter:%(INTERPRETER)s --metadata Platform:%(PLATFORM)s --variable INTERPRETER:%(INTERPRETER)s --variable PYTHON:%(PYTHON)s --variable JYTHON:%(JYTHON)s --variable IRONPYTHON:%(IRONPYTHON)s --variable STANDALONE_JYTHON:NO --pythonpath %(PYTHONPATH)s --include %(INCLUDE)s --outputdir %(OUTPUTDIR)s --output output.xml --report report.html --log log.html --splitlog --escape space:SP --escape star:STAR --escape paren1:PAR1 --escape paren2:PAR2 --critical regression --SuiteStatLevel 3 --TagStatCombine jybotNOTpybot --TagStatCombine pybotNOTjybot --TagStatExclude pybot --TagStatExclude jybot --TagStatExclude x-* '''.strip().split()) def atests(interpreter_path, *params): interpreter = _get_interpreter_basename(interpreter_path) resultdir, tempdir = _get_result_and_temp_dirs(interpreter) args = ARGUMENTS % { 'PYTHONPATH' : join(CURDIR, 'resources'), 'OUTPUTDIR' : resultdir, 'INTERPRETER': interpreter_path, 'PYTHON': interpreter_path if 'python' in interpreter else '', 'JYTHON': interpreter_path if 'jython' in interpreter else '', 'IRONPYTHON': interpreter_path if 'ipy' in interpreter else '', 'PLATFORM': sys.platform, 'INCLUDE': 'jybot' if 'jython' in interpreter else 'pybot' } if os.name == 'nt': args += ' --exclude x-exclude-on-windows' if sys.platform == 'darwin' and 'python' in interpreter: args += ' --exclude x-exclude-on-osx-python' if 'ipy' in interpreter: args += ' --noncritical x-fails-on-ipy' command = '%s %s %s %s' % (sys.executable, RUNNER, args, ' '.join(params)) environ = dict(os.environ, TEMPDIR=tempdir) print 'Running command\n%s\n' % command sys.stdout.flush() signal.signal(signal.SIGINT, signal.SIG_IGN) return subprocess.call(command.split(), env=environ) def _get_interpreter_basename(interpreter): interpreter = basename(interpreter) base, ext = splitext(interpreter) if ext.lower() in ('.sh', '.bat', '.cmd', '.exe'): return base return interpreter def _get_result_and_temp_dirs(interpreter): resultdir = join(CURDIR, 'results', interpreter) tempdir = join(tempfile.gettempdir(), 'robottests', interpreter) if exists(resultdir): shutil.rmtree(resultdir) if exists(tempdir): shutil.rmtree(tempdir) os.makedirs(tempdir) return resultdir, tempdir if __name__ == '__main__': if len(sys.argv) == 1 or '--help' in sys.argv: print __doc__ rc = 251 else: rc = atests(*sys.argv[1:]) sys.exit(rc)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- def difference_between_stuff(file1, file2): with open(file1) as f1: content1 = f1.readlines() with open(file2) as f2: content2 = f2.readlines() for l1,l2 in zip(content1, content2): if 'generatedTimestamp' in l1: continue if 'generatedMillis' in l1: continue if l1 != l2: raise AssertionError('%r\n is not same as\n%r' % (l1, l2)) if len(content1) != len(content2): raise AssertionError("file %r len %d is different " "than file %r len %d" % (file1, len(content1), file2, len(content2)))
Python
import subprocess import os import signal import ctypes class ProcessManager(object): def __init__(self): self._process = None self._stdout = None self._stderr = None def start_process(self, *args): self._process = subprocess.Popen(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE) self._stdout = None self._stderr = None 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): self.wait_until_finished() print 'STDOUT:' print self._stdout print 'STDERR:' print self._stderr def wait_until_finished(self): if self._stdout is None: self._stdout, self._stderr = self._process.communicate() def get_runner(self, interpreter, robot_path): run = os.path.join(robot_path, 'run.py') if 'jython' not in interpreter: return [interpreter, run] jython_home = os.getenv('JYTHON_HOME') if not jython_home: raise RuntimeError('This test requires JYTHON_HOME environment variable to be set.') return [self._get_java(), '-Dpython.home=%s' % jython_home, '-classpath', self._get_classpath(jython_home), 'org.python.util.jython', run] 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') cp = jython_jar + os.pathsep + os.getenv('CLASSPATH', '') return cp.strip(':;')
Python
from __future__ import with_statement import os import re from os.path import abspath, dirname, join from subprocess import call, STDOUT import tempfile from robot.utils.asserts import assert_equals, assert_true from robot.utils import decode_output ROBOT_SRC = join(dirname(abspath(__file__)), '..', '..', '..', 'src') DATA_DIR = join(dirname(abspath(__file__)), '..', '..', 'testdata', 'tidy') TEMP_FILE = join(os.getenv('TEMPDIR'), 'tidy-test-dir', 'tidy-test-file.txt') class TidyLib(object): def __init__(self, interpreter): self._tidy = [interpreter, '-m', 'robot.tidy'] self._interpreter = interpreter def run_tidy(self, options, input, output=None, tidy=None): """Runs tidy in the operating system and returns output.""" command = (tidy or self._tidy)[:] if options: command.extend(options.split(' ')) command.append(self._path(input)) if output: command.append(output) print ' '.join(command) with tempfile.TemporaryFile() as stdout: rc = call(command, stdout=stdout, stderr=STDOUT, cwd=ROBOT_SRC, shell=os.sep=='\\') stdout.seek(0) content = decode_output(stdout.read().strip()) if rc: raise RuntimeError(content) return content def run_tidy_and_check_result(self, options, input, output=TEMP_FILE, expected=None): """Runs tidy and checks that output matches content of file `expected`.""" result = self.run_tidy(options, input, output) return self.compare_tidy_results(output or result, expected or input) def run_tidy_as_a_script_and_check_result(self, options, input, output=TEMP_FILE, expected=None): """Runs tidy and checks that output matches content of file `expected`.""" tidy = [self._interpreter, join(ROBOT_SRC, 'robot', 'tidy.py')] result = self.run_tidy(options, input, output, tidy) return self.compare_tidy_results(output or result, expected or input) def compare_tidy_results(self, result, expected, *filters): if os.path.isfile(result): result = self._read(result) filters = [re.compile('^%s$' % f) for f in filters] expected = self._read(expected) result_lines = result.splitlines() expected_lines = expected.splitlines() msg = "Actual:\n%r\n\nExpected:\n%r\n\n" % (result, expected) assert_equals(len(result_lines), len(expected_lines), msg) for res, exp in zip(result_lines, expected_lines): filter = self._filter_matches(filters, exp) if not filter: assert_equals(repr(unicode(res)), repr(unicode(exp)), msg) else: assert_true(filter.match(res), '%s: %r does not match %r' % (msg, res, filter.pattern)) return result def _filter_matches(self, filters, expected): for filter in filters: if filter.match(expected): return filter return None def _path(self, path): return abspath(join(DATA_DIR, path.replace('/', os.sep))) def _read(self, path): with open(self._path(path), 'rb') as f: return f.read().decode('UTF-8')
Python
import json import os import pprint import tempfile from os.path import join, dirname, abspath from subprocess import call, STDOUT from robot.api import logger from robot.utils import decode_output ROBOT_SRC = join(dirname(abspath(__file__)), '..', '..', '..', 'src') class LibDocLib(object): def __init__(self, interpreter): self._interpreter = interpreter self._cmd = [interpreter, '-m', 'robot.libdoc'] def run_libdoc(self, args): cmd = self._cmd + [a for a in args.split(' ') if a] cmd[-1] = cmd[-1].replace('/', os.sep) logger.info(' '.join(cmd)) stdout = tempfile.TemporaryFile() call(cmd, cwd=ROBOT_SRC, stdout=stdout, stderr=STDOUT, shell=os.sep=='\\') stdout.seek(0) output = stdout.read().replace('\r\n', '\n') logger.info(output) return decode_output(output) def get_libdoc_model_from_html(self, path): with open(path) as html_file: model_string = self._find_model(html_file) model = json.loads(model_string.replace('\\x3c/', '</')) logger.info(pprint.pformat(model)) return model def _find_model(self, html_file): for line in html_file: if line.startswith('libdoc = '): return line.split('=', 1)[1].strip(' \n;') raise RuntimeError('No model found from HTML')
Python
from __future__ import with_statement from robot.api import logger class WrongStat(AssertionError): ROBOT_CONTINUE_ON_FAILURE = True def get_total_stats(path): return get_all_stats(path)[0] def get_tag_stats(path): return get_all_stats(path)[1] def get_suite_stats(path): return get_all_stats(path)[2] def get_all_stats(path): logger.info('Getting stats from <a href="file://%s">%s</a>' % (path, path), html=True) stats_line = _get_stats_line(path) logger.debug('Stats line: %s' % stats_line) total, tags, suite = eval(stats_line) return total, tags, suite def _get_stats_line(path): prefix = 'window.output["stats"] = ' with open(path) as file: for line in file: if line.startswith(prefix): return line[len(prefix):-2] def verify_stat(stat, *attrs): stat.pop('elapsed') expected = dict(_get_expected_stat(attrs)) if stat != expected: raise WrongStat('\n%-9s: %s\n%-9s: %s' % ('Got', stat, 'Expected', expected)) def _get_expected_stat(attrs): for key, value in (a.split(':', 1) for a in attrs): value = int(value) if value.isdigit() else str(value) yield str(key), value
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 __future__ import with_statement from os.path import abspath, dirname, join from fnmatch import fnmatchcase from operator import eq from robot.api import logger CURDIR = dirname(abspath(__file__)) def verify_output(actual, expected): actual = _read_file(actual, 'Actual') expected = _read_file(join(CURDIR, expected), 'Expected') if len(expected) != len(actual): raise AssertionError('Lengths differ. Expected %d lines but got %d' % (len(expected), len(actual))) for exp, act in zip(expected, actual): tester = fnmatchcase if '*' in exp else eq if not tester(act.rstrip(), exp.rstrip()): raise AssertionError('Lines differ.\nExpected: %s\nActual: %s' % (exp, act)) def _read_file(path, title): with open(path) as file: content = file.read() logger.debug('%s:\n%s' % (title, content)) return content.splitlines()
Python
import os import time class ListenAll: ROBOT_LISTENER_API_VERSION = '2' def __init__(self, *path): path = ':'.join(path) if path else self._get_default_path() self.outfile = open(path, 'w') def _get_default_path(self): return os.path.join(os.getenv('TEMPDIR'), 'listen_all.txt') 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 crit: %s\n" % (name, attrs['doc'], tags, attrs['critical'])) 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 crit: %s\n' % attrs['critical']) else: self.outfile.write("TEST END: %s %s crit: %s\n" % (attrs['status'], attrs['message'], attrs['critical'])) 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 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 class OldListenAll: def __init__(self, *path): if not path: path = os.path.join(os.getenv('TEMPDIR'), '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 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 outpath = os.path.join(os.getenv('TEMPDIR'), '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 crit: %s\n" % (name, attrs['doc'], tags, attrs['critical'])) 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 crit: %s\n' % attrs['critical']) else: OUTFILE.write("TEST END: %s %s crit: %s\n" % (attrs['status'], attrs['message'], attrs['critical'])) 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 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 class ListenSome: def __init__(self): outpath = os.path.join(os.getenv('TEMPDIR'), '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(os.getenv('TEMPDIR'), 'listener_with_args.txt') outfile = open(outpath, 'a') outfile.write("I got arguments '%s' and '%s'\n" % (arg1, arg2)) outfile.close() class InvalidMethods: def start_suite(self, wrong, number, of, args, here): pass def end_suite(self, *args): raise RuntimeError("Here comes an exception!")
Python
import os from robot.libraries.BuiltIn import BuiltIn class ListenSome: ROBOT_LISTENER_API_VERSION = '2' def __init__(self): outpath = os.path.join(os.getenv('TEMPDIR'), '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(os.getenv('TEMPDIR'), 'listener_with_args.txt') outfile = open(outpath, 'a') outfile.write("I got arguments '%s' and '%s'\n" % (arg1, arg2)) outfile.close() class SuiteAndTestCounts(object): ROBOT_LISTENER_API_VERSION = '2' exp_data = { 'Subsuites & Subsuites2': ([], ['Subsuites', 'Subsuites2'], 5), 'Subsuites': ([], ['Sub1', 'Sub2'], 2), 'Sub1': (['SubSuite1 First'], [], 1), 'Sub2': (['SubSuite2 First'], [], 1), 'Subsuites2': ([], ['Sub.Suite.4', 'Subsuite3'], 3), 'Subsuite3': (['SubSuite3 First', 'SubSuite3 Second'], [], 2), 'Sub.Suite.4': (['Test From Sub Suite 4'], [], 1) } 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.startswith('BuiltIn.') 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) class SuiteSource(object): ROBOT_LISTENER_API_VERSION = '2' def __init__(self): self._started = 0 self._ended = 0 def start_suite(self, name, attrs): self._started += 1 self._test_source(name, attrs['source']) def end_suite(self, name, attrs): self._ended += 1 self._test_source(name, attrs['source']) def _test_source(self, suite, source): default = os.path.isfile verifier = {'Root': lambda source: source == '', 'Subsuites': os.path.isdir}.get(suite, default) if (source and not os.path.isabs(source)) or not verifier(source): raise AssertionError("Suite '%s' has wrong source '%s'" % (suite, source, verifier)) def close(self): if not (self._started == self._ended == 5): raise AssertionError("Wrong number of started (%d) or ended (%d) " "suites. Expected 5." % (self._started, self._ended))
Python
import os outpath = os.path.join(os.getenv('TEMPDIR'), '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 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 ROBOT_LISTENER_API_VERSION = '2' OUTFILE = open(os.path.join(os.getenv('TEMPDIR'), 'listener_attrs.txt'), 'w') START_ATTRS = 'doc starttime ' END_ATTRS = START_ATTRS + '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_attrs('START SUITE', attrs, START_ATTRS + 'longname metadata source tests suites totaltests') def end_suite(name, attrs): _verify_attrs('END SUITE', attrs, END_ATTRS + 'longname metadata source tests suites totaltests statistics message') def start_test(name, attrs): _verify_attrs('START TEST', attrs, START_ATTRS + 'longname tags critical template') def end_test(name, attrs): _verify_attrs('END TEST', attrs, END_ATTRS + 'longname tags critical message template') def start_keyword(name, attrs): _verify_attrs('START KEYWORD', attrs, START_ATTRS + 'args type') def end_keyword(name, attrs): _verify_attrs('END KEYWORD', attrs, END_ATTRS + 'args type') def _verify_attrs(method_name, attrs, names): names = names.split() 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, exp_type, type(value))) def close(): OUTFILE.close()
Python
def get_variables(*args): return { 'PPATH_VARFILE_2' : ' '.join(args), 'LIST__PPATH_VARFILE_2' : args }
Python
PPATH_VARFILE = "Variable from variable file in PYTHONPATH"
Python
list1 = [1, 2, 3, 4, 'foo', 'bar'] dictionary1 = {'a': 1} dictionary2 = {'a': 1, 'b': 2}
Python
class TraceLogArgsLibrary(object): def only_mandatory(self, mand1, mand2): pass def mandatory_and_default(self, mand, default="default value"): pass def multiple_default_values(self, a=1, a2=2, a3=3, a4=4): pass def mandatory_and_varargs(self, mand, *varargs): pass def return_object_with_invalid_repr(self): return InvalidRepr() def return_object_with_non_ascii_string_repr(self): return ByteRepr() class InvalidRepr: def __repr__(self): return u'Hyv\xe4' class ByteRepr: def __repr__(self): return 'Hyv\xe4'
Python
def in_exception(): raise Exception('hyv\xe4') def in_return_value(): return 'ty\xf6paikka' def in_message(): print '\xe4iti' def in_multiline_message(): print '\xe4iti\nis\xe4'
Python
import exceptions class ObjectToReturn: def __init__(self, name): self.name = name def __str__(self): return self.name def exception(self, name, msg=""): exception = getattr(exceptions, name) raise exception, msg
Python
class SameNamesAsInBuiltIn: def noop(self): """Using this keyword without libname causes an error"""
Python
from robot.libraries.BuiltIn import BuiltIn class NamespaceUsingLibrary(object): def __init__(self): self._importing_suite = BuiltIn().get_variable_value('${SUITE NAME}') self._easter = BuiltIn().get_library_instance('Easter') def get_importing_suite(self): return self._importing_suite def get_other_library(self): return self._easter
Python
class ZipLib: def kw_from_zip(self, arg): print '*INFO*', arg return arg * 2
Python
class PythonVarArgsConstructor: def __init__(self, mandatory, *varargs): self.mandatory = mandatory self.varargs = varargs def get_args(self): return self.mandatory, ' '.join(self.varargs)
Python
import os _dirs = __file__.split(os.sep) while True: if _dirs.pop() == 'atest': break _BITMAP = os.path.join(os.sep.join(_dirs), 'robot.bmp') class BinaryDataLibrary: def print_bytes(self): """Prints all bytes in range 0-255. Many of them are control chars.""" for i in range(256): print "*INFO* Byte %d: '%s'" % (i, chr(i)) print "*INFO* All bytes printed successfully" def raise_byte_error(self): raise AssertionError("Bytes 0, 10, 127, 255: '%s', '%s', '%s', '%s'" % (chr(0), chr(10), chr(127), chr(255))) def print_binary_data(self): bitmap = open(_BITMAP, 'rb') print bitmap.read() bitmap.close() print "*INFO* Binary data printed successfully"
Python
import ExampleJavaLibrary import DefaultArgs class ExtendJavaLib(ExampleJavaLibrary): def kw_in_java_extender(self, arg): return arg*2 def javaSleep(self, secs): raise Exception('Overridden kw executed!') def using_method_from_java_parent(self): self.divByZero() class ExtendJavaLibWithConstructor(DefaultArgs): def keyword(self): return None class ExtendJavaLibWithInit(ExampleJavaLibrary): def __init__(self, *args): self.args = args def get_args(self): return self.args class ExtendJavaLibWithInitAndConstructor(DefaultArgs): def __init__(self, *args): if len(args) == 1: DefaultArgs.__init__(self, args[0]) self.kw = lambda self: "Hello, world!"
Python
import os # Tests that standard modules can be imported from libraries import sys class ImportRobotModuleTestLibrary: """Tests that robot internal modules can't be imported accidentally""" def import_logging(self): try: import logging except ImportError: if os.name == 'java': print 'Could not import logging, which is OK in Jython!' return raise AssertionError, 'Importing logging module failed with Python!' try: logger = logging.getLogger() except: raise AssertionError, 'Wrong logging module imported!' print 'Importing succeeded!' def importing_robot_module_directly_fails(self): try: import serializing except ImportError: pass except: raise else: msg = "'import result' should have failed. Got it from '%s'. sys.path: %s" raise AssertionError, msg % (serializing.__file__, sys.path) def importing_robot_module_through_robot_succeeds(self): try: import robot.running except: raise AssertionError, "'import robot.running' failed"
Python
class ArgumentsPython: # method docs are used in unit tests as expected min and max args def a_0(self): """(0,0)""" return 'a_0' def a_1(self, arg): """(1,1)""" return 'a_1: ' + arg def a_3(self, arg1, arg2, arg3): """(3,3)""" return ' '.join(['a_3:',arg1,arg2,arg3]) def a_0_1(self, arg='default'): """(0,1)""" return 'a_0_1: ' + arg def a_1_3(self, arg1, arg2='default', arg3='default'): """(1,3)""" return ' '.join(['a_1_3:',arg1,arg2,arg3]) def a_0_n(self, *args): """(0,sys.maxint)""" return ' '.join(['a_0_n:', ' '.join(args)]) def a_1_n(self, arg, *args): """(1,sys.maxint)""" return ' '.join(['a_1_n:', arg, ' '.join(args)]) def a_1_2_n(self, arg1, arg2='default', *args): """(1,sys.maxint)""" return ' '.join(['a_1_2_n:', arg1, arg2, ' '.join(args)])
Python
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
def keyword_from_deeper_submodule(): return 'hi again' class Sub: def keyword_from_class_in_deeper_submodule(self): return 'bye'
Python
attribute = 42
Python
library = "It should be OK to have an attribute with same name as the module" def keyword_from_submodule(arg='World'): return "Hello, %s!" % arg
Python
some_string = 'Hello, World!' class _SomeObject: pass some_object = _SomeObject()
Python
class ParameterLibrary: def __init__(self, host='localhost', port='8080'): self.host = host self.port = port def parameters(self): return self.host, self.port
Python
from robot import utils def passing_handler(*args): for arg in args: print arg, return ', '.join(args) def failing_handler(*args): if len(args) == 0: msg = 'Failure' else: msg = 'Failure: %s' % ' '.join(args) raise AssertionError(msg) class GetKeywordNamesLibrary: def __init__(self): self.this_is_not_keyword = 'This is just an attribute!!' def get_keyword_names(self): return ['Get Keyword That Passes', 'Get Keyword That Fails', 'keyword_in_library_itself', 'non_existing_kw', 'this_is_not_keyword'] def __getattr__(self, name): if name == 'Get Keyword That Passes': return passing_handler if name == 'Get Keyword That Fails': return failing_handler raise AttributeError("Non-existing keyword '%s'" % name) def keyword_in_library_itself(self): msg = 'No need for __getattr__ here!!' print msg return msg
Python
import sys import time import exceptions from robot import utils from objecttoreturn import ObjectToReturn class ExampleLibrary: def print_(self, msg, stream='stdout'): """Print given message to selected stream (stdout or stderr)""" out_stream = getattr(sys, stream) out_stream.write(msg) def print_n_times(self, msg, count, delay=0): """Print given message n times""" for i in range(int(count)): print msg self._sleep(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 print_to_python_and_java_streams(self): import ExampleJavaLibrary print '*INFO* First message to Python' getattr(ExampleJavaLibrary(), 'print')('*INFO* Second message to Java') print '*INFO* Last message to Python' 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) 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 self._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') try: self._sleep(sec) f.write(msg or 'Slept %s seconds' % sec) finally: # may be killed by timeouts f.close() def sleep_without_logging(self, timestr): seconds = utils.timestr_to_secs(timestr) self._sleep(seconds) def _sleep(self, seconds): endtime = time.time() + float(seconds) while True: remaining = endtime - time.time() if remaining <= 0: break time.sleep(min(remaining, 0.1)) def return_custom_iterable(self, *values): return _MyIterable(*values) def return_list_subclass(self, *values): return _MyList(values) def return_unrepresentable_objects(self): class FailiningStr(object): def __str__(self): raise RuntimeError def __unicode__(self): raise UnicodeError() class FailiningUnicode(object): def __unicode__(self): raise RuntimeError return FailiningStr(), FailiningUnicode() def fail_with_suppressed_exception_name(self, msg): raise MyException(msg) class _MyIterable(object): def __init__(self, *values): self._list = list(values) def __iter__(self): return iter(self._list) class _MyList(list): pass class MyException(AssertionError): ROBOT_SUPPRESS_NAME = True
Python
class Mandatory: def __init__(self, mandatory1, mandatory2): self.mandatory1 = mandatory1 self.mandatory2 = mandatory2 def get_args(self): return self.mandatory1, self.mandatory2 class Defaults(object): def __init__(self, mandatory, default1='value', default2=None): self.mandatory = mandatory self.default1 = default1 self.default2 = default2 def get_args(self): return self.mandatory, self.default1, self.default2 class Varargs(Mandatory): def __init__(self, mandatory, *varargs): Mandatory.__init__(self, mandatory, ' '.join(str(a) for a in varargs)) class Mixed(Defaults): def __init__(self, mandatory, default=42, *extra): Defaults.__init__(self, mandatory, default, ' '.join(str(a) for a in extra))
Python
messages = [ u'Circle is 360\u00B0', u'Hyv\u00E4\u00E4 \u00FC\u00F6t\u00E4', u'\u0989\u09C4 \u09F0 \u09FA \u099F \u09EB \u09EA \u09B9' ] class UnicodeLibrary: def print_unicode_strings(self): """Prints message containing unicode characters""" for msg in messages: print '*INFO*' + msg def print_and_return_unicode_object(self): """Prints unicode object and returns it.""" object = UnicodeObject() print unicode(object) return object def raise_unicode_error(self): raise AssertionError, ', '.join(messages) class UnicodeObject: def __init__(self): self.message = u', '.join(messages) def __str__(self): return self.message def __repr__(self): return repr(self.message)
Python
from ExampleLibrary import ExampleLibrary class ExtendPythonLib(ExampleLibrary): def kw_in_python_extender(self, arg): return arg/2 def print_many(self, *msgs): raise Exception('Overridden kw executed!') def using_method_from_python_parent(self): self.exception('AssertionError', 'Error message from lib')
Python
__version__ = 'N/A' # This should be ignored when version is parsed class NameLibrary: handler_count = 10 def simple1(self): """Simple 1""" def simple2___(self): """Simple 2""" def underscore_name(self): """Underscore Name""" def underscore_name2_(self): """Underscore Name2""" def un_der__sco_r__e_3(self): """Un Der Sco R E 3""" def MiXeD_CAPS(self): """MiXeD CAPS""" def camelCase(self): """Camel Case""" def camelCase2(self): """Camel Case 2""" def mixedCAPSCamel(self): """Mixed CAPS Camel""" def camelCase_and_underscores_doesNot_work(self): """CamelCase And Underscores DoesNot Work""" def _skipped1(self): """Starts with underscore""" skipped2 = "Not a function" class DocLibrary: handler_count = 3 def no_doc(self): pass no_doc.expected_doc = '' no_doc.expected_shortdoc = '' def one_line_doc(self): """One line doc""" one_line_doc.expected_doc = 'One line doc' one_line_doc.expected_shortdoc = 'One line doc' def multiline_doc(self): """Multiline doc. Spans multiple lines. """ multiline_doc.expected_doc = 'Multiline doc.\n\nSpans multiple lines.' multiline_doc.expected_shortdoc = 'Multiline doc.' class ArgInfoLibrary: handler_count = 13 def no_args(self): """[], [], None, 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, None""" def required2(self, one, two): """['one','two'], [], None, None""" def required9(self, one, two, three, four, five, six, seven, eight, nine): """['one','two','three','four','five','six','seven','eight','nine'],\ [], None, None""" def default1(self, one=1): """['one'], [1], None, None""" def default5(self, one='', two=None, three=3, four='huh', five=True): """['one','two','three','four','five'], ['',None,3,'huh',True], None, None""" def required1_default1(self, one, two=''): """['one','two'], [''], None, None""" def required2_default3(self, one, two, three=3, four=4, five=5): """['one','two','three','four','five'], [3,4,5], None, None""" def varargs(self,*one): """[], [], 'one', None""" def required2_varargs(self, one, two, *three): """['one','two'], [], 'three', None""" def req4_def2_varargs(self, one, two, three, four, five=5, six=6, *seven): """['one','two','three','four','five','six'], [5,6], 'seven', None""" def req2_def3_varargs_kwargs(self, three, four, five=5, six=6, seven=7, *eight, **nine): """['three','four','five','six','seven'], [5,6,7], 'eight', 'nine'""" def varargs_kwargs(self,*one, **two): """[], [], 'one', 'two'""" 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' ROBOT_LIBRARY_DOC_FORMAT = 'html' 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(object): ROBOT_LIBRARY_SCOPE = 'GLOBAL' def __init__(self): self.kw_accessed = 0 self.kw_called = 0 def kw(self): self.kw_called += 1 def __getattribute__(self, name): if name == 'kw': self.kw_accessed += 1 return object.__getattribute__(self, name) class ArgDocDynamicLibrary: def __init__(self): kws = [('No Arg', []), ('One Arg', ['arg']), ('One or Two Args', ['arg', 'darg=dvalue']), ('Many Args', ['*args']), ('No Arg Spec', None)] 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 ArgDocDynamicLibraryWithKwargsSupport(ArgDocDynamicLibrary): def __init__(self): ArgDocDynamicLibrary.__init__(self) for name, argspec in [('Kwargs', ['**kwargs']), ('Varargs and Kwargs', ['*args', '**kwargs'])]: self._keywords[name] = _KeywordInfo(name, argspec) def run_keyword(self, name, args, kwargs={}): argstr = ' '.join([str(a) for a in args] + ['%s:%s' % kv for kv in sorted(kwargs.items())]) print '*INFO* Executed keyword %s with arguments %s' % (name, argstr) class _KeywordInfo: doc_template = 'Keyword documentation for %s' def __init__(self, name, argspec): self.doc = self.doc_template % name self.argspec = argspec class InvalidGetDocDynamicLibrary(ArgDocDynamicLibrary): def get_keyword_documentation(self, name, invalid_arg): pass class InvalidGetArgsDynamicLibrary(ArgDocDynamicLibrary): def get_keyword_arguments(self, name): 1/0 class InvalidAttributeDynamicLibrary(ArgDocDynamicLibrary): get_keyword_documentation = True get_keyword_arguments = False
Python
class NewStyleClassLibrary(object): def mirror(self, arg): arg = list(arg) arg.reverse() return ''.join(arg) def _property_getter(self): raise SystemExit('This should not be called, ever!!!') prop = property(_property_getter) class NewStyleClassArgsLibrary(object): def __init__(self, param): self.get_param = lambda self: param class _MyMetaClass(type): def __new__(cls, name, bases, ns): ns['kw_created_by_metaclass'] = lambda self, arg: arg.upper() return type.__new__(cls, name, bases, ns) def method_in_metaclass(cls): pass class MetaClassLibrary(object): __metaclass__ = _MyMetaClass def greet(self, name): return 'Hello %s!' % name
Python
class LibClass1: def verify_libclass1(self): return 'LibClass 1 works' class LibClass2: def verify_libclass2(self): return 'LibClass 2 works also'
Python
class FatalCatastrophyException(RuntimeError): ROBOT_EXIT_ON_FAILURE = True class ContinuableApocalypseException(RuntimeError): ROBOT_CONTINUE_ON_FAILURE = True def exit_on_failure(): raise FatalCatastrophyException() def raise_continuable_failure(msg='Can be continued'): raise ContinuableApocalypseException(msg)
Python
class _BaseDynamicLibrary(object): def get_keyword_names(self): return [] def run_keyword(self, name, *args): return None class StaticDocsLib(_BaseDynamicLibrary): """This is lib intro.""" def __init__(self, some=None, args=[]): """Init doc.""" class DynamicDocsLib(_BaseDynamicLibrary): def __init__(self, *args): pass def get_keyword_documentation(self, name): if name == '__intro__': return 'Dynamic intro doc.' if name == '__init__': return 'Dynamic init doc.' return '' class StaticAndDynamicDocsLib(_BaseDynamicLibrary): """This is static doc.""" def __init__(self, an_arg=None): """This is static doc.""" def get_keyword_documentation(self, name): if name == '__intro__': return 'dynamic override' if name == '__init__': return 'dynamic override' return '' class FailingDynamicDocLib(_BaseDynamicLibrary): """intro-o-o""" def __init__(self): """initoo-o-o""" def get_keyword_documentation(self, name): raise RuntimeError('Failing in get_keyword_documentation')
Python
ROBOT_LIBRARY_SCOPE = 'Test Suite' # this should be ignored __version__ = 'test' # this should be used as version of this library def passing(): pass def failing(): raise AssertionError('This is a failing keyword from module library') def logging(): print 'Hello from module library' print '*WARN* WARNING!' def returning(): return 'Hello from module library' def argument(arg): assert arg == 'Hello', "Expected 'Hello', got '%s'" % arg def many_arguments(arg1, arg2, arg3): assert arg1 == arg2 == arg3, ("All arguments should have been equal, got: " "%s, %s and %s") % (arg1, arg2, arg3) def default_arguments(arg1, arg2='Hi', arg3='Hello'): many_arguments(arg1, arg2, arg3) def variable_arguments(*args): return sum([int(arg) for arg in args]) attribute = 'This is not a keyword!' class NotLibrary: def two_arguments(self, arg1, arg2): msg = "Arguments should have been unequal, both were '%s'" % arg1 assert arg1 != arg2, msg def not_keyword(self): pass notlib = NotLibrary() two_arguments_from_class = notlib.two_arguments lambda_keyword = lambda arg: int(arg) + 1 lambda_keyword_with_two_args = lambda x, y: int(x) / int(y) def _not_keyword(): pass def module_library(): return "It should be OK to have an attribute with same name as the module"
Python
class _BaseLib: def __init__(self): self.registered = {} def register(self, name): self.registered[name] = None def should_be_registered(self, *expected): exp = dict([ (name, None) for name in expected ]) if self.registered != exp: raise AssertionError, 'Wrong registered: %s != %s' \ % (self.registered.keys(), exp.keys()) class Global(_BaseLib): ROBOT_LIBRARY_SCOPE = 'global' count = 0 def __init__(self): Global.count += 1 _BaseLib.__init__(self) def should_be_registered(self, *expected): if self.count != 1: raise AssertionError("Global library initialized more than once.") _BaseLib.should_be_registered(self, *expected) class Suite(_BaseLib): ROBOT_LIBRARY_SCOPE = 'TEST_SUITE' class Test(_BaseLib): ROBOT_LIBRARY_SCOPE = 'TeSt CAse' class InvalidValue(_BaseLib): ROBOT_LIBRARY_SCOPE = 'invalid' class InvalidEmpty(_BaseLib): pass class InvalidMethod(_BaseLib): def ROBOT_LIBRARY_SCOPE(self): pass class InvalidNone(_BaseLib): ROBOT_LIBRARY_SCOPE = None
Python
import os import re from robot import utils from robot.utils.asserts import assert_equals from robot.result.resultbuilder import ExecutionResultBuilder from robot.result.executionresult import Result from robot.result.testsuite import TestSuite from robot.result.testcase import TestCase from robot.result.keyword import Keyword from robot.libraries.BuiltIn import BuiltIn class NoSlotsKeyword(Keyword): pass class NoSlotsTestCase(TestCase): keyword_class = NoSlotsKeyword class NoSlotsTestSuite(TestSuite): test_class = NoSlotsTestCase keyword_class = NoSlotsKeyword class TestCheckerLibrary: def process_output(self, path): path = path.replace('/', os.sep) try: print "Processing output '%s'" % path result = Result(root_suite=NoSlotsTestSuite()) ExecutionResultBuilder(path).build(result) except: raise RuntimeError('Processing output failed: %s' % utils.get_error_message()) setter = BuiltIn().set_suite_variable setter('$SUITE', process_suite(result.suite)) setter('$STATISTICS', result.statistics) setter('$ERRORS', process_errors(result.errors)) def get_test_from_suite(self, suite, name): tests = self.get_tests_from_suite(suite, name) if len(tests) == 1: return tests[0] err = "No test '%s' found from suite '%s'" if not tests \ else "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] err = "No suite '%s' found from suite '%s'" if not suites \ else "More than one suite '%s' found from suite '%s'" raise RuntimeError(err % (name, suite.name)) def get_suites_from_suite(self, suite, name): suites = [suite] if utils.eq(suite.name, name) else [] 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, **statuses): 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] statuses = dict((utils.normalize(k), v) for k, v in statuses.items()) if len(actual_tests) != len(expected_names): raise AssertionError("Wrong number of tests." + tests_msg) for test in actual_tests: norm_name = utils.normalize(test.name) if utils.MultiMatcher(expected_names).match(test.name): print "Verifying test '%s'" % test.name status = statuses.get(norm_name) if status and ':' in status: status, message = status.split(':', 1) else: message = None self.check_test_status(test, status, message) expected_names.remove(norm_name) else: raise AssertionError("Test '%s' was not expected to be run.%s" % (test.name, tests_msg)) assert not expected_names def should_contain_tests(self, suite, *test_names): self.check_suite_contains_tests(suite, *test_names) def should_not_contain_tests(self, suite, *test_names): actual_names = [t.name for t in suite.tests] for name in test_names: if name in actual_names: raise AssertionError('Suite should not have contained test "%s"' % name) def should_contain_suites(self, suite, *expected_names): print 'Suite has suites', suite.suites actual_names = [s.name for s in suite.suites] assert_equals(len(actual_names), len(expected_names), 'Wrong number of subsuites') for expected in expected_names: if not utils.Matcher(expected).match_any(actual_names): raise AssertionError('Suite %s not found' % expected) def should_contain_tags(self, test, *tags): print 'Test has tags', test.tags assert_equals(len(test.tags), len(tags), 'Wrong number of tags') tags = sorted(tags, key=lambda s: s.lower().replace('_', '').replace(' ', '')) for act, exp in zip(test.tags, tags): assert_equals(act, exp) def should_contain_keywords(self, item, *kw_names): actual_names = [kw.name for kw in item.keywords] assert_equals(len(actual_names), len(kw_names), 'Wrong number of keywords') for act, exp in zip(actual_names, kw_names): assert_equals(act, exp) def process_suite(suite): for subsuite in suite.suites: process_suite(subsuite) for test in suite.tests: process_test(test) for kw in suite.keywords: process_keyword(kw) suite.setup = suite.keywords.setup suite.teardown = suite.keywords.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 = '' if 'PASS' not in test.doc else test.doc.split('PASS', 1)[1].lstrip() for kw in test.keywords: process_keyword(kw) test.setup = test.keywords.setup test.teardown = test.keywords.teardown test.keywords = test.kws = list(test.keywords.normal) test.keyword_count = test.kw_count = len(test.keywords) 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(list(kw.keywords.normal)) 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
import re from collections import namedtuple from robot.utils import ET MATCHER = re.compile(r'.*\((\w*) (.*) on (.*)\)') Interpreter = namedtuple('Interpreter', ['interpreter', 'version', 'platform']) def get_interpreter(output): tree = ET.parse(output) root = tree.getroot() return Interpreter(*MATCHER.match(root.attrib['generator']).groups()) def is_27(interpreter): return interpreter.version.startswith('2.7') def is_25(interpreter): return interpreter.version.startswith('2.5') def is_jython(interpreter): return interpreter.interpreter.lower() == 'jython' def is_python(interpreter): return interpreter.interpreter.lower() == 'python'
Python
from os.path import abspath, dirname, join import os import robot __all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'WINDOWS'] ROBOTPATH = dirname(abspath(robot.__file__)) ROBOT_VERSION = robot.version.get_version() DATADIR = join(dirname(abspath(__file__)), '..', 'testdata') WINDOWS = os.sep == '\\'
Python
import os import sys from stat import S_IREAD, S_IWRITE from robot.api import logger 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 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 def file_should_have_correct_line_separators(self, output, sep=os.linesep): if os.path.isfile(output): with open(output, 'rb') as infile: output = infile.read().decode('UTF-8') if sep not in output: self._wrong_separators('Output has no %r separators' % sep, output) extra_r = output.replace(sep, '').count('\r') extra_n = output.replace(sep, '').count('\n') if extra_r or extra_n: self._wrong_separators("Output has %d extra \\r and %d extra \\n" % (extra_r, extra_n), output) def _wrong_separators(self, message, output): logger.info(repr(output).replace('\\n', '\\n\n')) failure = AssertionError(message) failure.ROBOT_CONTINUE_ON_FAILURE = True raise failure
Python
#!/usr/bin/env python """Script to generate atest runners based on plain text data files. Usage: %s testdata/path/data.txt [robot/path/runner.txt] """ from os.path import abspath, basename, dirname, exists, join, splitext import os import sys if len(sys.argv) not in [2, 3] or not all(a.endswith('.txt') for a in sys.argv[1:]): print __doc__ % basename(sys.argv[0]) sys.exit(1) INPATH = abspath(sys.argv[1]) if len(sys.argv) == 2: OUTPATH = INPATH.replace(join('atest', 'testdata'), join('atest', 'robot')) else: OUTPATH = sys.argv[2] if not exists(dirname(OUTPATH)): os.mkdir(dirname(OUTPATH)) with open(INPATH) as input: TESTS = [] process = False for line in input.readlines(): line = line.rstrip() if line.startswith('*'): name = line.replace('*', '').replace(' ', '').upper() process = name in ('TESTCASE', 'TESTCASES') elif process and line and line[0] != ' ': TESTS.append(line.split(' ')[0]) with open(OUTPATH, 'wb') as output: path = INPATH.split(join('atest', 'testdata'))[1][1:].replace(os.sep, '/') output.write("""\ *** Settings *** Suite Setup Run Tests ${EMPTY} %(path)s Force Tags regression pybot jybot Resource atest_resource.txt *** Test Cases *** """ % locals()) for test in TESTS: output.write(test + '\n Check Test Case ${TESTNAME}\n') if test is not TESTS[-1]: output.write('\n') print OUTPATH
Python
#!/usr/bin/env python # Copyright 2008-2014 Nokia Solutions and Networks # # 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 implementing the command line entry point for the `Libdoc` tool. This module can be executed from the command line using the following approaches:: python -m robot.libdoc python path/to/robot/libdoc.py Instead of ``python`` it is possible to use also other Python interpreters. This module also provides :func:`libdoc` and :func:`libdoc_cli` functions that can be used programmatically. Other code is for internal usage. Libdoc itself is implemented in the :mod:`~robot.libdocpkg` package. """ USAGE = """robot.libdoc -- Robot Framework library documentation generator Version: <VERSION> Usage: python -m robot.libdoc [options] library output_file or: python -m robot.libdoc [options] library list|show|version [names] Libdoc tool can generate keyword documentation in HTML and XML formats both for test libraries and resource files. HTML format is suitable for humans and XML specs for RIDE and other tools. Libdoc also has few special commands to show library or resource information on the console. Libdoc supports all library and resource types and also earlier generated XML specs can be used as input. If a library needs arguments, they must be given as part of the library name and separated by two colons, for example, like `LibraryName::arg1::arg2`. Options ======= -f --format HTML|XML Specifies whether to generate HTML or XML output. If this options is not used, the format is got from the extension of the output file. -F --docformat ROBOT|HTML|TEXT|REST Specifies the source documentation format. Possible values are Robot Framework's documentation format, HTML, plain text, and reStructuredText. The default value can be specified in test library source code and the initial default value is `ROBOT`. New in Robot Framework 2.7.5. -n --name newname Sets the name of the documented library or resource. -v --version newversion Sets the version of the documented library or resource. -P --pythonpath path * Additional locations where to search for libraries and resources. -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. Creating documentation ====================== When creating documentation in HTML or XML format, the output file must be specified as a second argument after the library/resource name or path. Output format is got automatically from the extension but can also be set with `--format` option. Examples: python -m robot.libdoc src/MyLib.py doc/MyLib.html jython -m robot.libdoc MyJavaLibrary.java MyJavaLibrary.html python -m robot.libdoc --name MyLib Remote::10.0.0.42:8270 MyLib.xml Viewing information on console ============================== Libdoc has three special commands to show information on the console. These commands are used instead of the name of the output file, and they can also take additional arguments. list: List names of the keywords the library/resource contains. Can be limited to show only certain keywords by passing optional patterns as arguments. Keyword is listed if its name contains any given pattern. show: Show library/resource documentation. Can be limited to show only certain keywords by passing names as arguments. Keyword is shown if its name matches any given name. Special argument `intro` will show the library introduction and importing sections. version: Show library version Optional patterns given to `list` and `show` are case and space insensitive. Both also accept `*` and `?` as wildcards. Examples: python -m robot.libdoc Dialogs list python -m robot.libdoc Selenium2Library list browser python -m robot.libdoc Remote::10.0.0.42:8270 show python -m robot.libdoc Dialogs show PauseExecution execute* python -m robot.libdoc Selenium2Library show intro python -m robot.libdoc Selenium2Library version Alternative execution ===================== Libdoc works with all interpreters supported by Robot Framework (Python, Jython and IronPython). In the examples above libdoc is executed as an installed module, but it can also be executed as a script like `python path/robot/libdoc.py`. For more information see libdoc section in Robot Framework User Guide at http://code.google.com/p/robotframework/wiki/UserGuide """ import sys import os # Allows running as a script. __name__ check needed with multiprocessing: # http://code.google.com/p/robotframework/issues/detail?id=1137 if 'robot' not in sys.modules and __name__ == '__main__': import pythonpathsetter from robot.utils import Application, seq2str from robot.errors import DataError from robot.libdocpkg import LibraryDocumentation, ConsoleViewer class LibDoc(Application): def __init__(self): Application.__init__(self, USAGE, arg_limits=(2,), auto_version=False) def validate(self, options, arguments): if ConsoleViewer.handles(arguments[1]): ConsoleViewer.validate_command(arguments[1], arguments[2:]) elif len(arguments) > 2: raise DataError('Only two arguments allowed when writing output.') return options, arguments def main(self, args, name='', version='', format=None, docformat=None): lib_or_res, output = args[:2] libdoc = LibraryDocumentation(lib_or_res, name, version, self._get_doc_format(docformat)) if ConsoleViewer.handles(output): ConsoleViewer(libdoc).view(output, *args[2:]) else: libdoc.save(output, self._get_output_format(format, output)) self.console(os.path.abspath(output)) def _get_doc_format(self, format): if not format: return None return self._verify_format('Doc format', format, ['ROBOT', 'TEXT', 'HTML', 'REST']) def _get_output_format(self, format, output): default = os.path.splitext(output)[1][1:] return self._verify_format('Format', format or default, ['HTML', 'XML']) def _verify_format(self, type, format, valid): format = format.upper() if format not in valid: raise DataError("%s must be %s, got '%s'." % (type, seq2str(valid, lastsep=' or '), format)) return format def libdoc_cli(arguments): """Executes Libdoc similarly as from the command line. :param arguments: Command line arguments as a list of strings. For programmatic usage the :func:`libdoc` function is typically better. It has a better API for that usage and does not call :func:`sys.exit` like this function. Example:: from robot.libdoc import libdoc_cli libdoc_cli(['--version', '1.0', 'MyLibrary.py', 'MyLibraryDoc.html']) """ LibDoc().execute_cli(arguments) def libdoc(library_or_resource, outfile, name='', version='', format=None): """Executes libdoc. Arguments have same semantics as Libdoc command line options with same names. Example:: from robot.libdoc import libdoc libdoc('MyLibrary.py', 'MyLibraryDoc.html', version='1.0') """ LibDoc().execute(library_or_resource, outfile, name=name, version=version, format=format) if __name__ == '__main__': libdoc_cli(sys.argv[1:])
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys from java.lang import String # Global workaround for os.listdir bug http://bugs.jython.org/issue1593 # This bug has been fixed in Jython 2.5.2. if sys.version_info[:3] < (2, 5, 2): os._orig_listdir = os.listdir def listdir(path): items = os._orig_listdir(path) if isinstance(path, unicode): items = [unicode(String(i).toString()) for i in items] return items os.listdir = listdir
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import random from robot.model import SuiteVisitor class Randomizer(SuiteVisitor): def __init__(self, randomize_suites=True, randomize_tests=True): self.randomize_suites = randomize_suites self.randomize_tests = randomize_tests def start_suite(self, suite): if not self.randomize_suites and not self.randomize_tests: return False if self.randomize_suites: suite.suites = self._shuffle(suite.suites) if self.randomize_tests: suite.tests = self._shuffle(suite.tests) def _shuffle(self, item_list): items = list(item_list) random.shuffle(items) return items def visit_test(self, test): pass def visit_keyword(self, kw): pass
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from java.lang import Byte, Short, Integer, Long, Boolean, Float, Double from robot.variables import contains_var from robot.utils import is_list_like class JavaArgumentCoercer(object): def __init__(self, signatures, argspec): self._argspec = argspec self._coercers = CoercerFinder().find_coercers(signatures) self._varargs_handler = VarargsHandler(argspec) def coerce(self, arguments, named, dryrun=False): arguments = self._varargs_handler.handle(arguments) arguments = [c.coerce(a, dryrun) for c, a in zip(self._coercers, arguments)] if self._argspec.kwargs: arguments.append(named) return arguments class CoercerFinder(object): def find_coercers(self, signatures): return [self._get_coercer(types, position) for position, types in self._parse_types(signatures)] def _parse_types(self, signatures): types = {} for sig in signatures: for index, arg in enumerate(sig.args): types.setdefault(index + 1, []).append(arg) return sorted(types.items()) def _get_coercer(self, types, position): possible = [BooleanCoercer(position), IntegerCoercer(position), FloatCoercer(position), NullCoercer(position)] coercers = [self._get_coercer_for_type(t, possible) for t in types] if self._coercers_conflict(*coercers): return NullCoercer() return coercers[0] def _get_coercer_for_type(self, type, coercers): for coercer in coercers: if coercer.handles(type): return coercer def _coercers_conflict(self, first, *rest): return not all(coercer is first for coercer in rest) class _Coercer(object): _name = '' _types = [] _primitives = [] def __init__(self, position=None): self._position = position def handles(self, type): return type in self._types or type.__name__ in self._primitives def coerce(self, argument, dryrun=False): if not isinstance(argument, basestring) \ or (dryrun and contains_var(argument)): return argument try: return self._coerce(argument) except ValueError: raise ValueError('Argument at position %d cannot be coerced to %s.' % (self._position, self._name)) def _coerce(self, argument): raise NotImplementedError class BooleanCoercer(_Coercer): _name = 'boolean' _types = [Boolean] _primitives = ['boolean'] def _coerce(self, argument): try: return {'false': False, 'true': True}[argument.lower()] except KeyError: raise ValueError class IntegerCoercer(_Coercer): _name = 'integer' _types = [Byte, Short, Integer, Long] _primitives = ['byte', 'short', 'int', 'long'] def _coerce(self, argument): return int(argument) class FloatCoercer(_Coercer): _name = 'floating point number' _types = [Float, Double] _primitives = ['float', 'double'] def _coerce(self, argument): return float(argument) class NullCoercer(_Coercer): def handles(self, argument): return True def _coerce(self, argument): return argument class VarargsHandler(object): def __init__(self, argspec): self._index = argspec.minargs if argspec.varargs else -1 def handle(self, arguments): if self._index > -1 and not self._passing_list(arguments): arguments[self._index:] = [arguments[self._index:]] return arguments def _passing_list(self, arguments): return self._correct_count(arguments) and is_list_like(arguments[-1]) def _correct_count(self, arguments): return len(arguments) == self._index + 1
Python
# 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 if sys.platform.startswith('java'): from java.lang import Class from java.util import List, Map from robot.errors import DataError from robot.variables import is_list_var, is_scalar_var from .argumentspec import ArgumentSpec class _ArgumentParser(object): def __init__(self, type='Keyword'): self._type = type def parse(self, source, name=None): return ArgumentSpec(name, self._type, *self._get_arg_spec(source)) def _get_arg_spec(self, source): raise NotImplementedError class PythonArgumentParser(_ArgumentParser): def _get_arg_spec(self, handler): args, varargs, kwargs, defaults = inspect.getargspec(handler) if inspect.ismethod(handler): args = args[1:] # drop 'self' defaults = list(defaults) if defaults else [] return args, defaults, varargs, kwargs class JavaArgumentParser(_ArgumentParser): def _get_arg_spec(self, signatures): if not signatures: return self._no_signatures_arg_spec() elif len(signatures) == 1: return self._single_signature_arg_spec(signatures[0]) else: return self._multi_signature_arg_spec(signatures) def _no_signatures_arg_spec(self): # Happens when a class has no public constructors return self._format_arg_spec() def _single_signature_arg_spec(self, signature): varargs, kwargs = self._get_varargs_and_kwargs_support(signature.args) positional = len(signature.args) - int(varargs) - int(kwargs) return self._format_arg_spec(positional, varargs=varargs, kwargs=kwargs) def _get_varargs_and_kwargs_support(self, args): if not args: return False, False if self._is_varargs_type(args[-1]): return True, False if not self._is_kwargs_type(args[-1]): return False, False if len(args) > 1 and self._is_varargs_type(args[-2]): return True, True return False, True def _is_varargs_type(self, arg): return arg is List or isinstance(arg, Class) and arg.isArray() def _is_kwargs_type(self, arg): return arg is Map def _multi_signature_arg_spec(self, signatures): mina = maxa = len(signatures[0].args) for sig in signatures[1:]: argc = len(sig.args) mina = min(argc, mina) maxa = max(argc, maxa) return self._format_arg_spec(maxa, maxa-mina) def _format_arg_spec(self, positional=0, defaults=0, varargs=False, kwargs=False): positional = ['arg%d' % (i+1) for i in range(positional)] defaults = [''] * defaults varargs = '*varargs' if varargs else None kwargs = '**kwargs' if kwargs else None supports_named = False return positional, defaults, varargs, kwargs, supports_named class _ArgumentSpecParser(_ArgumentParser): def parse(self, argspec, name=None): result = ArgumentSpec(name, self._type) for arg in argspec: if result.kwargs: raise DataError('Only last argument can be kwargs.') if self._is_kwargs(arg): self._add_kwargs(arg, result) continue if result.varargs: raise DataError('Positional argument after varargs.') if self._is_varargs(arg): self._add_varargs(arg, result) continue if '=' in arg: self._add_arg_with_default(arg, result) continue if result.defaults: raise DataError('Non-default argument after default arguments.') self._add_arg(arg, result) return result def _is_kwargs(self, arg): raise NotImplementedError def _add_kwargs(self, kwargs, result): result.kwargs = self._format_kwargs(kwargs) def _format_kwargs(self, kwargs): raise NotImplementedError def _is_varargs(self, arg): raise NotImplementedError def _add_varargs(self, varargs, result): result.varargs = self._format_varargs(varargs) def _format_varargs(self, varargs): raise NotImplementedError def _add_arg_with_default(self, arg, result): arg, default = arg.split('=', 1) self._add_arg(arg, result) result.defaults.append(default) def _add_arg(self, arg, result): result.positional.append(self._format_arg(arg)) def _format_arg(self, arg): return arg class DynamicArgumentParser(_ArgumentSpecParser): def _is_kwargs(self, arg): return arg.startswith('**') def _format_kwargs(self, kwargs): return kwargs[2:] def _is_varargs(self, arg): return arg.startswith('*') and not self._is_kwargs(arg) def _format_varargs(self, varargs): return varargs[1:] class UserKeywordArgumentParser(_ArgumentSpecParser): def _is_kwargs(self, arg): return False def _is_varargs(self, arg): return is_list_var(arg) def _format_varargs(self, varargs): return varargs[2:-1] def _format_arg(self, arg): if not is_scalar_var(arg): raise DataError("Invalid argument '%s'." % arg) return arg[2:-1]
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.errors import DataError from robot.utils import plural_or_not from robot.variables import is_list_var class ArgumentValidator(object): def __init__(self, argspec): self._argspec = argspec def validate(self, positional, named, dryrun=False): if dryrun and any(is_list_var(arg) for arg in positional): return self._validate_no_multiple_values(positional, named, self._argspec) self._validate_limits(positional, named, self._argspec) self._validate_no_mandatory_missing(positional, named, self._argspec) def _validate_limits(self, positional, named, spec): count = len(positional) + self._named_positionals(named, spec) if not spec.minargs <= count <= spec.maxargs: self._raise_wrong_count(count, spec) def _named_positionals(self, named, spec): if not spec.supports_named: return 0 return sum(1 for n in named if n in spec.positional) def _raise_wrong_count(self, count, spec): minend = plural_or_not(spec.minargs) if spec.minargs == spec.maxargs: expected = '%d argument%s' % (spec.minargs, minend) elif not spec.varargs: expected = '%d to %d arguments' % (spec.minargs, spec.maxargs) else: expected = 'at least %d argument%s' % (spec.minargs, minend) if spec.kwargs: expected = expected.replace('argument', 'non-keyword argument') raise DataError("%s '%s' expected %s, got %d." % (spec.type, spec.name, expected, count)) def _validate_no_multiple_values(self, positional, named, spec): for name in spec.positional[:len(positional)]: if name in named and spec.supports_named: raise DataError("%s '%s' got multiple values for argument '%s'." % (spec.type, spec.name, name)) def _validate_no_mandatory_missing(self, positional, named, spec): for name in spec.positional[len(positional):spec.minargs]: if name not in named: raise DataError("%s '%s' missing value for argument '%s'." % (spec.type, spec.name, name))
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.errors import DataError from robot.utils import is_dict_like from .argumentvalidator import ArgumentValidator class ArgumentResolver(object): def __init__(self, argspec, resolve_named=True, resolve_variables_until=None, dict_to_kwargs=False): self._named_resolver = NamedArgumentResolver(argspec) \ if resolve_named else NullNamedArgumentResolver() self._variable_replacer = VariableReplacer(resolve_variables_until) self._dict_to_kwargs = DictToKwargs(argspec, dict_to_kwargs) self._argument_validator = ArgumentValidator(argspec) def resolve(self, arguments, variables=None): positional, named = self._named_resolver.resolve(arguments) positional, named = self._variable_replacer.replace(positional, named, variables) positional, named = self._dict_to_kwargs.handle(positional, named) self._argument_validator.validate(positional, named, dryrun=not variables) return positional, named class NamedArgumentResolver(object): def __init__(self, argspec): self._argspec = argspec def resolve(self, arguments): positional = [] named = {} for arg in arguments: if self._is_named(arg): self._add_named(arg, named) elif named: self._raise_positional_after_named() else: positional.append(arg) return positional, named def _is_named(self, arg): if not isinstance(arg, basestring) or '=' not in arg: return False name = arg.split('=')[0] if self._is_escaped(name): return False if not self._argspec.supports_named: return self._argspec.kwargs return name in self._argspec.positional or self._argspec.kwargs def _is_escaped(self, name): return name.endswith('\\') def _add_named(self, arg, named): name, value = arg.split('=', 1) name = self._convert_to_str_if_possible(name) if name in named: self._raise_multiple_values(name) named[name] = value def _convert_to_str_if_possible(self, name): # Python 2.5 doesn't handle Unicode kwargs at all, so we will try to # support it by converting to str if possible try: return str(name) except UnicodeError: return name def _raise_multiple_values(self, name): raise DataError("%s '%s' got multiple values for argument '%s'." % (self._argspec.type, self._argspec.name, name)) def _raise_positional_after_named(self): raise DataError("%s '%s' got positional argument after named arguments." % (self._argspec.type, self._argspec.name)) class NullNamedArgumentResolver(object): def resolve(self, arguments): return arguments, {} class DictToKwargs(object): def __init__(self, argspec, enabled=False): self._maxargs = argspec.maxargs self._enabled = enabled and bool(argspec.kwargs) def handle(self, positional, named): if self._enabled and self._extra_arg_has_kwargs(positional, named): named = positional.pop() return positional, named def _extra_arg_has_kwargs(self, positional, named): if named or len(positional) != self._maxargs + 1: return False return is_dict_like(positional[-1], allow_java=True) class VariableReplacer(object): def __init__(self, resolve_until=None): self._resolve_until = resolve_until def replace(self, positional, named, variables=None): # `variables` is None in dry-run mode and when using Libdoc if variables: positional = variables.replace_list(positional, self._resolve_until) named = dict((name, variables.replace_scalar(value)) for name, value in named.items()) else: positional = list(positional) return positional, named
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 .argumentmapper import ArgumentMapper from .argumentparser import (PythonArgumentParser, UserKeywordArgumentParser, DynamicArgumentParser, JavaArgumentParser) from .argumentresolver import ArgumentResolver from .argumentvalidator import ArgumentValidator if sys.platform.startswith('java'): from .javaargumentcoercer import JavaArgumentCoercer else: JavaArgumentCoercer = lambda *args: None
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 ArgumentMapper(object): def __init__(self, argspec): self._argspec = argspec def map(self, positional, named, variables=None, prune_trailing_defaults=False): template = KeywordCallTemplate(self._argspec, variables) template.fill_positional(positional) template.fill_named(named) if prune_trailing_defaults: template.prune_trailing_defaults() template.fill_defaults() return template.args, template.kwargs class KeywordCallTemplate(object): def __init__(self, argspec, variables): defaults = argspec.defaults if variables: defaults = variables.replace_list(defaults) self._positional = argspec.positional self._supports_kwargs = bool(argspec.kwargs) self._supports_named = argspec.supports_named self.args = [None] * argspec.minargs + [Default(d) for d in defaults] self.kwargs = {} def fill_positional(self, positional): self.args[:len(positional)] = positional def fill_named(self, named): for name, value in named.items(): if name in self._positional and self._supports_named: index = self._positional.index(name) self.args[index] = value elif self._supports_kwargs: self.kwargs[name] = value else: raise ValueError("Non-existing named argument '%s'" % name) def prune_trailing_defaults(self): while self.args and isinstance(self.args[-1], Default): self.args.pop() def fill_defaults(self): self.args = [arg if not isinstance(arg, Default) else arg.value for arg in self.args] class Default(object): def __init__(self, value): self.value = value
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 class ArgumentSpec(object): def __init__(self, name, type='Keyword', positional=None, defaults=None, varargs=None, kwargs=None, supports_named=True): self.name = name self.type = type self.positional = positional or [] self.defaults = defaults or [] self.varargs = varargs self.kwargs = kwargs self.supports_named = supports_named @property def minargs(self): return len(self.positional) - len(self.defaults) @property def maxargs(self): return len(self.positional) if not self.varargs else sys.maxint
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement from robot import utils from robot.errors import DataError from robot.variables import is_list_var from .arguments import (PythonArgumentParser, JavaArgumentParser, DynamicArgumentParser, ArgumentResolver, ArgumentMapper, JavaArgumentCoercer) from .keywords import Keywords, Keyword from .outputcapture import OutputCapturer from .runkwregister import RUN_KW_REGISTER from .signalhandler import STOP_SIGNAL_MONITOR def Handler(library, name, method): if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name): return _RunKeywordHandler(library, name, method) if utils.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, docgetter=None): Init = _PythonInitHandler if not utils.is_java_init(method) else _JavaInitHandler return Init(library, '__init__', method, docgetter) class _RunnableHandler(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) self._handler_name = handler_name self._method = self._get_initial_handler(library, handler_name, handler_method) self._argument_resolver = self._get_argument_resolver(self.arguments) def _parse_arguments(self, handler_method): raise NotImplementedError def _get_argument_resolver(self, argspec): return ArgumentResolver(argspec) def _get_initial_handler(self, library, name, method): if library.scope == 'GLOBAL': return self._get_global_handler(method, name) return None def resolve_arguments(self, args, variables=None): return self._argument_resolver.resolve(args, variables) @property def doc(self): return self._doc @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 '' @property def libname(self): return self.library.name 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): if self.longname == 'BuiltIn.Import Library': return self._run(context, args) self.resolve_arguments(args) return None def _run(self, context, args): positional, named = \ self.resolve_arguments(args, context.variables) context.output.trace(lambda: self._log_args(positional, named)) runner = self._runner_for(self._current_handler(), context, positional, named, self._get_timeout(context)) return self._run_with_output_captured_and_signal_monitor(runner, context) def _log_args(self, positional, named): positional = [utils.safe_repr(arg) for arg in positional] named = ['%s=%s' % (utils.unic(name), utils.safe_repr(value)) for name, value in named.items()] return 'Arguments: [ %s ]' % ' | '.join(positional + named) def _runner_for(self, handler, context, positional, named, timeout): if timeout and timeout.active: context.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): with OutputCapturer(): return self._run_with_signal_monitoring(runner, context) def _run_with_signal_monitoring(self, runner, context): try: STOP_SIGNAL_MONITOR.start_running_keyword(context.in_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, context): timeouts = self._get_timeouts(context) return None if not timeouts else min(timeouts) def _get_timeouts(self, context): timeouts = [kw.timeout for kw in context.keywords] if context.test and not context.in_test_teardown: timeouts.append(context.test.timeout) return [timeout for timeout in timeouts if timeout] class _PythonHandler(_RunnableHandler): def __init__(self, library, handler_name, handler_method): _RunnableHandler.__init__(self, library, handler_name, handler_method) self._doc = utils.getdoc(handler_method) def _parse_arguments(self, handler_method): return PythonArgumentParser().parse(handler_method, self.longname) class _JavaHandler(_RunnableHandler): def __init__(self, library, handler_name, handler_method): _RunnableHandler.__init__(self, library, handler_name, handler_method) signatures = self._get_signatures(handler_method) self._arg_coercer = JavaArgumentCoercer(signatures, self.arguments) def _get_argument_resolver(self, argspec): return ArgumentResolver(argspec, dict_to_kwargs=True) def _parse_arguments(self, handler_method): signatures = self._get_signatures(handler_method) return JavaArgumentParser().parse(signatures, self.longname) def _get_signatures(self, handler): code_object = getattr(handler, 'im_func', handler) return code_object.argslist[:code_object.nargs] def resolve_arguments(self, args, variables=None): positional, named = self._argument_resolver.resolve(args, variables) arguments = self._arg_coercer.coerce(positional, named, dryrun=not variables) return arguments, {} class _DynamicHandler(_RunnableHandler): def __init__(self, library, handler_name, dynamic_method, doc='', argspec=None): self._argspec = argspec _RunnableHandler.__init__(self, library, handler_name, dynamic_method.method) self._run_keyword_method_name = dynamic_method.name self._doc = doc is not None and utils.unic(doc) or '' self._supports_kwargs = dynamic_method.supports_kwargs if argspec and argspec[-1].startswith('**'): if not self._supports_kwargs: raise DataError("Too few '%s' method parameters for **kwargs " "support." % self._run_keyword_method_name) def _parse_arguments(self, handler_method): return DynamicArgumentParser().parse(self._argspec, self.longname) def resolve_arguments(self, arguments, variables=None): positional, named = _RunnableHandler.resolve_arguments(self, arguments, variables) mapper = ArgumentMapper(self.arguments) arguments, kwargs = mapper.map(positional, named, prune_trailing_defaults=True) return arguments, kwargs 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(*positional, **kwargs): if self._supports_kwargs: return runner(name, positional, kwargs) else: return runner(name, positional) 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 _get_argument_resolver(self, argspec): resolve_until = self._get_args_to_process() return ArgumentResolver(argspec, resolve_named=False, resolve_variables_until=resolve_until) def _get_args_to_process(self): return RUN_KW_REGISTER.get_args_to_process(self.library.orig_name, self.name) def _get_timeout(self, namespace): return None def _dry_run(self, context, args): _RunnableHandler._dry_run(self, context, args) keywords = self._get_runnable_dry_run_keywords(context, args) keywords.run(context) def _get_runnable_dry_run_keywords(self, context, args): keywords = Keywords([]) for keyword in self._get_dry_run_keywords(args): if self._variable_syntax_in(keyword.name, context): continue keywords.add_keyword(keyword) return keywords 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 def _get_dry_run_keywords(self, args): if self._handler_name == 'run_keyword_if': return list(self._get_run_kw_if_keywords(args)) if self._handler_name == 'run_keywords': return list(self._get_run_kws_keywords(args)) if 'name' in self.arguments.positional and self._get_args_to_process() > 0: return self._get_default_run_kw_keywords(args) return [] def _get_run_kw_if_keywords(self, given_args): for kw_call in self._get_run_kw_if_calls(given_args): if kw_call: yield Keyword(kw_call[0], kw_call[1:]) def _get_run_kw_if_calls(self, given_args): while 'ELSE IF' in given_args: kw_call, given_args = self._split_run_kw_if_args(given_args, 'ELSE IF', 2) yield kw_call if 'ELSE' in given_args: kw_call, else_call = self._split_run_kw_if_args(given_args, 'ELSE', 1) yield kw_call yield else_call elif self._validate_kw_call(given_args): expr, kw_call = given_args[0], given_args[1:] if not is_list_var(expr): yield kw_call def _split_run_kw_if_args(self, given_args, control_word, required_after): index = list(given_args).index(control_word) expr_and_call = given_args[:index] remaining = given_args[index+1:] if not (self._validate_kw_call(expr_and_call) and self._validate_kw_call(remaining, required_after)): raise DataError("Invalid 'Run Keyword If' usage.") if is_list_var(expr_and_call[0]): return (), remaining return expr_and_call[1:], remaining def _validate_kw_call(self, kw_call, min_length=2): if len(kw_call) >= min_length: return True return any(is_list_var(item) for item in kw_call) def _get_run_kws_keywords(self, given_args): for kw_call in self._get_run_kws_calls(given_args): yield Keyword(kw_call[0], kw_call[1:]) def _get_run_kws_calls(self, given_args): if 'AND' not in given_args: for kw_call in given_args: yield [kw_call,] else: while 'AND' in given_args: index = list(given_args).index('AND') kw_call, given_args = given_args[:index], given_args[index + 1:] yield kw_call if given_args: yield given_args def _get_default_run_kw_keywords(self, given_args): index = list(self.arguments.positional).index('name') return [Keyword(given_args[index], given_args[index+1:])] 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,) + tuple(args)) @property def longname(self): return self.name class _DynamicRunKeywordHandler(_DynamicHandler, _RunKeywordHandler): _parse_arguments = _RunKeywordHandler._parse_arguments _get_timeout = _RunKeywordHandler._get_timeout _get_argument_resolver = _RunKeywordHandler._get_argument_resolver class _PythonInitHandler(_PythonHandler): def __init__(self, library, handler_name, handler_method, docgetter): _PythonHandler.__init__(self, library, handler_name, handler_method) self._docgetter = docgetter @property def doc(self): if self._docgetter: self._doc = self._docgetter() or self._doc self._docgetter = None return self._doc def _parse_arguments(self, handler_method): parser = PythonArgumentParser(type='Test Library') return parser.parse(handler_method, self.library.name) class _JavaInitHandler(_JavaHandler): def __init__(self, library, handler_name, handler_method, docgetter): _JavaHandler.__init__(self, library, handler_name, handler_method) self._docgetter = docgetter @property def doc(self): if self._docgetter: self._doc = self._docgetter() or self._doc self._docgetter = None return self._doc def _parse_arguments(self, handler_method): parser = JavaArgumentParser(type='Test Library') signatures = self._get_signatures(handler_method) return parser.parse(signatures, self.library.name)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.errors import DataError from robot.utils import get_error_message, unic, is_java_method from .arguments import JavaArgumentParser, PythonArgumentParser def no_dynamic_method(*args): pass class _DynamicMethod(object): _underscore_name = NotImplemented def __init__(self, lib): self.method = self._get_method(lib) def _get_method(self, lib): for name in self._underscore_name, self._camelCaseName: method = getattr(lib, name, None) if callable(method): return method return no_dynamic_method @property def _camelCaseName(self): tokens = self._underscore_name.split('_') return ''.join([tokens[0]] + [t.capitalize() for t in tokens[1:]]) @property def name(self): return self.method.__name__ def __call__(self, *args): try: return self._handle_return_value(self.method(*args)) except: raise DataError("Calling dynamic method '%s' failed: %s" % (self.method.__name__, get_error_message())) def _handle_return_value(self, value): raise NotImplementedError def _to_string(self, value): if not isinstance(value, basestring): raise DataError('Return value must be string.') return value if isinstance(value, unicode) else unic(value, 'UTF-8') def _to_list_of_strings(self, value): try: return [self._to_string(v) for v in value] except (TypeError, DataError): raise DataError('Return value must be list of strings.') def __nonzero__(self): return self.method is not no_dynamic_method class GetKeywordNames(_DynamicMethod): _underscore_name = 'get_keyword_names' def _handle_return_value(self, value): return self._to_list_of_strings(value or []) class RunKeyword(_DynamicMethod): _underscore_name = 'run_keyword' @property def supports_kwargs(self): if is_java_method(self.method): return self._supports_java_kwargs(self.method) return self._supports_python_kwargs(self.method) def _supports_python_kwargs(self, method): spec = PythonArgumentParser().parse(method) return len(spec.positional) == 3 def _supports_java_kwargs(self, method): func = self.method.im_func if hasattr(method, 'im_func') else method signatures = func.argslist[:func.nargs] spec = JavaArgumentParser().parse(signatures) return (self._java_single_signature_kwargs(spec) or self._java_multi_signature_kwargs(spec)) def _java_single_signature_kwargs(self, spec): return len(spec.positional) == 1 and spec.varargs and spec.kwargs def _java_multi_signature_kwargs(self, spec): return len(spec.positional) == 3 and not (spec.varargs or spec.kwargs) class GetKeywordDocumentation(_DynamicMethod): _underscore_name = 'get_keyword_documentation' def _handle_return_value(self, value): return self._to_string(value or '') class GetKeywordArguments(_DynamicMethod): _underscore_name = 'get_keyword_arguments' def __init__(self, lib): _DynamicMethod.__init__(self, lib) self._supports_kwargs = RunKeyword(lib).supports_kwargs def _handle_return_value(self, value): if value is None: if self._supports_kwargs: return ['*varargs', '**kwargs'] return ['*varargs'] return self._to_list_of_strings(value)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement from robot import model from robot.conf import RobotSettings from robot.output import LOGGER, Output, pyloggingconf from robot.utils import setter from robot.variables import init_global_variables from .namespace import IMPORTER from .randomizer import Randomizer from .runner import Runner from .signalhandler import STOP_SIGNAL_MONITOR # TODO: This module should be turned into a package with submodules. # No time for that prior to 2.8, but it ought to be safe also in 2.8.x. # Important to check that references in API docs don't break. class Keyword(model.Keyword): """Running model for single keyword.""" __slots__ = ['assign'] message_class = None # TODO: Remove from base model? def __init__(self, name='', args=(), assign=(), type='kw'): model.Keyword.__init__(self, name=name, args=args, type=type) #: Variables to be assigned. self.assign = assign def is_for_loop(self): return False def is_comment(self): return False @property def keyword(self): """Name of the keyword.""" return self.name class ForLoop(Keyword): __slots__ = ['range'] keyword_class = Keyword def __init__(self, vars, items, range): Keyword.__init__(self, assign=vars, args=items, type='for') self.range = range @property def vars(self): return self.assign @property def items(self): return self.args def is_for_loop(self): return True @property def steps(self): return self.keywords class TestCase(model.TestCase): """Running model for single test case.""" __slots__ = ['template'] keyword_class = Keyword def __init__(self, name='', doc='', tags=None, timeout=None, template=None): model.TestCase.__init__(self, name, doc, tags, timeout) #: Name of the keyword that has been used as template #: when building the test. `None` if no is template used. self.template = template @setter def timeout(self, timeout): """Timeout limit of the test case as an instance of :class:`~.Timeout. """ return Timeout(*timeout) if timeout else None class TestSuite(model.TestSuite): """Running model for single test suite.""" __slots__ = [] test_class = TestCase keyword_class = Keyword def __init__(self, name='', doc='', metadata=None, source=None): model.TestSuite.__init__(self, name, doc, metadata, source) #: Imports the suite contains. self.imports = [] #: User keywords defined in the same file as the suite. #: **Likely to change or to be removed.** self.user_keywords = [] #: Variables defined in the same file as the suite. #: **Likely to change or to be removed.** self.variables = [] @setter def imports(self, imports): return model.Imports(self.source, imports) @setter def user_keywords(self, keywords): return model.ItemList(UserKeyword, items=keywords) @setter def variables(self, variables): return model.ItemList(Variable, {'source': self.source}, items=variables) def configure(self, randomize_suites=False, randomize_tests=False, **options): model.TestSuite.configure(self, **options) self.randomize(randomize_suites, randomize_tests) def randomize(self, suites=True, tests=True): """Randomizes the order of suites and/or tests, recursively.""" self.visit(Randomizer(suites, tests)) def run(self, settings=None, **options): """Executes the suite based based the given ``settings`` or ``options``. :param settings: :class:`~robot.conf.settings.RobotSettings` object to configure test execution. :param options: Used to construct new :class:`~robot.conf.settings.RobotSettings` object if ``settings`` are not given. :return: :class:`~robot.result.executionresult.Result` object with information about executed suites and tests. If ``options`` are used, their names are the same as long command line options except without hyphens, and they also have the same semantics. Options that can be given on the command line multiple times can be passed as lists like ``variable=['VAR1:value1', 'VAR2:value2']``. If such an option is used only once, it can be given also as a single string like ``variable='VAR:value'``. To capture stdout and/or stderr streams, pass open file objects in as special keyword arguments `stdout` and `stderr`, respectively. Note that this works only in version 2.8.4 and newer. Only options related to the actual test execution have an effect. For example, options related to selecting test cases or creating logs and reports are silently ignored. The output XML generated as part of the execution can be configured, though. This includes disabling it with ``output=None``. Example:: stdout = StringIO() result = suite.run(variable='EXAMPLE:value', critical='regression', output='example.xml', exitonfailure=True, stdout=stdout) print result.return_code To save memory, the returned :class:`~robot.result.executionresult.Result` object does not have any information about the executed keywords. If that information is needed, the created output XML file needs to be read using the :class:`~robot.result.resultbuilder.ExecutionResult` factory method. See the :mod:`package level <robot.running>` documentation for more examples, including how to construct executable test suites and how to create logs and reports based on the execution results. See the :func:`robot.run <robot.run.run>` function for a higher-level API for executing tests in files or directories. """ if not settings: settings = RobotSettings(options) LOGGER.register_console_logger(**settings.console_logger_config) with STOP_SIGNAL_MONITOR: IMPORTER.reset() pyloggingconf.initialize(settings['LogLevel']) init_global_variables(settings) output = Output(settings) runner = Runner(output, settings) self.visit(runner) output.close(runner.result) return runner.result class Variable(object): def __init__(self, name, value, source=None): # TODO: check name and value self.name = name self.value = value self.source = source def report_invalid_syntax(self, message, level='ERROR'): LOGGER.write("Error in file '%s': Setting variable '%s' failed: %s" % (self.source or '<unknown>', self.name, message), level) class Timeout(object): def __init__(self, value, message=None): self.value = value self.message = message def __str__(self): return self.value class UserKeyword(object): # TODO: In 2.9: # - Teardown should be handled as a keyword like with tests and suites. # - Timeout should be handled consistently with tests. # - Also resource files should use these model objects. def __init__(self, name, args=(), doc='', return_=None, timeout=None, teardown=None): self.name = name self.args = args self.doc = doc self.return_ = return_ or () self.teardown = None self.timeout = timeout self.teardown = teardown self.keywords = [] @setter def keywords(self, keywords): return model.ItemList(Keyword, items=keywords) # Compatibility with parsing model. Should be removed in 2.9. @property def steps(self): return self.keywords
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.errors import DataError class UserErrorHandler: """Created if creating handlers fail -- running raises DataError. The idea is not to raise DataError at processing time and prevent all tests in affected test case file from executing. Instead UserErrorHandler is created and if it is ever run DataError is raised then. """ type = 'error' def __init__(self, name, error): self.name = self.longname = name self.doc = self.shortdoc = '' self.error = error self.timeout = '' def init_keyword(self, varz): pass def run(self, *args): raise DataError(self.error)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 PassExecution class _ExecutionStatus(object): def __init__(self, parent=None): self.parent = parent self.setup_failure = None self.test_failure = None self.teardown_failure = None self._teardown_allowed = False self.exiting_on_failure = parent.exiting_on_failure if parent else False self.exiting_on_fatal = parent.exiting_on_fatal if parent else False self.skip_teardown_on_exit_mode = parent.skip_teardown_on_exit_mode if parent else False def setup_executed(self, failure=None): if failure and not isinstance(failure, PassExecution): self.setup_failure = unicode(failure) self._handle_possible_fatal(failure) self._teardown_allowed = True def teardown_executed(self, failure=None): if failure and not isinstance(failure, PassExecution): self.teardown_failure = unicode(failure) self._handle_possible_fatal(failure) @property def teardown_allowed(self): if self.skip_teardown_on_exit_mode and (self.exiting_on_failure or self.exiting_on_fatal): return False return self._teardown_allowed @property def failures(self): return bool(self._parent_failures() or self._my_failures()) def _parent_failures(self): return self.parent and self.parent.failures def _my_failures(self): return bool(self.setup_failure or self.teardown_failure or self.test_failure or self.exiting_on_failure or self.exiting_on_fatal) @property def status(self): return 'FAIL' if self.failures else 'PASS' @property def message(self): if self._my_failures(): return self._my_message() if self._parent_failures(): return self._parent_message() return '' def _my_message(self): raise NotImplementedError def _parent_message(self): return ParentMessage(self.parent).message def _handle_possible_fatal(self, failure): if getattr(failure, 'exit', False): if self.parent: self.parent.fatal_failure() self.exiting_on_fatal = True class SuiteStatus(_ExecutionStatus): def __init__(self, parent, exit_on_failure_mode=False, skip_teardown_on_exit_mode=False): _ExecutionStatus.__init__(self, parent) self.exit_on_failure_mode = exit_on_failure_mode self.skip_teardown_on_exit_mode = skip_teardown_on_exit_mode def critical_failure(self): if self.exit_on_failure_mode: self.exiting_on_failure = True if self.parent: self.parent.critical_failure() def fatal_failure(self): self.exiting_on_fatal = True if self.parent: self.parent.fatal_failure() def _my_message(self): return SuiteMessage(self).message class TestStatus(_ExecutionStatus): def __init__(self, suite_status): _ExecutionStatus.__init__(self, suite_status) def test_failed(self, failure, critical): self.test_failure = unicode(failure) if critical: self.parent.critical_failure() self.exiting_on_failure = self.parent.exit_on_failure_mode self._handle_possible_fatal(failure) def _my_message(self): return TestMessage(self).message class _Message(object): setup_message = NotImplemented teardown_message = NotImplemented also_teardown_message = NotImplemented def __init__(self, status): self.setup_failure = status.setup_failure self.test_failure = status.test_failure or '' self.teardown_failure = status.teardown_failure @property def message(self): msg = self._get_message_before_teardown() return self._get_message_after_teardown(msg) def _get_message_before_teardown(self): if self.setup_failure: return self.setup_message % self.setup_failure return self.test_failure def _get_message_after_teardown(self, msg): if not self.teardown_failure: return msg if not msg: return self.teardown_message % self.teardown_failure return self.also_teardown_message % (msg, self.teardown_failure) class TestMessage(_Message): setup_message = 'Setup failed:\n%s' teardown_message = 'Teardown failed:\n%s' also_teardown_message = '%s\n\nAlso teardown failed:\n%s' exit_on_fatal_message = 'Test execution stopped due to a fatal error.' exit_on_failure_message = \ 'Critical failure occurred and exit-on-failure mode is in use.' def __init__(self, status): _Message.__init__(self, status) self.exiting_on_failure = status.exiting_on_failure self.exiting_on_fatal = status.exiting_on_fatal @property def message(self): message = super(TestMessage, self).message if message: return message if self.exiting_on_failure: return self.exit_on_failure_message if self.exiting_on_fatal: return self.exit_on_fatal_message return '' class SuiteMessage(_Message): setup_message = 'Suite setup failed:\n%s' teardown_message = 'Suite teardown failed:\n%s' also_teardown_message = '%s\n\nAlso suite teardown failed:\n%s' class ParentMessage(SuiteMessage): setup_message = 'Parent suite setup failed:\n%s' teardown_message = 'Parent suite teardown failed:\n%s' also_teardown_message = '%s\n\nAlso parent suite teardown failed:\n%s' def __init__(self, status): while status.parent and status.parent.failures: status = status.parent SuiteMessage.__init__(self, status)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.errors import DataError class BaseLibrary: def get_handler(self, name): try: return self.handlers[name] except KeyError: raise DataError("No keyword handler with name '%s' found" % name) def has_handler(self, name): return name in self.handlers def __len__(self): return len(self.handlers)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import threading class Thread(threading.Thread): """A subclass of threading.Thread, with a stop() method. Original version posted by Connelly Barnes to python-list and available at http://mail.python.org/pipermail/python-list/2004-May/219465.html This version mainly has kill() changed to stop() to match java.lang.Thread. This is a hack but seems to be the best way the get this done. Only used in Python because in Jython we can use java.lang.Thread. """ def __init__(self, runner, name=None): threading.Thread.__init__(self, target=runner, name=name) self._stopped = False def start(self): self.__run_backup = self.run self.run = self.__run threading.Thread.start(self) def stop(self): self._stopped = True def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self._globaltrace) self.__run_backup() self.run = self.__run_backup def _globaltrace(self, frame, why, arg): if why == 'call': return self._localtrace else: return None def _localtrace(self, frame, why, arg): if self._stopped: if why == 'line': raise SystemExit() return self._localtrace
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from threading import Event from robot.errors import TimeoutError if sys.platform.startswith('java'): from java.lang import Thread, Runnable else: from .stoppablethread import Thread Runnable = object TIMEOUT_THREAD_NAME = 'RobotFrameworkTimeoutThread' class ThreadedRunner(Runnable): def __init__(self, runnable): self._runnable = runnable self._notifier = Event() self._result = None self._error = None self._traceback = None self._thread = None def run(self): try: self._result = self._runnable() except: self._error, self._traceback = sys.exc_info()[1:] self._notifier.set() __call__ = run def run_in_thread(self, timeout): self._thread = Thread(self, name=TIMEOUT_THREAD_NAME) self._thread.setDaemon(True) self._thread.start() self._notifier.wait(timeout) return self._notifier.isSet() def get_result(self): if self._error: raise self._error, None, self._traceback return self._result def stop_thread(self): self._thread.stop() class Timeout(object): def __init__(self, timeout, error): self._timeout = timeout self._error = error def execute(self, runnable): runner = ThreadedRunner(runnable) if runner.run_in_thread(self._timeout): return runner.get_result() runner.stop_thread() raise TimeoutError(self._error)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 signal import setitimer, signal, SIGALRM, ITIMER_REAL from robot.errors import TimeoutError class Timeout(object): def __init__(self, timeout, error): self._timeout = timeout self._error = error def execute(self, runnable): self._start_timer() try: return runnable() finally: self._stop_timer() def _start_timer(self): signal(SIGALRM, self._raise_timeout_error) setitimer(ITIMER_REAL, self._timeout) def _raise_timeout_error(self, signum, frame): raise TimeoutError(self._error) def _stop_timer(self): setitimer(ITIMER_REAL, 0)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 ctypes import thread import time from threading import Timer from robot.errors import TimeoutError class Timeout(object): def __init__(self, timeout, timeout_error): self._runner_thread_id = thread.get_ident() self._timeout_error = self._create_timeout_error_class(timeout_error) self._timer = Timer(timeout, self._raise_timeout_error) self._timeout_occurred = False def _create_timeout_error_class(self, timeout_error): return type(TimeoutError.__name__, (TimeoutError,), {'__unicode__': lambda self: timeout_error}) def execute(self, runnable): self._start_timer() try: return runnable() finally: self._stop_timer() def _start_timer(self): self._timer.start() def _stop_timer(self): self._timer.cancel() # In case timeout has occurred but the exception has not yet been # thrown we need to do this to ensure that the exception # is not thrown in an unsafe location if self._timeout_occurred: self._cancel_exception() raise self._timeout_error() def _raise_timeout_error(self): self._timeout_occurred = True return_code = self._try_to_raise_timeout_error_in_runner_thread() # return code tells how many threads have been influenced while return_code > 1: # if more than one then cancel and retry self._cancel_exception() time.sleep(0) # yield so that other threads will get time return_code = self._try_to_raise_timeout_error_in_runner_thread() def _try_to_raise_timeout_error_in_runner_thread(self): return ctypes.pythonapi.PyThreadState_SetAsyncExc( self._runner_thread_id, ctypes.py_object(self._timeout_error)) def _cancel_exception(self): ctypes.pythonapi.PyThreadState_SetAsyncExc(self._runner_thread_id, None)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os import time from robot import utils from robot.errors import TimeoutError, DataError, FrameworkError if sys.platform == 'cli': from .timeoutthread import Timeout elif os.name == 'nt': from .timeoutwin import Timeout else: try: # python 2.6 or newer in *nix or mac from .timeoutsignaling import Timeout except ImportError: # python < 2.6 and jython don't have complete signal module from .timeoutthread import Timeout 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 active(self): return self.starttime > 0 def replace_variables(self, variables): try: self.string = variables.replace_string(self.string) if not self: 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 timeout 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 unicode(self).encode('utf-8') def __unicode__(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 __nonzero__(self): return bool(self.string and self.string.upper() != 'NONE') 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()) executable = lambda: runnable(*(args or ()), **(kwargs or {})) return Timeout(timeout, self._timeout_error).execute(executable) def get_message(self): if not self.active: return '%s timeout not active.' % self.type if not self.timed_out(): return '%s timeout %s active. %s seconds left.' \ % (self.type, self.string, self.time_left()) return self._timeout_error @property def _timeout_error(self): if self.message: return self.message return '%s timeout %s exceeded.' % (self.type, self.string) class TestTimeout(_Timeout): type = 'Test' _keyword_timeout_occurred = False def set_keyword_timeout(self, timeout_occurred): if timeout_occurred: self._keyword_timeout_occurred = True def any_timeout_occurred(self): return self.timed_out() or self._keyword_timeout_occurred class KeywordTimeout(_Timeout): type = 'Keyword'
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 from robot.output import LOGGER from robot.utils import decode_output, encode_output class OutputCapturer(object): def __init__(self, library_import=False): self._library_import = library_import 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 __enter__(self): if self._library_import: LOGGER.enable_library_import_logging() return self def __exit__(self, exc_type, exc_value, exc_trace): self._release_and_log() if self._library_import: LOGGER.disable_library_import_logging() return False def _release_and_log(self): stdout, stderr = self._release() if stdout: LOGGER.log_output(stdout) if stderr: LOGGER.log_output(stderr) sys.__stderr__.write(encode_output(stderr+'\n')) def _release(self): stdout = self._python_out.release() + self._java_out.release() stderr = self._python_err.release() + self._java_err.release() return stdout, stderr 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) try: return self._get_value(self._stream) finally: self._stream.close() def _get_value(self, stream): try: return decode_output(stream.getvalue()) except UnicodeError: stream.buf = decode_output(stream.buf) stream.buflist = [decode_output(item) for item in stream.buflist] return stream.getvalue() if not sys.platform.startswith('java'): class JavaCapturer(object): def __init__(self, stdout=True): pass def release(self): return u'' else: from java.io import ByteArrayOutputStream, PrintStream 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-2014 Nokia Solutions and Networks # # 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.utils import NormalizedDict 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] = 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-2014 Nokia Solutions and Networks # # 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 self._orig_sigint = None self._orig_sigterm = None 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): # TODO: Remove start() in favor of __enter__ in RF 2.9. Refactoring # the whole signal handler at that point would be a good idea. self.__enter__() def __enter__(self): if signal: self._orig_sigint = signal.getsignal(signal.SIGINT) self._orig_sigterm = signal.getsignal(signal.SIGTERM) for signum in signal.SIGINT, signal.SIGTERM: self._register_signal_handler(signum) return self def __exit__(self, *exc_info): if signal: signal.signal(signal.SIGINT, self._orig_sigint) signal.signal(signal.SIGTERM, self._orig_sigterm) 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-2014 Nokia Solutions and Networks # # 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 copy from robot import utils from robot.errors import DataError from robot.variables import GLOBAL_VARIABLES, is_scalar_var from robot.output import LOGGER from robot.parsing.settings import Library, Variables, Resource from .usererrorhandler import UserErrorHandler from .userkeyword import UserLibrary from .importer import Importer, ImportCache from .runkwregister import RUN_KW_REGISTER from .handlers import _XTimesHandler from .context import EXECUTION_CONTEXTS STDLIB_NAMES = set(('BuiltIn', 'Collections', 'Dialogs', 'Easter', 'OperatingSystem', 'Process', 'Remote', 'Reserved', 'Screenshot', 'String', 'Telnet', 'XML')) IMPORTER = Importer() class Namespace: _default_libraries = ('BuiltIn', 'Reserved', 'Easter') _deprecated_libraries = {'BuiltIn': 'DeprecatedBuiltIn', 'OperatingSystem': 'DeprecatedOperatingSystem'} _library_import_by_path_endings = ('.py', '.java', '.class', '/', os.sep) def __init__(self, suite, variables, parent_variables, user_keywords, imports): LOGGER.info("Initializing namespace for test suite '%s'" % suite.longname) self.suite = suite self.test = None self.uk_handlers = [] self.variables = _VariableScopes(variables, parent_variables) self.library_search_order = [] self._imports = imports self._user_keywords = UserLibrary(user_keywords) self._testlibs = {} self._imported_resource_files = ImportCache() self._imported_variable_files = ImportCache() def handle_imports(self): self._import_default_libraries() self._handle_imports(self._imports) def _create_variables(self, suite, parent_vars, suite_variables=None): if suite_variables is None: suite_variables = suite.variables return _VariableScopes(suite_variables, parent_vars) def _import_default_libraries(self): for name in self._default_libraries: self.import_library(name) def _handle_imports(self, import_settings): for item in import_settings: try: if not item.name: raise DataError('%s setting requires a name' % item.type) self._import(item) except DataError, err: item.report_invalid_syntax(unicode(err)) def _import(self, import_setting): action = {'Library': self._import_library, 'Resource': self._import_resource, 'Variables': self._import_variables}[import_setting.type] action(import_setting) def import_resource(self, name, overwrite=True): self._import_resource(Resource(None, name), overwrite=overwrite) def _import_resource(self, import_setting, overwrite=False): path = self._resolve_name(import_setting) self._validate_not_importing_init_file(path) if overwrite or path not in self._imported_resource_files: resource = IMPORTER.import_resource(path) self.variables.set_from_variable_table(resource.variable_table, overwrite) self._imported_resource_files[path] \ = UserLibrary(resource.keyword_table.keywords, resource.source) self._handle_imports(resource.setting_table.imports) else: LOGGER.info("Resource file '%s' already imported by suite '%s'" % (path, self.suite.longname)) def _validate_not_importing_init_file(self, path): name = os.path.splitext(os.path.basename(path))[0] if name.lower() == '__init__': raise DataError("Initialization file '%s' cannot be imported as " "a resource file." % path) def import_variables(self, name, args, overwrite=False): self._import_variables(Variables(None, name, args), overwrite) def _import_variables(self, import_setting, overwrite=False): path = self._resolve_name(import_setting) args = self._resolve_args(import_setting) if overwrite or (path, args) not in self._imported_variable_files: self._imported_variable_files.add((path,args)) self.variables.set_from_file(path, args, overwrite) else: msg = "Variable file '%s'" % path if args: msg += " with arguments %s" % utils.seq2str2(args) LOGGER.info("%s already imported by suite '%s'" % (msg, self.suite.longname)) def import_library(self, name, args=None, alias=None): self._import_library(Library(None, name, args=args, alias=alias)) def _import_library(self, import_setting): name = self._resolve_name(import_setting) lib = IMPORTER.import_library(name, import_setting.args, import_setting.alias, self.variables) if lib.name in self._testlibs: LOGGER.info("Test library '%s' already imported by suite '%s'" % (lib.name, self.suite.longname)) return self._testlibs[lib.name] = lib lib.start_suite() if self.test: lib.start_test() self._import_deprecated_standard_libs(lib.name) def _resolve_name(self, import_setting): name = import_setting.name try: name = self.variables.replace_string(name) except DataError, err: self._raise_replacing_vars_failed(import_setting, err) return self._get_path(name, import_setting.directory, import_setting.type) def _raise_replacing_vars_failed(self, import_setting, err): raise DataError("Replacing variables from setting '%s' failed: %s" % (import_setting.type, unicode(err))) def _get_path(self, name, basedir, import_type): if import_type == 'Library' and not self._is_library_by_path(name): return name.replace(' ', '') return utils.find_file(name, basedir, file_type=import_type) def _is_library_by_path(self, path): return path.lower().endswith(self._library_import_by_path_endings) def _resolve_args(self, import_setting): try: return self.variables.replace_list(import_setting.args) except DataError, err: self._raise_replacing_vars_failed(import_setting, err) def _import_deprecated_standard_libs(self, name): if name in self._deprecated_libraries: self.import_library(self._deprecated_libraries[name]) def start_test(self, test): self.test = test self.variables.start_test() for lib in self._testlibs.values(): lib.start_test() def end_test(self): self.test = None self.variables.end_test() self.uk_handlers = [] for lib in self._testlibs.values(): lib.end_test() def end_suite(self): self.suite = None self.variables.end_suite() for lib in self._testlibs.values(): lib.end_suite() def start_user_keyword(self, handler): self.variables.start_uk() self.uk_handlers.append(handler) def end_user_keyword(self): self.variables.end_uk() self.uk_handlers.pop() def get_library_instance(self, libname): try: return self._testlibs[libname.replace(' ', '')].get_instance() except KeyError: raise DataError("No library with name '%s' found." % libname) def get_handler(self, name): try: handler = self._get_handler(name) if handler is None: raise DataError("No keyword with name '%s' found." % name) except DataError, err: handler = UserErrorHandler(name, unicode(err)) self._replace_variables_from_user_handlers(handler) return handler def _replace_variables_from_user_handlers(self, handler): if hasattr(handler, 'replace_variables'): handler.replace_variables(self.variables) def _get_handler(self, name): handler = None if not name: raise DataError('Keyword name cannot be empty.') if not isinstance(name, basestring): raise DataError('Keyword name must be a string.') if '.' in name: handler = self._get_explicit_handler(name) if not handler: handler = self._get_implicit_handler(name) if not handler: handler = self._get_bdd_style_handler(name) if not handler: handler = self._get_x_times_handler(name) return handler def _get_x_times_handler(self, name): if not self._is_old_x_times_syntax(name): return None return _XTimesHandler(self._get_handler('Repeat Keyword'), name) def _is_old_x_times_syntax(self, name): if not name.lower().endswith('x'): return False times = name[:-1].strip() if is_scalar_var(times): return True try: int(times) except ValueError: return False else: return True def _get_bdd_style_handler(self, name): for prefix in ['given ', 'when ', 'then ', 'and ']: if name.lower().startswith(prefix): handler = self._get_handler(name[len(prefix):]) if handler: handler = copy.copy(handler) handler.name = name return handler return None def _get_implicit_handler(self, name): for method in [self._get_handler_from_test_case_file_user_keywords, self._get_handler_from_resource_file_user_keywords, self._get_handler_from_library_keywords]: handler = method(name) if handler: return handler return None def _get_handler_from_test_case_file_user_keywords(self, name): if self._user_keywords.has_handler(name): return self._user_keywords.get_handler(name) def _get_handler_from_resource_file_user_keywords(self, name): found = [lib.get_handler(name) for lib in self._imported_resource_files.values() if lib.has_handler(name)] if not found: return None if len(found) > 1: found = self._get_handler_based_on_library_search_order(found) if len(found) == 1: return found[0] self._raise_multiple_keywords_found(name, found) def _get_handler_from_library_keywords(self, name): found = [lib.get_handler(name) for lib in self._testlibs.values() if lib.has_handler(name)] if not found: return None if len(found) > 1: found = self._get_handler_based_on_library_search_order(found) if len(found) == 2: found = self._prefer_process_over_operatingsystem(*found) if len(found) == 2: found = self._filter_stdlib_handler(*found) if len(found) == 1: return found[0] self._raise_multiple_keywords_found(name, found) def _get_handler_based_on_library_search_order(self, handlers): for libname in self.library_search_order: for handler in handlers: if utils.eq(libname, handler.libname): return [handler] return handlers def _prefer_process_over_operatingsystem(self, handler1, handler2): handlers = {handler1.library.orig_name: handler1, handler2.library.orig_name: handler2} if set(handlers) == set(['Process', 'OperatingSystem']): return [handlers['Process']] return [handler1, handler2] def _filter_stdlib_handler(self, handler1, handler2): if handler1.library.orig_name in STDLIB_NAMES: standard, external = handler1, handler2 elif handler2.library.orig_name in STDLIB_NAMES: standard, external = handler2, handler1 else: return [handler1, handler2] if not RUN_KW_REGISTER.is_run_keyword(external.library.orig_name, external.name): LOGGER.warn( "Keyword '%s' found both from a user created test library " "'%s' and Robot Framework standard library '%s'. The user " "created keyword is used. To select explicitly, and to get " "rid of this warning, use either '%s' or '%s'." % (standard.name, external.library.orig_name, standard.library.orig_name, external.longname, standard.longname)) return [external] def _get_explicit_handler(self, name): libname, kwname = name.rsplit('.', 1) # 1) Find matching lib(s) libs = [lib for lib in self._imported_resource_files.values() + self._testlibs.values() if utils.eq(lib.name, libname)] if not libs: return None # 2) Find matching kw from found libs found = [lib.get_handler(kwname) for lib in libs if lib.has_handler(kwname)] if len(found) > 1: self._raise_multiple_keywords_found(name, found, implicit=False) return found and found[0] or None def _raise_multiple_keywords_found(self, name, found, implicit=True): error = "Multiple keywords with name '%s' found.\n" % name if implicit: error += "Give the full name of the keyword you want to use.\n" names = sorted(handler.longname for handler in found) error += "Found: %s" % utils.seq2str(names) raise DataError(error) class _VariableScopes: def __init__(self, suite_variables, parent_variables): # suite and parent are None only when used by copy_all if suite_variables is not None: suite_variables.update(GLOBAL_VARIABLES) self._suite = self.current = suite_variables else: self._suite = self.current = None self._parents = [] if parent_variables is not None: self._parents.append(parent_variables.current) self._parents.extend(parent_variables._parents) self._test = None self._uk_handlers = [] def __len__(self): if self.current: return len(self.current) return 0 def copy_all(self): vs = _VariableScopes(None, None) vs._suite = self._suite vs._test = self._test vs._uk_handlers = self._uk_handlers[:] vs._parents = self._parents[:] vs.current = self.current return vs def replace_list(self, items, replace_until=None): return self.current.replace_list(items, replace_until) def replace_scalar(self, items): return self.current.replace_scalar(items) def replace_string(self, string, ignore_errors=False): return self.current.replace_string(string, ignore_errors=ignore_errors) def set_from_file(self, path, args, overwrite=False): variables = self._suite.set_from_file(path, args, overwrite) if self._test is not None: self._test._set_from_file(variables, overwrite=True) for varz in self._uk_handlers: varz._set_from_file(variables, overwrite=True) if self._uk_handlers: self.current._set_from_file(variables, overwrite=True) def set_from_variable_table(self, rawvariables, overwrite=False): self._suite.set_from_variable_table(rawvariables, overwrite) if self._test is not None: self._test.set_from_variable_table(rawvariables, overwrite) for varz in self._uk_handlers: varz.set_from_variable_table(rawvariables, overwrite) if self._uk_handlers: self.current.set_from_variable_table(rawvariables, overwrite) def __getitem__(self, name): return self.current[name] def __setitem__(self, name, value): self.current[name] = value def end_suite(self): self._suite = self._test = self.current = None def start_test(self): self._test = self.current = self._suite.copy() def end_test(self): self.current = self._suite def start_uk(self): self._uk_handlers.append(self.current) self.current = self.current.copy() def end_uk(self): self.current = self._uk_handlers.pop() def set_global(self, name, value): GLOBAL_VARIABLES.__setitem__(name, value) for ns in EXECUTION_CONTEXTS.namespaces: ns.variables.set_suite(name, value) def set_suite(self, name, value): self._suite.__setitem__(name, value) self.set_test(name, value, False) def set_test(self, name, value, fail_if_no_test=True): if self._test is not None: self._test.__setitem__(name, value) elif fail_if_no_test: raise DataError("Cannot set test variable when no test is started") for varz in self._uk_handlers: varz.__setitem__(name, value) self.current.__setitem__(name, value) def keys(self): return self.current.keys() def has_key(self, key): return self.current.has_key(key) __contains__ = has_key def contains(self, name, extended=False): return self.current.contains(name, extended)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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. """Implements the core test execution logic. The public API of this package consists of the following two classes: * :class:`~robot.running.model.TestSuite` for creating an executable test suite structure programmatically. * :class:`~robot.running.builder.TestSuiteBuilder` for creating executable test suites based on existing test case files and directories. It is recommended to import both of these classes via the :mod:`robot.api` package like in the examples below. This package and especially all public code was rewritten in Robot Framework 2.8 to make it easier to generate and execute test suites programmatically. Rewriting of the test execution logic will continue in future releases, but changes to the public API ought to be relatively small. Examples -------- First, let's assume we have the following test suite in file ``activate_skynet.txt``: .. sourcecode:: RobotFramework *** Settings *** Library OperatingSystem *** Test Cases *** Should Activate Skynet [Tags] smoke [Setup] Set Environment Variable SKYNET activated Environment Variable Should Be Set SKYNET We can easily parse and create an executable test suite based on the above file using the :class:`~robot.running.builder.TestSuiteBuilder` class as follows:: from robot.api import TestSuiteBuilder suite = TestSuiteBuilder().build('path/to/activate_skynet.txt') That was easy. Let's next generate the same test suite from scratch using the :class:`~robot.running.model.TestSuite` class:: from robot.api import TestSuite suite = TestSuite('Activate Skynet') suite.imports.library('OperatingSystem') test = suite.tests.create('Should Activate Skynet', tags=['smoke']) test.keywords.create('Set Environment Variable', args=['SKYNET', 'activated'], type='setup') test.keywords.create('Environment Variable Should Be Set', args=['SKYNET']) Not that complicated either, especially considering the flexibility. Notice that the suite created based on the file could be edited further using the same API. Now that we have a test suite ready, let's :meth:`run <robot.running.model.TestSuite.run>` it and verify that the returned :class:`~robot.result.executionresult.Result` object contains correct information:: result = suite.run(critical='smoke', output='skynet.xml') assert result.return_code == 0 assert result.suite.name == 'Activate Skynet' test = result.suite.tests[0] assert test.name == 'Should Activate Skynet' assert test.passed and test.critical stats = result.suite.statistics assert stats.critical.total == 1 and stats.critical.failed == 0 Running the suite generates a normal output XML file, unless it is disabled by using ``output=None``. Generating log, report, and xUnit files based on the results is possible using the :class:`~robot.reporting.resultwriter.ResultWriter` class:: from robot.api import ResultWriter # Report and xUnit files can be generated based on the result object. ResultWriter(result).write_results(report='skynet.html', log=None) # Generating log files requires processing the earlier generated output XML. ResultWriter('skynet.xml').write_results() Package methods --------------- """ from .builder import TestSuiteBuilder from .context import EXECUTION_CONTEXTS from .keywords import Keyword from .model import TestSuite, TestCase from .testlibraries import TestLibrary from .runkwregister import RUN_KW_REGISTER def UserLibrary(path): """Create a user library instance from given resource file. This is used by Libdoc. """ from robot.parsing import ResourceFile from robot import utils from .arguments.argumentspec import ArgumentSpec from .userkeyword import UserLibrary as RuntimeUserLibrary resource = ResourceFile(path).populate() ret = RuntimeUserLibrary(resource.keyword_table.keywords, path) for handler in ret.handlers.values(): if handler.type != 'error': handler.doc = utils.unescape(handler._doc) else: handler.arguments = ArgumentSpec(handler.longname) handler.doc = '*Creating keyword failed: %s*' % handler.error ret.doc = resource.setting_table.doc.value return ret
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement from contextlib import contextmanager from robot.errors import DataError from robot.variables import GLOBAL_VARIABLES class ExecutionContexts(object): def __init__(self): self._contexts = [] @property def current(self): return self._contexts[-1] if self._contexts else None @property def top(self): return self._contexts[0] if self._contexts else None def __iter__(self): return iter(self._contexts) @property def namespaces(self): return (context.namespace for context in self) def start_suite(self, namespace, output, dry_run=False): self._contexts.append(_ExecutionContext(namespace, output, dry_run)) return self.current def end_suite(self): self._contexts.pop() # This is ugly but currently needed e.g. by BuiltIn EXECUTION_CONTEXTS = ExecutionContexts() class _ExecutionContext(object): _started_keywords_threshold = 42 # Jython on Windows don't work with higher def __init__(self, namespace, output, dry_run=False): self.namespace = namespace self.output = output self.dry_run = dry_run self.in_suite_teardown = False self.in_test_teardown = False self.in_keyword_teardown = 0 self._started_keywords = 0 # Set by Runner, checked by Builtin. Should be moved to TestStatus, # but currently BuiltIn doesn't have access to it. self.timeout_occurred = False # TODO: namespace should not have suite, test, or uk_handlers. @property def suite(self): return self.namespace.suite @property def test(self): return self.namespace.test @property def keywords(self): return self.namespace.uk_handlers @contextmanager def suite_teardown(self): self.in_suite_teardown = True try: yield finally: self.in_suite_teardown = False @contextmanager def test_teardown(self, test): self.variables['${TEST_STATUS}'] = test.status self.variables['${TEST_MESSAGE}'] = test.message self.in_test_teardown = True try: yield finally: self.in_test_teardown = False @contextmanager def keyword_teardown(self, error): self.variables['${KEYWORD_STATUS}'] = 'FAIL' if error else 'PASS' self.variables['${KEYWORD_MESSAGE}'] = unicode(error or '') self.in_keyword_teardown += 1 try: yield finally: self.in_keyword_teardown -= 1 @property def in_teardown(self): return bool(self.in_suite_teardown or self.in_test_teardown or self.in_keyword_teardown) @property def variables(self): return self.namespace.variables # TODO: Move start_suite here from EXECUTION_CONTEXT def end_suite(self, suite): for var in ['${PREV_TEST_NAME}', '${PREV_TEST_STATUS}', '${PREV_TEST_MESSAGE}']: GLOBAL_VARIABLES[var] = self.variables[var] self.output.end_suite(suite) self.namespace.end_suite() EXECUTION_CONTEXTS.end_suite() def set_suite_variables(self, suite): self.variables['${SUITE_NAME}'] = suite.longname self.variables['${SUITE_SOURCE}'] = suite.source or '' self.variables['${SUITE_DOCUMENTATION}'] = suite.doc self.variables['${SUITE_METADATA}'] = suite.metadata.copy() def report_suite_status(self, status, message): self.variables['${SUITE_STATUS}'] = status self.variables['${SUITE_MESSAGE}'] = message def start_test(self, test): self.namespace.start_test(test) self.variables['${TEST_NAME}'] = test.name self.variables['${TEST_DOCUMENTATION}'] = test.doc self.variables['@{TEST_TAGS}'] = list(test.tags) def end_test(self, test): self.namespace.end_test() self.variables['${PREV_TEST_NAME}'] = test.name self.variables['${PREV_TEST_STATUS}'] = test.status self.variables['${PREV_TEST_MESSAGE}'] = test.message self.timeout_occurred = False # Should not need separate start/end_keyword and start/end_user_keyword def start_keyword(self, keyword): self._started_keywords += 1 if self._started_keywords > self._started_keywords_threshold: raise DataError('Maximum limit of started keywords exceeded.') self.output.start_keyword(keyword) def end_keyword(self, keyword): self.output.end_keyword(keyword) self._started_keywords -= 1 def start_user_keyword(self, kw): self.namespace.start_user_keyword(kw) def end_user_keyword(self): self.namespace.end_user_keyword() def get_handler(self, name): return self.namespace.get_handler(name) def warn(self, message): self.output.warn(message) def trace(self, message): self.output.trace(message) def info(self, message): self.output.info(message)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 TestDefaults(object): def __init__(self, settings, parent=None): 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.template = settings.test_template if parent: self.setup = self.setup or parent.setup self.teardown = self.teardown or parent.teardown self.timeout = self.timeout or parent.timeout self.force_tags += parent.force_tags def get_test_values(self, test): return TestValues(test, self) class TestValues(object): def __init__(self, test, defaults): self.setup = test.setup or defaults.setup self.teardown = test.teardown or defaults.teardown self.timeout = test.timeout or defaults.timeout self.template = test.template or defaults.template self.tags = (test.tags or defaults.default_tags) + defaults.force_tags
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement from robot.errors import ExecutionFailed, DataError, PassExecution from robot.model import SuiteVisitor from robot.result import TestSuite, Result from robot.variables import GLOBAL_VARIABLES from robot.utils import get_timestamp, NormalizedDict from .context import EXECUTION_CONTEXTS from .keywords import Keywords, Keyword from .namespace import Namespace from .status import SuiteStatus, TestStatus from .timeouts import TestTimeout # TODO: Some 'extract method' love needed here. Perhaps even 'extract class'. class Runner(SuiteVisitor): def __init__(self, output, settings): self.result = None self._output = output self._settings = settings self._suite = None self._suite_status = None self._executed_tests = None @property def _context(self): return EXECUTION_CONTEXTS.current @property def _variables(self): ctx = self._context return ctx.variables if ctx else None def start_suite(self, suite): variables = GLOBAL_VARIABLES.copy() variables.set_from_variable_table(suite.variables) result = TestSuite(source=suite.source, name=suite.name, doc=suite.doc, metadata=suite.metadata, starttime=get_timestamp()) if not self.result: result.set_criticality(self._settings.critical_tags, self._settings.non_critical_tags) self.result = Result(root_suite=result) self.result.configure(status_rc=self._settings.status_rc, stat_config=self._settings.statistics_config) else: self._suite.suites.append(result) ns = Namespace(result, variables, self._variables, suite.user_keywords, suite.imports) EXECUTION_CONTEXTS.start_suite(ns, self._output, self._settings.dry_run) self._context.set_suite_variables(result) if not (self._suite_status and self._suite_status.failures): ns.handle_imports() variables.resolve_delayed() result.doc = self._resolve_setting(result.doc) result.metadata = [(self._resolve_setting(n), self._resolve_setting(v)) for n, v in result.metadata.items()] self._context.set_suite_variables(result) self._suite = result self._suite_status = SuiteStatus(self._suite_status, self._settings.exit_on_failure, self._settings.skip_teardown_on_exit) self._output.start_suite(ModelCombiner(suite, self._suite)) self._run_setup(suite.keywords.setup, self._suite_status) self._executed_tests = NormalizedDict(ignore='_') def _resolve_setting(self, value): return self._variables.replace_string(value, ignore_errors=True) def end_suite(self, suite): self._suite.message = self._suite_status.message self._context.report_suite_status(self._suite.status, self._suite.full_message) with self._context.suite_teardown(): failure = self._run_teardown(suite.keywords.teardown, self._suite_status) if failure: self._suite.suite_teardown_failed(unicode(failure)) self._suite.endtime = get_timestamp() self._suite.message = self._suite_status.message self._context.end_suite(self._suite) self._suite = self._suite.parent self._suite_status = self._suite_status.parent def visit_test(self, test): if test.name in self._executed_tests: self._output.warn("Multiple test cases with name '%s' executed in " "test suite '%s'." % (test.name, self._suite.longname)) self._executed_tests[test.name] = True result = self._suite.tests.create(name=test.name, doc=self._resolve_setting(test.doc), tags=test.tags, starttime=get_timestamp(), timeout=self._get_timeout(test)) keywords = Keywords(test.keywords.normal, bool(test.template)) status = TestStatus(self._suite_status) if not status.failures and not test.name: status.test_failed('Test case name cannot be empty.', result.critical) if not status.failures and not keywords: status.test_failed('Test case contains no keywords.', result.critical) try: result.tags = self._context.variables.replace_list(result.tags) except DataError, err: status.test_failed('Replacing variables from test tags failed: %s' % unicode(err), result.critical) self._context.start_test(result) self._output.start_test(ModelCombiner(result, test)) self._run_setup(test.keywords.setup, status, result) try: if not status.failures: keywords.run(self._context) except PassExecution, exception: err = exception.earlier_failures if err: status.test_failed(err, result.critical) else: result.message = exception.message except ExecutionFailed, err: status.test_failed(err, result.critical) if err.timeout: self._context.timeout_occurred = True result.status = status.status result.message = status.message or result.message if status.teardown_allowed: with self._context.test_teardown(result): self._run_teardown(test.keywords.teardown, status, result) if not status.failures and result.timeout and result.timeout.timed_out(): status.test_failed(result.timeout.get_message(), result.critical) result.message = status.message result.status = status.status result.endtime = get_timestamp() self._output.end_test(ModelCombiner(result, test)) self._context.end_test(result) def _get_timeout(self, test): if not test.timeout: return None timeout = TestTimeout(test.timeout.value, test.timeout.message, self._variables) timeout.start() return timeout def _run_setup(self, setup, status, result=None): if not status.failures: exception = self._run_setup_or_teardown(setup, 'setup') status.setup_executed(exception) if result and isinstance(exception, PassExecution): result.message = exception.message def _run_teardown(self, teardown, status, result=None): if status.teardown_allowed: exception = self._run_setup_or_teardown(teardown, 'teardown') status.teardown_executed(exception) failed = not isinstance(exception, PassExecution) if result and exception: result.message = status.message if failed else exception.message return exception if failed else None def _run_setup_or_teardown(self, data, kw_type): if not data: return None try: name = self._variables.replace_string(data.name) except DataError, err: return err if name.upper() in ('', 'NONE'): return None kw = Keyword(name, data.args, type=kw_type) try: kw.run(self._context) except ExecutionFailed, err: if err.timeout: self._context.timeout_occurred = True return err class ModelCombiner(object): def __init__(self, *models): self.models = models def __getattr__(self, name): for model in self.models: if hasattr(model, name): return getattr(model, name) raise AttributeError(name)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.errors import DataError from robot.parsing import TestData from robot.running.defaults import TestDefaults from robot.utils import abspath from robot.variables import VariableIterator from .model import TestSuite, ForLoop class TestSuiteBuilder(object): def __init__(self, include_suites=None, warn_on_skipped=False, include_empty_suites=False): """Create programmatically executable :class:`~robot.running.model.TestSuite` objects based on existing data on the file system. See example of usage in :mod:`.running` package. """ self.include_suites = include_suites self.warn_on_skipped = warn_on_skipped self.include_empty_suites = include_empty_suites def build(self, *paths): if not paths: raise DataError('One or more source paths required.') if len(paths) == 1: return self._build_and_check_if_empty(paths[0]) root = TestSuite() for path in paths: root.suites.append(self._build_and_check_if_empty(path)) return root def _build_and_check_if_empty(self, path): builded = self._build_suite(self._parse(path)) if not self._empty_suites_allowed and not builded.test_count: raise DataError("Suite '%s' contains no tests." % builded.name) builded.remove_empty_suites() return builded @property def _empty_suites_allowed(self): return self.include_empty_suites or self.include_suites def _parse(self, path): try: return TestData(source=abspath(path), include_suites=self.include_suites, warn_on_skipped=self.warn_on_skipped) except DataError, err: raise DataError("Parsing '%s' failed: %s" % (path, unicode(err))) def _build_suite(self, data, parent_defaults=None): defaults = TestDefaults(data.setting_table, parent_defaults) suite = TestSuite(name=data.name, source=data.source, doc=unicode(data.setting_table.doc), metadata=self._get_metadata(data.setting_table)) for import_data in data.setting_table.imports: self._create_import(suite, import_data) self._create_setup(suite, data.setting_table.suite_setup) self._create_teardown(suite, data.setting_table.suite_teardown) for var_data in data.variable_table.variables: self._create_variable(suite, var_data) for uk_data in data.keyword_table.keywords: self._create_user_keyword(suite, uk_data) for test_data in data.testcase_table.tests: self._create_test(suite, test_data, defaults) for child in data.children: suite.suites.append(self._build_suite(child, defaults)) return suite def _get_metadata(self, settings): # Must return as a list to preserve ordering return [(meta.name, meta.value) for meta in settings.metadata] def _create_import(self, suite, data): suite.imports.create(type=data.type, name=data.name, args=tuple(data.args), alias=data.alias) def _create_test(self, suite, data, defaults): values = defaults.get_test_values(data) test = suite.tests.create(name=data.name, doc=unicode(data.doc), tags=values.tags.value, template=self._get_template(values.template), timeout=self._get_timeout(values.timeout)) self._create_setup(test, values.setup) for step_data in data.steps: self._create_step(test, step_data, template=values.template) self._create_teardown(test, values.teardown) def _get_timeout(self, timeout): return (timeout.value, timeout.message) if timeout else None def _get_template(self, template): return unicode(template) if template.is_active() else None def _create_user_keyword(self, suite, data): uk = suite.user_keywords.create(name=data.name, args=tuple(data.args), doc=unicode(data.doc), return_=tuple(data.return_), timeout=data.timeout, teardown=data.teardown) for step_data in data.steps: self._create_step(uk, step_data) def _create_variable(self, suite, data): if data: suite.variables.create(name=data.name, value=data.value) def _create_setup(self, parent, data): if data.is_active(): self._create_step(parent, data, kw_type='setup') def _create_teardown(self, parent, data): if data.is_active(): self._create_step(parent, data, kw_type='teardown') def _create_step(self, parent, data, template=None, kw_type='kw'): if not data or data.is_comment(): return if data.is_for_loop(): self._create_for_loop(parent, data, template) elif template and template.is_active(): self._create_templated(parent, data, template) else: parent.keywords.create(name=data.keyword, args=tuple(data.args), assign=tuple(data.assign), type=kw_type) def _create_templated(self, parent, data, template): args = data.as_list(include_comment=False) template, args = self._format_template(unicode(template), args) parent.keywords.create(name=template, args=tuple(args)) def _format_template(self, template, args): iterator = VariableIterator(template, identifiers='$') variables = len(iterator) if not variables or variables != len(args): return template, args temp = [] for before, variable, after in iterator: temp.extend([before, args.pop(0)]) temp.append(after) return ''.join(temp), () def _create_for_loop(self, parent, data, template): loop = parent.keywords.append(ForLoop(vars=data.vars, items=data.items, range=data.range)) for step in data.steps: self._create_step(loop, step, template=template)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement import os import re from robot.errors import (DataError, ExecutionFailed, ExecutionPassed, PassExecution, ReturnFromKeyword, UserKeywordExecutionFailed) from robot.variables import is_list_var, VariableIterator from robot.output import LOGGER from robot import utils from .arguments import (ArgumentMapper, ArgumentResolver, UserKeywordArgumentParser) from .baselibrary import BaseLibrary from .keywords import Keywords, Keyword from .timeouts import KeywordTimeout from .usererrorhandler import UserErrorHandler class UserLibrary(BaseLibrary): 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 = self._create_handler(kw) except DataError, err: LOGGER.error("Creating user keyword '%s' failed: %s" % (kw.name, unicode(err))) continue if handler.name in self.handlers: error = "Keyword '%s' defined multiple times." % handler.name handler = UserErrorHandler(handler.name, error) self.handlers[handler.name] = handler def _create_handler(self, kw): try: handler = EmbeddedArgsTemplate(kw, self.name) except TypeError: handler = UserKeywordHandler(kw, self.name) else: self.embedded_arg_handlers.append(handler) return 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.orig_name 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 = tuple(keyword.return_) self.teardown = keyword.teardown self.libname = libname self.doc = self._doc = unicode(keyword.doc) self.arguments = UserKeywordArgumentParser().parse(tuple(keyword.args), self.longname) self._timeout = keyword.timeout @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, variables): self.doc = variables.replace_string(self._doc, ignore_errors=True) timeout = (self._timeout.value, self._timeout.message) if self._timeout else () self.timeout = KeywordTimeout(*timeout) self.timeout.replace_variables(variables) def run(self, context, arguments): context.start_user_keyword(self) try: return self._run(context, arguments) finally: context.end_user_keyword() def _run(self, context, arguments): if context.dry_run: return self._dry_run(context, arguments) return self._normal_run(context, arguments) def _dry_run(self, context, arguments): arguments = self._resolve_arguments(arguments) error, return_ = self._execute(context, arguments) if error: raise error return None def _normal_run(self, context, arguments): arguments = self._resolve_arguments(arguments, context.variables) error, return_ = self._execute(context, arguments) if error and not error.can_continue(context.in_teardown): raise error return_value = self._get_return_value(context.variables, return_) if error: error.return_value = return_value raise error return return_value def _resolve_arguments(self, arguments, variables=None): resolver = ArgumentResolver(self.arguments) mapper = ArgumentMapper(self.arguments) positional, named = resolver.resolve(arguments, variables) arguments, _ = mapper.map(positional, named, variables) return arguments def _execute(self, context, arguments): self._set_variables(arguments, context.variables) context.output.trace(lambda: self._log_args(context.variables)) self._verify_keyword_is_valid() self.timeout.start() error = return_ = pass_ = None try: self.keywords.run(context) except ReturnFromKeyword, exception: return_ = exception error = exception.earlier_failures except ExecutionPassed, exception: pass_ = exception error = exception.earlier_failures except ExecutionFailed, exception: error = exception with context.keyword_teardown(error): td_error = self._run_teardown(context) if error or td_error: error = UserKeywordExecutionFailed(error, td_error) return error or pass_, return_ def _set_variables(self, arguments, variables): before_varargs, varargs = self._split_args_and_varargs(arguments) for name, value in zip(self.arguments.positional, before_varargs): variables['${%s}' % name] = value if self.arguments.varargs: variables['@{%s}' % self.arguments.varargs] = varargs def _split_args_and_varargs(self, args): if not self.arguments.varargs: return args, [] positional = len(self.arguments.positional) return args[:positional], args[positional:] def _log_args(self, variables): args = ['${%s}' % arg for arg in self.arguments.positional] if self.arguments.varargs: args.append('@{%s}' % self.arguments.varargs) args = ['%s=%s' % (name, utils.safe_repr(variables[name])) for name in args] return 'Arguments: [ %s ]' % ' | '.join(args) def _run_teardown(self, context): if not self.teardown: return None try: name = context.variables.replace_string(self.teardown.name) except DataError, err: return ExecutionFailed(unicode(err), syntax=True) if name.upper() in ('', 'NONE'): return None kw = Keyword(name, self.teardown.args, type='teardown') try: kw.run(context) except PassExecution: return None except ExecutionFailed, err: return err return None def _verify_keyword_is_valid(self): if not (self.keywords or self.return_value): raise DataError("User keyword '%s' contains no keywords." % self.name) def _get_return_value(self, variables, return_): ret = self.return_value if not return_ else return_.return_value if not ret: return None contains_list_var = any(is_list_var(item) for item in ret) try: ret = variables.replace_list(ret) except DataError, err: raise DataError('Replacing variables from keyword return value ' 'failed: %s' % unicode(err)) if len(ret) != 1 or contains_list_var: 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: 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) self.keyword = keyword def _read_embedded_args_and_regexp(self, string): args = [] full_pattern = ['^'] for before, variable, string in VariableIterator(string, identifiers='$'): variable, pattern = self._get_regexp_pattern(variable[2:-1]) args.append('${%s}' % variable) full_pattern.extend([re.escape(before), '(%s)' % pattern]) full_pattern.extend([re.escape(string), '$']) return args, self._compile_regexp(full_pattern) 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') UserKeywordHandler.__init__(self, template.keyword, template.libname) self.embedded_args = zip(template.embedded_args, match.groups()) self.name = name self.orig_name = template.name def _run(self, context, args): if not context.dry_run: variables = context.variables self._resolve_arguments(args, variables) # validates no args given for name, value in self.embedded_args: variables[name] = variables.replace_scalar(value) return UserKeywordHandler._run(self, context, args)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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(object): def __init__(self): self._library_cache = ImportCache() self._resource_cache = ImportCache() def reset(self): self.__init__() 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: alias = variables.replace_scalar(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).populate() self._resource_cache[path] = resource return self._resource_cache[path] def _import_library(self, name, positional, named, lib): args = positional + ['%s=%s' % arg for arg in sorted(named.items())] key = (name, positional, named) if key in self._library_cache: LOGGER.info("Found test library '%s' with arguments %s from cache" % (name, utils.seq2str2(args))) return self._library_cache[key] lib.create_handlers() self._library_cache[key] = lib self._log_imported_library(name, args, lib) return lib def _log_imported_library(self, name, args, lib): type = lib.__class__.__name__.replace('Library', '').lower()[1:] LOGGER.info("Imported library '%s' with arguments %s " "(version %s, %s type, %s scope, %d keywords)" % (name, utils.seq2str2(args), lib.version or '<unknown>', type, lib.scope.lower(), len(lib))) if not lib: LOGGER.warn("Imported library '%s' contains no keywords" % name) 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') key = self._norm_path_key(key) if key not in self._keys: self._keys.append(key) self._items.append(item) else: self._items[self._keys.index(key)] = 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 values(self): return self._items def _norm_path_key(self, key): if self._is_path(key): return utils.normpath(key) if isinstance(key, tuple): return tuple(self._norm_path_key(k) for k in key) return key def _is_path(self, key): return isinstance(key, basestring) and os.path.isabs(key) and os.path.exists(key)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement import inspect import os import sys from robot.errors import DataError from robot.output import LOGGER from robot.utils import (getdoc, get_error_details, Importer, is_java_init, is_java_method, normalize, NormalizedDict, seq2str2, unic) from .baselibrary import BaseLibrary from .dynamicmethods import (GetKeywordArguments, GetKeywordDocumentation, GetKeywordNames, RunKeyword) from .handlers import Handler, InitHandler, DynamicHandler from .outputcapture import OutputCapturer if sys.platform.startswith('java'): from java.lang import Object else: Object = None def TestLibrary(name, args=None, variables=None, create_handlers=True): with OutputCapturer(library_import=True): importer = Importer('test library') libcode = importer.import_class_or_module(name) libclass = _get_lib_class(libcode) lib = libclass(libcode, name, args or [], variables) if create_handlers: lib.create_handlers() return lib def _get_lib_class(libcode): if inspect.ismodule(libcode): return _ModuleLibrary if GetKeywordNames(libcode): if RunKeyword(libcode): return _DynamicLibrary else: return _HybridLibrary return _ClassLibrary class _BaseTestLibrary(BaseLibrary): _log_success = LOGGER.debug _log_failure = LOGGER.info _log_failure_details = LOGGER.debug def __init__(self, libcode, name, args, variables): if os.path.exists(name): name = os.path.splitext(os.path.basename(os.path.abspath(name)))[0] 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 = getdoc(libcode) self.doc_format = self._get_doc_format(libcode) self.scope = self._get_scope(libcode) self._libcode = libcode self.init = self._create_init_handler(libcode) self.positional_args, self.named_args \ = self.init.resolve_arguments(args, variables) @property def doc(self): return self._doc 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, libcode): return self._get_attr(libcode, 'ROBOT_LIBRARY_VERSION') \ or self._get_attr(libcode, '__version__') def _get_attr(self, object, attr, default='', upper=False): value = unic(getattr(object, attr, default)) if upper: value = normalize(value, ignore='_').upper() return value def _get_doc_format(self, libcode): return self._get_attr(libcode, 'ROBOT_LIBRARY_DOC_FORMAT', upper=True) def _get_scope(self, libcode): scope = self._get_attr(libcode, 'ROBOT_LIBRARY_SCOPE', upper=True) return scope if scope in ['GLOBAL','TESTSUITE'] else 'TESTCASE' def _create_init_handler(self, libcode): return InitHandler(self, self._resolve_init_method(libcode)) def _resolve_init_method(self, libcode): init_method = getattr(libcode, '__init__', None) return init_method if self._valid_init(init_method) else lambda: None def _valid_init(self, method): return inspect.ismethod(method) or is_java_init(method) 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_instance(self): if self._libinst is None: self._libinst = self._get_instance() return self._libinst def _get_instance(self): with OutputCapturer(library_import=True): try: return self._libcode(*self.positional_args, **self.named_args) except: self._raise_creating_instance_failed() def _create_handlers(self, libcode): handlers = 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 = 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 = get_error_details() if self.positional_args or self.named_args: args = self.positional_args \ + ['%s=%s' % item for item in self.named_args.items()] args_text = 'arguments %s' % seq2str2(args) else: args_text = 'no arguments' raise DataError("Initializing test library '%s' with %s failed: %s\n%s" % (self.name, args_text, msg, details)) class _ClassLibrary(_BaseTestLibrary): 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): return inspect.isroutine(handler) or is_java_method(handler) def _is_implicit_java_or_jython_method(self, handler): if not 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): 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): return self._libcode def _create_init_handler(self, libcode): return InitHandler(self, lambda: 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, name, args, variables=None): _BaseTestLibrary.__init__(self, libcode, name, args, variables) self._doc_get = False @property def doc(self): if not self._doc_get: self._doc = self._get_kw_doc('__intro__') or self._doc self._doc_get = True return self._doc def _get_kw_doc(self, name, instance=None): getter = GetKeywordDocumentation(instance or self.get_instance()) return getter(name) def _get_kw_args(self, name, instance=None): getter = GetKeywordArguments(instance or self.get_instance()) return getter(name) def _get_handler_names(self, instance): return GetKeywordNames(instance)() def _get_handler_method(self, instance, name): return RunKeyword(instance) def _create_handler(self, name, method): doc = self._get_kw_doc(name) argspec = self._get_kw_args(name) return DynamicHandler(self, name, method, doc, argspec) def _create_init_handler(self, libcode): docgetter = lambda: self._get_kw_doc('__init__') return InitHandler(self, self._resolve_init_method(libcode), docgetter)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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.utils import (format_assign_message, get_elapsed_time, get_error_message, get_timestamp, plural_or_not) from robot.errors import (ContinueForLoop, DataError, ExecutionFailed, ExecutionFailures, ExecutionPassed, ExitForLoop, HandlerExecutionFailed) from robot.variables import is_scalar_var, VariableAssigner class Keywords(object): def __init__(self, steps, templated=False): self._keywords = [] self._templated = templated for s in steps: self._add_step(s) def _add_step(self, step): if step.is_comment(): return if step.is_for_loop(): keyword = ForLoop(step, self._templated) 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 ExecutionPassed, exception: exception.set_earlier_failures(errors) raise exception except ExecutionFailed, exception: errors.extend(exception.get_errors()) if not exception.can_continue(context.in_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 _BaseKeyword: def __init__(self, name='', args=None, doc='', timeout='', type='kw'): self.name = name self.args = args or [] self.doc = doc self.timeout = timeout self.type = type self.message = '' self.status = 'NOT_RUN' @property def passed(self): return self.status == 'PASS' def serialize(self, serializer): serializer.start_keyword(self) serializer.end_keyword(self) def _get_status(self, error): if not error: return 'PASS' if isinstance(error, ExecutionPassed) and not error.earlier_failures: return 'PASS' return 'FAIL' 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 = self._get_status(err) 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.variables) self.name = self._get_name(handler.longname) self.doc = handler.shortdoc self.timeout = getattr(handler, 'timeout', '') self.starttime = 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 = get_timestamp() self.elapsedtime = get_elapsed_time(self.starttime, self.endtime) if error and self.type == 'teardown': self.message = unicode(error) try: if not error or error.can_continue(context.in_teardown): self._set_variables(context, return_value, error) finally: context.end_keyword(self) def _set_variables(self, context, return_value, error): if error: return_value = error.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() context.output.fail(failure.full_message) if failure.traceback: context.output.debug(failure.traceback) raise failure class ForLoop(_BaseKeyword): def __init__(self, forstep, templated=False): _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, templated) self._templated = templated 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 = get_timestamp() context.start_keyword(self) error = self._run_with_error_handling(self._validate_and_run, context) self.status = self._get_status(error) self.endtime = get_timestamp() self.elapsedtime = get_elapsed_time(self.starttime, self.endtime) context.end_keyword(self) if error: raise error def _run_with_error_handling(self, runnable, context): try: runnable(context) except ExecutionFailed, err: return err except DataError, err: msg = unicode(err) context.output.fail(msg) return ExecutionFailed(msg, syntax=True) else: return None def _validate_and_run(self, context): self._validate() self._run(context) 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)] exception = self._run_one_round(context, self.vars, values) if exception: if isinstance(exception, ExitForLoop): if exception.earlier_failures: errors.extend(exception.earlier_failures.get_errors()) break if isinstance(exception, ContinueForLoop): if exception.earlier_failures: errors.extend(exception.earlier_failures.get_errors()) continue if isinstance(exception, ExecutionPassed): exception.set_earlier_failures(errors) raise exception errors.extend(exception.get_errors()) if not exception.can_continue(context.in_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.variables) return items, range(0, len(items), len(self.vars)) def _run_one_round(self, context, variables, values): foritem = _ForItem(variables, values) context.start_keyword(foritem) for var, value in zip(variables, values): context.variables[var] = value error = self._run_with_error_handling(self.keywords.run, context) foritem.end(self._get_status(error)) context.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), plural_or_not(items))) def _get_range_items(self, items): try: items = [self._to_int_with_arithmetics(item) for item in items] except: raise DataError('Converting argument of FOR IN RANGE failed: %s' % 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_with_arithmetics(self, item): item = str(item) try: return int(item) except ValueError: return int(eval(item)) class _ForItem(_BaseKeyword): def __init__(self, vars, items): name = ', '.join(format_assign_message(var, item) for var, item in zip(vars, items)) _BaseKeyword.__init__(self, name, type='foritem') self.starttime = get_timestamp() def end(self, status): self.status = status self.endtime = get_timestamp() self.elapsedtime = get_elapsed_time(self.starttime, self.endtime)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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(object): 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: raise 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: raise ValueError('No variable start found') return start_index, max_end_index def _find_start_index(self, string, start, end): while True: index = string.find('{', start, end) - 1 if index < 0: return -1 if self._start_index_is_ok(string, index): return index start = index + 2 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 class VariableIterator(object): def __init__(self, string, identifiers): self._string = string self._identifiers = identifiers def __iter__(self): string = self._string while True: var = VariableSplitter(string, self._identifiers) if var.identifier is None: break before = string[:var.start] variable = '%s{%s}' % (var.identifier, var.base) string = string[var.end:] yield before, variable, string def __len__(self): return sum(1 for _ in self)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from robot.errors import DataError from robot.utils import safe_repr, format_assign_message, get_error_message from .isvar import is_list_var, is_scalar_var class VariableAssigner(object): _valid_extended_attr = re.compile('^[_a-zA-Z]\w*$') 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(lambda: 'Return: %s' % safe_repr(return_value)) if self.scalar_vars or self.list_var: self._assign(context, ReturnValue(self.scalar_vars, self.list_var, return_value)) def _assign(self, context, return_value): for name, value in return_value.get_variables_to_set(): if not self._extended_assign(name, value, context.variables): self._normal_assign(name, value, context.variables) context.info(format_assign_message(name, value)) def _extended_assign(self, name, value, variables): if '.' not in name or name.startswith('@') \ or variables.contains(name, extended=False): return False base, attr = self._split_extended_assign(name) if not variables.contains(base, extended=True): return False var = variables[base] if not (self._variable_supports_extended_assign(var) and self._is_valid_extended_attribute(attr)): return False try: setattr(var, attr, value) except: raise DataError("Setting attribute '%s' to variable '%s' failed: %s" % (attr, base, get_error_message())) return True def _split_extended_assign(self, name): base, attr = name.rsplit('.', 1) return base.strip() + '}', attr[:-1].strip() def _variable_supports_extended_assign(self, var): return not isinstance(var, (basestring, int, long, float)) def _is_valid_extended_attribute(self, attr): return self._valid_extended_attr.match(attr) is not None def _normal_assign(self, name, value, variables): variables[name] = value 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 ReturnValue(object): def __init__(self, scalar_vars, list_var, return_value): self._scalars = scalar_vars self._list = list_var self._return = return_value def get_variables_to_set(self): if self._return is None: return self._return_value_is_none(self._scalars, self._list) if len(self._scalars) == 1 and not self._list: return self._only_one_variable(self._scalars[0], self._return) ret = self._convert_to_list(self._return) if not self._list: return self._only_scalars(self._scalars, ret) if not self._scalars: return self._only_one_variable(self._list, ret) return self._scalars_and_list(self._scalars, self._list, ret) def _return_value_is_none(self, scalars, list_): ret = [(var, None) for var in scalars] if self._list: ret.append((list_, [])) return ret def _only_one_variable(self, variable, ret): return [(variable, ret)] def _convert_to_list(self, ret): if isinstance(ret, basestring): self._raise_expected_list(ret) try: return list(ret) except TypeError: self._raise_expected_list(ret) def _only_scalars(self, scalars, ret): needed = len(scalars) if len(ret) < needed: self._raise_too_few_arguments(ret) if len(ret) == needed: return zip(scalars, ret) return zip(scalars[:-1], ret) + [(scalars[-1], ret[needed-1:])] def _scalars_and_list(self, scalars, list_, ret): if len(ret) < len(scalars): self._raise_too_few_arguments(ret) return zip(scalars, ret) + [(list_, ret[len(scalars):])] def _raise_expected_list(self, ret): typ = 'string' if isinstance(ret, basestring) else type(ret).__name__ self._raise('Expected list-like object, got %s instead.' % typ) def _raise_too_few_arguments(self, ret): self._raise('Need more values than %d.' % len(ret)) def _raise(self, error): raise DataError('Cannot assign return values: %s' % error)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 inspect from functools import partial from UserDict import UserDict try: from java.lang.System import getProperty as getJavaSystemProperty from java.util import Map except ImportError: getJavaSystemProperty = lambda name: None class Map: pass from robot import utils from robot.errors import DataError from robot.output import LOGGER from .isvar import is_var, is_scalar_var, is_list_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.UNICODE|re.VERBOSE) def __init__(self, identifiers=('$', '@', '%', '&', '*')): utils.NormalizedDict.__init__(self, ignore='_') self._identifiers = identifiers importer = utils.Importer('variable file').import_class_or_module_by_path self._import_variable_file = partial(importer, instantiate_with_args=()) def __setitem__(self, name, value): 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 self._find_variable(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_scalar_var_as_list(name) except ValueError: try: return self._get_extended_var(name) except ValueError: raise DataError("Non-existing variable '%s'." % name) def _find_variable(self, name): variable = utils.NormalizedDict.__getitem__(self, name) return self._solve_delayed(name, variable) def _solve_delayed(self, name, value): if isinstance(value, DelayedVariable): return value.resolve(name, self) return value def resolve_delayed(self): # cannot iterate over `self` here because loop changes the state. for var in self.keys(): try: self[var] # getting variable resolves it if needed except DataError: pass 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 not is_scalar_var(name): raise ValueError name = '@'+name[1:] try: return self._find_variable(name) except KeyError: return self._get_extended_var(name) def _get_scalar_var_as_list(self, name): if not is_list_var(name): raise ValueError name = '$'+name[1:] try: value = self._find_variable(name) except KeyError: value = self._get_extended_var(name) if not utils.is_list_like(value): raise DataError("Using scalar variable '%s' as list variable '@%s' " "requires its value to be list or list-like." % (name, name[1:])) return value 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, replace_until=None): """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. 'replace_until' can be used to limit replacing arguments to certain index from the beginning. Used with Run Keyword variants that only want to resolve some of the arguments in the beginning and pass others to called keywords unmodified. """ items = list(items or []) if replace_until is not None: return self._replace_list_until(items, replace_until) return self._replace_list(items) def _replace_list_until(self, items, replace_until): # @{list} variables can contain more or less arguments than needed. # Therefore we need to go through arguments one by one. processed = [] while len(processed) < replace_until and items: processed.extend(self._replace_list([items.pop(0)])) # If @{list} variable is opened, arguments going further must be # escaped to prevent them being un-escaped twice. if len(processed) > replace_until: processed[replace_until:] = [self._escape(item) for item in processed[replace_until:]] return processed + items def _escape(self, item): item = utils.escape(item) # Escape also special syntax used by Run Kw If and Run Kws. if item in ('ELSE', 'ELSE IF', 'AND'): item = '\\' + item return item def _replace_list(self, items): results = [] for item in items: 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) and '{' in item) def replace_string(self, string, splitter=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 splitter is None: splitter = VariableSplitter(string, self._identifiers) while True: if splitter.identifier is None: result.append(utils.unescape(string)) break result.append(utils.unescape(string[:splitter.start])) try: value = self._get_variable(splitter) except DataError: if not ignore_errors: raise value = string[splitter.start:splitter.end] if not isinstance(value, unicode): value = utils.unic(value) result.append(value) string = string[splitter.end:] splitter = 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 not name: return '%%{%s}' % var.base value = utils.get_env_var(name) if value is not None: return value value = getJavaSystemProperty(name) if value is not None: return value 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=None, overwrite=False): LOGGER.info("Importing variable file '%s' with args %s" % (path, args)) var_file = self._import_variable_file(path) try: variables = self._get_variables_from_var_file(var_file, args) self._set_from_file(variables, overwrite) except: amsg = 'with arguments %s ' % utils.seq2str2(args) if args else '' 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=False): 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 self.contains(name): self.set(name, value) def set_from_variable_table(self, variables, overwrite=False): for var in variables: if not var: continue try: name, value = self._get_var_table_name_and_value( var.name, var.value, var.report_invalid_syntax) if overwrite or not self.contains(name): self.set(name, value) except DataError, err: var.report_invalid_syntax(err) def _get_var_table_name_and_value(self, name, value, error_reporter): self._validate_var_name(name) if is_scalar_var(name) and isinstance(value, basestring): value = [value] else: self._validate_var_is_not_scalar_list(name, value) value = [self._unescape_leading_trailing_spaces(cell) for cell in value] return name, DelayedVariable(value, error_reporter) def _unescape_leading_trailing_spaces(self, item): if item.endswith(' \\'): item = item[:-1] if item.startswith('\\ '): item = item[1:] return item def _validate_var_is_not_scalar_list(self, name, value): if is_scalar_var(name) and len(value) > 1: raise DataError("Creating a scalar variable with a list value in " "the Variable table is no longer possible. " "Create a list variable '@%s' and use it as a " "scalar variable '%s' instead." % (name[1:], name)) def _get_variables_from_var_file(self, var_file, args): variables = self._get_dynamical_variables(var_file, args or ()) if variables is not None: return variables names = self._get_static_variable_names(var_file) return self._get_static_variables(var_file, names) def _get_dynamical_variables(self, var_file, args): get_variables = getattr(var_file, 'get_variables', None) if not get_variables: get_variables = getattr(var_file, 'getVariables', None) if not get_variables: return None variables = get_variables(*args) if utils.is_dict_like(variables): 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 _get_static_variable_names(self, var_file): names = [attr for attr in dir(var_file) if not attr.startswith('_')] if hasattr(var_file, '__all__'): names = [name for name in names if name in var_file.__all__] return names def _get_static_variables(self, var_file, names): variables = [(name, getattr(var_file, name)) for name in names] if not inspect.ismodule(var_file): variables = [var for var in variables if not callable(var[1])] return variables def has_key(self, variable): try: self[variable] except DataError: return False else: return True __contains__ = has_key def contains(self, variable, extended=False): if extended: return self.has_key(variable) return utils.NormalizedDict.has_key(self, variable) class DelayedVariable(object): def __init__(self, value, error_reporter): self._value = value self._error_reporter = error_reporter def resolve(self, name, variables): try: value = self._resolve(name, variables) except DataError, err: self._error_reporter(unicode(err)) variables.pop(name) raise DataError("Non-existing variable '%s'." % name) variables[name] = value return value def _resolve(self, name, variables): if is_list_var(name): return variables.replace_list(self._value) return variables.replace_scalar(self._value[0])
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 .variablesplitter import VariableIterator 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] == '@' def contains_var(string): return bool(isinstance(string, basestring) and VariableIterator(string, '$@'))
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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. """Implements storing and resolving variables. This package is for internal usage only, and also subject to heavy refactoring in the future. """ import os import tempfile from robot import utils from robot.output import LOGGER from .isvar import contains_var, is_var, is_scalar_var, is_list_var from .variables import Variables from .variableassigner import VariableAssigner from .variablesplitter import VariableSplitter, VariableIterator GLOBAL_VARIABLES = Variables() def init_global_variables(settings): GLOBAL_VARIABLES.clear() _set_cli_vars(settings) for name, value in [ ('${TEMPDIR}', utils.abspath(tempfile.gettempdir())), ('${EXECDIR}', utils.abspath('.')), ('${/}', os.sep), ('${:}', os.pathsep), ('${\\n}', os.linesep), ('${SPACE}', ' '), ('${EMPTY}', ''), ('@{EMPTY}', ()), ('${True}', True), ('${False}', False), ('${None}', None), ('${null}', None), ('${OUTPUT_DIR}', settings['OutputDir']), ('${OUTPUT_FILE}', settings['Output'] or 'NONE'), ('${REPORT_FILE}', settings['Report'] or 'NONE'), ('${LOG_FILE}', settings['Log'] or 'NONE'), ('${LOG_LEVEL}', settings['LogLevel']), ('${DEBUG_FILE}', settings['DebugFile'] or 'NONE'), ('${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: path = utils.find_file(path, file_type='Variable file') 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-2014 Nokia Solutions and Networks # # 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 os import sys import fnmatch from os.path import abspath, dirname, join ROBOTDIR = dirname(abspath(__file__)) def add_path(path, end=False): if not end: remove_path(path) sys.path.insert(0, path) elif not any(fnmatch.fnmatch(p, path) for p in sys.path): sys.path.append(path) def remove_path(path): sys.path = [p for p in sys.path if not fnmatch.fnmatch(p, path)] # When, for example, robot/run.py is executed as a script, the directory # containing the robot module is not added to sys.path automatically but # the robot directory itself is. Former is added to allow importing # the module and the latter removed to prevent accidentally importing # internal modules directly. add_path(dirname(ROBOTDIR)) remove_path(ROBOTDIR) # Default library search locations. add_path(join(ROBOTDIR, 'libraries')) add_path('.', end=True) # Support libraries/resources in PYTHONPATH also with Jython and IronPython. for item in os.getenv('PYTHONPATH', '').split(os.pathsep): add_path(abspath(item), end=True)
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 itertools class RowSplitter(object): _comment_mark = '#' _empty_cell_escape = '${EMPTY}' _line_continuation = '...' _setting_table = 'setting' _tc_table = 'test case' _kw_table = 'keyword' def __init__(self, cols=8, split_multiline_doc=True): self._cols = cols self._split_multiline_doc = split_multiline_doc def split(self, row, table_type): if not row: return self._split_empty_row() indent = self._get_indent(row, table_type) if self._split_multiline_doc and self._is_doc_row(row, table_type): return self._split_doc_row(row, indent) return self._split_row(row, indent) def _split_empty_row(self): yield [] def _get_indent(self, row, table_type): indent = len(list(itertools.takewhile(lambda x: x == '', row))) min_indent = 1 if table_type in [self._tc_table, self._kw_table] else 0 return max(indent, min_indent) def _is_doc_row(self, row, table_type): if table_type == self._setting_table: return len(row) > 1 and row[0] == 'Documentation' if table_type in [self._tc_table, self._kw_table]: return len(row) > 2 and row[1] == '[Documentation]' return False def _split_doc_row(self, row, indent): first, rest = self._split_doc(row[indent+1]) yield row[:indent+1] + [first] + row[indent+2:] while rest: current, rest = self._split_doc(rest) current = [self._line_continuation, current] if current else [self._line_continuation] yield self._indent(current, indent) def _split_doc(self, doc): if '\\n' not in doc: return doc, '' if '\\n ' in doc: doc = doc.replace('\\n ', '\\n') return doc.split('\\n', 1) def _split_row(self, row, indent): while row: current, row = self._split(row) yield self._escape_last_empty_cell(current) if row and indent + 1 < self._cols: row = self._indent(row, indent) def _split(self, data): row, rest = data[:self._cols], data[self._cols:] self._in_comment = any(c.startswith(self._comment_mark) for c in row) rest = self._add_line_continuation(rest) return row, rest def _add_line_continuation(self, data): if data: if self._in_comment and not data[0].startswith(self._comment_mark): data[0] = self._comment_mark + data[0] data = [self._line_continuation] + data return data def _escape_last_empty_cell(self, row): if not row[-1].strip(): row[-1] = self._empty_cell_escape return row def _indent(self, row, indent): return [''] * indent + row
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 .aligners import FirstColumnAligner, ColumnAligner, NullAligner from .dataextractor import DataExtractor from .rowsplitter import RowSplitter class _DataFileFormatter(object): _whitespace = re.compile('\s{2,}') _split_multiline_doc = True def __init__(self, column_count): self._splitter = RowSplitter(column_count, self._split_multiline_doc) self._column_count = column_count self._extractor = DataExtractor(self._want_names_on_first_content_row) def _want_names_on_first_content_row(self, table, name): return True def empty_row_after(self, table): return self._format_row([], table) def format_header(self, table): header = self._format_row(table.header) return self._format_header(header, table) def format_table(self, table): rows = self._extractor.rows_from_table(table) if self._should_split_rows(table): rows = self._split_rows(rows, table) return (self._format_row(r, table) for r in rows) def _should_split_rows(self, table): return not self._should_align_columns(table) def _split_rows(self, original_rows, table): for original in original_rows: for split in self._splitter.split(original, table.type): yield split def _should_align_columns(self, table): return self._is_indented_table(table) and bool(table.header[1:]) def _is_indented_table(self, table): return table is not None and table.type in ['test case', 'keyword'] def _escape_consecutive_whitespace(self, row): return [self._whitespace.sub(self._whitespace_escaper, cell.replace('\n', ' ')) for cell in row] def _whitespace_escaper(self, match): return '\\'.join(match.group(0)) def _format_row(self, row, table=None): raise NotImplementedError def _format_header(self, header, table): raise NotImplementedError class TsvFormatter(_DataFileFormatter): def _format_header(self, header, table): return [self._format_header_cell(cell) for cell in header] def _format_header_cell(self, cell): return '*%s*' % cell if cell else '' def _format_row(self, row, table=None): return self._pad(self._escape(row)) def _escape(self, row): return self._escape_consecutive_whitespace(self._escape_tabs(row)) def _escape_tabs(self, row): return [c.replace('\t', '\\t') for c in row] def _pad(self, row): row = [cell.replace('\n', ' ') for cell in row] return row + [''] * (self._column_count - len(row)) class TxtFormatter(_DataFileFormatter): _test_or_keyword_name_width = 18 _setting_and_variable_name_width = 14 def _format_row(self, row, table=None): row = self._escape(row) aligner = self._aligner_for(table) return aligner.align_row(row) def _aligner_for(self, table): if table and table.type in ['setting', 'variable']: return FirstColumnAligner(self._setting_and_variable_name_width) if self._should_align_columns(table): return ColumnAligner(self._test_or_keyword_name_width, table) return NullAligner() def _format_header(self, header, table): header = ['*** %s ***' % header[0]] + header[1:] aligner = self._aligner_for(table) return aligner.align_row(header) def _want_names_on_first_content_row(self, table, name): return self._should_align_columns(table) and \ len(name) <= self._test_or_keyword_name_width def _escape(self, row): if not row: return row return self._escape_cells(self._escape_consecutive_whitespace(row)) def _escape_cells(self, row): return [row[0]] + [self._escape_empty(cell) for cell in row[1:]] def _escape_empty(self, cell): return cell or '\\' class PipeFormatter(TxtFormatter): def _escape_cells(self, row): return [self._escape_empty(self._escape_pipes(cell)) for cell in row] def _escape_empty(self, cell): return cell or ' ' def _escape_pipes(self, cell): if ' | ' in cell: cell = cell.replace(' | ', ' \\| ') if cell.startswith('| '): cell = '\\' + cell if cell.endswith(' |'): cell = cell[:-1] + '\\|' return cell
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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. TEMPLATE_START = """\ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> html { font-family: Arial,Helvetica,sans-serif; background-color: white; color: black; } table { border-collapse: collapse; empty-cells: show; margin: 1em 0em; border: 1px solid black; } th, td { border: 1px solid black; padding: 0.1em 0.2em; height: 1.5em; width: 12em; } td.colspan4, th.colspan4 { width: 48em; } td.colspan3, th.colspan3 { width: 36em; } td.colspan2, th.colspan2 { width: 24em; } th { background-color: rgb(192, 192, 192); color: black; height: 1.7em; font-weight: bold; text-align: center; letter-spacing: 0.1em; } td.name { background-color: rgb(240, 240, 240); letter-spacing: 0.1em; } td.name, th.name { width: 10em; } </style> <title>%(NAME)s</title> </head> <body> <h1>%(NAME)s</h1> """ TEMPLATE_END = """</body> </html> """
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 DataExtractor(object): """Transforms table of a parsed test data file into a list of rows.""" def __init__(self, want_name_on_first_row=None): self._want_name_on_first_row = want_name_on_first_row or \ (lambda t,n: False) def rows_from_table(self, table): if table.type in ['setting', 'variable']: return self._rows_from_item(table) return self._rows_from_indented_table(table) def _rows_from_indented_table(self, table): items = list(table) for index, item in enumerate(items): for row in self._rows_from_test_or_keyword(item, table): yield row if not self._last(items, index): yield [] def _rows_from_test_or_keyword(self, test_or_keyword, table): rows = list(self._rows_from_item(test_or_keyword, 1)) for r in self._add_name(test_or_keyword.name, rows, table): yield r def _add_name(self, name, rows, table): if rows and self._want_name_on_first_row(table, name): rows[0][0] = name return rows return [[name]] + rows def _rows_from_item(self, item, indent=0): for child in item: if child.is_set(): yield [''] * indent + child.as_list() if child.is_for_loop(): for row in self._rows_from_item(child, indent+1): yield row def _last(self, items, index): return index >= len(items) -1
Python
# Copyright 2008-2014 Nokia Solutions and Networks # # 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. """Implements writing of parsed, and possibly edited, test data back to files. This functionality is used by :meth:`robot.parsing.model.TestCaseFile.save` and indirectly by :mod:`robot.tidy`. External tools should not need to use this package directly. This package is considered stable, although the planned changes to :mod:`robot.parsing` may affect also this package. """ from .datafilewriter import DataFileWriter
Python