code
stringlengths
1
1.72M
language
stringclasses
1 value
# 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 import utils from .formatters import _DataFileFormatter class HtmlFormatter(_DataFileFormatter): _split_multiline_doc = False def _format_row(self, row, table=None): row = self._pad(self._escape_consecutive_whitespace(row), table) if self._is_documentation_row(row): return self._create_documentation_row(row) first_cell = self._create_first_cell(row[0], table) if self._is_indented_documentation_row(row[1:], table): return self._create_indented_documentation_row(first_cell, row[1:]) return [first_cell] + [HtmlCell(c) for c in row[1:]] def _is_documentation_row(self, row): return row[0] == 'Documentation' def _create_documentation_row(self, row): return [NameCell(row[0]), DocumentationCell(row[1], span=self._column_count-1)] def _is_indented_documentation_row(self, cells, table): return self._is_indented_table(table) and cells and \ cells[0] == '[Documentation]' def _create_indented_documentation_row(self, first_cell, cells): start = [first_cell, HtmlCell(cells[0])] if any(c.startswith('#') for c in cells): return start + [HtmlCell(c) for c in cells[1:]] return start + [DocumentationCell(cells[1], self._column_count-2)] def _create_first_cell(self, cell, table): if self._is_indented_table(table) and cell: return AnchorNameCell(cell, 'keyword' if table.type == 'keyword' else 'test') return NameCell(cell) def format_header(self, table): if not self._should_align_columns(table) or len(table.header) == 1: return [HeaderCell(table.header[0], self._column_count)] headers = self._pad_header(table) return [HeaderCell(hdr) for hdr in headers] def _pad_header(self, table): header = table.header return header + [''] * (self._get_column_count(table) - len(header)) def _pad(self, row, table): return row + [''] * (self._get_column_count(table) - len(row)) def _get_column_count(self, table): if table is None or len(table.header) == 1 \ or not self._is_indented_table(table): return self._column_count return max(self._max_column_count(table), len(table.header)) def _max_column_count(self, table): count = 0 for item in table: for child in item: count = max(count, len(child.as_list()) + 1) return count class HtmlCell(object): _backslash_matcher = re.compile(r'(\\+)n ?') def __init__(self, content='', attributes=None, tag='td', escape=True): if escape: content = utils.html_escape(content) self.content = self._replace_newlines(content) self.attributes = attributes or {} self.tag = tag def _replace_newlines(self, content): def replacer(match): backslash_count = len(match.group(1)) if backslash_count % 2 == 1: return '%sn<br>\n' % match.group(1) return match.group() return self._backslash_matcher.sub(replacer, content) class NameCell(HtmlCell): def __init__(self, name='', attributes=None): HtmlCell.__init__(self, name, {'class': 'name'}) class AnchorNameCell(HtmlCell): def __init__(self, name, type_): HtmlCell.__init__(self, self._link_from_name(name, type_), {'class': 'name'}, escape=False) def _link_from_name(self, name, type_): return '<a name="%s_%s">%s</a>' % (type_, utils.attribute_escape(name), utils.html_escape(name)) class DocumentationCell(HtmlCell): def __init__(self, content, span): HtmlCell.__init__(self, content, {'class': 'colspan%d' % span, 'colspan': '%d' % span}) class HeaderCell(HtmlCell): def __init__(self, name, span=1): HtmlCell.__init__(self, name, {'class': 'name', 'colspan': '%d' % span}, tag='th')
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 from robot.errors import DataError from .filewriters import FileWriter class DataFileWriter(object): """Object to write parsed test data file objects back to disk.""" def __init__(self, **options): """ :param `**options`: A :class:`.WritingContext` is created based on these. """ self._options = options def write(self, datafile): """Writes given `datafile` using `**options`. :param datafile: The parsed test data object to be written :type datafile: :py:class:`~robot.parsing.model.TestCaseFile`, :py:class:`~robot.parsing.model.ResourceFile`, :py:class:`~robot.parsing.model.TestDataDirectory` """ with WritingContext(datafile, **self._options) as ctx: FileWriter(ctx).write(datafile) class WritingContext(object): """Contains configuration used in writing a test data file to disk.""" encoding = 'UTF-8' txt_format = 'txt' html_format = 'html' tsv_format = 'tsv' robot_format = 'robot' txt_column_count = 8 html_column_count = 5 tsv_column_count = 8 _formats = [txt_format, html_format, tsv_format, robot_format] def __init__(self, datafile, format='', output=None, pipe_separated=False, txt_separating_spaces=4, line_separator='\n'): """ :param datafile: The datafile to be written. :type datafile: :py:class:`~robot.parsing.model.TestCaseFile`, :py:class:`~robot.parsing.model.ResourceFile`, :py:class:`~robot.parsing.model.TestDataDirectory` :param str format: Output file format. If omitted, read from the extension of the `source` attribute of the given `datafile`. :param output: An open, file-like object used in writing. If omitted, value of `source` attribute of the given `datafile` is used to construct a new file object. :param bool pipe_separated: Whether to use pipes as separator when output file format is txt. :param int txt_separating_spaces: Number of separating spaces between cells in space separated format. :param str line_separator: Line separator used in output files. If `output` is not given, an output file is created based on the source of the given datafile and value of `format`. Examples: Write output in a StringIO instance using format of `datafile.source`:: WriteConfiguration(datafile, output=StringIO) Output file is created from `datafile.source` by stripping extension and replacing it with `html`:: WriteConfiguration(datafile, format='html') """ self.datafile = datafile self.pipe_separated = pipe_separated self.line_separator = line_separator self._given_output = output self.format = self._validate_format(format) or self._format_from_file() self.txt_separating_spaces = txt_separating_spaces self.output = output def __enter__(self): if not self.output: self.output = open(self._output_path(), 'wb') return self def __exit__(self, *exc_info): if self._given_output is None: self.output.close() def _validate_format(self, format): format = format.lower() if format else '' if format and format not in self._formats: raise DataError('Invalid format: %s' % format) return format def _format_from_file(self): return self._format_from_extension(self._source_from_file()) def _format_from_extension(self, path): return os.path.splitext(path)[1][1:].lower() def _output_path(self): return '%s.%s' % (self._base_name(), self.format) def _base_name(self): return os.path.splitext(self._source_from_file())[0] def _source_from_file(self): return getattr(self.datafile, 'initfile', self.datafile.source)
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 .dataextractor import DataExtractor class _Aligner(object): def __init__(self, widths=None): self._widths = widths or [] def align_rows(self, rows): return [self.align_row(r) for r in rows] def align_row(self, row): for index, col in enumerate(row): if len(self._widths) <= index: break row[index] = row[index].ljust(self._widths[index]) return row class FirstColumnAligner(_Aligner): def __init__(self, first_column_width): _Aligner.__init__(self, [first_column_width]) class ColumnAligner(_Aligner): def __init__(self, first_column_width, table): _Aligner.__init__(self, self._count_widths(first_column_width, table)) def _count_widths(self, first_column_width, table): result = [first_column_width] + [len(h) for h in table.header[1:]] for row in DataExtractor().rows_from_table(table): for index, col in enumerate(row[1:]): index += 1 if len(result) <= index: result.append(len(col)) else: result[index] = max(len(col), result[index]) return result class NullAligner(_Aligner): def align_rows(self, rows): return rows def align_row(self, row): return 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. try: import csv except ImportError: # csv module is missing from IronPython < 2.7.1 csv = None from robot import utils from .formatters import TsvFormatter, TxtFormatter, PipeFormatter from .htmlformatter import HtmlFormatter from .htmltemplate import TEMPLATE_START, TEMPLATE_END def FileWriter(context): """Creates and returns a FileWriter object. :param context: Type of returned FileWriter is determined based on `context.format`. `context` is also passed to created writer. :type context: :py:class:`WritingContext` """ if context.format == context.html_format: return HtmlFileWriter(context) if context.format == context.tsv_format: return TsvFileWriter(context) if context.pipe_separated: return PipeSeparatedTxtWriter(context) return SpaceSeparatedTxtWriter(context) class _DataFileWriter(object): def __init__(self, formatter, configuration): self._formatter = formatter self._output = configuration.output self._line_separator = configuration.line_separator self._encoding = configuration.encoding def write(self, datafile): tables = [table for table in datafile if table] for table in tables: self._write_table(table, is_last=table is tables[-1]) def _write_table(self, table, is_last): self._write_header(table) self._write_rows(self._formatter.format_table(table)) if not is_last: self._write_empty_row(table) def _write_header(self, table): self._write_row(self._formatter.format_header(table)) def _write_rows(self, rows): for row in rows: self._write_row(row) def _write_empty_row(self, table): self._write_row(self._formatter.empty_row_after(table)) def _encode(self, row): return row.encode(self._encoding) def _write_row(self, row): raise NotImplementedError class SpaceSeparatedTxtWriter(_DataFileWriter): def __init__(self, configuration): formatter = TxtFormatter(configuration.txt_column_count) self._separator = ' ' * configuration.txt_separating_spaces _DataFileWriter.__init__(self, formatter, configuration) def _write_row(self, row): line = self._separator.join(row).rstrip() + self._line_separator self._output.write(self._encode(line)) class PipeSeparatedTxtWriter(_DataFileWriter): _separator = ' | ' def __init__(self, configuration): formatter = PipeFormatter(configuration.txt_column_count) _DataFileWriter.__init__(self, formatter, configuration) def _write_row(self, row): row = self._separator.join(row) if row: row = '| ' + row + ' |' self._output.write(self._encode(row + self._line_separator)) class TsvFileWriter(_DataFileWriter): def __init__(self, configuration): if not csv: raise RuntimeError('No csv module found. ' 'Writing tab separated format is not possible.') formatter = TsvFormatter(configuration.tsv_column_count) _DataFileWriter.__init__(self, formatter, configuration) self._writer = self._get_writer(configuration) def _get_writer(self, configuration): # Custom dialect needed as a workaround for # http://ironpython.codeplex.com/workitem/33627 dialect = csv.excel_tab() dialect.lineterminator = configuration.line_separator return csv.writer(configuration.output, dialect=dialect) def _write_row(self, row): self._writer.writerow([self._encode(c) for c in row]) class HtmlFileWriter(_DataFileWriter): def __init__(self, configuration): formatter = HtmlFormatter(configuration.html_column_count) _DataFileWriter.__init__(self, formatter, configuration) self._name = configuration.datafile.name self._writer = utils.HtmlWriter(configuration.output, configuration.line_separator, encoding=self._encoding) def write(self, datafile): self._writer.content(TEMPLATE_START % {'NAME': self._name}, escape=False, replace_newlines=True) _DataFileWriter.write(self, datafile) self._writer.content(TEMPLATE_END, escape=False, replace_newlines=True) def _write_table(self, table, is_last): self._writer.start('table', {'id': table.type.replace(' ', ''), 'border': '1'}) _DataFileWriter._write_table(self, table, is_last) self._writer.end('table') def _write_row(self, row): self._writer.start('tr') for cell in row: self._writer.element(cell.tag, cell.content, cell.attributes, escape=False) self._writer.end('tr')
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 .encodingsniffer import get_output_encoding, get_system_encoding from .unic import unic OUTPUT_ENCODING = get_output_encoding() SYSTEM_ENCODING = get_system_encoding() def decode_output(string, force=False): """Decodes bytes from console encoding to Unicode. By default returns Unicode strings as-is. `force` argument can be used on IronPython where all strings are `unicode` and caller knows decoding is needed. """ if isinstance(string, unicode) and not force: return string return unic(string, OUTPUT_ENCODING) def encode_output(string, errors='replace'): """Encodes Unicode to bytes in console encoding.""" # http://ironpython.codeplex.com/workitem/29487 if sys.platform == 'cli': return string return string.encode(OUTPUT_ENCODING, errors) def decode_from_system(string, can_be_from_java=True): """Decodes bytes from system (e.g. cli args or env vars) to Unicode.""" if sys.platform == 'cli': return string if sys.platform.startswith('java') and can_be_from_java: # http://bugs.jython.org/issue1592 from java.lang import String string = String(string) return unic(string, SYSTEM_ENCODING) def encode_to_system(string, errors='replace'): """Encodes Unicode to system encoding (e.g. cli args and env vars).""" return string.encode(SYSTEM_ENCODING, errors)
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 ANY = True UNIXY = os.sep == '/' WINDOWS = not UNIXY JYTHON = sys.platform.startswith('java') if UNIXY: DEFAULT_SYSTEM_ENCODING = 'UTF-8' DEFAULT_OUTPUT_ENCODING = 'UTF-8' else: DEFAULT_SYSTEM_ENCODING = 'cp1252' DEFAULT_OUTPUT_ENCODING = 'cp437' def get_system_encoding(): platform_getters = [(ANY, _get_python_system_encoding), (JYTHON, _get_java_system_encoding), (UNIXY, _get_unixy_encoding), (WINDOWS, _get_windows_system_encoding)] return _get_encoding(platform_getters, DEFAULT_SYSTEM_ENCODING) def get_output_encoding(): platform_getters = [(ANY, _get_stream_output_encoding), (UNIXY, _get_unixy_encoding), (WINDOWS, _get_windows_output_encoding)] return _get_encoding(platform_getters, DEFAULT_OUTPUT_ENCODING) def _get_encoding(platform_getters, default): for platform, getter in platform_getters: if platform: encoding = getter() if _is_valid(encoding): return encoding return default def _get_python_system_encoding(): return sys.getfilesystemencoding() def _get_java_system_encoding(): from java.lang import System return System.getProperty('file.encoding') def _get_unixy_encoding(): for name in 'LANG', 'LC_CTYPE', 'LANGUAGE', 'LC_ALL': if name in os.environ: # Encoding can be in format like `UTF-8` or `en_US.UTF-8` encoding = os.environ[name].split('.')[-1] if _is_valid(encoding): return encoding return None def _get_stream_output_encoding(): # http://bugs.jython.org/issue1568 if WINDOWS and JYTHON: if sys.platform.startswith('java1.5') or sys.version_info < (2, 5, 2): return None # Stream may not have encoding attribute if it is intercepted outside RF # in Python. Encoding is None if process's outputs are redirected. for stream in sys.__stdout__, sys.__stderr__, sys.__stdin__: encoding = getattr(stream, 'encoding', None) if _is_valid(encoding): return encoding return None def _get_windows_system_encoding(): from ctypes import cdll return _call_ctypes(cdll.kernel32.GetACP) def _get_windows_output_encoding(): from ctypes import cdll return _call_ctypes(cdll.kernel32.GetOEMCP) def _call_ctypes(method): method.argtypes = () # needed w/ jython (at least 2.5) try: return 'cp%s' % method() except Exception: # Has failed on IronPython at least once return None def _is_valid(encoding): if not encoding: return False try: 'test'.encode(encoding) except LookupError: return False else: return 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 re import sys import traceback from robot.errors import RobotError from .unic import unic RERAISED_EXCEPTIONS = (KeyboardInterrupt, SystemExit, MemoryError) if sys.platform.startswith('java'): from java.io import StringWriter, PrintWriter from java.lang import Throwable, OutOfMemoryError RERAISED_EXCEPTIONS += (OutOfMemoryError,) else: Throwable = () def get_error_message(): """Returns error message of the last occurred exception. This method handles also exceptions containing unicode messages. Thus it MUST be used to get messages from all exceptions originating outside the framework. """ return ErrorDetails().message def get_error_details(): """Returns error message and details of the last occurred exception. """ details = ErrorDetails() return details.message, details.traceback def ErrorDetails(): """This factory returns an object that wraps the last occurred exception It has attributes `message`, `traceback` and `error`, where `message` contains type and message of the original error, `traceback` contains the traceback/stack trace and `error` contains the original error instance. """ exc_type, exc_value, exc_traceback = sys.exc_info() if exc_type in RERAISED_EXCEPTIONS: raise exc_value details = PythonErrorDetails \ if not isinstance(exc_value, Throwable) else JavaErrorDetails return details(exc_type, exc_value, exc_traceback) class _ErrorDetails(object): _generic_exceptions = ('AssertionError', 'AssertionFailedError', 'Exception', 'Error', 'RuntimeError', 'RuntimeException', 'DataError', 'TimeoutError', 'RemoteError') def __init__(self, exc_type, exc_value, exc_traceback): self.error = exc_value self._exc_value = exc_value self._exc_type = exc_type self._exc_traceback = exc_traceback self._message = None self._traceback = None @property def message(self): if self._message is None: self._message = self._get_message() return self._message @property def traceback(self): if self._traceback is None: self._traceback = self._get_details() return self._traceback def _get_name(self, exc_type): try: return exc_type.__name__ except AttributeError: return unic(exc_type) def _format_message(self, name, message): message = unic(message or '') message = self._clean_up_message(message, name) name = name.split('.')[-1] # Use only last part of the name if not message: return name if name in self._generic_exceptions or \ getattr(self.error, 'ROBOT_SUPPRESS_NAME', False): return message return '%s: %s' % (name, message) def _clean_up_message(self, message, name): return message class PythonErrorDetails(_ErrorDetails): def _get_message(self): # If exception is a "string exception" without a message exc_value is None if self._exc_value is None: return unic(self._exc_type) name = self._get_name(self._exc_type) try: msg = unicode(self._exc_value) except UnicodeError: # Happens if message is Unicode and version < 2.6 msg = ' '.join(unic(a) for a in self._exc_value.args) return self._format_message(name, msg) def _get_details(self): if isinstance(self._exc_value, RobotError): return self._exc_value.details return 'Traceback (most recent call last):\n' + self._get_traceback() def _get_traceback(self): tb = self._exc_traceback while tb and self._is_excluded_traceback(tb): tb = tb.tb_next return ''.join(traceback.format_tb(tb)).rstrip() or ' None' def _is_excluded_traceback(self, traceback): module = traceback.tb_frame.f_globals.get('__name__') return module and module.startswith('robot.') class JavaErrorDetails(_ErrorDetails): _java_trace_re = re.compile('^\s+at (\w.+)') _ignored_java_trace = ('org.python.', 'robot.running.', 'robot$py.', 'sun.reflect.', 'java.lang.reflect.') def _get_message(self): exc_name = self._get_name(self._exc_type) # OOME.getMessage and even toString seem to throw NullPointerException if not self._is_out_of_memory_error(self._exc_type): exc_msg = self._exc_value.getMessage() else: exc_msg = str(self._exc_value) return self._format_message(exc_name, exc_msg) def _is_out_of_memory_error(self, exc_type): return exc_type is OutOfMemoryError def _get_details(self): # OOME.printStackTrace seems to throw NullPointerException if self._is_out_of_memory_error(self._exc_type): return '' output = StringWriter() self._exc_value.printStackTrace(PrintWriter(output)) details = '\n'.join(line for line in output.toString().splitlines() if not self._is_ignored_stack_trace_line(line)) msg = unic(self._exc_value.getMessage() or '') if msg: details = details.replace(msg, '', 1) return details def _is_ignored_stack_trace_line(self, line): if not line: return True res = self._java_trace_re.match(line) if res is None: return False location = res.group(1) for entry in self._ignored_java_trace: if location.startswith(entry): return True return False def _clean_up_message(self, msg, name): msg = self._remove_stack_trace_lines(msg) return self._remove_exception_name(msg, name).strip() def _remove_stack_trace_lines(self, msg): lines = msg.splitlines() while lines: if self._java_trace_re.match(lines[-1]): lines.pop() else: break return '\n'.join(lines) def _remove_exception_name(self, msg, name): tokens = msg.split(':', 1) if len(tokens) == 2 and tokens[0] == name: msg = tokens[1] return msg
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 codecs import BOM_UTF8 class Utf8Reader(object): def __init__(self, path_or_file): if isinstance(path_or_file, basestring): self._file = open(path_or_file, 'rb') self._close = True else: self._file = path_or_file self._close = False # IronPython handles BOM incorrectly if file not opened in binary mode: # http://code.google.com/p/robotframework/issues/detail?id=1580 if hasattr(self._file, 'mode') and self._file.mode != 'rb': raise ValueError('Only files in binary mode accepted.') def __enter__(self): return self def __exit__(self, *exc_info): if self._close: self._file.close() def read(self): return self._decode(self._file.read()) def readlines(self): for index, line in enumerate(self._file.readlines()): yield self._decode(line, remove_bom=index == 0) def _decode(self, content, remove_bom=True): if remove_bom and content.startswith(BOM_UTF8): content = content[len(BOM_UTF8):] return content.decode('UTF-8')
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 base64 import sys def compress_text(text): return base64.b64encode(_compress(text.encode('UTF-8'))) if not sys.platform.startswith('java'): import zlib def _compress(text): return zlib.compress(text, 9) else: # Custom compress implementation needed to avoid memory leak: # http://bugs.jython.org/issue1775 # This is based on the zlib.compress in Jython 2.5.2 but has a memory # leak fix and is also a little faster. from java.util.zip import Deflater import jarray _DEFLATOR = Deflater(9, False) def _compress(text): _DEFLATOR.setInput(text) _DEFLATOR.finish() buf = jarray.zeros(1024, 'b') compressed = [] while not _DEFLATOR.finished(): length = _DEFLATOR.deflate(buf, 0, 1024) compressed.append(buf[:length].tostring()) _DEFLATOR.reset() return ''.join(compressed)
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 import urllib from robot.errors import DataError from .encoding import decode_from_system if os.sep == '\\': CASE_INSENSITIVE_FILESYSTEM = True else: try: CASE_INSENSITIVE_FILESYSTEM = os.listdir('/tmp') == os.listdir('/TMP') except OSError: CASE_INSENSITIVE_FILESYSTEM = False def normpath(path): """Returns path in normalized and absolute format. On case-insensitive file systems the path is also case normalized. If that is not desired, abspath should be used instead. """ path = abspath(path) if CASE_INSENSITIVE_FILESYSTEM: path = path.lower() return path def abspath(path): """Replacement for os.path.abspath with some bug fixes and enhancements. 1) Converts non-Unicode paths to Unicode using file system encoding 2) At least Jython 2.5.1 on Windows returns wrong path with 'c:'. 3) Python until 2.6.5 and at least Jython 2.5.1 don't handle non-ASCII characters in the working directory: http://bugs.python.org/issue3426 """ if not isinstance(path, unicode): path = decode_from_system(path) if os.sep == '\\' and len(path) == 2 and path[1] == ':': return path + '\\' if not os.path.isabs(path): path = os.path.join(os.getcwdu(), path) return os.path.normpath(path) def get_link_path(target, base): """Returns a relative path to a target from a base. If base is an existing file, then its parent directory is considered. Otherwise, base is assumed to be a directory. Rationale: os.path.relpath is not available before Python 2.6 """ path = _get_pathname(target, base) url = urllib.pathname2url(path.encode('UTF-8')) if os.path.isabs(path): url = 'file:' + url # At least Jython seems to use 'C|/Path' and not 'C:/Path' if os.sep == '\\' and '|/' in url: url = url.replace('|/', ':/', 1) return url.replace('%5C', '/').replace('%3A', ':').replace('|', ':') def _get_pathname(target, base): target = abspath(target) base = abspath(base) if os.path.isfile(base): base = os.path.dirname(base) if base == target: return os.path.basename(target) base_drive, base_path = os.path.splitdrive(base) # if in Windows and base and link on different drives if os.path.splitdrive(target)[0] != base_drive: return target common_len = len(_common_path(base, target)) if base_path == os.sep: return target[common_len:] if common_len == len(base_drive) + len(os.sep): common_len -= len(os.sep) dirs_up = os.sep.join([os.pardir] * base[common_len:].count(os.sep)) return os.path.join(dirs_up, target[common_len + len(os.sep):]) def _common_path(p1, p2): """Returns the longest path common to p1 and p2. Rationale: as os.path.commonprefix is character based, it doesn't consider path separators as such, so it may return invalid paths: commonprefix(('/foo/bar/', '/foo/baz.txt')) -> '/foo/ba' (instead of /foo) """ while p1 and p2: if p1 == p2: return p1 if len(p1) > len(p2): p1 = os.path.dirname(p1) else: p2 = os.path.dirname(p2) return '' def find_file(path, basedir='.', file_type=None): path = os.path.normpath(path.replace('/', os.sep)) for base in [basedir] + sys.path: if not (base and os.path.isdir(base)): continue if not isinstance(base, unicode): base = decode_from_system(base) ret = os.path.abspath(os.path.join(base, path)) if os.path.isfile(ret): return ret if os.path.isdir(ret) and os.path.isfile(os.path.join(ret, '__init__.py')): return ret default = file_type or 'File' file_type = {'Library': 'Test library', 'Variables': 'Variable file', 'Resource': 'Resource file'}.get(file_type, default) raise DataError("%s '%s' does not exist." % (file_type, path))
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 .markuputils import html_escape, xml_escape, attribute_escape class _MarkupWriter(object): def __init__(self, output, line_separator='\n', encoding='UTF-8'): """ :param output: Either an opened, file like object, or a path to the desired output file. In the latter case, the file is created and clients should use :py:meth:`close` method to close it. :param line_separator: Defines the used line separator. :param encoding: Encoding to be used to encode all text written to the output file. If `None`, text will not be encoded. """ if isinstance(output, basestring): output = open(output, 'w') self.output = output self._line_separator = line_separator self._encoding = encoding self._preamble() def _preamble(self): pass def start(self, name, attrs=None, newline=True): self._write('<%s %s>' % (name, self._format_attrs(attrs)) if attrs else '<%s>' % name, newline) def _format_attrs(self, attrs): return ' '.join('%s="%s"' % (name, attribute_escape(attrs[name])) for name in self._order_attrs(attrs)) def _order_attrs(self, attrs): return attrs def content(self, content=None, escape=True, newline=False, replace_newlines=False): if content: if replace_newlines: content = content.replace('\n', self._line_separator) self._write(self._escape(content) if escape else content, newline) def _escape(self, content): raise NotImplementedError def end(self, name, newline=True): self._write('</%s>' % name, newline) def element(self, name, content=None, attrs=None, escape=True, newline=True, replace_newlines=False): self.start(name, attrs, newline=False) self.content(content, escape, replace_newlines) self.end(name, newline) def close(self): """Closes the underlying output file.""" self.output.close() def _write(self, text, newline=False): self.output.write(self._encode(text)) if newline: self.output.write(self._line_separator) def _encode(self, text): return text.encode(self._encoding) if self._encoding else text class HtmlWriter(_MarkupWriter): def _order_attrs(self, attrs): return sorted(attrs) # eases testing def _escape(self, content): return html_escape(content) class XmlWriter(_MarkupWriter): def _preamble(self): self._write('<?xml version="1.0" encoding="%s"?>' % self._encoding, newline=True) def _escape(self, text): return xml_escape(text) class NullMarkupWriter(object): """Null implementation of _MarkupWriter interface""" __init__ = start = content = element = end = close = 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. from .charwidth import get_char_width from .misc import seq2str2 from .unic import unic _MAX_ASSIGN_LENGTH = 200 _MAX_ERROR_LINES = 40 _MAX_ERROR_LINE_LENGTH = 78 _ERROR_CUT_EXPLN = ' [ Message content over the limit has been removed. ]' def cut_long_message(msg): lines = msg.splitlines() lengths = _count_line_lengths(lines) if sum(lengths) <= _MAX_ERROR_LINES: return msg start = _prune_excess_lines(lines, lengths) end = _prune_excess_lines(lines, lengths, from_end=True) return '\n'.join(start + [_ERROR_CUT_EXPLN] + end) def _prune_excess_lines(lines, lengths, from_end=False): if from_end: lines.reverse() lengths.reverse() ret = [] total = 0 limit = _MAX_ERROR_LINES/2 for line, length in zip(lines[:limit], lengths[:limit]): if total + length >= limit: ret.append(_cut_long_line(line, total, from_end)) break total += length ret.append(line) if from_end: ret.reverse() return ret def _cut_long_line(line, used, from_end): available_lines = _MAX_ERROR_LINES/2 - used available_chars = available_lines * _MAX_ERROR_LINE_LENGTH - 3 if len(line) > available_chars: if not from_end: line = line[:available_chars] + '...' else: line = '...' + line[-available_chars:] return line def _count_line_lengths(lines): return [ _count_virtual_line_length(line) for line in lines ] def _count_virtual_line_length(line): if not line: return 1 lines, remainder = divmod(len(line), _MAX_ERROR_LINE_LENGTH) return lines if not remainder else lines + 1 def format_assign_message(variable, value, cut_long=True): value = unic(value) if variable.startswith('$') else seq2str2(value) if cut_long and len(value) > _MAX_ASSIGN_LENGTH: value = value[:_MAX_ASSIGN_LENGTH] + '...' return '%s = %s' % (variable, value) def get_console_length(text): return sum(get_char_width(char) for char in text) def pad_console_length(text, width): if width < 5: width = 5 diff = get_console_length(text) - width if diff > 0: text = _lose_width(text, diff+3) + '...' return _pad_width(text, width) def _pad_width(text, width): more = width - get_console_length(text) return text + ' ' * more def _lose_width(text, diff): lost = 0 while lost < diff: lost += get_console_length(text[-1]) text = text[:-1] return text
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.path from StringIO import StringIO _IRONPYTHON = sys.platform == 'cli' _ERROR = 'No valid ElementTree XML parser module found' if not _IRONPYTHON: try: from xml.etree import cElementTree as ET except ImportError: try: import cElementTree as ET except ImportError: try: from xml.etree import ElementTree as ET except ImportError: try: from elementtree import ElementTree as ET except ImportError: raise ImportError(_ERROR) else: # Cannot use standard ET available on IronPython because it is broken # both in 2.7.0 and 2.7.1: # http://ironpython.codeplex.com/workitem/31923 # http://ironpython.codeplex.com/workitem/21407 try: from elementtree import ElementTree as ET except ImportError: raise ImportError(_ERROR) # cElementTree.VERSION seems to always be 1.0.6. We want real API version. if ET.VERSION < '1.3' and hasattr(ET, 'tostringlist'): ET.VERSION = '1.3' class ETSource(object): def __init__(self, source): self._source = source self._opened = None def __enter__(self): self._opened = self._open_source_if_necessary() return self._opened or self._source def __exit__(self, exc_type, exc_value, exc_trace): if self._opened: self._opened.close() def __str__(self): if self._source_is_file_name(): return self._source if hasattr(self._source, 'name'): return self._source.name return '<in-memory file>' def _source_is_file_name(self): return isinstance(self._source, basestring) \ and not self._source.lstrip().startswith('<') def _open_source_if_necessary(self): if self._source_is_file_name(): return self._open_file(self._source) if isinstance(self._source, basestring): return self._open_string_io(self._source) return None if not _IRONPYTHON: # File is opened, and later closed, because ElementTree had a bug that # it didn't close files it had opened. This caused problems with Jython # especially on Windows: http://bugs.jython.org/issue1598 # The bug has now been fixed in ET and worked around in Jython 2.5.2. def _open_file(self, source): return open(source, 'rb') def _open_string_io(self, source): return StringIO(source.encode('UTF-8')) else: # File cannot be opened on IronPython, however, as ET does not seem to # handle non-ASCII characters correctly in that case. We want to check # that the file exists even in that case, though. def _open_file(self, source): if not os.path.exists(source): raise IOError(2, 'No such file', source) return None def _open_string_io(self, source): return StringIO(source)
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 getopt # optparse was not supported by Jython 2.2 import os import re import sys import glob import string import textwrap from robot.errors import DataError, Information, FrameworkError from robot.version import get_full_version from .misc import plural_or_not from .encoding import decode_output, decode_from_system from .utf8reader import Utf8Reader ESCAPES = dict( space = ' ', apos = "'", quot = '"', lt = '<', gt = '>', pipe = '|', star = '*', comma = ',', slash = '/', semic = ';', colon = ':', quest = '?', hash = '#', amp = '&', dollar = '$', percent = '%', at = '@', exclam = '!', paren1 = '(', paren2 = ')', square1 = '[', square2 = ']', curly1 = '{', curly2 = '}', bslash = '\\' ) class ArgumentParser: _opt_line_re = re.compile(''' ^\s{1,4} # 1-4 spaces in the beginning of the line ((-\S\s)*) # all possible short options incl. spaces (group 1) --(\S{2,}) # required long option (group 3) (\s\S+)? # optional value (group 4) (\s\*)? # optional '*' telling option allowed multiple times (group 5) ''', re.VERBOSE) def __init__(self, usage, name=None, version=None, arg_limits=None, validator=None, env_options=None, auto_help=True, auto_version=True, auto_escape=True, auto_pythonpath=True, auto_argumentfile=True): """Available options and tool name are read from the usage. Tool name is got from the first row of the usage. It is either the whole row or anything before first ' -- '. """ if not usage: raise FrameworkError('Usage cannot be empty') self.name = name or usage.splitlines()[0].split(' -- ')[0].strip() self.version = version or get_full_version() self._usage = usage self._arg_limit_validator = ArgLimitValidator(arg_limits) self._validator = validator self._auto_help = auto_help self._auto_version = auto_version self._auto_escape = auto_escape self._auto_pythonpath = auto_pythonpath self._auto_argumentfile = auto_argumentfile self._env_options = env_options self._short_opts = '' self._long_opts = [] self._multi_opts = [] self._toggle_opts = [] self._names = [] self._short_to_long = {} self._expected_args = () self._create_options(usage) def parse_args(self, args): """Parse given arguments and return options and positional arguments. Arguments must be given as a list and are typically sys.argv[1:]. Options are returned as a dictionary where long options are keys. Value is a string for those options that can be given only one time (if they are given multiple times the last value is used) or None if the option is not used at all. Value for options that can be given multiple times (denoted with '*' in the usage) is a list which contains all the given values and is empty if options are not used. Options not taken arguments have value False when they are not set and True otherwise. Positional arguments are returned as a list in the order they are given. If 'check_args' is True, this method will automatically check that correct number of arguments, as parsed from the usage line, are given. If the last argument in the usage line ends with the character 's', the maximum number of arguments is infinite. Possible errors in processing arguments are reported using DataError. Some options have a special meaning and are handled automatically if defined in the usage and given from the command line: --escape option can be used to automatically unescape problematic characters given in an escaped format. --argumentfile can be used to automatically read arguments from a specified file. When --argumentfile is used, the parser always allows using it multiple times. Adding '*' to denote that is thus recommend. A special value 'stdin' can be used to read arguments from stdin instead of a file. --pythonpath can be used to add extra path(s) to sys.path. --help and --version automatically generate help and version messages. Version is generated based on the tool name and version -- see __init__ for information how to set them. Help contains the whole usage given to __init__. Possible <VERSION> text in the usage is replaced with the given version. Possible <--ESCAPES--> is replaced with available escapes so that they are wrapped to multiple lines but take the same amount of horizontal space as <---ESCAPES--->. Both help and version are wrapped to Information exception. """ if self._env_options: args = os.getenv(self._env_options, '').split() + list(args) args = [decode_from_system(a) for a in args] if self._auto_argumentfile: args = self._process_possible_argfile(args) opts, args = self._parse_args(args) opts, args = self._handle_special_options(opts, args) self._arg_limit_validator(args) if self._validator: opts, args = self._validator(opts, args) return opts, args def _handle_special_options(self, opts, args): if self._auto_escape and opts.get('escape'): opts, args = self._unescape_opts_and_args(opts, args) if self._auto_help and opts.get('help'): self._raise_help() if self._auto_version and opts.get('version'): self._raise_version() if self._auto_pythonpath and opts.get('pythonpath'): sys.path = self._get_pythonpath(opts['pythonpath']) + sys.path for auto, opt in [(self._auto_help, 'help'), (self._auto_version, 'version'), (self._auto_escape, 'escape'), (self._auto_pythonpath, 'pythonpath'), (self._auto_argumentfile, 'argumentfile')]: if auto and opt in opts: opts.pop(opt) return opts, args def _parse_args(self, args): args = [self._lowercase_long_option(a) for a in args] try: opts, args = getopt.getopt(args, self._short_opts, self._long_opts) except getopt.GetoptError, err: raise DataError(err.msg) return self._process_opts(opts), self._glob_args(args) def _lowercase_long_option(self, opt): if not opt.startswith('--'): return opt if '=' not in opt: return opt.lower() opt, value = opt.split('=', 1) return '%s=%s' % (opt.lower(), value) def _unescape_opts_and_args(self, opts, args): try: escape_strings = opts['escape'] except KeyError: raise FrameworkError("No 'escape' in options") escapes = self._get_escapes(escape_strings) for name, value in opts.items(): if name != 'escape': opts[name] = self._unescape(value, escapes) return opts, [self._unescape(arg, escapes) for arg in args] def _process_possible_argfile(self, args): options = ['--argumentfile'] for short_opt, long_opt in self._short_to_long.items(): if long_opt == 'argumentfile': options.append('-'+short_opt) return ArgFileParser(options).process(args) def _get_escapes(self, escape_strings): escapes = {} for estr in escape_strings: try: name, value = estr.split(':', 1) except ValueError: raise DataError("Invalid escape string syntax '%s'. " "Expected: what:with" % estr) try: escapes[value] = ESCAPES[name.lower()] except KeyError: raise DataError("Invalid escape '%s'. Available: %s" % (name, self._get_available_escapes())) return escapes def _unescape(self, value, escapes): if value in [None, True, False]: return value if isinstance(value, list): return [self._unescape(item, escapes) for item in value] for esc_name, esc_value in escapes.items(): if esc_name in value: value = value.replace(esc_name, esc_value) return value def _process_opts(self, opt_tuple): opts = self._init_opts() for name, value in opt_tuple: name = self._get_name(name) if name in self._multi_opts: opts[name].append(value) elif name in self._toggle_opts: opts[name] = not opts[name] else: opts[name] = value return opts def _glob_args(self, args): temp = [] for path in args: paths = sorted(glob.glob(path)) if paths: temp.extend(paths) else: temp.append(path) return temp def _init_opts(self): opts = {} for name in self._names: if name in self._multi_opts: opts[name] = [] elif name in self._toggle_opts: opts[name] = False else: opts[name] = None return opts def _get_name(self, name): name = name.lstrip('-') try: return self._short_to_long[name] except KeyError: return name def _create_options(self, usage): for line in usage.splitlines(): res = self._opt_line_re.match(line) if res: self._create_option(short_opts=[o[1] for o in res.group(1).split()], long_opt=res.group(3).lower(), takes_arg=bool(res.group(4)), is_multi=bool(res.group(5))) def _create_option(self, short_opts, long_opt, takes_arg, is_multi): if long_opt in self._names: self._raise_option_multiple_times_in_usage('--' + long_opt) self._names.append(long_opt) for sopt in short_opts: if sopt in self._short_to_long: self._raise_option_multiple_times_in_usage('-' + sopt) self._short_to_long[sopt] = long_opt if is_multi: self._multi_opts.append(long_opt) if takes_arg: long_opt += '=' short_opts = [sopt+':' for sopt in short_opts] else: self._toggle_opts.append(long_opt) self._long_opts.append(long_opt) self._short_opts += (''.join(short_opts)) def _get_pythonpath(self, paths): if isinstance(paths, basestring): paths = [paths] temp = [] for path in self._split_pythonpath(paths): temp.extend(glob.glob(path)) return [os.path.abspath(path) for path in temp if path] def _split_pythonpath(self, paths): # paths may already contain ':' as separator tokens = ':'.join(paths).split(':') if os.sep == '/': return tokens # Fix paths split like 'c:\temp' -> 'c', '\temp' ret = [] drive = '' for item in tokens: item = item.replace('/', '\\') if drive and item.startswith('\\'): ret.append('%s:%s' % (drive, item)) drive = '' continue if drive: ret.append(drive) drive = '' if len(item) == 1 and item in string.letters: drive = item else: ret.append(item) if drive: ret.append(drive) return ret def _get_available_escapes(self): names = sorted(ESCAPES.keys(), key=str.lower) return ', '.join('%s (%s)' % (n, ESCAPES[n]) for n in names) def _raise_help(self): msg = self._usage if self.version: msg = msg.replace('<VERSION>', self.version) def replace_escapes(res): escapes = 'Available escapes: ' + self._get_available_escapes() lines = textwrap.wrap(escapes, width=len(res.group(2))) indent = ' ' * len(res.group(1)) return '\n'.join(indent + line for line in lines) msg = re.sub('( *)(<-+ESCAPES-+>)', replace_escapes, msg) raise Information(msg) def _raise_version(self): raise Information('%s %s' % (self.name, self.version)) def _raise_option_multiple_times_in_usage(self, opt): raise FrameworkError("Option '%s' multiple times in usage" % opt) class ArgLimitValidator(object): def __init__(self, arg_limits): self._min_args, self._max_args = self._parse_arg_limits(arg_limits) def _parse_arg_limits(self, arg_limits): if arg_limits is None: return 0, sys.maxint if isinstance(arg_limits, int): return arg_limits, arg_limits if len(arg_limits) == 1: return arg_limits[0], sys.maxint return arg_limits[0], arg_limits[1] def __call__(self, args): if not (self._min_args <= len(args) <= self._max_args): self._raise_invalid_args(self._min_args, self._max_args, len(args)) def _raise_invalid_args(self, min_args, max_args, arg_count): min_end = plural_or_not(min_args) if min_args == max_args: expectation = "%d argument%s" % (min_args, min_end) elif max_args != sys.maxint: expectation = "%d to %d arguments" % (min_args, max_args) else: expectation = "at least %d argument%s" % (min_args, min_end) raise DataError("Expected %s, got %d." % (expectation, arg_count)) class ArgFileParser(object): def __init__(self, options): self._options = options def process(self, args): while True: path, replace = self._get_index(args) if not path: break args[replace] = self._get_args(path) return args def _get_index(self, args): for opt in self._options: start = opt + '=' if opt.startswith('--') else opt for index, arg in enumerate(args): # Handles `--argumentfile foo` and `-A foo` if arg == opt and index + 1 < len(args): return args[index+1], slice(index, index+2) # Handles `--argumentfile=foo` and `-Afoo` if arg.startswith(start): return arg[len(start):], slice(index, index+1) return None, -1 def _get_args(self, path): if path.upper() != 'STDIN': content = self._read_from_file(path) else: content = self._read_from_stdin() return self._process_file(content) def _read_from_file(self, path): try: with Utf8Reader(path) as reader: return reader.read() except (IOError, UnicodeError), err: raise DataError("Opening argument file '%s' failed: %s" % (path, err)) def _read_from_stdin(self): content = sys.__stdin__.read() if sys.platform != 'cli': content = decode_output(content) return content def _process_file(self, content): args = [] for line in content.splitlines(): line = line.strip() if line.startswith('-'): args.extend(self._split_option(line)) elif line and not line.startswith('#'): args.append(line) return args def _split_option(self, line): separator = self._get_option_separator(line) if not separator: return [line] option, value = line.split(separator, 1) if separator == ' ': value = value.strip() return [option, value] def _get_option_separator(self, line): if ' ' not in line and '=' not in line: return None if '=' not in line: return ' ' if ' ' not in line: return '=' return ' ' if line.index(' ') < line.index('=') else '='
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 if sys.platform.startswith('java'): from org.python.core import PyReflectedFunction, PyReflectedConstructor def is_java_init(init): return isinstance(init, PyReflectedConstructor) def is_java_method(method): func = method.im_func if hasattr(method, 'im_func') else method return isinstance(func, PyReflectedFunction) else: def is_java_init(init): return False def is_java_method(method): return False
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 time import datetime from .normalizing import normalize from .misc import plural_or_not def _get_timetuple(epoch_secs=None): if epoch_secs is None: # can also be 0 (at least in unit tests) epoch_secs = time.time() secs, millis = _float_secs_to_secs_and_millis(epoch_secs) timetuple = time.localtime(secs)[:6] # from year to secs return timetuple + (millis,) def _float_secs_to_secs_and_millis(secs): isecs = int(secs) millis = int(round((secs - isecs) * 1000)) return (isecs, millis) if millis < 1000 else (isecs+1, 0) START_TIME = _get_timetuple() def timestr_to_secs(timestr): """Parses time in format like '1h 10s' and returns time in seconds (float). Given time must be in format '1d 2h 3m 4s 5ms' with following rules: - Time parts having zero value can be ignored (e.g. '3m 4s' is ok) - Format is case and space insensitive - Instead of 'd' it is also possible to use 'day' or 'days' - Instead of 'h' also 'hour' and 'hours' are ok - Instead of 'm' also 'minute', 'minutes', 'min' and 'mins' are ok - Instead of 's' also 'second', 'seconds', 'sec' and 'secs' are ok - Instead of 'ms' also 'millisecond', 'milliseconds' and 'millis' are ok - It is possible to give time only as a float and then it is considered to be seconds (e.g. '123', '123.0', '123s', '2min 3s' are all equivelant) """ try: secs = _timestr_to_secs(timestr) except (ValueError, TypeError): raise ValueError("Invalid time string '%s'" % timestr) return round(secs, 3) def _timestr_to_secs(timestr): timestr = _normalize_timestr(timestr) if timestr == '': raise ValueError try: return float(timestr) except ValueError: pass millis = secs = mins = hours = days = 0 if timestr[0] == '-': sign = -1 timestr = timestr[1:] else: sign = 1 temp = [] for c in timestr: if c == 'x': millis = float(''.join(temp)); temp = [] elif c == 's': secs = float(''.join(temp)); temp = [] elif c == 'm': mins = float(''.join(temp)); temp = [] elif c == 'h': hours = float(''.join(temp)); temp = [] elif c == 'p': days = float(''.join(temp)); temp = [] else: temp.append(c) if temp: raise ValueError return sign * (millis/1000 + secs + mins*60 + hours*60*60 + days*60*60*24) def _normalize_timestr(timestr): if isinstance(timestr, (int, long, float)): return timestr timestr = normalize(timestr) for item in 'milliseconds', 'millisecond', 'millis': timestr = timestr.replace(item, 'ms') for item in 'seconds', 'second', 'secs', 'sec': timestr = timestr.replace(item, 's') for item in 'minutes', 'minute', 'mins', 'min': timestr = timestr.replace(item, 'm') for item in 'hours', 'hour': timestr = timestr.replace(item, 'h') for item in 'days', 'day': timestr = timestr.replace(item, 'd') # 1) 'ms' -> 'x' to ease processing later # 2) 'd' -> 'p' because float('1d') returns 1.0 in Jython (bug submitted) return timestr.replace('ms','x').replace('d','p') def secs_to_timestr(secs, compact=False): """Converts time in seconds to a string representation. Returned string is in format like '1 day 2 hours 3 minutes 4 seconds 5 milliseconds' with following rules: - Time parts having zero value are not included (e.g. '3 minutes 4 seconds' instead of '0 days 0 hours 3 minutes 4 seconds') - Hour part has a maximun of 23 and minutes and seconds both have 59 (e.g. '1 minute 40 seconds' instead of '100 seconds') If compact has value 'True', short suffixes are used. (e.g. 1d 2h 3min 4s 5ms) """ return _SecsToTimestrHelper(secs, compact).get_value() class _SecsToTimestrHelper: def __init__(self, float_secs, compact): self._compact = compact self._ret = [] self._sign, millis, secs, mins, hours, days \ = self._secs_to_components(float_secs) self._add_item(days, 'd', 'day') self._add_item(hours, 'h', 'hour') self._add_item(mins, 'min', 'minute') self._add_item(secs, 's', 'second') self._add_item(millis, 'ms', 'millisecond') def get_value(self): if len(self._ret) > 0: return self._sign + ' '.join(self._ret) return '0s' if self._compact else '0 seconds' def _add_item(self, value, compact_suffix, long_suffix): if value == 0: return if self._compact: suffix = compact_suffix else: suffix = ' %s%s' % (long_suffix, plural_or_not(value)) self._ret.append('%d%s' % (value, suffix)) def _secs_to_components(self, float_secs): if float_secs < 0: sign = '- ' float_secs = abs(float_secs) else: sign = '' int_secs, millis = _float_secs_to_secs_and_millis(float_secs) secs = int_secs % 60 mins = int(int_secs / 60) % 60 hours = int(int_secs / (60*60)) % 24 days = int(int_secs / (60*60*24)) return sign, millis, secs, mins, hours, days def format_time(timetuple_or_epochsecs, daysep='', daytimesep=' ', timesep=':', millissep=None, gmtsep=None): """Returns a timestamp formatted from given time using separators. Time can be given either as a timetuple or seconds after epoch. Timetuple is (year, month, day, hour, min, sec[, millis]), where parts must be integers and millis is required only when millissep is not None. Notice that this is not 100% compatible with standard Python timetuples which do not have millis. Seconds after epoch can be either an integer or a float. """ if isinstance(timetuple_or_epochsecs, (int, long, float)): timetuple = _get_timetuple(timetuple_or_epochsecs) else: timetuple = timetuple_or_epochsecs daytimeparts = ['%02d' % t for t in timetuple[:6]] day = daysep.join(daytimeparts[:3]) time_ = timesep.join(daytimeparts[3:6]) millis = millissep and '%s%03d' % (millissep, timetuple[6]) or '' return day + daytimesep + time_ + millis + _diff_to_gmt(gmtsep) def _diff_to_gmt(sep): if not sep: return '' if time.altzone == 0: sign = '' elif time.altzone > 0: sign = '-' else: sign = '+' minutes = abs(time.altzone) / 60.0 hours, minutes = divmod(minutes, 60) return '%sGMT%s%s%02d:%02d' % (sep, sep, sign, hours, minutes) def get_time(format='timestamp', time_=None): """Return the given or current time in requested format. If time is not given, current time is used. How time is returned is is deternined based on the given 'format' string as follows. Note that all checks are case insensitive. - If 'format' contains word 'epoch' the time is returned in seconds after the unix epoch. - If 'format' contains any of the words 'year', 'month', 'day', 'hour', 'min' or 'sec' only selected parts are returned. The order of the returned parts is always the one in previous sentence and order of words in 'format' is not significant. Parts are returned as zero padded strings (e.g. May -> '05'). - Otherwise (and by default) the time is returned as a timestamp string in format '2006-02-24 15:08:31' """ time_ = int(time_ or time.time()) format = format.lower() # 1) Return time in seconds since epoc if 'epoch' in format: return time_ timetuple = time.localtime(time_) parts = [] for i, match in enumerate('year month day hour min sec'.split()): if match in format: parts.append('%.2d' % timetuple[i]) # 2) Return time as timestamp if not parts: return format_time(timetuple, daysep='-') # Return requested parts of the time elif len(parts) == 1: return parts[0] else: return parts def parse_time(timestr): """Parses the time string and returns its value as seconds since epoch. Time can be given in five different formats: 1) Numbers are interpreted as time since epoch directly. It is possible to use also ints and floats, not only strings containing numbers. 2) Valid timestamp ('YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss'). 3) 'NOW' (case-insensitive) is the current local time. 4) 'UTC' (case-insensitive) is the current time in UTC. 5) Format 'NOW - 1 day' or 'UTC + 1 hour 30 min' is the current local/UTC time plus/minus the time specified with the time string. Seconds are rounded down to avoid getting times in the future. """ for method in [_parse_time_epoch, _parse_time_timestamp, _parse_time_now_and_utc]: seconds = method(timestr) if seconds is not None: return int(seconds) raise ValueError("Invalid time format '%s'" % timestr) def _parse_time_epoch(timestr): try: ret = float(timestr) except ValueError: return None if ret < 0: raise ValueError("Epoch time must be positive (got %s)" % timestr) return ret def _parse_time_timestamp(timestr): try: return timestamp_to_secs(timestr, (' ', ':', '-', '.')) except ValueError: return None def _parse_time_now_and_utc(timestr): timestr = timestr.replace(' ', '').lower() base = _parse_time_now_and_utc_base(timestr[:3]) if base is not None: extra = _parse_time_now_and_utc_extra(timestr[3:]) if extra is not None: return base + extra return None def _parse_time_now_and_utc_base(base): now = time.time() if base == 'now': return now if base == 'utc': zone = time.altzone if time.localtime().tm_isdst else time.timezone return now + zone return None def _parse_time_now_and_utc_extra(extra): if not extra: return 0 if extra[0] not in ['+', '-']: return None return (1 if extra[0] == '+' else -1) * timestr_to_secs(extra[1:]) def get_timestamp(daysep='', daytimesep=' ', timesep=':', millissep='.'): return TIMESTAMP_CACHE.get_timestamp(daysep, daytimesep, timesep, millissep) def timestamp_to_secs(timestamp, seps=None): try: secs = _timestamp_to_millis(timestamp, seps) / 1000.0 except (ValueError, OverflowError): raise ValueError("Invalid timestamp '%s'" % timestamp) else: return round(secs, 3) def secs_to_timestamp(secs, seps=None, millis=False): if not seps: seps = ('', ' ', ':', '.' if millis else None) ttuple = time.localtime(secs)[:6] if millis: millis = (secs - int(secs)) * 1000 ttuple = ttuple + (int(round(millis)),) return format_time(ttuple, *seps) def get_start_timestamp(daysep='', daytimesep=' ', timesep=':', millissep=None): return format_time(START_TIME, daysep, daytimesep, timesep, millissep) def get_elapsed_time(start_time, end_time): """Returns the time between given timestamps in milliseconds.""" if start_time == end_time or not (start_time and end_time): return 0 if start_time[:-4] == end_time[:-4]: return int(end_time[-3:]) - int(start_time[-3:]) start_millis = _timestamp_to_millis(start_time) end_millis = _timestamp_to_millis(end_time) # start/end_millis can be long but we want to return int when possible return int(end_millis - start_millis) def elapsed_time_to_string(elapsed, include_millis=True): """Converts elapsed time in milliseconds to format 'hh:mm:ss.mil'. If `include_millis` is True, '.mil' part is omitted. """ prefix = '' if elapsed < 0: elapsed = abs(elapsed) prefix = '-' if include_millis: return prefix + _elapsed_time_to_string(elapsed) return prefix + _elapsed_time_to_string_without_millis(elapsed) def _elapsed_time_to_string(elapsed): secs, millis = divmod(int(round(elapsed)), 1000) mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) return '%02d:%02d:%02d.%03d' % (hours, mins, secs, millis) def _elapsed_time_to_string_without_millis(elapsed): secs = int(round(elapsed, -3)) / 1000 mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) return '%02d:%02d:%02d' % (hours, mins, secs) def _timestamp_to_millis(timestamp, seps=None): if seps: timestamp = _normalize_timestamp(timestamp, seps) Y, M, D, h, m, s, millis = _split_timestamp(timestamp) secs = time.mktime(datetime.datetime(Y, M, D, h, m, s).timetuple()) return int(round(1000*secs + millis)) def _normalize_timestamp(ts, seps): for sep in seps: if sep in ts: ts = ts.replace(sep, '') ts = ts.ljust(17, '0') return '%s%s%s %s:%s:%s.%s' % (ts[:4], ts[4:6], ts[6:8], ts[8:10], ts[10:12], ts[12:14], ts[14:17]) def _split_timestamp(timestamp): years = int(timestamp[:4]) mons = int(timestamp[4:6]) days = int(timestamp[6:8]) hours = int(timestamp[9:11]) mins = int(timestamp[12:14]) secs = int(timestamp[15:17]) millis = int(timestamp[18:21]) return years, mons, days, hours, mins, secs, millis class TimestampCache(object): def __init__(self): self._previous_secs = None self._previous_separators = None self._previous_timestamp = None def get_timestamp(self, daysep='', daytimesep=' ', timesep=':', millissep='.'): epoch = self._get_epoch() secs, millis = _float_secs_to_secs_and_millis(epoch) if self._use_cache(secs, daysep, daytimesep, timesep): return self._cached_timestamp(millis, millissep) timestamp = format_time(epoch, daysep, daytimesep, timesep, millissep) self._cache_timestamp(secs, timestamp, daysep, daytimesep, timesep, millissep) return timestamp # Seam for mocking def _get_epoch(self): return time.time() def _use_cache(self, secs, *separators): return self._previous_timestamp \ and self._previous_secs == secs \ and self._previous_separators == separators def _cached_timestamp(self, millis, millissep): if millissep: return '%s%s%03d' % (self._previous_timestamp, millissep, millis) return self._previous_timestamp def _cache_timestamp(self, secs, timestamp, daysep, daytimesep, timesep, millissep): self._previous_secs = secs self._previous_separators = (daysep, daytimesep, timesep) self._previous_timestamp = timestamp[:-4] if millissep else timestamp TIMESTAMP_CACHE = TimestampCache()
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 _SEQS_TO_BE_ESCAPED = ('\\', '${', '@{', '%{', '&{', '*{', '=') def escape(item): if not isinstance(item, basestring): return item for seq in _SEQS_TO_BE_ESCAPED: if seq in item: item = item.replace(seq, '\\' + seq) return item def unescape(item): if not (isinstance(item, basestring) and '\\' in item): return item return Unescaper().unescape(item) class Unescaper(object): _escaped = re.compile(r'(\\+)([^\\]*)') def unescape(self, string): return ''.join(self._yield_unescaped(string)) def _yield_unescaped(self, string): while '\\' in string: finder = EscapeFinder(string) yield finder.before + finder.backslashes if finder.escaped and finder.text: yield self._unescape(finder.text) else: yield finder.text string = finder.after yield string def _unescape(self, text): try: escape = str(text[0]) except UnicodeError: return text try: unescaper = getattr(self, '_unescaper_for_' + escape) except AttributeError: return text else: return unescaper(text[1:]) def _unescaper_for_n(self, text): if text.startswith(' '): text = text[1:] return '\n' + text def _unescaper_for_r(self, text): return '\r' + text def _unescaper_for_t(self, text): return '\t' + text def _unescaper_for_x(self, text): return self._unescape_character(text, 2, 'x') def _unescaper_for_u(self, text): return self._unescape_character(text, 4, 'u') def _unescaper_for_U(self, text): return self._unescape_character(text, 8, 'U') def _unescape_character(self, text, length, escape): try: char = self._get_character(text[:length], length) except ValueError: return escape + text else: return char + text[length:] def _get_character(self, text, length): if len(text) < length or not text.isalnum(): raise ValueError ordinal = int(text, 16) # No Unicode code points above 0x10FFFF if ordinal > 0x10FFFF: raise ValueError # unichr only supports ordinals up to 0xFFFF with narrow Python builds if ordinal > 0xFFFF: return eval("u'\\U%08x'" % ordinal) return unichr(ordinal) class EscapeFinder(object): _escaped = re.compile(r'(\\+)([^\\]*)') def __init__(self, string): res = self._escaped.search(string) self.before = string[:res.start()] escape_chars = len(res.group(1)) self.backslashes = '\\' * (escape_chars // 2) self.escaped = bool(escape_chars % 2) self.text = res.group(2) self.after = string[res.end():]
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 sys from contextlib import contextmanager from robot.errors import (INFO_PRINTED, DATA_ERROR, STOPPED_BY_USER, FRAMEWORK_ERROR, Information, DataError) from .argumentparser import ArgumentParser from .encoding import encode_output from .error import get_error_details class Application(object): def __init__(self, usage, name=None, version=None, arg_limits=None, env_options=None, logger=None, **auto_options): self._ap = ArgumentParser(usage, name, version, arg_limits, self.validate, env_options, **auto_options) self._logger = logger or DefaultLogger() def main(self, arguments, **options): raise NotImplementedError def validate(self, options, arguments): return options, arguments def execute_cli(self, cli_arguments): with self._logging(): options, arguments = self._parse_arguments(cli_arguments) rc = self._execute(arguments, options) self._exit(rc) def console(self, msg): if msg: print encode_output(msg) @contextmanager def _logging(self): self._logger.register_file_logger() self._logger.info('%s %s' % (self._ap.name, self._ap.version)) try: yield finally: self._logger.close() def _parse_arguments(self, cli_args): try: options, arguments = self.parse_arguments(cli_args) except Information, msg: self._report_info(unicode(msg)) except DataError, err: self._report_error(unicode(err), help=True, exit=True) else: self._logger.info('Arguments: %s' % ','.join(arguments)) return options, arguments def parse_arguments(self, cli_args): """Public interface for parsing command line arguments. :param cli_args: Command line arguments as a list :returns: options (dict), arguments (list) :raises: :class:`~robot.errors.Information` when --help or --version used :raises: :class:`~robot.errors.DataError` when parsing fails """ return self._ap.parse_args(cli_args) def execute(self, *arguments, **options): with self._logging(): return self._execute(list(arguments), options) def _execute(self, arguments, options): try: rc = self.main(arguments, **options) except DataError, err: return self._report_error(unicode(err), help=True) except (KeyboardInterrupt, SystemExit): return self._report_error('Execution stopped by user.', rc=STOPPED_BY_USER) except: error, details = get_error_details() return self._report_error('Unexpected error: %s' % error, details, rc=FRAMEWORK_ERROR) else: return rc or 0 def _report_info(self, err): self.console(unicode(err)) self._exit(INFO_PRINTED) def _report_error(self, message, details=None, help=False, rc=DATA_ERROR, exit=False): if help: message += '\n\nTry --help for usage information.' if details: message += '\n' + details self._logger.error(message) if exit: self._exit(rc) return rc def _exit(self, rc): sys.exit(rc) class DefaultLogger(object): def register_file_logger(self): pass def info(self, message): pass def error(self, message): print encode_output(message) def close(self): 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. """Convenience functions for testing both in unit and higher levels. Benefits: - Integrates 100% with unittest (see example below) - Can be easily used without unittest (using unittest.TestCase when you only need convenient asserts is not so nice) - Saved typing and shorter lines because no need to have 'self.' before asserts. These are static functions after all so that is OK. - All 'equals' methods (by default) report given values even if optional message given. This behavior can be controlled with the optional values argument. Drawbacks: - unittest is not able to filter as much non-interesting traceback away as with its own methods because AssertionErrors occur outside Most of the functions are copied more or less directly from unittest.TestCase which comes with the following license. Further information about unittest in general can be found from http://pyunit.sourceforge.net/. This module can be used freely in same terms as unittest. unittest license:: Copyright (c) 1999-2003 Steve Purcell This module is free software, and you may redistribute it and/or modify it under the same terms as Python itself, so long as this copyright message and disclaimer are retained in their original form. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. Examples:: import unittest from robot.util.asserts import * class MyTests(unittest.TestCase): def test_old_style(self): self.assertEquals(1, 2, 'my msg') def test_new_style(self): assert_equals(1, 2, 'my msg') Example output:: FF ====================================================================== FAIL: test_old_style (__main__.MyTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "example.py", line 7, in test_old_style self.assertEquals(1, 2, 'my msg') AssertionError: my msg ====================================================================== FAIL: test_new_style (__main__.MyTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "example.py", line 10, in test_new_style assert_equals(1, 2, 'my msg') File "/path/to/robot/asserts.py", line 142, in fail_unless_equal _report_unequality_failure(first, second, msg, values, '!=') File "/path/to/robot/src/robot/asserts.py", line 209, in _report_unequality_failure raise _report_failure(msg) File "/path/to/robot/src/robot/asserts.py", line 200, in _report_failure raise AssertionError(msg) AssertionError: my msg: 1 != 2 ---------------------------------------------------------------------- Ran 2 tests in 0.000s FAILED (failures=2) """ from .unic import unic def fail(msg=None): """Fail test immediately with the given message.""" _report_failure(msg) def error(msg=None): """Error test immediately with the given message.""" _report_error(msg) def fail_if(expr, msg=None): """Fail the test if the expression is True.""" if expr: _report_failure(msg) def fail_unless(expr, msg=None): """Fail the test unless the expression is True.""" if not expr: _report_failure(msg) def fail_if_none(obj, msg=None, values=True): """Fail the test if given object is None.""" _msg = 'is None' if obj is None: if msg is None: msg = _msg elif values is True: msg = '%s: %s' % (msg, _msg) _report_failure(msg) def fail_unless_none(obj, msg=None, values=True): """Fail the test if given object is not None.""" _msg = '%r is not None' % obj if obj is not None: if msg is None: msg = _msg elif values is True: msg = '%s: %s' % (msg, _msg) _report_failure(msg) def fail_unless_raises(exc_class, callable_obj, *args, **kwargs): """Fail unless an exception of class exc_class is thrown by callable_obj. callable_obj is invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. If a correct exception is raised, the exception instance is returned by this method. """ try: callable_obj(*args, **kwargs) except exc_class, err: return err else: if hasattr(exc_class,'__name__'): exc_name = exc_class.__name__ else: exc_name = str(exc_class) _report_failure('%s not raised' % exc_name) def fail_unless_raises_with_msg(exc_class, expected_msg, callable_obj, *args, **kwargs): """Similar to fail_unless_raises but also checks the exception message.""" try: callable_obj(*args, **kwargs) except exc_class, err: assert_equal(expected_msg, unic(err), 'Correct exception but wrong message') else: if hasattr(exc_class,'__name__'): exc_name = exc_class.__name__ else: exc_name = str(exc_class) _report_failure('%s not raised' % exc_name) def fail_unless_equal(first, second, msg=None, values=True): """Fail if given objects are unequal as determined by the '==' operator.""" if not first == second: _report_unequality_failure(first, second, msg, values, '!=') def fail_if_equal(first, second, msg=None, values=True): """Fail if given objects are equal as determined by the '==' operator.""" if first == second: _report_unequality_failure(first, second, msg, values, '==') def fail_unless_almost_equal(first, second, places=7, msg=None, values=True): """Fail if the two objects are unequal after rounded to given places. Unequality is determined by object's difference rounded to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). """ if round(second - first, places) != 0: extra = 'within %r places' % places _report_unequality_failure(first, second, msg, values, '!=', extra) def fail_if_almost_equal(first, second, places=7, msg=None, values=True): """Fail if the two objects are unequal after rounded to given places. Equality is determined by object's difference rounded to to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). """ if round(second-first, places) == 0: extra = 'within %r places' % places _report_unequality_failure(first, second, msg, values, '==', extra) # Synonyms for assertion methods assert_equal = assert_equals = fail_unless_equal assert_not_equal = assert_not_equals = fail_if_equal assert_almost_equal = assert_almost_equals = fail_unless_almost_equal assert_not_almost_equal = assert_not_almost_equals = fail_if_almost_equal assert_raises = fail_unless_raises assert_raises_with_msg = fail_unless_raises_with_msg assert_ = assert_true = fail_unless assert_false = fail_if assert_none = fail_unless_none assert_not_none = fail_if_none # Helpers def _report_failure(msg): if msg is None: raise AssertionError() raise AssertionError(msg) def _report_error(msg): if msg is None: raise Exception() raise Exception(msg) def _report_unequality_failure(obj1, obj2, msg, values, delim, extra=None): if not msg: msg = _get_default_message(obj1, obj2, delim) elif values: msg = '%s: %s' % (msg, _get_default_message(obj1, obj2, delim)) if values and extra: msg += ' ' + extra _report_failure(msg) def _get_default_message(obj1, obj2, delim): str1 = unic(obj1) str2 = unic(obj2) if delim == '!=' and str1 == str2: return '%s (%s) != %s (%s)' % (str1, _type_name(obj1), str2, _type_name(obj2)) return '%s %s %s' % (str1, delim, str2) def _type_name(val): known_types = {int: 'number', long: 'number', float: 'number', str: 'string', unicode: 'string', bool: 'boolean'} return known_types.get(type(val), type(val).__name__)
Python
# Copyright 2008-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 if sys.platform.startswith('java'): from java.lang import String from java.util import Map else: String = Map = () try: from collections import Mapping except ImportError: # New in 2.6 Mapping = dict from UserDict import UserDict from UserString import UserString def is_str_like(item, allow_java=False): return (isinstance(item, (basestring, UserString)) or allow_java and isinstance(item, String)) def is_list_like(item): if is_str_like(item, allow_java=True) or is_dict_like(item, allow_java=True): return False try: iter(item) except TypeError: return False else: return True def is_dict_like(item, allow_java=False): return (isinstance(item, (Mapping, UserDict)) or allow_java and isinstance(item, Map))
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 import sys from .unic import unic def printable_name(string, code_style=False): """Generates and returns printable name from the given string. Examples: 'simple' -> 'Simple' 'name with spaces' -> 'Name With Spaces' 'more spaces' -> 'More Spaces' 'Cases AND spaces' -> 'Cases AND Spaces' '' -> '' If 'code_style' is True: 'mixedCAPSCamel' -> 'Mixed CAPS Camel' 'camelCaseName' -> 'Camel Case Name' 'under_score_name' -> 'Under Score Name' 'under_and space' -> 'Under And Space' 'miXed_CAPS_nAMe' -> 'MiXed CAPS NAMe' '' -> '' """ if code_style and '_' in string: string = string.replace('_', ' ') parts = string.split() if not parts: return '' if code_style and len(parts) == 1: parts = _splitCamelCaseString(parts[0]) return ' '.join(part[0].upper() + part[1:] for part in parts if part != '') def _splitCamelCaseString(string): parts = [] current_part = [] string = ' ' + string + ' ' # extra spaces make going through string easier for i in range(1, len(string)-1): # on 1st/last round prev/next is ' ' and char is 1st/last real char prev, char, next = string[i-1:i+2] if _isWordBoundary(prev, char, next): parts.append(''.join(current_part)) current_part = [char] else: current_part.append(char) parts.append(''.join(current_part)) # append last part return parts def _isWordBoundary(prev, char, next): if char.isupper(): return (prev.islower() or next.islower()) and prev.isalnum() if char.isdigit(): return prev.isalpha() return prev.isdigit() def plural_or_not(item): count = item if isinstance(item, (int, long)) else len(item) return '' if count == 1 else 's' def seq2str(sequence, quote="'", sep=', ', lastsep=' and '): """Returns sequence in format 'item 1', 'item 2' and 'item 3'""" quote_elem = lambda string: quote + unic(string) + quote if not sequence: return '' if len(sequence) == 1: return quote_elem(sequence[0]) elems = [quote_elem(s) for s in sequence[:-2]] elems.append(quote_elem(sequence[-2]) + lastsep + quote_elem(sequence[-1])) return sep.join(elems) def seq2str2(sequence): """Returns sequence in format [ item 1 | item 2 | ... ] """ if not sequence: return '[ ]' return '[ %s ]' % ' | '.join(unic(item) for item in sequence) def getdoc(item): doc = inspect.getdoc(item) or u'' if isinstance(doc, unicode): return doc try: return doc.decode('UTF-8') except UnicodeDecodeError: return unic(doc) # On IronPython sys.stdxxx.isatty() always returns True if sys.platform != 'cli': def isatty(stream): return hasattr(stream, 'isatty') and stream.isatty() else: from ctypes import windll _HANDLE_IDS = {sys.__stdout__ : -11, sys.__stderr__ : -12} _CONSOLE_TYPE = 2 def isatty(stream): if stream not in _HANDLE_IDS: return False handle = windll.kernel32.GetStdHandle(_HANDLE_IDS[stream]) return windll.kernel32.GetFileType(handle) == _CONSOLE_TYPE
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. """A module to handle different character widths on the console. Some East Asian characters have width of two on console, and combining characters themselves take no extra space. See issue 604 [1] for more details about East Asian characters. The issue also contains `generate_wild_chars.py` script that was originally used to create `_EAST_ASIAN_WILD_CHARS` mapping. An updated version of the script is attached to issue 1096. Big thanks for xieyanbo for the script and the original patch. Note that Python's `unicodedata` module is not used here because importing it takes several seconds on Jython. [1] http://code.google.com/p/robotframework/issues/detail?id=604 [2] http://code.google.com/p/robotframework/issues/detail?id=1096 """ def get_char_width(char): char = ord(char) if _char_in_map(char, _COMBINING_CHARS): return 0 if _char_in_map(char, _EAST_ASIAN_WILD_CHARS): return 2 return 1 def _char_in_map(char, map): for begin, end in map: if char < begin: break if begin <= char <= end: return True return False _COMBINING_CHARS = [(768, 879)] _EAST_ASIAN_WILD_CHARS = [ (888, 889), (895, 899), (907, 907), (909, 909), (930, 930), (1316, 1328), (1367, 1368), (1376, 1376), (1416, 1416), (1419, 1424), (1480, 1487), (1515, 1519), (1525, 1535), (1540, 1541), (1564, 1565), (1568, 1568), (1631, 1631), (1806, 1806), (1867, 1868), (1970, 1983), (2043, 2304), (2362, 2363), (2382, 2383), (2389, 2391), (2419, 2426), (2432, 2432), (2436, 2436), (2445, 2446), (2449, 2450), (2473, 2473), (2481, 2481), (2483, 2485), (2490, 2491), (2501, 2502), (2505, 2506), (2511, 2518), (2520, 2523), (2526, 2526), (2532, 2533), (2555, 2560), (2564, 2564), (2571, 2574), (2577, 2578), (2601, 2601), (2609, 2609), (2612, 2612), (2615, 2615), (2618, 2619), (2621, 2621), (2627, 2630), (2633, 2634), (2638, 2640), (2642, 2648), (2653, 2653), (2655, 2661), (2678, 2688), (2692, 2692), (2702, 2702), (2706, 2706), (2729, 2729), (2737, 2737), (2740, 2740), (2746, 2747), (2758, 2758), (2762, 2762), (2766, 2767), (2769, 2783), (2788, 2789), (2800, 2800), (2802, 2816), (2820, 2820), (2829, 2830), (2833, 2834), (2857, 2857), (2865, 2865), (2868, 2868), (2874, 2875), (2885, 2886), (2889, 2890), (2894, 2901), (2904, 2907), (2910, 2910), (2916, 2917), (2930, 2945), (2948, 2948), (2955, 2957), (2961, 2961), (2966, 2968), (2971, 2971), (2973, 2973), (2976, 2978), (2981, 2983), (2987, 2989), (3002, 3005), (3011, 3013), (3017, 3017), (3022, 3023), (3025, 3030), (3032, 3045), (3067, 3072), (3076, 3076), (3085, 3085), (3089, 3089), (3113, 3113), (3124, 3124), (3130, 3132), (3141, 3141), (3145, 3145), (3150, 3156), (3159, 3159), (3162, 3167), (3172, 3173), (3184, 3191), (3200, 3201), (3204, 3204), (3213, 3213), (3217, 3217), (3241, 3241), (3252, 3252), (3258, 3259), (3269, 3269), (3273, 3273), (3278, 3284), (3287, 3293), (3295, 3295), (3300, 3301), (3312, 3312), (3315, 3329), (3332, 3332), (3341, 3341), (3345, 3345), (3369, 3369), (3386, 3388), (3397, 3397), (3401, 3401), (3406, 3414), (3416, 3423), (3428, 3429), (3446, 3448), (3456, 3457), (3460, 3460), (3479, 3481), (3506, 3506), (3516, 3516), (3518, 3519), (3527, 3529), (3531, 3534), (3541, 3541), (3543, 3543), (3552, 3569), (3573, 3584), (3643, 3646), (3676, 3712), (3715, 3715), (3717, 3718), (3721, 3721), (3723, 3724), (3726, 3731), (3736, 3736), (3744, 3744), (3748, 3748), (3750, 3750), (3752, 3753), (3756, 3756), (3770, 3770), (3774, 3775), (3781, 3781), (3783, 3783), (3790, 3791), (3802, 3803), (3806, 3839), (3912, 3912), (3949, 3952), (3980, 3983), (3992, 3992), (4029, 4029), (4045, 4045), (4053, 4095), (4250, 4253), (4294, 4303), (4349, 4447), (4515, 4519), (4602, 4607), (4681, 4681), (4686, 4687), (4695, 4695), (4697, 4697), (4702, 4703), (4745, 4745), (4750, 4751), (4785, 4785), (4790, 4791), (4799, 4799), (4801, 4801), (4806, 4807), (4823, 4823), (4881, 4881), (4886, 4887), (4955, 4958), (4989, 4991), (5018, 5023), (5109, 5120), (5751, 5759), (5789, 5791), (5873, 5887), (5901, 5901), (5909, 5919), (5943, 5951), (5972, 5983), (5997, 5997), (6001, 6001), (6004, 6015), (6110, 6111), (6122, 6127), (6138, 6143), (6159, 6159), (6170, 6175), (6264, 6271), (6315, 6399), (6429, 6431), (6444, 6447), (6460, 6463), (6465, 6467), (6510, 6511), (6517, 6527), (6570, 6575), (6602, 6607), (6618, 6621), (6684, 6685), (6688, 6911), (6988, 6991), (7037, 7039), (7083, 7085), (7098, 7167), (7224, 7226), (7242, 7244), (7296, 7423), (7655, 7677), (7958, 7959), (7966, 7967), (8006, 8007), (8014, 8015), (8024, 8024), (8026, 8026), (8028, 8028), (8030, 8030), (8062, 8063), (8117, 8117), (8133, 8133), (8148, 8149), (8156, 8156), (8176, 8177), (8181, 8181), (8191, 8191), (8293, 8297), (8306, 8307), (8335, 8335), (8341, 8351), (8374, 8399), (8433, 8447), (8528, 8530), (8585, 8591), (9001, 9002), (9192, 9215), (9255, 9279), (9291, 9311), (9886, 9887), (9917, 9919), (9924, 9984), (9989, 9989), (9994, 9995), (10024, 10024), (10060, 10060), (10062, 10062), (10067, 10069), (10071, 10071), (10079, 10080), (10133, 10135), (10160, 10160), (10175, 10175), (10187, 10187), (10189, 10191), (11085, 11087), (11093, 11263), (11311, 11311), (11359, 11359), (11376, 11376), (11390, 11391), (11499, 11512), (11558, 11567), (11622, 11630), (11632, 11647), (11671, 11679), (11687, 11687), (11695, 11695), (11703, 11703), (11711, 11711), (11719, 11719), (11727, 11727), (11735, 11735), (11743, 11743), (11825, 12350), (12352, 19903), (19968, 42239), (42540, 42559), (42592, 42593), (42612, 42619), (42648, 42751), (42893, 43002), (43052, 43071), (43128, 43135), (43205, 43213), (43226, 43263), (43348, 43358), (43360, 43519), (43575, 43583), (43598, 43599), (43610, 43611), (43616, 55295), (63744, 64255), (64263, 64274), (64280, 64284), (64311, 64311), (64317, 64317), (64319, 64319), (64322, 64322), (64325, 64325), (64434, 64466), (64832, 64847), (64912, 64913), (64968, 65007), (65022, 65023), (65040, 65055), (65063, 65135), (65141, 65141), (65277, 65278), (65280, 65376), (65471, 65473), (65480, 65481), (65488, 65489), (65496, 65497), (65501, 65511), (65519, 65528), (65534, 65535), ]
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 .encoding import decode_from_system, encode_to_system from .unic import unic def get_env_var(name, default=None): value = _get_env_var_from_java(name) if value is not None: return value try: value = os.environ[_encode(name)] except KeyError: return default else: return _decode(value) def set_env_var(name, value): os.environ[_encode(name)] = _encode(value) def del_env_var(name): # cannot use os.environ.pop() due to http://bugs.python.org/issue1287 value = get_env_var(name) if value is not None: del os.environ[_encode(name)] return value def get_env_vars(upper=os.sep != '/'): # by default, name is upper-cased on Windows regardless interpreter return dict((name if not upper else name.upper(), get_env_var(name)) for name in (_decode(name) for name in os.environ)) def _encode(var): if isinstance(var, str): return var if isinstance(var, unicode): return encode_to_system(var) return str(var) def _decode(var): return decode_from_system(var, can_be_from_java=False) # Jython hack below needed due to http://bugs.jython.org/issue1841 if not sys.platform.startswith('java'): def _get_env_var_from_java(name): return None else: from java.lang import String, System def _get_env_var_from_java(name): name = name if isinstance(name, basestring) else unic(name) value_set_before_execution = System.getenv(name) if value_set_before_execution is None: return None current_value = String(os.environ[name]).toString() if value_set_before_execution != current_value: return None return value_set_before_execution
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 .htmlformatters import LinkFormatter, HtmlFormatter _format_url = LinkFormatter().format_url _generic_escapes = (('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;')) _attribute_escapes = _generic_escapes \ + (('"', '&quot;'), ('\n', '&#10;'), ('\r', '&#13;'), ('\t', '&#09;')) _illegal_chars_in_xml = re.compile(u'[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]') def html_escape(text): return _format_url(_escape(text)) def xml_escape(text): return _illegal_chars_in_xml.sub('', _escape(text)) def html_format(text): return HtmlFormatter().format(_escape(text)) def attribute_escape(attr): return _escape(attr, _attribute_escapes) def _escape(text, escapes=_generic_escapes): for name, value in escapes: if name in text: # performance optimization text = text.replace(name, value) return _illegal_chars_in_xml.sub('', text)
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 # Need different unic implementations for different Pythons because: # 1) Importing unicodedata module on Jython takes a very long time, and doesn't # seem to be necessary as Java probably already handles normalization. # Furthermore, Jython on Java 1.5 doesn't even have unicodedata.normalize. # 2) IronPython 2.6 doesn't have unicodedata and probably doesn't need it. # 3) CPython doesn't automatically normalize Unicode strings. if sys.platform.startswith('java'): from java.lang import Object, Class def unic(item, *args): # http://bugs.jython.org/issue1564 if isinstance(item, Object) and not isinstance(item, Class): try: item = item.toString() # http://bugs.jython.org/issue1563 except: return _unrepresentable_object(item) return _unic(item, *args) elif sys.platform == 'cli': def unic(item, *args): return _unic(item, *args) else: from unicodedata import normalize def unic(item, *args): return normalize('NFC', _unic(item, *args)) def _unic(item, *args): # Based on a recipe from http://code.activestate.com/recipes/466341 try: return unicode(item, *args) except UnicodeError: try: return u''.join(c if ord(c) < 128 else c.encode('string_escape') for c in str(item)) except: return _unrepresentable_object(item) except: return _unrepresentable_object(item) def safe_repr(item): try: return unic(repr(item)) except UnicodeError: return repr(unic(item)) except: return _unrepresentable_object(item) if sys.platform == 'cli': # IronPython omits `u` prefix from `repr(u'foo')`. We add it back to have # consistent and easier to test log messages. _safe_repr = safe_repr def safe_repr(item): if isinstance(item, list): return '[%s]' % ', '.join(safe_repr(i) for i in item) ret = _safe_repr(item) if isinstance(item, unicode) and not ret.startswith('u'): ret = 'u' + ret return ret def _unrepresentable_object(item): from robot.utils.error import get_error_message return u"<Unrepresentable object '%s'. Error: %s>" \ % (item.__class__.__name__, get_error_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. import re import sys from UserDict import UserDict try: from collections import Mapping except ImportError: # Pre Python 2.6 support mappings = (dict, UserDict) else: mappings = (Mapping, UserDict) _WHITESPACE_REGEXP = re.compile('\s+') def normalize(string, ignore=(), caseless=True, spaceless=True): """Normalizes given string according to given spec. By default string is turned to lower case and all whitespace is removed. Additional characters can be removed by giving them in `ignore` list. """ if spaceless: string = _WHITESPACE_REGEXP.sub('', string) if caseless: string = lower(string) ignore = [lower(i) for i in ignore] for ign in ignore: if ign in string: # performance optimization string = string.replace(ign, '') return string # IronPython fails to lowercase non-ASCII characters: # http://ironpython.codeplex.com/workitem/33133 if sys.platform != 'cli': def lower(string): return string.lower() else: def lower(string): if string.islower(): return string if string.isupper(): return string.swapcase() if not _has_uppercase_non_ascii_chars(string): return string.lower() return ''.join(c if not c.isupper() else c.swapcase() for c in string) def _has_uppercase_non_ascii_chars(string): for c in string: if c >= u'\x80' and c.isupper(): return True return False class NormalizedDict(UserDict): """Custom dictionary implementation automatically normalizing keys.""" def __init__(self, initial=None, ignore=(), caseless=True, spaceless=True): """Initializes with possible initial value and normalizing spec. Initial values can be either a dictionary or an iterable of name/value pairs. In the latter case items are added in the given order. Normalizing spec has exact same semantics as with `normalize` method. """ UserDict.__init__(self) self._keys = {} self._normalize = lambda s: normalize(s, ignore, caseless, spaceless) if initial: self._add_initial(initial) def _add_initial(self, items): if hasattr(items, 'items'): items = items.items() for key, value in items: self[key] = value def update(self, dict=None, **kwargs): if dict: for key in dict: self.set(key, dict[key]) if kwargs: self.update(kwargs) def _add_key(self, key): nkey = self._normalize(key) self._keys.setdefault(nkey, key) return nkey def set(self, key, value): nkey = self._add_key(key) self.data[nkey] = value __setitem__ = set def get(self, key, default=None): try: return self.__getitem__(key) except KeyError: return default def __getitem__(self, key): return self.data[self._normalize(key)] def pop(self, key, *default): nkey = self._normalize(key) self._keys.pop(nkey, *default) return self.data.pop(nkey, *default) __delitem__ = pop def clear(self): UserDict.clear(self) self._keys.clear() def has_key(self, key): return self.data.has_key(self._normalize(key)) __contains__ = has_key def __iter__(self): return (self._keys[norm_key] for norm_key in sorted(self._keys)) def keys(self): return list(self) def iterkeys(self): return iter(self) def values(self): return list(self.itervalues()) def itervalues(self): return (self[key] for key in self) def items(self): return list(self.iteritems()) def iteritems(self): return ((key, self[key]) for key in self) def popitem(self): if not self: raise KeyError('dictionary is empty') key = self.iterkeys().next() return key, self.pop(key) def copy(self): copy = UserDict.copy(self) copy._keys = self._keys.copy() return copy def __str__(self): return str(dict(self.items())) def __cmp__(self, other): if not isinstance(other, NormalizedDict) and isinstance(other, mappings): other = NormalizedDict(other) return UserDict.__cmp__(self, other)
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. """Various generic utility functions and classes. Utilities are mainly for internal usage, but external libraries and tools may find some of them useful. Utilities are generally stable, but absolute backwards compatibility between major versions is not guaranteed. All utilities are exposed via the :mod:`robot.utils` package, and should be used either like:: from robot import utils assert utils.Matcher('H?llo').match('Hillo') or:: from robot.utils import Matcher assert Matcher('H?llo').match('Hillo') """ from .argumentparser import ArgumentParser from .application import Application from .compress import compress_text from .connectioncache import ConnectionCache from .encoding import (decode_output, encode_output, decode_from_system, encode_to_system) from .error import (get_error_message, get_error_details, ErrorDetails, RERAISED_EXCEPTIONS) from .escaping import escape, unescape from .etreewrapper import ET, ETSource from .markuputils import html_format, html_escape, xml_escape, attribute_escape from .markupwriters import HtmlWriter, XmlWriter, NullMarkupWriter from .importer import Importer from .islike import is_dict_like, is_list_like, is_str_like from .match import eq, Matcher, MultiMatcher from .misc import (isatty, getdoc, plural_or_not, printable_name, seq2str, seq2str2) from .normalizing import lower, normalize, NormalizedDict from .robotenv import get_env_var, set_env_var, del_env_var, get_env_vars from .robotinspect import is_java_init, is_java_method from .robotpath import abspath, find_file, get_link_path, normpath from .robottime import (get_timestamp, get_start_timestamp, format_time, get_time, get_elapsed_time, elapsed_time_to_string, timestr_to_secs, secs_to_timestr, secs_to_timestamp, timestamp_to_secs, parse_time) from .setter import setter from .text import (cut_long_message, format_assign_message, pad_console_length, get_console_length) from .unic import unic, safe_repr from .utf8reader import Utf8Reader import sys is_jython = sys.platform.startswith('java') del sys # Following utils were removed in 2.8 but added back in 2.8.1 because they # were used by SSHLibrary and SeleniumLibrary. Libs must be changed not to # use them and then, hopefully, we can remove them again in 2.9. # https://code.google.com/p/robotframework/issues/detail?id=1472 def matches(string, pattern, ignore=(), caseless=True, spaceless=True): """Deprecated!! Use Matcher instead.""" return Matcher(pattern, ignore, caseless, spaceless).match(string) def html_attr_escape(attr): """Deprecated!! Use attribute_escape instead.""" return attribute_escape(attr)
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 functools import partial from itertools import cycle class LinkFormatter(object): _image_exts = ('.jpg', '.jpeg', '.png', '.gif', '.bmp') _link = re.compile('\[(.+?\|.*?)\]') _url = re.compile(''' ((^|\ ) ["'\(\[]*) # begin of line or space and opt. any char "'([ ([a-z][\w+-.]*://[^\s|]+?) # url (?=[\]\)|"'.,!?:;]* ($|\ )) # opt. any char ])"'.,!?:; and end of line or space ''', re.VERBOSE|re.MULTILINE|re.IGNORECASE) def format_url(self, text): return self._format_url(text, format_as_image=False) def _format_url(self, text, format_as_image=True): if '://' not in text: return text return self._url.sub(partial(self._replace_url, format_as_image), text) def _replace_url(self, format_as_image, match): pre = match.group(1) url = match.group(3) if format_as_image and self._is_image(url): return pre + self._get_image(url) return pre + self._get_link(url) def _get_image(self, src, title=None): return '<img src="%s" title="%s">' \ % (self._quot(src), self._quot(title or src)) def _get_link(self, href, content=None): return '<a href="%s">%s</a>' % (self._quot(href), content or href) def _quot(self, attr): return attr if '"' not in attr else attr.replace('"', '&quot;') def format_link(self, text): # 2nd, 4th, etc. token contains link, others surrounding content tokens = self._link.split(text) formatters = cycle((self._format_url, self._format_link)) return ''.join(f(t) for f, t in zip(formatters, tokens)) def _format_link(self, text): link, content = [t.strip() for t in text.split('|', 1)] if self._is_image(content): content = self._get_image(content, link) elif self._is_image(link): return self._get_image(link, content) return self._get_link(link, content) def _is_image(self, text): return text.lower().endswith(self._image_exts) class LineFormatter(object): handles = lambda self, line: True newline = '\n' _bold = re.compile(''' ( # prefix (group 1) (^|\ ) # begin of line or space ["'(]* _? # optionally any char "'( and optional begin of italic ) # \* # start of bold ([^\ ].*?) # no space and then anything (group 3) \* # end of bold (?= # start of postfix (non-capturing group) _? ["').,!?:;]* # optional end of italic and any char "').,!?:; ($|\ ) # end of line or space ) ''', re.VERBOSE) _italic = re.compile(''' ( (^|\ ) ["'(]* ) # begin of line or space and opt. any char "'( _ # start of italic ([^\ _].*?) # no space or underline and then anything _ # end of italic (?= ["').,!?:;]* ($|\ ) ) # opt. any char "').,!?:; and end of line or space ''', re.VERBOSE) def __init__(self): self._format_link = LinkFormatter().format_link def format(self, line): return self._format_link(self._format_italic(self._format_bold(line))) def _format_bold(self, line): return self._bold.sub('\\1<b>\\3</b>', line) if '*' in line else line def _format_italic(self, line): return self._italic.sub('\\1<i>\\3</i>', line) if '_' in line else line class HtmlFormatter(object): def __init__(self): self._results = [] self._formatters = [TableFormatter(), PreformattedFormatter(), ListFormatter(), HeaderFormatter(), RulerFormatter()] self._formatters.append(ParagraphFormatter(self._formatters[:])) self._current = None def format(self, text): for line in text.splitlines(): self._process_line(line) self._end_current() return '\n'.join(self._results) def _process_line(self, line): if not line.strip(): self._end_current() elif self._current and self._current.handles(line): self._current.add(line) else: self._end_current() self._current = self._find_formatter(line) self._current.add(line) def _end_current(self): if self._current: self._results.append(self._current.end()) self._current = None def _find_formatter(self, line): for formatter in self._formatters: if formatter.handles(line): return formatter class _Formatter(object): _strip_lines = True def __init__(self): self._lines = [] def handles(self, line): return self._handles(line.strip() if self._strip_lines else line) def _handles(self, line): raise NotImplementedError def add(self, line): self._lines.append(line.strip() if self._strip_lines else line) def end(self): result = self.format(self._lines) self._lines = [] return result def format(self, lines): raise NotImplementedError class _SingleLineFormatter(_Formatter): def _handles(self, line): return not self._lines and self.match(line) def match(self, line): raise NotImplementedError def format(self, lines): return self.format_line(lines[0]) def format_line(self, line): raise NotImplementedError class RulerFormatter(_SingleLineFormatter): match = re.compile('^-{3,}$').match def format_line(self, line): return '<hr>' class HeaderFormatter(_SingleLineFormatter): match = re.compile(r'^(={1,3})\s+(\S.*?)\s+\1$').match def format_line(self, line): level, text = self.match(line).groups() level = len(level) + 1 return '<h%d>%s</h%d>' % (level, text, level) class ParagraphFormatter(_Formatter): _format_line = LineFormatter().format def __init__(self, other_formatters): _Formatter.__init__(self) self._other_formatters = other_formatters def _handles(self, line): return not any(other.handles(line) for other in self._other_formatters) def format(self, lines): return '<p>%s</p>' % self._format_line(' '.join(lines)) class TableFormatter(_Formatter): _table_line = re.compile('^\| (.* |)\|$') _line_splitter = re.compile(' \|(?= )') _format_cell_content = LineFormatter().format def _handles(self, line): return self._table_line.match(line) is not None def format(self, lines): return self._format_table([self._split_to_cells(l) for l in lines]) def _split_to_cells(self, line): return [cell.strip() for cell in self._line_splitter.split(line[1:-1])] def _format_table(self, rows): maxlen = max(len(row) for row in rows) table = ['<table border="1">'] for row in rows: row += [''] * (maxlen - len(row)) # fix ragged tables table.append('<tr>') table.extend(self._format_cell(cell) for cell in row) table.append('</tr>') table.append('</table>') return '\n'.join(table) def _format_cell(self, content): if content.startswith('=') and content.endswith('='): tx = 'th' content = content[1:-1].strip() else: tx = 'td' return '<%s>%s</%s>' % (tx, self._format_cell_content(content), tx) class PreformattedFormatter(_Formatter): _format_line = LineFormatter().format def _handles(self, line): return line.startswith('| ') or line == '|' def format(self, lines): lines = [self._format_line(line[2:]) for line in lines] return '\n'.join(['<pre>'] + lines + ['</pre>']) class ListFormatter(_Formatter): _strip_lines = False _format_item = LineFormatter().format def _handles(self, line): return line.strip().startswith('- ') or \ line.startswith(' ') and self._lines def format(self, lines): items = ['<li>%s</li>' % self._format_item(line) for line in self._combine_lines(lines)] return '\n'.join(['<ul>'] + items + ['</ul>']) def _combine_lines(self, lines): current = [] for line in lines: line = line.strip() if not line.startswith('- '): current.append(line) continue if current: yield ' '.join(current) current = [line[2:].strip()] yield ' '.join(current)
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 sys import inspect if sys.platform.startswith('java'): from java.lang.System import getProperty from robot.errors import DataError from .encoding import decode_from_system from .error import get_error_details from .robotpath import abspath, normpath class Importer(object): def __init__(self, type=None, logger=None): if not logger: from robot.output import LOGGER as logger self._type = type or '' self._logger = logger self._importers = (ByPathImporter(logger), NonDottedImporter(logger), DottedImporter(logger)) self._by_path_importer = self._importers[0] def import_class_or_module(self, name, instantiate_with_args=None): """Imports Python class/module or Java class with given name. Class can either live in a module/package or be standalone Java class. In the former case the name is something like 'MyClass' and in the latter it could be 'your.package.YourLibrary'. Python classes always live in a module, but if the module name is exactly same as the class name then simple 'MyLibrary' will import a class. Python modules can be imported both using format 'MyModule' and 'mymodule.submodule'. `name` can also be a path to the imported file/directory. In that case importing is done using `import_class_or_module_by_path` method. If `instantiate_with_args` is not None, imported classes are instantiated with the specified arguments automatically. """ try: imported, source = self._import_class_or_module(name) self._log_import_succeeded(imported, name, source) return self._instantiate_if_needed(imported, instantiate_with_args) except DataError, err: self._raise_import_failed(name, err) def _import_class_or_module(self, name): for importer in self._importers: if importer.handles(name): return importer.import_(name) def import_class_or_module_by_path(self, path, instantiate_with_args=None): """Import a Python module or Java class using a file system path. When importing a Python file, the path must end with '.py' and the actual file must also exist. When importing Java classes, the path must end with '.java' or '.class'. The class file must exist in both cases and in the former case also the source file must exist. If `instantiate_with_args` is not None, imported classes are instantiated with the specified arguments automatically. """ try: imported, source = self._by_path_importer.import_(path) self._log_import_succeeded(imported, imported.__name__, source) return self._instantiate_if_needed(imported, instantiate_with_args) except DataError, err: self._raise_import_failed(path, err) def _raise_import_failed(self, name, error): import_type = '%s ' % self._type if self._type else '' msg = "Importing %s'%s' failed: %s" % (import_type, name, error.message) if not error.details: raise DataError(msg) msg = [msg, error.details] msg.extend(self._get_items_in('PYTHONPATH', sys.path)) if sys.platform.startswith('java'): classpath = getProperty('java.class.path').split(os.path.pathsep) msg.extend(self._get_items_in('CLASSPATH', classpath)) raise DataError('\n'.join(msg)) def _get_items_in(self, type, items): yield '%s:' % type for item in items: if item: yield ' %s' % (item if isinstance(item, unicode) else decode_from_system(item)) def _instantiate_if_needed(self, imported, args): if args is None: return imported if inspect.isclass(imported): return self._instantiate_class(imported, args) if args: raise DataError("Modules do not take arguments.") return imported def _instantiate_class(self, imported, args): try: return imported(*args) except: raise DataError('Creating instance failed: %s\n%s' % get_error_details()) def _log_import_succeeded(self, item, name, source): import_type = '%s ' % self._type if self._type else '' item_type = 'module' if inspect.ismodule(item) else 'class' location = ("'%s'" % source) if source else 'unknown location' self._logger.info("Imported %s%s '%s' from %s." % (import_type, item_type, name, location)) class _Importer(object): def __init__(self, logger): self._logger = logger def _import(self, name, fromlist=None, retry=True): try: try: return __import__(name, fromlist=fromlist) except ImportError: # Hack to support standalone Jython. For more information, see: # http://code.google.com/p/robotframework/issues/detail?id=515 # http://bugs.jython.org/issue1778514 if sys.platform.startswith('java') and fromlist and retry: __import__('%s.%s' % (name, fromlist[0])) return self._import(name, fromlist, retry=False) # Cannot use plain raise due to # http://ironpython.codeplex.com/workitem/32332 raise sys.exc_type, sys.exc_value, sys.exc_traceback except: raise DataError(*get_error_details()) def _verify_type(self, imported): if inspect.isclass(imported) or inspect.ismodule(imported): return imported raise DataError('Expected class or module, got <%s>.' % type(imported).__name__) def _get_class_from_module(self, module, name=None): klass = getattr(module, name or module.__name__, None) return klass if inspect.isclass(klass) else None def _get_source(self, module): source = getattr(module, '__file__', None) return abspath(source) if source else None class ByPathImporter(_Importer): _valid_import_extensions = ('.py', '.java', '.class', '') def handles(self, path): return os.path.isabs(path) def import_(self, path): self._verify_import_path(path) self._remove_wrong_module_from_sys_modules(path) module = self._import_by_path(path) imported = self._get_class_from_module(module) or module return self._verify_type(imported), path def _verify_import_path(self, path): if not os.path.exists(path): raise DataError('File or directory does not exist.') if not os.path.isabs(path): raise DataError('Import path must be absolute.') if not os.path.splitext(path)[1] in self._valid_import_extensions: raise DataError('Not a valid file or directory to import.') def _remove_wrong_module_from_sys_modules(self, path): importing_from, name = self._split_path_to_module(path) importing_package = os.path.splitext(path)[1] == '' if self._wrong_module_imported(name, importing_from, importing_package): del sys.modules[name] self._logger.info("Removed module '%s' from sys.modules to import " "fresh module." % name) def _split_path_to_module(self, path): module_dir, module_file = os.path.split(abspath(path)) module_name = os.path.splitext(module_file)[0] if module_name.endswith('$py'): module_name = module_name[:-3] return module_dir, module_name def _wrong_module_imported(self, name, importing_from, importing_package): module = sys.modules.get(name) if not module: return False source = getattr(module, '__file__', None) if not source: # play safe (occurs at least with java based modules) return True imported_from, imported_package = self._get_import_information(source) return ((normpath(importing_from), importing_package) != (normpath(imported_from), imported_package)) def _get_import_information(self, source): imported_from, imported_file = self._split_path_to_module(source) imported_package = imported_file == '__init__' if imported_package: imported_from = os.path.dirname(imported_from) return imported_from, imported_package def _import_by_path(self, path): module_dir, module_name = self._split_path_to_module(path) sys.path.insert(0, module_dir) try: return self._import(module_name) finally: sys.path.pop(0) class NonDottedImporter(_Importer): def handles(self, name): return '.' not in name def import_(self, name): module = self._import(name) imported = self._get_class_from_module(module) or module return self._verify_type(imported), self._get_source(module) class DottedImporter(_Importer): def handles(self, name): return '.' in name def import_(self, name): parent_name, lib_name = name.rsplit('.', 1) parent = self._import(parent_name, fromlist=[str(lib_name)]) try: imported = getattr(parent, lib_name) except AttributeError: raise DataError("Module '%s' does not contain '%s'." % (parent_name, lib_name)) imported = self._get_class_from_module(imported, lib_name) or imported return self._verify_type(imported), self._get_source(parent)
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 .normalizing import NormalizedDict class ConnectionCache(object): """Cache for test libs to use with concurrent connections, processes, etc. The cache stores the registered connections (or other objects) and allows switching between them using generated indices or user given aliases. This is useful with any test library where there's need for multiple concurrent connections, processes, etc. This class can, and is, used also outside the core framework by SSHLibrary, Selenium(2)Library, etc. Backwards compatibility is thus important when doing changes. """ def __init__(self, no_current_msg='No open connection.'): self._no_current = NoConnection(no_current_msg) self.current = self._no_current #: Current active connection. self._connections = [] self._aliases = NormalizedDict() def _get_current_index(self): if not self: return None for index, conn in enumerate(self): if conn is self.current: return index + 1 def _set_current_index(self, index): self.current = self._connections[index - 1] \ if index is not None else self._no_current current_index = property(_get_current_index, _set_current_index) def register(self, connection, alias=None): """Registers given connection with optional alias and returns its index. Given connection is set to be the :attr:`current` connection. If alias is given, it must be a string. Aliases are case and space insensitive. The index of the first connection after initialization, and after :meth:`close_all` or :meth:`empty_cache`, is 1, second is 2, etc. """ self.current = connection self._connections.append(connection) index = len(self._connections) if isinstance(alias, basestring): self._aliases[alias] = index return index def switch(self, alias_or_index): """Switches to the connection specified by the given alias or index. Updates :attr:`current` and also returns its new value. Alias is whatever was given to :meth:`register` method and indices are returned by it. Index can be given either as an integer or as a string that can be converted to an integer. Raises an error if no connection with the given index or alias found. """ self.current = self.get_connection(alias_or_index) return self.current def get_connection(self, alias_or_index=None): """Get the connection specified by the given alias or index.. If ``alias_or_index`` is ``None``, returns the current connection if it is active, or raises an error if it is not. Alias is whatever was given to :meth:`register` method and indices are returned by it. Index can be given either as an integer or as a string that can be converted to an integer. Raises an error if no connection with the given index or alias found. """ if alias_or_index is None: if not self: self.current.raise_error() return self.current try: index = self._resolve_alias_or_index(alias_or_index) except ValueError: raise RuntimeError("Non-existing index or alias '%s'." % alias_or_index) return self._connections[index-1] __getitem__ = get_connection def close_all(self, closer_method='close'): """Closes connections using given closer method and empties cache. If simply calling the closer method is not adequate for closing connections, clients should close connections themselves and use :meth:`empty_cache` afterwards. """ for conn in self._connections: getattr(conn, closer_method)() self.empty_cache() return self.current def empty_cache(self): """Empties the connection cache. Indexes of the new connections starts from 1 after this. """ self.current = self._no_current self._connections = [] self._aliases = NormalizedDict() def __iter__(self): return iter(self._connections) def __len__(self): return len(self._connections) def __nonzero__(self): return self.current is not self._no_current def _resolve_alias_or_index(self, alias_or_index): try: return self._resolve_alias(alias_or_index) except ValueError: return self._resolve_index(alias_or_index) def _resolve_alias(self, alias): if isinstance(alias, basestring): try: return self._aliases[alias] except KeyError: pass raise ValueError def _resolve_index(self, index): try: index = int(index) except TypeError: raise ValueError if not 0 < index <= len(self._connections): raise ValueError return index class NoConnection(object): def __init__(self, message): self.message = message def __getattr__(self, name): if name.startswith('__') and name.endswith('__'): raise AttributeError self.raise_error() def raise_error(self): raise RuntimeError(self.message) def __nonzero__(self): return False
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 functools import partial from .normalizing import normalize def eq(str1, str2, ignore=(), caseless=True, spaceless=True): str1 = normalize(str1, ignore, caseless, spaceless) str2 = normalize(str2, ignore, caseless, spaceless) return str1 == str2 class Matcher(object): _pattern_tokenizer = re.compile('(\*|\?)') _wildcards = {'*': '.*', '?': '.'} def __init__(self, pattern, ignore=(), caseless=True, spaceless=True): self.pattern = pattern self._normalize = partial(normalize, ignore=ignore, caseless=caseless, spaceless=spaceless) self._regexp = self._get_and_compile_regexp(self._normalize(pattern)) def _get_and_compile_regexp(self, pattern): pattern = '^%s$' % ''.join(self._yield_regexp(pattern)) return re.compile(pattern, re.DOTALL) def _yield_regexp(self, pattern): for token in self._pattern_tokenizer.split(pattern): if token in self._wildcards: yield self._wildcards[token] else: yield re.escape(token) def match(self, string): return self._regexp.match(self._normalize(string)) is not None def match_any(self, strings): return any(self.match(s) for s in strings) class MultiMatcher(object): def __init__(self, patterns=None, ignore=(), caseless=True, spaceless=True, match_if_no_patterns=False): self._matchers = [Matcher(pattern, ignore, caseless, spaceless) for pattern in self._ensure_list(patterns)] self._match_if_no_patterns = match_if_no_patterns def _ensure_list(self, patterns): if patterns is None: return [] if isinstance(patterns, basestring): return [patterns] return patterns def match(self, string): if self._matchers: return any(m.match(string) for m in self._matchers) return self._match_if_no_patterns def match_any(self, strings): return any(self.match(s) for s in strings) def __len__(self): return len(self._matchers) def __iter__(self): for matcher in self._matchers: yield matcher.pattern
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 setter(object): def __init__(self, method): self.method = method self.attr_name = '_setter__' + method.__name__ self.__doc__ = method.__doc__ def __get__(self, instance, owner): if instance is None: return self try: return getattr(instance, self.attr_name) except AttributeError: raise AttributeError(self.method.__name__) def __set__(self, instance, value): if instance is None: return setattr(instance, self.attr_name, self.method(instance, value)) class SetterAwareType(type): def __new__(cls, name, bases, dct): slots = dct.get('__slots__') if slots is not None: for item in dct.values(): if isinstance(item, setter): slots.append(item.attr_name) return type.__new__(cls, name, bases, dct)
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 robot.errors import DataError from robot.running import TestLibrary, UserLibrary from robot.parsing import disable_curdir_processing from robot import utils from .model import LibraryDoc, KeywordDoc class LibraryDocBuilder(object): _argument_separator = '::' def build(self, library): name, args = self._split_library_name_and_args(library) lib = TestLibrary(name, args) libdoc = LibraryDoc(name=lib.name, doc=self._get_doc(lib), version=lib.version, scope=lib.scope, doc_format=lib.doc_format) libdoc.inits = self._get_initializers(lib) libdoc.keywords = KeywordDocBuilder().build_keywords(lib) return libdoc def _split_library_name_and_args(self, library): args = library.split(self._argument_separator) name = args.pop(0) return self._normalize_library_path(name), args def _normalize_library_path(self, library): path = library.replace('/', os.sep) if os.path.exists(path): return os.path.abspath(path) return library def _get_doc(self, lib): return lib.doc or "Documentation for test library `%s`." % lib.name def _get_initializers(self, lib): if lib.init.arguments.maxargs: return [KeywordDocBuilder().build_keyword(lib.init)] return [] class ResourceDocBuilder(object): def build(self, path): res = self._import_resource(path) libdoc = LibraryDoc(name=res.name, doc=self._get_doc(res), type='resource') libdoc.keywords = KeywordDocBuilder().build_keywords(res) return libdoc @disable_curdir_processing def _import_resource(self, path): return UserLibrary(self._find_resource_file(path)) def _find_resource_file(self, path): if os.path.isfile(path): return path for dire in [item for item in sys.path if os.path.isdir(item)]: if os.path.isfile(os.path.join(dire, path)): return os.path.join(dire, path) raise DataError("Resource file '%s' does not exist." % path) def _get_doc(self, res): doc = res.doc or "Documentation for resource file `%s`." % res.name return utils.unescape(doc) class KeywordDocBuilder(object): def build_keywords(self, lib): return [self.build_keyword(kw) for kw in lib.handlers.values()] def build_keyword(self, kw): return KeywordDoc(name=kw.name, args=self._get_args(kw.arguments), doc=kw.doc) def _get_args(self, argspec): required = argspec.positional[:argspec.minargs] defaults = zip(argspec.positional[argspec.minargs:], argspec.defaults) args = required + ['%s=%s' % item for item in defaults] if argspec.varargs: args.append('*%s' % argspec.varargs) if argspec.kwargs: args.append('**%s' % argspec.kwargs) return 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. from __future__ import with_statement from robot.utils import setter from .writer import LibdocWriter from .output import LibdocOutput class LibraryDoc(object): def __init__(self, name='', doc='', version='', type='library', scope='', named_args=True, doc_format=''): self.name = name self.doc = doc self.version = version self.type = type self.scope = scope self.named_args = named_args self.doc_format = doc_format self.inits = [] self.keywords = [] @setter def scope(self, scope): return {'TESTCASE': 'test case', 'TESTSUITE': 'test suite', 'GLOBAL': 'global'}.get(scope, scope) @setter def doc_format(self, format): return format or 'ROBOT' @setter def keywords(self, kws): return sorted(kws) def save(self, output=None, format='HTML'): with LibdocOutput(output, format) as outfile: LibdocWriter(format).write(self, outfile) class KeywordDoc(object): def __init__(self, name='', args=None, doc=''): self.name = name self.args = args or [] self.doc = doc @property def shortdoc(self): return self.doc.splitlines()[0] if self.doc else '' def __cmp__(self, other): return cmp(self.name.lower(), other.name.lower())
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.htmldata import HtmlFileWriter, ModelWriter, JsonWriter, LIBDOC from robot.utils import get_timestamp, html_escape, html_format, NormalizedDict from robot.utils.htmlformatters import HeaderFormatter class LibdocHtmlWriter(object): def write(self, libdoc, output): model_writer = LibdocModelWriter(output, libdoc) HtmlFileWriter(output, model_writer).write(LIBDOC) class LibdocModelWriter(ModelWriter): def __init__(self, output, libdoc): self._output = output formatter = DocFormatter(libdoc.keywords, libdoc.doc, libdoc.doc_format) self._libdoc = JsonConverter(formatter).convert(libdoc) def write(self, line): self._output.write('<script type="text/javascript">\n') self.write_data() self._output.write('</script>\n') def write_data(self): JsonWriter(self._output).write_json('libdoc = ', self._libdoc) class JsonConverter(object): def __init__(self, doc_formatter): self._doc_formatter = doc_formatter def convert(self, libdoc): return { 'name': libdoc.name, 'doc': self._doc_formatter.html(libdoc.doc, intro=True), 'version': libdoc.version, 'named_args': libdoc.named_args, 'scope': libdoc.scope, 'generated': get_timestamp(daysep='-', millissep=None), 'inits': self._get_keywords(libdoc.inits), 'keywords': self._get_keywords(libdoc.keywords) } def _get_keywords(self, keywords): return [self._convert_keyword(kw) for kw in keywords] def _convert_keyword(self, kw): return { 'name': kw.name, 'args': ', '.join(kw.args), 'doc': self._doc_formatter.html(kw.doc), 'shortdoc': kw.shortdoc } class DocFormatter(object): _header_regexp = re.compile(r'<h([234])>(.+?)</h\1>') _name_regexp = re.compile('`(.+?)`') def __init__(self, keywords, introduction, doc_format='ROBOT'): self._doc_to_html = DocToHtml(doc_format) self._targets = self._get_targets(keywords, introduction, robot_format=doc_format == 'ROBOT') def _get_targets(self, keywords, introduction, robot_format): targets = NormalizedDict({ 'introduction': 'Introduction', 'library introduction': 'Introduction', 'importing': 'Importing', 'library importing': 'Importing', 'shortcuts': 'Shortcuts', 'keywords': 'Keywords' }) for kw in keywords: targets[kw.name] = kw.name if robot_format: for header in self._yield_header_targets(introduction): targets[header] = header return targets def _yield_header_targets(self, introduction): headers = HeaderFormatter() for line in introduction.splitlines(): match = headers.match(line) if match: yield match.group(2) def html(self, doc, intro=False): doc = self._doc_to_html(doc) if intro: doc = self._header_regexp.sub(r'<h\1 id="\2">\2</h\1>', doc) return self._name_regexp.sub(self._link_keywords, doc) def _link_keywords(self, match): name = match.group(1) if name in self._targets: return '<a href="#%s" class="name">%s</a>' % (self._targets[name], name) return '<span class="name">%s</span>' % name class DocToHtml(object): def __init__(self, doc_format): self._formatter = self._get_formatter(doc_format) def _get_formatter(self, doc_format): try: return {'ROBOT': html_format, 'TEXT': self._format_text, 'HTML': self._format_html, 'REST': self._format_rest}[doc_format] except KeyError: raise DataError("Invalid documentation format '%s'." % doc_format) def _format_text(self, doc): return '<p style="white-space: pre-wrap">%s</p>' % html_escape(doc) def _format_html(self, doc): return '<div style="margin: 0">%s</div>' % doc def _format_rest(self, doc): try: from docutils.core import publish_parts except ImportError: raise DataError("reST format requires 'docutils' module to be installed.") parts = publish_parts(doc, writer_name='html') return self._format_html(parts['html_body']) def __call__(self, doc): return self._formatter(doc)
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 class LibdocOutput(object): def __init__(self, output_path, format): self._output_path = output_path self._format = format.upper() self._output_file = None def __enter__(self): if self._format == 'HTML': self._output_file = open(self._output_path, 'w') return self._output_file return self._output_path def __exit__(self, *exc_info): if self._output_file: self._output_file.close() if any(exc_info): os.remove(self._output_path)
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 XmlWriter, get_timestamp class LibdocXmlWriter(object): def write(self, libdoc, outfile): writer = XmlWriter(outfile, encoding='UTF-8') writer.start('keywordspec', {'name': libdoc.name, 'type': libdoc.type, 'format': libdoc.doc_format, 'generated': get_timestamp(millissep=None)}) writer.element('version', libdoc.version) writer.element('scope', libdoc.scope) writer.element('namedargs', 'yes' if libdoc.named_args else 'no') writer.element('doc', libdoc.doc) self._write_keywords('init', libdoc.inits, writer) self._write_keywords('kw', libdoc.keywords, writer) writer.end('keywordspec') writer.close() def _write_keywords(self, type, keywords, writer): for kw in keywords: writer.start(type, {'name': kw.name} if type == 'kw' else {}) writer.start('arguments') for arg in kw.args: writer.element('arg', arg) writer.end('arguments') writer.element('doc', kw.doc) writer.end(type)
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 textwrap from robot.utils import MultiMatcher, encode_output from robot.errors import DataError class ConsoleViewer(object): def __init__(self, libdoc): self._libdoc = libdoc self._keywords = KeywordMatcher(libdoc) @classmethod def handles(cls, command): return command.lower() in ['list', 'show', 'version'] @classmethod def validate_command(cls, command, args): if not cls.handles(command): raise DataError("Unknown command '%s'." % command) if command.lower() == 'version' and args: raise DataError("Command 'version' does not take arguments.") def view(self, command, *args): self.validate_command(command, args) getattr(self, command.lower())(*args) def list(self, *patterns): for kw in self._keywords.search('*%s*' % p for p in patterns): self._console(kw.name) def show(self, *names): if MultiMatcher(names, match_if_no_patterns=True).match('intro'): self._show_intro(self._libdoc) if self._libdoc.inits: self._show_inits(self._libdoc) for kw in self._keywords.search(names): self._show_keyword(kw) def version(self): self._console(self._libdoc.version or 'N/A') def _console(self, msg): print encode_output(msg) def _show_intro(self, lib): self._header(lib.name, underline='=') named_args = 'supported' if lib.named_args else 'not supported' self._data([('Version', lib.version), ('Scope', lib.scope), ('Named arguments', named_args)]) self._doc(lib.doc) def _show_inits(self, lib): self._header('Importing', underline='-') for init in lib.inits: self._show_keyword(init, show_name=False) def _show_keyword(self, kw, show_name=True): if show_name: self._header(kw.name, underline='-') self._data([('Arguments', '[%s]' % ', '.join(kw.args))]) self._doc(kw.doc) def _header(self, name, underline): self._console('%s\n%s' % (name, underline * len(name))) def _data(self, items): ljust = max(len(name) for name, _ in items) + 3 for name, value in items: if value: text = '%s%s' % ((name+':').ljust(ljust), value) self._console(self._wrap(text, subsequent_indent=' '*ljust)) def _doc(self, doc): self._console('') for line in doc.splitlines(): self._console(self._wrap(line)) if doc: self._console('') def _wrap(self, text, width=78, **config): return '\n'.join(textwrap.wrap(text, width=width, **config)) class KeywordMatcher(object): def __init__(self, libdoc): self._keywords = libdoc.keywords def search(self, patterns): matcher = MultiMatcher(patterns, match_if_no_patterns=True) for kw in self._keywords: if matcher.match(kw.name): yield kw
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 import utils from .model import LibraryDoc, KeywordDoc class JavaDocBuilder(object): def build(self, path): doc = ClassDoc(path) libdoc = LibraryDoc(name=doc.qualifiedName(), doc=self._get_doc(doc), version=self._get_version(doc), scope=self._get_scope(doc), named_args=False, doc_format=self._get_doc_format(doc)) libdoc.inits = self._initializers(doc) libdoc.keywords = self._keywords(doc) return libdoc def _get_doc(self, doc): text = doc.getRawCommentText() return '\n'.join(line.strip() for line in text.splitlines()) def _get_version(self, doc): return self._get_attr(doc, 'VERSION') def _get_scope(self, doc): return self._get_attr(doc, 'SCOPE', default='TESTCASE', upper=True) def _get_doc_format(self, doc): return self._get_attr(doc, 'DOC_FORMAT', upper=True) def _get_attr(self, doc, name, default='', upper=False): name = 'ROBOT_LIBRARY_' + name for field in doc.fields(): if field.name() == name and field.isPublic(): value = field.constantValue() if upper: value = utils.normalize(value, ignore='_').upper() return value return default def _initializers(self, doc): inits = [self._keyword_doc(init) for init in doc.constructors()] if len(inits) == 1 and not inits[0].args: return [] return inits def _keywords(self, doc): return [self._keyword_doc(m) for m in doc.methods()] def _keyword_doc(self, method): return KeywordDoc( name=utils.printable_name(method.name(), code_style=True), args=self._get_keyword_arguments(method), doc=self._get_doc(method) ) def _get_keyword_arguments(self, method): params = method.parameters() if not params: return [] names = [p.name() for p in params] if self._is_varargs(params[-1]): names[-1] = '*' + names[-1] elif self._is_kwargs(params[-1]): names[-1] = '**' + names[-1] if len(params) > 1 and self._is_varargs(params[-2]): names[-2] = '*' + names[-2] return names def _is_varargs(self, param): return (param.typeName().startswith('java.util.List') or param.type().dimension() == '[]') def _is_kwargs(self, param): return param.typeName().startswith('java.util.Map') def ClassDoc(path): """Process the given Java source file and return ClassDoc instance. Processing is done using com.sun.tools.javadoc APIs. Returned object implements com.sun.javadoc.ClassDoc interface: http://docs.oracle.com/javase/7/docs/jdk/api/javadoc/doclet/ """ try: from com.sun.tools.javadoc import JavadocTool, Messager, ModifierFilter from com.sun.tools.javac.util import List, Context from com.sun.tools.javac.code.Flags import PUBLIC except ImportError: raise DataError("Creating documentation from Java source files " "requires 'tools.jar' to be in CLASSPATH.") context = Context() Messager.preRegister(context, 'libdoc') jdoctool = JavadocTool.make0(context) filter = ModifierFilter(PUBLIC) java_names = List.of(path) root = jdoctool.getRootDocImpl('en', 'utf-8', filter, java_names, List.nil(), False, List.nil(), List.nil(), False, False, True) return root.classes()[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. """Implements the `Libdoc` tool. The command line entry point and programmatic interface for Libdoc are provided by the separate :mod:`robot.libdoc` module. This package is considered stable but it is not part of the public API. """ from robot.errors import DataError from robot.utils import get_error_message from .builder import DocumentationBuilder from .consoleviewer import ConsoleViewer def LibraryDocumentation(library_or_resource, name=None, version=None, doc_format=None): builder = DocumentationBuilder(library_or_resource) try: libdoc = builder.build(library_or_resource) except DataError: raise except: raise DataError("Building library '%s' failed: %s" % (library_or_resource, get_error_message())) if name: libdoc.name = name if version: libdoc.version = version if doc_format: libdoc.doc_format = doc_format return libdoc
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 from robot.parsing import VALID_EXTENSIONS as RESOURCE_EXTENSIONS from robot.errors import DataError from .robotbuilder import LibraryDocBuilder, ResourceDocBuilder from .specbuilder import SpecDocBuilder if sys.platform.startswith('java'): from .javabuilder import JavaDocBuilder else: def JavaDocBuilder(): raise DataError('Documenting Java test libraries requires Jython.') def DocumentationBuilder(library_or_resource): extension = os.path.splitext(library_or_resource)[1][1:].lower() if extension in RESOURCE_EXTENSIONS: return ResourceDocBuilder() if extension == 'xml': return SpecDocBuilder() if extension == 'java': return JavaDocBuilder() return LibraryDocBuilder()
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 .htmlwriter import LibdocHtmlWriter from .xmlwriter import LibdocXmlWriter def LibdocWriter(format=None): format = (format or 'HTML').upper() if format == 'HTML': return LibdocHtmlWriter() if format == 'XML': return LibdocXmlWriter() raise DataError("Format must be either 'HTML' or 'XML', got '%s'." % format)
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.path from robot.errors import DataError from robot.utils import ET, ETSource from .model import LibraryDoc, KeywordDoc class SpecDocBuilder(object): def build(self, path): spec = self._parse_spec(path) libdoc = LibraryDoc(name=spec.get('name'), type=spec.get('type'), version=spec.find('version').text or '', doc=spec.find('doc').text or '', scope=spec.find('scope').text or '', named_args=self._get_named_args(spec), doc_format=spec.get('format', 'ROBOT')) libdoc.inits = self._create_keywords(spec, 'init') libdoc.keywords = self._create_keywords(spec, 'kw') return libdoc def _parse_spec(self, path): if not os.path.isfile(path): raise DataError("Spec file '%s' does not exist." % path) with ETSource(path) as source: root = ET.parse(source).getroot() if root.tag != 'keywordspec': raise DataError("Invalid spec file '%s'." % path) return root def _get_named_args(self, spec): elem = spec.find('namedargs') if elem is None: return False # Backwards compatiblity with RF < 2.6.2 return elem.text == 'yes' def _create_keywords(self, spec, path): return [self._create_keyword(elem) for elem in spec.findall(path)] def _create_keyword(self, elem): return KeywordDoc(name=elem.get('name', ''), args=[a.text for a in elem.findall('arguments/arg')], doc=elem.find('doc').text or '')
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 `Testdoc` tool. This module can be executed from the command line using the following approaches:: python -m robot.testdoc python path/to/robot/testdoc.py Instead of ``python`` it is possible to use also other Python interpreters. This module also provides :func:`testdoc` and :func:`testdoc_cli` functions that can be used programmatically. Other code is for internal usage. """ from __future__ import with_statement USAGE = """robot.testdoc -- Robot Framework test data documentation tool Version: <VERSION> Usage: python -m robot.testdoc [options] data_sources output_file Testdoc generates a high level test documentation based on Robot Framework test data. Generated documentation includes name, documentation and other metadata of each test suite and test case, as well as the top-level keywords and their arguments. Options ======= -T --title title Set the title of the generated documentation. Underscores in the title are converted to spaces. The default title is the name of the top level suite. -N --name name Override the name of the top level suite. -D --doc document Override the documentation of the top level suite. -M --metadata name:value * Set/override metadata of the top level suite. -G --settag tag * Set given tag(s) to all test cases. -t --test name * Include tests by name. -s --suite name * Include suites by name. -i --include tag * Include tests by tags. -e --exclude tag * Exclude tests by tags. -h -? --help Print this help. All options except --title have exactly same semantics as same options have when executing test cases. Execution ========= Data can be given as a single file, directory, or as multiple files and directories. In all these cases, the last argument must be the file where to write the output. The output is always created in HTML format. Testdoc works with all interpreters supported by Robot Framework (Python, Jython and IronPython). It can be executed as an installed module like `python -m robot.testdoc` or as a script like `python path/robot/testdoc.py`. Examples: python -m robot.testdoc my_test.html testdoc.html jython -m robot.testdoc -N smoke_tests -i smoke path/to/my_tests smoke.html ipy path/to/robot/testdoc.py first_suite.txt second_suite.txt output.html """ import os.path import sys import time # 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 import utils from robot.conf import RobotSettings from robot.htmldata import HtmlFileWriter, ModelWriter, JsonWriter, TESTDOC from robot.parsing import disable_curdir_processing from robot.running import TestSuiteBuilder class TestDoc(utils.Application): def __init__(self): utils.Application.__init__(self, USAGE, arg_limits=(2,)) def main(self, datasources, title=None, **options): outfile = utils.abspath(datasources.pop()) suite = TestSuiteFactory(datasources, **options) self._write_test_doc(suite, outfile, title) self.console(outfile) def _write_test_doc(self, suite, outfile, title): with open(outfile, 'w') as output: model_writer = TestdocModelWriter(output, suite, title) HtmlFileWriter(output, model_writer).write(TESTDOC) @disable_curdir_processing def TestSuiteFactory(datasources, **options): settings = RobotSettings(options) if isinstance(datasources, basestring): datasources = [datasources] suite = TestSuiteBuilder().build(*datasources) suite.configure(**settings.suite_config) return suite class TestdocModelWriter(ModelWriter): def __init__(self, output, suite, title=None): self._output = output self._output_path = getattr(output, 'name', None) self._suite = suite self._title = title.replace('_', ' ') if title else suite.name def write(self, line): self._output.write('<script type="text/javascript">\n') self.write_data() self._output.write('</script>\n') def write_data(self): generated_time = time.localtime() model = { 'suite': JsonConverter(self._output_path).convert(self._suite), 'title': self._title, 'generated': utils.format_time(generated_time, gmtsep=' '), 'generatedMillis': long(time.mktime(generated_time) * 1000) } JsonWriter(self._output).write_json('testdoc = ', model) class JsonConverter(object): def __init__(self, output_path=None): self._output_path = output_path def convert(self, suite): return self._convert_suite(suite) def _convert_suite(self, suite): return { 'source': suite.source or '', 'relativeSource': self._get_relative_source(suite.source), 'id': suite.id, 'name': self._escape(suite.name), 'fullName': self._escape(suite.longname), 'doc': self._html(suite.doc), 'metadata': [(self._escape(name), self._html(value)) for name, value in suite.metadata.items()], 'numberOfTests': suite.test_count , 'suites': self._convert_suites(suite), 'tests': self._convert_tests(suite), 'keywords': list(self._convert_keywords(suite)) } def _get_relative_source(self, source): if not source or not self._output_path: return '' return utils.get_link_path(source, os.path.dirname(self._output_path)) def _escape(self, item): return utils.html_escape(item) def _html(self, item): return utils.html_format(utils.unescape(item)) def _convert_suites(self, suite): return [self._convert_suite(s) for s in suite.suites] def _convert_tests(self, suite): return [self._convert_test(t) for t in suite.tests] def _convert_test(self, test): return { 'name': self._escape(test.name), 'fullName': self._escape(test.longname), 'id': test.id, 'doc': self._html(test.doc), 'tags': [self._escape(t) for t in test.tags], 'timeout': self._get_timeout(test.timeout), 'keywords': list(self._convert_keywords(test)) } def _convert_keywords(self, item): for kw in getattr(item, 'keywords', []): if kw.type == 'setup': yield self._convert_keyword(kw, 'SETUP') elif kw.type == 'teardown': yield self._convert_keyword(kw, 'TEARDOWN') elif kw.is_for_loop(): yield self._convert_for_loop(kw) else: yield self._convert_keyword(kw, 'KEYWORD') def _convert_for_loop(self, kw): return { 'name': self._escape(self._get_for_loop(kw)), 'arguments': '', 'type': 'FOR' } def _convert_keyword(self, kw, kw_type): return { 'name': self._escape(self._get_kw_name(kw)), 'arguments': self._escape(', '.join(kw.args)), 'type': kw_type } def _get_kw_name(self, kw): if kw.assign: return '%s = %s' % (', '.join(a.rstrip('= ') for a in kw.assign), kw.name) return kw.name def _get_for_loop(self, kw): joiner = ' IN RANGE ' if kw.range else ' IN ' return ', '.join(kw.vars) + joiner + utils.seq2str2(kw.items) def _get_timeout(self, timeout): if timeout is None: return '' try: tout = utils.secs_to_timestr(utils.timestr_to_secs(timeout.value)) except ValueError: tout = timeout.value if timeout.message: tout += ' :: ' + timeout.message return tout def testdoc_cli(arguments): """Executes `Testdoc` similarly as from the command line. :param arguments: command line arguments as a list of strings. For programmatic usage the :func:`testdoc` function is typically better. It has a better API for that and does not call :func:`sys.exit` like this function. Example:: from robot.testdoc import testdoc_cli testdoc_cli(['--title', 'Test Plan', 'mytests', 'plan.html']) """ TestDoc().execute_cli(arguments) def testdoc(*arguments, **options): """Executes `Testdoc` programmatically. Arguments and options have same semantics, and options have same names, as arguments and options to Testdoc. Example:: from robot.testdoc import testdoc testdoc('mytests', 'plan.html', title='Test Plan') """ TestDoc().execute(*arguments, **options) if __name__ == '__main__': testdoc_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. from robot.api import logger from robot.utils import plural_or_not, seq2str, seq2str2, unic from robot.utils.asserts import assert_equals from robot.version import get_version class _List: def convert_to_list(self, item): """Converts the given `item` to a list. Mainly useful for converting tuples and other iterable to lists. Use `Create List` from the BuiltIn library for constructing new lists. """ return list(item) def append_to_list(self, list_, *values): """Adds `values` to the end of `list`. Example: | Append To List | ${L1} | xxx | | | | Append To List | ${L2} | x | y | z | => - ${L1} = ['a', 'xxx'] - ${L2} = ['a', 'b', 'x', 'y', 'z'] """ for value in values: list_.append(value) def insert_into_list(self, list_, index, value): """Inserts `value` into `list` to the position specified with `index`. Index '0' adds the value into the first position, '1' to the second, and so on. Inserting from right works with negative indices so that '-1' is the second last position, '-2' third last, and so on. Use `Append To List` to add items to the end of the list. If the absolute value of the index is greater than the length of the list, the value is added at the end (positive index) or the beginning (negative index). An index can be given either as an integer or a string that can be converted to an integer. Example: | Insert Into List | ${L1} | 0 | xxx | | Insert Into List | ${L2} | ${-1} | xxx | => - ${L1} = ['xxx', 'a'] - ${L2} = ['a', 'xxx', 'b'] """ list_.insert(self._index_to_int(index), value) def combine_lists(self, *lists): """Combines the given `lists` together and returns the result. The given lists are not altered by this keyword. Example: | ${x} = | Combine List | ${L1} | ${L2} | | | ${y} = | Combine List | ${L1} | ${L2} | ${L1} | => - ${x} = ['a', 'a', 'b'] - ${y} = ['a', 'a', 'b', 'a'] - ${L1} and ${L2} are not changed. """ ret = [] for item in lists: ret.extend(item) return ret def set_list_value(self, list_, index, value): """Sets the value of `list` specified by `index` to the given `value`. Index '0' means the first position, '1' the second and so on. Similarly, '-1' is the last position, '-2' second last, and so on. Using an index that does not exist on the list causes an error. The index can be either an integer or a string that can be converted to an integer. Example: | Set List Value | ${L3} | 1 | xxx | | Set List Value | ${L3} | -1 | yyy | => - ${L3} = ['a', 'xxx', 'yyy'] """ try: list_[self._index_to_int(index)] = value except IndexError: self._index_error(list_, index) def remove_values_from_list(self, list_, *values): """Removes all occurences of given `values` from `list`. It is not an error is a value does not exist in the list at all. Example: | Remove Values From List | ${L4} | a | c | e | f | => - ${L4} = ['b', 'd'] """ for value in values: while value in list_: list_.remove(value) def remove_from_list(self, list_, index): """Removes and returns the value specified with an `index` from `list`. Index '0' means the first position, '1' the second and so on. Similarly, '-1' is the last position, '-2' the second last, and so on. Using an index that does not exist on the list causes an error. The index can be either an integer or a string that can be converted to an integer. Example: | ${x} = | Remove From List | ${L2} | 0 | => - ${x} = 'a' - ${L2} = ['b'] """ try: return list_.pop(self._index_to_int(index)) except IndexError: self._index_error(list_, index) def remove_duplicates(self, list_): """Returns a list without duplicates based on the given `list`. Creates and returns a new list that contains all items in the given list so that one item can appear only once. Order of the items in the new list is the same as in the original except for missing duplicates. Number of the removed duplicates is logged. New in Robot Framework 2.7.5. """ ret = [] for item in list_: if item not in ret: ret.append(item) removed = len(list_) - len(ret) logger.info('%d duplicate%s removed.' % (removed, plural_or_not(removed))) return ret def get_from_list(self, list_, index): """Returns the value specified with an `index` from `list`. The given list is never altered by this keyword. Index '0' means the first position, '1' the second, and so on. Similarly, '-1' is the last position, '-2' the second last, and so on. Using an index that does not exist on the list causes an error. The index can be either an integer or a string that can be converted to an integer. Examples (including Python equivalents in comments): | ${x} = | Get From List | ${L5} | 0 | # L5[0] | | ${y} = | Get From List | ${L5} | -2 | # L5[-2] | => - ${x} = 'a' - ${y} = 'd' - ${L5} is not changed """ try: return list_[self._index_to_int(index)] except IndexError: self._index_error(list_, index) def get_slice_from_list(self, list_, start=0, end=None): """Returns a slice of the given list between `start` and `end` indexes. The given list is never altered by this keyword. If both `start` and `end` are given, a sublist containing values from `start` to `end` is returned. This is the same as 'list[start:end]' in Python. To get all items from the beginning, use 0 as the start value, and to get all items until the end, use 'None' as the end value. 'None' is also a default value, so in this case, it is enough to give only `start`. If only `end` is given, `start` gets the value 0. Using `start` or `end` not found on the list is the same as using the largest (or smallest) available index. Examples (incl. Python equivelants in comments): | ${x} = | Get Slice From List | ${L5} | 2 | 4 | # L5[2:4] | | ${y} = | Get Slice From List | ${L5} | 1 | | # L5[1:None] | | ${z} = | Get Slice From List | ${L5} | | -2 | # L5[0:-2] | => - ${x} = ['c', 'd'] - ${y} = ['b', 'c', 'd', 'e'] - ${z} = ['a', 'b', 'c'] - ${L5} is not changed """ start = self._index_to_int(start, True) if end is not None: end = self._index_to_int(end) return list_[start:end] def count_values_in_list(self, list_, value, start=0, end=None): """Returns the number of occurrences of the given `value` in `list`. The search can be narrowed to the selected sublist by the `start` and `end` indexes having the same semantics as in the `Get Slice From List` keyword. The given list is never altered by this keyword. Example: | ${x} = | Count Values In List | ${L3} | b | => - ${x} = 1 - ${L3} is not changed """ return self.get_slice_from_list(list_, start, end).count(value) def get_index_from_list(self, list_, value, start=0, end=None): """Returns the index of the first occurrence of the `value` on the list. The search can be narrowed to the selected sublist by the `start` and `end` indexes having the same semantics as in the `Get Slice From List` keyword. In case the value is not found, -1 is returned. The given list is never altered by this keyword. Example: | ${x} = | Get Index From List | ${L5} | d | => - ${x} = 3 - ${L5} is not changed """ if start == '': start = 0 list_ = self.get_slice_from_list(list_, start, end) try: return int(start) + list_.index(value) except ValueError: return -1 def copy_list(self, list_): """Returns a copy of the given list. The given list is never altered by this keyword. """ return list_[:] def reverse_list(self, list_): """Reverses the given list in place. Note that the given list is changed and nothing is returned. Use `Copy List` first, if you need to keep also the original order. | Reverse List | ${L3} | => - ${L3} = ['c', 'b', 'a'] """ list_.reverse() def sort_list(self, list_): """Sorts the given list in place. The strings are sorted alphabetically and the numbers numerically. Note that the given list is changed and nothing is returned. Use `Copy List` first, if you need to keep also the original order. ${L} = [2,1,'a','c','b'] | Sort List | ${L} | => - ${L} = [1, 2, 'a', 'b', 'c'] """ list_.sort() def list_should_contain_value(self, list_, value, msg=None): """Fails if the `value` is not found from `list`. If `msg` is not given, the default error message "[ a | b | c ] does not contain the value 'x'" is shown in case of a failure. Otherwise, the given `msg` is used in case of a failure. """ default = "%s does not contain value '%s'." % (seq2str2(list_), value) _verify_condition(value in list_, default, msg) def list_should_not_contain_value(self, list_, value, msg=None): """Fails if the `value` is not found from `list`. See `List Should Contain Value` for an explanation of `msg`. """ default = "%s contains value '%s'." % (seq2str2(list_), value) _verify_condition(value not in list_, default, msg) def list_should_not_contain_duplicates(self, list_, msg=None): """Fails if any element in the `list` is found from it more than once. The default error message lists all the elements that were found from the `list` multiple times, but it can be overridden by giving a custom `msg`. All multiple times found items and their counts are also logged. This keyword works with all iterables that can be converted to a list. The original iterable is never altered. """ if not isinstance(list_, list): list_ = list(list_) dupes = [] for item in list_: if item not in dupes: count = list_.count(item) if count > 1: logger.info("'%s' found %d times." % (item, count)) dupes.append(item) if dupes: raise AssertionError(msg or '%s found multiple times.' % seq2str(dupes)) def lists_should_be_equal(self, list1, list2, msg=None, values=True, names=None): """Fails if given lists are unequal. The keyword first verifies that the lists have equal lengths, and then it checks are all their values equal. Possible differences between the values are listed in the default error message like `Index 4: ABC != Abc`. The error message can be configured using `msg` and `values` arguments: - If `msg` is not given, the default error message is used. - If `msg` is given and `values` is either Boolean False or a string 'False' or 'No Values', the error message is simply `msg`. - Otherwise the error message is `msg` + 'new line' + default. Optional `names` argument (new in 2.6) can be used for naming the indices shown in the default error message. It can either be a list of names matching the indices in the lists or a dictionary where keys are indices that need to be named. It is not necessary to name all of the indices. When using a dictionary, keys can be either integers or strings that can be converted to integers. Examples: | ${names} = | Create List | First Name | Family Name | Email | | Lists Should Be Equal | ${people1} | ${people2} | names=${names} | | ${names} = | Create Dictionary | 0 | First Name | 2 | Email | | Lists Should Be Equal | ${people1} | ${people2} | names=${names} | If the items in index 2 would differ in the above examples, the error message would contain a row like `Index 2 (email): name@foo.com != name@bar.com`. """ len1 = len(list1) len2 = len(list2) default = 'Lengths are different: %d != %d' % (len1, len2) _verify_condition(len1 == len2, default, msg, values) names = self._get_list_index_name_mapping(names, len1) diffs = list(self._yield_list_diffs(list1, list2, names)) default = 'Lists are different:\n' + '\n'.join(diffs) _verify_condition(diffs == [], default, msg, values) def _get_list_index_name_mapping(self, names, list_length): if not names: return {} if isinstance(names, dict): return dict((int(index), names[index]) for index in names) return dict(zip(range(list_length), names)) def _yield_list_diffs(self, list1, list2, names): for index, (item1, item2) in enumerate(zip(list1, list2)): name = ' (%s)' % names[index] if index in names else '' try: assert_equals(item1, item2, msg='Index %d%s' % (index, name)) except AssertionError, err: yield unic(err) def list_should_contain_sub_list(self, list1, list2, msg=None, values=True): """Fails if not all of the elements in `list2` are found in `list1`. The order of values and the number of values are not taken into account. See the use of `msg` and `values` from the `Lists Should Be Equal` keyword. """ diffs = ', '.join(unic(item) for item in list2 if item not in list1) default = 'Following values were not found from first list: ' + diffs _verify_condition(not diffs, default, msg, values) def log_list(self, list_, level='INFO'): """Logs the length and contents of the `list` using given `level`. Valid levels are TRACE, DEBUG, INFO (default), and WARN. If you only want to the length, use keyword `Get Length` from the BuiltIn library. """ logger.write('\n'.join(self._log_list(list_)), level) def _log_list(self, list_): if not list_: yield 'List is empty.' elif len(list_) == 1: yield 'List has one item:\n%s' % list_[0] else: yield 'List length is %d and it contains following items:' % len(list_) for index, item in enumerate(list_): yield '%s: %s' % (index, item) def _index_to_int(self, index, empty_to_zero=False): if empty_to_zero and not index: return 0 try: return int(index) except ValueError: raise ValueError("Cannot convert index '%s' to an integer." % index) def _index_error(self, list_, index): raise IndexError('Given index %s is out of the range 0-%d.' % (index, len(list_)-1)) class _Dictionary: def create_dictionary(self, *key_value_pairs, **items): """Creates and returns a dictionary based on given items. Giving items as `key_value_pairs` means giving keys and values as separate arguments: | ${x} = | Create Dictionary | name | value | | | | ${y} = | Create Dictionary | a | 1 | b | ${2} | => - ${x} = {'name': 'value'} - ${y} = {'a': '1', 'b': 2} Starting from Robot Framework 2.8.1, items can also be given as kwargs: | ${x} = | Create Dictionary | name=value | | | ${y} = | Create Dictionary | a=1 | b=${2} | The latter syntax is typically more convenient to use, but it has a limitation that keys must be strings. """ if len(key_value_pairs) % 2 != 0: raise ValueError("Creating a dictionary failed. There should be " "even number of key-value-pairs.") return self.set_to_dictionary({}, *key_value_pairs, **items) def set_to_dictionary(self, dictionary, *key_value_pairs, **items): """Adds the given `key_value_pairs` and `items`to the `dictionary`. See `Create Dictionary` for information about giving items. Example: | Set To Dictionary | ${D1} | key | value | => - ${D1} = {'a': 1, 'key': 'value'} """ if len(key_value_pairs) % 2 != 0: raise ValueError("Adding data to a dictionary failed. There " "should be even number of key-value-pairs.") for i in range(0, len(key_value_pairs), 2): dictionary[key_value_pairs[i]] = key_value_pairs[i+1] dictionary.update(items) return dictionary def remove_from_dictionary(self, dictionary, *keys): """Removes the given `keys` from the `dictionary`. If the given `key` cannot be found from the `dictionary`, it is ignored. Example: | Remove From Dictionary | ${D3} | b | x | y | => - ${D3} = {'a': 1, 'c': 3} """ for key in keys: if key in dictionary: value = dictionary.pop(key) logger.info("Removed item with key '%s' and value '%s'." % (key, value)) else: logger.info("Key '%s' not found." % key) def keep_in_dictionary(self, dictionary, *keys): """Keeps the given `keys` in the `dictionary` and removes all other. If the given `key` cannot be found from the `dictionary`, it is ignored. Example: | Keep In Dictionary | ${D5} | b | x | d | => - ${D5} = {'b': 2, 'd': 4} """ remove_keys = [k for k in dictionary if k not in keys] self.remove_from_dictionary(dictionary, *remove_keys) def copy_dictionary(self, dictionary): """Returns a copy of the given dictionary. The given dictionary is never altered by this keyword. """ return dictionary.copy() def get_dictionary_keys(self, dictionary): """Returns `keys` of the given `dictionary`. `Keys` are returned in sorted order. The given `dictionary` is never altered by this keyword. Example: | ${keys} = | Get Dictionary Keys | ${D3} | => - ${keys} = ['a', 'b', 'c'] """ return sorted(dictionary) def get_dictionary_values(self, dictionary): """Returns values of the given dictionary. Values are returned sorted according to keys. The given dictionary is never altered by this keyword. Example: | ${values} = | Get Dictionary Values | ${D3} | => - ${values} = [1, 2, 3] """ return [dictionary[k] for k in self.get_dictionary_keys(dictionary)] def get_dictionary_items(self, dictionary): """Returns items of the given `dictionary`. Items are returned sorted by keys. The given `dictionary` is not altered by this keyword. Example: | ${items} = | Get Dictionary Items | ${D3} | => - ${items} = ['a', 1, 'b', 2, 'c', 3] """ ret = [] for key in self.get_dictionary_keys(dictionary): ret.extend((key, dictionary[key])) return ret def get_from_dictionary(self, dictionary, key): """Returns a value from the given `dictionary` based on the given `key`. If the given `key` cannot be found from the `dictionary`, this keyword fails. The given dictionary is never altered by this keyword. Example: | ${value} = | Get From Dictionary | ${D3} | b | => - ${value} = 2 """ try: return dictionary[key] except KeyError: raise RuntimeError("Dictionary does not contain key '%s'." % key) def dictionary_should_contain_key(self, dictionary, key, msg=None): """Fails if `key` is not found from `dictionary`. See `List Should Contain Value` for an explanation of `msg`. The given dictionary is never altered by this keyword. """ default = "Dictionary does not contain key '%s'." % key _verify_condition(key in dictionary, default, msg) def dictionary_should_not_contain_key(self, dictionary, key, msg=None): """Fails if `key` is found from `dictionary`. See `List Should Contain Value` for an explanation of `msg`. The given dictionary is never altered by this keyword. """ default = "Dictionary contains key '%s'." % key _verify_condition(key not in dictionary, default, msg) def dictionary_should_contain_item(self, dictionary, key, value, msg=None): """An item of `key`/`value` must be found in a `dictionary`. Value is converted to unicode for comparison. See `Lists Should Be Equal` for an explanation of `msg`. The given dictionary is never altered by this keyword. """ self.dictionary_should_contain_key(dictionary, key, msg) actual, expected = unicode(dictionary[key]), unicode(value) default = "Value of dictionary key '%s' does not match: %s != %s" % (key, actual, expected) _verify_condition(actual == expected, default, msg) def dictionary_should_contain_value(self, dictionary, value, msg=None): """Fails if `value` is not found from `dictionary`. See `List Should Contain Value` for an explanation of `msg`. The given dictionary is never altered by this keyword. """ default = "Dictionary does not contain value '%s'." % value _verify_condition(value in dictionary.values(), default, msg) def dictionary_should_not_contain_value(self, dictionary, value, msg=None): """Fails if `value` is found from `dictionary`. See `List Should Contain Value` for an explanation of `msg`. The given dictionary is never altered by this keyword. """ default = "Dictionary contains value '%s'." % value _verify_condition(not value in dictionary.values(), default, msg) def dictionaries_should_be_equal(self, dict1, dict2, msg=None, values=True): """Fails if the given dictionaries are not equal. First the equality of dictionaries' keys is checked and after that all the key value pairs. If there are differences between the values, those are listed in the error message. See `Lists Should Be Equal` for an explanation of `msg`. The given dictionaries are never altered by this keyword. """ keys = self._keys_should_be_equal(dict1, dict2, msg, values) self._key_values_should_be_equal(keys, dict1, dict2, msg, values) def dictionary_should_contain_sub_dictionary(self, dict1, dict2, msg=None, values=True): """Fails unless all items in `dict2` are found from `dict1`. See `Lists Should Be Equal` for an explanation of `msg`. The given dictionaries are never altered by this keyword. """ keys = self.get_dictionary_keys(dict2) diffs = [unic(k) for k in keys if k not in dict1] default = "Following keys missing from first dictionary: %s" \ % ', '.join(diffs) _verify_condition(not diffs, default, msg, values) self._key_values_should_be_equal(keys, dict1, dict2, msg, values) def log_dictionary(self, dictionary, level='INFO'): """Logs the size and contents of the `dictionary` using given `level`. Valid levels are TRACE, DEBUG, INFO (default), and WARN. If you only want to log the size, use keyword `Get Length` from the BuiltIn library. """ logger.write('\n'.join(self._log_dictionary(dictionary)), level) def _log_dictionary(self, dictionary): if not dictionary: yield 'Dictionary is empty.' elif len(dictionary) == 1: yield 'Dictionary has one item:' else: yield 'Dictionary size is %d and it contains following items:' % len(dictionary) for key in self.get_dictionary_keys(dictionary): yield '%s: %s' % (key, dictionary[key]) def _keys_should_be_equal(self, dict1, dict2, msg, values): keys1 = self.get_dictionary_keys(dict1) keys2 = self.get_dictionary_keys(dict2) miss1 = [unic(k) for k in keys2 if k not in dict1] miss2 = [unic(k) for k in keys1 if k not in dict2] error = [] if miss1: error += ['Following keys missing from first dictionary: %s' % ', '.join(miss1)] if miss2: error += ['Following keys missing from second dictionary: %s' % ', '.join(miss2)] _verify_condition(not error, '\n'.join(error), msg, values) return keys1 def _key_values_should_be_equal(self, keys, dict1, dict2, msg, values): diffs = list(self._yield_dict_diffs(keys, dict1, dict2)) default = 'Following keys have different values:\n' + '\n'.join(diffs) _verify_condition(not diffs, default, msg, values) def _yield_dict_diffs(self, keys, dict1, dict2): for key in keys: try: assert_equals(dict1[key], dict2[key], msg='Key %s' % (key,)) except AssertionError, err: yield unic(err) class Collections(_List, _Dictionary): """A test library providing keywords for handling lists and dictionaries. `Collections` is Robot Framework's standard library that provides a set of keywords for handling Python lists and dictionaries. This library has keywords, for example, for modifying and getting values from lists and dictionaries (e.g. `Append To List`, `Get From Dictionary`) and for verifying their contents (e.g. `Lists Should Be Equal`, `Dictionary Should Contain Value`). Following keywords from the BuiltIn library can also be used with lists and dictionaries: | *Keyword Name* | *Applicable With* | | `Create List` | lists | | `Get Length` | both | | `Length Should Be` | both | | `Should Be Empty` | both | | `Should Not Be Empty` | both | | `Should Contain` | lists | | `Should Not Contain` | lists | | `Should Contain X Times` | lists | | `Should Not Contain X Times` | lists | | `Get Count` | lists | All list keywords expect a scalar variable (e.g. ${list}) as an argument. It is, however, possible to use list variables (e.g. @{list}) as scalars simply by replacing '@' with '$'. List keywords that do not alter the given list can also be used with tuples, and to some extend also with other iterables. `Convert To List` can be used to convert tuples and other iterables to lists. ------- List related keywords use variables in format ${Lx} in their examples, which means a list with as many alphabetic characters as specified by 'x'. For example ${L1} means ['a'] and ${L3} means ['a', 'b', 'c']. Dictionary keywords use similar ${Dx} variables. For example ${D1} means {'a': 1} and ${D3} means {'a': 1, 'b': 2, 'c': 3}. -------- """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() def _verify_condition(condition, default_msg, given_msg, include_default=False): if not condition: if not given_msg: raise AssertionError(default_msg) if _include_default_message(include_default): raise AssertionError(given_msg + '\n' + default_msg) raise AssertionError(given_msg) def _include_default_message(include): if isinstance(include, basestring): return include.lower() not in ['no values', 'false'] return bool(include)
Python
# Copyright 2008-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. RESERVED_KEYWORDS = ['for', 'while', 'break', 'continue', 'end', 'if', 'else', 'elif', 'else if', 'return'] class Reserved(object): ROBOT_LIBRARY_SCOPE = 'GLOBAL' def get_keyword_names(self): return RESERVED_KEYWORDS def run_keyword(self, name, args): raise Exception("'%s' is a reserved keyword" % name.title())
Python
# Copyright 2008-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 subprocess import sys import time import signal as signal_module from robot.utils import (ConnectionCache, abspath, encode_to_system, decode_output, secs_to_timestr, timestr_to_secs) from robot.version import get_version from robot.api import logger if os.sep == '/' and sys.platform.startswith('java'): encode_to_system = lambda string: string class Process(object): """Robot Framework test library for running processes. This library utilizes Python's [http://docs.python.org/2/library/subprocess.html|subprocess] module and its [http://docs.python.org/2/library/subprocess.html#subprocess.Popen|Popen] class. The library has following main usages: - Running processes in system and waiting for their completion using `Run Process` keyword. - Starting processes on background using `Start Process`. - Waiting started process to complete using `Wait For Process` or stopping them with `Terminate Process` or `Terminate All Processes`. This library is new in Robot Framework 2.8. == Table of contents == - `Specifying command and arguments` - `Process configuration` - `Active process` - `Result object` - `Boolean arguments` - `Using with OperatingSystem library` - `Example` - `Shortcuts` - `Keywords` = Specifying command and arguments = Both `Run Process` and `Start Process` accept the command to execute and all arguments passed to it as separate arguments. This is convenient to use and also allows these keywords to automatically escape possible spaces and other special characters in the command or arguments. When `running processes in shell`, it is also possible to give the whole command to execute as a single string. The command can then contain multiple commands, for example, connected with pipes. When using this approach the caller is responsible on escaping. Examples: | `Run Process` | ${progdir}${/}prog.py | first arg | second | | `Run Process` | script1.sh arg && script2.sh | shell=yes | cwd=${progdir} | = Process configuration = `Run Process` and `Start Process` keywords can be configured using optional `**configuration` keyword arguments. Configuration arguments must be given after other arguments passed to these keywords and must use syntax like `name=value`. Available configuration arguments are listed below and discussed further in sections afterwards. | = Name = | = Explanation = | | shell | Specifies whether to run the command in shell or not | | cwd | Specifies the working directory. | | env | Specifies environment variables given to the process. | | env:<name> | Overrides the named environment variable(s) only. | | stdout | Path of a file where to write standard output. | | stderr | Path of a file where to write standard error. | | alias | Alias given to the process. | == Running processes in shell == The `shell` argument specifies whether to run the process in a shell or not. By default shell is not used, which means that shell specific commands, like `copy` and `dir` on Windows, are not available. Giving the `shell` argument any non-false value, such as `shell=True`, changes the program to be executed in a shell. It allows using the shell capabilities, but can also make the process invocation operating system dependent. When using a shell it is possible to give the whole command to execute as a single string. See `Specifying command and arguments` section for examples and more details in general. == Current working directory == By default the child process will be executed in the same directory as the parent process, the process running tests, is executed. This can be changed by giving an alternative location using the `cwd` argument. Forward slashes in the given path are automatically converted to backslashes on Windows. `Standard output and error streams`, when redirected to files, are also relative to the current working directory possibly set using the `cwd` argument. Example: | `Run Process` | prog.exe | cwd=${ROOT}/directory | stdout=stdout.txt | == Environment variables == By default the child process will get a copy of the parent process's environment variables. The `env` argument can be used to give the child a custom environment as a Python dictionary. If there is a need to specify only certain environment variable, it is possible to use the `env:<name>=<value>` format to set or override only that named variables. It is also possible to use these two approaches together. Examples: | `Run Process` | program | env=${environ} | | `Run Process` | program | env:http_proxy=10.144.1.10:8080 | env:PATH=%{PATH}${:}${PROGDIR} | | `Run Process` | program | env=${environ} | env:EXTRA=value | == Standard output and error streams == By default processes are run so that their standard output and standard error streams are kept in the memory. This works fine normally, but if there is a lot of output, the output buffers may get full and the program can hang. To avoid output buffers getting full, it is possible to use `stdout` and `stderr` arguments to specify files on the file system where to redirect the outputs. This can also be useful if other processes or other keywords need to read or manipulate the outputs somehow. Given `stdout` and `stderr` paths are relative to the `current working directory`. Forward slashes in the given paths are automatically converted to backslashes on Windows. As a special feature, it is possible to redirect the standard error to the standard output by using `stderr=STDOUT`. Regardless are outputs redirected to files or not, they are accessible through the `result object` returned when the process ends. Examples: | ${result} = | `Run Process` | program | stdout=${TEMPDIR}/stdout.txt | stderr=${TEMPDIR}/stderr.txt | | `Log Many` | stdout: ${result.stdout} | stderr: ${result.stderr} | | ${result} = | `Run Process` | program | stderr=STDOUT | | `Log` | all output: ${result.stdout} | Note that the created output files are not automatically removed after the test run. The user is responsible to remove them if needed. == Alias == A custom name given to the process that can be used when selecting the `active process`. Examples: | `Start Process` | program | alias=example | | `Run Process` | python | -c | print 'hello' | alias=hello | = Active process = The test library keeps record which of the started processes is currently active. By default it is latest process started with `Start Process`, but `Switch Process` can be used to select a different one. Using `Run Process` does not affect the active process. The keywords that operate on started processes will use the active process by default, but it is possible to explicitly select a different process using the `handle` argument. The handle can be the identifier returned by `Start Process` or an `alias` explicitly given to `Start Process` or `Run Process`. = Result object = `Run Process`, `Wait For Process` and `Terminate Process` keywords return a result object that contains information about the process execution as its attributes. The same result object, or some of its attributes, can also be get using `Get Process Result` keyword. Attributes available in the object are documented in the table below. | = Attribute = | = Explanation = | | rc | Return code of the process as an integer. | | stdout | Contents of the standard output stream. | | stderr | Contents of the standard error stream. | | stdout_path | Path where stdout was redirected or `None` if not redirected. | | stderr_path | Path where stderr was redirected or `None` if not redirected. | Example: | ${result} = | `Run Process` | program | | `Should Be Equal As Integers` | ${result.rc} | 0 | | `Should Match` | ${result.stdout} | Some t?xt* | | `Should Be Empty` | ${result.stderr} | | | ${stdout} = | `Get File` | ${result.stdout_path} | | `Should Be Equal` | ${stdout} | ${result.stdout} | | `File Should Be Empty` | ${result.stderr_path} | | = Boolean arguments = Some keywords accept arguments that are handled as Boolean values. If such an argument is given as a string, it is considered false if it is either empty or case-insensitively equal to `false`. Other strings are considered true regardless what they contain, and other argument types are tested using same [http://docs.python.org/2/library/stdtypes.html#truth-value-testing|rules as in Python]. True examples: | `Terminate Process` | kill=True | # Strings are generally true. | | `Terminate Process` | kill=yes | # Same as above. | | `Terminate Process` | kill=${TRUE} | # Python `True` is true. | | `Terminate Process` | kill=${42} | # Numbers other than 0 are true. | False examples: | `Terminate Process` | kill=False | # String `False` is false. | | `Terminate Process` | kill=${EMPTY} | # Empty string is false. | | `Terminate Process` | kill=${FALSE} | # Python `False` is false. | | `Terminate Process` | kill=${0} | # Number 0 is false. | Note that prior to Robot Framework 2.8 all non-empty strings, including `false`, were considered true. = Using with OperatingSystem library = The OperatingSystem library also contains keywords for running processes. They are not as flexible as the keywords provided by this library, and thus not recommended to be used anymore. They may eventually even be deprecated. There is a name collision because both of these libraries have `Start Process` and `Switch Process` keywords. This is handled so that if both libraries are imported, the keywords in the Process library are used by default. If there is a need to use the OperatingSystem variants, it is possible to use `OperatingSystem.Start Process` syntax or use the `BuiltIn` keyword `Set Library Search Order` to change the priority. Other keywords in the OperatingSystem library can be used freely with keywords in the Process library. = Example = | ***** Settings ***** | Library Process | Suite Teardown `Terminate All Processes` kill=True | | ***** Test Cases ***** | Example | `Start Process` program arg1 arg2 alias=First | ${handle} = `Start Process` command.sh arg | command2.sh shell=True cwd=/path | ${result} = `Run Process` ${CURDIR}/script.py | `Should Not Contain` ${result.stdout} FAIL | `Terminate Process` ${handle} | ${result} = `Wait For Process` First | `Should Be Equal As Integers` ${result.rc} 0 """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() TERMINATE_TIMEOUT = 30 KILL_TIMEOUT = 10 def __init__(self): self._processes = ConnectionCache('No active process.') self._results = {} def run_process(self, command, *arguments, **configuration): """Runs a process and waits for it to complete. `command` and `*arguments` specify the command to execute and arguments passed to it. See `Specifying command and arguments` for more details. `**configuration` contains additional configuration related to starting processes and waiting for them to finish. See `Process configuration` for more details about configuration related to starting processes. Configuration related to waiting for processes consists of `timeout` and `on_timeout` arguments that have same semantics as with `Wait For Process` keyword. By default there is no timeout, and if timeout is defined the default action on timeout is `terminate`. Returns a `result object` containing information about the execution. Examples: | ${result} = | Run Process | python | -c | print 'Hello, world!' | | Should Be Equal | ${result.stdout} | Hello, world! | | ${result} = | Run Process | ${command} | stderr=STDOUT | timeout=10s | | ${result} = | Run Process | ${command} | timeout=1min | on_timeout=continue | This command does not change the `active process`. `timeout` and `on_timeout` arguments are new in Robot Framework 2.8.4. """ current = self._processes.current timeout = configuration.pop('timeout', None) on_timeout = configuration.pop('on_timeout', 'terminate') try: handle = self.start_process(command, *arguments, **configuration) return self.wait_for_process(handle, timeout, on_timeout) finally: self._processes.current = current def start_process(self, command, *arguments, **configuration): """Starts a new process on background. See `Specifying command and arguments` and `Process configuration` for more information about the arguments. Makes the started process new `active process`. Returns an identifier that can be used as a handle to active the started process if needed. """ config = ProcessConfig(**configuration) executable_command = self._cmd(command, arguments, config.shell) logger.info('Starting process:\n%s' % executable_command) logger.debug('Process configuration:\n%s' % config) process = subprocess.Popen(executable_command, stdout=config.stdout_stream, stderr=config.stderr_stream, stdin=subprocess.PIPE, shell=config.shell, cwd=config.cwd, env=config.env, universal_newlines=True) self._results[process] = ExecutionResult(process, config.stdout_stream, config.stderr_stream) return self._processes.register(process, alias=config.alias) def _cmd(self, command, args, use_shell): command = [encode_to_system(item) for item in [command] + list(args)] if not use_shell: return command if args: return subprocess.list2cmdline(command) return command[0] def is_process_running(self, handle=None): """Checks is the process running or not. If `handle` is not given, uses the current `active process`. Returns `True` if the process is still running and `False` otherwise. """ return self._processes[handle].poll() is None def process_should_be_running(self, handle=None, error_message='Process is not running.'): """Verifies that the process is running. If `handle` is not given, uses the current `active process`. Fails if the process has stopped. """ if not self.is_process_running(handle): raise AssertionError(error_message) def process_should_be_stopped(self, handle=None, error_message='Process is running.'): """Verifies that the process is not running. If `handle` is not given, uses the current `active process`. Fails if the process is still running. """ if self.is_process_running(handle): raise AssertionError(error_message) def wait_for_process(self, handle=None, timeout=None, on_timeout='continue'): """Waits for the process to complete or to reach the given timeout. The process to wait for must have been started earlier with `Start Process`. If `handle` is not given, uses the current `active process`. `timeout` defines the maximum time to wait for the process. It is interpreted according to Robot Framework User Guide Appendix `Time Format`, for example, '42', '42 s', or '1 minute 30 seconds'. `on_timeout` defines what to do if the timeout occurs. Possible values and corresponding actions are explained in the table below. Notice that reaching the timeout never fails the test. | = Value = | = Action = | | `continue` | The process is left running (default). | | `terminate` | The process is gracefully terminated. | | `kill` | The process is forcefully stopped. | See `Terminate Process` keyword for more details how processes are terminated and killed. If the process ends before the timeout or it is terminated or killed, this keyword returns a `result object` containing information about the execution. If the process is left running, Python `None` is returned instead. Examples: | # Process ends cleanly | | | | ${result} = | Wait For Process | example | | Process Should Be Stopped | example | | | Should Be Equal As Integers | ${result.rc} | 0 | | # Process does not end | | | | ${result} = | Wait For Process | timeout=42 secs | | Process Should Be Running | | | | Should Be Equal | ${result} | ${NONE} | | # Kill non-ending process | | | | ${result} = | Wait For Process | timeout=1min 30s | on_timeout=kill | | Process Should Be Stopped | | | | Should Be Equal As Integers | ${result.rc} | -9 | `timeout` and `on_timeout` are new in Robot Framework 2.8.2. """ process = self._processes[handle] logger.info('Waiting for process to complete.') if timeout: timeout = timestr_to_secs(timeout) if not self._process_is_stopped(process, timeout): logger.info('Process did not complete in %s.' % secs_to_timestr(timeout)) return self._manage_process_timeout(handle, on_timeout.lower()) return self._wait(process) def _manage_process_timeout(self, handle, on_timeout): if on_timeout == 'terminate': return self.terminate_process(handle) elif on_timeout == 'kill': return self.terminate_process(handle, kill=True) else: logger.info('Leaving process intact.') return None def _wait(self, process): result = self._results[process] result.rc = process.wait() or 0 result.close_custom_streams() logger.info('Process completed.') return result def terminate_process(self, handle=None, kill=False): """Stops the process gracefully or forcefully. If `handle` is not given, uses the current `active process`. Waits for the process to stop after terminating it. Returns a `result object` containing information about the execution similarly as `Wait For Process`. On Unix-like machines, by default, first tries to terminate the process gracefully, but forcefully kills it if it does not stop in 30 seconds. Kills the process immediately if the `kill` argument is given any value considered true. See `Boolean arguments` section for more details about true and false values. Termination is done using `TERM (15)` signal and killing using `KILL (9)`. Use `Send Signal To Process` instead if you just want to send either of these signals without waiting for the process to stop. On Windows the Win32 API function `TerminateProcess()` is used directly to stop the process. Using the `kill` argument has no special effect. | ${result} = | Terminate Process | | | Should Be Equal As Integers | ${result.rc} | -15 | | Terminate Process | myproc | kill=true | *NOTE:* Stopping processes requires the [http://docs.python.org/2/library/subprocess.html|subprocess] module to have working `terminate` and `kill` functions. They were added in Python 2.6 and are thus missing from earlier versions. Unfortunately at least beta releases of Jython 2.7 [http://bugs.jython.org/issue1898|do not seem to support them either]. Automatically killing the process if termination fails as well as returning the result object are new features in Robot Framework 2.8.2. """ process = self._processes[handle] if not hasattr(process, 'terminate'): raise RuntimeError('Terminating processes is not supported ' 'by this Python version.') terminator = self._kill if is_true(kill) else self._terminate try: terminator(process) except OSError: if not self._process_is_stopped(process, self.KILL_TIMEOUT): raise logger.debug('Ignored OSError because process was stopped.') return self._wait(process) def _kill(self, process): logger.info('Forcefully killing process.') process.kill() if not self._process_is_stopped(process, self.KILL_TIMEOUT): raise RuntimeError('Failed to kill process.') def _terminate(self, process): logger.info('Gracefully terminating process.') process.terminate() if not self._process_is_stopped(process, self.TERMINATE_TIMEOUT): logger.info('Graceful termination failed.') self._kill(process) def terminate_all_processes(self, kill=False): """Terminates all still running processes started by this library. This keyword can be used in suite teardown or elsewhere to make sure that all processes are stopped, By default tries to terminate processes gracefully, but can be configured to forcefully kill them immediately. See `Terminate Process` that this keyword uses internally for more details. """ for handle in range(1, len(self._processes) + 1): if self.is_process_running(handle): self.terminate_process(handle, kill=kill) self.__init__() def send_signal_to_process(self, signal, handle=None): """Sends the given `signal` to the specified process. If `handle` is not given, uses the current `active process`. Signal can be specified either as an integer, or anything that can be converted to an integer, or as a name. In the latter case it is possible to give the name both with or without a `SIG` prefix, but names are case-sensitive. For example, all the examples below send signal `INT (2)`: | Send Signal To Process | 2 | | # Send to active process | | Send Signal To Process | INT | | | | Send Signal To Process | SIGINT | myproc | # Send to named process | What signals are supported depends on the system. For a list of existing signals on your system, see the Unix man pages related to signal handling (typically `man signal` or `man 7 signal`). If you are stopping a process, it is often easier and safer to use `Terminate Process` instead. *NOTE:* Sending signals requires the [http://docs.python.org/2/library/subprocess.html|subprocess] module to have working `send_signal` function. It was added in Python 2.6 and are thus missing from earlier versions. How well it will work with forthcoming Jython 2.7 is unknown. New in Robot Framework 2.8.2. """ if os.sep == '\\': raise RuntimeError('This keyword does not work on Windows.') process = self._processes[handle] if not hasattr(process, 'send_signal'): raise RuntimeError('Sending signals is not supported ' 'by this Python version.') process.send_signal(self._get_signal_number(signal)) def _get_signal_number(self, int_or_name): try: return int(int_or_name) except ValueError: return self._convert_signal_name_to_number(int_or_name) def _convert_signal_name_to_number(self, name): try: return getattr(signal_module, name if name.startswith('SIG') else 'SIG' + name) except AttributeError: raise RuntimeError("Unsupported signal '%s'." % name) def get_process_id(self, handle=None): """Returns the process ID (pid) of the process. If `handle` is not given, uses the current `active process`. Returns the pid assigned by the operating system as an integer. Note that with Jython, at least with the 2.5 version, the returned pid seems to always be `None`. The pid is not the same as the identifier returned by `Start Process` that is used internally by this library. """ return self._processes[handle].pid def get_process_object(self, handle=None): """Return the underlying `subprocess.Popen` object. If `handle` is not given, uses the current `active process`. """ return self._processes[handle] def get_process_result(self, handle=None, rc=False, stdout=False, stderr=False, stdout_path=False, stderr_path=False): """Returns the specified `result object` or some of its attributes. The given `handle` specifies the process whose results should be returned. If no `handle` is given, results of the current `active process` are returned. In either case, the process must have been finishes before this keyword can be used. In practice this means that processes started with `Start Process` must be finished either with `Wait For Process` or `Terminate Process` before using this keyword. If no other arguments than the optional `handle` are given, a whole `result object` is returned. If one or more of the other arguments are given any true value, only the specified attributes of the `result object` are returned. These attributes are always returned in the same order as arguments are specified in the keyword signature. See `Boolean arguments` section for more details about true and false values. Examples: | Run Process | python | -c | print 'Hello, world!' | alias=myproc | | # Get result object | | | | ${result} = | Get Process Result | myproc | | Should Be Equal | ${result.rc} | ${0} | | Should Be Equal | ${result.stdout} | Hello, world! | | Should Be Empty | ${result.stderr} | | | # Get one attribute | | | | ${stdout} = | Get Process Result | myproc | stdout=true | | Should Be Equal | ${stdout} | Hello, world! | | # Multiple attributes | | | | ${stdout} | ${stderr} = | Get Process Result | myproc | stdout=yes | stderr=yes | | Should Be Equal | ${stdout} | Hello, world! | | Should Be Empty | ${stderr} | | Although getting results of a previously executed process can be handy in general, the main use case for this keyword is returning results over the remote library interface. The remote interface does not support returning the whole result object, but individual attributes can be returned without problems. New in Robot Framework 2.8.2. """ result = self._results[self._processes[handle]] if result.rc is None: raise RuntimeError('Getting results of unfinished processes ' 'is not supported.') attributes = self._get_result_attributes(result, rc, stdout, stderr, stdout_path, stderr_path) if not attributes: return result elif len(attributes) == 1: return attributes[0] return attributes def _get_result_attributes(self, result, *includes): attributes = (result.rc, result.stdout, result.stderr, result.stdout_path, result.stderr_path) includes = (is_true(incl) for incl in includes) return tuple(attr for attr, incl in zip(attributes, includes) if incl) def switch_process(self, handle): """Makes the specified process the current `active process`. The handle can be an identifier returned by `Start Process` or the `alias` given to it explicitly. Example: | Start Process | prog1 | alias=process1 | | Start Process | prog2 | alias=process2 | | # currently active process is process2 | | Switch Process | process1 | | # now active process is process1 | """ self._processes.switch(handle) def _process_is_stopped(self, process, timeout): max_time = time.time() + timeout while time.time() <= max_time: if process.poll() is not None: return True time.sleep(0.1) return False class ExecutionResult(object): def __init__(self, process, stdout, stderr, rc=None): self._process = process self.stdout_path = self._get_path(stdout) self.stderr_path = self._get_path(stderr) self.rc = rc self._stdout = None self._stderr = None self._custom_streams = [stream for stream in (stdout, stderr) if self._is_custom_stream(stream)] def _get_path(self, stream): return stream.name if self._is_custom_stream(stream) else None def _is_custom_stream(self, stream): return stream not in (subprocess.PIPE, subprocess.STDOUT) @property def stdout(self): if self._stdout is None: self._stdout = self._read_stream(self.stdout_path, self._process.stdout) return self._stdout @property def stderr(self): if self._stderr is None: self._stderr = self._read_stream(self.stderr_path, self._process.stderr) return self._stderr def close_custom_streams(self): for stream in self._custom_streams: if not stream.closed: stream.flush() stream.close() def _read_stream(self, stream_path, stream): if stream_path: stream = open(stream_path, 'r') try: return self._format_output(stream.read() if stream else '') finally: if stream_path: stream.close() def _format_output(self, output): if output.endswith('\n'): output = output[:-1] return decode_output(output, force=True) def __str__(self): return '<result object with rc %d>' % self.rc class ProcessConfig(object): def __init__(self, cwd=None, shell=False, stdout=None, stderr=None, alias=None, env=None, **rest): self.cwd = self._get_cwd(cwd) self.stdout_stream = self._new_stream(stdout) self.stderr_stream = self._get_stderr(stderr, stdout, self.stdout_stream) self.shell = is_true(shell) self.alias = alias self.env = self._construct_env(env, rest) def _get_cwd(self, cwd): if cwd: return cwd.replace('/', os.sep) return abspath('.') def _new_stream(self, name): if name: name = name.replace('/', os.sep) return open(os.path.join(self.cwd, name), 'w') return subprocess.PIPE def _get_stderr(self, stderr, stdout, stdout_stream): if stderr and stderr in ['STDOUT', stdout]: if stdout_stream != subprocess.PIPE: return stdout_stream return subprocess.STDOUT return self._new_stream(stderr) def _construct_env(self, env, extra): if env: env = dict((encode_to_system(k), encode_to_system(v)) for k, v in env.items()) for key in extra: if not key.startswith('env:'): raise RuntimeError("'%s' is not supported by this keyword." % key) if env is None: env = os.environ.copy() env[encode_to_system(key[4:])] = encode_to_system(extra[key]) return env def __str__(self): return encode_to_system("""\ cwd = %s stdout_stream = %s stderr_stream = %s shell = %r alias = %s env = %r""" % (self.cwd, self.stdout_stream, self.stderr_stream, self.shell, self.alias, self.env)) def is_true(argument): if isinstance(argument, basestring) and argument.upper() == 'FALSE': return False return bool(argument)
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. def none_shall_pass(who): if who is not None: raise AssertionError('None shall pass!') print '*HTML* <object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/dhRUe-gz690&hl=en_US&fs=1&rel=0&color1=0x234900&color2=0x4e9e00"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/dhRUe-gz690&hl=en_US&fs=1&rel=0&color1=0x234900&color2=0x4e9e00" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>'
Python
# Copyright 2008-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 _AbstractWinformsDialog: def __init__(self): raise RuntimeError('This keyword is not yet implemented with IronPython') class MessageDialog(_AbstractWinformsDialog): def __init__(self, message): _AbstractWinformsDialog.__init__(self) class InputDialog(_AbstractWinformsDialog): def __init__(self, message, default, hidden=False): _AbstractWinformsDialog.__init__(self) class SelectionDialog(_AbstractWinformsDialog): def __init__(self, message, options): _AbstractWinformsDialog.__init__(self) class PassFailDialog(_AbstractWinformsDialog): def __init__(self, message): _AbstractWinformsDialog.__init__(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 sys import os if sys.platform.startswith('java'): from java.awt import Toolkit, Robot, Rectangle from javax.imageio import ImageIO from java.io import File elif sys.platform == 'cli': import clr clr.AddReference('System.Windows.Forms') clr.AddReference('System.Drawing') from System.Drawing import Bitmap, Graphics, Imaging from System.Windows.Forms import Screen else: try: import wx except ImportError: wx = None try: from gtk import gdk except ImportError: gdk = None try: from PIL import ImageGrab # apparently available only on Windows except ImportError: ImageGrab = None from robot import utils from robot.api import logger from robot.libraries.BuiltIn import BuiltIn from robot.version import get_version class Screenshot(object): """Test library for taking screenshots on the machine where tests are run. Notice that successfully taking screenshots requires tests to be run with a physical or virtual display. = Using with Python = With Python you need to have one of the following modules installed to be able to use this library. The first module that is found will be used. - wxPython :: http://wxpython.org :: Required also by RIDE so many Robot Framework users already have this module installed. - PyGTK :: http://pygtk.org :: This module is available by default on most Linux distributions. - Python Imaging Library (PIL) :: http://www.pythonware.com/products/pil :: This module can take screenshots only on Windows. Python support was added in Robot Framework 2.5.5. = Using with Jython and IronPython = With Jython and IronPython this library uses APIs provided by JVM and .NET platforms, respectively. These APIs are always available and thus no external modules are needed. IronPython support was added in Robot Framework 2.7.5. = Where screenshots are saved = By default screenshots are saved into the same directory where the Robot Framework log file is written. If no log is created, screenshots are saved into the directory where the XML output file is written. It is possible to specify a custom location for screenshots using `screenshot_directory` argument in `importing` and `Set Screenshot Directory` keyword during execution. It is also possible to save screenshots using an absolute path. Note that prior to Robot Framework 2.5.5 the default screenshot location was system's temporary directory. = Changes in Robot Framework 2.5.5 and Robot Framework 2.6 = This library was heavily enhanced in Robot Framework 2.5.5 release. The changes are listed below and explained more thoroughly in affected places. - The support for using this library on Python (see above) was added. - The default location where screenshots are saved was changed (see above). - New `Take Screenshot` and `Take Screenshot Without Embedding` keywords were added. These keywords should be used for taking screenshots in the future. Other screenshot taking keywords will be deprecated and removed later. - `log_file_directory` argument was deprecated everywhere it was used. In Robot Framework 2.6, following additional changes were made: - `log_file_directory` argument was removed altogether. - `Set Screenshot Directories` keyword was removed. - `Save Screenshot`, `Save Screenshot To` and `Log Screenshot` keywords were deprecated. They will be removed in Robot Framework 2.8. """ ROBOT_LIBRARY_SCOPE = 'TEST SUITE' ROBOT_LIBRARY_VERSION = get_version() def __init__(self, screenshot_directory=None): """Configure where screenshots are saved. If `screenshot_directory` is not given, screenshots are saved into same directory as the log file. The directory can also be set using `Set Screenshot Directory` keyword. Examples (use only one of these): | =Setting= | =Value= | =Value= | =Value= | | Library | Screenshot | | # Default location | | Library | Screenshot | ${TEMPDIR} | # System temp (this was default prior to 2.5.5) | """ self._given_screenshot_dir = self._norm_path(screenshot_directory) self._screenshot_taker = ScreenshotTaker() def _norm_path(self, path): if not path: return path return os.path.normpath(path.replace('/', os.sep)) @property def _screenshot_dir(self): return self._given_screenshot_dir or self._log_dir @property def _log_dir(self): variables = BuiltIn().get_variables() outdir = variables['${OUTPUTDIR}'] log = variables['${LOGFILE}'] log = os.path.dirname(log) if log != 'NONE' else '.' return self._norm_path(os.path.join(outdir, log)) def set_screenshot_directory(self, path): """Sets the directory where screenshots are saved. It is possible to use `/` as a path separator in all operating systems. Path to the old directory is returned. The directory can also be set in `importing`. """ path = self._norm_path(path) if not os.path.isdir(path): raise RuntimeError("Directory '%s' does not exist." % path) old = self._screenshot_dir self._given_screenshot_dir = path return old def take_screenshot(self, name="screenshot", width="800px"): """Takes a screenshot in JPEG format and embeds it into the log file. Name of the file where the screenshot is stored is derived from the given `name`. If the `name` ends with extension `.jpg` or `.jpeg`, the screenshot will be stored with that exact name. Otherwise a unique name is created by adding an underscore, a running index and an extension to the `name`. The name will be interpreted to be relative to the directory where the log file is written. It is also possible to use absolute paths. Using `/` as a path separator works in all operating systems. `width` specifies the size of the screenshot in the log file. Examples: (LOGDIR is determined automatically by the library) | Take Screenshot | | | # LOGDIR/screenshot_1.jpg (index automatically incremented) | | Take Screenshot | mypic | | # LOGDIR/mypic_1.jpg (index automatically incremented) | | Take Screenshot | ${TEMPDIR}/mypic | | # /tmp/mypic_1.jpg (index automatically incremented) | | Take Screenshot | pic.jpg | | # LOGDIR/pic.jpg (always uses this file) | | Take Screenshot | images/login.jpg | 80% | # Specify both name and width. | | Take Screenshot | width=550px | | # Specify only width. | The path where the screenshot is saved is returned. """ path = self._save_screenshot(name) self._embed_screenshot(path, width) return path def take_screenshot_without_embedding(self, name="screenshot"): """Takes a screenshot and links it from the log file. This keyword is otherwise identical to `Take Screenshot` but the saved screenshot is not embedded into the log file. The screenshot is linked so it is nevertheless easily available. """ path = self._save_screenshot(name) self._link_screenshot(path) return path def _save_screenshot(self, basename, directory=None): path = self._get_screenshot_path(basename, directory) return self._screenshot_to_file(path) def _screenshot_to_file(self, path): path = self._validate_screenshot_path(path) logger.debug('Using %s modules for taking screenshot.' % self._screenshot_taker.module) try: self._screenshot_taker(path) except: logger.warn('Taking screenshot failed: %s\n' 'Make sure tests are run with a physical or virtual display.' % utils.get_error_message()) return path def _validate_screenshot_path(self, path): path = utils.abspath(self._norm_path(path)) if not os.path.exists(os.path.dirname(path)): raise RuntimeError("Directory '%s' where to save the screenshot " "does not exist" % os.path.dirname(path)) return path def _get_screenshot_path(self, basename, directory): directory = self._norm_path(directory) if directory else self._screenshot_dir if basename.lower().endswith(('.jpg', '.jpeg')): return os.path.join(directory, basename) index = 0 while True: index += 1 path = os.path.join(directory, "%s_%d.jpg" % (basename, index)) if not os.path.exists(path): return path def _embed_screenshot(self, path, width): link = utils.get_link_path(path, self._log_dir) logger.info('<a href="%s"><img src="%s" width="%s"></a>' % (link, link, width), html=True) def _link_screenshot(self, path): link = utils.get_link_path(path, self._log_dir) logger.info("Screenshot saved to '<a href=\"%s\">%s</a>'." % (link, path), html=True) class ScreenshotTaker(object): def __init__(self, module_name=None): self._screenshot = self._get_screenshot_taker(module_name) self.module = self._screenshot.__name__.split('_')[1] self._wx_app_reference = None def __call__(self, path): self._screenshot(path) def __nonzero__(self): return self.module != 'no' def test(self, path=None): print "Using '%s' module." % self.module if not self: return False if not path: print "Not taking test screenshot." return True print "Taking test screenshot to '%s'." % path try: self(path) except: print "Failed: %s" % utils.get_error_message() return False else: print "Success!" return True def _get_screenshot_taker(self, module_name): if sys.platform.startswith('java'): return self._java_screenshot if sys.platform == 'cli': return self._cli_screenshot if module_name: method_name = '_%s_screenshot' % module_name.lower() if hasattr(self, method_name): return getattr(self, method_name) return self._get_default_screenshot_taker() def _get_default_screenshot_taker(self): for module, screenshot_taker in [(wx, self._wx_screenshot), (gdk, self._gtk_screenshot), (ImageGrab, self._pil_screenshot), (True, self._no_screenshot)]: if module: return screenshot_taker def _java_screenshot(self, path): size = Toolkit.getDefaultToolkit().getScreenSize() rectangle = Rectangle(0, 0, size.width, size.height) image = Robot().createScreenCapture(rectangle) ImageIO.write(image, 'jpg', File(path)) def _cli_screenshot(self, path): bmp = Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height) graphics = Graphics.FromImage(bmp) try: graphics.CopyFromScreen(0, 0, 0, 0, bmp.Size) finally: graphics.Dispose() bmp.Save(path, Imaging.ImageFormat.Jpeg) def _wx_screenshot(self, path): if not self._wx_app_reference: self._wx_app_reference = wx.PySimpleApp() context = wx.ScreenDC() width, height = context.GetSize() bitmap = wx.EmptyBitmap(width, height, -1) memory = wx.MemoryDC() memory.SelectObject(bitmap) memory.Blit(0, 0, width, height, context, -1, -1) memory.SelectObject(wx.NullBitmap) bitmap.SaveFile(path, wx.BITMAP_TYPE_JPEG) def _gtk_screenshot(self, path): window = gdk.get_default_root_window() if not window: raise RuntimeError('Taking screenshot failed') width, height = window.get_size() pb = gdk.Pixbuf(gdk.COLORSPACE_RGB, False, 8, width, height) pb = pb.get_from_drawable(window, window.get_colormap(), 0, 0, 0, 0, width, height) if not pb: raise RuntimeError('Taking screenshot failed') pb.save(path, 'jpeg') def _pil_screenshot(self, path): ImageGrab.grab().save(path, 'JPEG') def _no_screenshot(self, path): raise RuntimeError('Taking screenshots is not supported on this platform ' 'by default. See library documentation for details.') if __name__ == "__main__": if len(sys.argv) not in [2, 3]: sys.exit("Usage: %s <path> [wx|gtk|pil] OR test [<path>]" % os.path.basename(sys.argv[0])) if sys.argv[1] == 'test': sys.exit(0 if ScreenshotTaker().test(*sys.argv[2:]) else 1) path = utils.abspath(sys.argv[1]) module = sys.argv[2] if len(sys.argv) == 3 else None shooter = ScreenshotTaker(module) print 'Using %s modules' % shooter.module shooter(path) print path
Python
# Copyright 2008-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. """A test library providing dialogs for interacting with users. `Dialogs` is Robot Framework's standard library that provides means for pausing the test execution and getting input from users. The dialogs are slightly different depending on are tests run on Python or Jython but they provide the same functionality. Long lines in the provided messages are wrapped automatically since Robot Framework 2.8. If you want to wrap lines manually, you can add newlines using the `\\n` character sequence. The library has following two limitations: - It is not compatible with IronPython. - It cannot be used with timeouts on Python. """ import sys if sys.platform.startswith('java'): from dialogs_jy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog elif sys.platform == 'cli': from dialogs_ipy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog else: from dialogs_py import MessageDialog, PassFailDialog, InputDialog, SelectionDialog try: from robot.version import get_version except ImportError: __version__ = '<unknown>' else: __version__ = get_version() __all__ = ['execute_manual_step', 'get_value_from_user', 'get_selection_from_user', 'pause_execution'] def pause_execution(message='Test execution paused. Press OK to continue.'): """Pauses test execution until user clicks `Ok` button. `message` is the message shown in the dialog. """ MessageDialog(message).show() def execute_manual_step(message, default_error=''): """Pauses test execution until user sets the keyword status. User can press either `PASS` or `FAIL` button. In the latter case execution fails and an additional dialog is opened for defining the error message. `message` is the instruction shown in the initial dialog and `default_error` is the default value shown in the possible error message dialog. """ if not PassFailDialog(message).show(): msg = get_value_from_user('Give error message:', default_error) raise AssertionError(msg) def get_value_from_user(message, default_value='', hidden=False): """Pauses test execution and asks user to input a value. Value typed by the user, or the possible default value, is returned. Returning an empty value is fine, but pressing `Cancel` fails the keyword. `message` is the instruction shown in the dialog and `default_value` is the possible default value shown in the input field. If `hidden` is given any true value, such as any non-empty string, the value typed by the user is hidden. This is a new feature in Robot Framework 2.8.4. Example: | ${username} = | Get Value From User | Input user name | default | | ${password} = | Get Value From User | Input password | hidden=yes | """ return _validate_user_input(InputDialog(message, default_value, hidden)) def get_selection_from_user(message, *values): """Pauses test execution and asks user to select a value. The selected value is returned. Pressing `Cancel` fails the keyword. `message` is the instruction shown in the dialog and `values` are the options given to the user. Example: | ${username} = | Get Selection From User | Select user name | user1 | user2 | admin | """ return _validate_user_input(SelectionDialog(message, values)) def _validate_user_input(dialog): value = dialog.show() if value is None: raise RuntimeError('No value provided by user.') return 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 contextlib import contextmanager import telnetlib import time import re import inspect import struct try: import pyte except ImportError: pyte = None from robot.api import logger from robot.version import get_version from robot import utils class Telnet: """A test library providing communication over Telnet connections. `Telnet` is Robot Framework's standard library that makes it possible to connect to Telnet servers and execute commands on the opened connections. == Table of contents == - `Connections` - `Writing and reading` - `Configuration` - `Terminal emulation` - `Logging` - `Time string format` - `Importing` - `Shortcuts` - `Keywords` = Connections = The first step of using `Telnet` is opening a connection with `Open Connection` keyword. Typically the next step is logging in with `Login` keyword, and in the end the opened connection can be closed with `Close Connection`. It is possible to open multiple connections and switch the active one using `Switch Connection`. `Close All Connections` can be used to close all the connections, which is especially useful in suite teardowns to guarantee that all connections are always closed. = Writing and reading = After opening a connection and possibly logging in, commands can be executed or text written to the connection for other reasons using `Write` and `Write Bare` keywords. The main difference between these two is that the former adds a [#Configuration|configurable newline] after the text automatically. After writing something to the connection, the resulting output can be read using `Read`, `Read Until`, `Read Until Regexp`, and `Read Until Prompt` keywords. Which one to use depends on the context, but the latest one is often the most convenient. As a convenience when running a command, it is possible to use `Execute Command` that simply uses `Write` and `Read Until Prompt` internally. `Write Until Expected Output` is useful if you need to wait until writing something produces a desired output. Written and read text is automatically encoded/decoded using a [#Configuration|configured encoding]. The ANSI escape codes, like cursor movement and color codes, are normally returned as part of the read operation. If an escape code occurs in middle of a search pattern it may also prevent finding the searched string. `Terminal emulation` can be used to process these escape codes as they would be if a real terminal would be in use. = Configuration = Many aspects related the connections can be easily configured either globally or per connection basis. Global configuration is done when [#Importing|library is imported], and these values can be overridden per connection by `Open Connection` or with setting specific keywords `Set Timeout`, `Set Newline`, `Set Prompt`, `Set Encoding`, and `Set Default Log Level` Values of `environ_user`, `window_size`, `terminal_emulation`, and `terminal_type` can not be changed after opening the connection. == Timeout == Timeout defines how long is the maximum time to wait when reading output. It is used internally by `Read Until`, `Read Until Regexp`, `Read Until Prompt`, and `Login` keywords. The default value is 3 seconds. == Newline == Newline defines which line separator `Write` keyword should use. The default value is `CRLF` that is typically used by Telnet connections. Newline can be given either in escaped format using '\\n' and '\\r' or with special 'LF' and 'CR' syntax. Examples: | `Set Newline` | \\n | | `Set Newline` | CRLF | == Prompt == Often the easiest way to read the output of a command is reading all the output until the next prompt with `Read Until Prompt`. It also makes it easier, and faster, to verify did `Login` succeed. Prompt can be specified either as a normal string or a regular expression. The latter is especially useful if the prompt changes as a result of the executed commands. == Encoding == To ease handling text containing non-ASCII characters, all written text is encoded and read text decoded by default. The default encoding is UTF-8 that works also with ASCII. Encoding can be disabled by using a special encoding value `NONE`. This is mainly useful if you need to get the bytes received from the connection as-is. Notice that when writing to the connection, only Unicode strings are encoded using the defined encoding. Byte strings are expected to be already encoded correctly. Notice also that normal text in test data is passed to the library as Unicode and you need to use variables to use bytes. It is also possible to configure the error handler to use if encoding or decoding characters fails. Accepted values are the same that encode/decode functions in Python strings accept. In practice the following values are the most useful: - `ignore`: ignore characters that cannot be encoded (default) - `strict`: fail if characters cannot be encoded - `replace`: replace characters that cannot be encoded with a replacement character Examples: | `Open Connection` | lolcathost | encoding=Latin1 | encoding_errors=strict | | `Set Encoding` | ISO-8859-15 | | `Set Encoding` | errors=ignore | Using UTF-8 encoding by default and being able to configure the encoding are new features in Robot Framework 2.7.6. In earlier versions only ASCII was supported and encoding errors were silently ignored. Robot Framework 2.7.7 added a possibility to specify the error handler, changed the default behavior back to ignoring encoding errors, and added the possibility to disable encoding. == Default log level == Default log level specifies the log level keywords use for `logging` unless they are given an explicit log level. The default value is `INFO`, and changing it, for example, to `DEBUG` can be a good idea if there is lot of unnecessary output that makes log files big. Configuring default log level in `importing` and with `Open Connection` are new features in Robot Framework 2.7.6. In earlier versions only `Set Default Log Level` could be used. == Terminal type == By default the Telnet library does not negotiate any specific terminal type with the server. If a specific terminal type, for example `vt100`, is desired, the terminal type can be configured in `importing` and with `Open Connection`. New in Robot Framework 2.8.2. == Window size == Window size for negotiation with the server can be configured when `importing` the library and with `Open Connection`. New in Robot Framework 2.8.2. == USER environment variable == Telnet protocol allows the `USER` environment variable to be sent when connecting to the server. On some servers it may happen that there is no login prompt, and on those cases this configuration option will allow still to define the desired username. The option `environ_user` can be used in `importing` and with `Open Connection`. New in Robot Framework 2.8.2. = Terminal emulation = Starting from Robot Framework 2.8.2, Telnet library supports terminal emulation with [https://github.com/selectel/pyte|Pyte]. Terminal emulation will process the output in a virtual screen. This means that ANSI escape codes, like cursor movements, and also control characters, like carriage returns and backspaces, have the same effect on the result as they would have on a normal terminal screen. For example the sequence 'acdc\\x1b[3Dbba' will result in output 'abba'. Terminal emulation is taken into use with option terminal_emulation=True, either in the library initialization, or as a option to `Open Connection`. As Pyte approximates vt-style terminal, you may also want to set the terminal type as `vt100`. We also recommend that you increase the window size, as the terminal emulation will break all lines that are longer than the window row length. When terminal emulation is used, the `newline` and `encoding` can not be changed anymore after opening the connection. As a prequisite for using terminal emulation you need to have [https://github.com/selectel/pyte|Pyte] installed. This is easiest done with [http://pip-installer.org|pip] by running `pip install pyte`. Examples: | `Open Connection` | lolcathost | terminal_emulation=True | terminal_type=vt100 | window_size=400x100 | = Logging = All keywords that read something log the output. These keywords take the log level to use as an optional argument, and if no log level is specified they use the [#Configuration|configured] default value. The valid log levels to use are `TRACE`, `DEBUG`, `INFO` (default), and `WARN`. Levels below `INFO` are not shown in log files by default whereas warnings are shown more prominently. The [http://docs.python.org/2/library/telnetlib.html|telnetlib module] used by this library has a custom logging system for logging content it sends and receives. Starting from Robot Framework 2.7.7, these low level log messages are forwarded to Robot's log file using `TRACE` level. = Time string format = Timeouts and other times used must be given as a time string using format in format like '15 seconds' or '1min 10s'. If the timeout is given as just a number, for example, '10' or '1.5', it is considered to be seconds. The time string format is described in more detail in an appendix of [http://code.google.com/p/robotframework/wiki/UserGuide|Robot Framework User Guide]. """ ROBOT_LIBRARY_SCOPE = 'TEST_SUITE' ROBOT_LIBRARY_VERSION = get_version() def __init__(self, timeout='3 seconds', newline='CRLF', prompt=None, prompt_is_regexp=False, encoding='UTF-8', encoding_errors='ignore', default_log_level='INFO', window_size=None, environ_user=None, terminal_emulation=False, terminal_type=None): """Telnet library can be imported with optional configuration parameters. Configuration parameters are used as default values when new connections are opened with `Open Connection` keyword. They can also be overridden after opening the connection using the `Set Timeout`, `Set Newline`, `Set Prompt`, `Set Encoding`, and `Set Default Log Level` keywords. See these keywords as well as `Configuration` and `Terminal emulation` sections above for more information about these parameters and their possible values. Examples (use only one of these): | *Setting* | *Value* | *Value* | *Value* | *Value* | *Value* | *Comment* | | Library | Telnet | | | | | # default values | | Library | Telnet | 0.5 | | | | # set only timeout | | Library | Telnet | | LF | | | # set only newline | | Library | Telnet | newline=LF | encoding=ISO-8859-1 | | | # set newline and encoding using named arguments | | Library | Telnet | 2.0 | LF | | | # set timeout and newline | | Library | Telnet | 2.0 | CRLF | $ | | # set also prompt | | Library | Telnet | 2.0 | LF | (> |# ) | True | # set prompt as a regular expression | | Library | Telnet | terminal_emulation=True | terminal_type=vt100 | window_size=400x100 | | # use terminal emulation with defined window size and terminal type | """ self._timeout = timeout or 3.0 self._newline = newline or 'CRLF' self._prompt = (prompt, bool(prompt_is_regexp)) self._encoding = encoding self._encoding_errors = encoding_errors self._default_log_level = default_log_level self._window_size = self._parse_window_size(window_size) self._environ_user = environ_user self._terminal_emulation = self._parse_terminal_emulation(terminal_emulation) self._terminal_type = terminal_type self._cache = utils.ConnectionCache() self._conn = None self._conn_kws = self._lib_kws = None def get_keyword_names(self): return self._get_library_keywords() + self._get_connection_keywords() def _get_library_keywords(self): if self._lib_kws is None: self._lib_kws = self._get_keywords(self, ['get_keyword_names']) return self._lib_kws def _get_keywords(self, source, excluded): return [name for name in dir(source) if self._is_keyword(name, source, excluded)] def _is_keyword(self, name, source, excluded): return (name not in excluded and not name.startswith('_') and name != 'get_keyword_names' and inspect.ismethod(getattr(source, name))) def _get_connection_keywords(self): if self._conn_kws is None: conn = self._get_connection() excluded = [name for name in dir(telnetlib.Telnet()) if name not in ['write', 'read', 'read_until']] self._conn_kws = self._get_keywords(conn, excluded) return self._conn_kws def __getattr__(self, name): if name not in self._get_connection_keywords(): raise AttributeError(name) # If no connection is initialized, get attributes from a non-active # connection. This makes it possible for Robot to create keyword # handlers when it imports the library. return getattr(self._conn or self._get_connection(), name) def open_connection(self, host, alias=None, port=23, timeout=None, newline=None, prompt=None, prompt_is_regexp=False, encoding=None, encoding_errors=None, default_log_level=None, window_size=None, environ_user=None, terminal_emulation=False, terminal_type=None): """Opens a new Telnet connection to the given host and port. The `timeout`, `newline`, `prompt`, `prompt_is_regexp`, `encoding`, `default_log_level`, `window_size`, `environ_user`, `terminal_emulation`, and `terminal_type` arguments get default values when the library is [#Importing|imported]. Setting them here overrides those values for the opened connection. See `Configuration` and `Terminal emulation` sections for more information. Possible already opened connections are cached and it is possible to switch back to them using `Switch Connection` keyword. It is possible to switch either using explicitly given `alias` or using index returned by this keyword. Indexing starts from 1 and is reset back to it by `Close All Connections` keyword. """ timeout = timeout or self._timeout newline = newline or self._newline encoding = encoding or self._encoding encoding_errors = encoding_errors or self._encoding_errors default_log_level = default_log_level or self._default_log_level window_size = self._parse_window_size(window_size) or self._window_size environ_user = environ_user or self._environ_user terminal_emulation = self._get_terminal_emulation_with_default(terminal_emulation) terminal_type = terminal_type or self._terminal_type if not prompt: prompt, prompt_is_regexp = self._prompt logger.info('Opening connection to %s:%s with prompt: %s' % (host, port, prompt)) self._conn = self._get_connection(host, port, timeout, newline, prompt, prompt_is_regexp, encoding, encoding_errors, default_log_level, window_size, environ_user, terminal_emulation, terminal_type) return self._cache.register(self._conn, alias) def _get_terminal_emulation_with_default(self, terminal_emulation): if terminal_emulation is None or terminal_emulation == '': return self._terminal_emulation return self._parse_terminal_emulation(terminal_emulation) def _parse_terminal_emulation(self, terminal_emulation): if not terminal_emulation: return False if isinstance(terminal_emulation, basestring): return terminal_emulation.lower() == 'true' return bool(terminal_emulation) def _parse_window_size(self, window_size): if not window_size: return None try: cols, rows = window_size.split('x') cols, rows = (int(cols), int(rows)) except: raise AssertionError("Invalid window size '%s'. Should be <rows>x<columns>" % window_size) return cols, rows def _get_connection(self, *args): """Can be overridden to use a custom connection.""" return TelnetConnection(*args) def switch_connection(self, index_or_alias): """Switches between active connections using an index or an alias. Aliases can be given to `Open Connection` keyword which also always returns the connection index. This keyword returns the index of previous active connection. Example: | `Open Connection` | myhost.net | | | | `Login` | john | secret | | | `Write` | some command | | | | `Open Connection` | yourhost.com | 2nd conn | | | `Login` | root | password | | | `Write` | another cmd | | | | ${old index}= | `Switch Connection` | 1 | # index | | `Write` | something | | | | `Switch Connection` | 2nd conn | | # alias | | `Write` | whatever | | | | `Switch Connection` | ${old index} | | # back to original | | [Teardown] | `Close All Connections` | | | The example above expects that there were no other open connections when opening the first one, because it used index '1' when switching to the connection later. If you are not sure about that, you can store the index into a variable as shown below. | ${index} = | `Open Connection` | myhost.net | | `Do Something` | | | | `Switch Connection` | ${index} | | """ old_index = self._cache.current_index self._conn = self._cache.switch(index_or_alias) return old_index def close_all_connections(self): """Closes all open connections and empties the connection cache. If multiple connections are opened, this keyword should be used in a test or suite teardown to make sure that all connections are closed. It is not an error is some of the connections have already been closed by `Close Connection`. After this keyword, new indexes returned by `Open Connection` keyword are reset to 1. """ self._conn = self._cache.close_all() class TelnetConnection(telnetlib.Telnet): NEW_ENVIRON_IS = chr(0) NEW_ENVIRON_VAR = chr(0) NEW_ENVIRON_VALUE = chr(1) INTERNAL_UPDATE_FREQUENCY = 0.03 def __init__(self, host=None, port=23, timeout=3.0, newline='CRLF', prompt=None, prompt_is_regexp=False, encoding='UTF-8', encoding_errors='ignore', default_log_level='INFO', window_size=None, environ_user=None, terminal_emulation=False, terminal_type=None): telnetlib.Telnet.__init__(self, host, int(port) if port else 23) self._set_timeout(timeout) self._set_newline(newline) self._set_prompt(prompt, prompt_is_regexp) self._set_encoding(encoding, encoding_errors) self._set_default_log_level(default_log_level) self._window_size = window_size self._environ_user = environ_user self._terminal_emulator = self._check_terminal_emulation(terminal_emulation) self._terminal_type = str(terminal_type) if terminal_type else None self.set_option_negotiation_callback(self._negotiate_options) def set_timeout(self, timeout): """Sets the timeout used for waiting output in the current connection. Read operations that expect some output to appear (`Read Until`, `Read Until Regexp`, `Read Until Prompt`, `Login`) use this timeout and fail if the expected output does not appear before this timeout expires. The `timeout` must be given in `time string format`. The old timeout is returned and can be used to restore the timeout later. Example: | ${old} = | `Set Timeout` | 2 minute 30 seconds | | `Do Something` | | `Set Timeout` | ${old} | See `Configuration` section for more information about global and connection specific configuration. """ self._verify_connection() old = self._timeout self._set_timeout(timeout) return utils.secs_to_timestr(old) def _set_timeout(self, timeout): self._timeout = utils.timestr_to_secs(timeout) def set_newline(self, newline): """Sets the newline used by `Write` keyword in the current connection. The old newline is returned and can be used to restore the newline later. See `Set Timeout` for a similar example. If terminal emulation is used, the newline can not be changed on an open connection. See `Configuration` section for more information about global and connection specific configuration. """ self._verify_connection() if self._terminal_emulator: raise AssertionError("Newline can not be changed when terminal emulation is used.") old = self._newline self._set_newline(newline) return old def _set_newline(self, newline): self._newline = str(newline).upper().replace('LF','\n').replace('CR','\r') def set_prompt(self, prompt, prompt_is_regexp=False): """Sets the prompt used by `Read Until Prompt` and `Login` in the current connection. If `prompt_is_regexp` is given any true value, including any non-empty string, the given `prompt` is considered to be a regular expression. The old prompt is returned and can be used to restore the prompt later. Example: | ${prompt} | ${regexp} = | `Set Prompt` | $ | | `Do Something` | | `Set Prompt` | ${prompt} | ${regexp} | See the documentation of [http://docs.python.org/2/library/re.html|Python `re` module] for more information about the supported regular expression syntax. Notice that possible backslashes need to be escaped in Robot Framework test data. See `Configuration` section for more information about global and connection specific configuration. """ self._verify_connection() old = self._prompt self._set_prompt(prompt, prompt_is_regexp) if old[1]: return old[0].pattern, True return old def _set_prompt(self, prompt, prompt_is_regexp): if prompt_is_regexp: self._prompt = (re.compile(prompt), True) else: self._prompt = (prompt, False) def _prompt_is_set(self): return self._prompt[0] is not None def set_encoding(self, encoding=None, errors=None): """Sets the encoding to use for `writing and reading` in the current connection. The given `encoding` specifies the encoding to use when written/read text is encoded/decoded, and `errors` specifies the error handler to use if encoding/decoding fails. Either of these can be omitted and in that case the old value is not affected. Use string `NONE` to disable encoding altogether. See `Configuration` section for more information about encoding and error handlers, as well as global and connection specific configuration in general. The old values are returned and can be used to restore the encoding and the error handler later. See `Set Prompt` for a similar example. If terminal emulation is used, the encoding can not be changed on an open connection. Setting encoding in general is a new feature in Robot Framework 2.7.6. Specifying the error handler and disabling encoding were added in 2.7.7. """ self._verify_connection() if self._terminal_emulator: raise AssertionError("Encoding can not be changed when terminal emulation is used.") old = self._encoding self._set_encoding(encoding or old[0], errors or old[1]) return old def _set_encoding(self, encoding, errors): self._encoding = (encoding.upper(), errors) def _encode(self, text): if isinstance(text, str): return text if self._encoding[0] == 'NONE': return str(text) return text.encode(*self._encoding) def _decode(self, bytes): if self._encoding[0] == 'NONE': return bytes return bytes.decode(*self._encoding) def set_default_log_level(self, level): """Sets the default log level used for `logging` in the current connection. The old default log level is returned and can be used to restore the log level later. See `Configuration` section for more information about global and connection specific configuration. """ self._verify_connection() old = self._default_log_level self._set_default_log_level(level) return old def _set_default_log_level(self, level): if level is None or not self._is_valid_log_level(level): raise AssertionError("Invalid log level '%s'" % level) self._default_log_level = level.upper() def _is_valid_log_level(self, level): if level is None: return True if not isinstance(level, basestring): return False return level.upper() in ('TRACE', 'DEBUG', 'INFO', 'WARN') def close_connection(self, loglevel=None): """Closes the current Telnet connection. Remaining output in the connection is read, logged, and returned. It is not an error to close an already closed connection. Use `Close All Connections` if you want to make sure all opened connections are closed. See `Logging` section for more information about log levels. """ self.close() output = self._decode(self.read_all()) self._log(output, loglevel) return output def login(self, username, password, login_prompt='login: ', password_prompt='Password: ', login_timeout='1 second', login_incorrect='Login incorrect'): """Logs in to the Telnet server with the given user information. This keyword reads from the connection until the `login_prompt` is encountered and then types the given `username`. Then it reads until the `password_prompt` and types the given `password`. In both cases a newline is appended automatically and the connection specific timeout used when waiting for outputs. How logging status is verified depends on whether a prompt is set for this connection or not: 1) If the prompt is set, this keyword reads the output until the prompt is found using the normal timeout. If no prompt is found, login is considered failed and also this keyword fails. Note that in this case both `login_timeout` and `login_incorrect` arguments are ignored. 2) If the prompt is not set, this keywords sleeps until `login_timeout` and then reads all the output available on the connection. If the output contains `login_incorrect` text, login is considered failed and also this keyword fails. Both of these configuration parameters were added in Robot Framework 2.7.6. In earlier versions they were hard coded. See `Configuration` section for more information about setting newline, timeout, and prompt. """ output = self._submit_credentials(username, password, login_prompt, password_prompt) if self._prompt_is_set(): success, output2 = self._read_until_prompt() else: success, output2 = self._verify_login_without_prompt( login_timeout, login_incorrect) output += output2 self._log(output) if not success: raise AssertionError('Login incorrect') return output def _submit_credentials(self, username, password, login_prompt, password_prompt): # Using write_bare here instead of write because don't want to wait for # newline: http://code.google.com/p/robotframework/issues/detail?id=1371 output = self.read_until(login_prompt, 'TRACE') self.write_bare(username + self._newline) output += self.read_until(password_prompt, 'TRACE') self.write_bare(password + self._newline) return output def _verify_login_without_prompt(self, delay, incorrect): time.sleep(utils.timestr_to_secs(delay)) output = self.read('TRACE') success = incorrect not in output return success, output def write(self, text, loglevel=None): """Writes the given text plus a newline into the connection. The newline character sequence to use can be [#Configuration|configured] both globally and per connection basis. The default value is `CRLF`. This keyword consumes the written text, until the added newline, from the output and logs and returns it. The given text itself must not contain newlines. Use `Write Bare` instead if either of these features causes a problem. *Note:* This keyword does not return the possible output of the executed command. To get the output, one of the `Read ...` keywords must be used. See `Writing and reading` section for more details. See `Logging` section for more information about log levels. """ if self._newline in text: raise RuntimeError("'Write' keyword cannot be used with strings " "containing newlines. Use 'Write Bare' instead.") self.write_bare(text + self._newline) # Can't read until 'text' because long lines are cut strangely in the output return self.read_until(self._newline, loglevel) def write_bare(self, text): """Writes the given text, and nothing else, into the connection. This keyword does not append a newline nor consume the written text. Use `Write` if these features are needed. """ self._verify_connection() telnetlib.Telnet.write(self, self._encode(text)) def write_until_expected_output(self, text, expected, timeout, retry_interval, loglevel=None): """Writes the given `text` repeatedly, until `expected` appears in the output. `text` is written without appending a newline and it is consumed from the output before trying to find `expected`. If `expected` does not appear in the output within `timeout`, this keyword fails. `retry_interval` defines the time to wait `expected` to appear before writing the `text` again. Consuming the written `text` is subject to the normal [#Configuration|configured timeout]. Both `timeout` and `retry_interval` must be given in `time string format`. See `Logging` section for more information about log levels. Example: | Write Until Expected Output | ps -ef| grep myprocess\\r\\n | myprocess | | ... | 5 s | 0.5 s | The above example writes command `ps -ef | grep myprocess\\r\\n` until `myprocess` appears in the output. The command is written every 0.5 seconds and the keyword fails if `myprocess` does not appear in the output in 5 seconds. """ timeout = utils.timestr_to_secs(timeout) retry_interval = utils.timestr_to_secs(retry_interval) maxtime = time.time() + timeout while time.time() < maxtime: self.write_bare(text) self.read_until(text, loglevel) try: with self._custom_timeout(retry_interval): return self.read_until(expected, loglevel) except AssertionError: pass raise NoMatchError(expected, timeout) def read(self, loglevel=None): """Reads everything that is currently available in the output. Read output is both returned and logged. See `Logging` section for more information about log levels. """ self._verify_connection() output = self.read_very_eager() if self._terminal_emulator: self._terminal_emulator.feed(output) output = self._terminal_emulator.read() else: output = self._decode(output) self._log(output, loglevel) return output def read_until(self, expected, loglevel=None): """Reads output until `expected` text is encountered. Text up to and including the match is returned and logged. If no match is found, this keyword fails. How much to wait for the output depends on the [#Configuration|configured timeout]. See `Logging` section for more information about log levels. Use `Read Until Regexp` if more complex matching is needed. """ success, output = self._read_until(expected) self._log(output, loglevel) if not success: raise NoMatchError(expected, self._timeout, output) return output def _read_until(self, expected): self._verify_connection() if self._terminal_emulator: return self._terminal_read_until(expected) expected = self._encode(expected) output = telnetlib.Telnet.read_until(self, expected, self._timeout) return output.endswith(expected), self._decode(output) @property def _terminal_frequency(self): return min(self.INTERNAL_UPDATE_FREQUENCY, self._timeout) def _terminal_read_until(self, expected): max_time = time.time() + self._timeout out = self._terminal_emulator.read_until(expected) if out: return True, out while time.time() < max_time: input_bytes = telnetlib.Telnet.read_until(self, expected, self._terminal_frequency) self._terminal_emulator.feed(input_bytes) out = self._terminal_emulator.read_until(expected) if out: return True, out return False, self._terminal_emulator.read() def _read_until_regexp(self, *expected): self._verify_connection() if self._terminal_emulator: return self._terminal_read_until_regexp(expected) expected = [self._encode(exp) if isinstance(exp, unicode) else exp for exp in expected] return self._telnet_read_until_regexp(expected) def _terminal_read_until_regexp(self, expected_list): max_time = time.time() + self._timeout regexp_list = [re.compile(rgx) for rgx in expected_list] out = self._terminal_emulator.read_until_regexp(regexp_list) if out: return True, out while time.time() < max_time: output = self.expect(regexp_list, self._terminal_frequency)[-1] self._terminal_emulator.feed(output) out = self._terminal_emulator.read_until_regexp(regexp_list) if out: return True, out return False, self._terminal_emulator.read() def _telnet_read_until_regexp(self, expected_list): try: index, _, output = self.expect(expected_list, self._timeout) except TypeError: index, output = -1, '' return index != -1, self._decode(output) def read_until_regexp(self, *expected): """Reads output until any of the `expected` regular expressions match. This keyword accepts any number of regular expressions patterns or compiled Python regular expression objects as arguments. Text up to and including the first match to any of the regular expressions is returned and logged. If no match is found, this keyword fails. How much to wait for the output depends on the [#Configuration|configured timeout]. If the last given argument is a [#Logging|valid log level], it is used as `loglevel` similarly as with `Read Until` keyword. See the documentation of [http://docs.python.org/2/library/re.html|Python `re` module] for more information about the supported regular expression syntax. Notice that possible backslashes need to be escaped in Robot Framework test data. Examples: | `Read Until Regexp` | (#|$) | | `Read Until Regexp` | first_regexp | second_regexp | | `Read Until Regexp` | \\\\d{4}-\\\\d{2}-\\\\d{2} | DEBUG | """ if not expected: raise RuntimeError('At least one pattern required') if self._is_valid_log_level(expected[-1]): loglevel = expected[-1] expected = expected[:-1] else: loglevel = None success, output = self._read_until_regexp(*expected) self._log(output, loglevel) if not success: expected = [exp if isinstance(exp, basestring) else exp.pattern for exp in expected] raise NoMatchError(expected, self._timeout, output) return output def read_until_prompt(self, loglevel=None): """Reads output until the prompt is encountered. This keyword requires the prompt to be [#Configuration|configured] either in `importing` or with `Open Connection` or `Set Prompt` keyword. Text up to and including the prompt is returned and logged. If no prompt is found, this keyword fails. How much to wait for the output depends on the [#Configuration|configured timeout]. See `Logging` section for more information about log levels. """ if not self._prompt_is_set(): raise RuntimeError('Prompt is not set.') success, output = self._read_until_prompt() self._log(output, loglevel) if not success: prompt, regexp = self._prompt raise AssertionError("Prompt '%s' not found in %s." % (prompt if not regexp else prompt.pattern, utils.secs_to_timestr(self._timeout))) return output def _read_until_prompt(self): prompt, regexp = self._prompt read_until = self._read_until_regexp if regexp else self._read_until return read_until(prompt) def execute_command(self, command, loglevel=None): """Executes the given `command` and reads, logs, and returns everything until the prompt. This keyword requires the prompt to be [#Configuration|configured] either in `importing` or with `Open Connection` or `Set Prompt` keyword. This is a convenience keyword that uses `Write` and `Read Until Prompt` internally Following two examples are thus functionally identical: | ${out} = | `Execute Command` | pwd | | `Write` | pwd | | ${out} = | `Read Until Prompt` | See `Logging` section for more information about log levels. """ self.write(command, loglevel) return self.read_until_prompt(loglevel) @contextmanager def _custom_timeout(self, timeout): old = self.set_timeout(timeout) try: yield finally: self.set_timeout(old) def _verify_connection(self): if not self.sock: raise RuntimeError('No connection open') def _log(self, msg, level=None): msg = msg.strip() if msg: logger.write(msg, level or self._default_log_level) def _negotiate_options(self, sock, cmd, opt): # This is supposed to turn server side echoing on and turn other options off. if opt == telnetlib.ECHO and cmd in (telnetlib.WILL, telnetlib.WONT): self._opt_echo_on(opt) elif cmd == telnetlib.DO and opt == telnetlib.TTYPE and self._terminal_type: self._opt_terminal_type(opt, self._terminal_type) elif cmd == telnetlib.DO and opt == telnetlib.NEW_ENVIRON and self._environ_user: self._opt_environ_user(opt, self._environ_user) elif cmd == telnetlib.DO and opt == telnetlib.NAWS and self._window_size: self._opt_window_size(opt, *self._window_size) elif opt != telnetlib.NOOPT: self._opt_dont_and_wont(cmd, opt) def _opt_echo_on(self, opt): return self.sock.sendall(telnetlib.IAC + telnetlib.DO + opt) def _opt_terminal_type(self, opt, terminal_type): self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt) self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.TTYPE + self.NEW_ENVIRON_IS + terminal_type + telnetlib.IAC + telnetlib.SE) def _opt_environ_user(self, opt, environ_user): self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt) self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NEW_ENVIRON + self.NEW_ENVIRON_IS + self.NEW_ENVIRON_VAR + "USER" + self.NEW_ENVIRON_VALUE + environ_user + telnetlib.IAC + telnetlib.SE) def _opt_window_size(self, opt, window_x, window_y): self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt) self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NAWS + struct.pack('!HH', window_x, window_y) + telnetlib.IAC + telnetlib.SE) def _opt_dont_and_wont(self, cmd, opt): if cmd in (telnetlib.DO, telnetlib.DONT): self.sock.sendall(telnetlib.IAC + telnetlib.WONT + opt) elif cmd in (telnetlib.WILL, telnetlib.WONT): self.sock.sendall(telnetlib.IAC + telnetlib.DONT + opt) def msg(self, msg, *args): # Forward telnetlib's debug messages to log logger.trace(msg % args) def _check_terminal_emulation(self, terminal_emulation): if not terminal_emulation: return False if not pyte: raise RuntimeError("Terminal emulation requires pyte module!\n" "https://pypi.python.org/pypi/pyte/") return TerminalEmulator(window_size=self._window_size, newline=self._newline, encoding=self._encoding) class TerminalEmulator(object): def __init__(self, window_size=None, newline="\r\n", encoding=('UTF-8', 'ignore')): self._rows, self._columns = window_size or (200, 200) self._newline = newline self._stream = pyte.ByteStream(encodings=[encoding]) self._screen = pyte.HistoryScreen(self._rows, self._columns, history=100000) self._stream.attach(self._screen) self._screen.set_charset('B', '(') self._buffer = '' self._whitespace_after_last_feed = '' @property def current_output(self): return self._buffer + self._dump_screen() def _dump_screen(self): return self._get_history() + \ self._get_screen(self._screen) + \ self._whitespace_after_last_feed def _get_history(self): if self._screen.history.top: return self._get_screen(self._screen.history.top) + self._newline return '' def _get_screen(self, screen): return self._newline.join(''.join(c.data for c in row).rstrip() for row in screen).rstrip(self._newline) def feed(self, input_bytes): self._stream.feed(input_bytes) self._whitespace_after_last_feed = input_bytes[len(input_bytes.rstrip()):] def read(self): current_out = self.current_output self._update_buffer('') return current_out def read_until(self, expected): current_out = self.current_output exp_index = current_out.find(expected) if exp_index != -1: self._update_buffer(current_out[exp_index+len(expected):]) return current_out[:exp_index+len(expected)] return None def read_until_regexp(self, regexp_list): current_out = self.current_output for rgx in regexp_list: match = rgx.search(current_out) if match: self._update_buffer(current_out[match.end():]) return current_out[:match.end()] return None def _update_buffer(self, terminal_buffer): self._buffer = terminal_buffer self._whitespace_after_last_feed = '' self._screen.reset() self._screen.set_charset('B', '(') class NoMatchError(AssertionError): ROBOT_SUPPRESS_NAME = True def __init__(self, expected, timeout, output=None): self.expected = expected self.timeout = utils.secs_to_timestr(timeout) self.output = output AssertionError.__init__(self, self._get_message()) def _get_message(self): expected = "'%s'" % self.expected \ if isinstance(self.expected, basestring) \ else utils.seq2str(self.expected, lastsep=' or ') msg = "No match found for %s in %s." % (expected, self.timeout) if self.output is not None: msg += ' Output:\n%s' % self.output return msg
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 OperatingSystem OPSYS = OperatingSystem.OperatingSystem() class DeprecatedOperatingSystem: ROBOT_LIBRARY_SCOPE = 'GLOBAL' delete_environment_variable = OPSYS.remove_environment_variable environment_variable_is_set = OPSYS.environment_variable_should_be_set environment_variable_is_not_set = OPSYS.environment_variable_should_not_be_set fail_unless_exists = OPSYS.should_exist fail_if_exists = OPSYS.should_not_exist fail_unless_file_exists = OPSYS.file_should_exist fail_if_file_exists = OPSYS.file_should_not_exist fail_unless_dir_exists = OPSYS.directory_should_exist fail_if_dir_exists = OPSYS.directory_should_not_exist fail_unless_dir_empty = OPSYS.directory_should_be_empty fail_if_dir_empty = OPSYS.directory_should_not_be_empty fail_unless_file_empty = OPSYS.file_should_be_empty fail_if_file_empty = OPSYS.file_should_not_be_empty empty_dir = OPSYS.empty_directory remove_dir = OPSYS.remove_directory copy_dir = OPSYS.copy_directory move_dir = OPSYS.move_directory create_dir = OPSYS.create_directory list_dir = OPSYS.list_directory list_files_in_dir = OPSYS.list_files_in_directory list_dirs_in_dir = OPSYS.list_directories_in_directory count_items_in_dir = OPSYS.count_items_in_directory count_files_in_dir = OPSYS.count_files_in_directory count_dirs_in_dir = OPSYS.count_directories_in_directory
Python
# Copyright 2008-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 sys import tempfile import time import glob import fnmatch import shutil import subprocess try: from robot.version import get_version from robot.api import logger from robot.utils import (ConnectionCache, seq2str, timestr_to_secs, secs_to_timestr, plural_or_not, get_time, abspath, secs_to_timestamp, parse_time, unic, decode_output, get_env_var, set_env_var, del_env_var, get_env_vars, decode_from_system) __version__ = get_version() PROCESSES = ConnectionCache('No active processes') del ConnectionCache, get_version # Support for using this library without installed Robot Framework except ImportError: from os.path import abspath from os import (getenv as get_env_var, putenv as set_env_var, unsetenv as del_env_var, environ) __version__ = '<unknown>' get_env_vars = environ.copy logger = None seq2str = lambda items: ', '.join("'%s'" % item for item in items) timestr_to_secs = int plural_or_not = lambda count: '' if count == 1 else 's' secs_to_timestr = lambda secs: '%d second%s' % (secs, plural_or_not(secs)) unic = unicode decode_output = decode_from_system = lambda string: string class _NotImplemented: def __getattr__(self, name): raise NotImplementedError('This usage requires Robot Framework ' 'to be installed.') get_time = secs_to_timestamp = parse_time = PROCESSES = _NotImplemented() class OperatingSystem: """A test library providing keywords for OS related tasks. `OperatingSystem` is Robot Framework's standard library that enables various operating system related tasks to be performed in the system where Robot Framework is running. It can, among other things, execute commands (e.g. `Run`), create and remove files and directories (e.g. `Create File`, `Remove Directory`), check whether files or directories exists or contain something (e.g. `File Should Exist`, `Directory Should Be Empty`) and manipulate environment variables (e.g. `Set Environment Variable`). = Pattern matching = Some keywords allow their arguments to be specified as _glob patterns_ where: | * | matches anything, even an empty string | | ? | matches any single character | | [chars] | matches any character inside square brackets (e.g. '[abc]' matches either 'a', 'b' or 'c') | | [!chars] | matches any character not inside square brackets | Unless otherwise noted, matching is case-insensitive on case-insensitive operating systems such as Windows. Pattern matching is implemented using [http://docs.python.org/library/fnmatch.html|fnmatch module]. = Path separators = All keywords expecting paths as arguments accept a forward slash (`/`) as a path separator regardless the operating system. Notice that this *does not work when the path is part of an argument*, like it often is with `Run` and `Start Process` keywords. In such cases the built-in variable `${/}` can be used to keep the test data platform independent. = Tilde expansion = Paths beginning with `~` or `~username` are expanded to the current or specified user's home directory, respectively. The resulting path is operating system dependent, but typically e.g. `~/robot` is expanded to `C:\\Users\\<user>\\robot` on Windows and `/home/<user>/robot` on Linuxes. Notice that the `~username` form does not work on Jython or on Windows python 2.5. Tilde expansion is a new feature in Robot Framework 2.8. = Process library = Process library replaces old process keywords (`Start Process` and `Switch Process`) from OperatingSystem library. These keywords in the OperatingSystem library might be deprecated in the future. This library is new in Robot Framework 2.8. = Example = | *Setting* | *Value* | | Library | OperatingSystem | | *Variable* | *Value* | | ${PATH} | ${CURDIR}/example.txt | | *Test Case* | *Action* | *Argument* | *Argument* | | Example | Create File | ${PATH} | Some text | | | File Should Exist | ${PATH} | | | | Copy File | ${PATH} | ~/file.txt | | | ${output} = | Run | ${TEMPDIR}${/}script.py arg | """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = __version__ def run(self, command): """Runs the given command in the system and returns the output. The execution status of the command *is not checked* by this keyword, and it must be done separately based on the returned output. If the execution return code is needed, either `Run And Return RC` or `Run And Return RC And Output` can be used. The standard error stream is automatically redirected to the standard output stream by adding `2>&1` after the executed command. This automatic redirection is done only when the executed command does not contain additional output redirections. You can thus freely forward the standard error somewhere else, for example, like `my_command 2>stderr.txt`. The returned output contains everything written into the standard output or error streams by the command (unless either of them is redirected explicitly). Many commands add an extra newline (`\\n`) after the output to make it easier to read in the console. To ease processing the returned output, this possible trailing newline is stripped by this keyword. Examples: | ${output} = | Run | ls -lhF /tmp | | Log | ${output} | | ${result} = | Run | ${CURDIR}${/}tester.py arg1 arg2 | | Should Not Contain | ${result} | FAIL | | ${stdout} = | Run | /opt/script.sh 2>/tmp/stderr.txt | | Should Be Equal | ${stdout} | TEST PASSED | | File Should Be Empty | /tmp/stderr.txt | """ return self._run(command)[1] def run_and_return_rc(self, command): """Runs the given command in the system and returns the return code. The return code (RC) is returned as a positive integer in range from 0 to 255 as returned by the executed command. On some operating systems (notable Windows) original return codes can be something else, but this keyword always maps them to the 0-255 range. Since the RC is an integer, it must be checked e.g. with the keyword `Should Be Equal As Integers` instead of `Should Be Equal` (both are built-in keywords). Examples: | ${rc} = | Run and Return RC | ${CURDIR}${/}script.py arg | | Should Be Equal As Integers | ${rc} | 0 | | ${rc} = | Run and Return RC | /path/to/example.rb arg1 arg2 | | Should Be True | 0 < ${rc} < 42 | See `Run` and `Run And Return RC And Output` if you need to get the output of the executed command. """ return self._run(command)[0] def run_and_return_rc_and_output(self, command): """Runs the given command in the system and returns the RC and output. The return code (RC) is returned similarly as with `Run And Return RC` and the output similarly as with `Run`. Examples: | ${rc} | ${output} = | Run and Return RC and Output | ${CURDIR}${/}mytool | | Should Be Equal As Integers | ${rc} | 0 | | Should Not Contain | ${output} | FAIL | | ${rc} | ${stdout} = | Run and Return RC and Output | /opt/script.sh 2>/tmp/stderr.txt | | Should Be True | ${rc} > 42 | | Should Be Equal | ${stdout} | TEST PASSED | | File Should Be Empty | /tmp/stderr.txt | """ return self._run(command) def _run(self, command): process = _Process(command) self._info("Running command '%s'" % process) stdout = process.read() rc = process.close() return rc, stdout def start_process(self, command, stdin=None, alias=None): """It is recommended to use same keyword from Process library instead. Starts the given command as a background process. Starts the process in background and sets it as the active process. `Read Process Output` or `Stop Process` keywords affect this process unless `Switch Process` is used in between. If the command needs input through the standard input stream, it can be defined with the `stdin` argument. It is not possible to give input to the command later. Possible command line arguments must be given as part of the command like '/tmp/script.sh arg1 arg2'. Returns the index of this process. Indexing starts from 1, and indices can be used to switch between processes using `Switch Process` keyword. `Stop All Processes` can be used to reset indexing. The optional `alias` is a name for this process that may be used with `Switch Process` instead of the returned index. The standard error stream is redirected to the standard input stream automatically. This is done for the same reasons as with `Run` keyword, but redirecting is done when the process is started and not by adding '2>&1' to the command. Example: | Start Process | /path/longlasting.sh | | Do Something | | | ${output} = | Read Process Output | | Should Contain | ${output} | Expected text | | [Teardown] | Stop All Processes | """ process = _Process2(command, stdin) self._info("Running command '%s'" % process) return PROCESSES.register(process, alias) def switch_process(self, index_or_alias): """It is recommended to use same keyword from Process library instead. Switches the active process to the specified process. New active process can be specified either using an index or an alias. Indices are return values from `Start Process` and aliases can be given to that keyword. Example: | Start Process | /path/script.sh arg | alias=1st process | | ${2nd} = | Start Process | /path/script2.sh | | Switch Process | 1st process | | ${out1} = | Read Process Output | | Switch Process | ${2nd} | | ${out2} = | Read Process Output | | Log Many | 1st process: ${out1} | 2nd process: ${out1} | | [Teardown] | Stop All Processes | """ PROCESSES.switch(index_or_alias) def read_process_output(self): """Waits for a process to finish and returns its output. This keyword waits for a process started with `Start Process` to end and then returns all output it has produced. The returned output contains everything the process has written into the standard output and error streams. There is no need to use `Stop Process` after using this keyword. Trying to read from an already stopped process fails. Note that although the process is finished, it still stays as the active process. Use `Switch Process` to switch the active process or `Stop All Processes` to reset the list of started processes. """ output = PROCESSES.current.read() PROCESSES.current.close() return output def stop_process(self): """Closes the standard output stream of the process. This keyword does not actually stop the process nor even wait for it to terminate. Only thing it does is closing the standard output stream of the process. Depending on the process that may terminate it but that is not guaranteed. Use `Read Process Output` instead if you need to wait for the process to complete. This keyword operates the active process similarly as `Read Process Output`. Stopping an already stopped process is not an error. """ PROCESSES.current.close() def stop_all_processes(self): """Closes the standard output of all the processes and resets the process list. Exactly like `Stop Process`, this keyword does not actually stop processes nor even wait for them to terminate. This keyword resets the indexing that `Start Process` uses. All aliases are also deleted. It does not matter have some of the processes already been closed or not. """ PROCESSES.close_all() def get_file(self, path, encoding='UTF-8'): """Returns the contents of a specified file. This keyword reads the specified file and returns the contents. Line breaks in content are converted to platform independent form. See also `Get Binary File`. `encoding` defines the encoding of the file. By default the value is 'UTF-8', which means that UTF-8 and ASCII-encoded files are read correctly. """ content = self.get_binary_file(path) return unicode(content, encoding).replace('\r\n', '\n') def get_binary_file(self, path): """Returns the contents of a specified file. This keyword reads the specified file and returns the contents as is. See also `Get File`. New in Robot Framework 2.5.5. """ path = self._absnorm(path) self._link("Getting file '%s'", path) with open(path, 'rb') as f: return f.read() def grep_file(self, path, pattern, encoding='UTF-8'): """Returns the lines of the specified file that match the `pattern`. This keyword reads a file from the file system using the defined `path` and `encoding` similarly as `Get File`. A difference is that only the lines that match the given `pattern` are returned. Lines are returned as a single string catenated back together with newlines and the number of matched lines is automatically logged. Possible trailing newline is never returned. A line matches if it contains the `pattern` anywhere in it and it *does not need to match the pattern fully*. The pattern matching syntax is explained in `introduction`, and in this case matching is case-sensitive. Examples: | ${errors} = | Grep File | /var/log/myapp.log | ERROR | | ${ret} = | Grep File | ${CURDIR}/file.txt | [Ww]ildc??d ex*ple | If more complex pattern matching is needed, it is possible to use `Get File` in combination with String library keywords like `Get Lines Matching Regexp`. """ pattern = '*%s*' % pattern path = self._absnorm(path) lines = [] total_lines = 0 self._link("Reading file '%s'", path) with open(path, 'rU') as f: for line in f: total_lines += 1 line = unicode(line, encoding).rstrip('\n') if fnmatch.fnmatchcase(line, pattern): lines.append(line) self._info('%d out of %d lines matched' % (len(lines), total_lines)) return '\n'.join(lines) def log_file(self, path, encoding='UTF-8'): """Wrapper for `Get File` that also logs the returned file. The file is logged with the INFO level. If you want something else, just use `Get File` and the built-in keyword `Log` with the desired level. """ content = self.get_file(path, encoding) self._info(content) return content # File and directory existence def should_exist(self, path, msg=None): """Fails unless the given path (file or directory) exists. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) if not glob.glob(path): self._fail(msg, "Path '%s' does not match any file or directory" % path) self._link("Path '%s' exists", path) def should_not_exist(self, path, msg=None): """Fails if the given path (file or directory) exists. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = glob.glob(path) if not matches: self._link("Path '%s' does not exist", path) return if not msg: if self._is_pattern_path(path): matches.sort() msg = "Path '%s' matches %s" % (path, seq2str(matches)) else: msg = "Path '%s' exists" % path raise AssertionError(msg) def file_should_exist(self, path, msg=None): """Fails unless the given `path` points to an existing file. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = [p for p in glob.glob(path) if os.path.isfile(p)] if not matches: self._fail(msg, "Path '%s' does not match any file" % path) self._link("File '%s' exists", path) def file_should_not_exist(self, path, msg=None): """Fails if the given path points to an existing file. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = [p for p in glob.glob(path) if os.path.isfile(p)] if not matches: self._link("File '%s' does not exist", path) return if not msg: if self._is_pattern_path(path): matches.sort() name = len(matches) == 1 and 'file' or 'files' msg = "Path '%s' matches %s %s" % (path, name, seq2str(matches)) else: msg = "File '%s' exists" % path raise AssertionError(msg) def directory_should_exist(self, path, msg=None): """Fails unless the given path points to an existing directory. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = [p for p in glob.glob(path) if os.path.isdir(p)] if not matches: self._fail(msg, "Path '%s' does not match any directory" % path) self._link("Directory '%s' exists", path) def directory_should_not_exist(self, path, msg=None): """Fails if the given path points to an existing file. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = [p for p in glob.glob(path) if os.path.isdir(p)] if not matches: self._link("Directory '%s' does not exist", path) return if not msg: if self._is_pattern_path(path): matches.sort() name = len(matches) == 1 and 'directory' or 'directories' msg = "Path '%s' matches %s %s" % (path, name, seq2str(matches)) else: msg = "Directory '%s' exists" % path raise AssertionError(msg) def _is_pattern_path(self, path): return '*' in path or '?' in path or ('[' in path and ']' in path) # Waiting file/dir to appear/disappear def wait_until_removed(self, path, timeout='1 minute'): """Waits until the given file or directory is removed. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. If the path is a pattern, the keyword waits until all matching items are removed. The optional `timeout` can be used to control the maximum time of waiting. The timeout is given as a timeout string, e.g. in a format '15 seconds', '1min 10s' or just '10'. The time string format is described in an appendix of Robot Framework User Guide. If the timeout is negative, the keyword is never timed-out. The keyword returns immediately, if the path does not exist in the first place. """ path = self._absnorm(path) timeout = timestr_to_secs(timeout) maxtime = time.time() + timeout while glob.glob(path): time.sleep(0.1) if timeout >= 0 and time.time() > maxtime: raise AssertionError("'%s' was not removed in %s" % (path, secs_to_timestr(timeout))) self._link("'%s' was removed", path) def wait_until_created(self, path, timeout='1 minute'): """Waits until the given file or directory is created. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. If the path is a pattern, the keyword returns when an item matching it is created. The optional `timeout` can be used to control the maximum time of waiting. The timeout is given as a timeout string, e.g. in a format '15 seconds', '1min 10s' or just '10'. The time string format is described in an appendix of Robot Framework User Guide. If the timeout is negative, the keyword is never timed-out. The keyword returns immediately, if the path already exists. """ path = self._absnorm(path) timeout = timestr_to_secs(timeout) maxtime = time.time() + timeout while not glob.glob(path): time.sleep(0.1) if timeout >= 0 and time.time() > maxtime: raise AssertionError("'%s' was not created in %s" % (path, secs_to_timestr(timeout))) self._link("'%s' was created", path) # Dir/file empty def directory_should_be_empty(self, path, msg=None): """Fails unless the specified directory is empty. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) items = self._list_dir(path) if items: if not msg: msg = "Directory '%s' is not empty. Contents: %s" \ % (path, seq2str(items, lastsep=', ')) raise AssertionError(msg) self._link("Directory '%s' is empty.", path) def directory_should_not_be_empty(self, path, msg=None): """Fails if the specified directory is empty. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) count = len(self._list_dir(path)) if count == 0: self._fail(msg, "Directory '%s' is empty." % path) plural = plural_or_not(count) self._link("Directory '%%s' contains %d item%s." % (count, plural), path) def file_should_be_empty(self, path, msg=None): """Fails unless the specified file is empty. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) if not os.path.isfile(path): raise AssertionError("File '%s' does not exist" % path) size = os.stat(path).st_size if size > 0: self._fail(msg, "File '%s' is not empty. Size: %d bytes" % (path, size)) self._link("File '%s' is empty", path) def file_should_not_be_empty(self, path, msg=None): """Fails if the specified directory is empty. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) if not os.path.isfile(path): raise AssertionError("File '%s' does not exist" % path) size = os.stat(path).st_size if size == 0: self._fail(msg, "File '%s' is empty." % path) self._link("File '%%s' contains %d bytes" % size, path) # Creating and removing files and directory def create_file(self, path, content='', encoding='UTF-8'): """Creates a file with the given content and encoding. If the directory where to create file does not exist it, and possible intermediate missing directories, are created. Use `Append To File` if you want to append to an existing file, and use `File Should Not Exist` if you want to avoid overwriting existing files. """ path = self._write_to_file(path, content, encoding, 'w') self._link("Created file '%s'", path) def append_to_file(self, path, content, encoding='UTF-8'): """Appends the given contend to the specified file. If the file does not exists, this keyword works exactly the same way as `Create File With Encoding`. """ path = self._write_to_file(path, content, encoding, 'a') self._link("Appended to file '%s'", path) def _write_to_file(self, path, content, encoding, mode): path = self._absnorm(path) parent = os.path.dirname(path) if not os.path.exists(parent): os.makedirs(parent) f = open(path, mode+'b') try: f.write(content.encode(encoding)) finally: f.close() return path def remove_file(self, path): """Removes a file with the given path. Passes if the file does not exist, but fails if the path does not point to a regular file (e.g. it points to a directory). The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. If the path is a pattern, all files matching it are removed. """ path = self._absnorm(path) matches = glob.glob(path) if not matches: self._link("File '%s' does not exist", path) for match in matches: if not os.path.isfile(match): raise RuntimeError("Path '%s' is not a file" % match) os.remove(match) self._link("Removed file '%s'", match) def remove_files(self, *paths): """Uses `Remove File` to remove multiple files one-by-one. Example: | Remove Files | ${TEMPDIR}${/}foo.txt | ${TEMPDIR}${/}bar.txt | ${TEMPDIR}${/}zap.txt | """ for path in paths: self.remove_file(path) def empty_directory(self, path): """Deletes all the content (incl. subdirectories) from the given directory.""" path = self._absnorm(path) items = [os.path.join(path, item) for item in self._list_dir(path)] for item in items: if os.path.isdir(item): shutil.rmtree(item) else: os.remove(item) self._link("Emptied directory '%s'", path) def create_directory(self, path): """Creates the specified directory. Also possible intermediate directories are created. Passes if the directory already exists, and fails if the path points to a regular file. """ path = self._absnorm(path) if os.path.isdir(path): self._link("Directory '%s' already exists", path ) return if os.path.exists(path): raise RuntimeError("Path '%s' already exists but is not a directory" % path) os.makedirs(path) self._link("Created directory '%s'", path) def remove_directory(self, path, recursive=False): """Removes the directory pointed to by the given `path`. If the second argument `recursive` is set to any non-empty string, the directory is removed recursively. Otherwise removing fails if the directory is not empty. If the directory pointed to by the `path` does not exist, the keyword passes, but it fails, if the `path` points to a file. """ path = self._absnorm(path) if not os.path.exists(path): self._link("Directory '%s' does not exist", path) return if os.path.isfile(path): raise RuntimeError("Path '%s' is not a directory" % path) if recursive: shutil.rmtree(path) else: msg = "Directory '%s' is not empty." % path self.directory_should_be_empty(path, msg) os.rmdir(path) self._link("Removed directory '%s'", path) # Moving and copying files and directories def copy_file(self, source, destination): """Copies the source file into the destination. Source must be an existing file. Starting from Robot Framework 2.8.4, it can be given as a glob pattern (see `Pattern matching`) that matches exactly one file. How the destination is interpreted is explained below. 1) If the destination is an existing file, the source file is copied over it. 2) If the destination is an existing directory, the source file is copied into it. A possible file with the same name as the source is overwritten. 3) If the destination does not exist and it ends with a path separator ('/' or '\\'), it is considered a directory. That directory is created and a source file copied into it. Possible missing intermediate directories are also created. 4) If the destination does not exist and it does not end with a path separator, it is considered a file. If the path to the file does not exist, it is created. See also `Copy Files`, `Move File`, and `Move Files`. """ source, destination = self._copy_file(source, destination) self._link("Copied file from '%s' to '%s'", source, destination) def move_file(self, source, destination): """Moves the source file into the destination. Arguments have exactly same semantics as with `Copy File` keyword. If the source and destination are on the same filesystem, rename operation is used. Otherwise file is copied to the destination filesystem and then removed from the original filesystem. See also `Move Files`, `Copy File`, and `Copy Files`. """ source, destination, _ = self._prepare_for_move_or_copy(source, destination) shutil.move(source, destination) self._link("Moved file from '%s' to '%s'", source, destination) def copy_files(self, *sources_and_destination): """Copies specified files to the target directory. Source files can be given as exact paths and as glob patterns (see `Pattern matching`). At least one source must be given, but it is not an error if it is a pattern that does not match anything. Last argument must be the destination directory. If the destination does not exist, it will be created. Examples: | Copy Files | ${dir}/file1.txt | ${dir}/file2.txt | ${dir2} | | Copy Files | ${dir}/file-*.txt | ${dir2} | | See also `Copy File`, `Move File`, and `Move Files`. New in Robot Framework 2.8.4. """ source_files, dest_dir = self._parse_sources_and_destination(sources_and_destination) for source in source_files: self.copy_file(source, dest_dir) def move_files(self, *sources_and_destination): """Moves specified files to the target directory. Arguments have exactly same semantics as with `Copy Files` keyword. See also `Move File`, `Copy File`, and `Copy Files`. New in Robot Framework 2.8.4. """ source_files, dest_dir = self._parse_sources_and_destination(sources_and_destination) for source in source_files: self.move_file(source, dest_dir) def _parse_sources_and_destination(self, items): if len(items) < 2: raise RuntimeError("Must contain destination and at least one source") sources, destination = items[:-1], items[-1] self._ensure_destination_directory(destination) return self._glob_files(sources), destination def _normalize_dest(self, dest): dest = dest.replace('/', os.sep) dest_is_dir = dest.endswith(os.sep) or os.path.isdir(dest) dest = self._absnorm(dest) return dest, dest_is_dir def _ensure_destination_directory(self, destination): destination, _ = self._normalize_dest(destination) if not os.path.exists(destination): os.makedirs(destination) elif not os.path.isdir(destination): raise RuntimeError("Destination '%s' exists and is not a directory" % destination) def _glob_files(self, patterns): files = [] for pattern in patterns: files.extend(glob.glob(self._absnorm(pattern))) return files def _prepare_for_move_or_copy(self, source, dest): source, dest, dest_is_dir = self._normalize_source_and_dest(source, dest) self._verify_that_source_is_a_file(source) parent = self._ensure_directory_exists(dest, dest_is_dir) self._ensure_dest_file_does_not_exist(source, dest, dest_is_dir) return source, dest, parent def _ensure_dest_file_does_not_exist(self, source, dest, dest_is_dir): if dest_is_dir: dest = os.path.join(dest, os.path.basename(source)) if os.path.isfile(dest): os.remove(dest) def _copy_file(self, source, dest): source, dest, parent = self._prepare_for_move_or_copy(source, dest) return self._atomic_copy(source, dest, parent) def _normalize_source_and_dest(self, source, dest): sources = self._glob_files([source]) if len(sources) > 1: raise RuntimeError("Multiple matches with source pattern '%s'" % source) source = sources[0] if sources else source dest, dest_is_dir = self._normalize_dest(dest) return source, dest, dest_is_dir def _verify_that_source_is_a_file(self, source): if not os.path.exists(source): raise RuntimeError("Source file '%s' does not exist" % source) if not os.path.isfile(source): raise RuntimeError("Source file '%s' is not a regular file" % source) def _ensure_directory_exists(self, dest, dest_is_dir): parent = dest if dest_is_dir else os.path.dirname(dest) if not os.path.exists(dest) and not os.path.exists(parent): os.makedirs(parent) return parent def _atomic_copy(self, source, destination, destination_parent): # This method tries to ensure that a file copy operation will not fail if the destination file is removed during # copy operation. # This has been an issue for at least some of the users that had a mechanism that polled and removed # the destination - their test cases sometimes failed because the copy file failed. # This is done by first copying the source to a temporary directory on the same drive as the destination is # and then moving (that is almost always in every platform an atomic operation) that temporary file to # the destination. # See http://code.google.com/p/robotframework/issues/detail?id=1502 for details temp_directory = tempfile.mkdtemp(dir=destination_parent) # Temporary directory can be atomically created temp_file = os.path.join(temp_directory, os.path.basename(source)) shutil.copy(source, temp_file) shutil.move(temp_file, destination) os.rmdir(temp_directory) return source, destination def copy_directory(self, source, destination): """Copies the source directory into the destination. If the destination exists, the source is copied under it. Otherwise the destination directory and the possible missing intermediate directories are created. """ source, destination = self._copy_dir(source, destination) self._link("Copied directory from '%s' to '%s'", source, destination) def move_directory(self, source, destination): """Moves the source directory into a destination. Uses `Copy Directory` keyword internally, and `source` and `destination` arguments have exactly same semantics as with that keyword. """ source, destination = self._prepare_copy_or_move_dir(source, destination) shutil.move(source, destination) self._link("Moved directory from '%s' to '%s'", source, destination) def _copy_dir(self, source, dest): source, dest = self._prepare_copy_or_move_dir(source, dest) shutil.copytree(source, dest) return source, dest def _prepare_copy_or_move_dir(self, source, dest): source = self._absnorm(source) dest = self._absnorm(dest) if not os.path.exists(source): raise RuntimeError("Source directory '%s' does not exist" % source) if not os.path.isdir(source): raise RuntimeError("Source directory '%s' is not a directory" % source) if os.path.exists(dest) and not os.path.isdir(dest): raise RuntimeError("Destination '%s' exists but is not a directory" % dest) if os.path.exists(dest): base = os.path.basename(source) dest = os.path.join(dest, base) else: parent = os.path.dirname(dest) if not os.path.exists(parent): os.makedirs(parent) return source, dest # Environment Variables def get_environment_variable(self, name, default=None): """Returns the value of an environment variable with the given name. If no such environment variable is set, returns the default value, if given. Otherwise fails the test case. Starting from Robot Framework 2.7, returned variables are automatically decoded to Unicode using the system encoding. Note that you can also access environment variables directly using the variable syntax `%{ENV_VAR_NAME}`. """ value = get_env_var(name, default) if value is None: raise RuntimeError("Environment variable '%s' does not exist" % name) return value def set_environment_variable(self, name, value): """Sets an environment variable to a specified value. Values are converted to strings automatically. Starting from Robot Framework 2.7, set variables are automatically encoded using the system encoding. """ set_env_var(name, value) self._info("Environment variable '%s' set to value '%s'" % (name, value)) def append_to_environment_variable(self, name, *values, **config): """Appends given `values` to environment variable `name`. If the environment variable already exists, values are added after it, and otherwise a new environment variable is created. Values are, by default, joined together using the operating system path separator (';' on Windows, ':' elsewhere). This can be changed by giving a separator after the values like `separator=value`. No other configuration parameters are accepted. Examples (assuming `NAME` and `NAME2` do not exist initially): | Append To Environment Variable | NAME | first | | | Should Be Equal | %{NAME} | first | | | Append To Environment Variable | NAME | second | third | | Should Be Equal | %{NAME} | first${:}second${:}third | | Append To Environment Variable | NAME2 | first | separator=- | | Should Be Equal | %{NAME2} | first | | | Append To Environment Variable | NAME2 | second | separator=- | | Should Be Equal | %{NAME2} | first-second | New in Robot Framework 2.8.4. """ sentinel = object() initial = self.get_environment_variable(name, sentinel) if initial is not sentinel: values = (initial,) + values separator = config.pop('separator', os.pathsep) if config: config = ['='.join(i) for i in sorted(config.items())] raise RuntimeError('Configuration %s not accepted.' % seq2str(config, lastsep=' or ')) self.set_environment_variable(name, separator.join(values)) def remove_environment_variable(self, *names): """Deletes the specified environment variable. Does nothing if the environment variable is not set. Starting from Robot Framework 2.7, it is possible to remove multiple variables by passing them to this keyword as separate arguments. """ for name in names: value = del_env_var(name) if value: self._info("Environment variable '%s' deleted" % name) else: self._info("Environment variable '%s' does not exist" % name) def environment_variable_should_be_set(self, name, msg=None): """Fails if the specified environment variable is not set. The default error message can be overridden with the `msg` argument. """ value = get_env_var(name) if not value: self._fail(msg, "Environment variable '%s' is not set" % name) self._info("Environment variable '%s' is set to '%s'" % (name, value)) def environment_variable_should_not_be_set(self, name, msg=None): """Fails if the specified environment variable is set. The default error message can be overridden with the `msg` argument. """ value = get_env_var(name) if value: self._fail(msg, "Environment variable '%s' is set to '%s'" % (name, value)) self._info("Environment variable '%s' is not set" % name) def get_environment_variables(self): """Returns currently available environment variables as a dictionary. Both keys and values are decoded to Unicode using the system encoding. Altering the returned dictionary has no effect on the actual environment variables. New in Robot Framework 2.7. """ return get_env_vars() def log_environment_variables(self, level='INFO'): """Logs all environment variables using the given log level. Environment variables are also returned the same way as with `Get Environment Variables` keyword. New in Robot Framework 2.7. """ vars = get_env_vars() for name, value in sorted(vars.items(), key=lambda item: item[0].lower()): self._log('%s = %s' % (name, value), level) return vars # Path def join_path(self, base, *parts): """Joins the given path part(s) to the given base path. The path separator ('/' or '\\') is inserted when needed and the possible absolute paths handled as expected. The resulted path is also normalized. Examples: | ${path} = | Join Path | my | path | | ${p2} = | Join Path | my/ | path/ | | ${p3} = | Join Path | my | path | my | file.txt | | ${p4} = | Join Path | my | /path | | ${p5} = | Join Path | /my/path/ | .. | path2 | => - ${path} = 'my/path' - ${p2} = 'my/path' - ${p3} = 'my/path/my/file.txt' - ${p4} = '/path' - ${p5} = '/my/path2' """ base = base.replace('/', os.sep) parts = [p.replace('/', os.sep) for p in parts] return self.normalize_path(os.path.join(base, *parts)) def join_paths(self, base, *paths): """Joins given paths with base and returns resulted paths. See `Join Path` for more information. Examples: | @{p1} = | Join Path | base | example | other | | | @{p2} = | Join Path | /my/base | /example | other | | | @{p3} = | Join Path | my/base | example/path/ | other | one/more | => - @{p1} = ['base/example', 'base/other'] - @{p2} = ['/example', '/my/base/other'] - @{p3} = ['my/base/example/path', 'my/base/other', 'my/base/one/more'] """ return [self.join_path(base, path) for path in paths] def normalize_path(self, path): """Normalizes the given path. Examples: | ${path} = | Normalize Path | abc | | ${p2} = | Normalize Path | abc/ | | ${p3} = | Normalize Path | abc/../def | | ${p4} = | Normalize Path | abc/./def | | ${p5} = | Normalize Path | abc//def | => - ${path} = 'abc' - ${p2} = 'abc' - ${p3} = 'def' - ${p4} = 'abc/def' - ${p5} = 'abc/def' """ path = os.path.normpath(os.path.expanduser(path.replace('/', os.sep))) return path or '.' def split_path(self, path): """Splits the given path from the last path separator ('/' or '\\'). The given path is first normalized (e.g. a possible trailing path separator is removed, special directories '..' and '.' removed). The parts that are split are returned as separate components. Examples: | ${path1} | ${dir} = | Split Path | abc/def | | ${path2} | ${file} = | Split Path | abc/def/ghi.txt | | ${path3} | ${d2} = | Split Path | abc/../def/ghi/ | => - ${path1} = 'abc' & ${dir} = 'def' - ${path2} = 'abc/def' & ${file} = 'ghi.txt' - ${path3} = 'def' & ${d2} = 'ghi' """ return os.path.split(self.normalize_path(path)) def split_extension(self, path): """Splits the extension from the given path. The given path is first normalized (e.g. possible trailing path separators removed, special directories '..' and '.' removed). The base path and extension are returned as separate components so that the dot used as an extension separator is removed. If the path contains no extension, an empty string is returned for it. Possible leading and trailing dots in the file name are never considered to be extension separators. Examples: | ${path} | ${ext} = | Split Extension | file.extension | | ${p2} | ${e2} = | Split Extension | path/file.ext | | ${p3} | ${e3} = | Split Extension | path/file | | ${p4} | ${e4} = | Split Extension | p1/../p2/file.ext | | ${p5} | ${e5} = | Split Extension | path/.file.ext | | ${p6} | ${e6} = | Split Extension | path/.file | => - ${path} = 'file' & ${ext} = 'extension' - ${p2} = 'path/file' & ${e2} = 'ext' - ${p3} = 'path/file' & ${e3} = '' - ${p4} = 'p2/file' & ${e4} = 'ext' - ${p5} = 'path/.file' & ${e5} = 'ext' - ${p6} = 'path/.file' & ${e6} = '' """ path = self.normalize_path(path) basename = os.path.basename(path) if basename.startswith('.' * basename.count('.')): return path, '' if path.endswith('.'): path2 = path.rstrip('.') trailing_dots = '.' * (len(path) - len(path2)) path = path2 else: trailing_dots = '' basepath, ext = os.path.splitext(path) if ext.startswith('.'): ext = ext[1:] if ext: ext += trailing_dots else: basepath += trailing_dots return basepath, ext # Misc def get_modified_time(self, path, format='timestamp'): """Returns the last modification time of a file or directory. How time is returned is determined based on the given `format` string as follows. Note that all checks are case-insensitive. Returned time is also automatically logged. 1) If `format` contains the word 'epoch', the time is returned in seconds after the UNIX epoch. The return value is always an integer. 2) If `format` contains any of the words 'year', 'month', 'day', 'hour', 'min' or 'sec', only the selected parts are returned. The order of the returned parts is always the one in the previous sentence and the order of the words in `format` is not significant. The parts are returned as zero-padded strings (e.g. May -> '05'). 3) Otherwise, and by default, the time is returned as a timestamp string in the format '2006-02-24 15:08:31'. Examples (when the modified time of the ${CURDIR} is 2006-03-29 15:06:21): | ${time} = | Get Modified Time | ${CURDIR} | | ${secs} = | Get Modified Time | ${CURDIR} | epoch | | ${year} = | Get Modified Time | ${CURDIR} | return year | | ${y} | ${d} = | Get Modified Time | ${CURDIR} | year,day | | @{time} = | Get Modified Time | ${CURDIR} | year,month,day,hour,min,sec | => - ${time} = '2006-03-29 15:06:21' - ${secs} = 1143637581 - ${year} = '2006' - ${y} = '2006' & ${d} = '29' - @{time} = ['2006', '03', '29', '15', '06', '21'] """ path = self._absnorm(path) if not os.path.exists(path): raise RuntimeError("Getting modified time of '%s' failed: " "Path does not exist" % path) mtime = get_time(format, os.stat(path).st_mtime) self._link("Last modified time of '%%s' is %s" % mtime, path) return mtime def set_modified_time(self, path, mtime): """Sets the file modification and access times. Changes the modification and access times of the given file to the value determined by `mtime`. The time can be given in different formats described below. Note that all checks involving strings are case-insensitive. 1) If `mtime` is a number, or a string that can be converted to a number, it is interpreted as seconds since the UNIX epoch (1970-01-01 00:00:00 UTC). This documentation was originally written about 1177654467 seconds after the epoch. 2) If `mtime` is a timestamp, that time will be used. Valid timestamp formats are 'YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss'. 3) If `mtime` is equal to 'NOW', the current local time is used. This time is got using Python's 'time.time()' function. 4) If `mtime` is equal to 'UTC', the current time in [http://en.wikipedia.org/wiki/Coordinated_Universal_Time|UTC] is used. This time is got using 'time.time() + time.altzone' in Python. 5) If `mtime` is in the format like 'NOW - 1 day' or 'UTC + 1 hour 30 min', the current local/UTC time plus/minus the time specified with the time string is used. The time string format is described in an appendix of Robot Framework User Guide. Examples: | Set Modified Time | /path/file | 1177654467 | # Time given as epoch seconds | | Set Modified Time | /path/file | 2007-04-27 9:14:27 | # Time given as a timestamp | | Set Modified Time | /path/file | NOW | # The local time of execution | | Set Modified Time | /path/file | NOW - 1 day | # 1 day subtracted from the local time | | Set Modified Time | /path/file | UTC + 1h 2min 3s | # 1h 2min 3s added to the UTC time | Support for UTC time is a new feature in Robot Framework 2.7.5. """ path = self._absnorm(path) try: if not os.path.exists(path): raise ValueError('File does not exist') if not os.path.isfile(path): raise ValueError('Modified time can only be set to regular files') mtime = parse_time(mtime) except ValueError, err: raise RuntimeError("Setting modified time of '%s' failed: %s" % (path, unicode(err))) os.utime(path, (mtime, mtime)) time.sleep(0.1) # Give os some time to really set these times tstamp = secs_to_timestamp(mtime, ('-',' ',':')) self._link("Set modified time of '%%s' to %s" % tstamp, path) def get_file_size(self, path): """Returns and logs file size as an integer in bytes""" path = self._absnorm(path) if not os.path.isfile(path): raise RuntimeError("File '%s' does not exist." % path) size = os.stat(path).st_size plural = plural_or_not(size) self._link("Size of file '%%s' is %d byte%s" % (size, plural), path) return size def list_directory(self, path, pattern=None, absolute=False): """Returns and logs items in a directory, optionally filtered with `pattern`. File and directory names are returned in case-sensitive alphabetical order, e.g. ['A Name', 'Second', 'a lower case name', 'one more']. Implicit directories '.' and '..' are not returned. The returned items are automatically logged. By default, the file and directory names are returned relative to the given path (e.g. 'file.txt'). If you want them be returned in the absolute format (e.g. '/home/robot/file.txt'), set the `absolute` argument to any non-empty string. If `pattern` is given, only items matching it are returned. The pattern matching syntax is explained in `introduction`, and in this case matching is case-sensitive. Examples (using also other `List Directory` variants): | @{items} = | List Directory | ${TEMPDIR} | | @{files} = | List Files In Directory | /tmp | *.txt | absolute | | ${count} = | Count Files In Directory | ${CURDIR} | ??? | """ items = self._list_dir(path, pattern, absolute) self._info('%d item%s:\n%s' % (len(items), plural_or_not(items), '\n'.join(items))) return items def list_files_in_directory(self, path, pattern=None, absolute=False): """A wrapper for `List Directory` that returns only files.""" files = self._list_files_in_dir(path, pattern, absolute) self._info('%d file%s:\n%s' % (len(files), plural_or_not(files), '\n'.join(files))) return files def list_directories_in_directory(self, path, pattern=None, absolute=False): """A wrapper for `List Directory` that returns only directories.""" dirs = self._list_dirs_in_dir(path, pattern, absolute) self._info('%d director%s:\n%s' % (len(dirs), 'y' if len(dirs) == 1 else 'ies', '\n'.join(dirs))) return dirs def count_items_in_directory(self, path, pattern=None): """Returns and logs the number of all items in the given directory. The argument `pattern` has the same semantics as in the `List Directory` keyword. The count is returned as an integer, so it must be checked e.g. with the built-in keyword `Should Be Equal As Integers`. """ count = len(self._list_dir(path, pattern)) self._info("%s item%s." % (count, plural_or_not(count))) return count def count_files_in_directory(self, path, pattern=None): """A wrapper for `Count Items In Directory` returning only file count.""" count = len(self._list_files_in_dir(path, pattern)) self._info("%s file%s." % (count, plural_or_not(count))) return count def count_directories_in_directory(self, path, pattern=None): """A wrapper for `Count Items In Directory` returning only directory count.""" count = len(self._list_dirs_in_dir(path, pattern)) self._info("%s director%s." % (count, 'y' if count == 1 else 'ies')) return count def _list_dir(self, path, pattern=None, absolute=False): path = self._absnorm(path) self._link("Listing contents of directory '%s'.", path) if not os.path.isdir(path): raise RuntimeError("Directory '%s' does not exist" % path) # result is already unicode but unic also handles NFC normalization items = sorted(unic(item) for item in os.listdir(path)) if pattern: items = [i for i in items if fnmatch.fnmatchcase(i, pattern)] if absolute: path = os.path.normpath(path) items = [os.path.join(path,item) for item in items] return items def _list_files_in_dir(self, path, pattern=None, absolute=False): return [item for item in self._list_dir(path, pattern, absolute) if os.path.isfile(os.path.join(path, item))] def _list_dirs_in_dir(self, path, pattern=None, absolute=False): return [item for item in self._list_dir(path, pattern, absolute) if os.path.isdir(os.path.join(path, item))] def touch(self, path): """Emulates the UNIX touch command. Creates a file, if it does not exist. Otherwise changes its access and modification times to the current time. Fails if used with the directories or the parent directory of the given file does not exist. """ path = self._absnorm(path) if os.path.isdir(path): raise RuntimeError("Cannot touch '%s' because it is a directory" % path) if not os.path.exists(os.path.dirname(path)): raise RuntimeError("Cannot touch '%s' because its parent directory " "does not exist" % path) if os.path.exists(path): mtime = round(time.time()) os.utime(path, (mtime, mtime)) self._link("Touched existing file '%s'", path) else: open(path, 'w').close() self._link("Touched new file '%s'", path) def _absnorm(self, path): path = self.normalize_path(path) try: return abspath(path) except ValueError: # http://ironpython.codeplex.com/workitem/29489 return path def _fail(self, error, default): raise AssertionError(error or default) def _info(self, msg): self._log(msg, 'INFO') def _link(self, msg, *paths): paths = tuple('<a href="file://%s">%s</a>' % (p, p) for p in paths) self._log(msg % paths, 'HTML') def _warn(self, msg): self._log(msg, 'WARN') def _log(self, msg, level): if logger: logger.write(msg, level) else: print '*%s* %s' % (level, msg) class _Process: def __init__(self, command): self._command = self._process_command(command) self._process = os.popen(self._command) def __str__(self): return self._command def read(self): return self._process_output(self._process.read()) def close(self): try: rc = self._process.close() except IOError: # Has occurred sometimes in Windows return 255 if rc is None: return 0 # In Windows (Python and Jython) return code is value returned by # command (can be almost anything) # In other OS: # In Jython return code can be between '-255' - '255' # In Python return code must be converted with 'rc >> 8' and it is # between 0-255 after conversion if os.sep == '\\' or sys.platform.startswith('java'): return rc % 256 return rc >> 8 def _process_command(self, command): if '>' not in command: if command.endswith('&'): command = command[:-1] + ' 2>&1 &' else: command += ' 2>&1' return self._encode_to_file_system(command) def _encode_to_file_system(self, string): enc = sys.getfilesystemencoding() return string.encode(enc) if enc else string def _process_output(self, stdout): stdout = stdout.replace('\r\n', '\n') # http://bugs.jython.org/issue1566 if stdout.endswith('\n'): stdout = stdout[:-1] return decode_output(stdout, force=True) class _Process2(_Process): def __init__(self, command, input_): self._command = self._process_command(command) p = subprocess.Popen(self._command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=os.sep=='/') stdin, self.stdout = p.stdin, p.stdout if input_: stdin.write(input_) stdin.close() self.closed = False def read(self): if self.closed: raise RuntimeError('Cannot read from a closed process') return self._process_output(self.stdout.read()) def close(self): if not self.closed: self.stdout.close() self.closed = True
Python
# Copyright 2008-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 socket import sys import time import xmlrpclib try: from xml.parsers.expat import ExpatError except ImportError: # No expat in IronPython 2.7 class ExpatError(Exception): pass from robot.errors import RemoteError from robot.utils import is_list_like, is_dict_like, unic IRONPYTHON = sys.platform == 'cli' class Remote(object): ROBOT_LIBRARY_SCOPE = 'TEST SUITE' def __init__(self, uri='http://127.0.0.1:8270'): if '://' not in uri: uri = 'http://' + uri self._uri = uri self._client = XmlRpcRemoteClient(uri) def get_keyword_names(self, attempts=5): for i in range(attempts): try: return self._client.get_keyword_names() except TypeError, err: time.sleep(1) raise RuntimeError('Connecting remote server at %s failed: %s' % (self._uri, err)) def get_keyword_arguments(self, name): try: return self._client.get_keyword_arguments(name) except TypeError: return ['*args'] def get_keyword_documentation(self, name): try: return self._client.get_keyword_documentation(name) except TypeError: return None def run_keyword(self, name, args, kwargs): coercer = ArgumentCoercer() args = coercer.coerce(args) kwargs = coercer.coerce(kwargs) result = RemoteResult(self._client.run_keyword(name, args, kwargs)) sys.stdout.write(result.output) if result.status != 'PASS': raise RemoteError(result.error, result.traceback, result.fatal, result.continuable) return result.return_ class ArgumentCoercer(object): binary = re.compile('[\x00-\x08\x0B\x0C\x0E-\x1F]') non_ascii = re.compile('[\x80-\xff]') def coerce(self, argument): for handles, handle in [(self._is_string, self._handle_string), (self._is_number, self._pass_through), (is_list_like, self._coerce_list), (is_dict_like, self._coerce_dict), (lambda arg: True, self._to_string)]: if handles(argument): return handle(argument) def _is_string(self, arg): return isinstance(arg, basestring) def _is_number(self, arg): return isinstance(arg, (int, long, float)) def _handle_string(self, arg): if self._contains_binary(arg): return self._handle_binary(arg) return arg def _contains_binary(self, arg): return (self.binary.search(arg) or isinstance(arg, str) and not IRONPYTHON and self.non_ascii.search(arg)) def _handle_binary(self, arg): try: arg = str(arg) except UnicodeError: raise ValueError('Cannot represent %r as binary.' % arg) return xmlrpclib.Binary(arg) def _pass_through(self, arg): return arg def _coerce_list(self, arg): return [self.coerce(item) for item in arg] def _coerce_dict(self, arg): return dict((self._to_key(key), self.coerce(arg[key])) for key in arg) def _to_key(self, item): item = self._to_string(item) if IRONPYTHON: self._validate_key_on_ironpython(item) return item def _to_string(self, item): item = unic(item) if item is not None else '' return self._handle_string(item) def _validate_key_on_ironpython(self, item): try: return str(item) except UnicodeError: raise ValueError('Dictionary keys cannot contain non-ASCII ' 'characters on IronPython. Got %r.' % item) class RemoteResult(object): def __init__(self, result): if not (is_dict_like(result) and 'status' in result): raise RuntimeError('Invalid remote result dictionary: %s' % result) self.status = result['status'] self.output = self._get(result, 'output') self.return_ = self._get(result, 'return') self.error = self._get(result, 'error') self.traceback = self._get(result, 'traceback') self.fatal = bool(self._get(result, 'fatal', False)) self.continuable = bool(self._get(result, 'continuable', False)) def _get(self, result, key, default=''): value = result.get(key, default) return self._handle_binary(value) def _handle_binary(self, value): if isinstance(value, xmlrpclib.Binary): return str(value) if is_list_like(value): return [self._handle_binary(v) for v in value] if is_dict_like(value): return dict((k, self._handle_binary(v)) for k, v in value.items()) return value class XmlRpcRemoteClient(object): def __init__(self, uri): self._server = xmlrpclib.ServerProxy(uri, encoding='UTF-8') def get_keyword_names(self): try: return self._server.get_keyword_names() except socket.error, (errno, err): raise TypeError(err) except xmlrpclib.Error, err: raise TypeError(err) def get_keyword_arguments(self, name): try: return self._server.get_keyword_arguments(name) except xmlrpclib.Error: raise TypeError def get_keyword_documentation(self, name): try: return self._server.get_keyword_documentation(name) except xmlrpclib.Error: raise TypeError def run_keyword(self, name, args, kwargs): run_keyword_args = [name, args, kwargs] if kwargs else [name, args] try: return self._server.run_keyword(*run_keyword_args) except xmlrpclib.Fault, err: message = err.faultString except socket.error, err: message = 'Connection to remote server broken: %s' % err except ExpatError, err: message = ('Processing XML-RPC return value failed. ' 'Most often this happens when the return value ' 'contains characters that are not valid in XML. ' 'Original error was: ExpatError: %s' % err) raise RuntimeError(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. import re import fnmatch from robot.utils import asserts import BuiltIn BUILTIN = BuiltIn.BuiltIn() class DeprecatedBuiltIn: ROBOT_LIBRARY_SCOPE = 'GLOBAL' integer = BUILTIN.convert_to_integer float = BUILTIN.convert_to_number string = BUILTIN.convert_to_string boolean = BUILTIN.convert_to_boolean list = BUILTIN.create_list equal = equals = fail_unless_equal = BUILTIN.should_be_equal not_equal = not_equals = fail_if_equal = BUILTIN.should_not_be_equal is_true = fail_unless = BUILTIN.should_be_true is_false = fail_if = BUILTIN.should_not_be_true fail_if_ints_equal = ints_not_equal = BUILTIN.should_not_be_equal_as_integers ints_equal = fail_unless_ints_equal = BUILTIN.should_be_equal_as_integers floats_not_equal = fail_if_floats_equal = BUILTIN.should_not_be_equal_as_numbers floats_equal = fail_unless_floats_equal = BUILTIN.should_be_equal_as_numbers does_not_start = fail_if_starts = BUILTIN.should_not_start_with starts = fail_unless_starts = BUILTIN.should_start_with does_not_end = fail_if_ends = BUILTIN.should_not_end_with ends = fail_unless_ends = BUILTIN.should_end_with does_not_contain = fail_if_contains = BUILTIN.should_not_contain contains = fail_unless_contains = BUILTIN.should_contain does_not_match = fail_if_matches = BUILTIN.should_not_match matches = fail_unless_matches = BUILTIN.should_match does_not_match_regexp = fail_if_regexp_matches = BUILTIN.should_not_match_regexp matches_regexp = fail_unless_regexp_matches = BUILTIN.should_match_regexp noop = BUILTIN.no_operation set_ = BUILTIN.set_variable message = BUILTIN.comment variable_exists = fail_unless_variable_exists = BUILTIN.variable_should_exist variable_does_not_exist = fail_if_variable_exists = BUILTIN.variable_should_not_exist def error(self, msg=None): """Errors the test immediately with the given message.""" asserts.error(msg) def grep(self, text, pattern, pattern_type='literal string'): lines = self._filter_lines(text.splitlines(), pattern, pattern_type) return '\n'.join(lines) def _filter_lines(self, lines, pattern, ptype): ptype = ptype.lower().replace(' ','').replace('-','') if not pattern: filtr = lambda line: True elif 'simple' in ptype or 'glob' in ptype: if 'caseinsensitive' in ptype: pattern = pattern.lower() filtr = lambda line: fnmatch.fnmatchcase(line.lower(), pattern) else: filtr = lambda line: fnmatch.fnmatchcase(line, pattern) elif 'regularexpression' in ptype or 'regexp' in ptype: pattern = re.compile(pattern) filtr = lambda line: pattern.search(line) elif 'caseinsensitive' in ptype: pattern = pattern.lower() filtr = lambda line: pattern in line.lower() else: filtr = lambda line: pattern in line return [ line for line in lines if filtr(line) ]
Python
# Copyright 2008-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 from Tkinter import (Tk, Toplevel, Frame, Listbox, Label, Button, Entry, BOTH, END, LEFT, W) class _TkDialog(Toplevel): _left_button = 'OK' _right_button = 'Cancel' def __init__(self, message, value=None, **extra): self._prevent_execution_with_timeouts() self._parent = self._get_parent() Toplevel.__init__(self, self._parent) self._initialize_dialog() self._create_body(message, value, **extra) self._create_buttons() self._result = None def _prevent_execution_with_timeouts(self): if 'linux' not in sys.platform \ and currentThread().getName() != 'MainThread': raise RuntimeError('Dialogs library is not supported with ' 'timeouts on Python on this platform.') def _get_parent(self): parent = Tk() parent.withdraw() return parent def _initialize_dialog(self): self.title('Robot Framework') self.grab_set() self.protocol("WM_DELETE_WINDOW", self._right_button_clicked) self.bind("<Escape>", self._right_button_clicked) self.minsize(250, 80) self.geometry("+%d+%d" % self._get_center_location()) self._bring_to_front() def _get_center_location(self): x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2 y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2 return x, y def _bring_to_front(self): self.attributes('-topmost', True) self.attributes('-topmost', False) def _create_body(self, message, value, **extra): frame = Frame(self) Label(frame, text=message, anchor=W, justify=LEFT, wraplength=800).pack(fill=BOTH) selector = self._create_selector(frame, value, **extra) if selector: selector.pack(fill=BOTH) selector.focus_set() frame.pack(padx=5, pady=5, expand=1, fill=BOTH) def _create_selector(self, frame, value): return None def _create_buttons(self): frame = Frame(self) self._create_button(frame, self._left_button, self._left_button_clicked) self._create_button(frame, self._right_button, self._right_button_clicked) frame.pack() def _create_button(self, parent, label, callback): if label: button = Button(parent, text=label, width=10, command=callback) button.pack(side=LEFT, padx=5, pady=5) def _left_button_clicked(self, event=None): if self._validate_value(): self._result = self._get_value() self._close() def _validate_value(self): return True def _get_value(self): return None def _close(self): # self.destroy() is not enough on Linux self._parent.destroy() def _right_button_clicked(self, event=None): self._result = self._get_right_button_value() self._close() def _get_right_button_value(self): return None def show(self): self.wait_window(self) return self._result class MessageDialog(_TkDialog): _right_button = None class InputDialog(_TkDialog): def __init__(self, message, default='', hidden=False): _TkDialog.__init__(self, message, default, hidden=hidden) def _create_selector(self, parent, default, hidden): self._entry = Entry(parent, show='*' if hidden else '') self._entry.insert(0, default) self._entry.select_range(0, END) return self._entry def _get_value(self): return self._entry.get() class SelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent) for item in values: self._listbox.insert(END, item) return self._listbox def _validate_value(self): return bool(self._listbox.curselection()) def _get_value(self): return self._listbox.get(self._listbox.curselection()) class PassFailDialog(_TkDialog): _left_button = 'PASS' _right_button = 'FAIL' def _get_value(self): return True def _get_right_button_value(self): return False
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 copy import re from robot.api import logger from robot.libraries.BuiltIn import BuiltIn from robot.utils import asserts, ET, ETSource, plural_or_not as s from robot.version import get_version should_be_equal = asserts.assert_equals should_match = BuiltIn().should_match class XML(object): """Robot Framework test library for verifying and modifying XML documents. As the name implies, `XML` is a test library for verifying contents of XML files. In practice it is a pretty thin wrapper on top of Python's [http://docs.python.org/library/xml.etree.elementtree.html|ElementTree XML API]. The library has the following main usages: - Parsing an XML file, or a string containing XML, into an XML element structure and finding certain elements from it for for further analysis (e.g. `Parse XML` and `Get Element` keywords). - Getting text or attributes of elements (e.g. `Get Element Text` and `Get Element Attribute`). - Directly verifying text, attributes, or whole elements (e.g `Element Text Should Be` and `Elements Should Be Equal`). - Modifying XML and saving it (e.g. `Set Element Text`, `Add Element` and `Save XML`). == Table of contents == - `Parsing XML` - `Example` - `Finding elements with xpath` - `Element attributes` - `Handling XML namespaces` - `Shortcuts` - `Keywords` = Parsing XML = XML can be parsed into an element structure using `Parse XML` keyword. It accepts both paths to XML files and strings that contain XML. The keyword returns the root element of the structure, which then contains other elements as its children and their children. The element structure returned by `Parse XML`, as well as elements returned by keywords such as `Get Element`, can be used as the `source` argument with other keywords. In addition to an already parsed XML structure, other keywords also accept paths to XML files and strings containing XML similarly as `Parse XML`. When the source is given as a path to a file, the forward slash character (`/`) can be used as the path separator regardless the operating system. On Windows also the backslash works, but it the test data it needs to be escaped by doubling it (`\\\\`). Using the built-in variable `${/}` naturally works too. = Example = The following simple example demonstrates parsing XML and verifying its contents both using keywords in this library and in `BuiltIn` and `Collections` libraries. How to use xpath expressions to find elements and what attributes the returned elements contain are discussed, with more examples, in `Finding elements with xpath` and `Element attributes` sections. In this example, as well as in many other examples in this documentation, `${XML}` refers to the following example XML document. In practice `${XML}` could either be a path to an XML file or it could contain the XML itself. | <example> | <first id="1">text</first> | <second id="2"> | <child/> | </second> | <third> | <child>more text</child> | <second id="child"/> | <child><grandchild/></child> | </third> | <html> | <p> | Text with <b>bold</b> and <i>italics</i>. | </p> | </html> | </example> | ${root} = | `Parse XML` | ${XML} | | | | `Should Be Equal` | ${root.tag} | example | | | | ${first} = | `Get Element` | ${root} | first | | | `Should Be Equal` | ${first.text} | text | | | | `Dictionary Should Contain Key` | ${first.attrib} | id | | | `Element Text Should Be` | ${first} | text | | | | `Element Attribute Should Be` | ${first} | id | 1 | | | `Element Attribute Should Be` | ${root} | id | 1 | xpath=first | | `Element Attribute Should Be` | ${XML} | id | 1 | xpath=first | Notice that in the example three last lines are equivalent. Which one to use in practice depends on which other elements you need to get or verify. If you only need to do one verification, using the last line alone would suffice. If more verifications are needed, parsing the XML with `Parse XML` only once would be more efficient. = Finding elements with xpath = ElementTree, and thus also this library, supports finding elements using xpath expressions. ElementTree does not, however, support the full xpath syntax, and what is supported depends on its version. ElementTree 1.3 that is distributed with Python and Jython 2.7 supports richer syntax than versions distributed with earlier Python interpreters. The supported xpath syntax is explained below and [http://effbot.org/zone/element-xpath.htm|ElementTree documentation] provides more details. In the examples `${XML}` refers to the same XML structure as in the earlier example. == Tag names == When just a single tag name is used, xpath matches all direct child elements that have that tag name. | ${elem} = | `Get Element` | ${XML} | third | | `Should Be Equal` | ${elem.tag} | third | | | @{children} = | `Get Elements` | ${elem} | child | | `Length Should Be` | ${children} | 2 | | == Paths == Paths are created by combining tag names with a forward slash (`/`). For example, `parent/child` matches all `child` elements under `parent` element. Notice that if there are multiple `parent` elements that all have `child` elements, `parent/child` xpath will match all these `child` elements. | ${elem} = | `Get Element` | ${XML} | second/child | | `Should Be Equal` | ${elem.tag} | child | | | ${elem} = | `Get Element` | ${XML} | third/child/grandchild | | `Should Be Equal` | ${elem.tag} | grandchild | | == Wildcards == An asterisk (`*`) can be used in paths instead of a tag name to denote any element. | @{children} = | `Get Elements` | ${XML} | */child | | `Length Should Be` | ${children} | 3 | | == Current element == The current element is denoted with a dot (`.`). Normally the current element is implicit and does not need to be included in the xpath. == Parent element == The parent element of another element is denoted with two dots (`..`). Notice that it is not possible to refer to the parent of the current element. This syntax is supported only in ElementTree 1.3 (i.e. Python/Jython 2.7 and newer). | ${elem} = | `Get Element` | ${XML} | */second/.. | | `Should Be Equal` | ${elem.tag} | third | | == Search all sub elements == Two forward slashes (`//`) mean that all sub elements, not only the direct children, are searched. If the search is started from the current element, an explicit dot is required. | @{elements} = | `Get Elements` | ${XML} | .//second | | `Length Should Be` | ${elements} | 2 | | | ${b} = | `Get Element` | ${XML} | html//b | | `Should Be Equal` | ${b.text} | bold | | == Predicates == Predicates allow selecting elements using also other criteria than tag names, for example, attributes or position. They are specified after the normal tag name or path using syntax `path[predicate]`. The path can have wildcards and other special syntax explained above. What predicates ElementTree supports is explained in the table below. Notice that predicates in general are supported only in ElementTree 1.3 (i.e. Python/Jython 2.7 and newer). | = Predicate = | = Matches = | = Example = | | @attrib | Elements with attribute `attrib`. | second[@id] | | @attrib="value" | Elements with attribute `attrib` having value `value`. | *[@id="2"] | | position | Elements at the specified position. Position can be an integer (starting from 1), expression `last()`, or relative expression like `last() - 1`. | third/child[1] | | tag | Elements with a child element named `tag`. | third/child[grandchild] | Predicates can also be stacked like `path[predicate1][predicate2]`. A limitation is that possible position predicate must always be first. = Element attributes = All keywords returning elements, such as `Parse XML`, and `Get Element`, return ElementTree's [http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element|Element objects]. These elements can be used as inputs for other keywords, but they also contain several useful attributes that can be accessed directly using the extended variable syntax. The attributes that are both useful and convenient to use in the test data are explained below. Also other attributes, including methods, can be accessed, but that is typically better to do in custom libraries than directly in the test data. The examples use the same `${XML}` structure as the earlier examples. == tag == The tag of the element. | ${root} = | `Parse XML` | ${XML} | | `Should Be Equal` | ${root.tag} | example | == text == The text that the element contains or Python `None` if the element has no text. Notice that the text _does not_ contain texts of possible child elements nor text after or between children. Notice also that in XML whitespace is significant, so the text contains also possible indentation and newlines. To get also text of the possible children, optionally whitespace normalized, use `Get Element Text` keyword. | ${1st} = | `Get Element` | ${XML} | first | | `Should Be Equal` | ${1st.text} | text | | | ${2nd} = | `Get Element` | ${XML} | second/child | | `Should Be Equal` | ${2nd.text} | ${NONE} | | | ${p} = | `Get Element` | ${XML} | html/p | | `Should Be Equal` | ${p.text} | \\n${SPACE*6}Text with${SPACE} | == tail == The text after the element before the next opening or closing tag. Python `None` if the element has no tail. Similarly as with `text`, also `tail` contains possible indentation and newlines. | ${b} = | `Get Element` | ${XML} | html/p/b | | `Should Be Equal` | ${b.tail} | ${SPACE}and${SPACE} | == attrib == A Python dictionary containing attributes of the element. | ${2nd} = | `Get Element` | ${XML} | second | | `Should Be Equal` | ${2nd.attrib['id']} | 2 | | | ${3rd} = | `Get Element` | ${XML} | third | | `Should Be Empty` | ${3rd.attrib} | | | = Handling XML namespaces = ElementTree handles possible namespaces in XML documents by adding the namespace URI to tag names in so called Clark Notation. That is inconvenient especially with xpaths, and by default this library strips those namespaces away and moves them to `xmlns` attribute instead. That can be avoided by passing `keep_clark_notation` argument to `Parse XML` keyword. The pros and cons of both approaches are discussed in more detail below. == How ElementTree handles namespaces == If an XML document has namespaces, ElementTree adds namespace information to tag names in [http://www.jclark.com/xml/xmlns.htm|Clark Notation] (e.g. `{http://ns.uri}tag` and removes original `xmlns` attributes. This is done both with default namespaces and with namespaces with a prefix. How it works in practice is illustrated by the following example, where `${NS}` variable contains this XML document: | <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" | xmlns="http://www.w3.org/1999/xhtml"> | <xsl:template match="/"> | <html></html> | </xsl:template> | </xsl:stylesheet> | ${root} = | `Parse XML` | ${NS} | keep_clark_notation=yes | | `Should Be Equal` | ${root.tag} | {http://www.w3.org/1999/XSL/Transform}stylesheet | | `Element Should Exist` | ${root} | {http://www.w3.org/1999/XSL/Transform}template/{http://www.w3.org/1999/xhtml}html | | `Should Be Empty` | ${root.attrib} | As you can see, including the namespace URI in tag names makes xpaths really long and complex. If you save the XML, ElementTree moves namespace information back to `xmlns` attributes. Unfortunately it does not restore the original prefixes: | <ns0:stylesheet xmlns:ns0="http://www.w3.org/1999/XSL/Transform"> | <ns0:template match="/"> | <ns1:html xmlns:ns1="http://www.w3.org/1999/xhtml"></ns1:html> | </ns0:template> | </ns0:stylesheet> The resulting output is semantically same as the original, but mangling prefixes like this may still not be desirable. Notice also that the actual output depends slightly on ElementTree version. == Default namespace handling == Because the way ElementTree handles namespaces makes xpaths so complicated, this library, by default, strips namespaces from tag names and moves that information back to `xmlns` attributes. How this works in practice is shown by the example below, where `${NS}` variable contains the same XML document as in the previous example. | ${root} = | `Parse XML` | ${NS} | | `Should Be Equal` | ${root.tag} | stylesheet | | `Element Should Exist` | ${root} | template/html | | `Element Attribute Should Be` | ${root} | xmlns | http://www.w3.org/1999/XSL/Transform | | `Element Attribute Should Be` | ${root} | xmlns | http://www.w3.org/1999/xhtml | xpath=template/html | Now that tags do not contain namespace information, xpaths are simple again. A minor limitation of this approach is that namespace prefixes are lost. As a result the saved output is not exactly same as the original one in this case either: | <stylesheet xmlns="http://www.w3.org/1999/XSL/Transform"> | <template match="/"> | <html xmlns="http://www.w3.org/1999/xhtml"></html> | </template> | </stylesheet> Also this output is semantically same as the original. If the original XML had only default namespaces, the output would also looks identical. == Attribute namespaces == Attributes in XML documents are, by default, in the same namespaces as the element they belong to. It is possible to use different namespaces by using prefixes, but this is pretty rare. If an attribute has a namespace prefix, ElementTree will replace it with Clark Notation the same way it handles elements. Because stripping namespaces from attributes could cause attribute conflicts, this library does not handle attribute namespaces at all. Thus the following example works the same way regardless how namespaces are handled. | ${root} = | `Parse XML` | <root id="1" ns:id="2" xmlns:ns="http://my.ns"/> | | `Element Attribute Should Be` | ${root} | id | 1 | | `Element Attribute Should Be` | ${root} | {http://my.ns}id | 2 | """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() _whitespace = re.compile('\s+') _xml_declaration = re.compile('^<\?xml .*\?>\n') def parse_xml(self, source, keep_clark_notation=False): """Parses the given XML file or string into an element structure. The `source` can either be a path to an XML file or a string containing XML. In both cases the XML is parsed into ElementTree [http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element|element structure] and the root element is returned. As discussed in `Handling XML namespaces` section, this keyword, by default, strips possible namespaces added by ElementTree into tag names. This typically eases handling XML documents with namespaces considerably. If you do not want that to happen, or want to avoid the small overhead of going through the element structure when your XML does not have namespaces, you can disable this feature by giving `keep_clark_notation` argument a true value (e.g. any non-empty string). Examples: | ${root} = | Parse XML | <root><child/></root> | | ${xml} = | Parse XML | ${CURDIR}/test.xml | no namespace cleanup | Use `Get Element` keyword if you want to get a certain element and not the whole structure. See `Parsing XML` section for more details and examples Stripping namespaces is a new feature in Robot Framework 2.7.5. """ with ETSource(source) as source: root = ET.parse(source).getroot() if not keep_clark_notation: self._strip_namespaces(root) return root def _strip_namespaces(self, elem, current_ns=None): if elem.tag.startswith('{') and '}' in elem.tag: ns, elem.tag = elem.tag[1:].split('}', 1) if ns != current_ns: elem.set('xmlns', ns) current_ns = ns for child in elem: self._strip_namespaces(child, current_ns) def get_element(self, source, xpath='.'): """Returns an element in the `source` matching the `xpath`. The `source` can be a path to an XML file, a string containing XML, or an already parsed XML element. The `xpath` specifies which element to find. See the `introduction` for more details about both the possible sources and the supported xpath syntax. The keyword fails if more, or less, than one element matches the `xpath`. Use `Get Elements` if you want all matching elements to be returned. Examples using `${XML}` structure from the `introduction`: | ${element} = | Get Element | ${XML} | second | | ${child} = | Get Element | ${element} | child | `Parse XML` is recommended for parsing XML when the whole structure is needed. It must be used if there is a need to configure how XML namespaces are handled. """ elements = self.get_elements(source, xpath) if len(elements) != 1: self._raise_wrong_number_of_matches(len(elements), xpath) return elements[0] def _raise_wrong_number_of_matches(self, count, xpath, message=None): if not message: message = self._wrong_number_of_matches(count, xpath) raise AssertionError(message) def _wrong_number_of_matches(self, count, xpath): if not count: return "No element matching '%s' found." % xpath if count == 1: return "One element matching '%s' found." % xpath return "Multiple elements (%d) matching '%s' found." % (count, xpath) def get_elements(self, source, xpath): """Returns a list of elements in the `source` matching the `xpath`. The `source` can be a path to an XML file, a string containing XML, or an already parsed XML element. The `xpath` specifies which element to find. See the `introduction` for more details. Elements matching the `xpath` are returned as a list. If no elements match, an empty list is returned. Use `Get Element` if you want to get exactly one match. Examples using `${XML}` structure from the `introduction`: | ${children} = | Get Elements | ${XML} | third/child | | Length Should Be | ${children} | 2 | | | ${children} = | Get Elements | ${XML} | first/child | | Should Be Empty | ${children} | | | """ if isinstance(source, basestring): source = self.parse_xml(source) if not xpath: raise RuntimeError('No xpath given.') if xpath == '.': # ET < 1.3 does not support '.' alone. return [source] return source.findall(self._get_xpath(xpath)) if ET.VERSION >= '1.3': def _get_xpath(self, xpath): return xpath else: def _get_xpath(self, xpath): try: return str(xpath) except UnicodeError: if not xpath.replace('/', '').isalnum(): logger.warn('XPATHs containing non-ASCII characters and ' 'other than tag names do not always work with ' 'Python/Jython versions prior to 2.7. Verify ' 'results manually and consider upgrading to 2.7.') return xpath def get_child_elements(self, source, xpath='.'): """Returns the child elements of the specified element as a list. The element whose children to return is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. All the direct child elements of the specified element are returned. If the element has no children, an empty list is returned. Examples using `${XML}` structure from the `introduction`: | ${children} = | Get Child Elements | ${XML} | | | Length Should Be | ${children} | 4 | | | ${children} = | Get Child Elements | ${XML} | xpath=first | | Should Be Empty | ${children} | | | """ return list(self.get_element(source, xpath)) def get_element_count(self, source, xpath='.'): """Returns and logs how many elements the given `xpath` matches. Arguments `source` and `xpath` have exactly the same semantics as with `Get Elements` keyword that this keyword uses internally. See also `Element Should Exist` and `Element Should Not Exist`. New in Robot Framework 2.7.5. """ count = len(self.get_elements(source, xpath)) logger.info("%d element%s matched '%s'." % (count, s(count), xpath)) return count def element_should_exist(self, source, xpath='.', message=None): """Verifies that one or more element match the given `xpath`. Arguments `source` and `xpath` have exactly the same semantics as with `Get Elements` keyword. Keyword passes if the `xpath` matches one or more elements in the `source`. The default error message can be overridden with the `message` argument. See also `Element Should Not Exist` as well as `Get Element Count` that this keyword uses internally. New in Robot Framework 2.7.5. """ count = self.get_element_count(source, xpath) if not count: self._raise_wrong_number_of_matches(count, xpath, message) def element_should_not_exist(self, source, xpath='.', message=None): """Verifies that no element match the given `xpath`. Arguments `source` and `xpath` have exactly the same semantics as with `Get Elements` keyword. Keyword fails if the `xpath` matches any element in the `source`. The default error message can be overridden with the `message` argument. See also `Element Should Exist` as well as `Get Element Count` that this keyword uses internally. New in Robot Framework 2.7.5. """ count = self.get_element_count(source, xpath) if count: self._raise_wrong_number_of_matches(count, xpath, message) def get_element_text(self, source, xpath='.', normalize_whitespace=False): """Returns all text of the element, possibly whitespace normalized. The element whose text to return is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. This keyword returns all the text of the specified element, including all the text its children and grandchildren contains. If the element has no text, an empty string is returned. As discussed in the `introduction`, the returned text is thus not always the same as the `text` attribute of the element. Be default all whitespace, including newlines and indentation, inside the element is returned as-is. If `normalize_whitespace` is given any true value (e.g. any non-empty string), then leading and trailing whitespace is stripped, newlines and tabs converted to spaces, and multiple spaces collapsed into one. This is especially useful when dealing with HTML data. Examples using `${XML}` structure from the `introduction`: | ${text} = | Get Element Text | ${XML} | first | | Should Be Equal | ${text} | text | | | ${text} = | Get Element Text | ${XML} | second/child | | Should Be Empty | ${text} | | | | ${paragraph} = | Get Element | ${XML} | html/p | | ${text} = | Get Element Text | ${paragraph} | normalize_whitespace=yes | | Should Be Equal | ${text} | Text with bold and italics. | See also `Get Elements Texts`, `Element Text Should Be` and `Element Text Should Match`. """ element = self.get_element(source, xpath) text = ''.join(self._yield_texts(element)) if normalize_whitespace: text = self._normalize_whitespace(text) return text def _yield_texts(self, element, top=True): if element.text: yield element.text for child in element: for text in self._yield_texts(child, top=False): yield text if element.tail and not top: yield element.tail def _normalize_whitespace(self, text): return self._whitespace.sub(' ', text.strip()) def get_elements_texts(self, source, xpath, normalize_whitespace=False): """Returns text of all elements matching `xpath` as a list. The elements whose text to return is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Elements` keyword. The text of the matched elements is returned using the same logic as with `Get Element Text`. This includes optional whitespace normalization using the `normalize_whitespace` option. Examples using `${XML}` structure from the `introduction`: | @{texts} = | Get Elements Texts | ${XML} | third/child | | Length Should Be | ${texts} | 2 | | | Should Be Equal | @{texts}[0] | more text | | | Should Be Equal | @{texts}[1] | ${EMPTY} | | """ return [self.get_element_text(elem, normalize_whitespace=normalize_whitespace) for elem in self.get_elements(source, xpath)] def element_text_should_be(self, source, expected, xpath='.', normalize_whitespace=False, message=None): """Verifies that the text of the specified element is `expected`. The element whose text is verified is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The text to verify is got from the specified element using the same logic as with `Get Element Text`. This includes optional whitespace normalization using the `normalize_whitespace` option. The keyword passes if the text of the element is equal to the `expected` value, and otherwise it fails. The default error message can be overridden with the `message` argument. Use `Element Text Should Match` to verify the text against a pattern instead of an exact value. Examples using `${XML}` structure from the `introduction`: | Element Text Should Be | ${XML} | text | xpath=first | | Element Text Should Be | ${XML} | ${EMPTY} | xpath=second/child | | ${paragraph} = | Get Element | ${XML} | xpath=html/p | | Element Text Should Be | ${paragraph} | Text with bold and italics. | normalize_whitespace=yes | """ text = self.get_element_text(source, xpath, normalize_whitespace) should_be_equal(text, expected, message, values=False) def element_text_should_match(self, source, pattern, xpath='.', normalize_whitespace=False, message=None): """Verifies that the text of the specified element matches `expected`. This keyword works exactly like `Element Text Should Be` except that the expected value can be given as a pattern that the text of the element must match. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern, '*' matches anything and '?' matches any single character. Examples using `${XML}` structure from the `introduction`: | Element Text Should Match | ${XML} | t??? | xpath=first | | ${paragraph} = | Get Element | ${XML} | xpath=html/p | | Element Text Should Match | ${paragraph} | Text with * and *. | normalize_whitespace=yes | """ text = self.get_element_text(source, xpath, normalize_whitespace) should_match(text, pattern, message, values=False) def get_element_attribute(self, source, name, xpath='.', default=None): """Returns the named attribute of the specified element. The element whose attribute to return is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The value of the attribute `name` of the specified element is returned. If the element does not have such element, the `default` value is returned instead. Examples using `${XML}` structure from the `introduction`: | ${attribute} = | Get Element Attribute | ${XML} | id | xpath=first | | Should Be Equal | ${attribute} | 1 | | | | ${attribute} = | Get Element Attribute | ${XML} | xx | xpath=first | default=value | | Should Be Equal | ${attribute} | value | | | See also `Get Element Attributes`, `Element Attribute Should Be`, `Element Attribute Should Match` and `Element Should Not Have Attribute`. """ return self.get_element(source, xpath).get(name, default) def get_element_attributes(self, source, xpath='.'): """Returns all attributes of the specified element. The element whose attributes to return is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. Attributes are returned as a Python dictionary. It is a copy of the original attributes so modifying it has no effect on the XML structure. Examples using `${XML}` structure from the `introduction`: | ${attributes} = | Get Element Attributes | ${XML} | first | | Dictionary Should Contain Key | ${attributes} | id | | | ${attributes} = | Get Element Attributes | ${XML} | third | | Should Be Empty | ${attributes} | | | Use `Get Element Attribute` to get the value of a single attribute. """ return self.get_element(source, xpath).attrib.copy() def element_attribute_should_be(self, source, name, expected, xpath='.', message=None): """Verifies that the specified attribute is `expected`. The element whose attribute is verified is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The keyword passes if the attribute `name` of the element is equal to the `expected` value, and otherwise it fails. The default error message can be overridden with the `message` argument. To test that the element does not have a certain attribute, Python `None` (i.e. variable `${NONE}`) can be used as the `expected` value. A cleaner alternative is using `Element Should Not Have Attribute`. Examples using `${XML}` structure from the `introduction`: | Element Attribute Should Be | ${XML} | id | 1 | xpath=first | | Element Attribute Should Be | ${XML} | id | ${NONE} | | See also `Element Attribute Should Match` and `Get Element Attribute`. """ attr = self.get_element_attribute(source, name, xpath) should_be_equal(attr, expected, message, values=False) def element_attribute_should_match(self, source, name, pattern, xpath='.', message=None): """Verifies that the specified attribute matches `expected`. This keyword works exactly like `Element Attribute Should Be` except that the expected value can be given as a pattern that the attribute of the element must match. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern, '*' matches anything and '?' matches any single character. Examples using `${XML}` structure from the `introduction`: | Element Attribute Should Match | ${XML} | id | ? | xpath=first | | Element Attribute Should Match | ${XML} | id | c*d | xpath=third/second | """ attr = self.get_element_attribute(source, name, xpath) if attr is None: raise AssertionError("Attribute '%s' does not exist." % name) should_match(attr, pattern, message, values=False) def element_should_not_have_attribute(self, source, name, xpath='.', message=None): """Verifies that the specified element does not have attribute `name`. The element whose attribute is verified is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The keyword fails if the specified element has attribute `name`. The default error message can be overridden with the `message` argument. Examples using `${XML}` structure from the `introduction`: | Element Should Not Have Attribute | ${XML} | id | | Element Should Not Have Attribute | ${XML} | xxx | xpath=first | See also `Get Element Attribute`, `Get Element Attributes`, `Element Text Should Be` and `Element Text Should Match`. New in Robot Framework 2.7.5. """ attr = self.get_element_attribute(source, name, xpath) if attr is not None: raise AssertionError(message or "Attribute '%s' exists and " "has value '%s'." % (name, attr)) def elements_should_be_equal(self, source, expected, exclude_children=False, normalize_whitespace=False): """Verifies that the given `source` element is equal to `expected`. Both `source` and `expected` can be given as a path to an XML file, as a string containing XML, or as an already parsed XML element structure. See `introduction` for more information about parsing XML in general. The keyword passes if the `source` element and `expected` element are equal. This includes testing the tag names, texts, and attributes of the elements. By default also child elements are verified the same way, but this can be disabled by setting `exclude_children` to any true value (e.g. any non-empty string). All texts inside the given elements are verified, but possible text outside them is not. By default texts must match exactly, but setting `normalize_whitespace` to any true value makes text verification independent on newlines, tabs, and the amount of spaces. For more details about handling text see `Get Element Text` keyword and discussion about elements' `text` and `tail` attributes in the `introduction`. Examples using `${XML}` structure from the `introduction`: | ${first} = | Get Element | ${XML} | first | | Elements Should Be Equal | ${first} | <first id="1">text</first> | | ${p} = | Get Element | ${XML} | html/p | | Elements Should Be Equal | ${p} | <p>Text with <b>bold</b> and <i>italics</i>.</p> | normalize_whitespace=yes | | Elements Should Be Equal | ${p} | <p>Text with</p> | exclude | normalize | The last example may look a bit strange because the `<p>` element only has text `Text with`. The reason is that rest of the text inside `<p>` actually belongs to the child elements. See also `Elements Should Match`. """ self._compare_elements(source, expected, should_be_equal, exclude_children, normalize_whitespace) def elements_should_match(self, source, expected, exclude_children=False, normalize_whitespace=False): """Verifies that the given `source` element matches `expected`. This keyword works exactly like `Elements Should Be Equal` except that texts and attribute values in the expected value can be given as patterns. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern, '*' matches anything and '?' matches any single character. Examples using `${XML}` structure from the `introduction`: | ${first} = | Get Element | ${XML} | first | | Elements Should Match | ${first} | <first id="?">*</first> | See `Elements Should Be Equal` for more examples. """ self._compare_elements(source, expected, should_match, exclude_children, normalize_whitespace) def _compare_elements(self, source, expected, comparator, exclude_children, normalize_whitespace): normalizer = self._normalize_whitespace if normalize_whitespace else None comparator = ElementComparator(comparator, normalizer, exclude_children) comparator.compare(self.get_element(source), self.get_element(expected)) def set_element_tag(self, source, tag, xpath='.'): """Sets the tag of the specified element to `tag`. The element whose tag to set is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The given `source` structure is modified and also returned. Examples using `${XML}` structure from `Example`: | Set Element Tag | ${XML} | newTag | | Should Be Equal | ${XML.tag} | newTag | | Set Element Tag | ${XML} | xxx | xpath=second/child | | Element Should Exist | ${XML} | second/xxx | | Element Should Not Exist | ${XML} | second/child | New in Robot Framework 2.7.5. """ source = self.get_element(source) self.get_element(source, xpath).tag = tag return source def set_element_text(self, source, text=None, tail=None, xpath='.'): """Sets text and/or tail text of the specified element. The element whose text to set is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The given `source` structure is modified and also returned. Element's text and tail text are changed only if new `text` and/or `tail` values are given. See `Element attributes` section for more information about text and tail in general. Examples using `${XML}` structure from `Example`: | Set Element Text | ${XML} | new text | xpath=first | | Element Text Should Be | ${XML} | new text | xpath=first | | Set Element Text | ${XML} | tail=& | xpath=html/p/b | | Element Text Should Be | ${XML} | Text with bold&italics. | xpath=html/p | normalize_whitespace=yes | | Set Element Text | ${XML} | slanted | !! | xpath=html/p/i | | Element Text Should Be | ${XML} | Text with bold&slanted!! | xpath=html/p | normalize_whitespace=yes | New in Robot Framework 2.7.5. """ source = self.get_element(source) element = self.get_element(source, xpath) if text is not None: element.text = text if tail is not None: element.tail = tail return source def set_element_attribute(self, source, name, value, xpath='.'): """Sets attribute `name` of the specified element to `value` The element whose attribute to set is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The given `source` structure is modified and also returned. It is possible to both set new attributes and to overwrite existing. Use `Remove Element Attribute` or `Remove Element Attributes` for removing them. Examples using `${XML}` structure from `Example`: | Set Element Attribute | ${XML} | attr | value | | Element Attribute Should Be | ${XML} | attr | value | | Set Element Attribute | ${XML} | id | new | xpath=first | | Element Attribute Should Be | ${XML} | id | new | xpath=first | New in Robot Framework 2.7.5. """ if not name: raise RuntimeError('Attribute name can not be empty.') source = self.get_element(source) self.get_element(source, xpath).attrib[name] = value return source def remove_element_attribute(self, source, name, xpath='.'): """Removes attribute `name` from the specified element. The element whose attribute to remove is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The given `source` structure is modified and also returned. It is not a failure to remove a non-existing attribute. Use `Remove Element Attributes` to remove all attributes and `Set Element Attribute` to set them. Examples using `${XML}` structure from `Example`: | Remove Element Attribute | ${XML} | id | xpath=first | | Element Should Not Have Attribute | ${XML} | id | xpath=first | New in Robot Framework 2.7.5. """ source = self.get_element(source) attrib = self.get_element(source, xpath).attrib if name in attrib: attrib.pop(name) return source def remove_element_attributes(self, source, xpath='.'): """Removes all attributes from the specified element. The element whose attributes to remove is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The given `source` structure is modified and also returned. Use `Remove Element Attribute` to remove a single attribute and `Set Element Attribute` to set them. Examples using `${XML}` structure from `Example`: | Remove Element Attributes | ${XML} | xpath=first | | Element Should Not Have Attribute | ${XML} | id | xpath=first | New in Robot Framework 2.7.5. """ source = self.get_element(source) self.get_element(source, xpath).attrib.clear() return source def add_element(self, source, element, index=None, xpath='.'): """Adds a child element to the specified element. The element to whom to add the new element is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The given `source` structure is modified and also returned. The `element` to add can be specified as a path to an XML file or as a string containing XML, or it can be an already parsed XML element. The element is copied before adding so modifying either the original or the added element has no effect on the other . The element is added as the last child by default, but a custom index can be used to alter the position. Indices start from zero (0 = first position, 1 = second position, etc.), and negative numbers refer to positions at the end (-1 = second last position, -2 = third last, etc.). Examples using `${XML}` structure from `Example`: | Add Element | ${XML} | <new id="x"><c1/></new> | | Add Element | ${XML} | <c2/> | xpath=new | | Add Element | ${XML} | <c3/> | index=1 | xpath=new | | ${new} = | Get Element | ${XML} | new | | Elements Should Be Equal | ${new} | <new id="x"><c1/><c3/><c2/></new> | Use `Remove Element` or `Remove Elements` to remove elements. New in Robot Framework 2.7.5. """ source = self.get_element(source) parent = self.get_element(source, xpath) element = self.copy_element(element) if index is None: parent.append(element) else: parent.insert(int(index), element) return source def remove_element(self, source, xpath='', remove_tail=False): """Removes the element matching `xpath` from the `source` structure. The element to remove from the `source` is specified with `xpath` using the same semantics as with `Get Element` keyword. The given `source` structure is modified and also returned. The keyword fails if `xpath` does not match exactly one element. Use `Remove Elements` to remove all matched elements. Element's tail text is not removed by default, but that can be changed by giving `remove_tail` a true value (e.g. any non-empty string). See `Element attributes` section for more information about tail in general. Examples using `${XML}` structure from `Example`: | Remove Element | ${XML} | xpath=second | | Element Should Not Exist | ${XML} | xpath=second | | Remove Element | ${XML} | xpath=html/p/b | remove_tail=yes | | Element Text Should Be | ${XML} | Text with italics. | xpath=html/p | normalize_whitespace=yes | New in Robot Framework 2.7.5. """ source = self.get_element(source) self._remove_element(source, self.get_element(source, xpath), remove_tail) return source def remove_elements(self, source, xpath='', remove_tail=False): """Removes all elements matching `xpath` from the `source` structure. The elements to remove from the `source` are specified with `xpath` using the same semantics as with `Get Elements` keyword. The given `source` structure is modified and also returned. It is not a failure if `xpath` matches no elements. Use `Remove Element` to remove exactly one element and `Add Element` to add new ones. Element's tail text is not removed by default, but that can be changed by using `remove_tail` argument similarly as with `Remove Element`. Examples using `${XML}` structure from `Example`: | Remove Elements | ${XML} | xpath=*/child | | Element Should Not Exist | ${XML} | xpath=second/child | | Element Should Not Exist | ${XML} | xpath=third/child | New in Robot Framework 2.7.5. """ source = self.get_element(source) for element in self.get_elements(source, xpath): self._remove_element(source, element, remove_tail) return source def _remove_element(self, root, element, remove_tail=False): parent = self._find_parent(root, element) if element.tail and not remove_tail: self._preserve_tail(element, parent) parent.remove(element) def _find_parent(self, root, element): for parent in root.getiterator(): for child in parent: if child is element: return parent raise RuntimeError('Cannot remove root element.') def _preserve_tail(self, element, parent): index = list(parent).index(element) if index == 0: parent.text = (parent.text or '') + element.tail else: sibling = parent[index-1] sibling.tail = (sibling.tail or '') + element.tail def clear_element(self, source, xpath='.', clear_tail=False): """Clears the contents of the specified element. The element to clear is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The given `source` structure is modified and also returned. Clearing the element means removing its text, attributes, and children. Element's tail text is not removed by default, but that can be changed by giving `clear_tail` a true value (e.g. any non-empty string). See `Element attributes` section for more information about tail in general. Examples using `${XML}` structure from `Example`: | Clear Element | ${XML} | xpath=first | | ${first} = | Get Element | ${XML} | xpath=first | | Elements Should Be Equal | ${first} | <first/> | | Clear Element | ${XML} | xpath=html/p/b | clear_tail=yes | | Element Text Should Be | ${XML} | Text with italics. | xpath=html/p | normalize_whitespace=yes | | Clear Element | ${XML} | | Elements Should Be Equal | ${XML} | <example/> | Use `Remove Element` to remove the whole element. New in Robot Framework 2.7.5. """ source = self.get_element(source) element = self.get_element(source, xpath) tail = element.tail element.clear() if not clear_tail: element.tail = tail return source def copy_element(self, source, xpath='.'): """Returns a copy of the specified element. The element to copy is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. If the copy or the original element is modified afterwards, the changes have no effect on the other. Examples using `${XML}` structure from `Example`: | ${elem} = | Get Element | ${XML} | xpath=first | | ${copy1} = | Copy Element | ${elem} | | ${copy2} = | Copy Element | ${XML} | xpath=first | | Set Element Text | ${XML} | new text | xpath=first | | Set Element Attribute | ${copy1} | id | new | | Elements Should Be Equal | ${elem} | <first id="1">new text</first> | | Elements Should Be Equal | ${copy1} | <first id="new">text</first> | | Elements Should Be Equal | ${copy2} | <first id="1">text</first> | New in Robot Framework 2.7.5. """ return copy.deepcopy(self.get_element(source, xpath)) def element_to_string(self, source, xpath='.'): """Returns the string representation of the specified element. The element to convert to a string is specified using `source` and `xpath`. They have exactly the same semantics as with `Get Element` keyword. The returned string is in Unicode format and it does not contain any XML declaration. See also `Log Element` and `Save XML`. """ string = ET.tostring(self.get_element(source, xpath), encoding='UTF-8') return self._xml_declaration.sub('', string.decode('UTF-8')).strip() def log_element(self, source, level='INFO', xpath='.'): """Logs the string representation of the specified element. The element specified with `source` and `xpath` is first converted into a string using `Element To String` keyword internally. The resulting string is then logged using the given `level`. The logged string is also returned. """ string = self.element_to_string(source, xpath) logger.write(string, level) return string def save_xml(self, source, path, encoding='UTF-8'): """Saves the given element to the specified file. The element to save is specified with `source` using the same semantics as with `Get Element` keyword. The file where the element is saved is denoted with `path` and the encoding to use with `encoding`. The resulting file contains an XML declaration. Use `Element To String` if you just need a string representation of the element, New in Robot Framework 2.7.5. """ tree = ET.ElementTree(self.get_element(source)) kwargs = {'xml_declaration': True} if ET.VERSION >= '1.3' else {} # Need to explicitly open/close files because older ET versions don't # close files they open and Jython/IPY don't close them implicitly. with open(path, 'w') as output: tree.write(output, encoding, **kwargs) class ElementComparator(object): def __init__(self, comparator, normalizer=None, exclude_children=False): self._comparator = comparator self._normalizer = normalizer or (lambda text: text) self._exclude_children = exclude_children def compare(self, actual, expected, location=None): if not location: location = Location(actual.tag) self._compare_tags(actual, expected, location) self._compare_attributes(actual, expected, location) self._compare_texts(actual, expected, location) if location.is_not_root: self._compare_tails(actual, expected, location) if not self._exclude_children: self._compare_children(actual, expected, location) def _compare_tags(self, actual, expected, location): self._compare(actual.tag, expected.tag, 'Different tag name', location, should_be_equal) def _compare(self, actual, expected, message, location, comparator=None): if location.is_not_root: message = "%s at '%s'" % (message, location.path) if not comparator: comparator = self._comparator comparator(actual, expected, message) def _compare_attributes(self, actual, expected, location): self._compare(sorted(actual.attrib), sorted(expected.attrib), 'Different attribute names', location, should_be_equal) for key in actual.attrib: self._compare(actual.attrib[key], expected.attrib[key], "Different value for attribute '%s'" % key, location) def _compare_texts(self, actual, expected, location): self._compare(self._text(actual.text), self._text(expected.text), 'Different text', location) def _text(self, text): return self._normalizer(text or '') def _compare_tails(self, actual, expected, location): self._compare(self._text(actual.tail), self._text(expected.tail), 'Different tail text', location) def _compare_children(self, actual, expected, location): self._compare(len(actual), len(expected), 'Different number of child elements', location, should_be_equal) for act, exp in zip(actual, expected): self.compare(act, exp, location.child(act.tag)) class Location(object): def __init__(self, path, is_root=True): self.path = path self.is_not_root = not is_root self._children = {} def child(self, tag): if tag not in self._children: self._children[tag] = 1 else: self._children[tag] += 1 tag += '[%d]' % self._children[tag] return Location('%s/%s' % (self.path, tag), is_root=False)
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 fnmatch import fnmatchcase from random import randint from string import ascii_lowercase, ascii_uppercase, digits from robot.api import logger from robot.utils import unic from robot.version import get_version class String(object): """A test library for string manipulation and verification. `String` is Robot Framework's standard library for manipulating strings (e.g. `Replace String Using Regexp`, `Split To Lines`) and verifying their contents (e.g. `Should Be String`). Following keywords from `BuiltIn` library can also be used with strings: - `Catenate` - `Get Length` - `Length Should Be` - `Should (Not) Be Empty` - `Should (Not) Be Equal (As Strings/Integers/Numbers)` - `Should (Not) Match (Regexp)` - `Should (Not) Contain` - `Should (Not) Start With` - `Should (Not) End With` - `Convert To String` - `Convert To Bytes` """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() def encode_string_to_bytes(self, string, encoding, errors='strict'): """Encodes the given Unicode `string` to bytes using the given `encoding`. `errors` argument controls what to do if encoding some characters fails. All values accepted by `encode` method in Python are valid, but in practice the following values are most useful: - `strict`: fail if characters cannot be encoded (default) - `ignore`: ignore characters that cannot be encoded - `replace`: replace characters that cannot be encoded with a replacement character Examples: | ${bytes} = | Encode String To Bytes | ${string} | UTF-8 | | ${bytes} = | Encode String To Bytes | ${string} | ASCII | errors=ignore | Use `Convert To Bytes` in `BuiltIn` if you want to create bytes based on character or integer sequences. Use `Decode Bytes To String` if you need to convert byte strings to Unicode strings and `Convert To String` in `BuiltIn` if you need to convert arbitrary objects to Unicode. New in Robot Framework 2.7.7. """ return string.encode(encoding, errors) def decode_bytes_to_string(self, bytes, encoding, errors='strict'): """Decodes the given `bytes` to a Unicode string using the given `encoding`. `errors` argument controls what to do if decoding some bytes fails. All values accepted by `decode` method in Python are valid, but in practice the following values are most useful: - `strict`: fail if characters cannot be decoded (default) - `ignore`: ignore characters that cannot be decoded - `replace`: replace characters that cannot be decoded with a replacement character Examples: | ${string} = | Decode Bytes To String | ${bytes} | UTF-8 | | ${string} = | Decode Bytes To String | ${bytes} | ASCII | errors=ignore | Use `Encode String To Bytes` if you need to convert Unicode strings to byte strings, and `Convert To String` in `BuiltIn` if you need to convert arbitrary objects to Unicode strings. New in Robot Framework 2.7.7. """ return bytes.decode(encoding, errors) def get_line_count(self, string): """Returns and logs the number of lines in the given `string`.""" count = len(string.splitlines()) logger.info('%d lines' % count) return count def split_to_lines(self, string, start=0, end=None): """Converts the `string` into a list of lines. It is possible to get only a selection of lines from `start` to `end` so that `start` index is inclusive and `end` is exclusive. Line numbering starts from 0, and it is possible to use negative indices to refer to lines from the end. Lines are returned without the newlines. The number of returned lines is automatically logged. Examples: | @{lines} = | Split To Lines | ${manylines} | | | | @{ignore first} = | Split To Lines | ${manylines} | 1 | | | @{ignore last} = | Split To Lines | ${manylines} | | -1 | | @{5th to 10th} = | Split To Lines | ${manylines} | 4 | 10 | | @{first two} = | Split To Lines | ${manylines} | | 1 | | @{last two} = | Split To Lines | ${manylines} | -2 | | Use `Get Line` if you only need to get a single line. """ start = self._convert_to_index(start, 'start') end = self._convert_to_index(end, 'end') lines = string.splitlines()[start:end] logger.info('%d lines returned' % len(lines)) return lines def get_line(self, string, line_number): """Returns the specified line from the given `string`. Line numbering starts from 0 and it is possible to use negative indices to refer to lines from the end. The line is returned without the newline character. Examples: | ${first} = | Get Line | ${string} | 0 | | ${2nd last} = | Get Line | ${string} | -2 | """ line_number = self._convert_to_integer(line_number, 'line_number') return string.splitlines()[line_number] def get_lines_containing_string(self, string, pattern, case_insensitive=False): """Returns lines of the given `string` that contain the `pattern`. The `pattern` is always considered to be a normal string and a line matches if the `pattern` is found anywhere in it. By default the match is case-sensitive, but setting `case_insensitive` to any value makes it case-insensitive. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: | ${lines} = | Get Lines Containing String | ${result} | An example | | ${ret} = | Get Lines Containing String | ${ret} | FAIL | case-insensitive | See `Get Lines Matching Pattern` and `Get Lines Matching Regexp` if you need more complex pattern matching. """ if case_insensitive: pattern = pattern.lower() contains = lambda line: pattern in line.lower() else: contains = lambda line: pattern in line return self._get_matching_lines(string, contains) def get_lines_matching_pattern(self, string, pattern, case_insensitive=False): """Returns lines of the given `string` that match the `pattern`. The `pattern` is a _glob pattern_ where: | * | matches everything | | ? | matches any single character | | [chars] | matches any character inside square brackets (e.g. '[abc]' matches either 'a', 'b' or 'c') | | [!chars] | matches any character not inside square brackets | A line matches only if it matches the `pattern` fully. By default the match is case-sensitive, but setting `case_insensitive` to any value makes it case-insensitive. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: | ${lines} = | Get Lines Matching Pattern | ${result} | Wild???? example | | ${ret} = | Get Lines Matching Pattern | ${ret} | FAIL: * | case-insensitive | See `Get Lines Matching Regexp` if you need more complex patterns and `Get Lines Containing String` if searching literal strings is enough. """ if case_insensitive: pattern = pattern.lower() matches = lambda line: fnmatchcase(line.lower(), pattern) else: matches = lambda line: fnmatchcase(line, pattern) return self._get_matching_lines(string, matches) def get_lines_matching_regexp(self, string, pattern): """Returns lines of the given `string` that match the regexp `pattern`. See `BuiltIn.Should Match Regexp` for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. A line matches only if it matches the `pattern` fully. Notice that to make the match case-insensitive, you need to embed case-insensitive flag into the pattern. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: | ${lines} = | Get Lines Matching Regexp | ${result} | Reg\\\\w{3} example | | ${ret} = | Get Lines Matching Regexp | ${ret} | (?i)FAIL: .* | See `Get Lines Matching Pattern` and `Get Lines Containing String` if you do not need full regular expression powers (and complexity). """ regexp = re.compile('^%s$' % pattern) return self._get_matching_lines(string, regexp.match) def _get_matching_lines(self, string, matches): lines = string.splitlines() matching = [line for line in lines if matches(line)] logger.info('%d out of %d lines matched' % (len(matching), len(lines))) return '\n'.join(matching) def replace_string(self, string, search_for, replace_with, count=-1): """Replaces `search_for` in the given `string` with `replace_with`. `search_for` is used as a literal string. See `Replace String Using Regexp` if more powerful pattern matching is needed. If you need to just remove a string see `Remove String`. If the optional argument `count` is given, only that many occurrences from left are replaced. Negative `count` means that all occurrences are replaced (default behaviour) and zero means that nothing is done. A modified version of the string is returned and the original string is not altered. Examples: | ${str} = | Replace String | Hello, world! | world | tellus | | Should Be Equal | ${str} | Hello, tellus! | | | | ${str} = | Replace String | Hello, world! | l | ${EMPTY} | count=1 | | Should Be Equal | ${str} | Helo, world! | | | """ count = self._convert_to_integer(count, 'count') return string.replace(search_for, replace_with, count) def replace_string_using_regexp(self, string, pattern, replace_with, count=-1): """Replaces `pattern` in the given `string` with `replace_with`. This keyword is otherwise identical to `Replace String`, but the `pattern` to search for is considered to be a regular expression. See `BuiltIn.Should Match Regexp` for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. If you need to just remove a string see `Remove String Using Regexp`. Examples: | ${str} = | Replace String Using Regexp | ${str} | 20\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d | <DATE> | | ${str} = | Replace String Using Regexp | ${str} | (Hello|Hi) | ${EMPTY} | count=1 | """ count = self._convert_to_integer(count, 'count') # re.sub handles 0 and negative counts differently than string.replace if count == 0: return string return re.sub(pattern, replace_with, string, max(count, 0)) def remove_string(self, string, *removables): """Removes all `removables` from the given `string`. `removables` are used as literal strings. Each removable will be matched to a temporary string from which preceding removables have been already removed. See second example below. Use `Remove String Using Regexp` if more powerful pattern matching is needed. If only a certain number of matches should be removed, `Replace String` or `Replace String Using Regexp` can be used. A modified version of the string is returned and the original string is not altered. Examples: | ${str} = | Remove String | Robot Framework | work | | Should Be Equal | ${str} | Robot Frame | | ${str} = | Remove String | Robot Framework | o | bt | | Should Be Equal | ${str} | R Framewrk | New in Robot Framework 2.8.2. """ for removable in removables: string = self.replace_string(string, removable, '') return string def remove_string_using_regexp(self, string, *patterns): """Removes `patterns` from the given `string`. This keyword is otherwise identical to `Remove String`, but the `patterns` to search for are considered to be a regular expression. See `Replace String Using Regexp` for more information about the regular expression syntax. That keyword can also be used if there is a need to remove only a certain number of occurrences. New in Robot Framework 2.8.2. """ for pattern in patterns: string = self.replace_string_using_regexp(string, pattern, '') return string def split_string(self, string, separator=None, max_split=-1): """Splits the `string` using `separator` as a delimiter string. If a `separator` is not given, any whitespace string is a separator. In that case also possible consecutive whitespace as well as leading and trailing whitespace is ignored. Split words are returned as a list. If the optional `max_split` is given, at most `max_split` splits are done, and the returned list will have maximum `max_split + 1` elements. Examples: | @{words} = | Split String | ${string} | | @{words} = | Split String | ${string} | ,${SPACE} | | ${pre} | ${post} = | Split String | ${string} | :: | 1 | See `Split String From Right` if you want to start splitting from right, and `Fetch From Left` and `Fetch From Right` if you only want to get first/last part of the string. """ if separator == '': separator = None max_split = self._convert_to_integer(max_split, 'max_split') return string.split(separator, max_split) def split_string_from_right(self, string, separator=None, max_split=-1): """Splits the `string` using `separator` starting from right. Same as `Split String`, but splitting is started from right. This has an effect only when `max_split` is given. Examples: | ${first} | ${rest} = | Split String | ${string} | - | 1 | | ${rest} | ${last} = | Split String From Right | ${string} | - | 1 | """ if separator == '': separator = None max_split = self._convert_to_integer(max_split, 'max_split') return string.rsplit(separator, max_split) def split_string_to_characters(self, string): """Splits the given `string` to characters. Example: | @{characters} = | Split String To Characters | ${string} | New in Robot Framework 2.7. """ return list(string) def fetch_from_left(self, string, marker): """Returns contents of the `string` before the first occurrence of `marker`. If the `marker` is not found, whole string is returned. See also `Fetch From Right`, `Split String` and `Split String From Right`. """ return string.split(marker)[0] def fetch_from_right(self, string, marker): """Returns contents of the `string` after the last occurrence of `marker`. If the `marker` is not found, whole string is returned. See also `Fetch From Left`, `Split String` and `Split String From Right`. """ return string.split(marker)[-1] def generate_random_string(self, length=8, chars='[LETTERS][NUMBERS]'): """Generates a string with a desired `length` from the given `chars`. The population sequence `chars` contains the characters to use when generating the random string. It can contain any characters, and it is possible to use special markers explained in the table below: | = Marker = | = Explanation = | | _[LOWER]_ | Lowercase ASCII characters from 'a' to 'z'. | | _[UPPER]_ | Uppercase ASCII characters from 'A' to 'Z'. | | _[LETTERS]_ | Lowercase and uppercase ASCII characters. | | _[NUMBERS]_ | Numbers from 0 to 9. | Examples: | ${ret} = | Generate Random String | | ${low} = | Generate Random String | 12 | [LOWER] | | ${bin} = | Generate Random String | 8 | 01 | | ${hex} = | Generate Random String | 4 | [NUMBERS]abcdef | """ if length == '': length = 8 length = self._convert_to_integer(length, 'length') for name, value in [('[LOWER]', ascii_lowercase), ('[UPPER]', ascii_uppercase), ('[LETTERS]', ascii_lowercase + ascii_uppercase), ('[NUMBERS]', digits)]: chars = chars.replace(name, value) maxi = len(chars) - 1 return ''.join(chars[randint(0, maxi)] for _ in xrange(length)) def get_substring(self, string, start, end=None): """Returns a substring from `start` index to `end` index. The `start` index is inclusive and `end` is exclusive. Indexing starts from 0, and it is possible to use negative indices to refer to characters from the end. Examples: | ${ignore first} = | Get Substring | ${string} | 1 | | | ${ignore last} = | Get Substring | ${string} | | -1 | | ${5th to 10th} = | Get Substring | ${string} | 4 | 10 | | ${first two} = | Get Substring | ${string} | | 1 | | ${last two} = | Get Substring | ${string} | -2 | | """ start = self._convert_to_index(start, 'start') end = self._convert_to_index(end, 'end') return string[start:end] def should_be_string(self, item, msg=None): """Fails if the given `item` is not a string. This keyword passes regardless is the `item` is a Unicode string or a byte string. Use `Should Be Unicode String` or `Should Be Byte String` if you want to restrict the string type. The default error message can be overridden with the optional `msg` argument. """ if not isinstance(item, basestring): self._fail(msg, "'%s' is not a string.", item) def should_not_be_string(self, item, msg=None): """Fails if the given `item` is a string. The default error message can be overridden with the optional `msg` argument. """ if isinstance(item, basestring): self._fail(msg, "'%s' is a string.", item) def should_be_unicode_string(self, item, msg=None): """Fails if the given `item` is not a Unicode string. Use `Should Be Byte String` if you want to verify the `item` is a byte string, or `Should Be String` if both Unicode and byte strings are fine. The default error message can be overridden with the optional `msg` argument. New in Robot Framework 2.7.7. """ if not isinstance(item, unicode): self._fail(msg, "'%s' is not a Unicode string.", item) def should_be_byte_string(self, item, msg=None): """Fails if the given `item` is not a byte string. Use `Should Be Unicode String` if you want to verify the `item` is a Unicode string, or `Should Be String` if both Unicode and byte strings are fine. The default error message can be overridden with the optional `msg` argument. New in Robot Framework 2.7.7. """ if not isinstance(item, str): self._fail(msg, "'%s' is not a byte string.", item) def should_be_lowercase(self, string, msg=None): """Fails if the given `string` is not in lowercase. For example 'string' and 'with specials!' would pass, and 'String', '' and ' ' would fail. The default error message can be overridden with the optional `msg` argument. See also `Should Be Uppercase` and `Should Be Titlecase`. All these keywords were added in Robot Framework 2.1.2. """ if not string.islower(): self._fail(msg, "'%s' is not lowercase.", string) def should_be_uppercase(self, string, msg=None): """Fails if the given `string` is not in uppercase. For example 'STRING' and 'WITH SPECIALS!' would pass, and 'String', '' and ' ' would fail. The default error message can be overridden with the optional `msg` argument. See also `Should Be Titlecase` and `Should Be Lowercase`. All these keywords were added in Robot Framework 2.1.2. """ if not string.isupper(): self._fail(msg, "'%s' is not uppercase.", string) def should_be_titlecase(self, string, msg=None): """Fails if given `string` is not title. `string` is a titlecased string if there is at least one character in it, uppercase characters only follow uncased characters and lowercase characters only cased ones. For example 'This Is Title' would pass, and 'Word In UPPER', 'Word In lower', '' and ' ' would fail. The default error message can be overridden with the optional `msg` argument. See also `Should Be Uppercase` and `Should Be Lowercase`. All theses keyword were added in Robot Framework 2.1.2. """ if not string.istitle(): self._fail(msg, "'%s' is not titlecase.", string) def _convert_to_index(self, value, name): if value == '': return 0 if value is None: return None return self._convert_to_integer(value, name) def _convert_to_integer(self, value, name): try: return int(value) except ValueError: raise ValueError("Cannot convert '%s' argument '%s' to an integer." % (name, value)) def _fail(self, message, default_template, *items): if not message: message = default_template % tuple(unic(item) for item in items) raise AssertionError(message)
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. """Package hosting Robot Framework standard test libraries. Libraries are mainly used externally in the test data, but they can be also used by custom test libraries if there is a need. Especially the :class:`~robot.libraries.BuiltIn.BuiltIn` library is often useful when there is a need to interact with the framework. Because libraries are documented using Robot Framework's own documentation syntax, the generated API docs are not that well formed. It is thus better to find the generated library documentations, for example, via the http://robotframework.org web site. """
Python
# -*- coding: utf-8 -*- # 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 time from robot.api import logger from robot.errors import (ContinueForLoop, DataError, ExecutionFailed, ExecutionFailures, ExecutionPassed, ExitForLoop, PassExecution, ReturnFromKeyword) from robot import utils from robot.utils import asserts from robot.variables import is_var, is_list_var from robot.running import Keyword, RUN_KW_REGISTER from robot.running.context import EXECUTION_CONTEXTS from robot.running.usererrorhandler import UserErrorHandler from robot.version import get_version if utils.is_jython: from java.lang import String, Number try: bin # available since Python 2.6 except NameError: def bin(integer): if not isinstance(integer, (int, long)): raise TypeError if integer >= 0: prefix = '0b' else: prefix = '-0b' integer = abs(integer) bins = [] while integer > 1: integer, remainder = divmod(integer, 2) bins.append(str(remainder)) bins.append(str(integer)) return prefix + ''.join(reversed(bins)) def run_keyword_variant(resolve): def decorator(method): RUN_KW_REGISTER.register_run_keyword('BuiltIn', method.__name__, resolve) return method return decorator class _Converter: def convert_to_integer(self, item, base=None): """Converts the given item to an integer number. If the given item is a string, it is by default expected to be an integer in base 10. Starting from Robot Framework 2.6 there are two ways to convert from other bases: - Give base explicitly to the keyword as `base` argument. - Prefix the given string with the base so that `0b` means binary (base 2), `0o` means octal (base 8), and `0x` means hex (base 16). The prefix is considered only when `base` argument is not given and may itself be prefixed with a plus or minus sign. The syntax is case-insensitive and possible spaces are ignored. Examples: | ${result} = | Convert To Integer | 100 | | # Result is 100 | | ${result} = | Convert To Integer | FF AA | 16 | # Result is 65450 | | ${result} = | Convert To Integer | 100 | 8 | # Result is 64 | | ${result} = | Convert To Integer | -100 | 2 | # Result is -4 | | ${result} = | Convert To Integer | 0b100 | | # Result is 4 | | ${result} = | Convert To Integer | -0x100 | | # Result is -256 | See also `Convert To Number`, `Convert To Binary`, `Convert To Octal`, `Convert To Hex`, and `Convert To Bytes`. """ self._log_types(item) return self._convert_to_integer(item, base) def _convert_to_integer(self, orig, base=None): try: item = self._handle_java_numbers(orig) item, base = self._get_base(item, base) if base: return int(item, self._convert_to_integer(base)) return int(item) except: raise RuntimeError("'%s' cannot be converted to an integer: %s" % (orig, utils.get_error_message())) def _handle_java_numbers(self, item): if not utils.is_jython: return item if isinstance(item, String): return utils.unic(item) if isinstance(item, Number): return item.doubleValue() return item def _get_base(self, item, base): if not isinstance(item, basestring): return item, base item = utils.normalize(item) if item.startswith(('-', '+')): sign = item[0] item = item[1:] else: sign = '' bases = {'0b': 2, '0o': 8, '0x': 16} if base or not item.startswith(tuple(bases)): return sign+item, base return sign+item[2:], bases[item[:2]] def convert_to_binary(self, item, base=None, prefix=None, length=None): """Converts the given item to a binary string. The `item`, with an optional `base`, is first converted to an integer using `Convert To Integer` internally. After that it is converted to a binary number (base 2) represented as a string such as `'1011'`. The returned value can contain an optional `prefix` and can be required to be of minimum `length` (excluding the prefix and a possible minus sign). If the value is initially shorter than the required length, it is padded with zeros. Examples: | ${result} = | Convert To Binary | 10 | | | # Result is 1010 | | ${result} = | Convert To Binary | F | base=16 | prefix=0b | # Result is 0b1111 | | ${result} = | Convert To Binary | -2 | prefix=B | length=4 | # Result is -B0010 | This keyword was added in Robot Framework 2.6. See also `Convert To Integer`, `Convert To Octal` and `Convert To Hex`. """ return self._convert_to_bin_oct_hex(bin, item, base, prefix, length) def convert_to_octal(self, item, base=None, prefix=None, length=None): """Converts the given item to an octal string. The `item`, with an optional `base`, is first converted to an integer using `Convert To Integer` internally. After that it is converted to an octal number (base 8) represented as a string such as `'775'`. The returned value can contain an optional `prefix` and can be required to be of minimum `length` (excluding the prefix and a possible minus sign). If the value is initially shorter than the required length, it is padded with zeros. Examples: | ${result} = | Convert To Octal | 10 | | | # Result is 12 | | ${result} = | Convert To Octal | -F | base=16 | prefix=0 | # Result is -017 | | ${result} = | Convert To Octal | 16 | prefix=oct | length=4 | # Result is oct0020 | This keyword was added in Robot Framework 2.6. See also `Convert To Integer`, `Convert To Binary` and `Convert To Hex`. """ return self._convert_to_bin_oct_hex(oct, item, base, prefix, length) def convert_to_hex(self, item, base=None, prefix=None, length=None, lowercase=False): """Converts the given item to a hexadecimal string. The `item`, with an optional `base`, is first converted to an integer using `Convert To Integer` internally. After that it is converted to a hexadecimal number (base 16) represented as a string such as `'FF0A'`. The returned value can contain an optional `prefix` and can be required to be of minimum `length` (excluding the prefix and a possible minus sign). If the value is initially shorter than the required length, it is padded with zeros. By default the value is returned as an upper case string, but giving any non-empty value to the `lowercase` argument turns the value (but not the prefix) to lower case. Examples: | ${result} = | Convert To Hex | 255 | | | # Result is FF | | ${result} = | Convert To Hex | -10 | prefix=0x | length=2 | # Result is -0x0A | | ${result} = | Convert To Hex | 255 | prefix=X | lowercase=yes | # Result is Xff | This keyword was added in Robot Framework 2.6. See also `Convert To Integer`, `Convert To Binary` and `Convert To Octal`. """ return self._convert_to_bin_oct_hex(hex, item, base, prefix, length, lowercase) def _convert_to_bin_oct_hex(self, method, item, base, prefix, length, lowercase=False): self._log_types(item) ret = method(self._convert_to_integer(item, base)).upper() prefix = prefix or '' if ret[0] == '-': prefix = '-' + prefix ret = ret[1:] if len(ret) > 1: # oct(0) -> '0' (i.e. has no prefix) prefix_length = {bin: 2, oct: 1, hex: 2}[method] ret = ret[prefix_length:] if length: ret = ret.rjust(self._convert_to_integer(length), '0') if lowercase: ret = ret.lower() return prefix + ret def convert_to_number(self, item, precision=None): """Converts the given item to a floating point number. If the optional `precision` is positive or zero, the returned number is rounded to that number of decimal digits. Negative precision means that the number is rounded to the closest multiple of 10 to the power of the absolute precision. The support for precision was added in Robot Framework 2.6. Examples: | ${result} = | Convert To Number | 42.512 | | # Result is 42.512 | | ${result} = | Convert To Number | 42.512 | 1 | # Result is 42.5 | | ${result} = | Convert To Number | 42.512 | 0 | # Result is 43.0 | | ${result} = | Convert To Number | 42.512 | -1 | # Result is 40.0 | Notice that machines generally cannot store floating point numbers accurately. This may cause surprises with these numbers in general and also when they are rounded. For more information see, for example, these resources: - http://docs.python.org/2/tutorial/floatingpoint.html - http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition If you need an integer number, use `Convert To Integer` instead. """ self._log_types(item) return self._convert_to_number(item, precision) def _convert_to_number(self, item, precision=None): number = self._convert_to_number_without_precision(item) if precision: number = round(number, self._convert_to_integer(precision)) return number def _convert_to_number_without_precision(self, item): try: if utils.is_jython: item = self._handle_java_numbers(item) return float(item) except: error = utils.get_error_message() try: return float(self._convert_to_integer(item)) except RuntimeError: raise RuntimeError("'%s' cannot be converted to a floating " "point number: %s" % (item, error)) def convert_to_string(self, item): """Converts the given item to a Unicode string. Uses `__unicode__` or `__str__` method with Python objects and `toString` with Java objects. Use `Encode String To Bytes` and `Decode Bytes To String` keywords in `String` library if you need to convert between Unicode and byte strings using different encodings. Use `Convert To Bytes` if you just want to create byte strings. """ self._log_types(item) return self._convert_to_string(item) def _convert_to_string(self, item): return utils.unic(item) def convert_to_boolean(self, item): """Converts the given item to Boolean true or false. Handles strings `True` and `False` (case-insensitive) as expected, otherwise returns item's [http://docs.python.org/2/library/stdtypes.html#truth|truth value] using Python's `bool` method. """ self._log_types(item) if isinstance(item, basestring): if utils.eq(item, 'True'): return True if utils.eq(item, 'False'): return False return bool(item) def convert_to_bytes(self, input, input_type='text'): """Converts the given `input` to bytes according to the `input_type`. Valid input types are listed below: - *text:* Converts text to bytes character by character. All characters with ordinal below 256 can be used and are converted to bytes with same values. Many characters are easiest to represent using escapes like `\\x00` or `\\xff`. - *int:* Converts integers separated by spaces to bytes. Similarly as with `Convert To Integer`, it is possible to use binary, octal, or hex values by prefixing the values with `0b`, `0o`, or `0x`, respectively. - *hex:* Converts hexadecimal values to bytes. Single byte is always two characters long (e.g. `01` or `FF`). Spaces are ignored and can be used freely as a visual separator. - *bin:* Converts binary values to bytes. Single byte is always eight characters long (e.g. `00001010`). Spaces are ignored and can be used freely as a visual separator. In addition to giving the input as a string, it is possible to use lists or other iterables containing individual characters or numbers. In that case numbers do not need to be padded to certain length and they cannot contain extra spaces. Examples (last column shows returned bytes): | ${bytes} = | Convert To Bytes | hyvä | | # hyv\\xe4 | | ${bytes} = | Convert To Bytes | \\xff\\x07 | | # \\xff\\x07 | | ${bytes} = | Convert To Bytes | 82 70 | int | # RF | | ${bytes} = | Convert To Bytes | 0b10 0x10 | int | # \\x02\\x10 | | ${bytes} = | Convert To Bytes | ff 00 07 | hex | # \\xff\\x00\\x07 | | ${bytes} = | Convert To Bytes | 5246212121 | hex | # RF!!! | | ${bytes} = | Convert To Bytes | 0000 1000 | bin | # \\x08 | | ${input} = | Create List | 1 | 2 | 12 | | ${bytes} = | Convert To Bytes | ${input} | int | # \\x01\\x02\\x0c | | ${bytes} = | Convert To Bytes | ${input} | hex | # \\x01\\x02\\x12 | Use `Encode String To Bytes` in `String` library if you need to convert text to bytes using a certain encoding. New in Robot Framework 2.8.2. """ try: try: ordinals = getattr(self, '_get_ordinals_from_%s' % input_type) except AttributeError: raise RuntimeError("Invalid input type '%s'." % input_type) return ''.join(chr(o) for o in ordinals(input)) except: raise RuntimeError("Creating bytes failed: %s" % utils.get_error_message()) def _get_ordinals_from_text(self, input): for char in input: yield self._test_ordinal(ord(char), char, 'Character') def _test_ordinal(self, ordinal, original, type): if 0 <= ordinal <= 255: return ordinal raise RuntimeError("%s '%s' cannot be represented as a byte." % (type, original)) def _get_ordinals_from_int(self, input): if isinstance(input, basestring): input = input.split() elif isinstance(input, (int, long)): input = [input] for integer in input: ordinal = self._convert_to_integer(integer) yield self._test_ordinal(ordinal, integer, 'Integer') def _get_ordinals_from_hex(self, input): for token in self._input_to_tokens(input, length=2): ordinal = self._convert_to_integer(token, base=16) yield self._test_ordinal(ordinal, token, 'Hex value') def _get_ordinals_from_bin(self, input): for token in self._input_to_tokens(input, length=8): ordinal = self._convert_to_integer(token, base=2) yield self._test_ordinal(ordinal, token, 'Binary value') def _input_to_tokens(self, input, length): if not isinstance(input, basestring): return input input = ''.join(input.split()) if len(input) % length != 0: raise RuntimeError('Expected input to be multiple of %d.' % length) return (input[i:i+length] for i in xrange(0, len(input), length)) def create_list(self, *items): """Returns a list containing given items. The returned list can be assigned both to `${scalar}` and `@{list}` variables. Examples: | @{list} = | Create List | a | b | c | | ${scalar} = | Create List | a | b | c | | ${ints} = | Create List | ${1} | ${2} | ${3} | """ return list(items) class _Verify: def _set_and_remove_tags(self, tags): set_tags = [tag for tag in tags if not tag.startswith('-')] remove_tags = [tag[1:] for tag in tags if tag.startswith('-')] if remove_tags: self.remove_tags(*remove_tags) if set_tags: self.set_tags(*set_tags) def fail(self, msg=None, *tags): """Fails the test with the given message and optionally alters its tags. The error message is specified using the `msg` argument. It is possible to use HTML in the given error message, similarly as with any other keyword accepting an error message, by prefixing the error with `*HTML*`. It is possible to modify tags of the current test case by passing tags after the message. Tags starting with a hyphen (e.g. `-regression`) are removed and others added. Tags are modified using `Set Tags` and `Remove Tags` internally, and the semantics setting and removing them are the same as with these keywords. Examples: | Fail | Test not ready | | | # Fails with the given message. | | Fail | *HTML*<b>Test not ready</b> | | | # Fails using HTML in the message. | | Fail | Test not ready | not-ready | | # Fails and adds 'not-ready' tag. | | Fail | OS not supported | -regression | | # Removes tag 'regression'. | | Fail | My message | tag | -t* | # Removes all tags starting with 't' except the newly added 'tag'. | See `Fatal Error` if you need to stop the whole test execution. Support for modifying tags was added in Robot Framework 2.7.4 and HTML message support in 2.8. """ self._set_and_remove_tags(tags) raise AssertionError(msg) if msg else AssertionError() def fatal_error(self, msg=None): """Stops the whole test execution. The test or suite where this keyword is used fails with the provided message, and subsequent tests fail with a canned message. Possible teardowns will nevertheless be executed. See `Fail` if you only want to stop one test case unconditionally. """ error = AssertionError(msg) if msg else AssertionError() error.ROBOT_EXIT_ON_FAILURE = True raise error def should_not_be_true(self, condition, msg=None): """Fails if the given condition is true. See `Should Be True` for details about how `condition` is evaluated and how `msg` can be used to override the default error message. """ if not msg: msg = "'%s' should not be true" % condition asserts.fail_if(self._is_true(condition), msg) def should_be_true(self, condition, msg=None): """Fails if the given condition is not true. If `condition` is a string (e.g. `${rc} < 10`), it is evaluated as a Python expression using the built-in `eval` function and the keyword status is decided based on the result. If a non-string item is given, the status is got directly from its [http://docs.python.org/2/library/stdtypes.html#truth|truth value]. The default error message (`<condition> should be true`) is not very informative, but it can be overridden with the `msg` argument. Examples: | Should Be True | ${rc} < 10 | | Should Be True | '${status}' == 'PASS' | # Strings must be quoted | | Should Be True | ${number} | # Passes if ${number} is not zero | | Should Be True | ${list} | # Passes if ${list} is not empty | Starting from Robot Framework 2.8, `Should Be True` automatically imports Python's [http://docs.python.org/2/library/os.html|os] and [http://docs.python.org/2/library/sys.html|sys] modules that contain several useful attributes: | Should Be True | os.linesep == '\\n' | # Unixy | | Should Be True | os.linesep == '\\r\\n' | # Windows | | Should Be True | sys.platform == 'darwin' | # OS X | | Should Be True | sys.platform.startswith('java') | # Jython | """ if not msg: msg = "'%s' should be true" % condition asserts.fail_unless(self._is_true(condition), msg) def should_be_equal(self, first, second, msg=None, values=True): """Fails if the given objects are unequal. - If `msg` is not given, the error message is 'first != second'. - If `msg` is given and `values` is either Boolean False or the string 'False' or 'No Values', the error message is simply `msg`. - Otherwise the error message is '`msg`: `first` != `second`'. """ self._log_types(first, second) self._should_be_equal(first, second, msg, values) def _should_be_equal(self, first, second, msg, values): asserts.fail_unless_equal(first, second, msg, self._include_values(values)) def _log_types(self, *args): msg = ["Argument types are:"] + [self._get_type(a) for a in args] self.log('\n'.join(msg)) def _get_type(self, arg): # In IronPython type(u'x') is str. We want to report unicode anyway. if isinstance(arg, unicode): return "<type 'unicode'>" return str(type(arg)) def _include_values(self, values): if isinstance(values, basestring): return values.lower() not in ['no values', 'false'] return bool(values) def should_not_be_equal(self, first, second, msg=None, values=True): """Fails if the given objects are equal. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) self._should_not_be_equal(first, second, msg, values) def _should_not_be_equal(self, first, second, msg, values): asserts.fail_if_equal(first, second, msg, self._include_values(values)) def should_not_be_equal_as_integers(self, first, second, msg=None, values=True, base=None): """Fails if objects are equal after converting them to integers. See `Convert To Integer` for information how to convert integers from other bases than 10 using `base` argument or `0b/0o/0x` prefixes. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. See `Should Be Equal As Integers` for some usage examples. """ self._log_types(first, second) self._should_not_be_equal(self._convert_to_integer(first, base), self._convert_to_integer(second, base), msg, values) def should_be_equal_as_integers(self, first, second, msg=None, values=True, base=None): """Fails if objects are unequal after converting them to integers. See `Convert To Integer` for information how to convert integers from other bases than 10 using `base` argument or `0b/0o/0x` prefixes. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. Examples: | Should Be Equal As Integers | 42 | ${42} | Error message | | Should Be Equal As Integers | ABCD | abcd | base=16 | | Should Be Equal As Integers | 0b1011 | 11 | """ self._log_types(first, second) self._should_be_equal(self._convert_to_integer(first, base), self._convert_to_integer(second, base), msg, values) def should_not_be_equal_as_numbers(self, first, second, msg=None, values=True, precision=6): """Fails if objects are equal after converting them to real numbers. The conversion is done with `Convert To Number` keyword using the given `precision`. The support for giving precision was added in Robot Framework 2.6, in earlier versions it was hard-coded to 6. See `Should Be Equal As Numbers` for examples on how to use `precision` and why it does not always work as expected. See also `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) first = self._convert_to_number(first, precision) second = self._convert_to_number(second, precision) self._should_not_be_equal(first, second, msg, values) def should_be_equal_as_numbers(self, first, second, msg=None, values=True, precision=6): """Fails if objects are unequal after converting them to real numbers. The conversion is done with `Convert To Number` keyword using the given `precision`. The support for giving precision was added in Robot Framework 2.6, in earlier versions it was hard-coded to 6. Examples: | Should Be Equal As Numbers | ${x} | 1.1 | | # Passes if ${x} is 1.1 | | Should Be Equal As Numbers | 1.123 | 1.1 | precision=1 | # Passes | | Should Be Equal As Numbers | 1.123 | 1.4 | precision=0 | # Passes | | Should Be Equal As Numbers | 112.3 | 75 | precision=-2 | # Passes | As discussed in the documentation of `Convert To Number`, machines generally cannot store floating point numbers accurately. Because of this limitation, comparing floats for equality is problematic and a correct approach to use depends on the context. This keyword uses a very naive approach of rounding the numbers before comparing them, which is both prone to rounding errors and does not work very well if numbers are really big or small. For more information about comparing floats, and ideas on how to implement your own context specific comparison algorithm, see http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/. See `Should Not Be Equal As Numbers` for a negative version of this keyword and `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) first = self._convert_to_number(first, precision) second = self._convert_to_number(second, precision) self._should_be_equal(first, second, msg, values) def should_not_be_equal_as_strings(self, first, second, msg=None, values=True): """Fails if objects are equal after converting them to strings. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) first, second = [self._convert_to_string(i) for i in first, second] self._should_not_be_equal(first, second, msg, values) def should_be_equal_as_strings(self, first, second, msg=None, values=True): """Fails if objects are unequal after converting them to strings. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) first, second = [self._convert_to_string(i) for i in first, second] self._should_be_equal(first, second, msg, values) def should_not_start_with(self, str1, str2, msg=None, values=True): """Fails if the string `str1` starts with the string `str2`. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(str1, str2, msg, values, 'starts with') asserts.fail_if(str1.startswith(str2), msg) def should_start_with(self, str1, str2, msg=None, values=True): """Fails if the string `str1` does not start with the string `str2`. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(str1, str2, msg, values, 'does not start with') asserts.fail_unless(str1.startswith(str2), msg) def should_not_end_with(self, str1, str2, msg=None, values=True): """Fails if the string `str1` ends with the string `str2`. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(str1, str2, msg, values, 'ends with') asserts.fail_if(str1.endswith(str2), msg) def should_end_with(self, str1, str2, msg=None, values=True): """Fails if the string `str1` does not end with the string `str2`. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(str1, str2, msg, values, 'does not end with') asserts.fail_unless(str1.endswith(str2), msg) def should_not_contain(self, item1, item2, msg=None, values=True): """Fails if `item1` contains `item2` one or more times. Works with strings, lists, and anything that supports Python's 'in' keyword. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. Examples: | Should Not Contain | ${output} | FAILED | | Should Not Contain | ${some_list} | value | """ msg = self._get_string_msg(item1, item2, msg, values, 'contains') asserts.fail_if(item2 in item1, msg) def should_contain(self, item1, item2, msg=None, values=True): """Fails if `item1` does not contain `item2` one or more times. Works with strings, lists, and anything that supports Python's `in` keyword. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. Examples: | Should Contain | ${output} | PASS | | Should Contain | ${some_list} | value | """ msg = self._get_string_msg(item1, item2, msg, values, 'does not contain') asserts.fail_unless(item2 in item1, msg) def should_contain_x_times(self, item1, item2, count, msg=None): """Fails if `item1` does not contain `item2` `count` times. Works with strings, lists and all objects that `Get Count` works with. The default error message can be overridden with `msg` and the actual count is always logged. Examples: | Should Contain X Times | ${output} | hello | 2 | | Should Contain X Times | ${some list} | value | 3 | """ if not msg: msg = "'%s' does not contain '%s' %s times" \ % (utils.unic(item1), utils.unic(item2), count) self.should_be_equal_as_integers(self.get_count(item1, item2), count, msg, values=False) def get_count(self, item1, item2): """Returns and logs how many times `item2` is found from `item1`. This keyword works with Python strings and lists and all objects that either have 'count' method or can be converted to Python lists. Example: | ${count} = | Get Count | ${some item} | interesting value | | Should Be True | 5 < ${count} < 10 | """ if not hasattr(item1, 'count'): try: item1 = list(item1) except: raise RuntimeError("Converting '%s' to list failed: %s" % (item1, utils.get_error_message())) count = item1.count(item2) self.log('Item found from the first item %d time%s' % (count, utils.plural_or_not(count))) return count def should_not_match(self, string, pattern, msg=None, values=True): """Fails if the given `string` matches the given `pattern`. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern '*' matches to anything and '?' matches to any single character. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(string, pattern, msg, values, 'matches') asserts.fail_if(self._matches(string, pattern), msg) def should_match(self, string, pattern, msg=None, values=True): """Fails unless the given `string` matches the given `pattern`. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern, '*' matches to anything and '?' matches to any single character. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(string, pattern, msg, values, 'does not match') asserts.fail_unless(self._matches(string, pattern), msg) def should_match_regexp(self, string, pattern, msg=None, values=True): """Fails if `string` does not match `pattern` as a regular expression. Regular expression check is implemented using the Python [http://docs.python.org/2/library/re.html|re module]. Python's regular expression syntax is derived from Perl, and it is thus also very similar to the syntax used, for example, in Java, Ruby and .NET. Things to note about the regexp syntax in Robot Framework test data: 1) Backslash is an escape character in the test data, and possible backslashes in the pattern must thus be escaped with another backslash (e.g. '\\\\d\\\\w+'). 2) Strings that may contain special characters, but should be handled as literal strings, can be escaped with the `Regexp Escape` keyword. 3) The given pattern does not need to match the whole string. For example, the pattern 'ello' matches the string 'Hello world!'. If a full match is needed, the '^' and '$' characters can be used to denote the beginning and end of the string, respectively. For example, '^ello$' only matches the exact string 'ello'. 4) Possible flags altering how the expression is parsed (e.g. re.IGNORECASE, re.MULTILINE) can be set by prefixing the pattern with the '(?iLmsux)' group (e.g. '(?im)pattern'). The available flags are 'IGNORECASE': 'i', 'MULTILINE': 'm', 'DOTALL': 's', 'VERBOSE': 'x', 'UNICODE': 'u', and 'LOCALE': 'L'. If this keyword passes, it returns the portion of the string that matched the pattern. Additionally, the possible captured groups are returned. See the `Should Be Equal` keyword for an explanation on how to override the default error message with the `msg` and `values` arguments. Examples: | Should Match Regexp | ${output} | \\\\d{6} | # Output contains six numbers | | Should Match Regexp | ${output} | ^\\\\d{6}$ | # Six numbers and nothing more | | ${ret} = | Should Match Regexp | Foo: 42 | (?i)foo: \\\\d+ | | ${match} | ${group1} | ${group2} = | | ... | Should Match Regexp | Bar: 43 | (Foo|Bar): (\\\\d+) | => | ${ret} = 'Foo: 42' | ${match} = 'Bar: 43' | ${group1} = 'Bar' | ${group2} = '43' """ msg = self._get_string_msg(string, pattern, msg, values, 'does not match') res = re.search(pattern, string) asserts.fail_if_none(res, msg, False) match = res.group(0) groups = res.groups() if groups: return [match] + list(groups) return match def should_not_match_regexp(self, string, pattern, msg=None, values=True): """Fails if `string` matches `pattern` as a regular expression. See `Should Match Regexp` for more information about arguments. """ msg = self._get_string_msg(string, pattern, msg, values, 'matches') asserts.fail_unless_none(re.search(pattern, string), msg, False) def get_length(self, item): """Returns and logs the length of the given item. The item can be anything that has a length, for example, a string, a list, or a mapping. The keyword first tries to get the length with the Python function `len`, which calls the item's `__len__` method internally. If that fails, the keyword tries to call the item's possible `length` and `size` methods directly. The final attempt is trying to get the value of the item's `length` attribute. If all these attempts are unsuccessful, the keyword fails. It is possible to use this keyword also with list variables (e.g. `@{LIST}`), but you need to use them as scalars (e.g. `${LIST}`). """ length = self._get_length(item) self.log('Length is %d' % length) return length def _get_length(self, item): try: return len(item) except utils.RERAISED_EXCEPTIONS: raise except: try: return item.length() except utils.RERAISED_EXCEPTIONS: raise except: try: return item.size() except utils.RERAISED_EXCEPTIONS: raise except: try: return item.length except utils.RERAISED_EXCEPTIONS: raise except: raise RuntimeError("Could not get length of '%s'" % item) def length_should_be(self, item, length, msg=None): """Verifies that the length of the given item is correct. The length of the item is got using the `Get Length` keyword. The default error message can be overridden with the `msg` argument. """ length = self._convert_to_integer(length) actual = self.get_length(item) if actual != length: raise AssertionError(msg or "Length of '%s' should be %d but is %d" % (item, length, actual)) def should_be_empty(self, item, msg=None): """Verifies that the given item is empty. The length of the item is got using the `Get Length` keyword. The default error message can be overridden with the `msg` argument. """ if self.get_length(item) > 0: raise AssertionError(msg or "'%s' should be empty" % item) def should_not_be_empty(self, item, msg=None): """Verifies that the given item is not empty. The length of the item is got using the `Get Length` keyword. The default error message can be overridden with the `msg` argument. """ if self.get_length(item) == 0: raise AssertionError(msg or "'%s' should not be empty" % item) def _get_string_msg(self, str1, str2, msg, values, delim): default = "'%s' %s '%s'" % (utils.unic(str1), delim, utils.unic(str2)) if not msg: msg = default elif values is True: msg = '%s: %s' % (msg, default) return msg class _Variables: def get_variables(self): """Returns a dictionary containing all variables in the current scope. Variables are returned as a special dictionary that allows accessing variables in space, case, and underscore insensitive manner similarly as accessing variables in the test data. This dictionary supports all same operations as normal Python dictionaries and, for example, Collections library can be used to access or modify it. Modifying the returned dictionary has no effect on the variables available in the current scope. Example: | ${example_variable} = | Set Variable | example value | | ${variables} = | Get Variables | | | Dictionary Should Contain Key | ${variables} | \\${example_variable} | | Dictionary Should Contain Key | ${variables} | \\${ExampleVariable} | | Set To Dictionary | ${variables} | \\${name} | value | | Variable Should Not Exist | \\${name} | | | Note: Prior to Robot Framework 2.7.4 variables were returned as a custom object that did not support all dictionary methods. """ return utils.NormalizedDict(self._variables.current, ignore='_') @run_keyword_variant(resolve=0) def get_variable_value(self, name, default=None): """Returns variable value or `default` if the variable does not exist. The name of the variable can be given either as a normal variable name (e.g. `${NAME}`) or in escaped format (e.g. `\\${NAME}`). Notice that the former has some limitations explained in `Set Suite Variable`. Examples: | ${x} = | Get Variable Value | ${a} | default | | ${y} = | Get Variable Value | ${a} | ${b} | | ${z} = | Get Variable Value | ${z} | | => | ${x} gets value of ${a} if ${a} exists and string "default" otherwise | ${y} gets value of ${a} if ${a} exists and value of ${b} otherwise | ${z} is set to Python `None` if it does not exist previously This keyword was added in Robot Framework 2.6. See `Set Variable If` for another keyword to set variables dynamically. """ try: return self._variables[self._get_var_name(name)] except DataError: return self._variables.replace_scalar(default) def log_variables(self, level='INFO'): """Logs all variables in the current scope with given log level.""" variables = self.get_variables() for name in sorted(variables.keys(), key=lambda s: s.lower()): msg = utils.format_assign_message(name, variables[name], cut_long=False) self.log(msg, level) @run_keyword_variant(resolve=0) def variable_should_exist(self, name, msg=None): """Fails unless the given variable exists within the current scope. The name of the variable can be given either as a normal variable name (e.g. `${NAME}`) or in escaped format (e.g. `\\${NAME}`). Notice that the former has some limitations explained in `Set Suite Variable`. The default error message can be overridden with the `msg` argument. See also `Variable Should Not Exist` and `Keyword Should Exist`. """ name = self._get_var_name(name) msg = self._variables.replace_string(msg) if msg \ else "Variable %s does not exist" % name asserts.fail_unless(name in self._variables, msg) @run_keyword_variant(resolve=0) def variable_should_not_exist(self, name, msg=None): """Fails if the given variable exists within the current scope. The name of the variable can be given either as a normal variable name (e.g. `${NAME}`) or in escaped format (e.g. `\\${NAME}`). Notice that the former has some limitations explained in `Set Suite Variable`. The default error message can be overridden with the `msg` argument. See also `Variable Should Exist` and `Keyword Should Exist`. """ name = self._get_var_name(name) msg = self._variables.replace_string(msg) if msg \ else "Variable %s exists" % name asserts.fail_if(name in self._variables, msg) def replace_variables(self, text): """Replaces variables in the given text with their current values. If the text contains undefined variables, this keyword fails. If the given `text` contains only a single variable, its value is returned as-is and it can be any object. Otherwise this keyword always returns a string. Example: The file 'template.txt' contains 'Hello ${NAME}!' and variable '${NAME}' has the value 'Robot'. | ${template} = | Get File | ${CURDIR}/template.txt | | ${message} = | Replace Variables | ${template} | | Should Be Equal | ${message} | Hello Robot! | """ return self._variables.replace_scalar(text) def set_variable(self, *values): """Returns the given values which can then be assigned to a variables. This keyword is mainly used for setting scalar variables. Additionally it can be used for converting a scalar variable containing a list to a list variable or to multiple scalar variables. It is recommended to use `Create List` when creating new lists. Examples: | ${hi} = | Set Variable | Hello, world! | | ${hi2} = | Set Variable | I said: ${hi} | | ${var1} | ${var2} = | Set Variable | Hello | world | | @{list} = | Set Variable | ${list with some items} | | ${item1} | ${item2} = | Set Variable | ${list with 2 items} | Variables created with this keyword are available only in the scope where they are created. See `Set Global Variable`, `Set Test Variable` and `Set Suite Variable` for information on how to set variables so that they are available also in a larger scope. """ if len(values) == 0: return '' elif len(values) == 1: return values[0] else: return list(values) @run_keyword_variant(resolve=0) def set_test_variable(self, name, *values): """Makes a variable available everywhere within the scope of the current test. Variables set with this keyword are available everywhere within the scope of the currently executed test case. For example, if you set a variable in a user keyword, it is available both in the test case level and also in all other user keywords used in the current test. Other test cases will not see variables set with this keyword. See `Set Suite Variable` for more information and examples. """ name = self._get_var_name(name) value = self._get_var_value(name, values) self._variables.set_test(name, value) self._log_set_variable(name, value) @run_keyword_variant(resolve=0) def set_suite_variable(self, name, *values): """Makes a variable available everywhere within the scope of the current suite. Variables set with this keyword are available everywhere within the scope of the currently executed test suite. Setting variables with this keyword thus has the same effect as creating them using the Variable table in the test data file or importing them from variable files. Other test suites, including possible child test suites, will not see variables set with this keyword. The name of the variable can be given either as a normal variable name (e.g. `${NAME}`) or in escaped format as `\\${NAME}` or `$NAME`. If a variable already exists within the new scope, its value will be overwritten. Otherwise a new variable is created. If a variable already exists within the current scope, the value can be left empty and the variable within the new scope gets the value within the current scope. Examples: | Set Suite Variable | ${GREET} | Hello, world! | | Set Suite Variable | @{LIST} | First item | Second item | | ${ID} = | Get ID | | Set Suite Variable | ${ID} | To override an existing value with an empty value, use built-in variables `${EMPTY}` or `@{EMPTY}`: | Set Suite Variable | ${GREET} | ${EMPTY} | | Set Suite Variable | @{LIST} | @{EMPTY} | # New in RF 2.7.4 | *NOTE:* If the variable has value which itself is a variable (escaped or not), you must always use the escaped format to reset the variable: Example: | ${NAME} = | Set Variable | \${var} | | Set Suite Variable | ${NAME} | value | # Sets variable ${var} | | Set Suite Variable | \${NAME} | value | # Sets variable ${NAME} | This limitation applies also to `Set Test/Suite/Global Variable`, `Variable Should (Not) Exist`, and `Get Variable Value` keywords. """ name = self._get_var_name(name) value = self._get_var_value(name, values) self._variables.set_suite(name, value) self._log_set_variable(name, value) @run_keyword_variant(resolve=0) def set_global_variable(self, name, *values): """Makes a variable available globally in all tests and suites. Variables set with this keyword are globally available in all test cases and suites executed after setting them. Setting variables with this keyword thus has the same effect as creating from the command line using the options '--variable' or '--variablefile'. Because this keyword can change variables everywhere, it should be used with care. See `Set Suite Variable` for more information and examples. """ name = self._get_var_name(name) value = self._get_var_value(name, values) self._variables.set_global(name, value) self._log_set_variable(name, value) # Helpers def _get_var_name(self, orig): name = self._resolve_possible_variable(orig) try: return self._unescape_variable_if_needed(name) except ValueError: raise RuntimeError("Invalid variable syntax '%s'" % orig) def _resolve_possible_variable(self, name): try: resolved = self._variables[name] return self._unescape_variable_if_needed(resolved) except (KeyError, ValueError, DataError): return name def _unescape_variable_if_needed(self, name): if not (isinstance(name, basestring) and len(name) > 1): raise ValueError if name.startswith('\\'): name = name[1:] elif name[0] in '$@' and name[1] != '{': name = '%s{%s}' % (name[0], name[1:]) if is_var(name): return name # Support for possible internal variables (issue 397) name = '%s{%s}' % (name[0], self.replace_variables(name[2:-1])) if is_var(name): return name raise ValueError def _get_var_value(self, name, values): if not values: return self._variables[name] values = self._variables.replace_list(values) if len(values) == 1 and name[0] == '$': return values[0] return list(values) def _log_set_variable(self, name, value): self.log(utils.format_assign_message(name, value)) class _RunKeyword: # If you use any of these run keyword variants from another library, you # should register those keywords with 'register_run_keyword' method. See # the documentation of that method at the end of this file. There are also # other run keyword variant keywords in BuiltIn which can also be seen # at the end of this file. def run_keyword(self, name, *args): """Executes the given keyword with the given arguments. Because the name of the keyword to execute is given as an argument, it can be a variable and thus set dynamically, e.g. from a return value of another keyword or from the command line. """ if not isinstance(name, basestring): raise RuntimeError('Keyword name must be a string.') kw = Keyword(name, list(args)) return kw.run(self._context) def run_keywords(self, *keywords): """Executes all the given keywords in a sequence. This keyword is mainly useful in setups and teardowns when they need to take care of multiple actions and creating a new higher level user keyword would be an overkill. Examples: | Run Keywords | Initialize database | Start servers | Clear logs | | Run Keywords | ${KW 1} | ${KW 2} | | Run Keywords | @{KEYWORDS} | In this example, we call `Run Keywords` with three different combination of arguments. Keyword names and arguments can come from variables, as demonstrated in the second and third row. Starting from Robot Framework 2.7.6, keywords can also be run with arguments using upper case `AND` as a separator between keywords. The keywords are executed so that the first argument is the first keyword and proceeding arguments until the first `AND` are arguments to it. First argument after the first `AND` is the second keyword and proceeding arguments until the next `AND` are its arguments. And so on. Examples: | Run Keywords | Initialize database | db1 | AND | Start servers | server1 | server2 | | Run Keywords | Initialize database | ${DB NAME} | AND | Start servers | @{SERVERS} | AND | Clear logs | | Run Keywords | ${KW} | AND | @{KW WITH ARGS} | Notice that the `AND` control argument must be used explicitly and thus cannot itself come from a variable. If you need to use literal `AND` string as argument, you can either use variables or escape it with a backslash like `\\AND`. """ errors = [] for kw, args in self._split_run_keywords(list(keywords)): try: self.run_keyword(kw, *args) except ExecutionPassed, err: err.set_earlier_failures(errors) raise err except ExecutionFailed, err: errors.extend(err.get_errors()) if not err.can_continue(self._context.in_teardown): break if errors: raise ExecutionFailures(errors) def _split_run_keywords(self, keywords): if 'AND' not in keywords: for name in self._variables.replace_list(keywords): yield name, () else: for name, args in self._split_run_keywords_from_and(keywords): yield name, args def _split_run_keywords_from_and(self, keywords): while 'AND' in keywords: index = keywords.index('AND') yield self._resolve_run_keywords_name_and_args(keywords[:index]) keywords = keywords[index+1:] yield self._resolve_run_keywords_name_and_args(keywords) def _resolve_run_keywords_name_and_args(self, kw_call): kw_call = self._variables.replace_list(kw_call, replace_until=1) if not kw_call: raise DataError('Incorrect use of AND') return kw_call[0], kw_call[1:] def run_keyword_if(self, condition, name, *args): """Runs the given keyword with the given arguments, if `condition` is true. The given `condition` is evaluated similarly as with `Should Be True` keyword, and `name` and `*args` have same semantics as with `Run Keyword`. Example, a simple if/else construct: | ${status} | ${value} = | `Run Keyword And Ignore Error` | `My Keyword` | | `Run Keyword If` | '${status}' == 'PASS' | `Some Action` | arg | | `Run Keyword Unless` | '${status}' == 'PASS' | `Another Action` | In this example, only either `Some Action` or `Another Action` is executed, based on the status of `My Keyword`. Instead of `Run Keyword And Ignore Error` you can also use `Run Keyword And Return Status`. Starting from Robot version 2.7.4, this keyword supports also optional ELSE and ELSE IF branches. Both of these are defined in `*args` and must use exactly format `ELSE` or `ELSE IF`, respectively. ELSE branches must contain first the name of the keyword to execute and then its possible arguments. ELSE IF branches must first contain a condition, like the first argument to this keyword, and then the keyword to execute and its possible arguments. It is possible to have ELSE branch after ELSE IF and to have multiple ELSE IF branches. Given previous example, if/else construct can also be created like this: | ${status} | ${value} = | `Run Keyword And Ignore Error` | My Keyword | | `Run Keyword If` | '${status}' == 'PASS' | `Some Action` | arg | ELSE | `Another Action` | Using ELSE and/or ELSE IF branches is especially handy if you are interested in the return value. This is illustrated by the example below that also demonstrates using ELSE IF and ELSE together: | ${result} = | `Run Keyword If` | ${rc} == 0 | `Zero return value` | | ... | ELSE IF | 0 < ${rc} < 42 | `Normal return value` | | ... | ELSE IF | ${rc} < 0 | `Negative return value` | ${rc} | arg2 | | ... | ELSE | `Abnormal return value` | ${rc} | Notice that ELSE and ELSE IF control arguments must be used explicitly and thus cannot come from variables. If you need to use literal ELSE and ELSE IF strings as arguments, you can either use variables or escape them with a backslash like `\\ELSE` and `\\ELSE IF`. Starting from Robot Framework 2.8, Python's [http://docs.python.org/2/library/os.html|os] and [http://docs.python.org/2/library/sys.html|sys] modules are automatically imported when evaluating the `condition`. Attributes they contain can thus be used in the condition: | `Run Keyword If` | os.sep == '/' | `Unix Keyword` | | ... | ELSE IF | sys.platform.startswith('java') | `Jython Keyword` | | ... | ELSE | `Windows Keyword` | """ args, branch = self._split_elif_or_else_branch(args) if self._is_true(condition): return self.run_keyword(name, *args) return branch() def _split_elif_or_else_branch(self, args): if 'ELSE IF' in args: args, branch = self._split_branch(args, 'ELSE IF', 2, 'condition and keyword') return args, lambda: self.run_keyword_if(*branch) if 'ELSE' in args: args, branch = self._split_branch(args, 'ELSE', 1, 'keyword') return args, lambda: self.run_keyword(*branch) return args, lambda: None def _split_branch(self, args, control_word, required, required_error): index = list(args).index(control_word) branch = self._variables.replace_list(args[index+1:], required) if len(branch) < required: raise DataError('%s requires %s.' % (control_word, required_error)) return args[:index], branch def run_keyword_unless(self, condition, name, *args): """Runs the given keyword with the given arguments, if `condition` is false. See `Run Keyword If` for more information and an example. """ if not self._is_true(condition): return self.run_keyword(name, *args) def run_keyword_and_ignore_error(self, name, *args): """Runs the given keyword with the given arguments and ignores possible error. This keyword returns two values, so that the first is either 'PASS' or 'FAIL', depending on the status of the executed keyword. The second value is either the return value of the keyword or the received error message. See `Run Keyword And Return Status` If you are only interested in the execution status. The keyword name and arguments work as in `Run Keyword`. See `Run Keyword If` for a usage example. Starting from Robot Framework 2.5 errors caused by invalid syntax, timeouts, or fatal exceptions are not caught by this keyword. """ try: return 'PASS', self.run_keyword(name, *args) except ExecutionFailed, err: if err.dont_continue: raise return 'FAIL', unicode(err) def run_keyword_and_return_status(self, name, *args): """Runs the given keyword with given arguments and returns the status as a Boolean value. This keyword returns `True` if the keyword that is executed succeeds and `False` if it fails. This is useful, for example, in combination with `Run Keyword If`. If you are interested in the error message or return value, use `Run Keyword And Ignore Error` instead. The keyword name and arguments work as in `Run Keyword`. Example: | ${passed} = | `Run Keyword And Return Status` | Keyword | args | | `Run Keyword If` | ${passed} | Another keyword | New in Robot Framework 2.7.6. """ status, _ = self.run_keyword_and_ignore_error(name, *args) return status == 'PASS' def run_keyword_and_continue_on_failure(self, name, *args): """Runs the keyword and continues execution even if a failure occurs. The keyword name and arguments work as with `Run Keyword`. Example: | Run Keyword And Continue On Failure | Fail | This is a stupid example | | Log | This keyword is executed | This keyword was added in Robot Framework 2.5. The execution is not continued if the failure is caused by invalid syntax, timeout, or fatal exception. """ try: return self.run_keyword(name, *args) except ExecutionFailed, err: if not err.dont_continue: err.continue_on_failure = True raise err def run_keyword_and_expect_error(self, expected_error, name, *args): """Runs the keyword and checks that the expected error occurred. The expected error must be given in the same format as in Robot Framework reports. It can be a pattern containing characters '?', which matches to any single character and '*', which matches to any number of any characters. `name` and `*args` have same semantics as with `Run Keyword`. If the expected error occurs, the error message is returned and it can be further processed/tested, if needed. If there is no error, or the error does not match the expected error, this keyword fails. Examples: | Run Keyword And Expect Error | My error | Some Keyword | arg1 | arg2 | | ${msg} = | Run Keyword And Expect Error | * | My KW | | Should Start With | ${msg} | Once upon a time in | Starting from Robot Framework 2.5 errors caused by invalid syntax, timeouts, or fatal exceptions are not caught by this keyword. """ try: self.run_keyword(name, *args) except ExecutionFailed, err: if err.dont_continue: raise else: raise AssertionError("Expected error '%s' did not occur" % expected_error) if not self._matches(unicode(err), expected_error): raise AssertionError("Expected error '%s' but got '%s'" % (expected_error, err)) return unicode(err) def repeat_keyword(self, times, name, *args): """Executes the specified keyword multiple times. `name` and `args` define the keyword that is executed similarly as with `Run Keyword`, and `times` specifies how many the keyword should be executed. `times` can be given as an integer or as a string that can be converted to an integer. It can also have postfix 'times' or 'x' (case and space insensitive) to make the expression easier to read. If `times` is zero or negative, the keyword is not executed at all. This keyword fails immediately if any of the execution rounds fails. Examples: | Repeat Keyword | 5 times | Goto Previous Page | | Repeat Keyword | ${var} | Some Keyword | arg1 | arg2 | """ times = utils.normalize(str(times)) if times.endswith('times'): times = times[:-5] elif times.endswith('x'): times = times[:-1] times = self._convert_to_integer(times) if times <= 0: self.log("Keyword '%s' repeated zero times" % name) for i in xrange(times): self.log("Repeating keyword, round %d/%d" % (i+1, times)) self.run_keyword(name, *args) def wait_until_keyword_succeeds(self, timeout, retry_interval, name, *args): """Waits until the specified keyword succeeds or the given timeout expires. `name` and `args` define the keyword that is executed similarly as with `Run Keyword`. If the specified keyword does not succeed within `timeout`, this keyword fails. `retry_interval` is the time to wait before trying to run the keyword again after the previous run has failed. Both `timeout` and `retry_interval` must be given in Robot Framework's time format (e.g. '1 minute', '2 min 3 s', '4.5'). Errors caused by invalid syntax, test or keyword timeouts, or fatal exceptions are not caught by this keyword. Example: | Wait Until Keyword Succeeds | 2 min | 5 sec | My keyword | arg1 | arg2 | Running the same keyword multiple times inside this keyword can create lots of output and considerably increase the size of the generated output files. Starting from Robot Framework 2.7, it is possible to remove unnecessary keywords from the outputs using `--RemoveKeywords WUKS` command line option. """ timeout = utils.timestr_to_secs(timeout) retry_interval = utils.timestr_to_secs(retry_interval) maxtime = time.time() + timeout error = None while not error: try: return self.run_keyword(name, *args) except ExecutionFailed, err: if err.dont_continue: raise if time.time() > maxtime: error = unicode(err) else: time.sleep(retry_interval) raise AssertionError("Timeout %s exceeded. The last error was: %s" % (utils.secs_to_timestr(timeout), error)) def set_variable_if(self, condition, *values): """Sets variable based on the given condition. The basic usage is giving a condition and two values. The given condition is first evaluated the same way as with the `Should Be True` keyword. If the condition is true, then the first value is returned, and otherwise the second value is returned. The second value can also be omitted, in which case it has a default value None. This usage is illustrated in the examples below, where `${rc}` is assumed to be zero. | ${var1} = | Set Variable If | ${rc} == 0 | zero | nonzero | | ${var2} = | Set Variable If | ${rc} > 0 | value1 | value2 | | ${var3} = | Set Variable If | ${rc} > 0 | whatever | | => | ${var1} = 'zero' | ${var2} = 'value2' | ${var3} = None It is also possible to have 'Else If' support by replacing the second value with another condition, and having two new values after it. If the first condition is not true, the second is evaluated and one of the values after it is returned based on its truth value. This can be continued by adding more conditions without a limit. | ${var} = | Set Variable If | ${rc} == 0 | zero | | ... | ${rc} > 0 | greater than zero | less then zero | | | | ${var} = | Set Variable If | | ... | ${rc} == 0 | zero | | ... | ${rc} == 1 | one | | ... | ${rc} == 2 | two | | ... | ${rc} > 2 | greater than two | | ... | ${rc} < 0 | less than zero | Use `Get Variable Value` if you need to set variables dynamically based on whether a variable exist or not. """ values = self._verify_values_for_set_variable_if(list(values)) if self._is_true(condition): return self._variables.replace_scalar(values[0]) values = self._verify_values_for_set_variable_if(values[1:], True) if len(values) == 1: return self._variables.replace_scalar(values[0]) return self.run_keyword('BuiltIn.Set Variable If', *values[0:]) def _verify_values_for_set_variable_if(self, values, default=False): if not values: if default: return [None] raise RuntimeError('At least one value is required') if is_list_var(values[0]): values[:1] = [utils.escape(item) for item in self._variables[values[0]]] return self._verify_values_for_set_variable_if(values) return values def run_keyword_if_test_failed(self, name, *args): """Runs the given keyword with the given arguments, if the test failed. This keyword can only be used in a test teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ test = self._get_test_in_teardown('Run Keyword If Test Failed') if not test.passed: return self.run_keyword(name, *args) def run_keyword_if_test_passed(self, name, *args): """Runs the given keyword with the given arguments, if the test passed. This keyword can only be used in a test teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ test = self._get_test_in_teardown('Run Keyword If Test Passed') if test.passed: return self.run_keyword(name, *args) def run_keyword_if_timeout_occurred(self, name, *args): """Runs the given keyword if either a test or a keyword timeout has occurred. This keyword can only be used in a test teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. Available in Robot Framework 2.5 and newer. """ self._get_test_in_teardown('Run Keyword If Timeout Occurred') if self._context.timeout_occurred: return self.run_keyword(name, *args) def _get_test_in_teardown(self, kwname): ctx = self._context if ctx.test and ctx.in_test_teardown: return ctx.test raise RuntimeError("Keyword '%s' can only be used in test teardown" % kwname) def run_keyword_if_all_critical_tests_passed(self, name, *args): """Runs the given keyword with the given arguments, if all critical tests passed. This keyword can only be used in suite teardown. Trying to use it in any other place will result in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ suite = self._get_suite_in_teardown('Run Keyword If ' 'All Critical Tests Passed') if suite.statistics.critical.failed == 0: return self.run_keyword(name, *args) def run_keyword_if_any_critical_tests_failed(self, name, *args): """Runs the given keyword with the given arguments, if any critical tests failed. This keyword can only be used in a suite teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ suite = self._get_suite_in_teardown('Run Keyword If ' 'Any Critical Tests Failed') if suite.statistics.critical.failed > 0: return self.run_keyword(name, *args) def run_keyword_if_all_tests_passed(self, name, *args): """Runs the given keyword with the given arguments, if all tests passed. This keyword can only be used in a suite teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ suite = self._get_suite_in_teardown('Run Keyword If All Tests Passed') if suite.statistics.all.failed == 0: return self.run_keyword(name, *args) def run_keyword_if_any_tests_failed(self, name, *args): """Runs the given keyword with the given arguments, if one or more tests failed. This keyword can only be used in a suite teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ suite = self._get_suite_in_teardown('Run Keyword If Any Tests Failed') if suite.statistics.all.failed > 0: return self.run_keyword(name, *args) def _get_suite_in_teardown(self, kwname): if not self._context.in_suite_teardown: raise RuntimeError("Keyword '%s' can only be used in suite teardown" % kwname) return self._context.suite class _Control: def continue_for_loop(self): """Skips the current for loop iteration and continues from the next. Skips the remaining keywords in the current for loop iteration and continues from the next one. Can be used directly in a for loop or in a keyword that the loop uses. Example: | :FOR | ${var} | IN | @{VALUES} | | | Run Keyword If | '${var}' == 'CONTINUE' | Continue For Loop | | | Do Something | ${var} | See `Continue For Loop If` to conditionally continue a for loop without using `Run Keyword If` or other wrapper keywords. New in Robot Framework 2.8. """ self.log("Continuing for loop from the next iteration.") raise ContinueForLoop() def continue_for_loop_if(self, condition): """Skips the current for loop iteration if the `condition` is true. A wrapper for `Continue For Loop` to continue a for loop based on the given condition. The condition is evaluated using the same semantics as with `Should Be True` keyword. Example: | :FOR | ${var} | IN | @{VALUES} | | | Continue For Loop If | '${var}' == 'CONTINUE' | | | Do Something | ${var} | New in Robot Framework 2.8. """ if self._is_true(condition): self.continue_for_loop() def exit_for_loop(self): """Stops executing the enclosing for loop. Exits the enclosing for loop and continues execution after it. Can be used directly in a for loop or in a keyword that the loop uses. Example: | :FOR | ${var} | IN | @{VALUES} | | | Run Keyword If | '${var}' == 'EXIT' | Exit For Loop | | | Do Something | ${var} | See `Exit For Loop If` to conditionally exit a for loop without using `Run Keyword If` or other wrapper keywords. New in Robot Framework 2.5.2. """ self.log("Exiting for loop altogether.") raise ExitForLoop() def exit_for_loop_if(self, condition): """Stops executing the enclosing for loop if the `condition` is true. A wrapper for `Exit For Loop` to exit a for loop based on the given condition. The condition is evaluated using the same semantics as with `Should Be True` keyword. Example: | :FOR | ${var} | IN | @{VALUES} | | | Exit For Loop If | '${var}' == 'EXIT' | | | Do Something | ${var} | New in Robot Framework 2.8. """ if self._is_true(condition): self.exit_for_loop() @run_keyword_variant(resolve=0) def return_from_keyword(self, *return_values): """Returns from the enclosing user keyword. This keyword can be used to return from a user keyword with PASS status without executing it fully. It is also possible to return values similarly as with the `[Return]` setting. For more detailed information about working with the return values, see the User Guide. This keyword is typically wrapped to some other keyword, such as `Run Keyword If` or `Run Keyword If Test Passed`, to return based on a condition: | Run Keyword If | ${rc} < 0 | Return From Keyword | | Run Keyword If Test Passed | Return From Keyword | It is possible to use this keyword to return from a keyword also inside a for loop. That, as well as returning values, is demonstrated by the `Find Index` keyword in the following somewhat advanced example. Notice that it is often a good idea to move this kind of complicated logic into a test library. | ***** Variables ***** | @{LIST} = foo baz | | ***** Test Cases ***** | Example | ${index} = Find Index baz @{LIST} | Should Be Equal ${index} ${1} | ${index} = Find Index non existing @{LIST} | Should Be Equal ${index} ${-1} | | ***** Keywords ***** | Find Index | [Arguments] ${element} @{items} | ${index} = Set Variable ${0} | :FOR ${item} IN @{items} | \\ Run Keyword If '${item}' == '${element}' Return From Keyword ${index} | \\ ${index} = Set Variable ${index + 1} | Return From Keyword ${-1} # Also [Return] would work here. The most common use case, returning based on an expression, can be accomplished directly with `Return From Keyword If`. Both of these keywords are new in Robot Framework 2.8. See also `Run Keyword And Return` and `Run Keyword And Return If`. """ self.log('Returning from the enclosing user keyword.') raise ReturnFromKeyword(return_values) @run_keyword_variant(resolve=1) def return_from_keyword_if(self, condition, *return_values): """Returns from the enclosing user keyword if `condition` is true. A wrapper for `Return From Keyword` to return based on the given condition. The condition is evaluated using the same semantics as with `Should Be True` keyword. Given the same example as in `Return From Keyword`, we can rewrite the `Find Index` keyword as follows: | ***** Keywords ***** | Find Index | [Arguments] ${element} @{items} | ${index} = Set Variable ${0} | :FOR ${item} IN @{items} | \\ Return From Keyword If '${item}' == '${element}' ${index} | \\ ${index} = Set Variable ${index + 1} | Return From Keyword ${-1} # Also [Return] would work here. See also `Run Keyword And Return` and `Run Keyword And Return If`. New in Robot Framework 2.8. """ if self._is_true(condition): self.return_from_keyword(*return_values) @run_keyword_variant(resolve=1) def run_keyword_and_return(self, name, *args): """Runs the specified keyword and returns from the enclosing user keyword. The keyword to execute is defined with `name` and `*args` exactly like with `Run Keyword`. After running the keyword, returns from the enclosing user keyword and passes possible return value from the executed keyword further. Returning from a keyword has exactly same semantics as with `Return From Keyword`. Example: | `Run Keyword And Return` | `My Keyword` | arg1 | arg2 | | # Above is equivalent to: | | ${result} = | `My Keyword` | arg1 | arg2 | | `Return From Keyword` | ${result} | | | Use `Run Keyword And Return If` if you want to run keyword and return based on a condition. New in Robot Framework 2.8.2. """ ret = self.run_keyword(name, *args) self.return_from_keyword(ret) @run_keyword_variant(resolve=2) def run_keyword_and_return_if(self, condition, name, *args): """Runs the specified keyword and returns from the enclosing user keyword. A wrapper for `Run Keyword And Return` to run and return based on the given `condition`. The condition is evaluated using the same semantics as with `Should Be True` keyword. Example: | `Run Keyword And Return If` | ${rc} > 0 | `My Keyword` | arg1 | arg2 | | # Above is equivalent to: | | `Run Keyword If` | ${rc} > 0 | `Run Keyword And Return` | `My Keyword ` | arg1 | arg2 | Use `Return From Keyword If` if you want to return a certain value based on a condition. New in Robot Framework 2.8.2. """ if self._is_true(condition): self.run_keyword_and_return(name, *args) def pass_execution(self, message, *tags): """Skips rest of the current test, setup, or teardown with PASS status. This keyword can be used anywhere in the test data, but the place where used affects the behavior: - When used in any setup or teardown (suite, test or keyword), passes that setup or teardown. Possible keyword teardowns of the started keywords are executed. Does not affect execution or statuses otherwise. - When used in a test outside setup or teardown, passes that particular test case. Possible test and keyword teardowns are executed. Possible continuable failures before this keyword is used, as well as failures in executed teardowns, will fail the execution. It is mandatory to give a message explaining why execution was passed. By default the message is considered plain text, but starting it with `*HTML*` allows using HTML formatting. It is also possible to modify test tags passing tags after the message similarly as with `Fail` keyword. Tags starting with a hyphen (e.g. `-regression`) are removed and others added. Tags are modified using `Set Tags` and `Remove Tags` internally, and the semantics setting and removing them are the same as with these keywords. Examples: | Pass Execution | All features available in this version tested. | | Pass Execution | Deprecated test. | deprecated | -regression | This keyword is typically wrapped to some other keyword, such as `Run Keyword If`, to pass based on a condition. The most common case can be handled also with `Pass Execution If`: | Run Keyword If | ${rc} < 0 | Pass Execution | Negative values are cool. | | Pass Execution If | ${rc} < 0 | Negative values are cool. | Passing execution in the middle of a test, setup or teardown should be used with care. In the worst case it leads to tests that skip all the parts that could actually uncover problems in the tested application. In cases where execution cannot continue do to external factors, it is often safer to fail the test case and make it non-critical. New in Robot Framework 2.8. """ message = message.strip() if not message: raise RuntimeError('Message cannot be empty.') self._set_and_remove_tags(tags) log_message, level = self._get_logged_test_message_and_level(message) self.log('Execution passed with message:\n%s' % log_message, level) raise PassExecution(message) @run_keyword_variant(resolve=1) def pass_execution_if(self, condition, message, *tags): """Conditionally skips rest of the current test, setup, or teardown with PASS status. A wrapper for `Pass Execution` to skip rest of the current test, setup or teardown based the given `condition`. The condition is evaluated similarly as with `Should Be True` keyword, and `message` and `*tags` have same semantics as with `Pass Execution`. Example: | :FOR | ${var} | IN | @{VALUES} | | | Pass Execution If | '${var}' == 'EXPECTED' | Correct value was found | | | Do Something | ${var} | New in Robot Framework 2.8. """ if self._is_true(condition): message = self._variables.replace_string(message) tags = [self._variables.replace_string(tag) for tag in tags] self.pass_execution(message, *tags) class _Misc: def no_operation(self): """Does absolutely nothing.""" def sleep(self, time_, reason=None): """Pauses the test executed for the given time. `time` may be either a number or a time string. Time strings are in a format such as '1 day 2 hours 3 minutes 4 seconds 5milliseconds' or '1d 2h 3m 4s 5ms', and they are fully explained in an appendix of Robot Framework User Guide. Optional `reason` can be used to explain why sleeping is necessary. Both the time slept and the reason are logged. Examples: | Sleep | 42 | | Sleep | 1.5 | | Sleep | 2 minutes 10 seconds | | Sleep | 10s | Wait for a reply | """ seconds = utils.timestr_to_secs(time_) # Python hangs with negative values if seconds < 0: seconds = 0 self._sleep_in_parts(seconds) self.log('Slept %s' % utils.secs_to_timestr(seconds)) if reason: self.log(reason) def _sleep_in_parts(self, seconds): # time.sleep can't be stopped in windows # to ensure that we can signal stop (with timeout) # split sleeping to small pieces endtime = time.time() + float(seconds) while True: remaining = endtime - time.time() if remaining <= 0: break time.sleep(min(remaining, 0.5)) def catenate(self, *items): """Catenates the given items together and returns the resulted string. By default, items are catenated with spaces, but if the first item contains the string 'SEPARATOR=<sep>', the separator '<sep>' is used. Items are converted into strings when necessary. Examples: | ${str1} = | Catenate | Hello | world | | | ${str2} = | Catenate | SEPARATOR=--- | Hello | world | | ${str3} = | Catenate | SEPARATOR= | Hello | world | => | ${str1} = 'Hello world' | ${str2} = 'Hello---world' | ${str3} = 'Helloworld' """ if not items: return '' items = [utils.unic(item) for item in items] if items[0].startswith('SEPARATOR='): sep = items[0][len('SEPARATOR='):] items = items[1:] else: sep = ' ' return sep.join(items) def log(self, message, level='INFO', html=False, console=False, repr=False): """Logs the given message with the given level. Valid levels are TRACE, DEBUG, INFO (default), HTML, and WARN. Messages below the current active log level are ignored. See `Set Log Level` keyword and `--loglevel` command line option for more details about setting the level. Messages logged with the WARN level will be automatically visible also in the console and in the `Test Execution Errors` section in the log file. If the `html` argument is given any true value (e.g. any non-empty string), the message will be considered HTML and special characters such as `<` in it are not escaped. For example, logging `<img src="image.png">` creates an image when `html` is true, but otherwise the message is that exact string. An alternative to using the `html` argument is using the `HTML` pseudo log level. It logs the message as HTML using the INFO level. If the `console` argument is true, the message will be written to the console where test execution was started from in addition to the log file. This keyword always uses the standard output stream and adds a newline after the written message. Use `Log To Console` instead if either of these is undesirable, If the `repr` argument is true, the given item will be passed through Python's `repr()` function before logging it. This is useful, for example, when working with strings or bytes containing invisible characters. Examples: | Log | Hello, world! | | | # Normal INFO message. | | Log | Warning, world! | WARN | | # Warning. | | Log | <b>Hello</b>, world! | html=yes | | # INFO message as HTML. | | Log | <b>Hello</b>, world! | HTML | | # Same as above. | | Log | <b>Hello</b>, world! | DEBUG | html=true | # DEBUG as HTML. | | Log | Hello, console! | console=yes | | # Write also to the console. | | Log | Hyvä \\x00 | repr=yes | | # Logs `u'Hyv\\xe4 \\x00'` | See `Log Many` if you want to log multiple messages in one go, and `Log To Console` if you only want to write to the console. Arguments `html`, `console`, and `repr` are new in Robot Framework 2.8.2. """ if repr: message = utils.safe_repr(message) logger.write(message, level, html) if console: logger.console(message) def log_many(self, *messages): """Logs the given messages as separate entries using the INFO level. See `Log` and `Log To Console` keywords if you want to use alternative log levels, use HTML, or log to the console. """ for msg in messages: self.log(msg) def log_to_console(self, message, stream='STDOUT', no_newline=False): """Logs the given message to the console. By default uses the standard output stream. Using the standard error stream is possibly by giving the `stream` argument value `STDERR` (case-insensitive). By default appends a newline to the logged message. This can be disabled by giving the `no_newline` argument any true value (e.g. any non-empty string). Examples: | Log To Console | Hello, console! | | | Log To Console | Hello, stderr! | STDERR | | Log To Console | Message starts here and is | no_newline=true | | Log To Console | continued without newline. | | This keyword does not log the message to the normal log file. Use `Log` keyword, possibly with argument `console`, if that is desired. New in Robot Framework 2.8.2. """ logger.console(message, newline=not no_newline, stream=stream) @run_keyword_variant(resolve=0) def comment(self, *messages): """Displays the given messages in the log file as keyword arguments. This keyword does nothing with the arguments it receives, but as they are visible in the log, this keyword can be used to display simple messages. Given arguments are ignored so thoroughly that they can even contain non-existing variables. If you are interested about variable values, you can use the `Log` or `Log Many` keywords. """ pass def set_log_level(self, level): """Sets the log threshold to the specified level and returns the old level. Messages below the level will not logged. The default logging level is INFO, but it can be overridden with the command line option '--loglevel'. The available levels: TRACE, DEBUG, INFO (default), WARN and NONE (no logging). """ try: old = self._context.output.set_log_level(level) except DataError, err: raise RuntimeError(unicode(err)) self._namespace.variables.set_global('${LOG_LEVEL}', level.upper()) self.log('Log level changed from %s to %s' % (old, level.upper())) return old @run_keyword_variant(resolve=0) def import_library(self, name, *args): """Imports a library with the given name and optional arguments. This functionality allows dynamic importing of libraries while tests are running. That may be necessary, if the library itself is dynamic and not yet available when test data is processed. In a normal case, libraries should be imported using the Library setting in the Setting table. This keyword supports importing libraries both using library names and physical paths. When paths are used, they must be given in absolute format. Forward slashes can be used as path separators in all operating systems. It is possible to pass arguments to the imported library and also named argument syntax works if the library supports it. 'WITH NAME' syntax can be used to give a custom name to the imported library. Examples: | Import Library | MyLibrary | | Import Library | ${CURDIR}/../Library.py | arg1 | named=arg2 | | Import Library | ${LIBRARIES}/Lib.java | arg | WITH NAME | JavaLib | """ try: self._namespace.import_library(name, list(args)) except DataError, err: raise RuntimeError(unicode(err)) @run_keyword_variant(resolve=0) def import_variables(self, path, *args): """Imports a variable file with the given path and optional arguments. Variables imported with this keyword are set into the test suite scope similarly when importing them in the Setting table using the Variables setting. These variables override possible existing variables with the same names. This functionality can thus be used to import new variables, for example, for each test in a test suite. The given path must be absolute. Forward slashes can be used as path separator regardless the operating system. Examples: | Import Variables | ${CURDIR}/variables.py | | | | Import Variables | ${CURDIR}/../vars/env.py | arg1 | arg2 | New in Robot Framework 2.5.4. """ try: self._namespace.import_variables(path, list(args), overwrite=True) except DataError, err: raise RuntimeError(unicode(err)) @run_keyword_variant(resolve=0) def import_resource(self, path): """Imports a resource file with the given path. Resources imported with this keyword are set into the test suite scope similarly when importing them in the Setting table using the Resource setting. The given path must be absolute. Forward slashes can be used as path separator regardless the operating system. Examples: | Import Resource | ${CURDIR}/resource.txt | | Import Resource | ${CURDIR}/../resources/resource.html | """ try: self._namespace.import_resource(path) except DataError, err: raise RuntimeError(unicode(err)) def set_library_search_order(self, *libraries): """Sets the resolution order to use when a name matches multiple keywords. The library search order is used to resolve conflicts when a keyword name in the test data matches multiple keywords. The first library (or resource, see below) containing the keyword is selected and that keyword implementation used. If the keyword is not found from any library (or resource), test executing fails the same way as when the search order is not set. When this keyword is used, there is no need to use the long `LibraryName.Keyword Name` notation. For example, instead of having | MyLibrary.Keyword | arg | | MyLibrary.Another Keyword | | MyLibrary.Keyword | xxx | you can have | Set Library Search Order | MyLibrary | | Keyword | arg | | Another Keyword | | Keyword | xxx | Starting from Robot Framework 2.6.2 this keyword can be used also to set the order of keywords in different resource files. In this case resource names must be given without paths or extensions like: | Set Library Search Order | resource | another_resource | *NOTE:* - The search order is valid only in the suite where this keywords is used. - Keywords in resources always have higher priority than keywords in libraries regardless the search order. - The old order is returned and can be used to reset the search order later. - Starting from RF 2.6.2, library and resource names in the search order are both case and space insensitive. """ old_order = self._namespace.library_search_order self._namespace.library_search_order = libraries return old_order def keyword_should_exist(self, name, msg=None): """Fails unless the given keyword exists in the current scope. Fails also if there are more than one keywords with the same name. Works both with the short name (e.g. `Log`) and the full name (e.g. `BuiltIn.Log`). The default error message can be overridden with the `msg` argument. New in Robot Framework 2.6. See also `Variable Should Exist`. """ try: handler = self._namespace._get_handler(name) if not handler: raise DataError("No keyword with name '%s' found." % name) if isinstance(handler, UserErrorHandler): handler.run() except DataError, err: raise AssertionError(msg or unicode(err)) def get_time(self, format='timestamp', time_='NOW'): """Returns the given time in the requested format. How time is returned is determined based on the given `format` string as follows. Note that all checks are case-insensitive. 1) If `format` contains the word 'epoch', the time is returned in seconds after the UNIX epoch (1970-01-01 00:00:00 UTC). The return value is always an integer. 2) If `format` contains any of the words 'year', 'month', 'day', 'hour', 'min', or 'sec', only the selected parts are returned. The order of the returned parts is always the one in the previous sentence and the order of words in `format` is not significant. The parts are returned as zero-padded strings (e.g. May -> '05'). 3) Otherwise (and by default) the time is returned as a timestamp string in the format '2006-02-24 15:08:31'. By default this keyword returns the current local time, but that can be altered using `time` argument as explained below. Note that all checks involving strings are case-insensitive. 1) If `time` is a number, or a string that can be converted to a number, it is interpreted as seconds since the UNIX epoch. This documentation was originally written about 1177654467 seconds after the epoch. 2) If `time` is a timestamp, that time will be used. Valid timestamp formats are 'YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss'. 3) If `time` is equal to 'NOW' (default), the current local time is used. This time is got using Python's 'time.time()' function. 4) If `time` is equal to 'UTC', the current time in [http://en.wikipedia.org/wiki/Coordinated_Universal_Time|UTC] is used. This time is got using 'time.time() + time.altzone' in Python. 5) If `time` is in the format like 'NOW - 1 day' or 'UTC + 1 hour 30 min', the current local/UTC time plus/minus the time specified with the time string is used. The time string format is described in an appendix of Robot Framework User Guide. Examples (expecting the current local time is 2006-03-29 15:06:21): | ${time} = | Get Time | | | | | ${secs} = | Get Time | epoch | | | | ${year} = | Get Time | return year | | | | ${yyyy} | ${mm} | ${dd} = | Get Time | year,month,day | | @{time} = | Get Time | year month day hour min sec | | | | ${y} | ${s} = | Get Time | seconds and year | | => | ${time} = '2006-03-29 15:06:21' | ${secs} = 1143637581 | ${year} = '2006' | ${yyyy} = '2006', ${mm} = '03', ${dd} = '29' | @{time} = ['2006', '03', '29', '15', '06', '21'] | ${y} = '2006' | ${s} = '21' Examples (expecting the current local time is 2006-03-29 15:06:21 and UTC time is 2006-03-29 12:06:21): | ${time} = | Get Time | | 1177654467 | # Time given as epoch seconds | | ${secs} = | Get Time | sec | 2007-04-27 09:14:27 | # Time given as a timestamp | | ${year} = | Get Time | year | NOW | # The local time of execution | | @{time} = | Get Time | hour min sec | NOW + 1h 2min 3s | # 1h 2min 3s added to the local time | | @{utc} = | Get Time | hour min sec | UTC | # The UTC time of execution | | ${hour} = | Get Time | hour | UTC - 1 hour | # 1h subtracted from the UTC time | => | ${time} = '2007-04-27 09:14:27' | ${secs} = 27 | ${year} = '2006' | @{time} = ['16', '08', '24'] | @{utc} = ['12', '06', '21'] | ${hour} = '11' Support for UTC time was added in Robot Framework 2.7.5 but it did not work correctly until 2.7.7. """ return utils.get_time(format, utils.parse_time(time_)) def evaluate(self, expression, modules=None, namespace=None): """Evaluates the given expression in Python and returns the results. `modules` argument can be used to specify a comma separated list of Python modules to be imported and added to the namespace of the evaluated `expression`. `namespace` argument can be used to pass a custom namespace as a dictionary. Possible `modules` are added to this namespace. Examples (expecting `${result}` is 3.14): | ${status} = | Evaluate | 0 < ${result} < 10 | | ${down} = | Evaluate | int(${result}) | | ${up} = | Evaluate | math.ceil(${result}) | math | | ${random} = | Evaluate | random.randint(0, sys.maxint) | random,sys | | ${ns} = | Create Dictionary | x=${4} | y=${2} | | ${result} = | Evaluate | x*10 + y | namespace=${ns} | => | ${status} = True | ${down} = 3 | ${up} = 4.0 | ${random} = <random integer> | ${result} = 42 Notice that instead of creating complicated expressions, it is recommended to move the logic into a test library. Support for `namespace` is a new feature in Robot Framework 2.8.4. """ namespace = namespace or {} modules = modules.replace(' ', '').split(',') if modules else [] namespace.update((m, __import__(m)) for m in modules if m) try: return eval(expression, namespace) except: raise RuntimeError("Evaluating expression '%s' failed: %s" % (expression, utils.get_error_message())) def call_method(self, object, method_name, *args): """Calls the named method of the given object with the provided arguments. The possible return value from the method is returned and can be assigned to a variable. Keyword fails both if the object does not have a method with the given name or if executing the method raises an exception. Examples: | Call Method | ${hashtable} | put | myname | myvalue | | ${isempty} = | Call Method | ${hashtable} | isEmpty | | | Should Not Be True | ${isempty} | | | | | ${value} = | Call Method | ${hashtable} | get | myname | | Should Be Equal | ${value} | myvalue | | | """ try: method = getattr(object, method_name) except AttributeError: raise RuntimeError("Object '%s' does not have a method '%s'" % (object, method_name)) return method(*args) def regexp_escape(self, *patterns): """Returns each argument string escaped for use as a regular expression. This keyword can be used to escape strings to be used with `Should Match Regexp` and `Should Not Match Regexp` keywords. Escaping is done with Python's re.escape() function. Examples: | ${escaped} = | Regexp Escape | ${original} | | @{strings} = | Regexp Escape | @{strings} | """ if len(patterns) == 0: return '' if len(patterns) == 1: return re.escape(patterns[0]) return [re.escape(p) for p in patterns] def set_test_message(self, message, append=False): """Sets message for the current test case. If the optional `append` argument is given any value considered `true` in Python, for example, any non-empty string, the given `message` is added after the possible earlier message by joining the messages with a space. In test teardown this keyword can alter the possible failure message, but otherwise failures override messages set by this keyword. Notice that in teardown the initial message is available as a built-in variable `${TEST MESSAGE}`. It is possible to use HTML format in the message by starting the message with `*HTML*`. Examples: | Set Test Message | My message | | | Set Test Message | is continued. | append=yes | | Should Be Equal | ${TEST MESSAGE} | My message is continued. | | Set Test Message | `*`HTML`*` <b>Hello!</b> | | This keyword can not be used in suite setup or suite teardown. New in Robot Framework 2.5. Support for `append` was added in 2.7.7 and HTML support in 2.8. """ test = self._namespace.test if not test: raise RuntimeError("'Set Test Message' keyword cannot be used in " "suite setup or teardown") test.message = self._get_possibly_appended_value(test.message, message, append) message, level = self._get_logged_test_message_and_level(test.message) self.log('Set test message to:\n%s' % message, level) def _get_possibly_appended_value(self, initial, new, append): if not isinstance(new, unicode): new = utils.unic(new) return '%s %s' % (initial, new) if append and initial else new def _get_logged_test_message_and_level(self, message): if message.startswith('*HTML*'): return message[6:].lstrip(), 'HTML' return message, 'INFO' def set_test_documentation(self, doc, append=False): """Sets documentation for the current test case. By default the possible existing documentation is overwritten, but this can be changed using the optional `append` argument similarly as with `Set Test Message` keyword. The current test documentation is available as a built-in variable `${TEST DOCUMENTATION}`. This keyword can not be used in suite setup or suite teardown. New in Robot Framework 2.7. Support for `append` was added in 2.7.7. """ test = self._namespace.test if not test: raise RuntimeError("'Set Test Documentation' keyword cannot be used in " "suite setup or teardown") test.doc = self._get_possibly_appended_value(test.doc, doc, append) self._variables.set_test('${TEST_DOCUMENTATION}', test.doc) self.log('Set test documentation to:\n%s' % test.doc) def set_suite_documentation(self, doc, append=False, top=False): """Sets documentation for the current test suite. By default the possible existing documentation is overwritten, but this can be changed using the optional `append` argument similarly as with `Set Test Message` keyword. This keyword sets the documentation of the current suite by default. If the optional `top` argument is given any value considered `true` in Python, for example, any non-empty string, the documentation of the top level suite is altered instead. The documentation of the current suite is available as a built-in variable `${SUITE DOCUMENTATION}`. New in Robot Framework 2.7. Support for `append` and `top` were added in 2.7.7. """ ns = self._get_namespace(top) suite = ns.suite suite.doc = self._get_possibly_appended_value(suite.doc, doc, append) ns.variables.set_suite('${SUITE_DOCUMENTATION}', suite.doc) self.log('Set suite documentation to:\n%s' % suite.doc) def set_suite_metadata(self, name, value, append=False, top=False): """Sets metadata for the current test suite. By default possible existing metadata values are overwritten, but this can be changed using the optional `append` argument similarly as with `Set Test Message` keyword. This keyword sets the metadata of the current suite by default. If the optional `top` argument is given any value considered `true` in Python, for example, any non-empty string, the metadata of the top level suite is altered instead. The metadata of the current suite is available as a built-in variable `${SUITE METADATA}` in a Python dictionary. Notice that modifying this variable directly has no effect on the actual metadata the suite has. New in Robot Framework 2.7.4. Support for `append` and `top` were added in 2.7.7. """ if not isinstance(name, unicode): name = utils.unic(name) ns = self._get_namespace(top) metadata = ns.suite.metadata metadata[name] = self._get_possibly_appended_value(metadata.get(name, ''), value, append) ns.variables.set_suite('${SUITE_METADATA}', metadata.copy()) self.log("Set suite metadata '%s' to value '%s'." % (name, metadata[name])) def set_tags(self, *tags): """Adds given `tags` for the current test or all tests in a suite. When this keyword is used inside a test case, that test gets the specified tags and other tests are not affected. If this keyword is used in a suite setup, all test cases in that suite, recursively, gets the given tags. It is a failure to use this keyword in a suite teardown. The current tags are available as a built-in variable `@{TEST TAGS}`. See `Remove Tags` if you want to remove certain tags and `Fail` if you want to fail the test case after setting and/or removing tags. """ ctx = self._context if ctx.test: ctx.test.tags.add(tags) ctx.variables.set_test('@{TEST_TAGS}', list(ctx.test.tags)) elif not ctx.in_suite_teardown: ctx.suite.set_tags(tags, persist=True) else: raise RuntimeError("'Set Tags' cannot be used in suite teardown.") self.log('Set tag%s %s.' % (utils.plural_or_not(tags), utils.seq2str(tags))) def remove_tags(self, *tags): """Removes given `tags` from the current test or all tests in a suite. Tags can be given exactly or using a pattern where '*' matches anything and '?' matches one character. This keyword can affect either one test case or all test cases in a test suite similarly as `Set Tags` keyword. The current tags are available as a built-in variable `@{TEST TAGS}`. Example: | Remove Tags | mytag | something-* | ?ython | See `Set Tags` if you want to add certain tags and `Fail` if you want to fail the test case after setting and/or removing tags. """ ctx = self._context if ctx.test: ctx.test.tags.remove(tags) ctx.variables.set_test('@{TEST_TAGS}', list(ctx.test.tags)) elif not ctx.in_suite_teardown: ctx.suite.set_tags(remove=tags, persist=True) else: raise RuntimeError("'Remove Tags' cannot be used in suite teardown.") self.log('Removed tag%s %s.' % (utils.plural_or_not(tags), utils.seq2str(tags))) def get_library_instance(self, name): """Returns the currently active instance of the specified test library. This keyword makes it easy for test libraries to interact with other test libraries that have state. This is illustrated by the Python example below: | from robot.libraries.BuiltIn import BuiltIn | | def title_should_start_with(expected): | seleniumlib = BuiltIn().get_library_instance('SeleniumLibrary') | title = seleniumlib.get_title() | if not title.startswith(expected): | raise AssertionError("Title '%s' did not start with '%s'" | % (title, expected)) It is also possible to use this keyword in the test data and pass the returned library instance to another keyword. If a library is imported with a custom name, the `name` used to get the instance must be that name and not the original library name. """ try: return self._namespace.get_library_instance(name) except DataError, err: raise RuntimeError(unicode(err)) class BuiltIn(_Verify, _Converter, _Variables, _RunKeyword, _Control, _Misc): """An always available standard library with often needed keywords. `BuiltIn` is Robot Framework's standard library that provides a set of generic keywords needed often. It is imported automatically and thus always available. The provided keywords can be used, for example, for verifications (e.g. `Should Be Equal`, `Should Contain`), conversions (e.g. `Convert To Integer`) and for various other purposes (e.g. `Log`, `Sleep`, `Run Keyword If`, `Set Global Variable`). Many of the keywords accept an optional error message to use if the keyword fails. Starting from Robot Framework 2.8, it is possible to use HTML in these messages by prefixing them with `*HTML*`. See `Fail` keyword for a usage example. Notice that using HTML in messages is not limited to BuiltIn library but works with any error message. """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() @property def _context(self): return EXECUTION_CONTEXTS.current @property def _namespace(self): return self._context.namespace def _get_namespace(self, top=False): ctx = EXECUTION_CONTEXTS.top if top else EXECUTION_CONTEXTS.current return ctx.namespace @property def _variables(self): return self._namespace.variables def _matches(self, string, pattern): # Must use this instead of fnmatch when string may contain newlines. matcher = utils.Matcher(pattern, caseless=False, spaceless=False) return matcher.match(string) def _is_true(self, condition): if isinstance(condition, basestring): condition = self.evaluate(condition, modules='os,sys') return bool(condition) def register_run_keyword(library, keyword, args_to_process=None): """Registers 'run keyword' so that its arguments can be handled correctly. 1) Why is this method needed Keywords running other keywords internally (normally using `Run Keyword` or some variants of it in BuiltIn) must have the arguments meant to the internally executed keyword handled specially to prevent processing them twice. This is done ONLY for keywords registered using this method. If the register keyword has same name as any keyword from Robot Framework standard libraries, it can be used without getting warnings. Normally there is a warning in such cases unless the keyword is used in long format (e.g. MyLib.Keyword). Starting from Robot Framework 2.5.2, keywords executed by registered run keywords can be tested in dry-run mode they have 'name' argument which takes the name of the executed keyword. 2) How to use this method `library` is the name of the library where the registered keyword is implemented. `keyword` can be either a function or method implementing the keyword, or name of the implemented keyword as a string. `args_to_process` is needed when `keyword` is given as a string, and it defines how many of the arguments to the registered keyword must be processed normally. When `keyword` is a method or function, this information is got directly from it so that varargs (those specified with syntax '*args') are not processed but others are. 3) Examples from robot.libraries.BuiltIn import BuiltIn, register_run_keyword def my_run_keyword(name, *args): # do something return BuiltIn().run_keyword(name, *args) # Either one of these works register_run_keyword(__name__, my_run_keyword) register_run_keyword(__name__, 'My Run Keyword', 1) ------------- from robot.libraries.BuiltIn import BuiltIn, register_run_keyword class MyLibrary: def my_run_keyword_if(self, expression, name, *args): # do something return BuiltIn().run_keyword_if(expression, name, *args) # Either one of these works register_run_keyword('MyLibrary', MyLibrary.my_run_keyword_if) register_run_keyword('MyLibrary', 'my_run_keyword_if', 2) """ RUN_KW_REGISTER.register_run_keyword(library, keyword, args_to_process) for name in [attr for attr in dir(_RunKeyword) if not attr.startswith('_')]: register_run_keyword('BuiltIn', getattr(_RunKeyword, name)) del name, attr
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 time from java.awt import GridLayout from java.awt.event import WindowAdapter from javax.swing import JLabel, JOptionPane, JPanel, JPasswordField, JTextField from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \ YES_NO_OPTION, OK_CANCEL_OPTION, OK_OPTION, DEFAULT_OPTION class _SwingDialog(object): def __init__(self, pane): self._pane = pane def show(self): self._show_dialog(self._pane) return self._get_value(self._pane) def _show_dialog(self, pane): dialog = pane.createDialog(None, 'Robot Framework') dialog.setModal(False) dialog.setAlwaysOnTop(True) dialog.addWindowFocusListener(pane.focus_listener) dialog.show() while dialog.isShowing(): time.sleep(0.2) dialog.dispose() def _get_value(self, pane): value = pane.getInputValue() return value if value != UNINITIALIZED_VALUE else None class MessageDialog(_SwingDialog): def __init__(self, message): pane = WrappedOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION) _SwingDialog.__init__(self, pane) class InputDialog(_SwingDialog): def __init__(self, message, default, hidden=False): self._input_field = JPasswordField() if hidden else JTextField() self._input_field.setText(default) self._input_field.selectAll() panel = JPanel(layout=GridLayout(2, 1)) panel.add(JLabel(message)) panel.add(self._input_field) pane = WrappedOptionPane(panel, PLAIN_MESSAGE, OK_CANCEL_OPTION) pane.set_focus_listener(self._input_field) _SwingDialog.__init__(self, pane) def _get_value(self, pane): if pane.getValue() != OK_OPTION: return None return self._input_field.getText() class SelectionDialog(_SwingDialog): def __init__(self, message, options): pane = WrappedOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION) pane.setWantsInput(True) pane.setSelectionValues(options) _SwingDialog.__init__(self, pane) class PassFailDialog(_SwingDialog): def __init__(self, message): pane = WrappedOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION, None, ['PASS', 'FAIL'], 'PASS') _SwingDialog.__init__(self, pane) def _get_value(self, pane): return pane.getValue() == 'PASS' class WrappedOptionPane(JOptionPane): focus_listener = None def getMaxCharactersPerLineCount(self): return 120 def set_focus_listener(self, component): self.focus_listener = WindowFocusListener(component) class WindowFocusListener(WindowAdapter): def __init__(self, component): self.component = component def windowGainedFocus(self, event): self.component.requestFocusInWindow()
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 executing tests. This module can be executed from the command line using the following approaches:: python -m robot.run python path/to/robot/run.py Instead of ``python`` it is possible to use also other Python interpreters. This module is also used by the installed ``pybot``, ``jybot`` and ``ipybot`` start-up scripts. This module also provides :func:`run` and :func:`run_cli` functions that can be used programmatically. Other code is for internal usage. """ USAGE = """Robot Framework -- A generic test automation framework Version: <VERSION> Usage: pybot|jybot|ipybot [options] data_sources or: python|jython|ipy -m robot.run [options] data_sources or: python|jython|ipy path/to/robot/run.py [options] data_sources or: java -jar robotframework.jar run [options] data_sources Robot Framework is a Python-based keyword-driven test automation framework for acceptance level testing and acceptance test-driven development (ATDD). It has an easy-to-use tabular syntax for creating test cases and its testing capabilities can be extended by test libraries implemented either with Python or Java. Users can also create new keywords from existing ones using the same simple syntax that is used for creating test cases. Depending is Robot Framework installed using Python, Jython, or IronPython interpreter, it has a start-up script, `pybot`, `jybot` or `ipybot`, respectively. Alternatively, it is possible to directly execute `robot.run` module (e.g. `python -m robot.run`) or `robot/run.py` script using a selected interpreter. Finally, there is also a standalone JAR distribution. Data sources given to Robot Framework are either test case files or directories containing them and/or other directories. Single test case file creates a test suite containing all the test cases in it and a directory containing test case files creates a higher level test suite with test case files or other directories as sub test suites. If multiple data sources are given, a virtual top level suite containing suites generated from given data sources is created. By default Robot Framework creates an XML output file and a log and a report in HTML format, but this can be configured using various options listed below. Outputs in HTML format are for human consumption and XML output for integration with other systems. XML outputs can also be combined and otherwise further processed with `rebot` tool. Run `rebot --help` for more information. Robot Framework is open source software released under Apache License 2.0. Its copyrights are owned and development supported by Nokia Solutions and Networks. For more information about the framework see http://robotframework.org/. Options ======= -N --name name Set the name of the top level test suite. Underscores in the name are converted to spaces. Default name is created from the name of the executed data source. -D --doc documentation Set the documentation of the top level test suite. Underscores in the documentation are converted to spaces and it may also contain simple HTML formatting (e.g. *bold* and http://url/). -M --metadata name:value * Set metadata of the top level test suite. Underscores in the name and value are converted to spaces. Value can contain same HTML formatting as --doc. Example: `--metadata version:1.2` -G --settag tag * Sets given tag(s) to all executed test cases. -t --test name * Select test cases to run by name or long name. Name is case and space insensitive and it can also be a simple pattern where `*` matches anything and `?` matches any char. If using `*` and `?` in the console is problematic see --escape and --argumentfile. -s --suite name * Select test suites to run by name. When this option is used with --test, --include or --exclude, only test cases in matching suites and also matching other filtering criteria are selected. Name can be a simple pattern similarly as with --test and it can contain parent name separated with a dot. For example `-s X.Y` selects suite `Y` only if its parent is `X`. -i --include tag * Select test cases to run by tag. Similarly as name with --test, tag is case and space insensitive and it is possible to use patterns with `*` and `?` as wildcards. Tags and patterns can also be combined together with `AND`, `OR`, and `NOT` operators. Examples: --include foo --include bar* --include fooANDbar* -e --exclude tag * Select test cases not to run by tag. These tests are not run even if included with --include. Tags are matched using the rules explained with --include. -R --rerunfailed output Select failed tests from an earlier output file to be re-executed. Equivalent to selecting same tests individually using --test option. --runfailed output Deprecated since RF 2.8.4. Use --rerunfailed instead. -c --critical tag * Tests having given tag are considered critical. If no critical tags are set, all tags are critical. Tags can be given as a pattern like with --include. -n --noncritical tag * Tests with given tag are not critical even if they have a tag set with --critical. Tag can be a pattern. -v --variable name:value * Set variables in the test data. Only scalar variables are supported and name is given without `${}`. See --escape for how to use special characters and --variablefile for a more powerful variable setting mechanism that allows also list variables. Examples: --variable str:Hello => ${str} = `Hello` -v str:Hi_World -E space:_ => ${str} = `Hi World` -v x: -v y:42 => ${x} = ``, ${y} = `42` -V --variablefile path * File to read variables from (e.g. `path/vars.py`). Example file: | import random | __all__ = [`scalar`, `LIST__var`, `integer`] | scalar = `Hello world!` | LIST__var = [`Hello`, `list`, `world`] | integer = random.randint(1,10) => ${scalar} = `Hello world!` @{var} = [`Hello`,`list`,`world`] ${integer} = <random integer from 1 to 10> -d --outputdir dir Where to create output files. The default is the directory where tests are run from and the given path is considered relative to that unless it is absolute. -o --output file XML output file. Given path, similarly as paths given to --log, --report, --xunit, and --debugfile, is relative to --outputdir unless given as an absolute path. Other output files are created based on XML output files after the test execution and XML outputs can also be further processed with Rebot tool. Can be disabled by giving a special value `NONE`. In this case, also log and report are automatically disabled. Default: output.xml -l --log file HTML log file. Can be disabled by giving a special value `NONE`. Default: log.html Examples: `--log mylog.html`, `-l NONE` -r --report file HTML report file. Can be disabled with `NONE` similarly as --log. Default: report.html -x --xunit file xUnit compatible result file. Not created unless this option is specified. --xunitfile file Deprecated. Use --xunit instead. --xunitskipnoncritical Mark non-critical tests on xUnit output as skipped. -b --debugfile file Debug file written during execution. Not created unless this option is specified. -T --timestampoutputs When this option is used, timestamp in a format `YYYYMMDD-hhmmss` is added to all generated output files between their basename and extension. For example `-T -o output.xml -r report.html -l none` creates files like `output-20070503-154410.xml` and `report-20070503-154410.html`. --splitlog Split log file into smaller pieces that open in browser transparently. --logtitle title Title for the generated test log. The default title is `<Name Of The Suite> Test Log`. Underscores in the title are converted into spaces in all titles. --reporttitle title Title for the generated test report. The default title is `<Name Of The Suite> Test Report`. --reportbackground colors Background colors to use in the report file. Either `all_passed:critical_passed:failed` or `passed:failed`. Both color names and codes work. Examples: --reportbackground green:yellow:red --reportbackground #00E:#E00 -L --loglevel level Threshold level for logging. Available levels: TRACE, DEBUG, INFO (default), WARN, NONE (no logging). Use syntax `LOGLEVEL:DEFAULT` to define the default visible log level in log files. Examples: --loglevel DEBUG --loglevel DEBUG:INFO --suitestatlevel level How many levels to show in `Statistics by Suite` in log and report. By default all suite levels are shown. Example: --suitestatlevel 3 --tagstatinclude tag * Include only matching tags in `Statistics by Tag` and `Test Details` in log and report. By default all tags set in test cases are shown. Given `tag` can also be a simple pattern (see e.g. --test). --tagstatexclude tag * Exclude matching tags from `Statistics by Tag` and `Test Details`. This option can be used with --tagstatinclude similarly as --exclude is used with --include. --tagstatcombine tags:name * Create combined statistics based on tags. These statistics are added into `Statistics by Tag` and matching tests into `Test Details`. If optional `name` is not given, name of the combined tag is got from the specified tags. Tags are combined using the rules explained in --include. Examples: --tagstatcombine requirement-* --tagstatcombine tag1ANDtag2:My_name --tagdoc pattern:doc * Add documentation to tags matching given pattern. Documentation is shown in `Test Details` and also as a tooltip in `Statistics by Tag`. Pattern can contain characters `*` (matches anything) and `?` (matches any char). Documentation can contain formatting similarly as with --doc option. Examples: --tagdoc mytag:My_documentation --tagdoc regression:*See*_http://info.html --tagdoc owner-*:Original_author --tagstatlink pattern:link:title * Add external links into `Statistics by Tag`. Pattern can contain characters `*` (matches anything) and `?` (matches any char). Characters matching to wildcard expressions can be used in link and title with syntax %N, where N is index of the match (starting from 1). In title underscores are automatically converted to spaces. Examples: --tagstatlink mytag:http://my.domain:Link --tagstatlink bug-*:http://tracker/id=%1:Bug_Tracker --removekeywords all|passed|name:<pattern>|for|wuks|none * Remove keyword data from the generated log file. Keywords containing warnings are not removed except in `all` mode. all: remove data from all keywords passed: remove data only from keywords in passed test cases and suites name:<pattern>: remove data from keywords that match the given pattern. The pattern is matched against the full name of the keyword (e.g. 'MyLib.Keyword', 'resource.Second Keyword'), is case, space, and underscore insensitive, and may contain `*` and `?` as wildcards. Examples: --removekeywords name:Lib.HugeKw --removekeywords name:myresource.* for: remove passed iterations from for loops wuks: remove all but the last failing keyword inside `BuiltIn.Wait Until Keyword Succeeds` --flattenkeywords name:<pattern> * Flattens matching keywords in the generated log file. Matching keywords get all messages from their child keywords and children are discarded otherwise. Matching rules are same as with `--removekeywords name:<pattern>`. --listener class * A class for monitoring test execution. Gets notifications e.g. when a test case starts and ends. Arguments to listener class can be given after class name, using colon as separator. For example: --listener MyListenerClass:arg1:arg2 --warnonskippedfiles If this option is used, skipped test data files will cause a warning that is visible in the console output and the log file. By default skipped files only cause an info level syslog message. --nostatusrc Sets the return code to zero regardless of failures in test cases. Error codes are returned normally. --runemptysuite Executes tests also if the top level test suite is empty. Useful e.g. with --include/--exclude when it is not an error that no test matches the condition. --dryrun Verifies test data and runs tests so that library keywords are not executed. --exitonfailure Stops test execution if any critical test fails. --skipteardownonexit Causes teardowns to be skipped if test execution is stopped prematurely. --randomize all|suites|tests|none Randomizes the test execution order. all: randomizes both suites and tests suites: randomizes suites tests: randomizes tests none: no randomization (default) --runmode mode * Deprecated in version 2.8. Use individual options --dryrun, --exitonfailure, --skipteardownonexit, or --randomize instead. -W --monitorwidth chars Width of the monitor output. Default is 78. -C --monitorcolors auto|on|ansi|off Use colors on console output or not. auto: use colors when output not redirected (default) on: always use colors ansi: like `on` but use ANSI colors also on Windows off: disable colors altogether Note that colors do not work with Jython on Windows. -K --monitormarkers auto|on|off Show `.` (success) or `F` (failure) on console when top level keywords in test cases end. Values have same semantics as with --monitorcolors. -P --pythonpath path * Additional locations (directories, ZIPs, JARs) where to search test libraries from when they are imported. Multiple paths can be given by separating them with a colon (`:`) or using this option several times. Given path can also be a glob pattern matching multiple paths but then it normally must be escaped or quoted. Examples: --pythonpath libs/ --pythonpath /opt/testlibs:mylibs.zip:yourlibs -E star:STAR -P lib/STAR.jar -P mylib.jar -E --escape what:with * Escape characters which are problematic in console. `what` is the name of the character to escape and `with` is the string to escape it with. Note that all given arguments, incl. data sources, are escaped so escape characters ought to be selected carefully. <--------------------ESCAPES------------------------> Examples: --escape space:_ --metadata X:Value_with_spaces -E space:SP -E quot:Q -v var:QhelloSPworldQ -A --argumentfile path * Text file to read more arguments from. Use special path `STDIN` to read contents from the standard input stream. File can have both options and data sources one per line. Contents do not need to be escaped but spaces in the beginning and end of lines are removed. Empty lines and lines starting with a hash character (#) are ignored. Example file: | --include regression | --name Regression Tests | # This is a comment line | my_tests.html | path/to/test/directory/ Examples: --argumentfile argfile.txt --argumentfile STDIN -h -? --help Print usage instructions. --version Print version information. Options that are marked with an asterisk (*) can be specified multiple times. For example, `--test first --test third` selects test cases with name `first` and `third`. If other options are given multiple times, the last value is used. Long option format is case-insensitive. For example, --SuiteStatLevel is equivalent to but easier to read than --suitestatlevel. Long options can also be shortened as long as they are unique. For example, `--logti Title` works while `--lo log.html` does not because the former matches only --logtitle but the latter matches --log, --loglevel and --logtitle. Environment Variables ===================== ROBOT_OPTIONS Space separated list of default options to be placed in front of any explicit options on the command line. ROBOT_SYSLOG_FILE Path to a file where Robot Framework writes internal information about parsing test case files and running tests. Can be useful when debugging problems. If not set, or set to special value `NONE`, writing to the syslog file is disabled. ROBOT_SYSLOG_LEVEL Log level to use when writing to the syslog file. Available levels are the same as for --loglevel command line option and the default is INFO. Examples ======== # Simple test run with `pybot` without options. $ pybot tests.html # Using options and running with `jybot`. $ jybot --include smoke --name Smoke_Tests path/to/tests.txt # Executing `robot.run` module using Python. $ python -m robot.run --test test1 --test test2 test_directory # Running `robot/run.py` script with Jython. $ jython /path/to/robot/run.py tests.robot # Executing multiple test case files and using case-insensitive long options. $ pybot --SuiteStatLevel 2 /my/tests/*.html /your/tests.html # Setting default options and syslog file before running tests. $ export ROBOT_OPTIONS="--critical regression --suitestatlevel 2" $ export ROBOT_SYSLOG_FILE=/tmp/syslog.txt $ pybot tests.tsv """ import sys # 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.conf import RobotSettings from robot.output import LOGGER from robot.reporting import ResultWriter from robot.running import TestSuiteBuilder from robot.utils import Application class RobotFramework(Application): def __init__(self): Application.__init__(self, USAGE, arg_limits=(1,), env_options='ROBOT_OPTIONS', logger=LOGGER) def main(self, datasources, **options): settings = RobotSettings(options) LOGGER.register_console_logger(**settings.console_logger_config) LOGGER.info('Settings:\n%s' % unicode(settings)) suite = TestSuiteBuilder(settings['SuiteNames'], settings['WarnOnSkipped'], settings['RunEmptySuite']).build(*datasources) suite.configure(**settings.suite_config) result = suite.run(settings) LOGGER.info("Tests execution ended. Statistics:\n%s" % result.suite.stat_message) if settings.log or settings.report or settings.xunit: writer = ResultWriter(settings.output if settings.log else result) writer.write_results(settings.get_rebot_settings()) return result.return_code def validate(self, options, arguments): return self._filter_options_without_value(options), arguments def _filter_options_without_value(self, options): return dict((name, value) for name, value in options.items() if value) def run_cli(arguments): """Command line execution entry point for running tests. :param arguments: Command line arguments as a list of strings. For programmatic usage the :func:`run` 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 import run_cli run_cli(['--include', 'tag', 'path/to/tests.html']) """ RobotFramework().execute_cli(arguments) def run(*datasources, **options): """Executes given Robot Framework data sources with given options. Data sources are paths to files and directories, similarly as when running `pybot` command from the command line. Options are given as keyword arguments and their names are same as long command line options except without hyphens. Options that can be given on the command line multiple times can be passed as lists like `include=['tag1', 'tag2']`. If such option is used only once, it can be given also as a single string like `include='tag'`. To capture stdout and/or stderr streams, pass open file objects in as special keyword arguments `stdout` and `stderr`, respectively. A return code is returned similarly as when running on the command line. Example:: from robot import run run('path/to/tests.html', include=['tag1', 'tag2']) with open('stdout.txt', 'w') as stdout: run('t1.txt', 't2.txt', report='r.html', log='NONE', stdout=stdout) Equivalent command line usage:: pybot --include tag1 --include tag2 path/to/tests.html pybot --report r.html --log NONE t1.txt t2.txt > stdout.txt """ return RobotFramework().execute(*datasources, **options) if __name__ == '__main__': run_cli(sys.argv[1:])
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 `Tidy` tool. This module can be executed from the command line using the following approaches:: python -m robot.tidy python path/to/robot/tidy.py Instead of ``python`` it is possible to use also other Python interpreters. This module also provides :class:`Tidy` class and :func:`tidy_cli` function that can be used programmatically. Other code is for internal usage. """ USAGE = """robot.tidy -- Robot Framework test data clean-up tool Version: <VERSION> Usage: python -m robot.tidy [options] inputfile or: python -m robot.tidy [options] inputfile [outputfile] or: python -m robot.tidy --inplace [options] inputfile [more input files] or: python -m robot.tidy --recursive [options] directory Tidy tool can be used to clean up and change format of Robot Framework test data files. The output is written into the standard output stream by default, but an optional output file can be given starting from Robot Framework 2.7.5. Files can also be modified in-place using --inplace or --recursive options. Options ======= -i --inplace Tidy given file(s) so that original file(s) are overwritten (or removed, if the format is changed). When this option is used, it is possible to give multiple input files. Examples: python -m robot.tidy --inplace tests.html python -m robot.tidy --inplace --format txt *.html -r --recursive Process given directory recursively. Files in the directory are processed in-place similarly as when --inplace option is used. -f --format txt|html|tsv|robot Output file format. If omitted, the format of the input file is used. -p --usepipes Use pipe (`|`) as a cell separator in the txt format. -s --spacecount number The number of spaces between cells in the txt format. New in Robot Framework 2.7.3. -l --lineseparator native|windows|unix Line separator to use in outputs. The default is 'native'. native: use operating system's native line separators windows: use Windows line separators (CRLF) unix: use Unix line separators (LF) New in Robot Framework 2.7.6. -h -? --help Show this help. Cleaning up the test data ========================= Test case files created with HTML editors or written by hand can be normalized using Tidy. Tidy always writes consistent headers, consistent order for settings, and consistent amount of whitespace between cells and tables. Examples: python -m robot.tidy messed_up_tests.html cleaned_tests.html python -m robot.tidy --inplace tests.txt Changing the test data format ============================= Robot Framework supports test data in HTML, TSV and TXT formats, and Tidy makes changing between the formats trivial. Input format is always determined based on the extension of the input file. Output format is got from the extension of the output file, when used, and can also be set using the --format option. Examples: python -m robot.tidy tests.html tests.tsv python -m robot.tidy --format tsv --inplace tests.html python -m robot.tidy --format txt --recursive mytests Output encoding =============== All output files are written using UTF-8 encoding. Outputs written to the console use the current console encoding. Alternative execution ===================== In the above examples Tidy is used only with Python, but it works also with Jython and IronPython. Above it is executed as an installed module, but it can also be run as a script like `python path/robot/tidy.py`. """ import os import sys from StringIO import StringIO # 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.errors import DataError from robot.parsing import (ResourceFile, TestDataDirectory, TestCaseFile, disable_curdir_processing) from robot.utils import Application class Tidy(object): """Programmatic API for the `Tidy` tool. Arguments accepted when creating an instance have same semantics as Tidy command line options with same names. """ def __init__(self, format='txt', use_pipes=False, space_count=4, line_separator=os.linesep): self._options = dict(format=format, pipe_separated=use_pipes, txt_separating_spaces=space_count, line_separator=line_separator) def file(self, path, output=None): """Tidy a file. :param path: Path of the input file. :param output: Path of the output file. If not given, output is returned. Use :func:`inplace` to tidy files in-place. """ data = self._parse_data(path) outfile = open(output, 'wb') if output else StringIO() try: self._save_file(data, outfile) if not output: return outfile.getvalue().replace('\r\n', '\n').decode('UTF-8') finally: outfile.close() def inplace(self, *paths): """Tidy file(s) in-place. :param paths: Paths of the files to to process. """ for path in paths: self._save_file(self._parse_data(path)) def directory(self, path): """Tidy a directory. :param path: Path of the directory to process. All files in a directory, recursively, are processed in-place. """ self._save_directory(self._parse_data(path)) @disable_curdir_processing def _parse_data(self, path): if os.path.isdir(path): return TestDataDirectory(source=path).populate() if self._is_init_file(path): path = os.path.dirname(path) return TestDataDirectory(source=path).populate(recurse=False) try: return TestCaseFile(source=path).populate() except DataError: try: return ResourceFile(source=path).populate() except DataError: raise DataError("Invalid data source '%s'." % path) def _is_init_file(self, path): return os.path.splitext(os.path.basename(path))[0].lower() == '__init__' def _save_file(self, data, output=None): source = data.initfile if self._is_directory(data) else data.source if source and not output: os.remove(source) data.save(output=output, **self._options) def _save_directory(self, data): if not self._is_directory(data): self._save_file(data) return if data.initfile: self._save_file(data) for child in data.children: self._save_directory(child) def _is_directory(self, data): return hasattr(data, 'initfile') class TidyCommandLine(Application): """Command line interface for the `Tidy` tool. Typically :func:`tidy_cli` is a better suited for command line style usage and :class:`Tidy` for other programmatic usage. """ def __init__(self): Application.__init__(self, USAGE, arg_limits=(1,)) def main(self, arguments, recursive=False, inplace=False, format='txt', usepipes=False, spacecount=4, lineseparator=os.linesep): tidy = Tidy(format=format, use_pipes=usepipes, space_count=spacecount, line_separator=lineseparator) if recursive: tidy.directory(arguments[0]) elif inplace: tidy.inplace(*arguments) else: output = tidy.file(*arguments) self.console(output) def validate(self, opts, args): validator = ArgumentValidator() validator.mode_and_arguments(args, **opts) opts['format'] = validator.format(args, **opts) opts['lineseparator'] = validator.line_sep(**opts) if not opts['spacecount']: opts.pop('spacecount') else: opts['spacecount'] = validator.spacecount(opts['spacecount']) return opts, args class ArgumentValidator(object): def mode_and_arguments(self, args, recursive, inplace, **others): validators = {(True, True): self._recursive_and_inplace_together, (True, False): self._recursive_mode_arguments, (False, True): self._inplace_mode_arguments, (False, False): self._default_mode_arguments} validators[(recursive, inplace)](args) def _recursive_and_inplace_together(self, args): raise DataError('--recursive and --inplace can not be used together.') def _recursive_mode_arguments(self, args): if len(args) != 1: raise DataError('--recursive requires exactly one argument.') if not os.path.isdir(args[0]): raise DataError('--recursive requires input to be a directory.') def _inplace_mode_arguments(self, args): if not all(os.path.isfile(path) for path in args): raise DataError('--inplace requires inputs to be files.') def _default_mode_arguments(self, args): if len(args) not in (1, 2): raise DataError('Default mode requires 1 or 2 arguments.') if not os.path.isfile(args[0]): raise DataError('Default mode requires input to be a file.') def format(self, args, format, inplace, recursive, **others): if not format: if inplace or recursive or len(args) < 2: return None format = os.path.splitext(args[1])[1][1:] format = format.upper() if format not in ('TXT', 'TSV', 'HTML', 'ROBOT'): raise DataError("Invalid format '%s'." % format) return format def line_sep(self, lineseparator, **others): values = {'native': os.linesep, 'windows': '\r\n', 'unix': '\n'} try: return values[(lineseparator or 'native').lower()] except KeyError: raise DataError("Invalid line separator '%s'." % lineseparator) def spacecount(self, spacecount): try: spacecount = int(spacecount) if spacecount < 2: raise ValueError except ValueError: raise DataError('--spacecount must be an integer greater than 1.') return spacecount def tidy_cli(arguments): """Executes `Tidy` similarly as from the command line. :param arguments: Command line arguments as a list of strings. Example:: from robot.tidy import tidy_cli tidy_cli(['--format', 'txt', 'tests.html']) """ TidyCommandLine().execute_cli(arguments) if __name__ == '__main__': tidy_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 from robot.errors import DataError from robot.model import SuiteNamePatterns from robot.output import LOGGER from robot.utils import get_error_message, unic from .datarow import DataRow from .tablepopulators import (SettingTablePopulator, VariableTablePopulator, TestTablePopulator, KeywordTablePopulator, NullPopulator) from .htmlreader import HtmlReader from .tsvreader import TsvReader from .txtreader import TxtReader from .restreader import RestReader READERS = {'html': HtmlReader, 'htm': HtmlReader, 'xhtml': HtmlReader, 'tsv': TsvReader , 'rst': RestReader, 'rest': RestReader, 'txt': TxtReader, 'robot': TxtReader} # Hook for external tools for altering ${CURDIR} processing PROCESS_CURDIR = True class FromFilePopulator(object): _populators = {'setting': SettingTablePopulator, 'variable': VariableTablePopulator, 'test case': TestTablePopulator, 'keyword': KeywordTablePopulator} def __init__(self, datafile): self._datafile = datafile self._populator = NullPopulator() self._curdir = self._get_curdir(datafile.directory) def _get_curdir(self, path): return path.replace('\\','\\\\') if path else None def populate(self, path): LOGGER.info("Parsing file '%s'." % path) source = self._open(path) try: self._get_reader(path).read(source, self) except: raise DataError(get_error_message()) finally: source.close() def _open(self, path): if not os.path.isfile(path): raise DataError("Data source does not exist.") try: # IronPython handles BOM incorrectly if not using binary mode: # http://code.google.com/p/robotframework/issues/detail?id=1580 return open(path, 'rb') except: raise DataError(get_error_message()) def _get_reader(self, path): extension = os.path.splitext(path.lower())[-1][1:] try: return READERS[extension]() except KeyError: raise DataError("Unsupported file format '%s'." % extension) def start_table(self, header): self._populator.populate() table = self._datafile.start_table(DataRow(header).all) self._populator = self._populators[table.type](table) \ if table is not None else NullPopulator() return bool(self._populator) def eof(self): self._populator.populate() def add(self, row): if PROCESS_CURDIR and self._curdir: row = self._replace_curdirs_in(row) data = DataRow(row) if data: self._populator.add(data) def _replace_curdirs_in(self, row): return [cell.replace('${CURDIR}', self._curdir) for cell in row] class FromDirectoryPopulator(object): ignored_prefixes = ('_', '.') ignored_dirs = ('CVS',) def populate(self, path, datadir, include_suites=None, warn_on_skipped=False, recurse=True): LOGGER.info("Parsing test data directory '%s'" % path) include_suites = self._get_include_suites(path, include_suites or []) init_file, children = self._get_children(path, include_suites) if init_file: self._populate_init_file(datadir, init_file) if recurse: self._populate_children(datadir, children, include_suites, warn_on_skipped) def _populate_init_file(self, datadir, init_file): datadir.initfile = init_file try: FromFilePopulator(datadir).populate(init_file) except DataError, err: LOGGER.error(unicode(err)) def _populate_children(self, datadir, children, include_suites, warn_on_skipped): for child in children: try: datadir.add_child(child, include_suites) except DataError, err: self._log_failed_parsing("Parsing data source '%s' failed: %s" % (child, unicode(err)), warn_on_skipped) def _log_failed_parsing(self, message, warn): if warn: LOGGER.warn(message) else: LOGGER.info(message) def _get_include_suites(self, path, incl_suites): if not isinstance(incl_suites, SuiteNamePatterns): incl_suites = SuiteNamePatterns(self._create_included_suites(incl_suites)) if not incl_suites: return incl_suites # If a directory is included, also all its children should be included. if self._directory_is_included(path, incl_suites): return SuiteNamePatterns() return incl_suites def _create_included_suites(self, incl_suites): for suite in incl_suites: yield suite while '.' in suite: suite = suite.split('.', 1)[1] yield suite def _directory_is_included(self, path, incl_suites): name = os.path.basename(os.path.normpath(path)) return self._is_in_included_suites(name, incl_suites) def _get_children(self, dirpath, incl_suites): init_file = None children = [] for name, path in self._list_dir(dirpath): if self._is_init_file(name, path): if not init_file: init_file = path else: LOGGER.error("Ignoring second test suite init file '%s'." % path) elif self._is_included(name, path, incl_suites): children.append(path) else: LOGGER.info("Ignoring file or directory '%s'." % name) return init_file, children def _list_dir(self, path): # os.listdir returns Unicode entries when path is Unicode names = os.listdir(unic(path)) for name in sorted(names, key=unicode.lower): # unic needed to handle nfc/nfd normalization on OSX yield unic(name), unic(os.path.join(path, name)) def _is_init_file(self, name, path): if not os.path.isfile(path): return False base, extension = os.path.splitext(name.lower()) return base == '__init__' and extension[1:] in READERS def _is_included(self, name, path, incl_suites): if name.startswith(self.ignored_prefixes): return False if os.path.isdir(path): return name not in self.ignored_dirs base, extension = os.path.splitext(name.lower()) return (extension[1:] in READERS and self._is_in_included_suites(base, incl_suites)) def _is_in_included_suites(self, name, incl_suites): return not incl_suites or incl_suites.match(self._split_prefix(name)) def _split_prefix(self, name): return name.split('__', 1)[-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 re from .comments import CommentCache, Comments from .settings import Documentation, MetadataList class Populator(object): """Explicit interface for all populators.""" def add(self, row): raise NotImplementedError def populate(self): raise NotImplementedError class NullPopulator(Populator): def add(self, row): pass def populate(self): pass def __nonzero__(self): return False class _TablePopulator(Populator): def __init__(self, table): self._table = table self._populator = NullPopulator() self._comment_cache = CommentCache() def add(self, row): if self._is_cacheable_comment_row(row): self._comment_cache.add(row) else: self._add(row) def _is_cacheable_comment_row(self, row): return row.is_commented() def _add(self, row): if self._is_continuing(row): self._consume_comments() else: self._populator.populate() self._populator = self._get_populator(row) self._consume_standalone_comments() self._populator.add(row) def _is_continuing(self, row): return row.is_continuing() and self._populator def _get_populator(self, row): raise NotImplementedError def _consume_comments(self): self._comment_cache.consume_with(self._populator.add) def _consume_standalone_comments(self): self._consume_comments() def populate(self): self._consume_comments() self._populator.populate() class SettingTablePopulator(_TablePopulator): def _get_populator(self, row): row.handle_old_style_metadata() setter = self._table.get_setter(row.head) if not setter: return NullPopulator() if setter.im_class is Documentation: return DocumentationPopulator(setter) if setter.im_class is MetadataList: return MetadataPopulator(setter) return SettingPopulator(setter) class VariableTablePopulator(_TablePopulator): def _get_populator(self, row): return VariablePopulator(self._table.add, row.head) def _consume_standalone_comments(self): self._comment_cache.consume_with(self._populate_standalone_comment) def _populate_standalone_comment(self, comment): populator = self._get_populator(comment) populator.add(comment) populator.populate() def populate(self): self._populator.populate() self._consume_standalone_comments() class _StepContainingTablePopulator(_TablePopulator): def _is_continuing(self, row): return row.is_indented() and self._populator or row.is_commented() def _is_cacheable_comment_row(self, row): return row.is_commented() and not self._populator class TestTablePopulator(_StepContainingTablePopulator): def _get_populator(self, row): return TestCasePopulator(self._table.add) class KeywordTablePopulator(_StepContainingTablePopulator): def _get_populator(self, row): return UserKeywordPopulator(self._table.add) class ForLoopPopulator(Populator): def __init__(self, for_loop_creator): self._for_loop_creator = for_loop_creator self._loop = None self._populator = NullPopulator() self._declaration = [] self._declaration_comments = [] def add(self, row): dedented_row = row.dedent() if not self._loop: declaration_ready = self._populate_declaration(row) if not declaration_ready: return self._create_for_loop() if not row.is_continuing(): self._populator.populate() self._populator = StepPopulator(self._loop.add_step) self._populator.add(dedented_row) def _populate_declaration(self, row): if row.starts_for_loop() or row.is_continuing(): self._declaration.extend(row.dedent().data) self._declaration_comments.extend(row.comments) return False return True def _create_for_loop(self): self._loop = self._for_loop_creator(self._declaration, self._declaration_comments) def populate(self): if not self._loop: self._create_for_loop() self._populator.populate() class _TestCaseUserKeywordPopulator(Populator): def __init__(self, test_or_uk_creator): self._test_or_uk_creator = test_or_uk_creator self._test_or_uk = None self._populator = NullPopulator() self._comment_cache = CommentCache() def add(self, row): if row.is_commented(): self._comment_cache.add(row) return if not self._test_or_uk: self._test_or_uk = self._test_or_uk_creator(row.head) dedented_row = row.dedent() if dedented_row: self._handle_data_row(dedented_row) def _handle_data_row(self, row): if not self._continues(row): self._populator.populate() self._populator = self._get_populator(row) self._comment_cache.consume_with(self._populate_comment_row) else: self._comment_cache.consume_with(self._populator.add) self._populator.add(row) def _populate_comment_row(self, crow): populator = StepPopulator(self._test_or_uk.add_step) populator.add(crow) populator.populate() def populate(self): self._populator.populate() self._comment_cache.consume_with(self._populate_comment_row) def _get_populator(self, row): if row.starts_test_or_user_keyword_setting(): setter = self._setting_setter(row) if not setter: return NullPopulator() if setter.im_class is Documentation: return DocumentationPopulator(setter) return SettingPopulator(setter) if row.starts_for_loop(): return ForLoopPopulator(self._test_or_uk.add_for_loop) return StepPopulator(self._test_or_uk.add_step) def _continues(self, row): return row.is_continuing() and self._populator or \ (isinstance(self._populator, ForLoopPopulator) and row.is_indented()) def _setting_setter(self, row): setting_name = row.test_or_user_keyword_setting_name() return self._test_or_uk.get_setter(setting_name) class TestCasePopulator(_TestCaseUserKeywordPopulator): _item_type = 'test case' class UserKeywordPopulator(_TestCaseUserKeywordPopulator): _item_type = 'keyword' class _PropertyPopulator(Populator): def __init__(self, setter): self._setter = setter self._value = [] self._comments = Comments() self._data_added = False def add(self, row): if not row.is_commented(): self._add(row) self._comments.add(row) def _add(self, row): self._value.extend(row.tail if not self._data_added else row.data) self._data_added = True class VariablePopulator(_PropertyPopulator): def __init__(self, setter, name): _PropertyPopulator.__init__(self, setter) self._name = name def populate(self): self._setter(self._name, self._value, self._comments.value) class SettingPopulator(_PropertyPopulator): def populate(self): self._setter(self._value, self._comments.value) class DocumentationPopulator(_PropertyPopulator): _end_of_line_escapes = re.compile(r'(\\+)n?$') def populate(self): self._setter(self._value, self._comments.value) def _add(self, row): self._add_to_value(row.dedent().data) def _add_to_value(self, data): joiner = self._row_joiner() if joiner: self._value.append(joiner) self._value.append(' '.join(data)) def _row_joiner(self): if self._is_empty(): return None return self._joiner_based_on_eol_escapes() def _is_empty(self): return not self._value or \ (len(self._value) == 1 and self._value[0] == '') def _joiner_based_on_eol_escapes(self): match = self._end_of_line_escapes.search(self._value[-1]) if not match or len(match.group(1)) % 2 == 0: return '\\n' if not match.group(0).endswith('n'): return ' ' return None class MetadataPopulator(DocumentationPopulator): def __init__(self, setter): _PropertyPopulator.__init__(self, setter) self._name = None def populate(self): self._setter(self._name, self._value, self._comments.value) def _add(self, row): data = row.dedent().data if self._name is None: self._name = data[0] if data else '' data = data[1:] self._add_to_value(data) class StepPopulator(_PropertyPopulator): def _add(self, row): self._value.extend(row.data) def populate(self): if self._value or self._comments: self._setter(self._value, self._comments.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 os import copy from robot.errors import DataError from robot.variables import is_var from robot.output import LOGGER from robot import utils from robot.writer import DataFileWriter from .comments import Comment from .populators import FromFilePopulator, FromDirectoryPopulator from .settings import (Documentation, Fixture, Timeout, Tags, Metadata, Library, Resource, Variables, Arguments, Return, Template, MetadataList, ImportList) def TestData(parent=None, source=None, include_suites=None, warn_on_skipped=False): """Parses a file or directory to a corresponding model object. :param parent: (optional) parent to be used in creation of the model object. :param source: path where test data is read from. :returns: :class:`~.model.TestDataDirectory` if `source` is a directory, :class:`~.model.TestCaseFile` otherwise. """ if os.path.isdir(source): return TestDataDirectory(parent, source).populate(include_suites, warn_on_skipped) return TestCaseFile(parent, source).populate() class _TestData(object): _setting_table_names = 'Setting', 'Settings', 'Metadata' _variable_table_names = 'Variable', 'Variables' _testcase_table_names = 'Test Case', 'Test Cases' _keyword_table_names = 'Keyword', 'Keywords', 'User Keyword', 'User Keywords' def __init__(self, parent=None, source=None): self.parent = parent self.source = utils.abspath(source) if source else None self.children = [] self._tables = utils.NormalizedDict(self._get_tables()) def _get_tables(self): for names, table in [(self._setting_table_names, self.setting_table), (self._variable_table_names, self.variable_table), (self._testcase_table_names, self.testcase_table), (self._keyword_table_names, self.keyword_table)]: for name in names: yield name, table def start_table(self, header_row): try: table = self._tables[header_row[0]] except (KeyError, IndexError): return None if not self._table_is_allowed(table): return None table.set_header(header_row) return table @property def name(self): return self._format_name(self._get_basename()) if self.source else None def _get_basename(self): return os.path.splitext(os.path.basename(self.source))[0] def _format_name(self, name): name = self._strip_possible_prefix_from_name(name) name = name.replace('_', ' ').strip() return name.title() if name.islower() else name def _strip_possible_prefix_from_name(self, name): return name.split('__', 1)[-1] @property def keywords(self): return self.keyword_table.keywords @property def imports(self): return self.setting_table.imports def report_invalid_syntax(self, message, level='ERROR'): initfile = getattr(self, 'initfile', None) path = os.path.join(self.source, initfile) if initfile else self.source LOGGER.write("Error in file '%s': %s" % (path, message), level) def save(self, **options): """Writes this datafile to disk. :param options: Configuration for writing. These are passed to :py:class:`~robot.writer.datafilewriter.WritingContext` as keyword arguments. See also :py:class:`robot.writer.datafilewriter.DataFileWriter` """ return DataFileWriter(**options).write(self) class TestCaseFile(_TestData): """The parsed test case file object. :param parent: parent object to be used in creation of the model object. :param source: path where test data is read from. """ def __init__(self, parent=None, source=None): self.directory = os.path.dirname(source) if source else None self.setting_table = TestCaseFileSettingTable(self) self.variable_table = VariableTable(self) self.testcase_table = TestCaseTable(self) self.keyword_table = KeywordTable(self) _TestData.__init__(self, parent, source) def populate(self): FromFilePopulator(self).populate(self.source) self._validate() return self def _validate(self): if not self.testcase_table.is_started(): raise DataError('File has no test case table.') def _table_is_allowed(self, table): return True def has_tests(self): return True def __iter__(self): for table in [self.setting_table, self.variable_table, self.testcase_table, self.keyword_table]: yield table class ResourceFile(_TestData): """The parsed resource file object. :param source: path where resource file is read from. """ def __init__(self, source=None): self.directory = os.path.dirname(source) if source else None self.setting_table = ResourceFileSettingTable(self) self.variable_table = VariableTable(self) self.testcase_table = TestCaseTable(self) self.keyword_table = KeywordTable(self) _TestData.__init__(self, source=source) def populate(self): FromFilePopulator(self).populate(self.source) self._report_status() return self def _report_status(self): if self.setting_table or self.variable_table or self.keyword_table: LOGGER.info("Imported resource file '%s' (%d keywords)." % (self.source, len(self.keyword_table.keywords))) else: LOGGER.warn("Imported resource file '%s' is empty." % self.source) def _table_is_allowed(self, table): if table is self.testcase_table: raise DataError("Resource file '%s' contains a test case table " "which is not allowed." % self.source) return True def __iter__(self): for table in [self.setting_table, self.variable_table, self.keyword_table]: yield table class TestDataDirectory(_TestData): """The parsed test data directory object. Contains hiearchical structure of other :py:class:`.TestDataDirectory` and :py:class:`.TestCaseFile` objects. :param parent: parent object to be used in creation of the model object. :param source: path where test data is read from. """ def __init__(self, parent=None, source=None): self.directory = source self.initfile = None self.setting_table = InitFileSettingTable(self) self.variable_table = VariableTable(self) self.testcase_table = TestCaseTable(self) self.keyword_table = KeywordTable(self) _TestData.__init__(self, parent, source) def populate(self, include_suites=None, warn_on_skipped=False, recurse=True): FromDirectoryPopulator().populate(self.source, self, include_suites, warn_on_skipped, recurse) self.children = [ch for ch in self.children if ch.has_tests()] return self def _get_basename(self): return os.path.basename(self.source) def _table_is_allowed(self, table): if table is self.testcase_table: LOGGER.error("Test suite init file in '%s' contains a test case " "table which is not allowed." % self.source) return False return True def add_child(self, path, include_suites): self.children.append(TestData(parent=self,source=path, include_suites=include_suites)) def has_tests(self): return any(ch.has_tests() for ch in self.children) def __iter__(self): for table in [self.setting_table, self.variable_table, self.keyword_table]: yield table class _Table(object): def __init__(self, parent): self.parent = parent self._header = None def set_header(self, header): self._header = self._prune_old_style_headers(header) def _prune_old_style_headers(self, header): if len(header) < 3: return header if self._old_header_matcher.match(header): return [header[0]] return header @property def header(self): return self._header or [self.type.title() + 's'] @property def name(self): return self.header[0] @property def source(self): return self.parent.source @property def directory(self): return self.parent.directory def report_invalid_syntax(self, message, level='ERROR'): self.parent.report_invalid_syntax(message, level) def __nonzero__(self): return bool(self._header or len(self)) def __len__(self): return sum(1 for item in self) class _WithSettings(object): def get_setter(self, setting_name): normalized = self.normalize(setting_name) if normalized in self._setters: return self._setters[normalized](self) self.report_invalid_syntax("Non-existing setting '%s'." % setting_name) def is_setting(self, setting_name): return self.normalize(setting_name) in self._setters def normalize(self, setting): result = utils.normalize(setting) return result[0:-1] if result and result[-1]==':' else result class _SettingTable(_Table, _WithSettings): type = 'setting' def __init__(self, parent): _Table.__init__(self, parent) self.doc = Documentation('Documentation', self) self.suite_setup = Fixture('Suite Setup', self) self.suite_teardown = Fixture('Suite Teardown', self) self.test_setup = Fixture('Test Setup', self) self.test_teardown = Fixture('Test Teardown', self) self.force_tags = Tags('Force Tags', self) self.default_tags = Tags('Default Tags', self) self.test_template = Template('Test Template', self) self.test_timeout = Timeout('Test Timeout', self) self.metadata = MetadataList(self) self.imports = ImportList(self) @property def _old_header_matcher(self): return OldStyleSettingAndVariableTableHeaderMatcher() def add_metadata(self, name, value='', comment=None): self.metadata.add(Metadata(self, name, value, comment)) return self.metadata[-1] def add_library(self, name, args=None, comment=None): self.imports.add(Library(self, name, args, comment=comment)) return self.imports[-1] def add_resource(self, name, invalid_args=None, comment=None): self.imports.add(Resource(self, name, invalid_args, comment=comment)) return self.imports[-1] def add_variables(self, name, args=None, comment=None): self.imports.add(Variables(self, name, args, comment=comment)) return self.imports[-1] def __len__(self): return sum(1 for setting in self if setting.is_set()) class TestCaseFileSettingTable(_SettingTable): _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'suitesetup': lambda s: s.suite_setup.populate, 'suiteprecondition': lambda s: s.suite_setup.populate, 'suiteteardown': lambda s: s.suite_teardown.populate, 'suitepostcondition': lambda s: s.suite_teardown.populate, 'testsetup': lambda s: s.test_setup.populate, 'testprecondition': lambda s: s.test_setup.populate, 'testteardown': lambda s: s.test_teardown.populate, 'testpostcondition': lambda s: s.test_teardown.populate, 'forcetags': lambda s: s.force_tags.populate, 'defaulttags': lambda s: s.default_tags.populate, 'testtemplate': lambda s: s.test_template.populate, 'testtimeout': lambda s: s.test_timeout.populate, 'library': lambda s: s.imports.populate_library, 'resource': lambda s: s.imports.populate_resource, 'variables': lambda s: s.imports.populate_variables, 'metadata': lambda s: s.metadata.populate} def __iter__(self): for setting in [self.doc, self.suite_setup, self.suite_teardown, self.test_setup, self.test_teardown, self.force_tags, self.default_tags, self.test_template, self.test_timeout] \ + self.metadata.data + self.imports.data: yield setting class ResourceFileSettingTable(_SettingTable): _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'library': lambda s: s.imports.populate_library, 'resource': lambda s: s.imports.populate_resource, 'variables': lambda s: s.imports.populate_variables} def __iter__(self): for setting in [self.doc] + self.imports.data: yield setting class InitFileSettingTable(_SettingTable): _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'suitesetup': lambda s: s.suite_setup.populate, 'suiteprecondition': lambda s: s.suite_setup.populate, 'suiteteardown': lambda s: s.suite_teardown.populate, 'suitepostcondition': lambda s: s.suite_teardown.populate, 'testsetup': lambda s: s.test_setup.populate, 'testprecondition': lambda s: s.test_setup.populate, 'testteardown': lambda s: s.test_teardown.populate, 'testpostcondition': lambda s: s.test_teardown.populate, 'testtimeout': lambda s: s.test_timeout.populate, 'forcetags': lambda s: s.force_tags.populate, 'library': lambda s: s.imports.populate_library, 'resource': lambda s: s.imports.populate_resource, 'variables': lambda s: s.imports.populate_variables, 'metadata': lambda s: s.metadata.populate} def __iter__(self): for setting in [self.doc, self.suite_setup, self.suite_teardown, self.test_setup, self.test_teardown, self.force_tags, self.test_timeout] + self.metadata.data + self.imports.data: yield setting class VariableTable(_Table): type = 'variable' def __init__(self, parent): _Table.__init__(self, parent) self.variables = [] @property def _old_header_matcher(self): return OldStyleSettingAndVariableTableHeaderMatcher() def add(self, name, value, comment=None): self.variables.append(Variable(self, name, value, comment)) def __iter__(self): return iter(self.variables) class TestCaseTable(_Table): type = 'test case' def __init__(self, parent): _Table.__init__(self, parent) self.tests = [] @property def _old_header_matcher(self): return OldStyleTestAndKeywordTableHeaderMatcher() def add(self, name): self.tests.append(TestCase(self, name)) return self.tests[-1] def __iter__(self): return iter(self.tests) def is_started(self): return bool(self._header) def __nonzero__(self): return True class KeywordTable(_Table): type = 'keyword' def __init__(self, parent): _Table.__init__(self, parent) self.keywords = [] @property def _old_header_matcher(self): return OldStyleTestAndKeywordTableHeaderMatcher() def add(self, name): self.keywords.append(UserKeyword(self, name)) return self.keywords[-1] def __iter__(self): return iter(self.keywords) class Variable(object): def __init__(self, parent, name, value, comment=None): self.parent = parent self.name = name.rstrip('= ') if name.startswith('$') and value == []: value = '' if isinstance(value, basestring): value = [value] # Must support scalar lists until RF 2.8 (issue 939) self.value = value self.comment = Comment(comment) def as_list(self): if self.has_data(): return [self.name] + self.value + self.comment.as_list() return self.comment.as_list() def is_set(self): return True def is_for_loop(self): return False def has_data(self): return bool(self.name or ''.join(self.value)) def __nonzero__(self): return self.has_data() def report_invalid_syntax(self, message, level='ERROR'): self.parent.report_invalid_syntax("Setting variable '%s' failed: %s" % (self.name, message), level) class _WithSteps(object): def add_step(self, content, comment=None): self.steps.append(Step(content, comment)) return self.steps[-1] def copy(self, name): new = copy.deepcopy(self) new.name = name self._add_to_parent(new) return new class TestCase(_WithSteps, _WithSettings): def __init__(self, parent, name): self.parent = parent self.name = name self.doc = Documentation('[Documentation]', self) self.template = Template('[Template]', self) self.tags = Tags('[Tags]', self) self.setup = Fixture('[Setup]', self) self.teardown = Fixture('[Teardown]', self) self.timeout = Timeout('[Timeout]', self) self.steps = [] _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'template': lambda s: s.template.populate, 'setup': lambda s: s.setup.populate, 'precondition': lambda s: s.setup.populate, 'teardown': lambda s: s.teardown.populate, 'postcondition': lambda s: s.teardown.populate, 'tags': lambda s: s.tags.populate, 'timeout': lambda s: s.timeout.populate} @property def source(self): return self.parent.source @property def directory(self): return self.parent.directory def add_for_loop(self, declaration, comment=None): self.steps.append(ForLoop(declaration, comment)) return self.steps[-1] def report_invalid_syntax(self, message, level='ERROR'): type_ = 'test case' if type(self) is TestCase else 'keyword' message = "Invalid syntax in %s '%s': %s" % (type_, self.name, message) self.parent.report_invalid_syntax(message, level) def _add_to_parent(self, test): self.parent.tests.append(test) @property def settings(self): return [self.doc, self.tags, self.setup, self.template, self.timeout, self.teardown] def __iter__(self): for element in [self.doc, self.tags, self.setup, self.template, self.timeout] \ + self.steps + [self.teardown]: yield element class UserKeyword(TestCase): def __init__(self, parent, name): self.parent = parent self.name = name self.doc = Documentation('[Documentation]', self) self.args = Arguments('[Arguments]', self) self.return_ = Return('[Return]', self) self.timeout = Timeout('[Timeout]', self) self.teardown = Fixture('[Teardown]', self) self.steps = [] _setters = {'documentation': lambda s: s.doc.populate, 'document': lambda s: s.doc.populate, 'arguments': lambda s: s.args.populate, 'return': lambda s: s.return_.populate, 'timeout': lambda s: s.timeout.populate, 'teardown': lambda s: s.teardown.populate} def _add_to_parent(self, test): self.parent.keywords.append(test) @property def settings(self): return [self.args, self.doc, self.timeout, self.teardown, self.return_] def __iter__(self): for element in [self.args, self.doc, self.timeout] \ + self.steps + [self.teardown, self.return_]: yield element class ForLoop(_WithSteps): def __init__(self, declaration, comment=None): self.range, index = self._get_range_and_index(declaration) self.vars = declaration[:index] self.items = declaration[index+1:] self.comment = Comment(comment) self.steps = [] def _get_range_and_index(self, declaration): for index, item in enumerate(declaration): item = item.upper().replace(' ', '') if item in ['IN', 'INRANGE']: return item == 'INRANGE', index return False, len(declaration) def is_comment(self): return False def is_for_loop(self): return True def as_list(self, indent=False, include_comment=True): IN = ['IN RANGE' if self.range else 'IN'] comments = self.comment.as_list() if include_comment else [] return [': FOR'] + self.vars + IN + self.items + comments def __iter__(self): return iter(self.steps) def is_set(self): return True class Step(object): def __init__(self, content, comment=None): self.assign = list(self._get_assigned_vars(content)) try: self.keyword = content[len(self.assign)] except IndexError: self.keyword = None self.args = content[len(self.assign)+1:] self.comment = Comment(comment) def _get_assigned_vars(self, content): for item in content: if not is_var(item.rstrip('= ')): return yield item def is_comment(self): return not (self.assign or self.keyword or self.args) def is_for_loop(self): return False def is_set(self): return True def as_list(self, indent=False, include_comment=True): kw = [self.keyword] if self.keyword is not None else [] comments = self.comment.as_list() if include_comment else [] data = self.assign + kw + self.args + comments if indent: data.insert(0, '') return data class OldStyleSettingAndVariableTableHeaderMatcher(object): def match(self, header): return all((True if e.lower() == 'value' else False) for e in header[1:]) class OldStyleTestAndKeywordTableHeaderMatcher(object): def match(self, header): if header[1].lower() != 'action': return False for h in header[2:]: if not h.lower().startswith('arg'): return False return 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 re from .tsvreader import TsvReader class TxtReader(TsvReader): _space_splitter = re.compile(' {2,}') _pipe_splitter = re.compile(' \|(?= )') @classmethod def split_row(cls, row): if '\t' in row: row = row.replace('\t', ' ') if not row.startswith('| '): return cls._space_splitter.split(row) row = row[1:-1] if row.endswith(' |') else row[1:] return [cell.strip() for cell in cls._pipe_splitter.split(row)] def _process_cell(self, cell): 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. from robot.utils import Utf8Reader NBSP = u'\xA0' class TsvReader(object): def read(self, tsvfile, populator): process = False for row in Utf8Reader(tsvfile).readlines(): row = self._process_row(row) cells = [self._process_cell(cell) for cell in self.split_row(row)] if cells and cells[0].strip().startswith('*') and \ populator.start_table([c.replace('*', '') for c in cells]): process = True elif process: populator.add(cells) populator.eof() def _process_row(self, row): if NBSP in row: row = row.replace(NBSP, ' ') return row.rstrip() @classmethod def split_row(cls, row): return row.split('\t') def _process_cell(self, cell): if len(cell) > 1 and cell[0] == cell[-1] == '"': cell = cell[1:-1].replace('""', '"') 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. from .comments import Comment class Setting(object): def __init__(self, setting_name, parent=None, comment=None): self.setting_name = setting_name self.parent = parent self._set_initial_value() self._set_comment(comment) def _set_initial_value(self): self.value = [] def _set_comment(self, comment): self.comment = Comment(comment) def reset(self): self.__init__(self.setting_name, self.parent) @property def source(self): return self.parent.source if self.parent is not None else None @property def directory(self): return self.parent.directory if self.parent is not None else None def populate(self, value, comment=None): """Mainly used at parsing time, later attributes can be set directly.""" self._populate(value) self._set_comment(comment) def _populate(self, value): self.value = value def is_set(self): return bool(self.value) def is_for_loop(self): return False def report_invalid_syntax(self, message, level='ERROR'): self.parent.report_invalid_syntax(message, level) def _string_value(self, value): return value if isinstance(value, basestring) else ' '.join(value) def _concat_string_with_value(self, string, value): if string: return string + ' ' + self._string_value(value) return self._string_value(value) def as_list(self): return self._data_as_list() + self.comment.as_list() def _data_as_list(self): ret = [self.setting_name] if self.value: ret.extend(self.value) return ret def __nonzero__(self): return self.is_set() def __iter__(self): return iter(self.value) def __unicode__(self): return unicode(self.value or '') class StringValueJoiner(object): def __init__(self, separator): self._separator = separator def join_string_with_value(self, string, value): if string: return string + self._separator + self.string_value(value) return self.string_value(value) def string_value(self, value): if isinstance(value, basestring): return value return self._separator.join(value) class Documentation(Setting): def _set_initial_value(self): self.value = '' def _populate(self, value): self.value = self._concat_string_with_value(self.value, value) def _string_value(self, value): return value if isinstance(value, basestring) else ''.join(value) def _data_as_list(self): return [self.setting_name, self.value] class Template(Setting): def _set_initial_value(self): self.value = None def _populate(self, value): self.value = self._concat_string_with_value(self.value, value) def is_set(self): return self.value is not None def is_active(self): return self.value and self.value.upper() != 'NONE' def _data_as_list(self): ret = [self.setting_name] if self.value: ret.append(self.value) return ret class Fixture(Setting): # `keyword`, `is_comment` and `assign` make the API compatible with Step. @property def keyword(self): return self.name or '' def is_comment(self): return False def _set_initial_value(self): self.name = None self.args = [] self.assign = () def _populate(self, value): if not self.name: self.name = value[0] if value else '' value = value[1:] self.args.extend(value) def is_set(self): return self.name is not None def is_active(self): return self.name and self.name.upper() != 'NONE' def _data_as_list(self): ret = [self.setting_name] if self.name or self.args: ret.append(self.name or '') if self.args: ret.extend(self.args) return ret class Timeout(Setting): def _set_initial_value(self): self.value = None self.message = '' def _populate(self, value): if not self.value: self.value = value[0] if value else '' value = value[1:] self.message = self._concat_string_with_value(self.message, value) def is_set(self): return self.value is not None def _data_as_list(self): ret = [self.setting_name] if self.value or self.message: ret.append(self.value or '') if self.message: ret.append(self.message) return ret class Tags(Setting): def _set_initial_value(self): self.value = None def _populate(self, value): self.value = (self.value or []) + value def is_set(self): return self.value is not None def __add__(self, other): if not isinstance(other, Tags): raise TypeError('Tags can only be added with tags') tags = Tags('Tags') tags.value = (self.value or []) + (other.value or []) return tags class Arguments(Setting): pass class Return(Setting): pass class Metadata(Setting): setting_name = 'Metadata' def __init__(self, parent, name, value, comment=None, joined=False): self.parent = parent self.name = name joiner = StringValueJoiner('' if joined else ' ') self.value = joiner.join_string_with_value('', value) self._set_comment(comment) def reset(self): pass def is_set(self): return True def _data_as_list(self): return [self.setting_name, self.name, self.value] class _Import(Setting): def __init__(self, parent, name, args=None, alias=None, comment=None): self.parent = parent self.name = name self.args = args or [] self.alias = alias self._set_comment(comment) def reset(self): pass @property def type(self): return type(self).__name__ def is_set(self): return True def _data_as_list(self): return [self.type, self.name] + self.args class Library(_Import): def __init__(self, parent, name, args=None, alias=None, comment=None): if args and not alias: args, alias = self._split_alias(args) _Import.__init__(self, parent, name, args, alias, comment) def _split_alias(self, args): if len(args) >= 2 and isinstance(args[-2], basestring) \ and args[-2].upper() == 'WITH NAME': return args[:-2], args[-1] return args, None def _data_as_list(self): alias = ['WITH NAME', self.alias] if self.alias else [] return ['Library', self.name] + self.args + alias class Resource(_Import): def __init__(self, parent, name, invalid_args=None, comment=None): if invalid_args: name += ' ' + ' '.join(invalid_args) _Import.__init__(self, parent, name, comment=comment) class Variables(_Import): def __init__(self, parent, name, args=None, comment=None): _Import.__init__(self, parent, name, args, comment=comment) class _DataList(object): def __init__(self, parent): self._parent = parent self.data = [] def add(self, meta): self._add(meta) def _add(self, meta): self.data.append(meta) def _parse_name_and_value(self, value): name = value[0] if value else '' return name, value[1:] def __getitem__(self, index): return self.data[index] def __setitem__(self, index, item): self.data[index] = item def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) class ImportList(_DataList): def populate_library(self, data, comment): self._populate(Library, data, comment) def populate_resource(self, data, comment): self._populate(Resource, data, comment) def populate_variables(self, data, comment): self._populate(Variables, data, comment) def _populate(self, item_class, data, comment): name, value = self._parse_name_and_value(data) self._add(item_class(self._parent, name, value, comment=comment)) class MetadataList(_DataList): def populate(self, name, value, comment): self._add(Metadata(self._parent, name, value, comment, joined=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. from robot.errors import DataError try: from docutils.core import publish_doctree, publish_from_doctree from docutils.parsers.rst.directives import register_directive from docutils.parsers.rst.directives.body import CodeBlock except ImportError: raise DataError("Using reStructuredText test data requires having " "'docutils' module version 0.9 or newer installed.") class CaptureRobotData(CodeBlock): def run(self): if 'robotframework' in self.arguments: store = RobotDataStorage(self.state_machine.document) store.add_data(self.content) return [] register_directive('code', CaptureRobotData) register_directive('code-block', CaptureRobotData) register_directive('sourcecode', CaptureRobotData) class RobotDataStorage(object): def __init__(self, doctree): if not hasattr(doctree, '_robot_data'): doctree._robot_data = [] self._robot_data = doctree._robot_data def add_data(self, rows): self._robot_data.extend(rows) def get_data(self): return '\n'.join(self._robot_data) def has_data(self): return bool(self._robot_data)
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 CommentCache(object): def __init__(self): self._comments = [] def add(self, comment): self._comments.append(comment) def consume_with(self, function): map(function, self._comments) self.__init__() class Comments(object): def __init__(self): self._comments = [] def add(self, row): if row.comments: self._comments.extend(c.strip() for c in row.comments if c.strip()) @property def value(self): return self._comments class Comment(object): def __init__(self, comment_data): if isinstance(comment_data, basestring): comment_data = [comment_data] if comment_data else [] self._comment = comment_data or [] def __len__(self): return len(self._comment) def as_list(self): if self._not_commented(): self._comment[0] = '# ' + self._comment[0] return self._comment def _not_commented(self): return self._comment and self._comment[0] and self._comment[0][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 re class DataRow(object): _row_continuation_marker = '...' _whitespace_regexp = re.compile('\s+') _ye_olde_metadata_prefix = 'meta:' def __init__(self, cells): self.cells, self.comments = self._parse(cells) def _parse(self, row): data = [] comments = [] for cell in row: cell = self._collapse_whitespace(cell) if cell.startswith('#') or comments: comments.append(cell) else: data.append(cell) return self._purge_empty_cells(data), self._purge_empty_cells(comments) def _collapse_whitespace(self, cell): return self._whitespace_regexp.sub(' ', cell).strip() def _purge_empty_cells(self, row): while row and not row[-1]: row.pop() # Cells with only a single backslash are considered empty return [cell if cell != '\\' else '' for cell in row] @property def head(self): return self.cells[0] if self.cells else '' @property def tail(self): return self.cells[1:] @property def all(self): return self.cells @property def data(self): if self.is_continuing(): index = self.cells.index(self._row_continuation_marker) + 1 return self.cells[index:] return self.cells def dedent(self): datarow = DataRow([]) datarow.cells = self.tail datarow.comments = self.comments return datarow def handle_old_style_metadata(self): if self._is_metadata_with_olde_prefix(self.head): self.cells = self._convert_to_new_style_metadata() def _is_metadata_with_olde_prefix(self, value): return value.lower().startswith(self._ye_olde_metadata_prefix) def _convert_to_new_style_metadata(self): return ['Metadata'] + [self.head.split(':', 1)[1].strip()] + self.tail def starts_for_loop(self): if self.head and self.head.startswith(':'): return self.head.replace(':', '').replace(' ', '').upper() == 'FOR' return False def starts_test_or_user_keyword_setting(self): head = self.head return head and head[0] == '[' and head[-1] == ']' def test_or_user_keyword_setting_name(self): return self.head[1:-1].strip() def is_indented(self): return self.head == '' def is_continuing(self): for cell in self.cells: if cell == self._row_continuation_marker: return True if cell: return False def is_commented(self): return bool(not self.cells and self.comments) def __nonzero__(self): return bool(self.cells or self.comments)
Python
# Copyright 2008-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 test data parsing. Classes :class:`~.model.TestCaseFile`, :class:`~.model.TestDataDirectory` and :class:`~.model.ResourceFile` represented parsed test data. Objects of these classes can be modified and saved back to disk. In addition, a convenience factory function :func:`~.model.TestData` can be used to parse a test case file or directory to a corresponding object. Aforementioned classes and functions are part of the public API. It is recommended that they are imported through the :mod:`robot.api` package like in the example below. This package is likely to change radically in Robot Framework 2.9. The main motivation for the planned changes is making the data easier to use for external tools that use these modules. Example ------- :: import sys from robot.api import TestData def print_suite(suite): print 'Suite:', suite.name for test in suite.testcase_table: print '-', test.name for child in suite.children: print_suite(child) suite = TestData(source=sys.argv[1]) print_suite(suite) """ from .model import TestData, TestCaseFile, TestDataDirectory, ResourceFile from . import populators VALID_EXTENSIONS = tuple(populators.READERS) def disable_curdir_processing(method): """Decorator to disable processing `${CURDIR}` variable.""" def decorated(*args, **kwargs): original = populators.PROCESS_CURDIR populators.PROCESS_CURDIR = False try: return method(*args, **kwargs) finally: populators.PROCESS_CURDIR = original return decorated
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 cStringIO import StringIO from .htmlreader import HtmlReader from .txtreader import TxtReader def RestReader(): from .restsupport import (publish_doctree, publish_from_doctree, RobotDataStorage) class RestReader(object): def read(self, rstfile, rawdata): doctree = publish_doctree( rstfile.read(), source_path=rstfile.name, settings_overrides={'input_encoding': 'UTF-8'}) store = RobotDataStorage(doctree) if store.has_data(): return self._read_text(store.get_data(), rawdata) return self._read_html(doctree, rawdata) def _read_text(self, data, rawdata): txtfile = StringIO(data.encode('UTF-8')) return TxtReader().read(txtfile, rawdata) def _read_html(self, doctree, rawdata): htmlfile = StringIO() htmlfile.write(publish_from_doctree( doctree, writer_name='html', settings_overrides={'output_encoding': 'UTF-8'})) htmlfile.seek(0) return HtmlReader().read(htmlfile, rawdata) return RestReader()
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 HTMLParser import HTMLParser from htmlentitydefs import entitydefs NON_BREAKING_SPACE = u'\xA0' class HtmlReader(HTMLParser): IGNORE = 0 INITIAL = 1 PROCESS = 2 def __init__(self): HTMLParser.__init__(self) self._encoding = 'ISO-8859-1' self._handlers = {'table_start' : self.table_start, 'table_end' : self.table_end, 'tr_start' : self.tr_start, 'tr_end' : self.tr_end, 'td_start' : self.td_start, 'td_end' : self.td_end, 'th_start' : self.td_start, 'th_end' : self.td_end, 'br_start' : self.br_start, 'meta_start' : self.meta_start} def read(self, htmlfile, populator): self.populator = populator self.state = self.IGNORE self.current_row = None self.current_cell = None for line in htmlfile.readlines(): self.feed(self._decode(line)) # Calling close is required by the HTMLParser but may cause problems # if the same instance of our HtmlParser is reused. Currently it's # used only once so there's no problem. self.close() self.populator.eof() def _decode(self, line): return line.decode(self._encoding) def handle_starttag(self, tag, attrs): handler = self._handlers.get(tag+'_start') if handler is not None: handler(attrs) def handle_endtag(self, tag): handler = self._handlers.get(tag+'_end') if handler is not None: handler() def handle_data(self, data): if self.state == self.IGNORE or self.current_cell is None: return if NON_BREAKING_SPACE in data: data = data.replace(NON_BREAKING_SPACE, ' ') self.current_cell.append(data) def handle_entityref(self, name): value = self._handle_entityref(name) self.handle_data(value) def _handle_entityref(self, name): if name == 'apos': # missing from entitydefs return "'" try: value = entitydefs[name] except KeyError: return '&'+name+';' if value.startswith('&#'): return unichr(int(value[2:-1])) return value.decode('ISO-8859-1') def handle_charref(self, number): value = self._handle_charref(number) self.handle_data(value) def _handle_charref(self, number): if number.startswith(('x', 'X')): base = 16 number = number[1:] else: base = 10 try: return unichr(int(number, base)) except ValueError: return '&#'+number+';' def unknown_decl(self, data): # Ignore everything even if it's invalid. This kind of stuff comes # at least from MS Excel pass def table_start(self, attrs=None): self.state = self.INITIAL self.current_row = None self.current_cell = None def table_end(self): if self.current_row is not None: self.tr_end() self.state = self.IGNORE def tr_start(self, attrs=None): if self.current_row is not None: self.tr_end() self.current_row = [] def tr_end(self): if self.current_row is None: return if self.current_cell is not None: self.td_end() if self.state == self.INITIAL: accepted = self.populator.start_table(self.current_row) self.state = self.PROCESS if accepted else self.IGNORE elif self.state == self.PROCESS: self.populator.add(self.current_row) self.current_row = None def td_start(self, attrs=None): if self.current_cell is not None: self.td_end() if self.current_row is None: self.tr_start() self.current_cell = [] def td_end(self): if self.current_cell is not None and self.state != self.IGNORE: cell = ''.join(self.current_cell) self.current_row.append(cell) self.current_cell = None def br_start(self, attrs=None): self.handle_data('\n') def meta_start(self, attrs): encoding = self._get_encoding_from_meta(attrs) if encoding: self._encoding = encoding def _get_encoding_from_meta(self, attrs): valid_http_equiv = False encoding = None for name, value in attrs: name = name.lower() if name == 'charset': # html5 return value if name == 'http-equiv' and value.lower() == 'content-type': valid_http_equiv = True if name == 'content': encoding = self._get_encoding_from_content_attr(value) return encoding if valid_http_equiv else None def _get_encoding_from_content_attr(self, value): for token in value.split(';'): token = token.strip() if token.lower().startswith('charset='): return token[8:] def handle_pi(self, data): encoding = self._get_encoding_from_pi(data) if encoding: self._encoding = encoding def _get_encoding_from_pi(self, data): data = data.strip() if not data.lower().startswith('xml '): return None if data.endswith('?'): data = data[:-1] for token in data.split(): if token.lower().startswith('encoding='): encoding = token[9:] if encoding.startswith("'") or encoding.startswith('"'): encoding = encoding[1:-1] return encoding return None
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 import utils from robot import model class SuiteConfigurer(model.SuiteConfigurer): """Result suite configured. Calls suite's :meth:`~robot.result.testsuite.TestSuite.remove_keywords`, :meth:`~robot.result.testsuite.TestSuite.filter_messages` and :meth:`~robot.result.testsuite.TestSuite.set_criticality` methods and sets it's start and end time based on the given named parameters. ``base_config`` is forwarded to :class:`robot.model.SuiteConfigurer <robot.model.configurer.SuiteConfigurer>` that will do further configuration based on them. """ def __init__(self, remove_keywords=None, log_level=None, start_time=None, end_time=None, critical_tags=None, non_critical_tags=None, **base_config): model.SuiteConfigurer.__init__(self, **base_config) self.remove_keywords = self._get_remove_keywords(remove_keywords) self.log_level = log_level self.start_time = self._get_time(start_time) self.end_time = self._get_time(end_time) self.critical_tags = critical_tags self.non_critical_tags = non_critical_tags def _get_remove_keywords(self, value): if value is None: return [] if isinstance(value, basestring): return [value] return value def _get_time(self, timestamp): if not timestamp: return None try: secs = utils.timestamp_to_secs(timestamp, seps=' :.-_') except ValueError: return None return utils.secs_to_timestamp(secs, millis=True) def visit_suite(self, suite): model.SuiteConfigurer.visit_suite(self, suite) self._remove_keywords(suite) self._set_times(suite) suite.filter_messages(self.log_level) suite.set_criticality(self.critical_tags, self.non_critical_tags) def _remove_keywords(self, suite): for how in self.remove_keywords: suite.remove_keywords(how) def _set_times(self, suite): if self.start_time: suite.starttime = self.start_time if self.end_time: suite.endtime = self.end_time
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 import model class Message(model.Message): __slots__ = []
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.model import ItemList from robot.utils import setter from .message import Message class ExecutionErrors(object): """Represents errors occurred during the execution of tests. An error might be, for example, that importing a library has failed. """ message_class = Message def __init__(self, messages=None): #: A :class:`list-like object <robot.model.itemlist.ItemList>` of #: :class:`~robot.model.message.Message` instances. self.messages = messages @setter def messages(self, msgs): return ItemList(self.message_class, items=msgs) def add(self, other): self.messages.extend(other.messages) def visit(self, visitor): visitor.visit_errors(self) def __iter__(self): return iter(self.messages) def __len__(self): return len(self.messages) def __getitem__(self, index): return self.messages[index]
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 XmlElementHandler(object): def __init__(self, execution_result, root_handler=None): self._stack = [(root_handler or RootHandler(), execution_result)] def start(self, elem): handler, result = self._stack[-1] handler = handler.get_child_handler(elem) result = handler.start(elem, result) self._stack.append((handler, result)) def end(self, elem): handler, result = self._stack.pop() handler.end(elem, result) class _Handler(object): def __init__(self): self._child_handlers = dict((c.tag, c) for c in self._children()) def _children(self): return [] def get_child_handler(self, elem): try: return self._child_handlers[elem.tag] except KeyError: raise DataError("Incompatible XML element '%s'." % elem.tag) def start(self, elem, result): return result def end(self, elem, result): pass def _timestamp(self, elem, attr_name): timestamp = elem.get(attr_name) return timestamp if timestamp != 'N/A' else None class RootHandler(_Handler): def _children(self): return [RobotHandler()] class RobotHandler(_Handler): tag = 'robot' def start(self, elem, result): generator = elem.get('generator', 'unknown').split()[0].upper() result.generated_by_robot = generator == 'ROBOT' return result def _children(self): return [RootSuiteHandler(), StatisticsHandler(), ErrorsHandler()] class SuiteHandler(_Handler): tag = 'suite' def start(self, elem, result): return result.suites.create(name=elem.get('name'), source=elem.get('source', '')) def _children(self): return [DocHandler(), MetadataHandler(), SuiteStatusHandler(), KeywordHandler(), TestCaseHandler(), self] class RootSuiteHandler(SuiteHandler): def start(self, elem, result): result.suite.name = elem.get('name') result.suite.source = elem.get('source') return result.suite def _children(self): return SuiteHandler._children(self)[:-1] + [SuiteHandler()] class TestCaseHandler(_Handler): tag = 'test' def start(self, elem, result): return result.tests.create(name=elem.get('name'), timeout=elem.get('timeout')) def _children(self): return [DocHandler(), TagsHandler(), TestStatusHandler(), KeywordHandler()] class KeywordHandler(_Handler): tag = 'kw' def start(self, elem, result): return result.keywords.create(name=elem.get('name'), timeout=elem.get('timeout'), type=elem.get('type')) def _children(self): return [DocHandler(), ArgumentsHandler(), KeywordStatusHandler(), MessageHandler(), self] class MessageHandler(_Handler): tag = 'msg' def end(self, elem, result): result.messages.create(elem.text or '', elem.get('level'), elem.get('html', 'no') == 'yes', self._timestamp(elem, 'timestamp')) class _StatusHandler(_Handler): tag = 'status' def _set_status(self, elem, result): result.status = elem.get('status', 'FAIL') def _set_message(self, elem, result): result.message = elem.text or '' def _set_times(self, elem, result): result.starttime = self._timestamp(elem, 'starttime') result.endtime = self._timestamp(elem, 'endtime') class KeywordStatusHandler(_StatusHandler): def end(self, elem, result): self._set_status(elem, result) self._set_times(elem, result) if result.type == result.TEARDOWN_TYPE: self._set_message(elem, result) class SuiteStatusHandler(_StatusHandler): def end(self, elem, result): self._set_message(elem, result) self._set_times(elem, result) class TestStatusHandler(_StatusHandler): def end(self, elem, result): self._set_status(elem, result) self._set_message(elem, result) self._set_times(elem, result) class DocHandler(_Handler): tag = 'doc' def end(self, elem, result): result.doc = elem.text or '' class MetadataHandler(_Handler): tag = 'metadata' def _children(self): return [MetadataItemHandler()] class MetadataItemHandler(_Handler): tag = 'item' def end(self, elem, result): result.metadata[elem.get('name')] = elem.text or '' class TagsHandler(_Handler): tag = 'tags' def _children(self): return [TagHandler()] class TagHandler(_Handler): tag = 'tag' def end(self, elem, result): result.tags.add(elem.text or '') class ArgumentsHandler(_Handler): tag = 'arguments' def _children(self): return [ArgumentHandler()] class ArgumentHandler(_Handler): tag = 'arg' def end(self, elem, result): result.args += (elem.text or '',) class ErrorsHandler(_Handler): tag = 'errors' def start(self, elem, result): return result.errors def _children(self): return [MessageHandler()] class StatisticsHandler(_Handler): tag = 'statistics' def get_child_handler(self, elem): return 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. from robot import model, utils from .message import Message class Keyword(model.Keyword): """Results of a single keyword.""" __slots__ = ['status', 'starttime', 'endtime', 'message'] message_class = Message def __init__(self, name='', doc='', args=(), type='kw', timeout='', status='FAIL', starttime=None, endtime=None): model.Keyword.__init__(self, name, doc, args, type, timeout) #: String 'PASS' of 'FAIL'. self.status = status #: Keyword execution start time in format ``%Y%m%d %H:%M:%S.%f``. self.starttime = starttime #: Keyword execution end time in format ``%Y%m%d %H:%M:%S.%f``. self.endtime = endtime #: Keyword status message. Used only with suite teardowns. self.message = '' @property def elapsedtime(self): """Elapsed execution time of the keyword in milliseconds.""" return utils.get_elapsed_time(self.starttime, self.endtime) @property def passed(self): """``True`` if the keyword did pass, ``False`` otherwise.""" return self.status == '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 robot import model, utils from keyword import Keyword class TestCase(model.TestCase): """Results of a single test case.""" __slots__ = ['status', 'message', 'starttime', 'endtime'] keyword_class = Keyword def __init__(self, name='', doc='', tags=None, timeout=None, status='FAIL', message='', starttime=None, endtime=None): model.TestCase.__init__(self, name, doc, tags, timeout) #: String 'PASS' of 'FAIL'. self.status = status #: Possible failure message. self.message = message #: Test case execution start time in format ``%Y%m%d %H:%M:%S.%f``. self.starttime = starttime #: Test case execution end time in format ``%Y%m%d %H:%M:%S.%f``. self.endtime = endtime @property def elapsedtime(self): """Elapsed execution time of the test case in milliseconds.""" return utils.get_elapsed_time(self.starttime, self.endtime) @property def passed(self): """``True`` if the test case did pass, ``False`` otherwise.""" return self.status == 'PASS' @property def critical(self): """``True`` if the test case is marked as critical, ``False`` otherwise. """ if not self.parent: return True return self.parent.criticality.test_is_critical(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. from __future__ import with_statement from robot.errors import DataError from robot.utils import ET, ETSource, get_error_message from .executionresult import Result, CombinedResult from .flattenkeywordmatcher import FlattenKeywordMatcher from .rerunmerger import ReRunMerger from .xmlelementhandlers import XmlElementHandler def ExecutionResult(*sources, **options): """Factory method to constructs :class:`~.executionresult.Result` objects. :param sources: Path(s) to output XML file(s). :param options: Configuration options. `rerun_merge` with True value causes multiple results to be combined so that tests in the latter results replace the ones in the original. Other options are passed further to :py:class:`~ExecutionResultBuilder`. :returns: :class:`~.executionresult.Result` instance. See :mod:`~robot.result` package for a usage example. """ if not sources: raise DataError('One or more data source needed.') if options.pop('rerun_merge', False): return _rerun_merge_results(sources[0], sources[1:], options) if len(sources) > 1: return _combine_results(sources, options) return _single_result(sources[0], options) def _rerun_merge_results(original, merged, options): result = ExecutionResult(original, **options) merger = ReRunMerger(result) for path in merged: merged = ExecutionResult(path, **options) merger.merge(merged) return result def _combine_results(sources, options): return CombinedResult(ExecutionResult(src, **options) for src in sources) def _single_result(source, options): ets = ETSource(source) try: return ExecutionResultBuilder(ets, **options).build(Result(source)) except IOError, err: error = err.strerror except: error = get_error_message() raise DataError("Reading XML source '%s' failed: %s" % (unicode(ets), error)) class ExecutionResultBuilder(object): def __init__(self, source, include_keywords=True, flattened_keywords=None): """Builds :class:`~.executionresult.Result` objects from existing output XML files on the file system. :param source: Path to output XML file. :param include_keywords: Include keyword information to the :class:`~.executionresult.Result` objects """ self._source = source \ if isinstance(source, ETSource) else ETSource(source) self._include_keywords = include_keywords self._flattened_keywords = flattened_keywords def build(self, result): # Parsing is performance optimized. Do not change without profiling! handler = XmlElementHandler(result) with self._source as source: self._parse(source, handler.start, handler.end) result.handle_suite_teardown_failures() return result def _parse(self, source, start, end): context = ET.iterparse(source, events=('start', 'end')) if not self._include_keywords: context = self._omit_keywords(context) elif self._flattened_keywords: context = self._flatten_keywords(context, self._flattened_keywords) for event, elem in context: if event == 'start': start(elem) else: end(elem) elem.clear() def _omit_keywords(self, context): started_kws = 0 for event, elem in context: start = event == 'start' kw = elem.tag == 'kw' if kw and start: started_kws += 1 if not started_kws: yield event, elem elif not start: elem.clear() if kw and not start: started_kws -= 1 def _flatten_keywords(self, context, flattened): match = FlattenKeywordMatcher(flattened).match started = -1 for event, elem in context: tag = elem.tag if event == 'start' and tag == 'kw': if started >= 0: started += 1 elif match(elem.attrib['name']): started = 0 if started == 0 and event == 'end' and tag == 'doc': elem.text = ('%s\n\n_*Keyword content flattened.*_' % (elem.text or '')).strip() if started <= 0 or tag == 'msg': yield event, elem else: elem.clear() if started >= 0 and event == 'end' and tag == 'kw': started -= 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 itertools import chain from robot.model import TotalStatisticsBuilder, Criticality from robot import model, utils from .configurer import SuiteConfigurer from .messagefilter import MessageFilter from .keywordremover import KeywordRemover from .keyword import Keyword from .suiteteardownfailed import (SuiteTeardownFailureHandler, SuiteTeardownFailed) from .testcase import TestCase class TestSuite(model.TestSuite): """Result of a single test suite.""" __slots__ = ['message', 'starttime', 'endtime', '_criticality'] test_class = TestCase keyword_class = Keyword def __init__(self, name='', doc='', metadata=None, source=None, message='', starttime=None, endtime=None): model.TestSuite.__init__(self, name, doc, metadata, source) #: Suite setup/teardown error message. self.message = message #: Suite execution start time in format ``%Y%m%d %H:%M:%S.%f``. self.starttime = starttime #: Suite execution end time in format ``%Y%m%d %H:%M:%S.%f``. self.endtime = endtime self._criticality = None @property def passed(self): """``True`` if all critical tests succeeded, ``False`` otherwise.""" return not self.statistics.critical.failed @property def status(self): """``'PASS'`` if all critical tests succeeded, ``'FAIL'`` otherwise.""" return 'PASS' if self.passed else 'FAIL' @property def statistics(self): """Suite statistics as a :class:`~robot.model.totalstatistics.TotalStatistics` object. Recreated every time this property is accessed, so saving the results to a variable and inspecting it is often a good idea:: stats = suite.statistics print stats.critical.failed print stats.all.total print stats.message """ return TotalStatisticsBuilder(self).stats @property def full_message(self): """Combination of :attr:`message` and :attr:`stat_message`.""" if not self.message: return self.stat_message return '%s\n\n%s' % (self.message, self.stat_message) @property def stat_message(self): """String representation of the suite's :attr:`statistics`.""" return self.statistics.message @property def elapsedtime(self): """Total execution time of the suite in milliseconds.""" if self.starttime and self.endtime: return utils.get_elapsed_time(self.starttime, self.endtime) return sum(child.elapsedtime for child in chain(self.suites, self.tests, self.keywords)) @property def criticality(self): """Used by tests to determine are they considered critical or not. Set using :meth:`set_criticality`. """ if self.parent: return self.parent.criticality if self._criticality is None: self.set_criticality() return self._criticality def set_criticality(self, critical_tags=None, non_critical_tags=None): """Sets which tags are considered critical and which non-critical. Tags can be given as lists of strings or, when giving only one, as single strings. This information is used by tests to determine are they considered critical or not. Criticality can be set only to the top level test suite. """ if self.parent: raise TypeError('Criticality can only be set to top level suite') self._criticality = Criticality(critical_tags, non_critical_tags) def remove_keywords(self, how): """Remove keywords based on the given condition. :param how: Is either ``ALL``, ``PASSED``, ``FOR``, ``WUKS``, or ``NAME:<pattern>``. These values have exact same semantics as values accepted by ``--removekeywords`` command line option. """ self.visit(KeywordRemover(how)) def filter_messages(self, log_level='TRACE'): """Remove log messages below the specified ``log_level``.""" self.visit(MessageFilter(log_level)) def configure(self, **options): """A shortcut to configure a suite using one method call. :param options: Passed to :class:`~robot.result.configurer.SuiteConfigurer` that will then call :meth:`filter`, :meth:`remove_keywords`, etc. based on them. Example:: suite.configure(remove_keywords='PASSED', critical_tags='smoke', doc='Smoke test results.') """ self.visit(SuiteConfigurer(**options)) def handle_suite_teardown_failures(self): """Internal usage only.""" self.visit(SuiteTeardownFailureHandler()) def suite_teardown_failed(self, message): """Internal usage only.""" self.visit(SuiteTeardownFailed(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. from robot.model import SuiteVisitor class ReRunMerger(SuiteVisitor): def __init__(self, result): self.root = result.suite self.current = None def merge(self, merged): merged.suite.visit(self) def start_suite(self, suite): try: if not self.current: self.current = self._find_root(suite) else: self.current = self._find(self.current.suites, suite.name) except ValueError: self._report_ignored(suite) return False def _find_root(self, suite): if self.root.name != suite.name: raise ValueError return self.root def _find(self, items, name): for item in items: if item.name == name: return item raise ValueError def _report_ignored(self, item, test=False): from robot.output import LOGGER type = 'suite' if not test else 'test' LOGGER.error("Merged %s '%s' is ignored because it is not found from " "original result." % (type, item.longname)) def end_suite(self, suite): self.current = self.current.parent def visit_test(self, test): try: old = self._find(self.current.tests, test.name) except ValueError: self._report_ignored(test, test=True) else: test.message = self._create_merge_message(test, old) index = self.current.tests.index(old) self.current.tests[index] = test def _create_merge_message(self, new, old): return '\n'.join(['Test has been re-run and results replaced.', '- - -', 'New status: %s' % new.status, 'New message: %s' % new.message, '- - -', 'Old status: %s' % old.status, 'Old message: %s' % old.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. from robot.errors import DataError from robot.model import SuiteVisitor from robot.utils import Matcher, plural_or_not def KeywordRemover(how): upper = how.upper() if upper.startswith('NAME:'): return ByNameKeywordRemover(pattern=how[5:]) try: return {'ALL': AllKeywordsRemover, 'PASSED': PassedKeywordRemover, 'FOR': ForLoopItemsRemover, 'WUKS': WaitUntilKeywordSucceedsRemover}[upper]() except KeyError: raise DataError("Expected 'ALL', 'PASSED', 'NAME:<pattern>', 'FOR', " "or 'WUKS' but got '%s'." % how) class _KeywordRemover(SuiteVisitor): _message = 'Keyword data removed using --RemoveKeywords option.' def __init__(self): self._removal_message = RemovalMessage(self._message) def _clear_content(self, kw): kw.keywords = [] kw.messages = [] self._removal_message.set(kw) def _failed_or_contains_warning(self, item): return not item.passed or self._contains_warning(item) def _contains_warning(self, item): contains_warning = ContainsWarning() item.visit(contains_warning) return contains_warning.result class AllKeywordsRemover(_KeywordRemover): def visit_keyword(self, keyword): self._clear_content(keyword) class PassedKeywordRemover(_KeywordRemover): def start_suite(self, suite): if not suite.statistics.all.failed: for keyword in suite.keywords: if not self._contains_warning(keyword): self._clear_content(keyword) def visit_test(self, test): if not self._failed_or_contains_warning(test): for keyword in test.keywords: self._clear_content(keyword) def visit_keyword(self, keyword): pass class ByNameKeywordRemover(_KeywordRemover): def __init__(self, pattern): _KeywordRemover.__init__(self) self._matcher = Matcher(pattern, ignore='_') def start_keyword(self, kw): if self._matcher.match(kw.name) and not self._contains_warning(kw): self._clear_content(kw) class ForLoopItemsRemover(_KeywordRemover): _message = '%d passing step%s removed using --RemoveKeywords option.' def start_keyword(self, kw): if kw.type == kw.FOR_LOOP_TYPE: before = len(kw.keywords) kw.keywords = self._remove_keywords(kw.keywords) self._removal_message.set_if_removed(kw, before) def _remove_keywords(self, keywords): return [kw for kw in keywords if self._failed_or_contains_warning(kw) or kw is keywords[-1]] class WaitUntilKeywordSucceedsRemover(_KeywordRemover): _message = '%d failing step%s removed using --RemoveKeywords option.' def start_keyword(self, kw): if kw.name == 'BuiltIn.Wait Until Keyword Succeeds' and kw.keywords: before = len(kw.keywords) kw.keywords = self._remove_keywords(list(kw.keywords)) self._removal_message.set_if_removed(kw, before) def _remove_keywords(self, keywords): include_from_end = 2 if keywords[-1].passed else 1 return self._kws_with_warnings(keywords[:-include_from_end]) \ + keywords[-include_from_end:] def _kws_with_warnings(self, keywords): return [kw for kw in keywords if self._contains_warning(kw)] class ContainsWarning(SuiteVisitor): def __init__(self): self.result = False def start_suite(self, suite): return not self.result def start_test(self, test): return not self.result def start_keyword(self, keyword): return not self.result def visit_message(self, msg): if msg.level == 'WARN': self.result = True class RemovalMessage(object): def __init__(self, message): self._message = message def set_if_removed(self, kw, len_before): removed = len_before - len(kw.keywords) if removed: self.set(kw, self._message % (removed, plural_or_not(removed))) def set(self, kw, message=None): kw.doc = ('%s\n\n_%s_' % (kw.doc, message or self._message)).strip()
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.model import Statistics from .executionerrors import ExecutionErrors from .testsuite import TestSuite class Result(object): """Test execution results. Can be created based on XML output files using the :func:`~.resultbuilder.ExecutionResult` factory method. Also returned by executed :class:`~robot.running.model.TestSuite`. """ def __init__(self, source=None, root_suite=None, errors=None): #: Path to the XML file where results are read from. self.source = source #: Hierarchical execution results as a #: :class:`~.testsuite.TestSuite` object. self.suite = root_suite or TestSuite() #: Execution errors as a #: :class:`~.executionerrors.ExecutionErrors` object. self.errors = errors or ExecutionErrors() self.generated_by_robot = True self._status_rc = True self._stat_config = {} @property def statistics(self): """Test execution statistics. Statistics are an instance of :class:`~robot.model.statistics.Statistics` that is created based on the contained ``suite`` and possible :func:`configuration <configure>`. Statistics are created every time this property is accessed. Saving them to a variable is thus often a good idea to avoid re-creating them unnecessarily:: from robot.api import ExecutionResult result = ExecutionResult('output.xml') result.configure(stat_config={'suite_stat_level': 2, 'tag_stat_combine': 'tagANDanother'}) stats = result.statistics print stats.total.critical.failed print stats.total.critical.passed print stats.tags.combined[0].total """ return Statistics(self.suite, **self._stat_config) @property def return_code(self): """Return code (integer) of test execution. By default returns the number of failed critical tests (max 250), but can be :func:`configured <configure>` to always return 0. """ if self._status_rc: return min(self.suite.statistics.critical.failed, 250) return 0 def configure(self, status_rc=True, suite_config=None, stat_config=None): """Configures the result object and objects it contains. :param status_rc: If set to ``False``, :attr:`return_code` always returns 0. :param suite_config: A dictionary of configuration options passed to :meth:`~.testsuite.TestSuite.configure` method of the contained ``suite``. :param stat_config: A dictionary of configuration options used when creating :attr:`statistics`. """ if suite_config: self.suite.configure(**suite_config) self._status_rc = status_rc self._stat_config = stat_config or {} def save(self, path=None): """Save results as a new output XML file. :param path: Path to save results to. If omitted, overwrites the original file. """ from robot.reporting.outputwriter import OutputWriter self.visit(OutputWriter(path or self.source)) def visit(self, visitor): """An entry point to visit the whole result object. :param visitor: An instance of :class:`~.visitor.ResultVisitor`. Visitors can gather information, modify results, etc. See :mod:`~robot.result` package for a simple usage example. Notice that it is also possible to call :meth:`result.suite.visit <robot.result.testsuite.TestSuite.visit>` if there is no need to visit the contained ``statistics`` or ``errors``. """ visitor.visit_result(self) def handle_suite_teardown_failures(self): """Internal usage only.""" if self.generated_by_robot: self.suite.handle_suite_teardown_failures() class CombinedResult(Result): """Combined results of multiple test executions.""" def __init__(self, results=None): Result.__init__(self) for result in results or (): self.add_result(result) def add_result(self, other): self.suite.suites.append(other.suite) self.errors.add(other.errors)
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.output.loggerhelper import IsLogged from robot.model import SuiteVisitor class MessageFilter(SuiteVisitor): def __init__(self, loglevel): self._is_logged = IsLogged(loglevel or 'TRACE') def start_keyword(self, keyword): keyword.messages = [msg for msg in keyword.messages if self._is_logged(msg.level)]
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 parsing execution results from XML output files. The public API of this package is the :func:`~.ExecutionResult` factory method, which returns :class:`~.Result` objects, and :class:`~.ResultVisitor` abstract class to ease further processing the results. It is highly recommended to use the public API via the :mod:`robot.api` package like in the example below. This package is considered stable. Example ------- .. literalinclude:: /../../doc/api/code_examples/check_test_times.py """ from .executionresult import Result from .resultbuilder import ExecutionResult from .testsuite import TestSuite from .visitor import ResultVisitor
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 MultiMatcher class FlattenKeywordMatcher(object): def __init__(self, flattened): self.match = MultiMatcher(self._yield_patterns(flattened)).match def _yield_patterns(self, flattened): if isinstance(flattened, basestring): flattened = [flattened] for flat in flattened: if not flat.upper().startswith('NAME:'): raise DataError("Expected pattern to start with 'NAME:' " "but got '%s'." % flat) yield flat[5:]
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.model import SuiteVisitor class SuiteTeardownFailureHandler(SuiteVisitor): def end_suite(self, suite): teardown = suite.keywords.teardown # Both 'PASS' and 'NOT_RUN' (used in dry-run) statuses are OK. if teardown and teardown.status == 'FAIL': suite.suite_teardown_failed(teardown.message) def visit_test(self, test): pass def visit_keyword(self, keyword): pass class SuiteTeardownFailed(SuiteVisitor): _normal_msg = 'Parent suite teardown failed:\n' _also_msg = '\n\nAlso parent suite teardown failed:\n' def __init__(self, error): self._normal_msg += error self._also_msg += error def visit_test(self, test): test.status = 'FAIL' test.message += self._also_msg if test.message else self._normal_msg def visit_keyword(self, keyword): 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. """Visitors can be used to easily travel test suites, test cases and keywords.""" from robot.model import SuiteVisitor class ResultVisitor(SuiteVisitor): """Abstract class to conveniently travel :class:`~robot.result.executionresult.Result` objects. An implementation of visitor can be given to the visit method of result object. This will cause the result object to be traversed and the visitor object's ``visit_x``, ``start_x``, and ``end_x`` methods to be called for each test suite, test case, and keyword, as well as for errors, statistics, and other information in the result object. See methods below for a full list of available visitor methods. The start and end method are called for each element and their child elements. The visitor implementation can override only those that it is interested in. If any of the ``start_x`` methods returns False for a certain element, its children are not visited. If the visitor implements a ``visit_x`` method for element x, then the children of that element will not be visited, unless the visitor calls them explicitly. For example, if the visitor implements method :meth:`visit_test`, the :meth:`start_test`, :meth:`end_test`, :meth:`visit_keyword`, :meth:`start_keyword`, and :meth:`end_keyword` methods are not called for tests at all. See the package documentation for :mod:`a usage example <robot.result>`. Visitors are also very widely used internally in Robot Framework. For an example, see the source code of :class:`robot.model.tagsetter.TagSetter`. """ def visit_result(self, result): if self.start_result(result) is not False: result.suite.visit(self) result.statistics.visit(self) result.errors.visit(self) self.end_result(result) def start_result(self, result): pass def end_result(self, result): pass def visit_statistics(self, stats): if self.start_statistics(stats) is not False: stats.total.visit(self) stats.tags.visit(self) stats.suite.visit(self) self.end_statistics(stats) def start_statistics(self, stats): pass def end_statistics(self, stats): pass def visit_total_statistics(self, stats): if self.start_total_statistics(stats) is not False: for stat in stats: stat.visit(self) self.end_total_statistics(stats) def start_total_statistics(self, stats): pass def end_total_statistics(self, stats): pass def visit_tag_statistics(self, stats): if self.start_tag_statistics(stats) is not False: for stat in stats: stat.visit(self) self.end_tag_statistics(stats) def start_tag_statistics(self, stats): pass def end_tag_statistics(self, stats): pass def visit_suite_statistics(self, stats): if self.start_suite_statistics(stats) is not False: for stat in stats: stat.visit(self) self.end_suite_statistics(stats) def start_suite_statistics(self, stats): pass def end_suite_statistics(self, suite_stats): pass def visit_stat(self, stat): if self.start_stat(stat) is not False: self.end_stat(stat) def start_stat(self, stat): pass def end_stat(self, stat): pass def visit_errors(self, errors): self.start_errors(errors) for msg in errors: msg.visit(self) self.end_errors(errors) def start_errors(self, errors): pass def end_errors(self, errors): 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. """Public logging API for test libraries. This module provides a public API for writing messages to the log file and the console. Test libraries can use this API like:: logger.info('My message') instead of logging through the standard output like:: print '*INFO* My message' In addition to a programmatic interface being cleaner to use, this API has a benefit that the log messages have accurate timestamps. Log levels ---------- It is possible to log messages using levels ``TRACE``, ``DEBUG``, ``INFO`` and ``WARN`` either using the ``write`` method or, more commonly, with the log level specific ``trace``, ``debug``, ``info`` and ``warn`` methods. By default the trace and debug messages are not logged but that can be changed with the ``--loglevel`` command line option. Warnings are automatically written also to the `Test Execution Errors` section in the log file and to the console. Logging HTML ------------ All methods that are used for writing messages to the log file have an optional ``html`` argument. If a message to be logged is supposed to be shown as HTML, this argument should be set to ``True``. Example ------- :: from robot.api import logger def my_keyword(arg): logger.debug('Got argument %s.' % arg) do_something() logger.info('<i>This</i> is a boring example.', html=True) """ from robot.output import librarylogger def write(msg, level, html=False): """Writes the message to the log file using the given level. Valid log levels are ``TRACE``, ``DEBUG``, ``INFO`` and ``WARN``. Instead of using this method, it is generally better to use the level specific methods such as ``info`` and ``debug``. """ librarylogger.write(msg, level, html) def trace(msg, html=False): """Writes the message to the log file using the ``TRACE`` level.""" librarylogger.trace(msg, html) def debug(msg, html=False): """Writes the message to the log file using the ``DEBUG`` level.""" librarylogger.debug(msg, html) def info(msg, html=False, also_console=False): """Writes the message to the log file using the ``INFO`` level. If ``also_console`` argument is set to ``True``, the message is written both to the log file and to the console. """ librarylogger.info(msg, html, also_console) def warn(msg, html=False): """Writes the message to the log file using the ``WARN`` level.""" librarylogger.warn(msg, html) def console(msg, newline=True, stream='stdout'): """Writes the message to the console. If the ``newline`` argument is ``True``, a newline character is automatically added to the message. By default the message is written to the standard output stream. Using the standard error stream is possibly by giving the ``stream`` argument value ``'stderr'``. This is a new feature in RF 2.8.2. """ librarylogger.console(msg, newline, stream)
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. """:mod:`robot.api` package exposes the public APIs of Robot Framework. Unless stated otherwise, the APIs exposed in this package are considered stable, and thus safe to use when building external tools on top of Robot Framework. Currently exposed APIs are: * :mod:`.logger` module for test libraries' logging purposes. * :class:`~robot.parsing.model.TestCaseFile`, :class:`~robot.parsing.model.TestDataDirectory`, and :class:`~robot.parsing.model.ResourceFile` classes for parsing test data files and directories. In addition, a convenience factory method :func:`~robot.parsing.model.TestData` creates either :class:`~robot.parsing.model.TestCaseFile` or :class:`~robot.parsing.model.TestDataDirectory` objects based on the input. **Note:** Test data parsing may be rewritten in Robot Framework 2.9 or later. * :class:`~robot.running.model.TestSuite` class for creating executable test suites programmatically and :class:`~robot.running.builder.TestSuiteBuilder` class for creating such suites based on existing test data on the file system. * :func:`~robot.result.resultbuilder.ExecutionResult` factory method for reading execution results from XML output files and :class:`~robot.result.visitor.ResultVisitor` abstract class to ease further processing the results. * :class:`~robot.reporting.resultwriter.ResultWriter` class for writing reports, logs, XML outputs, and XUnit files. Can write results based on XML outputs on the file system, as well as based on the result objects returned by the :func:`~robot.result.resultbuilder.ExecutionResult` or an executed :class:`~robot.running.model.TestSuite`. All of the above names can be imported like:: from robot.api import ApiName See documentations of the individual APIs for more details. .. tip:: APIs related to the command line entry points are exposed directly via the :mod:`robot` root package. """ from robot.parsing import TestCaseFile, TestDataDirectory, ResourceFile, TestData from robot.reporting import ResultWriter from robot.result import ExecutionResult, ResultVisitor from robot.running import TestSuite, TestSuiteBuilder
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 utils # Return codes from Robot and Rebot. # RC below 250 is the number of failed critical tests and exactly 250 # means that number or more such failures. INFO_PRINTED = 251 # --help or --version DATA_ERROR = 252 # Invalid data or cli args STOPPED_BY_USER = 253 # KeyboardInterrupt or SystemExit FRAMEWORK_ERROR = 255 # Unexpected error class RobotError(Exception): """Base class for Robot Framework errors. Do not raise this method but use more specific errors instead. """ def __init__(self, message='', details=''): Exception.__init__(self, message) self.details = details @property def message(self): return self.__unicode__() def __unicode__(self): # Needed to handle exceptions w/ Unicode correctly on Python 2.5 return unicode(self.args[0]) if self.args else u'' class FrameworkError(RobotError): """Can be used when the core framework goes to unexpected state. It is good to explicitly raise a FrameworkError if some framework component is used incorrectly. This is pretty much same as 'Internal Error' and should of course never happen. """ class DataError(RobotError): """Used when the provided test data is invalid. DataErrors are not be caught by keywords that run other keywords (e.g. `Run Keyword And Expect Error`). Libraries should thus use this exception with care. """ class TimeoutError(RobotError): """Used when a test or keyword timeout occurs. This exception is handled specially so that execution of the current test is always stopped immediately and it is not caught by keywords executing other keywords (e.g. `Run Keyword And Expect Error`). Libraries should thus NOT use this exception themselves. """ class Information(RobotError): """Used by argument parser with --help or --version.""" class ExecutionFailed(RobotError): """Used for communicating failures in test execution.""" def __init__(self, message, timeout=False, syntax=False, exit=False, continue_on_failure=False, return_value=None): if '\r\n' in message: message = message.replace('\r\n', '\n') RobotError.__init__(self, utils.cut_long_message(message)) self.timeout = timeout self.syntax = syntax self.exit = exit self.continue_on_failure = continue_on_failure self.return_value = return_value @property def dont_continue(self): return self.timeout or self.syntax or self.exit def _get_continue_on_failure(self): return self._continue_on_failure def _set_continue_on_failure(self, continue_on_failure): self._continue_on_failure = continue_on_failure for child in getattr(self, '_errors', []): child.continue_on_failure = continue_on_failure continue_on_failure = property(_get_continue_on_failure, _set_continue_on_failure) def can_continue(self, teardown=False, templated=False, dry_run=False): if dry_run: return True if self.dont_continue and not (teardown and self.syntax): return False if teardown or templated: return True return self.continue_on_failure def get_errors(self): return [self] class HandlerExecutionFailed(ExecutionFailed): def __init__(self): details = utils.ErrorDetails() timeout = isinstance(details.error, TimeoutError) syntax = isinstance(details.error, DataError) exit_on_failure = self._get(details.error, 'EXIT_ON_FAILURE') continue_on_failure = self._get(details.error, 'CONTINUE_ON_FAILURE') ExecutionFailed.__init__(self, details.message, timeout, syntax, exit_on_failure, continue_on_failure) self.full_message = details.message self.traceback = details.traceback self._handle_deprecated_exit_for_loop(details.error) def _get(self, error, attr): return bool(getattr(error, 'ROBOT_' + attr, False)) def _handle_deprecated_exit_for_loop(self, error): if self._get(error, 'EXIT_FOR_LOOP'): from robot.output import LOGGER LOGGER.warn("Support for using 'ROBOT_EXIT_FOR_LOOP' attribute to " "exit for loops is deprecated in Robot Framework 2.8 " "and will be removed in 2.9.") raise ExitForLoop class ExecutionFailures(ExecutionFailed): def __init__(self, errors, message=None): message = message or self._format_message([unicode(e) for e in errors]) ExecutionFailed.__init__(self, message, **self._get_attrs(errors)) self._errors = errors def _format_message(self, messages): if len(messages) == 1: return messages[0] lines = ['Several failures occurred:'] \ + ['%d) %s' % (i+1, m) for i, m in enumerate(messages)] return '\n\n'.join(lines) def _get_attrs(self, errors): return {'timeout': any(err.timeout for err in errors), 'syntax': any(err.syntax for err in errors), 'exit': any(err.exit for err in errors), 'continue_on_failure': all(err.continue_on_failure for err in errors) } def get_errors(self): return self._errors class UserKeywordExecutionFailed(ExecutionFailures): def __init__(self, run_errors=None, teardown_errors=None): errors = self._get_active_errors(run_errors, teardown_errors) message = self._get_message(run_errors, teardown_errors) ExecutionFailures.__init__(self, errors, message) if run_errors and not teardown_errors: self._errors = run_errors.get_errors() else: self._errors = [self] def _get_active_errors(self, *errors): return [err for err in errors if err] def _get_message(self, run_errors, teardown_errors): run_msg = unicode(run_errors or '') td_msg = unicode(teardown_errors or '') if not td_msg: return run_msg if not run_msg: return 'Keyword teardown failed:\n%s' % td_msg return '%s\n\nAlso keyword teardown failed:\n%s' % (run_msg, td_msg) class ExecutionPassed(ExecutionFailed): """Base class for all exceptions communicating that execution passed. Should not be raised directly, but more detailed exceptions used instead. """ def __init__(self, message=None, **kwargs): ExecutionFailed.__init__(self, message or self._get_message(), **kwargs) self._earlier_failures = [] def _get_message(self): return "Invalid '%s' usage." \ % utils.printable_name(self.__class__.__name__, code_style=True) def set_earlier_failures(self, failures): if failures: self._earlier_failures.extend(failures) @property def earlier_failures(self): if not self._earlier_failures: return None return ExecutionFailures(self._earlier_failures) class PassExecution(ExecutionPassed): """Used by 'Pass Execution' keyword.""" def __init__(self, message): ExecutionPassed.__init__(self, message) class ContinueForLoop(ExecutionPassed): """Used by 'Continue For Loop' keyword.""" class ExitForLoop(ExecutionPassed): """Used by 'Exit For Loop' keyword.""" class ReturnFromKeyword(ExecutionPassed): """Used by 'Return From Keyword' keyword.""" def __init__(self, return_value): ExecutionPassed.__init__(self, return_value=return_value) class RemoteError(RobotError): """Used by Remote library to report remote errors.""" def __init__(self, message='', details='', fatal=False, continuable=False): RobotError.__init__(self, message, details) self.ROBOT_EXIT_ON_FAILURE = fatal self.ROBOT_CONTINUE_ON_FAILURE = continuable
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 from robot import utils from robot.errors import DataError, FrameworkError from robot.output import LOGGER, loggerhelper from robot.result.keywordremover import KeywordRemover from robot.result.flattenkeywordmatcher import FlattenKeywordMatcher from .gatherfailed import gather_failed_tests class _BaseSettings(object): _cli_opts = {'Name' : ('name', None), 'Doc' : ('doc', None), 'Metadata' : ('metadata', []), 'TestNames' : ('test', []), 'ReRunFailed' : ('rerunfailed', 'NONE'), 'DeprecatedRunFailed': ('runfailed', 'NONE'), 'SuiteNames' : ('suite', []), 'SetTag' : ('settag', []), 'Include' : ('include', []), 'Exclude' : ('exclude', []), 'Critical' : ('critical', None), 'NonCritical' : ('noncritical', None), 'OutputDir' : ('outputdir', utils.abspath('.')), 'Log' : ('log', 'log.html'), 'Report' : ('report', 'report.html'), 'XUnit' : ('xunit', None), 'DeprecatedXUnit' : ('xunitfile', None), 'SplitLog' : ('splitlog', False), 'TimestampOutputs' : ('timestampoutputs', False), 'LogTitle' : ('logtitle', None), 'ReportTitle' : ('reporttitle', None), 'ReportBackground' : ('reportbackground', ('#99FF66', '#99FF66', '#FF3333')), 'SuiteStatLevel' : ('suitestatlevel', -1), 'TagStatInclude' : ('tagstatinclude', []), 'TagStatExclude' : ('tagstatexclude', []), 'TagStatCombine' : ('tagstatcombine', []), 'TagDoc' : ('tagdoc', []), 'TagStatLink' : ('tagstatlink', []), 'RemoveKeywords' : ('removekeywords', []), 'FlattenKeywords' : ('flattenkeywords', []), 'NoStatusRC' : ('nostatusrc', False), 'MonitorColors' : ('monitorcolors', 'AUTO'), 'StdOut' : ('stdout', None), 'StdErr' : ('stderr', None), 'XUnitSkipNonCritical' : ('xunitskipnoncritical', False)} _output_opts = ['Output', 'Log', 'Report', 'XUnit', 'DebugFile'] def __init__(self, options=None, **extra_options): self._opts = {} self._cli_opts = self._cli_opts.copy() self._cli_opts.update(self._extra_cli_opts) self._process_cli_opts(dict(options or {}, **extra_options)) def _process_cli_opts(self, opts): for name, (cli_name, default) in self._cli_opts.items(): value = opts[cli_name] if cli_name in opts else default if default == [] and isinstance(value, basestring): value = [value] self[name] = self._process_value(name, value) self['TestNames'] += self['ReRunFailed'] or self['DeprecatedRunFailed'] if self['DeprecatedXUnit']: self['XUnit'] = self['DeprecatedXUnit'] def __setitem__(self, name, value): if name not in self._cli_opts: raise KeyError("Non-existing settings '%s'" % name) self._opts[name] = value def _process_value(self, name, value): if name in ['ReRunFailed', 'DeprecatedRunFailed']: return gather_failed_tests(value) if name == 'LogLevel': return self._process_log_level(value) if value == self._get_default_value(name): return value if name in ['Name', 'Doc', 'LogTitle', 'ReportTitle']: if name == 'Doc': value = self._escape_as_data(value) return value.replace('_', ' ') if name in ['Metadata', 'TagDoc']: if name == 'Metadata': value = [self._escape_as_data(v) for v in value] return [self._process_metadata_or_tagdoc(v) for v in value] if name in ['Include', 'Exclude']: return [self._format_tag_patterns(v) for v in value] if name in self._output_opts and (not value or value.upper() == 'NONE'): return None if name == 'DeprecatedXUnit': LOGGER.warn('Option --xunitfile is deprecated. Use --xunit instead.') return self._process_value('XUnit', value) if name == 'OutputDir': return utils.abspath(value) if name in ['SuiteStatLevel', 'MonitorWidth']: return self._convert_to_positive_integer_or_default(name, value) if name in ['Listeners', 'VariableFiles']: return [self._split_args_from_name_or_path(item) for item in value] if name == 'ReportBackground': return self._process_report_background(value) if name == 'TagStatCombine': return [self._process_tag_stat_combine(v) for v in value] if name == 'TagStatLink': return [v for v in [self._process_tag_stat_link(v) for v in value] if v] if name == 'Randomize': return self._process_randomize_value(value) if name == 'RunMode': LOGGER.warn('Option --runmode is deprecated in Robot Framework 2.8 ' 'and will be removed in the future.') return [self._process_runmode_value(v) for v in value] if name == 'RemoveKeywords': self._validate_remove_keywords(value) if name == 'FlattenKeywords': self._validate_flatten_keywords(value) return value def _escape_as_data(self, value): return value def _process_log_level(self, level): level, visible_level = self._split_log_level(level.upper()) self._opts['VisibleLogLevel'] = visible_level return level def _split_log_level(self, level): if ':' in level: level, visible_level = level.split(':', 1) else: visible_level = level self._validate_log_level_and_default(level, visible_level) return level, visible_level def _validate_log_level_and_default(self, log_level, default): if log_level not in loggerhelper.LEVELS: raise DataError("Invalid log level '%s'" % log_level) if default not in loggerhelper.LEVELS: raise DataError("Invalid log level '%s'" % default) if not loggerhelper.IsLogged(log_level)(default): raise DataError("Default visible log level '%s' is lower than " "log level '%s'" % (default, log_level)) def _process_randomize_value(self, original_value): formatted_value = original_value.lower() if formatted_value in ('test', 'suite'): formatted_value += 's' if formatted_value not in ('tests', 'suites', 'none', 'all'): self._raise_invalid_option_value('--randomize', original_value) return formatted_value def _raise_invalid_option_value(self, option_name, given_value): raise DataError("Option '%s' does not support value '%s'." % (option_name, given_value)) def _process_runmode_value(self, original_value): formatted_value = original_value.lower() if formatted_value not in ('exitonfailure', 'skipteardownonexit', 'dryrun', 'random:test', 'random:suite', 'random:all'): self._raise_invalid_option_value('--runmode', original_value) return formatted_value def __getitem__(self, name): if name not in self._opts: raise KeyError("Non-existing setting '%s'" % name) if name in self._output_opts: return self._get_output_file(name) return self._opts[name] def _get_output_file(self, option): """Returns path of the requested output file and creates needed dirs. `option` can be 'Output', 'Log', 'Report', 'XUnit' or 'DebugFile'. """ name = self._opts[option] if not name: return None if option == 'Log' and self._output_disabled(): self['Log'] = None LOGGER.error('Log file is not created if output.xml is disabled.') return None name = self._process_output_name(option, name) path = utils.abspath(os.path.join(self['OutputDir'], name)) self._create_output_dir(os.path.dirname(path), option) return path def _process_output_name(self, option, name): base, ext = os.path.splitext(name) if self['TimestampOutputs']: base = '%s-%s' % (base, utils.get_start_timestamp('', '-', '')) ext = self._get_output_extension(ext, option) return base + ext def _get_output_extension(self, ext, type_): if ext != '': return ext if type_ in ['Output', 'XUnit']: return '.xml' if type_ in ['Log', 'Report']: return '.html' if type_ == 'DebugFile': return '.txt' raise FrameworkError("Invalid output file type: %s" % type_) def _create_output_dir(self, path, type_): try: if not os.path.exists(path): os.makedirs(path) except EnvironmentError, err: raise DataError("Creating %s file directory '%s' failed: %s" % (type_.lower(), path, err.strerror)) def _process_metadata_or_tagdoc(self, value): value = value.replace('_', ' ') if ':' in value: return value.split(':', 1) return value, '' def _process_report_background(self, colors): if colors.count(':') not in [1, 2]: raise DataError("Invalid report background colors '%s'." % colors) colors = colors.split(':') if len(colors) == 2: return colors[0], colors[0], colors[1] return tuple(colors) def _process_tag_stat_combine(self, pattern): if ':' in pattern: pattern, title = pattern.rsplit(':', 1) else: title = '' return self._format_tag_patterns(pattern), title.replace('_', ' ') def _format_tag_patterns(self, pattern): for search, replace in [('&', 'AND'), ('AND', ' AND '), ('OR', ' OR '), ('NOT', ' NOT '), ('_', ' ')]: if search in pattern: pattern = pattern.replace(search, replace) while ' ' in pattern: pattern = pattern.replace(' ', ' ') return pattern def _process_tag_stat_link(self, value): tokens = value.split(':') if len(tokens) >= 3: return tokens[0], ':'.join(tokens[1:-1]), tokens[-1] raise DataError("Invalid format for option '--tagstatlink'. " "Expected 'tag:link:title' but got '%s'." % value) def _convert_to_positive_integer_or_default(self, name, value): value = self._convert_to_integer(name, value) return value if value > 0 else self._get_default_value(name) def _convert_to_integer(self, name, value): try: return int(value) except ValueError: raise DataError("Option '--%s' expected integer value but got '%s'." % (name.lower(), value)) def _get_default_value(self, name): return self._cli_opts[name][1] def _split_args_from_name_or_path(self, name): if ':' not in name or os.path.exists(name): args = [] else: args = name.split(':') name = args.pop(0) # Handle absolute Windows paths with arguments if len(name) == 1 and args[0].startswith(('/', '\\')): name = name + ':' + args.pop(0) if os.path.exists(name): name = os.path.abspath(name) return name, args def _validate_remove_keywords(self, values): for value in values: try: KeywordRemover(value) except DataError, err: raise DataError("Invalid value for option '--removekeywords'. %s" % err) def _validate_flatten_keywords(self, values): for value in values: try: FlattenKeywordMatcher(value) except DataError, err: raise DataError("Invalid value for option '--flattenkeywords'. %s" % err) def __contains__(self, setting): return setting in self._cli_opts def __unicode__(self): return '\n'.join('%s: %s' % (name, self._opts[name]) for name in sorted(self._opts)) @property def output(self): return self['Output'] @property def log(self): return self['Log'] @property def report(self): return self['Report'] @property def xunit(self): return self['XUnit'] @property def split_log(self): return self['SplitLog'] @property def status_rc(self): return not self['NoStatusRC'] @property def xunit_skip_noncritical(self): return self['XUnitSkipNonCritical'] @property def statistics_config(self): return { 'suite_stat_level': self['SuiteStatLevel'], 'tag_stat_include': self['TagStatInclude'], 'tag_stat_exclude': self['TagStatExclude'], 'tag_stat_combine': self['TagStatCombine'], 'tag_stat_link': self['TagStatLink'], 'tag_doc': self['TagDoc'], } @property def critical_tags(self): return self['Critical'] @property def non_critical_tags(self): return self['NonCritical'] @property def remove_keywords(self): return self['RemoveKeywords'] @property def flatten_keywords(self): return self['FlattenKeywords'] class RobotSettings(_BaseSettings): _extra_cli_opts = {'Output' : ('output', 'output.xml'), 'LogLevel' : ('loglevel', 'INFO'), 'DryRun' : ('dryrun', False), 'ExitOnFailure' : ('exitonfailure', False), 'SkipTeardownOnExit' : ('skipteardownonexit', False), 'Randomize' : ('randomize', 'NONE'), 'RunMode' : ('runmode', []), 'RunEmptySuite' : ('runemptysuite', False), 'WarnOnSkipped' : ('warnonskippedfiles', False), 'Variables' : ('variable', []), 'VariableFiles' : ('variablefile', []), 'Listeners' : ('listener', []), 'MonitorWidth' : ('monitorwidth', 78), 'MonitorMarkers' : ('monitormarkers', 'AUTO'), 'DebugFile' : ('debugfile', None)} def get_rebot_settings(self): settings = RebotSettings() settings._opts.update(self._opts) for name in ['Variables', 'VariableFiles', 'Listeners']: del(settings._opts[name]) for name in ['Include', 'Exclude', 'TestNames', 'SuiteNames', 'Metadata']: settings._opts[name] = [] for name in ['Name', 'Doc']: settings._opts[name] = None settings._opts['Output'] = None settings._opts['LogLevel'] = 'TRACE' settings._opts['ProcessEmptySuite'] = self['RunEmptySuite'] return settings def _output_disabled(self): return self.output is None def _escape_as_data(self, value): return utils.escape(value) @property def suite_config(self): return { 'name': self['Name'], 'doc': self['Doc'], 'metadata': dict(self['Metadata']), 'set_tags': self['SetTag'], 'include_tags': self['Include'], 'exclude_tags': self['Exclude'], 'include_suites': self['SuiteNames'], 'include_tests': self['TestNames'], 'empty_suite_ok': self['RunEmptySuite'], 'randomize_suites': self.randomize_suites, 'randomize_tests': self.randomize_tests } @property def randomize_suites(self): return (self['Randomize'] in ('suites', 'all') or any(mode in ('random:suite', 'random:all') for mode in self['RunMode'])) @property def randomize_tests(self): return (self['Randomize'] in ('tests', 'all') or any(mode in ('random:test', 'random:all') for mode in self['RunMode'])) @property def dry_run(self): return (self['DryRun'] or any(mode == 'dryrun' for mode in self['RunMode'])) @property def exit_on_failure(self): return (self['ExitOnFailure'] or any(mode == 'exitonfailure' for mode in self['RunMode'])) @property def skip_teardown_on_exit(self): return (self['SkipTeardownOnExit'] or any(mode == 'skipteardownonexit' for mode in self['RunMode'])) @property def console_logger_config(self): return { 'width': self['MonitorWidth'], 'colors': self['MonitorColors'], 'markers': self['MonitorMarkers'], 'stdout': self['StdOut'], 'stderr': self['StdErr'] } class RebotSettings(_BaseSettings): _extra_cli_opts = {'Output' : ('output', None), 'LogLevel' : ('loglevel', 'TRACE'), 'ProcessEmptySuite' : ('processemptysuite', False), 'StartTime' : ('starttime', None), 'EndTime' : ('endtime', None), 'ReRunMerge' : ('rerunmerge', False)} def _output_disabled(self): return False @property def suite_config(self): return { 'name': self['Name'], 'doc': self['Doc'], 'metadata': dict(self['Metadata']), 'set_tags': self['SetTag'], 'include_tags': self['Include'], 'exclude_tags': self['Exclude'], 'include_suites': self['SuiteNames'], 'include_tests': self['TestNames'], 'empty_suite_ok': self['ProcessEmptySuite'], 'remove_keywords': self.remove_keywords, 'log_level': self['LogLevel'], 'critical_tags': self.critical_tags, 'non_critical_tags': self.non_critical_tags, 'start_time': self['StartTime'], 'end_time': self['EndTime'] } @property def log_config(self): if not self.log: return {} return { 'title': utils.html_escape(self['LogTitle'] or ''), 'reportURL': self._url_from_path(self.log, self.report), 'splitLogBase': os.path.basename(os.path.splitext(self.log)[0]), 'defaultLevel': self['VisibleLogLevel'] } @property def report_config(self): if not self.report: return {} return { 'title': utils.html_escape(self['ReportTitle'] or ''), 'logURL': self._url_from_path(self.report, self.log), 'background' : self._resolve_background_colors(), } def _url_from_path(self, source, destination): if not destination: return None return utils.get_link_path(destination, os.path.dirname(source)) def _resolve_background_colors(self): colors = self['ReportBackground'] return {'pass': colors[0], 'nonCriticalFail': colors[1], 'fail': colors[2]} @property def rerun_merge(self): return self['ReRunMerge'] @property def console_logger_config(self): return { 'colors': self['MonitorColors'], 'stdout': self['StdOut'], 'stderr': self['StdErr'] }
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.model import SuiteVisitor from robot.result import ExecutionResult from robot.utils import get_error_message class GatherFailedTests(SuiteVisitor): def __init__(self): self.tests = [] def visit_test(self, test): if not test.passed: self.tests.append(test.longname) def visit_keyword(self, kw): pass def gather_failed_tests(output): if output.upper() == 'NONE': return [] gatherer = GatherFailedTests() try: ExecutionResult(output, include_keywords=False).suite.visit(gatherer) if not gatherer.tests: raise DataError('All tests passed.') except: raise DataError("Collecting failed tests from '%s' failed: %s" % (output, get_error_message())) return gatherer.tests
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 settings for both test execution and output processing. This package implements :class:`~robot.conf.settings.RobotSettings` and :class:`~robot.conf.settings.RebotSettings` classes used internally by the framework. There should be no need to use these classes externally. This package can be considered relatively stable. Aforementioned classes are likely to be rewritten at some point to be more convenient to use. Instantiating them is not likely to change, though. """ from .settings import RobotSettings, RebotSettings
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 import utils from robot.errors import DataError from robot.model import Message as BaseMessage LEVELS = { 'NONE' : 6, 'ERROR' : 5, 'FAIL' : 4, 'WARN' : 3, 'INFO' : 2, 'DEBUG' : 1, 'TRACE' : 0, } class AbstractLogger: def __init__(self, level='TRACE'): self._is_logged = IsLogged(level) def set_level(self, level): return self._is_logged.set_level(level) def trace(self, msg): self.write(msg, 'TRACE') def debug(self, msg): self.write(msg, 'DEBUG') def info(self, msg): self.write(msg, 'INFO') def warn(self, msg): self.write(msg, 'WARN') def fail(self, msg): html = False if msg.startswith("*HTML*"): html = True msg = msg[6:].lstrip() self.write(msg, 'FAIL', html) def error(self, msg): self.write(msg, 'ERROR') def write(self, message, level, html=False): self.message(Message(message, level, html)) def message(self, msg): raise NotImplementedError(self.__class__) class Message(BaseMessage): __slots__ = ['_message'] def __init__(self, message, level='INFO', html=False, timestamp=None): message = self._normalize_message(message) level, html = self._get_level_and_html(level, html) timestamp = timestamp or utils.get_timestamp() BaseMessage.__init__(self, message, level, html, timestamp) def _normalize_message(self, msg): if callable(msg): return msg if not isinstance(msg, unicode): msg = utils.unic(msg) if '\r\n' in msg: msg = msg.replace('\r\n', '\n') return msg def _get_level_and_html(self, level, html): level = level.upper() if level == 'HTML': return 'INFO', True if level not in LEVELS: raise DataError("Invalid log level '%s'" % level) return level, html def _get_message(self): if callable(self._message): self._message = self._message() return self._message def _set_message(self, message): self._message = message message = property(_get_message, _set_message) class IsLogged: def __init__(self, level): self._str_level = level self._int_level = self._level_to_int(level) def __call__(self, level): return self._level_to_int(level) >= self._int_level def set_level(self, level): old = self._str_level.upper() self.__init__(level) return old def _level_to_int(self, level): try: return LEVELS[level.upper()] except KeyError: raise DataError("Invalid log level '%s'" % level) class AbstractLoggerProxy: _methods = NotImplemented _no_method = lambda *args: None def __init__(self, logger): self.logger = logger for name in self._methods: setattr(self, name, self._get_method(logger, name)) def _get_method(self, logger, name): if hasattr(logger, name): return getattr(logger, name) return getattr(logger, self._toCamelCase(name), self._no_method) def _toCamelCase(self, name): parts = name.split('_') return ''.join([parts[0]] + [part.capitalize() for part in parts[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 XmlWriter, NullMarkupWriter, get_timestamp, unic from robot.version import get_full_version from robot.result.visitor import ResultVisitor from .loggerhelper import IsLogged class XmlLogger(ResultVisitor): def __init__(self, path, log_level='TRACE', generator='Robot'): self._log_message_is_logged = IsLogged(log_level) self._error_message_is_logged = IsLogged('WARN') self._writer = self._get_writer(path, generator) self._errors = [] def _get_writer(self, path, generator): if not path: return NullMarkupWriter() try: writer = XmlWriter(path, encoding='UTF-8') except EnvironmentError, err: raise DataError("Opening output file '%s' failed: %s" % (path, err.strerror)) writer.start('robot', {'generator': get_full_version(generator), 'generated': get_timestamp()}) return writer def close(self): self.start_errors() for msg in self._errors: self._write_message(msg) self.end_errors() self._writer.end('robot') self._writer.close() def set_log_level(self, level): return self._log_message_is_logged.set_level(level) def message(self, msg): if self._error_message_is_logged(msg.level): self._errors.append(msg) def log_message(self, msg): if self._log_message_is_logged(msg.level): self._write_message(msg) def _write_message(self, msg): attrs = {'timestamp': msg.timestamp or 'N/A', 'level': msg.level} if msg.html: attrs['html'] = 'yes' self._writer.element('msg', msg.message, attrs) def start_keyword(self, kw): attrs = {'name': kw.name, 'type': kw.type} if kw.timeout: attrs['timeout'] = unicode(kw.timeout) self._writer.start('kw', attrs) self._writer.element('doc', kw.doc) self._write_list('arguments', 'arg', (unic(a) for a in kw.args)) def end_keyword(self, kw): self._write_status(kw) self._writer.end('kw') def start_test(self, test): attrs = {'id': test.id, 'name': test.name} if test.timeout: attrs['timeout'] = unicode(test.timeout) self._writer.start('test', attrs) def end_test(self, test): self._writer.element('doc', test.doc) self._write_list('tags', 'tag', test.tags) self._write_status(test, {'critical': 'yes' if test.critical else 'no'}) self._writer.end('test') def start_suite(self, suite): attrs = {'id': suite.id, 'name': suite.name} if suite.source: attrs['source'] = suite.source self._writer.start('suite', attrs) def end_suite(self, suite): self._writer.element('doc', suite.doc) self._writer.start('metadata') for name, value in suite.metadata.items(): self._writer.element('item', value, {'name': name}) self._writer.end('metadata') self._write_status(suite) self._writer.end('suite') def start_statistics(self, stats): self._writer.start('statistics') def end_statistics(self, stats): self._writer.end('statistics') def start_total_statistics(self, total_stats): self._writer.start('total') def end_total_statistics(self, total_stats): self._writer.end('total') def start_tag_statistics(self, tag_stats): self._writer.start('tag') def end_tag_statistics(self, tag_stats): self._writer.end('tag') def start_suite_statistics(self, tag_stats): self._writer.start('suite') def end_suite_statistics(self, tag_stats): self._writer.end('suite') def visit_stat(self, stat): self._writer.element('stat', stat.name, stat.get_attributes(values_as_strings=True)) def start_errors(self, errors=None): self._writer.start('errors') def end_errors(self, errors=None): self._writer.end('errors') def _write_list(self, container_tag, item_tag, items): self._writer.start(container_tag) for item in items: self._writer.element(item_tag, item) self._writer.end(container_tag) def _write_status(self, item, extra_attrs=None): attrs = {'status': item.status, 'starttime': item.starttime or 'N/A', 'endtime': item.endtime or 'N/A'} if not (item.starttime and item.endtime): attrs['elapsedtime'] = str(item.elapsedtime) if extra_attrs: attrs.update(extra_attrs) self._writer.element('status', item.message, attrs)
Python