code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
# robotframework-openweathermap [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![CodeQL](https://github.com/joergschultzelutter/robotframework-openweathermap/actions/workflows/codeql.yml/badge.svg)](https://github.com/joergschultzelutter/robotframework-openweathermap/actions/workflows/codeql.yml) [![PyPi version](https://img.shields.io/pypi/v/robotframework-openweathermap.svg)](https://pypi.python.org/pypi/robotframework-openweathermap) ```robotframework-openweathermap``` is a [Robot Framework](https://www.robotframework.org) keyword collection for the [OpenWeatherMap](https://www.openweathermap.org/api) API. ## Installation The easiest way is to install this package is from pypi: pip install robotframework-openweathermap ## Robot Framework Library Examples Prerequisites: The accompanying Robot Framework [test file](https://github.com/joergschultzelutter/robotframework-openweathermap/blob/master/tests/keyword_checks.robot) relies on two requirements: - [get an OpenWeatherMap API key](https://home.openweathermap.org/users/sign_up) (it's free) - create an environment variable ```OWM_API_KEY``` and assign the OpenWeatherMap API key to that variable - Execute test with ``robot keyword_checks.robot`` ## Library usage and supported keywords ### Default settings The following rules apply: - The default value for each parameter is ```None``` - Each parameter supports ```Getter``` and ```Setter``` keywords, e.g, ```Set OpenWeatherMap Latitude``` - Each OpenWeatherMap Keyword also permits the usage of these parameters. Example: ```robot Get Current Weather latitude=.... ``` - A keyword's parameter value has priority over the ```Setter``` value. This means that if you use ```Set OpenWeathermap Latitude 10``` and ```Get Current Weather latitude=20```, the value from the OWK Keyword will supersede the ``Setter`` keyword and a value of ```20``` is going to be used. ### Options for setting the parameter values You can either specify all parameters during the initial setup of the library or alternatively via separate keywords #### Option 1 - set as position parameters ```robot *** Settings *** Library OpenWeatherMapLibrary 51.82798 9.4455 ... *** Test Cases *** My first test case ``` #### Option 2 - set as named parameters ```robot *** Settings *** Library OpenWeatherMapLibrary latitude=51.82798 longitude=9.4455 ... *** Test Cases *** My first test case ``` #### Option 3 - Use Robot Keywords ```robot Set OpenWeatherMap Latitude latitude=51.82798 ``` ### Generic Getter / Setter Robot Keywords supported by this library You can use these optional Getter/Setter methods for setting your fixed default values. If you specify the same parameter as part of the actual OpenWeatherMap keyword, the value specified with that API call supersedes these generic Getter/Setter values. | Keyword | Description | Arguments | Valid Values | |--------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------|------------------------------------------------------------------------------------------| | ``Get``/``Set OpenWeatherMap Latitude`` | Gets / Sets the latitude value | ``latitude`` | float value | | ``Get``/``Set OpenWeatherMap Longitude`` | Gets / Sets the longitude value | ``longitude`` | float value | | ``Get``/``Set OpenWeatherMap API Key`` | Gets / Sets the OWM API Key | ``apikey`` | string | | ``Get``/``Set OpenWeatherMap Number Of Results`` | Gets / Sets the max number of results | ``number`` | integer > 0 | | ``Get``/``Set OpenWeatherMap Language`` | Gets / Sets the desired output language | ``language`` | see [OpenWeatherMap API](https://openweathermap.org/current#multi)<br />for valid values | | ``Get``/``Set OpenWeatherMap Excludes`` | Gets / Sets the exclude(s) value.<br /> Separarate multiple values with a comma<br />See [API documentation](https://openweathermap.org/api/one-call-api) for details | ``exclude`` | ``current``<br />``minutely``<br />``hourly``<br />``daily``<br />``alerts`` | | ``Get``/``Set OpenWeatherMap Output Format`` | Gets / Sets the output format (e.g. ``json``) | ``output_format`` | ``json``<br />``xml``<br />``html`` | | ``Get``/``Set OpenWeatherMap Unit Format`` | Gets / Sets the unit format<br />See [API Documentation](https://openweathermap.org/api/one-call-api#data) for details<br />Format availability depends on API call | ``unit_format`` | ``standard``<br />``metric``<br >``imperial`` | | ``Get``/``Set OpenWeatherMap Datetime Start`` | Gets / Sets the start datetime for date ranges | ``dt_start`` | Unix timestamp | | ``Get``/``Set OpenWeatherMap Datetime End`` | Gets / Sets the end datetime for date ranges | ``dt_end`` | Unix timestamp | | ``Get``/``Set OpenWeatherMap Datetime`` | Gets / Sets a single point in time | ``dt`` | Unix Timestamp | ## OpenWeatherMap Keywords Please note that a majority of these keywords requires a paid OpenWeatherMap subscription. You can still try to run the keywords but most of them will fail with a http 4xx error unless you have a valid paid subscription. Each of the following keywords has a set of mandatory parameters. which means that if you used the setter methods to assign values for ``latitude`` and ``longitude``, for example, you can omit those values for the following keywords. | Keyword | Description | Mandatory<br />parameters | Optional<br />parameters | Comments | | ------- | ----------- | -------------------- | ------------------- |---------------------------------------| | [Get Current Weather](https://openweathermap.org/current) | Access current weather data for any location on<br />Earth including over 200,000 cities | ``latitude``<br />``longitude``<br />``apikey``|``output_format``<br />``unit_format``<br />``language`` | | | [Get Hourly Forecast 4 Days](https://openweathermap.org/api/hourly-forecast) | Hourly forecast for 4 days (96 timestamps) | ``latitude``<br />``longitude``<br />``apikey``|``output_format``<br />``number``<br />``language`` | no ``output_format``<br />support for HTML | | [Get OneCall Forecast](https://openweathermap.org/api/one-call-api) | Current and forecast weather data | ``latitude``<br />``longitude``<br />``apikey``|``exclude``<br />``unit_format``<br />``language`` | | | [Get Daily Forecasts 16 Days](https://openweathermap.org/forecast16) | Daily Forecast 16 Days is available at any location on the globe. | ``latitude``<br />``longitude``<br />``apikey``|``number``<br />``unit_format``<br />``output_format``<br />``language`` | no ``output_format``<br />support for HTML | | [Get Climatic Forecasts 30 Days](https://openweathermap.org/forecast30) | Climate Forecast 30 Days allows you to request daily weather data for the next 30 days | ``latitude``<br />``longitude``<br />``apikey``|``number``<br />``unit_format``<br />``output_format``<br />``language`` | no ``output_format``<br />support for HTML | | [Get Current Solar Radiation](https://openweathermap.org/api/solar-radiation) | Current solar radiation data | ``latitude``<br />``longitude``<br />``apikey``| | | | [Get Solar Radiation Forecast](https://openweathermap.org/api/solar-radiation) | Forecast solar radiation data | ``latitude``<br />``longitude``<br />``apikey``| | | | [Get Solar Radiation History](https://openweathermap.org/api/solar-radiation) | Historical solar radiation data<br />for a from-to time span | ``latitude``<br />``longitude``<br />``apikey``<br />``dt_start``<br />``dt_end``| | | | [Get 5 Day 3 Hour Forecast](https://openweathermap.org/forecast5) | 5 day forecast is available at any location on the globe | ``latitude``<br />``longitude``<br />``apikey``|``number``<br />``unit_format``<br />``output_format``<br />``language`` | no ``output_format``<br />support for HTML | | [Get Current Air Pollution Radiation](https://openweathermap.org/api/air-pollution) | Current air pollution data | ``latitude``<br />``longitude``<br />``apikey``| | | | [Get Air Pollution Forecast](https://openweathermap.org/api/air-pollution) | Air pollution data forecast | ``latitude``<br />``longitude``<br />``apikey``| | | | [Get Air Pollution History](https://openweathermap.org/api/air-pollution) | Historical Air Pollution data<br />for a from-to time span | ``latitude``<br />``longitude``<br />``apikey``<br />``dt_start``<br />``dt_end``| | | | [Get Road Risk Data](https://openweathermap.org/api/road-risk) | Road Risk API provides weather data<br />and national alerts at the point of<br />destination and along a route | ``latitude``<br />``longitude``<br />``apikey``<br />``dt``| | | ## Known issues - Not all OpenWeatherMap APIs have been assigned with corresponding Robot Framework keywords. What you see is what you get - at least for this version. - The ``Get Road Risk Data`` keyword only supports a single set of ``latitude`` and ``longitude`` values (the underlying API supports multiple sets)
/robotframework-openweathermap-1.0.3.tar.gz/robotframework-openweathermap-1.0.3/README.md
0.927141
0.941493
README.md
pypi
import datetime import json def _decode_oid(decoder, oid): return decoder.memo[oid] def _decode_float(decoder, msg): return float(msg) def _decode_int(decoder, msg): return int(msg) def _decode_str(decoder, msg): return msg def _decode(message_definition, level_diff=0): names = [] name_to_decode = {} for s in message_definition.split(","): s = s.strip() i = s.find(":") decode = "oid" if i != -1: s, decode = s.split(":", 1) names.append(s) if decode == "oid": name_to_decode[s] = _decode_oid elif decode == "int": name_to_decode[s] = _decode_int elif decode == "float": name_to_decode[s] = _decode_float elif decode == "str": name_to_decode[s] = _decode_str else: raise RuntimeError(f"Unexpected: {decode}") def dec_impl(decoder, message): decoder.level += level_diff splitted = message.split("|", len(names) - 1) ret = {} for i, s in enumerate(splitted): name = names[i] try: ret[name] = name_to_decode[name](decoder, s) except: ret[name] = None return ret return dec_impl def decode_time(decoder, time): decoder.initial_time = datetime.datetime.fromisoformat(time) return {"initial_time": time} def decode_memo(decoder, message): memo_id, memo_value = message.split(":", 1) memo_value = json.loads(memo_value) decoder.memo[memo_id] = memo_value return None _MESSAGE_TYPE_INFO = { "V": lambda _decoder, message: {"version": message}, "I": lambda _decoder, message: {"info": json.loads(message)}, "ID": _decode("part:int, id:str"), "T": decode_time, "M": decode_memo, "L": _decode("level:str, message:oid, time_delta_in_seconds:float"), "LH": _decode("level:str, message:oid, time_delta_in_seconds:float"), "SS": _decode( "name:oid, suite_id:oid, suite_source:oid, time_delta_in_seconds:float", level_diff=+1, ), "ES": _decode("status:oid, time_delta_in_seconds:float", level_diff=-1), "ST": _decode( "name:oid, suite_id:oid, lineno:int, time_delta_in_seconds:float", level_diff=+1 ), "ET": _decode( "status:oid, message:oid, time_delta_in_seconds:float", level_diff=-1 ), "SK": _decode( "name:oid, libname:oid, keyword_type:oid, doc:oid, source:oid, lineno:int, time_delta_in_seconds:float", level_diff=+1, ), "EK": _decode("status:oid, time_delta_in_seconds:float", level_diff=-1), "KA": _decode("argument:oid"), "AS": _decode("assign:oid"), "TG": _decode("tag:oid"), "S": _decode("start_time_delta:float"), } _MESSAGE_TYPE_INFO["RS"] = _MESSAGE_TYPE_INFO["SS"] _MESSAGE_TYPE_INFO["RT"] = _MESSAGE_TYPE_INFO["ST"] _MESSAGE_TYPE_INFO["RK"] = _MESSAGE_TYPE_INFO["SK"] class Decoder: def __init__(self): self.memo = {} self.initial_time = None self.level = 0 @property def ident(self): return " " * self.level def decode_message_type(self, message_type, message): handler = _MESSAGE_TYPE_INFO[message_type] ret = {"message_type": message_type} try: r = handler(self, message) if not r: if message_type == "M": return None raise RuntimeError( f"No return when decoding: {message_type} - {message}" ) if not isinstance(r, dict): ret[ "error" ] = f"Expected dict return when decoding: {message_type} - {message}. Found: {ret}" ret.update(r) except Exception as e: ret["error"] = f"Error decoding: {message_type}: {e}" return ret def iter_decoded_log_format(stream): decoder = Decoder() for line in stream.readlines(): line = line.strip() if line: message_type, message = line.split(" ", 1) decoded = decoder.decode_message_type(message_type, message) if decoded: yield decoded
/robotframework-output-stream-0.0.6.tar.gz/robotframework-output-stream-0.0.6/robot_out_stream/_decoder.py
0.535584
0.285456
_decoder.py
pypi
from robot.api import logger from junitparser import Error, Failure, JUnitXml from junitparser.junitparser import TestSuite as JUnitXmlTestSuite from .base_handler import BaseHandler from .errors import JUnitHandlerException, SubprocessException from .utils import run_command_line, validate_path class JUnitHandler(BaseHandler): def run_junit(self, result_file, command, check_return_code=False, **env): '''Run JUnit unit testing tool specified with ``command``. See documentation for other arguments in \`Run Gatling\`. ''' logger.debug(f'Command: {command}') try: output = run_command_line(command, check_return_code, **env) except SubprocessException as e: raise JUnitHandlerException(e) logger.info(output) logger.info('Result file: {}'.format(result_file)) return result_file def parse_results(self, result_file): result_file = self._validate_path(result_file) try: xml = JUnitXml.fromfile(result_file) except TypeError as e: raise JUnitHandlerException(e) return self._transform_tests(xml) def _validate_path(self, result_file): try: return str(validate_path(result_file).resolve()) except TypeError as e: raise JUnitHandlerException(f'Invalid result file path: {e}') def _transform_tests(self, node): '''Convert the given xml object into a test suite dict node: An xml object from JUnitXml.fromfile() Return: The test suite dict ''' suite_dict = { 'name': 'JUnit Execution', 'tags': self._tags, 'setup': [], 'teardown': [], 'suites': [], 'tests': [], } if isinstance(node, JUnitXmlTestSuite): node = [node] for xunit_suite in node: suite = self._transform_test_suite(xunit_suite) suite_dict['suites'].append(suite) return suite_dict def _transform_test_suite(self, test_suite): '''Convert the given suite xml object into a suite dict test_suite: A JUnit suite xml object Return: A suite dict ''' suite_dict = { 'name': test_suite.name, 'tags': [], 'setup': [], 'teardown': [], 'suites': [], 'tests': [], } # For child suites for xunit_suite in test_suite.testsuites(): suite = self._transform_test_suite(xunit_suite) suite_dict['suites'].append(suite) # For test cases for xunit_case in test_suite: case = self._transform_test_case(xunit_case) suite_dict['tests'].append(case) return suite_dict def _transform_test_case(self, test_case): '''Convert the given test case xml object into a test case dict test_case: A JUnit case xml object Return: A test case dict ''' test_dict = { 'name': '{} (Execution)'.format(test_case.name), 'pass': True, 'tags': [], 'messages': [], 'teardown': [], 'keywords': [], } errors = test_case.iterchildren(Error) failures = test_case.iterchildren(Failure) if errors: for error in errors: error_name = 'ERROR: {} ({})'.format( error.message, error.type, ) test_dict['messages'].append(error_name) if failures: for failure in failures: failure_name = 'FAIL: {} ({})'.format( failure.message, failure.type, ) test_dict['messages'].append(failure_name) # If we had errors/failures, it's not a PASS if test_dict['messages']: test_dict['pass'] = False execution_time = (test_case.time or 0.0) * 1000 test_dict['elapsed'] = execution_time test_case_dict = { 'name': test_case.name, 'tags': [], 'setup': [], 'teardown': [], 'keywords': [ test_dict, ], } # This is really unreliable but at least we can find the trouble spots if not test_case.time: test_case_dict['tags'].append( 'oxygen-junit-unknown-execution-time') return test_case_dict
/robotframework_oxygen-0.2-py3-none-any.whl/oxygen/junit.py
0.710226
0.268925
junit.py
pypi
from argparse import ArgumentParser from datetime import datetime, timedelta from inspect import getdoc, signature from io import StringIO from pathlib import Path from traceback import format_exception from robot.api import ExecutionResult, ResultVisitor, ResultWriter from robot.libraries.BuiltIn import BuiltIn from robot.errors import DataError from yaml import load, FullLoader from .config import CONFIG_FILE from .errors import OxygenException from .robot_interface import RobotInterface from .version import VERSION class OxygenCore(object): '''OxygenCore collects shared faculties used by the actual classes that do something''' __version__ = VERSION def __init__(self): with open(CONFIG_FILE, 'r') as infile: self._config = load(infile, Loader=FullLoader) self._handlers = {} self._register_handlers() def _register_handlers(self): for tool_name, config in self._config.items(): handler_class = getattr(__import__(tool_name, fromlist=[config['handler']]), config['handler']) handler = handler_class(config) self._handlers[tool_name] = handler class OxygenVisitor(OxygenCore, ResultVisitor): '''OxygenVisitor goes over Robot Framework ExcutionResult object, transforming test cases that use keywords of OxygenLibrary to parsed test results from other tools. Read up on what is Robot Framework SuiteVisitor: http://robot-framework.readthedocs.io/en/latest/autodoc/robot.model.html#module-robot.model.visitor ''' def __init__(self, data): super().__init__() self.data = data def visit_test(self, test): failures = [] for handler_type, handler in self._handlers.items(): try: handler.check_for_keyword(test, self.data) except Exception as e: failures.append(e) if len(failures) == 1: raise failures.pop() if failures: tracebacks = [''.join(format_exception(e.__class__, e, e.__traceback__)) for e in failures] raise OxygenException('Multiple failures:\n{}'.format( '\n'.join(tracebacks))) class listener(object): '''listener passes data from test execution to where results are written. listener object is used during test execution to get dynamically data from OxygenLibrary keywords. After test execution is finished, listener will initiate OxygenVisitor, replacing test cases that used OxygenLibrary keywords with parsed test results from other test tools. In the end, the new output is written on the disk for rebot to take over and generate Robot Framework log and report normally ''' ROBOT_LISTENER_API_VERSION = 2 def __init__(self): self.run_time_data = {} def end_test(self, name, attributes): try: lib = BuiltIn()._get_context().namespace.get_library_instance( 'oxygen.OxygenLibrary') if lib: self.run_time_data[attributes['longname']] = lib.data except DataError as _: pass def output_file(self, path): result = ExecutionResult(path) result.visit(OxygenVisitor(self.run_time_data)) result.save() class OxygenLibrary(OxygenCore): '''Oxygen is a tool to consolidate different test tools' reports together as a single Robot Framework log and report. ``oxygen.OxygenLibrary`` enables you to write acceptance tests that run your other test tools, parse their results and include them into the Robot Framework reporting. In addition, you can use the `oxygen command line interface`_ to transform an existing test tool report to a single Robot Framework ``output.xml`` which you can combine together with other Robot Framework ``output.xml``'s with Robot Frameworks built-in tool rebot_. Acceptance tests that run other test tools might look something like this: .. code:: robotframework *** Test cases *** Java unit tests should pass Prepare environment platform=${PLATFORM} Run JUnit path/to/resuls.xml mvn clean test Java integration tests should pass [Tags] integration-tests Prepare environment platform=${PLATFORM} Run JUnit another/path/results.xml mvn clean integration-test Performance should not degrade ${gatling output folder}= Set variable path/to/simulations Run Gatling ${gatling output folder}/gatling.log ... %{GATLING_HOME}/bin/gatling.sh --results-folder ${gatling output folder} --simulation MyStressTest Application should not have security holes Run ZAP path/to/zap.json node my_zap_active_scan.js As you can see from the examples above, creating acceptance tests that run your other test tools is quite flexible. Tests can, in addition to keywords described in this documentation, have other Robot Framework keywords (like the imaginary user keyword ``Prepare environment`` in the examples above) that are normally executed before or after. These are also reported in the final Robot Framework reporting. You can also observe from the ``Java integration tests should pass`` example that tags in the test case will also be part of the final RF reporting — these tags will be added to each parsed test result from the other tool. This is a good way to add additional metadata like categorization of test cases for quality dashboards, if the test tool does not provide this themselves. Extending oxygen.OxygenLibrary ------------------------------ ``oxygen.OxygenLibrary`` is designed to be extensible with writing your own *handler* for Oxygen to use. It is expected that your *handler* also provides a keyword for running the test tool you want to provide integration for. Since ``oxygen.OxygenLibrary`` is a `dynamic library`_, it will also know how to run your *handler's* keyword. Keyword documentation should be provided as per `normal way one does with Robot Framework libraries`_. The documentation syntax is expected to be reStructuredText_. After editing Oxygen's ``config.yml`` to add your own handler, you can regenerate this library documentation to show your keyword with command: .. code:: bash $ python -m robot.libdoc OxygenLibrary MyOxygenLibrary.html .. _oxygen command line interface: http://github.com/eficode/robotframework-oxygen#using-from-command-line .. _rebot: http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#post-processing-outputs .. _dynamic library: http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#dynamic-library-api .. _normal way one does with Robot Framework libraries: http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#documenting-libraries .. _reStructuredText: https://docutils.sourceforge.io/docs/user/rst/quickref.html ''' ROBOT_LIBRARY_DOC_FORMAT = 'reST' def __init__(self): super().__init__() self.data = None def _fetch_handler(self, name): try: return next(filter(lambda h: h.keyword == name, self._handlers.values())) except StopIteration: raise OxygenException('No handler for keyword "{}"'.format(name)) def get_keyword_names(self): return list(handler.keyword for handler in self._handlers.values()) def run_keyword(self, name, args, kwargs): handler = self._fetch_handler(name) retval = getattr(handler, name)(*args, **kwargs) self.data = retval return retval def get_keyword_documentation(self, kw_name): if kw_name == '__intro__': return getdoc(self.__class__) return getdoc(getattr(self._fetch_handler(kw_name), kw_name)) def get_keyword_arguments(self, kw_name): method_sig = signature(getattr(self._fetch_handler(kw_name), kw_name)) return [str(param) for param in method_sig.parameters.values()] class OxygenCLI(OxygenCore): ''' OxygenCLI is a command line interface to transform one test result file to corresponding Robot Framework output.xml ''' def parse_args(self, parser): subcommands = parser.add_subparsers() for tool_name, tool_handler in self._handlers.items(): subcommand_parser = subcommands.add_parser(tool_name) for flags, params in tool_handler.cli().items(): subcommand_parser.add_argument(*flags, **params) subcommand_parser.set_defaults(func=tool_handler.parse_results) return vars(parser.parse_args()) # returns a dictionary def get_output_filename(self, result_file): filename = Path(result_file) filename = filename.with_suffix('.xml') robot_name = filename.stem + '_robot_output' + filename.suffix filename = filename.with_name(robot_name) return str(filename) def run(self): parser = ArgumentParser(prog='oxygen') parser.add_argument('--version', action='version', version=f'%(prog)s {self.__version__}') args = self.parse_args(parser) if not args: parser.error('No arguments given') output_filename = self.get_output_filename(args['result_file']) parsed_results = args['func']( **{k: v for (k, v) in args.items() if not callable(v)}) robot_suite = RobotInterface().running.build_suite(parsed_results) robot_suite.run(output=output_filename, log=None, report=None, stdout=StringIO()) if __name__ == '__main__': OxygenCLI().run()
/robotframework_oxygen-0.2-py3-none-any.whl/oxygen/oxygen.py
0.690663
0.18924
oxygen.py
pypi
from robot.api import logger from .base_handler import BaseHandler from .errors import GatlingHandlerException, SubprocessException from .utils import run_command_line, validate_path class GatlingHandler(BaseHandler): def run_gatling(self, result_file, command, check_return_code=False, **env): '''Run Gatling performance testing tool specified with ``command``. ``result_file`` is path to the file ``oxygen`` uses to parse the results. It is important you craft your `command` to produce the file `result_file` argument expects — otherwise Oxygen will not be able to parse the results later on. ``command`` is used to run the test tool. It is a single string which is run in a terminal subshell. ``check_return_code`` checks that ``command`` returns with exit code zero (0). By default, return code is not checked as failing test execution generally is reported with non-zero return code. However, it is useful to set ``check_return_code`` to ``True`` temporarily when you want to debug why the test tool is failing for other reasons than failing test execution. ``env`` is used to pass environment variables that are set in the subshell the ``command`` is run in. ''' try: output = run_command_line(command, check_return_code, **env) except SubprocessException as e: raise GatlingHandlerException(e) logger.info(output) logger.info('Result file: {}'.format(result_file)) return result_file def parse_results(self, result_file): return self._transform_tests(validate_path(result_file).resolve()) def _transform_tests(self, result_file): '''Given the result_file path, open the test results and get a suite dict. The whole Gatling format is jank 3000. Here be dragons. result_file: The path to the Gatling results ''' test_cases = [] with open(result_file) as results: result_contents = results.readlines() for line in result_contents: columns = line.strip().split('\t') if len(columns) < 8: continue step_name = columns[4] status = columns[7] if status not in ['OK', 'KO']: continue message = '' if len(columns) > 8: message = columns[8] keyword = { 'name': ' | '.join(columns), 'pass': True, 'tags': [], 'messages': [], 'teardown': [], 'keywords': [], } if status == 'KO': keyword['pass'] = False keyword['messages'].append(message) test_case = { 'name': step_name, 'tags': [], 'setup': [], 'teardown': [], 'keywords': [keyword] } test_cases.append(test_case) test_suite = { 'name': 'Gatling Scenario', 'tags': self._tags, 'setup': [], 'teardown': [], 'suites': [], 'tests': test_cases, } return test_suite
/robotframework_oxygen-0.2-py3-none-any.whl/oxygen/gatling.py
0.729616
0.382141
gatling.py
pypi
from datetime import datetime from datetime import timedelta from datetime import timezone from robot.result.model import (Keyword as RobotResultKeyword, TestCase as RobotResultTest, TestSuite as RobotResultSuite) from robot.model import BodyItem from robot.running.model import TestSuite as RobotRunningSuite class RobotResultInterface(object): def build_suites(self, starting_time, *suites): '''Convert a given `suite` dictionaries into a Robot suite''' finished_suites = [] current_time = starting_time for suite in suites: current_time, finished_suite = self.build_suite(current_time, suite) if finished_suite: finished_suites.append(finished_suite) return current_time, finished_suites def build_suite(self, starting_time, suite): '''Convert a set of suite dicts into Robot suites and append them to the given list-like object target: List-like object to add the Robot suites to suites: Set of suite dicts to build into Robot suites Return: The updated list-like object ''' if not suite: return starting_time, None updated_time = starting_time name = suite.get('name') or 'Unknown Suite Name' tags = suite.get('tags') or [] setup_keyword = suite.get('setup') or None teardown_keyword = suite.get('teardown') or None child_suites = suite.get('suites') or [] tests = suite.get('tests') or [] updated_time, robot_setup = self.build_keyword(updated_time, setup_keyword, setup=True) updated_time, robot_teardown = self.build_keyword(updated_time, teardown_keyword, teardown=True) updated_time, robot_suites = self.build_suites(updated_time, *child_suites) updated_time, robot_tests = self.build_tests(updated_time, *tests) robot_suite = self.spawn_robot_suite(name, starting_time, updated_time, tags, robot_setup, robot_teardown, robot_suites, robot_tests) return updated_time, robot_suite def spawn_robot_suite(self, name, start_time, end_time, tags, setup_keyword, teardown_keyword, suites, tests): start_timestamp = self.ms_to_timestamp(start_time) end_timestamp = self.ms_to_timestamp(end_time) robot_suite = RobotResultSuite(name, starttime=start_timestamp, endtime=end_timestamp) robot_suite.set_tags(add=tags, persist=True) if setup_keyword: robot_suite.setup = setup_keyword if teardown_keyword: robot_suite.teardown = teardown_keyword for suite in filter(None, suites): robot_suite.suites.append(suite) for test in filter(None, tests): robot_suite.tests.append(test) return robot_suite def build_tests(self, starting_time, *tests): '''Convert a set of `tests` dicts and add to a Robot suite `target`''' updated_time = starting_time robot_tests = [] for test in tests: updated_time, robot_test = self.build_test(updated_time, test) if robot_test: robot_tests.append(robot_test) return updated_time, robot_tests def build_test(self, starting_time, test): '''Convert a set of `tests` dicts and add to a Robot suite `target`''' if not test: return starting_time, None updated_time = starting_time test_name = test.get('name') or 'Unknown Test Name' tags = test.get('tags') or [] setup_keyword = test.get('setup') or None keywords = test.get('keywords') or [] teardown_keyword = test.get('teardown') or None updated_time, robot_setup = self.build_keyword(updated_time, setup_keyword, setup=True) updated_time, robot_keywords = self.build_keywords(updated_time, *keywords) updated_time, robot_teardown = self.build_keyword(updated_time, teardown_keyword, teardown=True) robot_test = self.spawn_robot_test(test_name, starting_time, updated_time, tags, robot_setup, robot_teardown, robot_keywords) return updated_time, robot_test def spawn_robot_test(self, name, start_time, end_time, tags, setup_keyword, teardown_keyword, keywords): start_timestamp = self.ms_to_timestamp(start_time) end_timestamp = self.ms_to_timestamp(end_time) status = self.get_keywords_status(setup_keyword, teardown_keyword, *(keywords or [])) robot_test = RobotResultTest(name, tags=tags, status=status, starttime=start_timestamp, endtime=end_timestamp) if setup_keyword: robot_test.setup = setup_keyword for keyword in keywords: if keyword: robot_test.body.append(keyword) if teardown_keyword: robot_test.teardown = teardown_keyword return robot_test def build_keywords(self, starting_time, *keywords): '''Convert `keywords` dicts, add them as sub-keywords to a `target`''' updated_time = starting_time robot_keywords = [] for keyword in keywords: updated_time, robot_keyword = self.build_keyword(updated_time, keyword) if robot_keyword: robot_keywords.append(robot_keyword) return updated_time, robot_keywords def build_keyword(self, starting_time, keyword, setup=False, teardown=False): if not keyword: return starting_time, None updated_time = starting_time name = keyword.get('name') or 'Unknown Keyword Name' status = keyword.get('pass') or None elapsed = keyword.get('elapsed') or 0.0 tags = keyword.get('tags') or [] messages = keyword.get('messages') or [] teardown = keyword.get('teardown') or None keywords = keyword.get('keywords') or [] updated_time, robot_teardown = self.build_keyword(updated_time, teardown) updated_time, robot_keywords = self.build_keywords(updated_time, keywords) final_time = updated_time + elapsed robot_keyword = self.spawn_robot_keyword(name, tags, status, updated_time, final_time, teardown, keywords, messages, setup, teardown) return final_time, robot_keyword def spawn_robot_keyword(self, name, tags, status, start_time, end_time, teardown_keyword, keywords, messages, setup=False, teardown=False): start_timestamp = self.ms_to_timestamp(start_time) end_timestamp = self.ms_to_timestamp(end_time) if setup: keyword_type = BodyItem.SETUP elif teardown: keyword_type = BodyItem.TEARDOWN else: keyword_type = BodyItem.KEYWORD if status is None: keyword_status = 'NOT RUN' elif status: keyword_status = 'PASS' else: keyword_status = 'FAIL' robot_keyword = RobotResultKeyword(name, tags=tags, status=keyword_status, starttime=start_timestamp, endtime=end_timestamp) robot_keyword.type = keyword_type for keyword in keywords: if keyword: robot_keyword.body.append(keyword) if teardown_keyword: robot_keyword.teardown = teardown_keyword for message in messages: if message: ishtml = message.startswith('*HTML*') if ishtml: message = message[6:] robot_keyword.body.create_message(message, html=ishtml) return robot_keyword def get_time_format(self): '''Convenience to return the general Robot timestamp format.''' return '%Y%m%d %H:%M:%S.%f' def timestamp_to_ms(self, timestamp): time_format = self.get_time_format() time_object = datetime.strptime( timestamp, time_format, ) tz_delta = self.get_timezone_delta() milliseconds = ((time_object + tz_delta).timestamp() * 1000) return milliseconds def ms_to_timestamp(self, milliseconds): tz_delta = self.get_timezone_delta() time_object = datetime.fromtimestamp(int(milliseconds / 1000)) - tz_delta milliseconds_delta = timedelta(milliseconds=(milliseconds % 1000)) time_object = (time_object + milliseconds_delta) time_format = self.get_time_format() return time_object.strftime(time_format) def get_timezone_delta(self): local_zone = datetime.now(timezone.utc).astimezone().tzinfo return local_zone.utcoffset(None) def get_keywords_status(self, *keywords): ''' keywords: List of Robot keywords Return: 'PASS' or 'FAIL' ''' if sum(not kw.passed for kw in filter(None, keywords)): return 'FAIL' else: return 'PASS' def create_wrapper_keyword(self, name, start_timestamp, end_timestamp, setup, *keywords): status = self.get_keywords_status(*keywords) start_time = self.timestamp_to_ms(start_timestamp) end_time = self.timestamp_to_ms(end_timestamp) robot_keyword = self.spawn_robot_keyword(name, [], status, start_time, end_time, None, keywords, [], setup, (not setup)) return robot_keyword class RobotRunningInterface(object): def build_suite(self, parsed_results): robot_root_suite = RobotRunningSuite(parsed_results['name']) for parsed_suite in parsed_results['suites']: robot_suite = robot_root_suite.suites.create(parsed_suite['name']) for subsuite in parsed_suite.get('suites', []): robot_subsuite = self.build_suite(subsuite) robot_suite.suites.append(robot_subsuite) self.build_tests(parsed_suite, robot_suite) self.build_tests(parsed_results, robot_root_suite) return robot_root_suite def build_tests(self, oxygen_suite, robot_suite): for parsed_test in oxygen_suite.get('tests', []): name = parsed_test['name'] tags = parsed_test['tags'] kw = parsed_test['keywords'][0] msg = '\n'.join(kw['messages']) test_robot_counterpart = robot_suite.tests.create(name, tags=tags) if kw['pass']: args = [msg if msg else 'Test passed :D'] test_robot_counterpart.body.create_keyword('Pass execution', args=args) else: args = [msg if msg else 'Test failed D:'] test_robot_counterpart.body.create_keyword('Fail', args=args)
/robotframework_oxygen-0.2-py3-none-any.whl/oxygen/robot4_interface.py
0.707203
0.340047
robot4_interface.py
pypi
from datetime import datetime from datetime import timedelta from datetime import timezone from robot.result.model import (Keyword as RobotResultKeyword, Message as RobotResultMessage, TestCase as RobotResultTest, TestSuite as RobotResultSuite) from robot.running.model import TestSuite as RobotRunningSuite class RobotResultInterface(object): def build_suites(self, starting_time, *suites): '''Convert a given `suite` dictionaries into a Robot suite''' finished_suites = [] current_time = starting_time for suite in suites: current_time, finished_suite = self.build_suite(current_time, suite) if finished_suite: finished_suites.append(finished_suite) return current_time, finished_suites def build_suite(self, starting_time, suite): '''Convert a set of suite dicts into Robot suites and append them to the given list-like object target: List-like object to add the Robot suites to suites: Set of suite dicts to build into Robot suites Return: The updated list-like object ''' if not suite: return starting_time, None updated_time = starting_time name = suite.get('name') or 'Unknown Suite Name' tags = suite.get('tags') or [] setup_keyword = suite.get('setup') or None teardown_keyword = suite.get('teardown') or None child_suites = suite.get('suites') or [] tests = suite.get('tests') or [] updated_time, robot_setup = self.build_keyword(updated_time, setup_keyword, setup=True) updated_time, robot_teardown = self.build_keyword(updated_time, teardown_keyword, teardown=True) updated_time, robot_suites = self.build_suites(updated_time, *child_suites) updated_time, robot_tests = self.build_tests(updated_time, *tests) robot_suite = self.spawn_robot_suite(name, starting_time, updated_time, tags, robot_setup, robot_teardown, robot_suites, robot_tests) return updated_time, robot_suite def spawn_robot_suite(self, name, start_time, end_time, tags, setup_keyword, teardown_keyword, suites, tests): start_timestamp = self.ms_to_timestamp(start_time) end_timestamp = self.ms_to_timestamp(end_time) robot_suite = RobotResultSuite(name, starttime=start_timestamp, endtime=end_timestamp) robot_suite.set_tags(add=tags, persist=True) if setup_keyword: robot_suite.keywords.append(setup_keyword) if teardown_keyword: robot_suite.keywords.append(teardown_keyword) for suite in filter(None, suites): robot_suite.suites.append(suite) for test in filter(None, tests): robot_suite.tests.append(test) return robot_suite def build_tests(self, starting_time, *tests): '''Convert a set of `tests` dicts and add to a Robot suite `target`''' updated_time = starting_time robot_tests = [] for test in tests: updated_time, robot_test = self.build_test(updated_time, test) if robot_test: robot_tests.append(robot_test) return updated_time, robot_tests def build_test(self, starting_time, test): '''Convert a set of `tests` dicts and add to a Robot suite `target`''' if not test: return starting_time, None updated_time = starting_time test_name = test.get('name') or 'Unknown Test Name' tags = test.get('tags') or [] setup_keyword = test.get('setup') or None keywords = test.get('keywords') or [] teardown_keyword = test.get('teardown') or None updated_time, robot_setup = self.build_keyword(updated_time, setup_keyword, setup=True) updated_time, robot_keywords = self.build_keywords(updated_time, *keywords) updated_time, robot_teardown = self.build_keyword(updated_time, teardown_keyword, teardown=True) robot_test = self.spawn_robot_test(test_name, starting_time, updated_time, tags, robot_setup, robot_teardown, robot_keywords) return updated_time, robot_test def spawn_robot_test(self, name, start_time, end_time, tags, setup_keyword, teardown_keyword, keywords): start_timestamp = self.ms_to_timestamp(start_time) end_timestamp = self.ms_to_timestamp(end_time) status = self.get_keywords_status(setup_keyword, teardown_keyword, *(keywords or [])) robot_test = RobotResultTest(name, tags=tags, status=status, starttime=start_timestamp, endtime=end_timestamp) if setup_keyword: robot_test.keywords.append(setup_keyword) for keyword in keywords: if keyword: robot_test.keywords.append(keyword) if teardown_keyword: robot_test.keywords.append(teardown_keyword) return robot_test def build_keywords(self, starting_time, *keywords): '''Convert `keywords` dicts, add them as sub-keywords to a `target`''' updated_time = starting_time robot_keywords = [] for keyword in keywords: updated_time, robot_keyword = self.build_keyword(updated_time, keyword) if robot_keyword: robot_keywords.append(robot_keyword) return updated_time, robot_keywords def build_keyword(self, starting_time, keyword, setup=False, teardown=False): if not keyword: return starting_time, None updated_time = starting_time name = keyword.get('name') or 'Unknown Keyword Name' status = keyword.get('pass') or None elapsed = keyword.get('elapsed') or 0.0 tags = keyword.get('tags') or [] messages = keyword.get('messages') or [] teardown = keyword.get('teardown') or None keywords = keyword.get('keywords') or [] updated_time, robot_teardown = self.build_keyword(updated_time, teardown) updated_time, robot_keywords = self.build_keywords(updated_time, keywords) final_time = updated_time + elapsed robot_keyword = self.spawn_robot_keyword(name, tags, status, updated_time, final_time, teardown, keywords, messages, setup, teardown) return final_time, robot_keyword def spawn_robot_keyword(self, name, tags, status, start_time, end_time, teardown_keyword, keywords, messages, setup=False, teardown=False): start_timestamp = self.ms_to_timestamp(start_time) end_timestamp = self.ms_to_timestamp(end_time) if setup: keyword_type = RobotResultKeyword.SETUP_TYPE elif teardown: keyword_type = RobotResultKeyword.TEARDOWN_TYPE else: keyword_type = RobotResultKeyword.KEYWORD_TYPE if status is None: keyword_status = 'NOT_RUN' elif status: keyword_status = 'PASS' else: keyword_status = 'FAIL' robot_keyword = RobotResultKeyword(name, tags=tags, status=keyword_status, starttime=start_timestamp, endtime=end_timestamp) robot_keyword.type = keyword_type for keyword in keywords: if keyword: robot_keyword.keywords.append(keyword) if teardown_keyword: robot_keyword.keywords.append(teardown_keyword) for message in messages: if message: ishtml = message.startswith('*HTML*') if ishtml: message = message[6:] robot_keyword.messages.append(RobotResultMessage(message,html=ishtml)) return robot_keyword def get_time_format(self): '''Convenience to return the general Robot timestamp format.''' return '%Y%m%d %H:%M:%S.%f' def timestamp_to_ms(self, timestamp): time_format = self.get_time_format() time_object = datetime.strptime( timestamp, time_format, ) tz_delta = self.get_timezone_delta() milliseconds = ((time_object + tz_delta).timestamp() * 1000) return milliseconds def ms_to_timestamp(self, milliseconds): tz_delta = self.get_timezone_delta() time_object = datetime.fromtimestamp(int(milliseconds / 1000)) - tz_delta milliseconds_delta = timedelta(milliseconds=(milliseconds % 1000)) time_object = (time_object + milliseconds_delta) time_format = self.get_time_format() return time_object.strftime(time_format) def get_timezone_delta(self): local_zone = datetime.now(timezone.utc).astimezone().tzinfo return local_zone.utcoffset(None) def get_keywords_status(self, *keywords): ''' keywords: List of Robot keywords Return: 'PASS' or 'FAIL' ''' if sum(not kw.passed for kw in filter(None, keywords)): return 'FAIL' else: return 'PASS' def create_wrapper_keyword(self, name, start_timestamp, end_timestamp, setup, *keywords): status = self.get_keywords_status(*keywords) start_time = self.timestamp_to_ms(start_timestamp) end_time = self.timestamp_to_ms(end_timestamp) robot_keyword = self.spawn_robot_keyword(name, [], status, start_time, end_time, None, keywords, [], setup, (not setup)) return robot_keyword class RobotRunningInterface(object): def build_suite(self, parsed_results): robot_root_suite = RobotRunningSuite(parsed_results['name']) for parsed_suite in parsed_results['suites']: robot_suite = robot_root_suite.suites.create(parsed_suite['name']) for subsuite in parsed_suite.get('suites', []): robot_subsuite = self.build_suite(subsuite) robot_suite.suites.append(robot_subsuite) self.build_tests(parsed_suite, robot_suite) self.build_tests(parsed_results, robot_root_suite) return robot_root_suite def build_tests(self, oxygen_suite, robot_suite): for parsed_test in oxygen_suite.get('tests', []): name = parsed_test['name'] tags = parsed_test['tags'] kw = parsed_test['keywords'][0] msg = '\n'.join(kw['messages']) test_robot_counterpart = robot_suite.tests.create(name, tags=tags) if kw['pass']: args = [msg if msg else 'Test passed :D'] test_robot_counterpart.keywords.create('Pass execution', args=args) else: args = [msg if msg else 'Test failed D:'] test_robot_counterpart.keywords.create('Fail', args=args)
/robotframework_oxygen-0.2-py3-none-any.whl/oxygen/robot3_interface.py
0.702734
0.302327
robot3_interface.py
pypi
# Pabot [Русская версия](README_ru.md) [中文版](README_zh.md) [![Version](https://img.shields.io/pypi/v/robotframework-pabot.svg)](https://pypi.python.org/pypi/robotframework-pabot) [![Downloads](http://pepy.tech/badge/robotframework-pabot)](http://pepy.tech/project/robotframework-pabot) <img src="https://raw.githubusercontent.com/mkorpela/pabot/master/pabot.png" width="100"> ---- A parallel executor for [Robot Framework](http://www.robotframework.org) tests. With Pabot you can split one execution into multiple and save test execution time. [![Pabot presentation at robocon.io 2018](http://img.youtube.com/vi/i0RV6SJSIn8/0.jpg)](https://youtu.be/i0RV6SJSIn8 "Pabot presentation at robocon.io 2018") ## Installation: From PyPi: pip install -U robotframework-pabot OR clone this repository and run: setup.py install ## Basic use Split execution to suite files. pabot [path to tests] Split execution on test level. pabot --testlevelsplit [path to tests] Run same tests with two different configurations. pabot --argumentfile1 first.args --argumentfile2 second.args [path to tests] For more complex cases please read onward. ## Contact Join [Pabot Slack channel](https://robotframework.slack.com/messages/C7HKR2L6L) in Robot Framework slack. [Get invite to Robot Framework slack](https://robotframework-slack-invite.herokuapp.com/). ## Contributing to the project There are several ways you can help in improving this tool: - Report an issue or an improvement idea to the [issue tracker](https://github.com/mkorpela/pabot/issues) - Contribute by programming and making a pull request (easiest way is to work on an issue from the issue tracker) ## Command-line options pabot [--verbose|--testlevelsplit|--command .. --end-command| --processes num|--pabotlib|--pabotlibhost host|--pabotlibport port| --processtimeout num| --shard i/n| --artifacts extensions|--artifactsinsubfolders| --resourcefile file|--argumentfile[num] file|--suitesfrom file] [robot options] [path ...] Supports all [Robot Framework command line options](https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#all-command-line-options) and also following options (these must be before RF options): --verbose more output from the parallel execution --testlevelsplit Split execution on test level instead of default suite level. If .pabotsuitenames contains both tests and suites then this will only affect new suites and split only them. Leaving this flag out when both suites and tests in .pabotsuitenames file will also only affect new suites and add them as suite files. --command [ACTUAL COMMANDS TO START ROBOT EXECUTOR] --end-command RF script for situations where robot is not used directly --processes [NUMBER OF PROCESSES] How many parallel executors to use (default max of 2 and cpu count). Special option "all" will use as many processes as there are executable suites or tests. --pabotlib Start PabotLib remote server. This enables locking and resource distribution between parallel test executions. --pabotlibhost [HOSTNAME] Host name of the PabotLib remote server (default is 127.0.0.1) If used with --pabotlib option, will change the host listen address of the created remote server (see https://github.com/robotframework/PythonRemoteServer) If used without the --pabotlib option, will connect to already running instance of the PabotLib remote server in the given host. The remote server can be also started and executed separately from pabot instances: python -m pabot.pabotlib <path_to_resourcefile> <host> <port> python -m pabot.pabotlib resource.txt 192.168.1.123 8271 This enables sharing a resource with multiple Robot Framework instances. --pabotlibport [PORT] Port number of the PabotLib remote server (default is 8270) See --pabotlibhost for more information --processtimeout [TIMEOUT] Maximum time in seconds to wait for a process before killing it. If not set, there's no timeout. --resourcefile [FILEPATH] Indicator for a file that can contain shared variables for distributing resources. This needs to be used together with pabotlib option. Resource file syntax is same as Windows ini files. Where a section is a shared set of variables. --artifacts [FILE EXTENSIONS] List of file extensions (comma separated). Defines which files (screenshots, videos etc.) from separate reporting directories would be copied and included in a final report. Possible links to copied files in RF log would be updated (only relative paths supported). The default value is `png`. Examples: --artifacts png,mp4,txt --artifactsinsubfolders Copy artifacts located not only directly in the RF output dir, but also in it's sub-folders. --argumentfile[INTEGER] [FILEPATH] Run same suites with multiple [argumentfile](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#argument-files) options. For example: --argumentfile1 arg1.txt --argumentfile2 arg2.txt --suitesfrom [FILEPATH TO OUTPUTXML] Optionally read suites from output.xml file. Failed suites will run first and longer running ones will be executed before shorter ones. --shard [INDEX]/[TOTAL] Optionally split execution into smaller pieces. This can be used for distributing testing to multiple machines. --chunk Optionally chunk tests to PROCESSES number of robot runs. This can save time because all the suites will share the same setups and teardowns. Example usages: pabot test_directory pabot --exclude FOO directory_to_tests pabot --command java -jar robotframework.jar --end-command --include SMOKE tests pabot --processes 10 tests pabot --pabotlibhost 192.168.1.123 --pabotlibport 8271 --processes 10 tests pabot --pabotlib --pabotlibhost 192.168.1.111 --pabotlibport 8272 --processes 10 tests pabot --artifacts png,mp4,txt --artifactsinsubfolders directory_to_tests ### PabotLib pabot.PabotLib provides keywords that will help communication and data sharing between the executor processes. These can be helpful when you must ensure that only one of the processes uses some piece of data or operates on some part of the system under test at a time. PabotLib Docs are located at https://pabot.org/PabotLib.html. ### PabotLib example: test.robot *** Settings *** Library pabot.PabotLib *** Test Case *** Testing PabotLib Acquire Lock MyLock Log This part is critical section Release Lock MyLock ${valuesetname}= Acquire Value Set admin-server ${host}= Get Value From Set host ${username}= Get Value From Set username ${password}= Get Value From Set password Log Do something with the values (for example access host with username and password) Release Value Set Log After value set release others can obtain the variable values valueset.dat [Server1] tags=admin-server HOST=123.123.123.123 USERNAME=user1 PASSWORD=password1 [Server2] tags=server HOST=121.121.121.121 USERNAME=user2 PASSWORD=password2 [Server3] tags=admin-server HOST=222.222.222.222 USERNAME=user3 PASSWORD=password4 pabot call using resources from valueset.dat pabot --pabotlib --resourcefile valueset.dat test.robot ### Controlling execution order and level of parallelism .pabotsuitenames file contains the list of suites that will be executed. File is created during pabot execution if not already there. The file is a cache that pabot uses when re-executing same tests to speed up processing. This file can be partially manually edited but easier option is to use ```--ordering FILENAME```. First 4 rows contain information that should not be edited - pabot will edit these when something changes. After this come the suite names. With ```--ordering FILENAME``` you can have a list that controls order also. The syntax is same as .pabotsuitenames file syntax but does not contain 4 hash rows that are present in .pabotsuitenames. There different possibilities to influence the execution: * The order of suites can be changed. * If a directory (or a directory structure) should be executed sequentially, add the directory suite name to a row as a ```--suite``` option. * If the base suite name is changing with robot option [```--name / -N```](https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#setting-the-name) you can also give partial suite name without the base suite. * You can add a line with text `#WAIT` to force executor to wait until all previous suites have been executed. * You can group suites and tests together to same executor process by adding line `{` before the group and `}`after. * You can introduce dependencies using the word `#DEPENDS` after a test declaration. Please take care that in case of circular dependencies an exception will be thrown. An example could be. ``` --test robotTest.1 Scalar.Test With Environment Variables #DEPENDS robotTest.1 Scalar.Test with BuiltIn Variables of Robot Framework --test robotTest.1 Scalar.Test with BuiltIn Variables of Robot Framework --test robotTest.2 Lists.Test with Keywords and a list #WAIT --test robotTest.2 Lists.Test with a Keyword that accepts multiple arguments --test robotTest.2 Lists.Test with some Collections keywords --test robotTest.2 Lists.Test to access list entries --test robotTest.3 Dictionary.Test that accesses Dictionaries --test robotTest.3 Dictionary.Dictionaries for named arguments #DEPENDS robotTest.3 Dictionary.Test that accesses Dictionaries --test robotTest.1 Scalar.Test Case With Variables #DEPENDS robotTest.3 Dictionary.Test that accesses Dictionaries --test robotTest.1 Scalar.Test with Numbers #DEPENDS robotTest.1 Scalar.Test With Arguments and Return Values --test robotTest.1 Scalar.Test Case with Return Values #DEPENDS robotTest.1 Scalar.Test with Numbers --test robotTest.1 Scalar.Test With Arguments and Return Values --test robotTest.3 Dictionary.Test with Dictionaries as Arguments --test robotTest.3 Dictionary.Test with FOR loops and Dictionaries #DEPENDS robotTest.1 Scalar.Test Case with Return Values ``` ### Programmatic use Library offers an endpoint `main_program` that will not call `sys.exit`. This can help in developing your own python program around pabot. ```Python import sys from pabot.pabot import main_program def amazing_new_program(): print("Before calling pabot") exit_code = main_program(['tests']) print(f"After calling pabot (return code {exit_code})") sys.exit(exit_code) ``` ### Global variables Pabot will insert following global variables to Robot Framework namespace. These are here to enable PabotLib functionality and for custom listeners etc. to get some information on the overall execution of pabot. PABOTQUEUEINDEX - this contains a unique index number for the execution. Indexes start from 0. PABOTLIBURI - this contains the URI for the running PabotLib server PABOTEXECUTIONPOOLID - this contains the pool id (an integer) for the current Robot Framework executor. This is helpful for example when visualizing the execution flow from your own listener. PABOTNUMBEROFPROCESSES - max number of concurrent processes that pabot may use in execution. CALLER_ID - a universally unique identifier for this execution.
/robotframework-pabot-2.16.0.tar.gz/robotframework-pabot-2.16.0/README.md
0.444565
0.669785
README.md
pypi
import multiprocessing import re from typing import Dict, List, Optional, Tuple from robot import __version__ as ROBOT_VERSION from robot.errors import DataError from robot.run import USAGE from robot.utils import ArgumentParser from .execution_items import ( DynamicTestItem, ExecutionItem, GroupEndItem, GroupStartItem, IncludeItem, SuiteItem, TestItem, WaitItem, ) ARGSMATCHER = re.compile(r"--argumentfile(\d+)") def _processes_count(): # type: () -> int try: return max(multiprocessing.cpu_count(), 2) except NotImplementedError: return 2 def parse_args( args, ): # type: (List[str]) -> Tuple[Dict[str, object], List[str], Dict[str, object], Dict[str, object]] args, pabot_args = _parse_pabot_args(args) options, datasources = ArgumentParser( USAGE, auto_pythonpath=False, auto_argumentfile=True, env_options="ROBOT_OPTIONS", ).parse_args(args) options_for_subprocesses, sources_without_argfile = ArgumentParser( USAGE, auto_pythonpath=False, auto_argumentfile=False, env_options="ROBOT_OPTIONS", ).parse_args(args) if len(datasources) != len(sources_without_argfile): raise DataError( "Pabot does not support datasources in argumentfiles.\nPlease move datasources to commandline." ) if len(datasources) > 1 and options["name"] is None: options["name"] = "Suites" options_for_subprocesses["name"] = "Suites" opts = _delete_none_keys(options) opts_sub = _delete_none_keys(options_for_subprocesses) return opts, datasources, pabot_args, opts_sub def _parse_shard(arg): # type: (str) -> Tuple[int, int] parts = arg.split("/") return int(parts[0]), int(parts[1]) def _parse_pabot_args(args): # type: (List[str]) -> Tuple[List[str], Dict[str, object]] pabot_args = { "command": ["pybot" if ROBOT_VERSION < "3.1" else "robot"], "verbose": False, "help": False, "testlevelsplit": False, "pabotlib": False, "pabotlibhost": "127.0.0.1", "pabotlibport": 8270, "processes": _processes_count(), "processtimeout": None, "artifacts": ["png"], "artifactsinsubfolders": False, "shardindex": 0, "shardcount": 1, "chunk": False, } argumentfiles = [] while args and ( args[0] in [ "--" + param for param in [ "hive", "command", "processes", "verbose", "resourcefile", "testlevelsplit", "pabotlib", "pabotlibhost", "pabotlibport", "processtimeout", "ordering", "suitesfrom", "artifacts", "artifactsinsubfolders", "help", "shard", "chunk", ] ] or ARGSMATCHER.match(args[0]) ): if args[0] == "--hive": pabot_args["hive"] = args[1] args = args[2:] continue if args[0] == "--command": end_index = args.index("--end-command") pabot_args["command"] = args[1:end_index] args = args[end_index + 1 :] continue if args[0] == "--processes": pabot_args["processes"] = int(args[1]) if args[1] != 'all' else None args = args[2:] continue if args[0] == "--verbose": pabot_args["verbose"] = True args = args[1:] continue if args[0] == "--chunk": pabot_args["chunk"] = True args = args[1:] continue if args[0] == "--resourcefile": pabot_args["resourcefile"] = args[1] args = args[2:] continue if args[0] == "--pabotlib": pabot_args["pabotlib"] = True args = args[1:] continue if args[0] == "--ordering": pabot_args["ordering"] = _parse_ordering(args[1]) args = args[2:] continue if args[0] == "--testlevelsplit": pabot_args["testlevelsplit"] = True args = args[1:] continue if args[0] == "--pabotlibhost": pabot_args["pabotlibhost"] = args[1] args = args[2:] continue if args[0] == "--pabotlibport": pabot_args["pabotlibport"] = int(args[1]) args = args[2:] continue if args[0] == "--processtimeout": pabot_args["processtimeout"] = int(args[1]) args = args[2:] continue if args[0] == "--suitesfrom": pabot_args["suitesfrom"] = args[1] args = args[2:] continue if args[0] == "--artifacts": pabot_args["artifacts"] = args[1].split(",") args = args[2:] continue if args[0] == "--artifactsinsubfolders": pabot_args["artifactsinsubfolders"] = True args = args[1:] continue if args[0] == "--shard": pabot_args["shardindex"], pabot_args["shardcount"] = _parse_shard(args[1]) args = args[2:] continue match = ARGSMATCHER.match(args[0]) if match: argumentfiles += [(match.group(1), args[1])] args = args[2:] continue if args and args[0] == "--help": pabot_args["help"] = True args = args[1:] pabot_args["argumentfiles"] = argumentfiles return args, pabot_args def _parse_ordering(filename): # type: (str) -> List[ExecutionItem] try: with open(filename, "r") as orderingfile: return [ parse_execution_item_line(line.strip()) for line in orderingfile.readlines() ] except: raise DataError("Error parsing ordering file '%s'" % filename) def _delete_none_keys(d): # type: (Dict[str, Optional[object]]) -> Dict[str, object] keys = set() for k in d: if d[k] is None: keys.add(k) for k in keys: del d[k] return d def parse_execution_item_line(text): # type: (str) -> ExecutionItem if text.startswith("--suite "): return SuiteItem(text[8:]) if text.startswith("--test "): return TestItem(text[7:]) if text.startswith("--include "): return IncludeItem(text[10:]) if text.startswith("DYNAMICTEST"): suite, test = text[12:].split(" :: ") return DynamicTestItem(test, suite) if text == "#WAIT": return WaitItem() if text == "{": return GroupStartItem() if text == "}": return GroupEndItem() # Assume old suite name return SuiteItem(text)
/robotframework-pabot-2.16.0.tar.gz/robotframework-pabot-2.16.0/src/pabot/arguments.py
0.453262
0.228071
arguments.py
pypi
from __future__ import absolute_import, print_function import os import re from robot import __version__ as ROBOT_VERSION from robot.api import ExecutionResult from robot.conf import RobotSettings from robot.errors import DataError from robot.result.executionresult import CombinedResult try: from robot.result import TestSuite except ImportError: from robot.result.testsuite import TestSuite from robot.model import SuiteVisitor class ResultMerger(SuiteVisitor): def __init__(self, result, tests_root_name, out_dir, copied_artifacts): self.root = result.suite self.errors = result.errors self.current = None self._skip_until = None self._tests_root_name = tests_root_name self._prefix = "" self._out_dir = out_dir self._patterns = [] regexp_template = ( r'(src|href)="(.*?[\\\/]+)?({})"' # https://regex101.com/r/sBwbgN/5 ) for artifact in copied_artifacts: pattern = regexp_template.format(re.escape(artifact)) self._patterns.append(re.compile(pattern)) def merge(self, merged): try: self._set_prefix(merged.source) merged.suite.visit(self) self.root.metadata.update(merged.suite.metadata) if self.errors != merged.errors: self.errors.add(merged.errors) except: print("Error while merging result %s" % merged.source) raise def _set_prefix(self, source): self._prefix = prefix(source) def start_suite(self, suite): if self._skip_until and self._skip_until != suite: return if not self.current: self.current = self._find_root(suite) assert self.current if self.current is not suite: self._append_keywords(suite) else: next = self._find(self.current.suites, suite) if next is None: self.current.suites.append(suite) suite.parent = self.current self._skip_until = suite else: self.current = next if self.current is not suite: self._append_keywords(suite) if ROBOT_VERSION < "4.0" or ROBOT_VERSION == "4.0b1": def _append_keywords(self, suite): for keyword in suite.keywords: self.current.keywords.append(keyword) else: def _append_keywords(self, suite): for keyword in suite.setup.body: self.current.setup.body.append(keyword) for keyword in suite.teardown.body: self.current.teardown.body.append(keyword) def _find_root(self, suite): if self.root.name != suite.name: raise ValueError( 'self.root.name "%s" != suite.name "%s"' % (self.root.name, suite.name) ) return self.root def _find(self, items, suite): name = suite.name source = suite.source for item in items: if item.name == name and item.source == source: return item return None def end_suite(self, suite): if self._skip_until and self._skip_until != suite: return if self._skip_until == suite: self._skip_until = None return self.merge_missing_tests(suite) self.merge_time(suite) self.clean_pabotlib_waiting_keywords(self.current) self.current = self.current.parent if ROBOT_VERSION <= "3.0" or ROBOT_VERSION >= "4.0": def clean_pabotlib_waiting_keywords(self, suite): pass else: def clean_pabotlib_waiting_keywords(self, suite): for index, keyword in reversed(list(enumerate(suite.keywords))): if ( keyword.libname == "pabot.PabotLib" and keyword.kwname.startswith("Run") and len(keyword.keywords) == 0 ): suite.keywords.pop(index) def merge_missing_tests(self, suite): cur = self.current for test in suite.tests: if not any(t.longname == test.longname for t in cur.tests): test.parent = cur cur.tests.append(test) def merge_time(self, suite): cur = self.current cur.endtime = max([cur.endtime, suite.endtime]) cur.starttime = min([cur.starttime, suite.starttime]) def visit_message(self, msg): if not msg.html: # no html -> no link -> no update needed return # fix links that go outside of result directory msg.message = msg.message.replace('src="../../', 'src="') msg.message = msg.message.replace('href="../../', 'href="') if not self._patterns: # don't update links if no artifacts were copied return if not ( "src=" in msg.message or "href=" in msg.message ): # quick check before start search with complex regex return for pattern in self._patterns: all_matches = re.finditer(pattern, msg.message) offset = 0 prefix_str = self._prefix + "-" for match in all_matches: filename_start = ( match.start(3) + offset ) # group 3 of regexp is the file name msg.message = ( msg.message[:filename_start] + prefix_str + msg.message[filename_start:] ) offset += len( prefix_str ) # the string has been changed but not the original match positions class ResultsCombiner(CombinedResult): def add_result(self, other): for suite in other.suite.suites: self.suite.suites.append(suite) self.errors.add(other.errors) def prefix(source): try: return os.path.split(os.path.dirname(source))[1] except: return "" def group_by_root(results, critical_tags, non_critical_tags, invalid_xml_callback): groups = {} for src in results: try: res = ExecutionResult(src) except DataError as err: print(err.message) print("Skipping '%s' from final result" % src) invalid_xml_callback() continue if ROBOT_VERSION < "4.0": res.suite.set_criticality(critical_tags, non_critical_tags) groups[res.suite.name] = groups.get(res.suite.name, []) + [res] return groups def merge_groups( results, critical_tags, non_critical_tags, tests_root_name, invalid_xml_callback, out_dir, copied_artifacts, ): merged = [] for group in group_by_root( results, critical_tags, non_critical_tags, invalid_xml_callback ).values(): base = group[0] merger = ResultMerger(base, tests_root_name, out_dir, copied_artifacts) for out in group: merger.merge(out) merged.append(base) return merged def merge( result_files, rebot_options, tests_root_name, copied_artifacts, invalid_xml_callback=None, ): assert len(result_files) > 0 if invalid_xml_callback is None: invalid_xml_callback = lambda: 0 settings = RobotSettings(rebot_options).get_rebot_settings() critical_tags = [] non_critical_tags = [] if ROBOT_VERSION < "4.0": critical_tags = settings.critical_tags non_critical_tags = settings.non_critical_tags merged = merge_groups( result_files, critical_tags, non_critical_tags, tests_root_name, invalid_xml_callback, settings.output_directory, copied_artifacts, ) if len(merged) == 1: if not merged[0].suite.doc: merged[ 0 ].suite.doc = "[https://pabot.org/?ref=log|Pabot] result from %d executions." % len( result_files ) return merged[0] else: return ResultsCombiner(merged)
/robotframework-pabot-2.16.0.tar.gz/robotframework-pabot-2.16.0/src/pabot/result_merger.py
0.492432
0.175503
result_merger.py
pypi
from functools import total_ordering from typing import Dict, List, Optional, Tuple, Union from robot import __version__ as ROBOT_VERSION from robot.errors import DataError from robot.utils import PY2, is_unicode @total_ordering class ExecutionItem(object): isWait = False type = None # type: str name = None # type: str def top_name(self): # type: () -> str return self.name.split(".")[0] def contains(self, other): # type: (ExecutionItem) -> bool return False def difference(self, from_items): # type: (List[ExecutionItem]) -> List[ExecutionItem] return [] def line(self): # type: () -> str return "" def modify_options_for_executor(self, options): options[self.type] = self.name def __eq__(self, other): if isinstance(other, ExecutionItem): return (self.name, self.type) == (other.name, other.type) return NotImplemented def __ne__(self, other): return not (self == other) def __lt__(self, other): return (self.name, self.type) < (other.name, other.type) def __hash__(self): return hash(self.name) | hash(self.type) def __repr__(self): return "<" + self.type + ":" + self.name + ">" class HivedItem(ExecutionItem): type = "hived" def __init__(self, item, hive): self._item = item self._hive = hive def modify_options_for_executor(self, options): self._item.modify_options_for_executor(options) @property def name(self): return self._item.name class GroupItem(ExecutionItem): type = "group" def __init__(self): self.name = "Group_" self._items = [] self._element_type = None def add(self, item): if item.isWait: raise DataError("[EXCEPTION] Ordering : Group can not contain #WAIT") if self._element_type and self._element_type != item.type: raise DataError( "[EXCEPTION] Ordering : Group can contain only test or suite elements. Not bouth" ) if len(self._items) > 0: self.name += "_" self.name += item.name self._element_type = item.type self._items.append(item) def modify_options_for_executor(self, options): for item in self._items: if item.type not in options: options[item.type] = [] opts = {} item.modify_options_for_executor(opts) options[item.type].append(opts[item.type]) class RunnableItem(ExecutionItem): pass depends = None # type: str depends_keyword = "#DEPENDS" def set_name_and_depends(self, name): line_name = name.encode("utf-8") if PY2 and is_unicode(name) else name depends_begin_index = line_name.find(self.depends_keyword) self.name = ( line_name if depends_begin_index == -1 else line_name[0:depends_begin_index].strip() ) self.depends = ( line_name[depends_begin_index + len(self.depends_keyword) :].strip() if depends_begin_index != -1 else None ) def line(self): # type: () -> str line_without_depends = "--" + self.type + " " + self.name return ( line_without_depends + " " + self.depends_keyword + " " + self.depends if self.depends else line_without_depends ) class SuiteItem(RunnableItem): type = "suite" def __init__(self, name, tests=None, suites=None, dynamictests=None): # type: (str, Optional[List[str]], Optional[List[str]], Optional[List[str]]) -> None assert (PY2 and isinstance(name, basestring)) or isinstance(name, str) self.set_name_and_depends(name) testslist = [ TestItem(t) for t in tests or [] ] # type: List[Union[TestItem, DynamicTestItem]] dynamictestslist = [ DynamicTestItem(t, self.name) for t in dynamictests or [] ] # type: List[Union[TestItem, DynamicTestItem]] self.tests = testslist + dynamictestslist self.suites = [SuiteItem(s) for s in suites or []] def difference(self, from_items): # type: (List[ExecutionItem]) -> List[ExecutionItem] if self.tests: return [t for t in self.tests if t not in from_items] if self.suites: return [s for s in self.suites if s not in from_items] return [] def contains(self, other): # type: (ExecutionItem) -> bool if self == other: return True return other.name.startswith(self.name + ".") def __eq__(self, other): if not isinstance(other, SuiteItem): return False if self.name == other.name: return True if other.name.endswith('.'+self.name): return True if self.name.endswith('.'+other.name): return True return False def __hash__(self): return RunnableItem.__hash__(self) def tags(self): # TODO Make this happen return [] class TestItem(RunnableItem): type = "test" def __init__(self, name): # type: (str) -> None self.set_name_and_depends(name) if ROBOT_VERSION >= "3.1": def modify_options_for_executor(self, options): if "rerunfailed" in options: del options["rerunfailed"] name = self.name for char in ["[", "?", "*"]: name = name.replace(char, "[" + char + "]") options[self.type] = name else: def modify_options_for_executor(self, options): if "rerunfailed" in options: del options["rerunfailed"] def difference(self, from_items): # type: (List[ExecutionItem]) -> List[ExecutionItem] return [] def contains(self, other): # type: (ExecutionItem) -> bool return self == other def tags(self): # TODO Make this happen return [] class DynamicSuiteItem(SuiteItem): type = "dynamicsuite" def __init__(self, name, variables): SuiteItem.__init__(self, name) self._variables = variables def modify_options_for_executor(self, options): variables = options.get("variable", [])[:] variables.extend(self._variables) options["variable"] = variables options["suite"] = self.name class DynamicTestItem(ExecutionItem): type = "dynamictest" def __init__(self, name, suite): # type: (str, str) -> None self.name = name.encode("utf-8") if PY2 and is_unicode(name) else name self.suite = suite # type:str def line(self): return "DYNAMICTEST %s :: %s" % (self.suite, self.name) def modify_options_for_executor(self, options): options["suite"] = self.suite variables = options.get("variable", [])[:] variables.append("DYNAMICTEST:" + self.name) options["variable"] = variables def difference(self, from_items): return [] def contains(self, other): return self == other def tags(self): # TODO Make this happen return [] class WaitItem(ExecutionItem): type = "wait" isWait = True def __init__(self): self.name = "#WAIT" def line(self): return self.name class GroupStartItem(ExecutionItem): type = "group" def __init__(self): self.name = "#START" def line(self): return "{" class GroupEndItem(ExecutionItem): type = "group" def __init__(self): self.name = "#END" def line(self): return "}" class IncludeItem(ExecutionItem): type = "include" def __init__(self, tag): self.name = tag def line(self): return "--include " + self.name def contains(self, other): return self.name in other.tags() def tags(self): return [self.name] class SuiteItems(ExecutionItem): type = "suite" def __init__(self, suites): self.suites = suites self.name = " ".join([suite.name for suite in suites]) def modify_options_for_executor(self, options): options["suite"] = [suite.name for suite in self.suites]
/robotframework-pabot-2.16.0.tar.gz/robotframework-pabot-2.16.0/src/pabot/execution_items.py
0.671794
0.203371
execution_items.py
pypi
from __future__ import absolute_import from robot.errors import RobotError try: import configparser # type: ignore except: import ConfigParser as configparser # type: ignore # Support Python 2 import threading import time from typing import Any, Dict, Iterable, List, Optional, Set, Tuple from robot.api import logger from robot.libraries.BuiltIn import BuiltIn from robot.libraries.Remote import Remote from robot.running import TestLibrary from .robotremoteserver import RobotRemoteServer PABOT_LAST_LEVEL = "PABOTLASTLEVEL" PABOT_QUEUE_INDEX = "PABOTQUEUEINDEX" PABOT_LAST_EXECUTION_IN_POOL = "PABOTISLASTEXECUTIONINPOOL" PABOT_MIN_QUEUE_INDEX_EXECUTING_PARALLEL_VALUE = "pabot_min_queue_index_executing" class _PabotLib(object): _TAGS_KEY = "tags" def __init__(self, resourcefile=None): # type: (Optional[str]) -> None self._locks = {} # type: Dict[str, Tuple[str, int]] self._owner_to_values = {} # type: Dict[str, Dict[str, object]] self._parallel_values = {} # type: Dict[str, object] self._remote_libraries = ( {} ) # type: Dict[str, Tuple[int, RobotRemoteServer, threading.Thread]] self._values = self._parse_values(resourcefile) self._added_suites = [] # type: List[Tuple[str, List[str]]] self._ignored_executions = set() # type: Set[str] def _parse_values( self, resourcefile ): # type: (Optional[str]) -> Dict[str, Dict[str, Any]] vals = {} # type: Dict[str, Dict[str, Any]] if resourcefile is None: return vals conf = configparser.ConfigParser() conf.read(resourcefile) for section in conf.sections(): vals[section] = dict( (k, conf.get(section, k)) for k in conf.options(section) ) for section in vals: if self._TAGS_KEY in vals[section]: vals[section][self._TAGS_KEY] = [ t.strip() for t in vals[section][self._TAGS_KEY].split(",") ] else: vals[section][self._TAGS_KEY] = [] return vals def set_parallel_value_for_key(self, key, value): # type: (str, object) -> None self._parallel_values[key] = value def get_parallel_value_for_key(self, key): # type: (str) -> object return self._parallel_values.get(key, "") def acquire_lock(self, name, caller_id): # type: (str, str) -> bool if name in self._locks and caller_id != self._locks[name][0]: return False if name not in self._locks: self._locks[name] = (caller_id, 0) self._locks[name] = (caller_id, self._locks[name][1] + 1) return True def release_lock(self, name, caller_id): # type: (str, str) -> None assert self._locks[name][0] == caller_id self._locks[name] = (caller_id, self._locks[name][1] - 1) if self._locks[name][1] == 0: del self._locks[name] def release_locks(self, caller_id): # type: (str) -> None for key in list(self._locks.keys()): if self._locks[key][0] == caller_id: self._locks[key] = (caller_id, self._locks[key][1] - 1) if self._locks[key][1] == 0: del self._locks[key] def acquire_value_set(self, caller_id, *tags): if not self._values: raise AssertionError( "Value set cannot be aquired. It was never imported or all are disabled. Use --resourcefile option to import." ) # CAN ONLY RESERVE ONE VALUE SET AT A TIME if ( caller_id in self._owner_to_values and self._owner_to_values[caller_id] is not None ): raise ValueError("Caller has already reserved a value set.") matching = False for valueset_key in self._values: if all(tag in self._values[valueset_key][self._TAGS_KEY] for tag in tags): matching = True if self._values[valueset_key] not in self._owner_to_values.values(): self._owner_to_values[caller_id] = self._values[valueset_key] return (valueset_key, self._values[valueset_key]) if not matching: raise ValueError("No value set matching given tags exists.") # This return value is for situations where no set could be reserved # and the caller needs to wait until one is free. return (None, None) def release_value_set(self, caller_id): # type: (str) -> None if caller_id not in self._owner_to_values: return del self._owner_to_values[caller_id] def disable_value_set(self, setname, caller_id): # type: (str, str) -> None del self._owner_to_values[caller_id] del self._values[setname] def get_value_from_set(self, key, caller_id): # type: (str, str) -> object if caller_id not in self._owner_to_values: raise AssertionError("No value set reserved for caller process") if key not in self._owner_to_values[caller_id]: raise AssertionError('No value for key "%s"' % key) return self._owner_to_values[caller_id][key] def add_value_to_set(self, name, content): if self._TAGS_KEY in content.keys(): content[self._TAGS_KEY] = [ t.strip() for t in content[self._TAGS_KEY].split(",") ] if self._TAGS_KEY not in content.keys(): content[self._TAGS_KEY] = [] self._values[name] = content def import_shared_library(self, name, args=None): # type: (str, Iterable[Any]|None) -> int if name in self._remote_libraries: return self._remote_libraries[name][0] imported = TestLibrary(name, args=args) server = RobotRemoteServer( imported.get_instance(), port=0, serve=False, allow_stop=True ) server_thread = threading.Thread(target=server.serve) server_thread.start() time.sleep(1) port = server.server_port self._remote_libraries[name] = (port, server, server_thread) return port def add_suite_to_execution_queue( self, suitename, variables ): # type: (str, List[str]) -> None self._added_suites.append((suitename, variables or [])) def get_added_suites(self): # type: () -> List[Tuple[str, List[str]]] added_suites = self._added_suites self._added_suites = [] return added_suites def ignore_execution(self, caller_id): # type: (str) -> None self._ignored_executions.add(caller_id) def is_ignored_execution(self, caller_id): # type: (str) -> bool return caller_id in self._ignored_executions def stop_remote_libraries(self): for name in self._remote_libraries: self._remote_libraries[name][1].stop_remote_server() for name in self._remote_libraries: self._remote_libraries[name][2].join() class PabotLib(_PabotLib): __version__ = 0.67 ROBOT_LIBRARY_SCOPE = "GLOBAL" ROBOT_LISTENER_API_VERSION = 2 _pollingSeconds_SetupTeardown = 0.3 _pollingSeconds = 0.1 _polling_logging = True _execution_ignored = False def __init__(self): _PabotLib.__init__(self) self.__remotelib = None self.__my_id = None self._valueset = None self._setname = None self.ROBOT_LIBRARY_LISTENER = self self._position = [] # type: List[str] self._row_index = 0 def _start(self, name, attributes): self._position.append(attributes["longname"]) def _end(self, name, attributes): self._position = ( self._position[:-1] if len(self._position) > 1 else [attributes["longname"][: -len(name) - 1]] ) def _start_keyword(self, name, attributes): if not (self._position): self._position = ["0", "0." + str(self._row_index)] else: self._position.append(self._position[-1] + "." + str(self._row_index)) self._row_index = 0 def _end_keyword(self, name, attributes): if not (self._position): self._row_index = 1 self._position = ["0"] return splitted = self._position[-1].split(".") self._row_index = int(splitted[-1]) if len(splitted) > 1 else 0 self._row_index += 1 self._position = ( self._position[:-1] if len(self._position) > 1 else [str(int(splitted[0]) + 1)] ) _start_suite = _start_test = _start _end_suite = _end_test = _end def _close(self): try: self.release_locks() self.release_value_set() except RuntimeError as err: # This is just last line of defence # Ignore connection errors if library server already closed logger.console( "pabot.PabotLib#_close: threw an exception: is --pabotlib flag used? ErrorDetails: {0}".format( repr(err) ), stream="stderr", ) pass @property def _path(self): if len(self._position) < 1: return "" return self._position[-1] @property def _my_id(self): if self.__my_id is None: my_id = BuiltIn().get_variable_value("${CALLER_ID}") logger.debug("Caller ID is %r" % my_id) self.__my_id = my_id if my_id else None return self.__my_id @property def _remotelib(self): if self.__remotelib is None: uri = BuiltIn().get_variable_value("${PABOTLIBURI}") logger.debug("PabotLib URI %r" % uri) self.__remotelib = Remote(uri) if uri else None return self.__remotelib def set_polling_seconds(self, secs): """ Determine the amount of seconds to wait between checking for free locks. Default: 0.1 (100ms) """ PabotLib._pollingSeconds = secs def set_polling_seconds_setupteardown(self, secs): """ Determine the amount of seconds to wait between checking for free locks during setup and teardown. Default: 0.3 (300ms) """ PabotLib._pollingSeconds_SetupTeardown = secs def set_polling_logging(self, enable): """ Enable or disable logging inside of polling. Logging inside of polling can be disabled (enable=False) to reduce log file size. """ if isinstance(enable, str): enable = enable.lower() == "true" PabotLib._polling_logging = bool(enable) def run_setup_only_once(self, keyword, *args): """ Runs a keyword only once at the first possible moment when an execution has gone through this step. [https://pabot.org/PabotLib.html?ref=log#run-setup-only-once|Open online docs.] """ if self._execution_ignored: return lock_name = "pabot_setup_%s" % self._path try: self.acquire_lock(lock_name) passed = self.get_parallel_value_for_key(lock_name) if passed != "": if passed == "FAILED": raise AssertionError("Setup failed in other process") logger.info("Setup skipped in this item") return BuiltIn().run_keyword(keyword, *args) self.set_parallel_value_for_key(lock_name, "PASSED") except: self.set_parallel_value_for_key(lock_name, "FAILED") raise finally: self.release_lock(lock_name) def run_only_once(self, keyword, *args): """ Runs a keyword only once in one of the parallel processes. Optional arguments of the keyword needs to be serializeable in order to create an unique lockname. Sample request sequence [keyword, keyword 'x', keyword, keyword 5, keyword 'x', keyword 5] results in execution of [keyword, keyword 'x', keyword 5] [https://pabot.org/PabotLib.html?ref=log#run-only-once|Open online docs.] """ if self._execution_ignored: return lock_name = "pabot_run_only_once_%s_%s" % (keyword, str(args)) try: self.acquire_lock(lock_name) passed = self.get_parallel_value_for_key(lock_name) if passed != "": if passed == "FAILED": raise AssertionError("Keyword failed in other process") logger.info("Skipped in this item") return BuiltIn().run_keyword(keyword, *args) self.set_parallel_value_for_key(lock_name, "PASSED") except: self.set_parallel_value_for_key(lock_name, "FAILED") raise finally: self.release_lock(lock_name) def run_teardown_only_once(self, keyword, *args): """ Runs a keyword only once after all executions have gone through this step in the last possible moment. [https://pabot.org/PabotLib.html?ref=log#run-teardown-only-once|Open online docs.] """ if self._execution_ignored: return last_level = BuiltIn().get_variable_value("${%s}" % PABOT_LAST_LEVEL) if last_level is None: BuiltIn().run_keyword(keyword, *args) return logger.trace('Current path "%s" and last level "%s"' % (self._path, last_level)) if not self._path.startswith(last_level): logger.info("Teardown skipped in this item") return queue_index = int( BuiltIn().get_variable_value("${%s}" % PABOT_QUEUE_INDEX) or 0 ) logger.trace("Queue index (%d)" % queue_index) if self._remotelib: while ( self.get_parallel_value_for_key( PABOT_MIN_QUEUE_INDEX_EXECUTING_PARALLEL_VALUE ) < queue_index ): if PabotLib._polling_logging: logger.trace( self.get_parallel_value_for_key( PABOT_MIN_QUEUE_INDEX_EXECUTING_PARALLEL_VALUE ) ) time.sleep(PabotLib._pollingSeconds_SetupTeardown) logger.trace("Teardown conditions met. Executing keyword.") BuiltIn().run_keyword(keyword, *args) def run_on_last_process(self, keyword): """ Runs a keyword only on last process used by pabot. [https://pabot.org/PabotLib.html?ref=log#run-on-last-process|Open online docs.] """ if self._execution_ignored: return is_last = ( int( BuiltIn().get_variable_value("${%s}" % PABOT_LAST_EXECUTION_IN_POOL) or 1 ) == 1 ) if not is_last: logger.info("Skipped in this item") return queue_index = int( BuiltIn().get_variable_value("${%s}" % PABOT_QUEUE_INDEX) or 0 ) if queue_index > 0 and self._remotelib: while self.get_parallel_value_for_key("pabot_only_last_executing") != 1: time.sleep(PabotLib._pollingSeconds_SetupTeardown) BuiltIn().run_keyword(keyword) def set_parallel_value_for_key(self, key, value): """ Set a globally available key and value that can be accessed from all the pabot processes. [https://pabot.org/PabotLib.html?ref=log#set-parallel-value-for-key|Open online docs.] """ self._run_with_lib("set_parallel_value_for_key", key, value) def _run_with_lib(self, keyword, *args): if self._remotelib: try: return self._remotelib.run_keyword(keyword, args, {}) except RuntimeError as err: logger.error( "RuntimeError catched in remotelib keyword execution. Maybe there is no connection - is pabot called with --pabotlib option? ErrorDetails: {0}".format( repr(err) ) ) self.__remotelib = None raise return getattr(_PabotLib, keyword)(self, *args) def add_suite_to_execution_queue(self, suitename, *variables): self._run_with_lib("add_suite_to_execution_queue", suitename, variables) def get_parallel_value_for_key(self, key): """ Get the value for a key. If there is no value for the key then empty string is returned. [https://pabot.org/PabotLib.html?ref=log#get-parallel-value-for-key|Open online docs.] """ return self._run_with_lib("get_parallel_value_for_key", key) def acquire_lock(self, name): """ Wait for a lock with name. [https://pabot.org/PabotLib.html?ref=log#acquire-lock|Open online docs.] """ if self._remotelib: try: while not self._remotelib.run_keyword( "acquire_lock", [name, self._my_id], {} ): time.sleep(PabotLib._pollingSeconds) if PabotLib._polling_logging: logger.debug("waiting for lock to release") return True except RuntimeError as err: logger.error( "RuntimeError catched in remote acquire_lock execution. Maybe there is no connection - is pabot called with --pabotlib option? ErrorDetails: {0}".format( repr(err) ) ) self.__remotelib = None raise return _PabotLib.acquire_lock(self, name, self._my_id) def release_lock(self, name): """ Release a lock with name. [https://pabot.org/PabotLib.html?ref=log#release-lock|Open online docs.] """ self._run_with_lib("release_lock", name, self._my_id) def release_locks(self): """ Release all locks called by instance. [https://pabot.org/PabotLib.html?ref=log#release-locks|Open online docs.] """ self._run_with_lib("release_locks", self._my_id) def acquire_value_set(self, *tags): """ Reserve a set of values for this execution. [https://pabot.org/PabotLib.html?ref=log#acquire-value-set|Open online docs.] """ setname = self._acquire_value_set(*tags) if setname is None: raise ValueError("Could not aquire a value set") return setname def _acquire_value_set(self, *tags): if self._remotelib: try: while True: self._setname, self._valueset = self._remotelib.run_keyword( "acquire_value_set", [self._my_id] + list(tags), {} ) if self._setname: logger.info('Value set "%s" acquired' % self._setname) return self._setname time.sleep(PabotLib._pollingSeconds) if PabotLib._polling_logging: logger.debug("waiting for a value set") except RuntimeError as err: logger.error( "RuntimeError catched in remote _acquire_value_set execution. Maybe there is no connection - is pabot called with --pabotlib option? ErrorDetails: {0}".format( repr(err) ) ) self.__remotelib = None raise self._setname, self._valueset = _PabotLib.acquire_value_set( self, self._my_id, *tags ) return self._setname def get_value_from_set(self, key): """ Get a value from previously reserved value set. [https://pabot.org/PabotLib.html?ref=log#get-value-from-set|Open online docs.] """ if self._valueset is None: raise AssertionError("No value set reserved for caller process") key = key.lower() if key not in self._valueset: raise AssertionError('No value for key "%s"' % key) return self._valueset[key] def ignore_execution(self): self._run_with_lib("ignore_execution", self._my_id) error = RobotError("Ignore") error.ROBOT_EXIT_ON_FAILURE = True error.ROBOT_CONTINUE_ON_FAILURE = False self._execution_ignored = True raise error def release_value_set(self): """ Release a reserved value set so that other executions can use it also. [https://pabot.org/PabotLib.html?ref=log#release-value-set|Open online docs.] """ self._valueset = None self._setname = None self._run_with_lib("release_value_set", self._my_id) def disable_value_set(self): """ Disable a reserved value set. [https://pabot.org/PabotLib.html?ref=log#disable-value-set|Open online docs.] """ self._valueset = None self._run_with_lib("disable_value_set", self._setname, self._my_id) self._setname = None # Module import will give a bad error message in log file # Workaround: expose PabotLib also as pabotlib pabotlib = PabotLib if __name__ == "__main__": import sys RobotRemoteServer( _PabotLib(sys.argv[1]), host=sys.argv[2], port=sys.argv[3], allow_stop=True )
/robotframework-pabot-2.16.0.tar.gz/robotframework-pabot-2.16.0/src/pabot/pabotlib.py
0.750278
0.160694
pabotlib.py
pypi
from __future__ import print_function, absolute_import, unicode_literals import six import robot.api from robot.libraries.BuiltIn import BuiltIn from .pageobject import PageObject try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse class PageObjectLibraryKeywords(object): ROBOT_LIBRARY_SCOPE = "TEST SUITE" def __init__(self): self.builtin = BuiltIn() self.logger = robot.api.logger def the_current_page_should_be(self, page_name): """Fails if the name of the current page is not the given page name ``page_name`` is the name you would use to import the page. This keyword will import the given page object, put it at the front of the Robot library search order, then call the method ``_is_current_page`` on the library. The default implementation of this method will compare the page title to the ``PAGE_TITLE`` attribute of the page object, but this implementation can be overridden by each page object. """ page = self._get_page_object(page_name) # This causes robot to automatically resolve keyword # conflicts by looking in the current page first. if page._is_current_page(): # only way to get the current order is to set a # new order. Once done, if there actually was an # old order, preserve the old but make sure our # page is at the front of the list old_order = self.builtin.set_library_search_order() new_order = ([str(page)],) + old_order self.builtin.set_library_search_order(new_order) return # If we get here, we're not on the page we think we're on raise Exception("Expected page to be %s but it was not" % page_name) def go_to_page(self, page_name, page_root=None): """Go to the url for the given page object. Unless explicitly provided, the URL root will be based on the root of the current page. For example, if the current page is http://www.example.com:8080 and the page object URL is ``/login``, the url will be http://www.example.com:8080/login == Example == Given a page object named ``ExampleLoginPage`` with the URL ``/login``, and a browser open to ``http://www.example.com``, the following statement will go to ``http://www.example.com/login``, and place ``ExampleLoginPage`` at the front of Robot's library search order. | Go to Page ExampleLoginPage The effect is the same as if you had called the following three keywords: | SeleniumLibrary.Go To http://www.example.com/login | Import Library ExampleLoginPage | Set Library Search Order ExampleLoginPage Tags: selenium, page-object """ page = self._get_page_object(page_name) url = page_root if page_root is not None else page.selib.get_location() (scheme, netloc, path, parameters, query, fragment) = urlparse(url) url = "%s://%s%s" % (scheme, netloc, page.PAGE_URL) with page._wait_for_page_refresh(): page.selib.go_to(url) # should I be calling this keyword? Should this keyword return # true/false, or should it throw an exception? self.the_current_page_should_be(page_name) def _get_page_object(self, page_name): """Import the page object if necessary, then return the handle to the library Note: If the page object has already been imported, it won't be imported again. """ try: page = self.builtin.get_library_instance(page_name) except RuntimeError: self.builtin.import_library(page_name) page = self.builtin.get_library_instance(page_name) return page
/robotframework_pageobjectlibrary-1.1-py3-none-any.whl/PageObjectLibrary/keywords.py
0.710729
0.152064
keywords.py
pypi
from __future__ import absolute_import, unicode_literals from abc import ABCMeta from contextlib import contextmanager import warnings import robot.api from robot.libraries.BuiltIn import BuiltIn from selenium.webdriver.support.expected_conditions import staleness_of from selenium.webdriver.support.ui import WebDriverWait import six from .locatormap import LocatorMap class PageObject(six.with_metaclass(ABCMeta, object)): """Base class for page objects Classes that inherit from this class need to define the following class variables: PAGE_TITLE the title of the page; used by the default implementation of _is_current_page PAGE_URL this should be the URL of the page, minus the hostname and port (eg: /loginpage.html) By default, the PageObjectLibrary keyword 'the current page should be' calls the method _is_current_page. A default implementation is provided by this class. It compares the current page title to the class variable PAGE_TITLE. A class can override this method if the page title is not unique or is indeterminate. Classes that inherit from this class have access to the following properties: * selib a reference to an instance of SeleniumLibrary * browser a reference to the current webdriver instance * logger a reference to robot.api.logger * locator a wrapper around the page object's ``_locators`` dictionary This class implements the following context managers: * _wait_for_page_refresh This context manager is designed to be used in page objects when a keyword should wait to return until the html element has been refreshed. """ PAGE_URL = None PAGE_TITLE = None def __init__(self): self.logger = robot.api.logger self.locator = LocatorMap(getattr(self, "_locators", {})) self.builtin = BuiltIn() # N.B. selib, browser use @property so that a # subclass can be instantiated outside of the context of a running # test (eg: by libdoc, robotframework-hub, etc) @property def se2lib(self): warnings.warn("se2lib is deprecated. Use selib intead.", warnings.DeprecationWarning) return self.selib @property def selib(self): return self.builtin.get_library_instance("SeleniumLibrary") @property def browser(self): return self.selib.driver def __str__(self): return self.__class__.__name__ def get_page_name(self): """Return the name of the current page """ return self.__class__.__name__ @contextmanager def _wait_for_page_refresh(self, timeout=10): """Context manager that waits for a page transition. This keyword works by waiting for two things to happen: 1) the <html> tag to go stale and get replaced, and 2) the javascript document.readyState variable to be set to "complete" """ old_page = self.browser.find_element_by_tag_name('html') yield WebDriverWait(self.browser, timeout).until( staleness_of(old_page), message="Old page did not go stale within %ss" % timeout ) self.selib.wait_for_condition("return (document.readyState == 'complete')", timeout=10) def _is_current_page(self): """Determine if this page object represents the current page. This works by comparing the current page title to the class variable PAGE_TITLE. Unless their page titles are unique, page objects should override this function. For example, a common solution is to look at the url of the current page, or to look for a specific heading or element on the page. """ actual_title = self.selib.get_title() expected_title = self.PAGE_TITLE if actual_title.lower() == expected_title.lower(): return True self.logger.info("expected title: '%s'" % expected_title) self.logger.info(" actual title: '%s'" % actual_title) raise Exception("expected title to be '%s' but it was '%s'" % (expected_title, actual_title)) return False
/robotframework_pageobjectlibrary-1.1-py3-none-any.whl/PageObjectLibrary/pageobject.py
0.764364
0.165694
pageobject.py
pypi
from __future__ import absolute_import, unicode_literals from .keywords import PageObjectLibraryKeywords from .pageobject import PageObject from .version import __version__ class PageObjectLibrary(PageObjectLibraryKeywords): """This project is hosted on github in the repository [https://github.com/boakley/robotframework-pageobjectlibrary| boakley/robotframework-pageobjectlibrary] *PageObjectLibrary* is a lightweight library which supports using the page object pattern with [http://robotframework.org/SeleniumLibrary/doc/SeleniumLibrary.html|SeleniumLibrary]. This library does not replace SeleniumLibrary; rather, it provides a framework around which to use SeleniumLibrary and the lower-level [http://selenium-python.readthedocs.org/|Python bindings to Selenium] This library provides the following keywords: | =Keyword Name= | =Synopsis= | | Go to page | Goes to the given page in the browser | | The current page should be | Assert that the given page is displayed in the browser | | Get page name | Returns the name of the current page | PageObjectLibrary provides a PageObject class which should be used as the base class for other page objects. By inheriting from this class your keywords have access to the following pre-defined attributes and methods: | =Attribute/method= | =Description= | | ``self.selib` ` | A reference to the SeleniumLibrary instance | | ``self.browser`` | A reference to the currently open browser | | ``self.locator`` | A wrapper around the ``_locators`` dictionary | | ``self.logger`` | A reference to the ``robot.api.logger`` instance | | ``self._wait_for_page_refresh()`` | a context manager for doing work that causes a page refresh | = Using SeleniumLibrary Keywords = Within your keywords you have access to the full power of SeleniumLibrary. You can use ``self.selib`` to access the library keywords. The following example shows how to call the ``Capture Page Screenshot`` keyword: | self.selib.capture_page_screenshot() = Using Selenium Methods = The attribute ``self.browser`` is a reference to a Selenium webdriver object. With this reference you can call any of the standard Selenium methods provided by the Selenium library. The following example shows how to find all link elements on a page: | elements = self.browser,find_elements_by_tag_name("a") = Creating Page Object Classes = Page objects should inherit from PageObjectLibrary.PageObject. At a minimum, the class should define the following attributes: | =Attribute= | =Description= | | ``PAGE_URL`` | The path to the current page, without the \ hostname and port (eg: ``/dashboard.html``) | | ``PAGE_TITLE`` | The web page title. This is used by the \ default implementation of ``_is_current_page``. | When using the keywords `Go To Page` or `The Current Page Should Be`, the PageObjectLibrary will call the method ``_is_current_page`` of the given page. By default this will compare the current page title to the ``PAGE_TITLE`` attribute of the page. If you are working on a site where the page titles are not unique, you can override this method to do any type of logic you need. = Page Objects are Normal Robot Libraries = All rules that apply to keyword libraries applies to page objects. For example, the libraries must be on ``PYTHONPATH``. You may also want to define ``ROBOT_LIBRARY_SCOPE``. Also, the filename and the classname must be identical (minus the ``.py`` suffix on the file). = Locators = When writing multiple keywords for a page, you often use the same locators in many places. PageObject allows you to define your locators in a dictionary, but them use them with a more convenient dot notation. To define locators, create a dictionary named ``_locators``. You can then access the locators via dot notation within your keywords as ``self.locator.<name>``. The ``_locators`` dictionary may have nested dictionaries. = Waiting for a Page to be Ready = One difficulty with writing Selenium tests is knowing when a page has refreshed. PageObject provides a context manager named ``_wait_for_page_refresh()`` which can be used to wrap a command that should result in a page refresh. It will get a reference to the DOM, run the body of the context manager, and then wait for the DOM to change before returning. = Example Page Object Definition = | from PageObjectLibrary import PageObject | from robot.libraries.BuiltIn import BuiltIn | | class LoginPage(PageObject): | PAGE_TITLE = "Login - PageObjectLibrary Demo" | PAGE_URL = "/" | | _locators = { | "username": "id=id_username", | "password": "id=id_password", | "submit_button": "id=id_submit", | } | | def login_as_a_normal_user(self): | username = BuiltIn().get_variable_value("${USERNAME}"} | password = BuiltIn().get_variable_value("${PASSWORD}"} | self.selib.input_text(self.locator.username, username) | self.selib.input_text(self.locator.password, password) | | with self._wait_for_page_refresh(): | self.click_the_submit_button() = Using the Page Object in a Test = To use the above page object in a test, you must make sure that Robot can import it, just like with any other keyword library. When you use the keyword `Go to page`, the keyword will automatically load the keyword library and put it at the front of the Robot Framework library search order (see [http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Set%20Library%20Search%20Order|Set Library Search Order]) In the following example it is assumed there is a second page object named ``DashboardPage`` which the browser is expected to go to if login is successful. | ``*** Settings ***`` | Library PageObjectLibrary | Library SeleniumLibrary | Suite Setup Open browser http://www.example.com | Suite Teardown Close all browsers | | ``*** Test Cases ***`` | Log in to the application | Go to page LoginPage | Log in as a normal user | The current page should be DashboardPage """ ROBOT_LIBRARY_SCOPE = "TEST SUITE"
/robotframework_pageobjectlibrary-1.1-py3-none-any.whl/PageObjectLibrary/__init__.py
0.84556
0.450118
__init__.py
pypi
import logging import sys import robot.api.logger import robot.output.pyloggingconf as robot_logging_conf from optionhandler import OptionHandler from context import Context class Logger(object): """Responsible for abstracting Robot logging and logging outside of Robot. """ def __init__(self): self.in_robot = Context.in_robot() self.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') self.threshold_level_as_str = self.get_threshold_level_as_str() self.threshold_level_as_int = self.get_log_level_from_str(self.threshold_level_as_str) if self.in_robot: self.logger = robot.api.logger else: # Stream handler is attached from log() since # that must be decided at run-time, but here we might as well # do the setup to keep log() clean. self.stream_handler = logging.StreamHandler(sys.stdout) self.stream_handler.setFormatter(self.formatter) # We have to instantiate a logger to something and this is a global # logger so we name it by this class. Later in this class' # log method, we manipulate the msg string to include the calling # page class name. logger = logging.getLogger(self.__class__.__name__) logger.setLevel(self.threshold_level_as_int) fh = logging.FileHandler("po_log.txt", "w") fh.setLevel(self.threshold_level_as_int) fh.setFormatter(self.formatter) logger.addHandler(fh) self.logger = logger @staticmethod def get_threshold_level_as_str(): ret = OptionHandler(object()).get("log_level") or "INFO" return ret.upper() @staticmethod def get_log_level_from_str(level_as_str): """ Convert string log level to integer logging level.""" str_upper = level_as_str.upper() try: return getattr(logging, str_upper) except AttributeError: return getattr(logging, "INFO") @staticmethod def get_normalized_logging_levels(level_as_str, in_robot): """ Given a log string, returns the translated log level string and the translated python logging level integer. This is needed because there are logging level constants defined in Robot that are not in Python, and Python logging level constants that are not defined in Robot. """ translation_map = { "CRITICAL": "WARN", "WARNING": "WARN", "NOTSET": "TRACE" } level_as_str_upper = level_as_str.upper() if in_robot: robot_levels = robot_logging_conf.LEVELS # The level passed in is a Robot level, so look up corresponding # python integer logging level if level_as_str_upper is "WARNING": # There is no "WARNING" in Robot level_as_str_upper = "WARN" if level_as_str_upper in robot_levels: return level_as_str_upper, robot_levels[level_as_str_upper] else: # The level passed-in doesn't correspond to a # Robot level, so translate it to one, then look it up. translated_level_str = None try: translated_level_str = translation_map[level_as_str_upper] except KeyError: raise ValueError("The log level '%s' is invalid" % level_as_str_upper) return translated_level_str, robot_levels[translated_level_str] else: try: # Try to get levels from python return level_as_str_upper, getattr(logging, level_as_str_upper) except AttributeError: # Could be user is passing in a Robot log string that # doesn't exist for Python. So look up the Python level given the robot level inv_translation_map = {v: k for k, v in translation_map.items()} try: translated_level_str = inv_translation_map[level_as_str_upper] except KeyError: translated_level_str = level_as_str_upper try: return translated_level_str, getattr(logging, translated_level_str) except AttributeError: raise ValueError("The log level '%s' is invalid" % level_as_str_upper) def log(self, msg, calling_page_name, level="INFO", is_console=True): level_as_str, level_as_int = self.get_normalized_logging_levels(level, self.in_robot) msg = "%s - %s" % (calling_page_name, msg) if self.in_robot: self.logger.write(msg, level_as_str) if is_console: # Robot's logging only outputs to stdout if it's a warning, so allow # always logging to console, unless caller specifies not to. robot.api.logger.console("%s - %s" % (level, msg)) else: if is_console: self.logger.addHandler(self.stream_handler) self.logger.log(level_as_int, msg)
/robotframework-pageobjects-1.3.3.tar.gz/robotframework-pageobjects-1.3.3/robotpageobjects/abstractedlogger.py
0.473414
0.16043
abstractedlogger.py
pypi
import re from playwright.sync_api import expect from robotlibcore import keyword from .ui_context import UIContext from .utils import Robot class DropdownHandler(UIContext): @keyword('dropdown should be enabled') def dropdown_should_be_enabled(self, locator): expect(self.get_element(locator)).to_be_enabled() @keyword('dropdown should be disabled') def dropdown_should_be_disabled(self, locator): expect(self.get_element(locator)).to_be_disabled() @keyword('dropdown should be required', tags=['specific']) def dropdown_should_be_required(self, locator): element = self.get_element(locator).locator("xpath=./preceding-sibling::*") expect(element).to_have_class(re.compile(r"required")) @keyword('dropdown should not be required', tags=['specific']) def dropdown_should_not_be_required(self, locator): element = self.get_element(locator).locator("xpath=./preceding-sibling::*") expect(element).not_to_have_class(re.compile(r"required")) @keyword('select value') def select_value(self, locator, selected_value): self.get_element(locator).select_option(label=selected_value, force=True) @keyword('select nested value', tags=["specific"]) def select_nested_value(self, locator, selected_value, wait_for_value=True, unchecked=False): element = self.get_element(locator) target_label = element.locator( f'xpath=/following-sibling::div//label[text()="{selected_value}"]').locator('nth=0') element.click() if wait_for_value: expect(target_label).to_be_visible() checkbox = target_label.locator('xpath=/preceding-sibling::input') checkbox.check() if not unchecked else checkbox.uncheck() element.click(force=True) @keyword('nested dropdown should contain', tags=["specific"]) def nested_dropdown_should_contain(self, locator, *values): element = self.get_element(locator) element.click(force=True) for value in values: expect(element.locator( f'xpath=/following-sibling::div//label[text()="{value}"]').locator('nth=0')).to_be_visible() element.click(force=True) @keyword('nested item should be ticked', tags=["specific"]) def nested_item_should_be_ticked(self, locator, *values): element = self.get_element(locator) element.click(force=True) for value in values: expect(element.locator( f'xpath=./following-sibling::div//div[@title="{value}"]/input')).to_be_checked() element.click(force=True) @keyword('nested item should not be ticked', tags=["specific"]) def nested_item_should_not_be_ticked(self, locator, *values): element = self.get_element(locator) element.click(force=True) for value in values: expect(element.locator( f'xpath=./following-sibling::div//div[@title="{value}"]/input')).not_to_be_checked() element.click(force=True) @keyword('nested item should be enabled', tags=["specific"]) def nested_item_should_be_enabled(self, locator, *values): element = self.get_element(locator) element.click(force=True) for value in values: expect(element.locator( f'xpath=./following-sibling::div//div[@title="{value}"]/input')).to_be_enabled() element.click(force=True) @keyword('nested item should be disabled', tags=["specific"]) def nested_item_should_be_disabled(self, locator, *values): element = self.get_element(locator) element.click(force=True) for value in values: expect(element.locator( f'xpath=./following-sibling::div//div[@title="{value}"]/input')).to_be_disabled() element.click(force=True) @keyword('dropdown itemlist should be') def dropdown_itemlist_should_be(self, locator, item_list): """ [Documentation] Verify combobox at ${locator} having correct item list as ${item_list} ${item_list} needs to be separated with ';' for each value E.g: Robot;Agent;Sale;Customer :param locator: element's locator :param item_list: Robot;Agent;Sale;Customer :return: assert the expected result """ assert self.get_list_values(locator) == item_list.split( ";"), f'{self.get_list_values(locator)} is not equal to {item_list.split(";")}' @keyword('list item should be') def list_item_should_be(self, locator, *item_list): """ [Documentation] Verify combobox at ${locator} having correct item list as ${item_list} ${item_list} needs to be separated with ';' for each value E.g: Robot;Agent;Sale;Customer :param locator: element's locator - string :param item_list: list of string :return: assert the expected result """ assert self.get_list_values(locator) == list(item_list), f'{self.get_list_values(locator)} is not equal to ' \ f'{item_list}' @keyword('dropdown itemlist should contain') def dropdown_itemlist_should_contain(self, locator, item_list): Robot().should_contain(self.get_list_values(locator), item_list.split(";")) @keyword('dropdown itemlist should not contain') def dropdown_itemlist_should_not_contain(self, locator, item_list): Robot().should_not_contain(self.get_list_values(locator), item_list.split(";")) @keyword('dropdown current value should be') def dropdown_current_value_should_be(self, locator, expected_value): element = self.get_element(locator).locator('xpath=./option[@selected="selected"]') expect(element).to_have_text(expected_value) @keyword('dropdown current value should not be') def dropdown_current_value_should_not_be(self, locator, expected_value): element = self.get_element(locator).locator('xpath=./option[@selected="selected"]') expect(element).not_to_have_value(expected_value) @keyword('dropdown current value should contain') def dropdown_current_value_should_contain(self, locator, expected_value): element = self.get_element(locator).locator('xpath=./option[@selected="selected"]') expect(element).to_contain_text(expected_value) @keyword('dropdown current value should not contain') def dropdown_current_value_should_not_contain(self, locator, expected_value): element = self.get_element(locator).locator('xpath=./option[@selected="selected"]') expect(element).not_to_contain_text(expected_value) @keyword('get current selected value') def get_current_selected_value(self, locator): element = self.get_element(locator).locator('xpath=./option[@selected="selected"]') return element.input_value() @keyword('get list values') def get_list_values(self, locator): return self.get_element(locator).locator("xpath=./option").all_text_contents() @keyword('dropdown should be correct') def dropdown_should_be_correct(self, locator, item_list=None, state='enabled', default=None, mandatory=None): element = self.get_element(locator) # Verify state if state == 'enabled': self.dropdown_should_be_enabled(element) elif state == 'disabled': self.dropdown_should_be_disabled(element) # Verify default value if default is not None: self.dropdown_current_value_should_be(element, default) # Verify item list if item_list is not None: self.dropdown_itemlist_should_be(element, item_list) # Verify mandatory: if mandatory == 'unrequired': self.dropdown_should_not_be_required(locator) elif mandatory == 'required': self.dropdown_should_be_required(locator) @keyword('nested dropdown should be correct') def nested_dropdown_should_be_correct(self, locator, item_list=None, state='enabled', default=None): element = self.get_element(locator) # Verify state if state == 'enabled': expect(element).to_be_enabled() elif state == 'disabled': assert "disabled" in element.get_attribute("class"), f"{locator} is not disabled" # Verify default value if default is not None: placeholder = element.locator('xpath=./div/p') assert default in placeholder.text_content(), f"{locator} is having default value: {placeholder.text}" # Verify item list if item_list is not None: self.nested_dropdown_should_contain(locator, *item_list.split(";")) @keyword('get selected item index') def get_selected_item_index(self, locator): item_list = self.get_list_values(locator) return item_list.index(self.get_element(locator).locator("xpath=./option").text_content()) @keyword('get item list length') def get_item_list_length(self, locator): return len(self.get_list_values(locator))
/robotframework-playerlibrary-1.0.3.tar.gz/robotframework-playerlibrary-1.0.3/src/PlayerLibrary/dropdown_handler.py
0.629775
0.286693
dropdown_handler.py
pypi
from playwright.sync_api import expect from robotlibcore import keyword from .utils import random_number_chars from .ui_context import UIContext from .utils import Robot class TextboxHandler(UIContext): @keyword('input into') def input_into(self, locator, text, clear=True, force=False): element = self.get_element(locator) if clear: element.fill('', force=force) element.fill(text, force=force) return text @keyword('input new text into', tags=["deprecated"]) def input_new_text_into(self, locator, text): element = self.get_element(locator) element.clear() element.fill(text) @keyword("input text by pressing key") def input_text_by_pressing_key(self, locator, text, delay=100): self.get_element(locator).type(text, delay=delay) return text @keyword('clear text using backspace') def clear_text_using_backspace(self, locator): element = self.get_element(locator) element.select_text() element.press("Backspace") @keyword('clear text') def clear_text(self, locator): self.get_element(locator).fill("") @keyword('maxlength should be') def maxlength_should_be(self, locator, expected_maxlength): element = self.get_element(locator) element.fill("") length = int(expected_maxlength) + 1 string = random_number_chars(length) element.fill(string) Robot().should_be_equal_as_integers(len(element.input_value()), expected_maxlength) element.fill("") @keyword('textbox should be empty') def textbox_should_be_empty(self, locator): expect(self.get_element(locator)).to_have_value("") @keyword('Placeholder should be') def placeholder_should_be(self, locator, expected_text): expect(self.get_element(locator)).to_have_attribute("placeholder", expected_text) @keyword('textbox should be correct') def textbox_should_be_correct(self, locator, state='enabled', default="", mandatory=None, maxlength=None, is_numeric=False): element = self.get_element(locator) default = default.replace(',', '') if is_numeric else default # Verify state if state == 'enabled': expect(element).to_be_enabled() elif state == 'disabled': expect(element).to_be_disabled() # Verify default value if default != "": expect(element).to_have_value(default) # Verify Max-length if maxlength is not None: self.maxlength_should_be(element, maxlength) # Verify mandatory if mandatory == 'unrequired': self.element_should_not_be_marked_as_required(element) elif mandatory == 'required': self.element_should_be_marked_as_required(element)
/robotframework-playerlibrary-1.0.3.tar.gz/robotframework-playerlibrary-1.0.3/src/PlayerLibrary/textbox_handler.py
0.534127
0.199522
textbox_handler.py
pypi
import base64 from playwright.sync_api import expect from robotlibcore import keyword from .utils import Robot from .ui_context import UIContext from .base_context import BaseContext from .custom_locator import * class PageHandler(UIContext): @keyword('page title should be') def page_title_should_be(self, title): expect(self.get_page()).to_have_title(title) @keyword('get all data of similar html elements') def get_all_data_of_similar_html_elements(self, locator): elements = self.get_elements(locator) return [element.text_content() for element in elements] @keyword('text should be visible') def text_should_be_visible(self, *texts, timeout=BaseContext.SMALL_TIMEOUT): for text in texts: element = self.get_element(f'//body//*[not(self::script)][contains(.,"{text}")]').first expect(element).to_be_visible(timeout=timeout) @keyword('text should not be visible') def text_should_not_be_visible(self, *texts, timeout=BaseContext.SMALL_TIMEOUT): for text in texts: element = self.get_element(f'//body//*[not(self::script)][contains(text(),"{text}")]') expect(element).to_be_hidden(timeout=timeout) @keyword('texts should be visible') def texts_should_be_visible(self, texts: list, timeout=BaseContext.TIMEOUT, deep_scan=False): text_node = "text()" if not deep_scan else "." for text in texts: element = self.get_element(f'//body//*[not(self::script)][contains({text_node},"{text}")]') expect(element).to_be_visible(timeout=timeout) @keyword('texts should not be visible') def texts_should_not_be_visible(self, texts: list, timeout=BaseContext.TIMEOUT, deep_scan=False): text_node = "text()" if not deep_scan else "." for text in texts: element = self.get_element(f'//body//*[not(self::script)][contains({text_node},"{text}")]') expect(element).to_be_hidden(timeout=timeout) @keyword('Page should have') def page_should_have(self, *items, timeout=BaseContext.TIMEOUT): for item in items: if item.startswith(BUILT_IN_PREFIX + CUSTOM_PREFIX + STANDARD_PREFIX + XPATH_PREFIX): self.page_should_have_element(item, timeout) else: self.text_should_be_visible(item) @keyword('page should not have') def page_should_not_have(self, *items, timeout=BaseContext.TIMEOUT): for item in items: if item.startswith(BUILT_IN_PREFIX + CUSTOM_PREFIX + STANDARD_PREFIX + XPATH_PREFIX): self.page_should_not_have_element(item, timeout) else: self.text_should_not_be_visible(item) @keyword('page should be blank') def page_should_be_blank(self): expect(self.get_page()).to_have_url("about:blank") @keyword('page should have element') def page_should_have_element(self, locator, timeout=BaseContext.TIMEOUT): element = self.get_element(locator) expect(element).to_be_visible(timeout=timeout) return element @keyword('page should not have element') def page_should_not_have_element(self, locator, timeout=BaseContext.SMALL_TIMEOUT, recheck_timeout=2): element = self.get_element(locator) expect(element).to_be_hidden(timeout=timeout) Robot().sleep(recheck_timeout) expect(element).to_be_hidden(timeout=timeout) @keyword('page should be redirected to') def page_should_be_redirected_to(self, url): expect(self.get_page()).to_have_url(url) @keyword('alert should be shown') def alert_should_be_shown(self, content, locator): """ Verifies that an alert is present and, by default, accepts it. > ACCEPT: Accept the alert i.e. press Ok. Default. > DISMISS: Dismiss the alert i.e. press Cancel. > LEAVE: Leave the alert open. :param locator: :param content: :return: """ with self.get_page().expect_event("dialog") as new_dialog_info: self.get_element(locator).click() dialog = new_dialog_info.value assert dialog.message == content dialog.dismiss() @keyword('capture screenshot') def capture_screenshot(self): image_bytes = self.get_page().screenshot(full_page=True) image_source = base64.b64encode(image_bytes).decode('utf-8') image = f""" <html> <head> <style> img.one {{ height: 75%; width: 75%; }} </style> </head> <body> <img class="one" src="data:image/png;base64, {image_source}"> </body> </html> """ Robot().log(message=image, html=True) @keyword('get page source') def get_page_source(self): return self.get_page().text_content() @keyword('reload whole page') def reload_whole_page(self): self.get_page().reload() @keyword('html title should be') def html_title_should_be(self, title): expect(self.get_page()).to_have_title(title) @keyword('go back to previous page') def go_back_to_previous_page(self): self.get_page().go_back() @keyword("text having correct amount value") def text_having_correct_amount_value(self, text, amount): """ :param text: Something like "I have the payout of {abc} will be refunded tomorrow". Should include the curly bracket here :param amount: The actual amount which will be replaced into {abc} :return: Verify if the text having correct expected amount or not """ text = re.sub(r'(?<=\{).*(?=\})', amount, text) text = text.replace("{", "").replace("}", "") self.page_should_have(text) @keyword('upload file') def upload_file(self, file_path, locator='//input[@type="file"]'): """ Handle the upload file function. Locator must point to the element having 'type=file' attribute :param locator: :param file_path: :return: None """ self.get_element(locator).set_input_files(file_path) @keyword('wait for text', tags=['deprecated']) def wait_for_text(self, text): self.text_should_be_visible(text) @keyword('wait for text to hide', tags=['deprecated']) def wait_for_text_to_hide(self, text): self.text_should_not_be_visible(text) @keyword('scroll to element', tags=["deprecated"]) def scroll_to_element(self, locator): pass @keyword('scroll element into view', tags=["deprecated"]) def scroll_element_into_view(self, locator): pass @keyword('scroll to element with additional alignment') def scroll_to_element_with_additional_alignment(self, locator, alignment='true'): """ [Documentation] True - the top of the element will be aligned to the top of the visible area of the scrollable ancestor ... False - the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor ... If omitted, it will scroll to the top of the element :param locator: :param alignment: :return: """ element = self.get_element(locator) element.evaluate(f"scrollIntoView({alignment});") @keyword('scroll right') def scroll_right(self): self.get_page().evaluate("window.scrollTo(document.body.scrollWidth,document.body.scrollHeight);") @keyword('scroll down') def scroll_down(self): self.get_page().evaluate("window.scrollTo(0,document.body.scrollHeight);")
/robotframework-playerlibrary-1.0.3.tar.gz/robotframework-playerlibrary-1.0.3/src/PlayerLibrary/page_handler.py
0.603231
0.184418
page_handler.py
pypi
from datetime import datetime from playwright.sync_api import expect from robotlibcore import keyword from .ui_context import UIContext from .utils import Robot from .base_context import BaseContext class DatePickerHandler(UIContext): BASIC_DATE_FORMAT = "%Y-%m-%d" ALTERNATIVE_DATE_FORMAT = "%d %b, %Y" @keyword('input datetime') def input_datetime(self, locator, value): element = self.get_element(locator) element.evaluate("node => node.removeAttribute('readonly')") element.fill(value, force=True) self.get_element("xpath=//body").click() Robot().sleep(1) return value @keyword('datepicker should be correct') def datepicker_should_be_correct(self, locator, state='enabled', default=None, mandatory=None): element = self.get_element(locator) # Verify state if state == 'enabled': expect(element).to_be_enabled() elif state == 'disabled': expect(element).to_be_disabled() # Verify default value if default is not None: expect(element).to_have_value(default) # Verify mandatory if mandatory == 'unrequired': self.element_should_not_be_marked_as_required(locator) elif mandatory == 'required': self.element_should_be_marked_as_required(locator) @keyword('actual date should be') def actual_date_should_be(self, locator, expected_date, input_format=BASIC_DATE_FORMAT, displayed_format=ALTERNATIVE_DATE_FORMAT, timeout=BaseContext.SMALL_TIMEOUT): actual_date = None for sec in range(int(timeout/1000)): actual_date = self.get_actual_text(locator) if datetime.strptime(expected_date, input_format) == datetime.strptime(actual_date, displayed_format): break Robot().sleep(1) if datetime.strptime(expected_date, input_format) != datetime.strptime(actual_date, displayed_format): raise AssertionError(f"Actual date: '{actual_date}' is different with expected date: '{expected_date}'") @keyword('actual date should not be') def actual_date_should_not_be(self, locator, expected_date, input_format=BASIC_DATE_FORMAT, displayed_format=ALTERNATIVE_DATE_FORMAT, timeout=BaseContext.SMALL_TIMEOUT): actual_date = None for sec in range(int(timeout/1000)): actual_date = self.get_actual_text(locator) if datetime.strptime(expected_date, input_format) != datetime.strptime(actual_date, displayed_format): break Robot().sleep(1) if datetime.strptime(expected_date, input_format) == datetime.strptime(actual_date, displayed_format): raise AssertionError(f"Actual date: '{actual_date}' is similar with expected text: '{expected_date}'") @keyword("element is datepicker", tags=["deprecated", "specific"]) def element_is_datepicker(self, locator): return True if self.get_element(locator).get_attribute(locator, "uib-datepicker-popup") is not None else False
/robotframework-playerlibrary-1.0.3.tar.gz/robotframework-playerlibrary-1.0.3/src/PlayerLibrary/datepicker_handler.py
0.494141
0.208793
datepicker_handler.py
pypi
from playwright.sync_api import expect from robotlibcore import keyword from .ui_context import UIContext class TableHandler(UIContext): @keyword('Table column should have') def table_column_should_have(self, *items, locator='//table'): """ Check for table header contains some labels or not :param locator: element locator :param items: list of strings :return: """ element = self.get_element(locator) for item in items: expect(element.locator(f'//thead//tr[contains(.,"{item}")]')).to_be_visible() @keyword('Table row should have') def table_row_should_have(self, *items, locator='//table', row_index=None): """ Check for table row contains some labels or not :param row_index: index of row starting from 1 :param locator: element locator :param items: list of strings :return: """ element = self.get_element(locator) for item in items: if row_index is not None: expect(element.locator(f'//tbody//tr[{row_index}][contains(.,"{item}")]')).to_be_visible() else: item_length = len(items) xpath_expression = f'{locator}//tbody//tr[' for index, item in enumerate(items): if index < item_length - 1: xpath_expression += f'contains(.,"{item}") and ' else: xpath_expression += f'contains(.,"{item}")' xpath_expression += f']' expect(self.page.locator(xpath_expression)).to_be_visible() @keyword('Table cell value should be') def table_cell_value_should_be(self, row_key, column_name, expected_cell_value): """ Check for specific cell in a table that has expected value :param row_key: a specific value in a row that can be identified with others :param column_name: name of the column that has the expected cell :param expected_cell_value: the expected cell's value :return: """ column_titles = self.get_elements(f'//th[.//*[text()="{column_name}"]]/preceding-sibling::*') pos = len(column_titles) + 1 expect(self.page.locator(f'//tr[.//*[text()="{row_key}"]][.//td[position()={pos} ' f'and .//*[text()="{expected_cell_value}"]]]')).to_be_visible()
/robotframework-playerlibrary-1.0.3.tar.gz/robotframework-playerlibrary-1.0.3/src/PlayerLibrary/table_handler.py
0.689724
0.34563
table_handler.py
pypi
from playwright.sync_api import expect from robotlibcore import keyword from .ui_context import UIContext from .base_context import BaseContext class CheckboxHandler(UIContext): @keyword('checkbox should be enabled') def checkbox_should_be_enabled(self, locator): element = self.get_element(locator) expect(element).to_be_enabled(timeout=BaseContext.SMALL_TIMEOUT) @keyword('checkbox should be disabled') def checkbox_should_be_disabled(self, locator): element = self.get_element(locator) expect(element).to_be_disabled(timeout=BaseContext.SMALL_TIMEOUT) @keyword('tick checkbox') def tick_checkbox(self, locator): element = self.get_element(locator) element.check() @keyword('untick checkbox') def untick_checkbox(self, locator): element = self.get_element(locator) element.uncheck() @keyword('checkbox should be checked') def checkbox_should_be_checked(self, locator): expect(self.get_element(locator)).to_be_checked() @keyword('checkbox should not be checked') def checkbox_should_not_be_checked(self, locator): expect(self.get_element(locator)).not_to_be_checked() @keyword('get current checkbox checking status') def get_current_checkbox_checking_status(self, locator): return self.get_element(locator).is_checked() @keyword('checkbox should be correct') def checkbox_should_be_correct(self, locator, state='enabled', status='unchecked'): element = self.get_element(locator) # Verify state if state == 'enabled': self.checkbox_should_be_enabled(element) elif state == 'disabled': self.checkbox_should_be_disabled(element) # Verify status: if status == 'unchecked': self.checkbox_should_not_be_checked(element) elif status == 'checked': self.checkbox_should_be_checked(element) @keyword('select a radio option') def select_a_radio_option(self, locator): self.get_element(locator).check(force=True) @keyword('radio button should be disabled') def radio_button_should_be_disabled(self, locator): expect(self.get_element(locator)).to_be_disabled() @keyword('radio button should be enabled') def radio_button_should_be_enabled(self, locator): expect(self.get_element(locator)).to_be_enabled() @keyword('radio button should be checked') def radio_button_should_be_checked(self, locator): expect(self.get_element(locator)).to_be_checked() @keyword('radio button should not be checked') def radio_button_should_not_be_checked(self, locator): expect(self.get_element(locator)).not_to_be_checked() @keyword('get current radio button checking status') def get_current_radio_button_checking_status(self, locator): return self.get_element(locator).is_checked() @keyword('radio should be correct') def radio_should_be_correct(self, locator, state='enabled', status='unchecked'): element = self.get_element(locator) if state == 'enabled': self.checkbox_should_be_enabled(element) elif state == 'disabled': self.checkbox_should_be_disabled(element) if status == 'unchecked': self.radio_button_should_not_be_checked(element) elif status == 'checked': self.radio_button_should_be_checked(element)
/robotframework-playerlibrary-1.0.3.tar.gz/robotframework-playerlibrary-1.0.3/src/PlayerLibrary/checkbox_handler.py
0.603465
0.243305
checkbox_handler.py
pypi
from __future__ import annotations import datetime import os.path from typing import Optional from robot.api import logger as robot_logger from robot.libraries.BuiltIn import BuiltIn from robot.result.model import TestCase as RTest from robot.running import TestSuite as ESuite, TestCase as ETest from robot.utils import is_truthy from robotframework_practitest.models import practi_test as pt, adapter, robot as rb from robotframework_practitest.models.field_adapter import update_fields from robotframework_practitest.services import configuration as config, scheduler as sh, statistics as st from robotframework_practitest.utils import get_error_info, read_variables from robotframework_practitest.utils.logger import create_file_handler, create_system_out_handler, \ set_level, add_handler, logger PT_RETENTION_TIMEOUT = 0 class Listener(adapter.RobotToPractiTest_Adapter): """Class represents service that sends Robot items to PractiTest API.""" ROBOT_LISTENER_API_VERSION = 3 def __init__(self): """Initialize service attributes.""" self._debug = False self.api_client: Optional[pt.PtClient] = None self.run_mode = sh.TaskType.Foreground self.version = None self._metadata_collection = [] self._init_suite_required = False super(Listener, self).__init__() @property def test_set_name(self): return '/'.join(self.current_suite_path_list) def init_api(self, **kwargs): """Initialize common PractiTest API client.""" if self.api_client is None: try: assert is_truthy(kwargs.get('PT_ENABLED', False)), "PractiTest report disabled" log_level = BuiltIn().get_variable_value("${LOG_LEVEL}", 'INFO') set_level(log_level) if kwargs.get('PT_LOG_TO_FILE'): out_path = BuiltIn().get_variable_value("${OUTPUT_DIR}") log_file_name = f"{__name__.split('.')[0]}.log" log_file = os.path.normpath(os.path.normpath(os.path.join(out_path, 'logs', log_file_name))) add_handler(create_file_handler(log_file)) robot_logger.warn(f"<a href=\"logs/{log_file_name}\">PractiTest log</a>", html=True) if kwargs.get('PT_LOG_TO_STDOUT'): add_handler(create_system_out_handler()) logger.info(f"Session opened at {datetime.datetime.now()}") endpoint = kwargs.get('PT_ENDPOINT', None) project = kwargs.get('PT_PROJECT_NAME', None) tester_name = kwargs.get('PT_USER_NAME', None) user_email = kwargs.get('PT_USER_NAME_EMAIL', None) user_token = kwargs.get('PT_USER_TOKEN', None) global PT_RETENTION_TIMEOUT PT_RETENTION_TIMEOUT = kwargs.get('PT_RETENTION_TIMEOUT') rb.helpers.set_tag_mapping(kwargs.get('TAG_MAPPING')) rb.helpers.set_test_fields(kwargs.get('PT_TEST_FIELDS')) rb.helpers.set_test_set_fields(kwargs.get('PT_TEST_SET_FIELDS')) self._debug = is_truthy(kwargs.get('PT_DEBUG', False)) self.run_mode = sh.TaskType.Foreground if self._debug else sh.TaskType.Synchron logger.debug(f"Run mode set: {self.run_mode.name}") self.version = kwargs.get('PT_VERSION') self.external_run_id = kwargs.get('PT_EXTERNAL_RUN_ID') self.test_set_level = kwargs.get('PT_TEST_SET_LEVEL', 0) self.api_client = pt.PtClient(endpoint, project_name=project, tester_name=tester_name, user_email=user_email, user_token=user_token, foreground=kwargs.get('PT_FOREGROUND', False)) self.api_client.initiate_session() self.init_adapter(self.api_client) self.enabled_reporting = True logger.info( 'PractiTest report enabled; Session info:' 'endpoint={0}, project={1}, User={2}'.format(endpoint, project, tester_name)) except AssertionError as e: robot_logger.info(f"{e}", also_console=True) except Exception as e: f, li = get_error_info() logger.warning(f"{e}; File: {f}:{li}") else: logger.warning('Practitest service already initialized.') def close(self): if not self.enabled_reporting: return """Terminate common PractiTest API Client.""" sh.Task.shutdown() if self.api_client is not None: self.api_client.terminate_session() def test_set_post_process(self, suite): def _(): self._metadata_collection.append(dict(suite=suite.name, project_id=self.project_id, **self.get_active_test_set_id(20))) return _ def start_suite(self, suite: ESuite, *_): """Call start_test method of the common client. :param result: :param suite: model.Suite object :return: """ try: if suite.parent is None: self.init_api(**read_variables(*config.PRACTI_TEST_VARIABLES)) if not self.enabled_reporting: return pt_suite = rb.wrappers.PTestSuite(suite) logger.debug(f"Suite '{pt_suite.test_set_name()}' started") if len(rb.wrappers.get_parents_path(suite)) == self.test_set_level: system_fields, custom_fields, tags = update_fields(self.test_set_info_fields, pt_suite) pt_suite_name = pt_suite.test_set_name(run_id=self.external_run_id) sh.Task(self.start_test_set, pt_suite_name, system_fields.get('Version'), self.test_set_post_process(suite), tags=list(tags), **custom_fields).run(self.run_mode) self._init_suite_required = suite.has_tests except Exception as e: f, li = get_error_info() logger.error(f"Start suite {suite.name} [Error: {e}; File: {f}:{li}]") def end_suite(self, suite: ESuite, *_): if not self.enabled_reporting: return if suite.parent is None: pt_suite = rb.wrappers.PTestSuite(suite) logger.debug(f"Suite '{pt_suite.test_set_name()}' ended; Pending scheduled task completion...") statuses = {st.TestStates.Status.name: (st.TestStatuses.NotRun, st.TestStatuses.Pending)} sh.Task.shutdown(None, self.show, st.TestStates.Robot, st.TestStates.Status, **statuses) rb.helpers.publish_to_metadata("PractiTest reports", *self._metadata_collection) if adapter.MISSED_TEST_IDs: logger.warning("PractiTest: Following tests not found: {}".format( ', '.join([f'{i}' for i in set(adapter.MISSED_TEST_IDs)]) )) rb.helpers.log_report("PractiTest reports", self.show(st.TestStates.Robot, st.TestStates.PractiTest, st.TestStates.ID, st.TestStates.Status, html=True), *self._metadata_collection) def start_test(self, test: ETest, *_): if not self.enabled_reporting: return try: if self._init_suite_required: self.add_suite_tests(rb.wrappers.PTestSuite(test.parent)) self._init_suite_required = False test_p = rb.wrappers.PTestCase(test) logger.info(f"Test '{test_p.pt_name}' started") system_fields, custom_fields, tags = update_fields(self.test_set_info_fields, test_p) sh.Task(self.create_test_instance, test_p.name, test_p.pt_name, tags, test.tags, test_p.parent, test_p.pt_description, system_fields.get('Version'), *test_p.steps, **custom_fields).run(self.run_mode) except Exception as e: f, li = get_error_info() logger.warning(f"Start test: {test.name} [Error: {e}; File: {f}:{li}]") def end_test(self, test: ETest, result: RTest): if not self.enabled_reporting: return try: test_p = rb.wrappers.PTestCase(test) logger.info(f"Test '{test_p.pt_name}' ended") result_p = rb.wrappers.PTestResult(result) sh.Task(self.set_test_results, test_p, result_p).run(sh.TaskType.Asynchron if self.run_mode == sh.TaskType.Synchron else self.run_mode) except Exception as e: f, w = get_error_info() logger.warning(f"End test {test.name} [Error: {e}; File: {f}:{w}]") __all__ = [ 'Listener' ]
/robotframework_practitest-1.2.53-py3-none-any.whl/robotframework_practitest/listener.py
0.787032
0.199678
listener.py
pypi
from __future__ import annotations from enum import Enum from typing import Iterable, Dict, Any, List, Tuple from robot.libraries.BuiltIn import BuiltIn from .robot.wrappers import PTestSuite, PTestCase class PT_FieldTypes(Enum): Custom = 'custom' System = 'system' @staticmethod def from_str(string: str): return PT_FieldTypes[string.capitalize() if string else PT_FieldTypes.Custom.name] def extract_robot_tag(item: PTestSuite | PTestCase) -> Iterable[str]: if isinstance(item, PTestSuite): return list(item.all_tags()) elif isinstance(item, PTestCase): return item.pt_tags[0] def extract_robot_suite_name(item: PTestSuite | PTestCase) -> Dict[str, Any]: return item.name class FieldMapping(Enum): robot_tags = 'extract_robot_tag' robot_suite_name = 'extract_robot_suite_name' @staticmethod def from_str(mapper): callback_name = FieldMapping[mapper.lower()].value return globals()[callback_name] class FieldFormatters(Enum): coma_separated_string = lambda *items: ', '.join(items) @staticmethod def from_str(formatter): try: FieldFormatters[formatter.lower()] except KeyError: return lambda item: item class StaticField: def __init__(self, **kwargs): self.type = self.__class__.__name__ self.name = kwargs.get('name', kwargs.get('id', None)) self.default = kwargs.get('default', None) self.formatter = FieldFormatters.from_str(kwargs.get('formatter', '')) self.match_value = kwargs.get('match_value', None) def __call__(self, *args, **kwargs) -> Dict[str, Any]: return {self.name: self.formatter(self.default)} class MappedField(StaticField): def __init__(self, **kwargs): super().__init__(**kwargs) self.map_cb = FieldMapping.from_str(kwargs.get('map')) def __call__(self, *args, **kwargs): return {self.name: self.map_cb(*args, **kwargs)} class VariableField(StaticField): def __init__(self, **kwargs): super().__init__(**kwargs) self.variable = kwargs.get('variable') assert self.variable, f"{self.type} -> Variable name missing" @property def decorated(self): return f"${{{self.variable}}}" def __call__(self, *args, **kwargs): value = BuiltIn().get_variable_value(self.decorated, self.default) try: assert value is not None, f"{self.type}: Variable '{self.variable}' are mandatory" except AssertionError as e: if self.default is None: raise return {self.name: value} class MappingType(Enum): Mapped = MappedField Variable = VariableField Static = StaticField @staticmethod def from_setting(**field): if field.get('map', None): return MappingType.Mapped.value(**field) if field.get('variable', None): return MappingType.Variable.value(**field) return MappingType.Static.value(**field) def fields_factory(fields: Iterable[Dict]): result = {PT_FieldTypes.System: [], PT_FieldTypes.Custom: []} for field in fields: try: type_ = PT_FieldTypes.from_str(field.get('type', None)) assert type_ result[type_].append(MappingType.from_setting(**field)) except Exception as e: print(f"{e}") raise return result def update_fields(fields: Dict[PT_FieldTypes, List[StaticField]], item: PTestSuite | PTestCase) -> \ Tuple[Dict[str, StaticField], Dict[str, StaticField], List[str]]: result = {} for category, fields_collection in fields.items(): result.setdefault(category, {}) for field in fields_collection: result[category].update(**field(item)) if isinstance(item, PTestCase): tags, extra_cf = item.pt_tags result[PT_FieldTypes.Custom].update(**extra_cf) else: tags = item.all_tags() return result[PT_FieldTypes.System], result[PT_FieldTypes.Custom], tags __all__ = [ 'fields_factory', 'update_fields' ]
/robotframework_practitest-1.2.53-py3-none-any.whl/robotframework_practitest/models/field_adapter.py
0.829871
0.271783
field_adapter.py
pypi
from __future__ import annotations import os.path import re from typing import Callable from robotframework_practitest import utils from robotframework_practitest.utils.logger import logger from robotframework_practitest.models import practi_test as pt, robot as rb from robotframework_practitest.models.field_adapter import fields_factory from robotframework_practitest.models.practi_test import data_formatters as df from robotframework_practitest.models.robot.helpers import get_test_fields, get_test_set_fields from robotframework_practitest.services import data_queue as data, configuration, statistics as st MISSED_TEST_IDs = [] def convert_test_display_to_id(client, *tags): kwargs = {'enforce_result': True, 'timeout': 3} related_test_display_ids = rb.helpers.get_related_test_display_ids(*tags) result_test_ids = [] for display_id in related_test_display_ids: try: kwargs.update(**{'formatter': df.filter_test_by_display_id(display_id), 'display-ids': display_id}) test_d = client.query_test(**kwargs) assert test_d result_test_ids.append(test_d['id']) except Exception as e: global MISSED_TEST_IDs MISSED_TEST_IDs.append(display_id) return result_test_ids class RobotToPractiTest_Adapter(st.DataStatistics): def __init__(self): super().__init__() self._client: pt.PtClient = None self.test_set_hash_tag = None self.test_info_fields = {} self.test_tag_mapping = {} self.test_set_info_fields = {} self._involved_tags = [] self._current_suite_cache = {} self.enabled_reporting = False self.test_set_level = None self.current_suite_path_list = [] self.external_run_id = None def init_adapter(self, client: pt.PtClient): self._client = client self.test_info_fields = fields_factory(get_test_fields()) self.test_set_info_fields = fields_factory(get_test_set_fields()) logger.info(f"Robot to PractiTest Adapter ready") @property def project_id(self): return self._client.project_id def add_suite_tests(self, suite: rb.wrappers.PTestSuite): try: tests_info = [(test.name, test.parent) for test in suite.tests] for test, path in tests_info: self.set_tests(st.TestStates.Robot, test, path=path) logger.info("\nPractiTest reporter: Suite '{0}' tests added:\n\t:{1}".format( suite.name, '\n\t'.join([f"{t} ({p})" for t, p in tests_info]))) except Exception as e: f, li = utils.get_error_info() logger.error(f"{type(e).__name__}: {e}; File: {f}:{li}") def get_active_test_set_id(self, timeout=None): timeout = timeout or data.DEFAULT_ITEM_WAIT timeout += self._client.active_timeout try: return data.DataQueueService().wait(data.CacheItem(self._client.test_set_tag, self.test_set_hash_tag), timeout) except Exception as e: self.enabled_reporting = False logger.error(f"Cannot occur active test set; reporting to PractiTest not allowed:\n\t{e}") def start_test_set(self, name, version, post_process: Callable = None, tags: list = None, **test_set_info): try: test_set_formatter = lambda data_: dict(id=data_['data']['id'], display_id=data_['data']['attributes']['display-id'], set_name=data_['data']['attributes']['name'], ) self.test_set_hash_tag = self._client.create_test_set(name, version=version, formatter=test_set_formatter, ignore_cache=True, tags=tags, **test_set_info) if post_process: post_process() logger.info(f"TestSet#{self.get_active_test_set_id()['display_id']}: Created from suite '{name}'") except Exception as e: f, w = utils.get_error_info() logger.error(f"PractiTest start_test_set: Cannot create TestSet '{name}'; Error: {e}; File: {f}:{w}") self.enabled_reporting = False raise def create_test_instance(self, robot_name, pt_name, tags, pure_tags, path, description, version, *steps, **custom_fields): test_data = self._get_or_create_test(robot_name, pt_name, tags, description, version, *steps, **custom_fields) self.set_tests(st.TestStates.PractiTest, robot_name, status=st.TestStatuses.Pending, path=path, update=pt_name, id_=f"Test#{test_data['attributes']['display-id']}") test_id = test_data['id'] related_tests_list = convert_test_display_to_id(self._client, *pure_tags) full_tests_list = set([test_id] + related_tests_list) instance_list = [] test_set_id = self.get_active_test_set_id(self._client.active_timeout).get('id') for id_ in full_tests_list: try: hash_tag = f"{test_set_id}_{id_}" self._client.create_test_instance(test_set_id, id_, version, hash_tag=hash_tag, formatter=lambda d: d['data']['id']) instance_list.append(hash_tag) logger.info(f"Test '{robot_name}': Run Instance created with name '{pt_name}' (Id: {test_id})") except Exception as e: f, w = utils.get_error_info() logger.error( f"PractiTest create_test_instance: " f"Cannot add '{robot_name}' (Test#{id_}) to TestSet ({self.test_set_hash_tag}) " f"[Error: {e}; File: {f}:{w}]" ) data.DataQueueService()[data.CacheItem('run_instances', pt_name)] = set(instance_list) def _get_or_create_test(self, robot_name, pt_name, tags, description, version, *steps, **custom_fields): attempts = 0 while True: test_data = self._client.query_test(name_exact=pt_name, ignore_cache=True, enforce_result=True, formatter=df.filter_test_by_name(pt_name), timeout=5) if test_data: logger.debug(f"Test {pt_name} already existing") return test_data try: assert attempts <= rb.helpers.TEST_ALLOWED_CREATE_ATTEMPTS, \ f"Cannot get or create test '{robot_name}' during {attempts} attempts" test_data = self._client.create_test_case(pt_name, version=version, description=description, tags=tags, steps=steps, ignore_cache=True, formatter=df.filter_test_by_name(pt_name), **custom_fields) logger.warning(f"Test '{robot_name}' created as '{pt_name}' successfully") return test_data except AssertionError as e: logger.error(e) raise except Exception as e: logger.error(f"Error creating test '{robot_name}': {e}") raise finally: attempts += 1 def set_test_results(self, test: rb.wrappers.PTestCase, results: rb.wrappers.PTestResult): try: test_name = rb.helpers.get_name(test.name, *test.parent) related_test_list = data.DataQueueService().wait(data.CacheItem('run_instances', test_name), configuration.WAIT_FOR_TEST_CREATED) logger.info(f"Result: {results.name}; {results.status}; Duration: {results.duration}") for index, instance in enumerate(related_test_list): try: set_id, test_id = instance.split('_', 1) instance_id = data.DataQueueService().wait(data.CacheItem(self._client.instance_tag, instance)) files = [] if len(results.automated_execution_output) > 255: file_path = utils.write_to_temp_file(results.automated_execution_output, name=re.sub(r'\\|\/|\s+', '_', test.name), suffix=f"{instance_id}.txt") file_name = os.path.basename(file_path) files.append(file_path) automated_execution_output = f"Output redirected to file: {file_name}" else: automated_execution_output = results.automated_execution_output self._client.create_run(instance_id, results.exit_code, results.duration, automated_execution_output, files=files) logger.info( f"PractiTest Reporter: {'Robot' if index == 0 else 'Referenced'} Test '{test_name}' " f"completed: {results.status} (TestSet: {set_id}, Test: {test_id}, Instance {instance_id})") except Exception as e: logger.error(f"PractiTest Reporter: Error report result for test '{test_name}': {e}") else: self.set_tests(st.TestStates.Status, test.name, status=st.TestStatuses[results.status], path=test.parent) except Exception as e: f, w = utils.get_error_info() logger.error(f"PractiTest set_test_results {test.name} [Error: {e}; File: {f}:{w}]") raise
/robotframework_practitest-1.2.53-py3-none-any.whl/robotframework_practitest/models/adapter.py
0.590661
0.344223
adapter.py
pypi
from __future__ import annotations import re from datetime import datetime from enum import Enum from typing import Mapping, AnyStr, Callable, Tuple, List, Dict from robot.libraries.BuiltIn import BuiltIn from robot.api import logger as robot_logger from robotframework_practitest.utils.misc_utils import get_error_info from robotframework_practitest.utils.logger import logger from robotframework_practitest.services.configuration import get_default_value from robotframework_practitest.models.practi_test.client import PT_PRODUCT_URL class PT_MANAGED_ITEMS(Enum): Test = 'TEST_FIELDS' TestSet = 'TEST_SET_FIELDS' # Instance = 'INSTANCE_FIELDS' TEST_ALLOWED_CREATE_ATTEMPTS = 3 TAG_MAPPING = {} # TAG_MAPPING = dict( # TEST={'prefix': 'Test-'}, # FIELD={'prefix': 'Custom-', 'delimiter': '-'} # ) PT_DATE_TIME_FORMAT = "%d-%m-%Y %H:%M:%S" def set_tag_mapping(tag_mapping): global TAG_MAPPING TAG_MAPPING = tag_mapping def get_tag_mapping(): global TAG_MAPPING return TAG_MAPPING TEST_FIELDS = {} def set_test_fields(test_fields): global TEST_FIELDS TEST_FIELDS = test_fields def get_test_fields(): global TEST_FIELDS return TEST_FIELDS TEST_SET_FIELDS = {} def set_test_set_fields(test_set_fields): global TEST_SET_FIELDS TEST_SET_FIELDS = test_set_fields def get_test_set_fields(): global TEST_SET_FIELDS return TEST_SET_FIELDS def get_test_steps_info(*keywords): return [{'name': k.name, 'description': k.doc} for k in keywords] def get_related_test_display_ids(*tag_list): test_map = get_tag_mapping().get('TEST') return [t.replace(test_map.get('prefix'), '') for t in tag_list if t.startswith(test_map.get('prefix'))] def get_related_fields(*tag_list, **tag_mapping) -> Mapping[AnyStr, AnyStr]: test_map = tag_mapping.get('FIELD') field_data = [t.replace(test_map.get('prefix'), '').split('-', 1) for t in tag_list if t.startswith(test_map.get('prefix'))] return {t[0]: t[1] for t in field_data} def get_common_robot_tags(*tag_list, **kwargs): return [t for t in tag_list if all([not t.startswith(p) for p in [f.get('prefix') for f in get_tag_mapping().values()]])] def get_field_by_tag(name, *tags): return get_related_fields(*tags).get(name, None) def update_variable_scope_from_tags(default): def _(*tags, **variables): for var, value in variables.items(): try: if isinstance(value, tuple) and isinstance(value[0], Callable): yield var, get_related_fields(*tags, **get_tag_mapping().get(var, None)) or value[1] else: yield var, value except Exception as e: f, li = get_error_info() logger.error(f"{e}; File: {f}:{li}") class FieldUpdate(Enum): TAGS = update_variable_scope_from_tags, ROBOT_TAGS = get_common_robot_tags @staticmethod def from_string(pattern: str, default): return FieldUpdate[pattern.upper()] def formate_test_tags(*tag_list) -> Tuple[List[str], Dict[str, AnyStr]]: def _except_fields(item): return any((item.startswith(f.get('prefix', '_')) for f in get_tag_mapping().values())) field_map = get_tag_mapping().get('FIELD') tags = sorted([t for t in tag_list if not _except_fields(t)]) custom_fields = {i[0]: i[1] for i in [t.replace(field_map.get('prefix'), '').split(field_map.get('delimiter')) for t in tag_list if t.startswith(field_map.get('prefix'))]} return tags, custom_fields def format_kw_list(kws: list): result = '' for index, item in enumerate(kws): if index == 0: result += item elif item == 'AND': result += '\n\t' + item else: result += '\n\t\t' + item return result def get_robot_variables_map(fields: list, *fields_map, **variables): for field in [f for f in fields_map if f.get('name') in fields]: robot_variable = field.get('variable', None) if robot_variable: value = variables.get(robot_variable, field.get('default', None)) yield field.get('name'), value def _clean_path(clean_regex, *path, **kwargs): delimiter = kwargs.get('delimiter', '/') return delimiter.join([re.sub(clean_regex, '', p) for p in path]) def get_name(name, *path, **kwargs): name = name.strip() delimiter = kwargs.get('delimiter', '/') start_level = kwargs.get('level', get_default_value('PT_TEST_NAME_LEVEL')) path = list([re.sub(r'^[\d]+[\s|_]+', '', p) for p in path]) run_id = kwargs.get('run_id', None) result = [] if path: result.append("{}".format(f"Path:{delimiter.join(path[start_level:])}")) if run_id: if run_id == 'datetime': result.append(f"TS: {datetime.now().strftime(PT_DATE_TIME_FORMAT)}") else: result.append(f"ExternalID:{run_id}") return f"{name} ({' '.join(result)})" if result else name def publish_to_metadata(report_name, *meta_collection): meta_msg = "{}".format( '\n\t'.join(["[{url}|TestSet#{display_id}]".format(num=i + 1, **n) for i, n in enumerate([dict(url=PT_PRODUCT_URL.format(**m), **m) for m in meta_collection])])) BuiltIn().set_suite_metadata(report_name, meta_msg) def log_report(report_name, test_mapping=None, *meta_collection): log_msg = "{}:\n\t{}{}".format( report_name, '\n\t'.join(["{num:02d}. Suite: {suite} -> <a href=\"{url}\">TestSet#{display_id}</a>".format(num=i + 1, **n) for i, n in enumerate([dict(url=PT_PRODUCT_URL.format(**m), **m) for m in meta_collection])]), f"\n\nTest list:\n{test_mapping}" if test_mapping else '' ) robot_logger.warn(log_msg, html=True) DATA_DRIVER_FIELD_DELIMITER = r',|\|' def data_driver_test_name_formatter(test_name): return re.split(DATA_DRIVER_FIELD_DELIMITER, test_name)[0].strip()
/robotframework_practitest-1.2.53-py3-none-any.whl/robotframework_practitest/models/robot/helpers.py
0.574037
0.239917
helpers.py
pypi
import itertools as it import re from collections import OrderedDict import pandas as pd from robot.api import logger from robot.errors import RobotError from robot.libraries.BuiltIn import BuiltIn from DataDriver.AbstractReaderClass import AbstractReaderClass from DataDriver.ReaderConfig import TestCaseData DEFAULT_PREFIX = 'arg' def _flat_iterator(*source): _result = [] for k in source: if isinstance(k, (tuple, list)): _result.extend(_flat_iterator(*k)) else: _result.append(k) return _result def all_permutation(*source): return [_flat_iterator(*_value) for _value in it.product(*source)] def _pairs_permutation(*source): raise NotImplementedError() PERMUTATION_METHOD = { 'all': all_permutation, 'pair': _pairs_permutation } def parse_permutations(prefix='arg', permutation_mode='all', **kwargs) -> pd.DataFrame: eq_cls = OrderedDict() err = [] for var, item in {k: v for k, v in kwargs.items() if k.startswith(prefix)}.items(): try: _list = re.split(r'\s*:\s*', item, 2) var_names, items = tuple(re.split(r'\s*,\s*', _list[0])), re.split(r'\s*,\s*', _list[1]) if items[0] == 'kw': kw, kw_args = items[1], items[2:] values = BuiltIn().run_keyword(kw, *kw_args) else: values = items except Exception as e: err.append(f"Item ({var}: {item}) raise error: {e}") else: eq_cls[var_names] = values if len(err) > 0: raise RobotError("Following permutations raising errors:\n\t{}".format('\n\t'.join(err))) _data = PERMUTATION_METHOD[permutation_mode](*eq_cls.values()) _columns = _flat_iterator(*eq_cls.keys()) _index = [i+1 for i, _ in enumerate(_data)] _data_frame = pd.DataFrame(data=_data, columns=_columns, index=_index) return _data_frame class courtesy_generator(AbstractReaderClass): __doc__ = """Courtesy generator are DataDriver extension for create data driven test from courtesan multiplication between provided lists Test Suite usage: Library DataDriver reader_class=../../py/data_generators/courtesy_generator.py ... file_search_strategy=None ... prefix='prefix pattern' (Default: arg) ... tags=Attack,Sanity ... arg1=binary:kw,ReadBinaryList,${BINARY_PATH} ... arg2=mode:Blocking, NonBlocking ... permutation=all| pairs; (Default: all - currently supported only) Where: tags: must return same tags as in 'Force Tags' of suite arg1, arg2, ...: (bonded variable group separated by coma): [Options] Options: 1. Elements for iteration separated by coma 2. If first are 'kw', second handled as keyword name, rest handles as keyword arguments (As following from usage of 'run keyword' of BuiltIn library Note: provided keyword must return list of tuples correlated to bonded variables count Assumption: Iteration calculating between arguments with prefix only """ def get_data_from_source(self): test_data = [] _tags = [t.strip() for t in re.split(r'\s*,\s*', self.kwargs.get('tags', ''))] prefix = self.kwargs.get('prefix', DEFAULT_PREFIX) permutation_mode = self.kwargs.get('permutation', 'all') data: pd.DataFrame = parse_permutations(prefix, permutation_mode, **self.kwargs) if len(data) == 0: logger.info("[ DataDriver ] empty data source created", also_console=True) return test_data logger.info("[ DataDriver ] data source created:\n\t{}".format(data), also_console=True) for index, item in data.iterrows(): _args = {f"${{{var}}}": value for var, value in dict(item).items()} _documentation = "Test for {}".format( ', '.join([f'{var}: {value}' for var, value in dict(item).items()]) ) test_data.append(TestCaseData(_documentation, _args, _tags, _documentation)) return test_data __all__ = [ 'courtesy_generator', all_permutation.__name__ ]
/robotframework_practitest-1.2.53-py3-none-any.whl/robotframework_practitest/utils/courtesy_generator.py
0.468061
0.219087
courtesy_generator.py
pypi
import json import time from threading import RLock from time import sleep from typing import Mapping, Any, Iterator, Callable from robotframework_practitest.utils.logger import logger from robotframework_practitest.utils.misc_utils import get_error_info from robotframework_practitest.utils.singleton import Singleton DEFAULT_ITEM_WAIT = 0.2 class CacheItem: def __init__(self, area, key, formatter: Callable = None): self.Area = area self.Key = key self.Formatter = formatter def __eq__(self, other): try: assert isinstance(other, CacheItem) assert self.Area == other.Area assert self.Key == self.Key except AssertionError: return False else: return True def __hash__(self): return hash(json.dumps(self.__dict__)) def __str__(self): return f"{self.Area}::{self.Key}" @Singleton class DataQueueService(Mapping[CacheItem, Any]): def __init__(self): self.__lock = RLock() self._cache = dict() @property def cache(self): return self._cache def __len__(self) -> int: return len(self.cache) def __iter__(self) -> Iterator[Any]: return self.cache.__iter__() def __setitem__(self, item: CacheItem, argument): with self.__lock: try: self.cache.setdefault(item.Area, dict()) value = item.Formatter(argument) if item.Formatter else argument self.cache[item.Area][item.Key] = value logger.debug(f"Update in cache: {item} -> {value}") except Exception as e: f, li = get_error_info() logger.error(f"Cannot add key '{item}:{argument}': {e}; File: {f}:{li}") def __getitem__(self, item): with self.__lock: if isinstance(item, str): value = self.cache[item] else: value = self.cache[item.Area][item.Key] logger.debug(f"Retrieve from cache: {item} -> {value}") return value def __delitem__(self, key): del self._cache[key] def keys(self): return self._cache.keys() def wait(self, item, timeout=None): timeout = timeout or DEFAULT_ITEM_WAIT start_ts = time.perf_counter() while (time.perf_counter() - start_ts) < timeout: try: return self[item] except KeyError: sleep(DEFAULT_ITEM_WAIT) # finally: # logger.debug(f"Result got in {time.perf_counter() - start_ts:.02f}s.") raise KeyError(f"Key '{item}' not found") DEFAULT_CACHE_TIMEOUT = 65 __all__ = [ 'DataQueueService', 'CacheItem', 'DEFAULT_ITEM_WAIT' ]
/robotframework_practitest-1.2.53-py3-none-any.whl/robotframework_practitest/services/data_queue.py
0.632389
0.18691
data_queue.py
pypi
from __future__ import annotations import datetime import time from enum import Enum from time import sleep from typing import List import pandas from robotframework_practitest.utils.logger import logger from robotframework_practitest.utils import get_error_info class _Color(Enum): FAILED = 'red' PASSED = 'green' SKIPPED = 'yellow' Default = 'grey' class TestStates(Enum): Robot = 'robot' ID = 'practitest_id' PractiTest = 'practi_test' Status = 'status' Path = 'path' @staticmethod def as_tuple(): return TestStates.Robot, TestStates.PractiTest, TestStates.ID, TestStates.Status class TestStatuses(Enum): NotRun = 'not_run' Pending = 'Pending' PASSED = 'passed' FAILED = 'failed' SKIPPED = 'skipped' class RowItem(dict): def __init__(self, **kwargs): for col in TestStates: self[col.name] = kwargs.get(col.name, None) def __str__(self): return ', '.join([f"{col.name}={getattr(self, col.name)}" for col in TestStates]) def __eq__(self, other): try: assert isinstance(other, type(self)) assert other[TestStates.Robot.name] == self[TestStates.Robot.name] assert other[TestStates.Path.name] == self[TestStates.Path.name] except AssertionError: return False else: return True class _TestTable(list, List[RowItem]): def set_tests(self, col: TestStates, *tests, status: TestStatuses = None, path=None, update=None, id_=None): if path is None: path = [] if col == TestStates.Robot: for test in tests: row_item = RowItem(**{TestStates.Robot.name: test, TestStates.PractiTest.name: '-', TestStates.Status.name: TestStatuses.NotRun.name, TestStates.Path.name: path}) self.append(row_item) elif col == TestStates.PractiTest: for test in tests: for i, item in enumerate(self): current_item = RowItem(**{TestStates.Robot.name: test, TestStates.Path.name: path}) if current_item == self[i]: self[i][TestStates.PractiTest.name] = update if id_: self[i][TestStates.ID.name] = id_ if status: self[i][TestStates.Status.name] = status.name break elif col == TestStates.Status: assert status, f"State {col.name} require status" for test in tests: for i, item in enumerate(self): current_item = RowItem(**{TestStates.Robot.name: test, TestStates.Path.name: path}) if current_item == self[i]: self[i][TestStates.Status.name] = status.name break def as_dict(self, *columns, **filters): columns = columns if len(columns) > 0 else TestStates.as_tuple() res_dict = {col.name: [] for col in columns} for row in self: if len(filters) > 0: for field, value in filters.items(): if isinstance(value, (list, tuple)): if row.get(field) not in (v.name for v in value): continue else: if row.get(field) != value.name: continue for col in columns: res_dict[col.name].append(row.get(col.name)) else: for col in columns: res_dict[col.name].append(row.get(col.name)) return res_dict def df(self, *columns, **filters): return pandas.DataFrame.from_dict(self.as_dict(*columns, **filters)) @staticmethod def _field_formatter(value): return value @staticmethod def _status_formatter(value): try: color = _Color[value] except Exception as e: color = _Color.Default return f"<font color='{color.value}'>{value}</font>" def show(self, *columns, html=False, **filters): df = self.df(*columns, **filters) pandas.set_option("display.precision", 2) pandas.set_option('display.max_rows', None) pandas.set_option('display.max_columns', None) pandas.set_option("max_colwidth", 500) pandas.set_option('display.colheader_justify', 'left') pandas.set_option('display.width', 10000) return df.to_html(justify='center') if html else df.to_string(justify='center') DataStatistics = _TestTable __all__ = [ 'TestStates', 'TestStatuses', 'DataStatistics' ]
/robotframework_practitest-1.2.53-py3-none-any.whl/robotframework_practitest/services/statistics.py
0.673406
0.292608
statistics.py
pypi
from itertools import groupby from operator import itemgetter from .constants import * class FormatterPayloadAzure: def __init__(self): pass @staticmethod def format_testpoint(testpoints): return [{"id": testpoint['id'], 'planId':testpoint['testPlan']['id'], 'suiteId':testpoint['suite']['id'], 'status':testpoint['status']} for testpoint in testpoints] @staticmethod def update_status_testcases(testpoints, outcomes): for testpoint in testpoints: testpoint['status'] = STATUS_RBF[outcomes[testpoint['testCase']['id']]] return testpoints @staticmethod def format_testpoint_payload(testpoint): print(testpoint) return {"id": testpoint['id'], "results": {"outcome": testpoint['status']}} @staticmethod def format_payload_update_testspoints(testpoints, outcomes): testpoints = FormatterPayloadAzure.update_status_testcases( testpoints, outcomes) testpoints = FormatterPayloadAzure.format_testpoint(testpoints) tests = sorted(testpoints, key=itemgetter('planId', 'suiteId')) outcomes = {} for key, value in groupby(tests, key=itemgetter('planId', 'suiteId')): outcomes[key] = [ FormatterPayloadAzure.format_testpoint_payload(k) for k in value] return outcomes @staticmethod def format_payload_create_runs(suites): for suite in suites: testpoints = FormatterPayloadAzure.update_status_testcases( testpoints, outcomes) testpoints = FormatterPayloadAzure.format_testresult_payload( testpoints) tests = sorted(testpoints, key=itemgetter('planId', 'suiteId')) outcomes = {} for key, value in groupby(tests, key=itemgetter('planId', 'suiteId')): outcomes[key] = [ FormatterPayloadAzure.format_testpoint_payload(k) for k in value] return outcomes @staticmethod def format_testresults_payload(testresults,runBy): return [{ "AutomatedTestName": testresult['name'], "comment": "", "createdDate": "", "completedDate": "", "durationInMs": float(testresult['elapsedtime']), "errorMessage": testresult['message'], "owner": testresult['assignedTo'], "runBy": { "displayName": runBy }, "state": "Completed", "testCaseTitle": testresult['name'], "testCase": testresult['testCase'], "testPoint": { "id": testresult['id'] }, "testPlan": testresult['testPlan'], "priority": 1, "outcome": testresult['status'], "testCaseRevision": 1 } for testresult in testresults ]
/robotframework-publisher-results-azure-2.0.1.tar.gz/robotframework-publisher-results-azure-2.0.1/PublisherAzureTestsResults/formatterPayloadAzure.py
0.664758
0.302789
formatterPayloadAzure.py
pypi
import os from robot.api import logger from base64 import b64encode from functools import wraps import pycurl from url import Url THIS_DIR = os.path.dirname(os.path.abspath(__file__)) execfile(os.path.join(THIS_DIR, 'version.py')) __version__ = VERSION __all__ = ['include', 'verbose', 'insecure', 'add_header', 'headers_file', 'post_fields', 'post_fields_file', 'request_method', 'data_file', 'set_url', 'ca_path', 'cert', 'key', 'perform', 'response', 'response_header' ] class PycURLLibrary(): """PycURLLibrary is a library for functional testing with URL syntax, supporting DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP. PycURLLibrary supports SSL certificates and more. PycURLLibrary is based on PycURL [http://pycurl.sourceforge.net/], PycURL is a Python interface to libcurl [http://curl.haxx.se/libcurl/]. xml.etree.ElementTree [http://docs.python.org/2/library/xml.etree.elementtree.html] is used for XML operations. Supported XPath syntax (from Python v2.7.5 documentation): | Syntax | Meaning | | tag | Selects all child elements with the given tag. For example, spam selects all child elements named spam, spam/egg selects all grandchildren named egg in all children named spam. | | * | Selects all child elements. For example, */egg selects all grandchildren named egg. | | . | Selects the current node. This is mostly useful at the beginning of the path, to indicate that it’s a relative path. | | // | Selects all subelements, on all levels beneath the current element. For example, .//egg selects all egg elements in the entire tree. | | .. | Selects the parent element. | | [@attrib] | Selects all elements that have the given attribute. | | [@attrib='value'] | Selects all elements for which the given attribute has the given value. The value cannot contain quotes. | | [tag] | Selects all elements that have a child named tag. Only immediate children are supported. | | [position] | Selects all elements that are located at the given position. The position can be either an integer (1 is the first position), the expression last() (for the last position), or a position relative to the last position (e.g. last()-1). | """ ROBOT_LIBRARY_VERSION = VERSION ROBOT_LIBRARY_SCOPE = "TEST CASE" ROBOT_LIBRARY_DOC_FORMAT = "ROBOT" def __init__(self): self._logger = logger self._url = Url() def verbose(self): """Makes the fetching more verbose/talkative. Mostly useful for debugging. A line starting with '>' means "header data" sent by curl, '<' means "header data" received by curl that is hidden in normal cases, and a line starting with '*' means additional info provided by curl. Note that if you only want HTTP headers in the output, -i, --include might be the option you're looking for. If you think this option still doesn't give you enough details, consider using --trace or --trace-ascii instead. This option overrides previous uses of --trace-ascii or --trace. """ self._url.set_verbose(True) # def no_buffer(self): # """Disables the buffering of the output stream. # # In normal work situations, curl will use a standard buffered output stream that will have the effect that it will output the data in chunks, # not necessarily exactly when the data arrives. Using this option will disable that buffering. # Note that this is the negated option name documented. You can thus use --buffer to enforce the buffering. # """ def server_connection_establishment_timeout(self, timeout): """The maximum time in seconds that you allow the connection to the server to take (long value). This only limits the connection phase, once it has connected, this option is of no more use. Set to zero to switch to the default built-in connection timeout - 300 seconds. """ self._url.get_context().set_server_connection_establishment_timeout(long(str(timeout))) def insecure_ssl(self): """(SSL) This option explicitly allows curl to perform "insecure" SSL connections and transfers. All SSL connections are attempted to be made secure by using the CA certificate bundle installed by default. This makes all connections considered "insecure" fail unless -k, --insecure is used. """ self._url.set_insecure(True) def request_method(self, requestMethod): """ Set's the request method. Default's to GET if Post Fields keyword is used POST is used | Method | | GET | | POST | | PUT | | DELETE | """ self._url.get_context().set_request_method(requestMethod) def add_header(self, header): """(HTTP) Extra header to use when getting a web page. Each *Add Header* keyword is equivalent for one <-H, --header> argument with curl Examples: | Add Header | Content-Type: text/xml; charset=UTF-8 | | Add Header | Frame.Version:3.0 | """ self._logger.info('Header %s' % header) self._url.get_context().add_header(str(header)) def headers_file(self, headerFile): """(HTTP) Extra headers to use when getting a web page. *headerFile* contains all headers. One line is one header. Note do not make line feed after last header. Example: | Headers File | /data/headers.txt | Example of content of *headerFile*: | Version: 2 | | Content-Type: text/xml; charset=UTF-8 | """ headers = [line.rstrip() for line in open(headerFile, 'r')] self._logger.info('Headers %s' % headers) self._url.get_context().set_headers(headers) def post_fields(self, postFields): """(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Equivalent for <--data> argument Example: | Post Fields | pizza=Quattro+Stagioni&extra=cheese | """ self._url.set_post_fields(postFields) if postFields is not None: self._url.get_context().set_request_method('POST') def post_fields_file(self, postFieldsFile): """(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Equivalent for <--data> @argument Example: | Post Fields File | /data/message.txt | """ f = open(postFieldsFile, 'r') postFields = f.read() f.close() self._url.set_post_fields(postFields) self._url.get_context().set_request_method('POST') def set_url(self, url): """Specify a URL to fetch. """ self._url.get_context().set_url(str(url)) def ca_path(self, cacertDirectory): """(SSL) Tells curl to use the specified certificate directory to verify the peer. Multiple paths can be provided by separating them with ":" (e.g. "path1:path2:path3"). The certificates must be in PEM format. Equivalent for <--capath> argument with curl """ self._url.get_context().set_capath(str(cacertDirectory)) def client_certificate_file(self, cert): """(SSL) Tells curl to use the specified client certificate file when getting a file with HTTPS, FTPS or another SSL-based protocol. The certificate must be in PEM format Equivalent for <--cert> argument with curl """ self._url.get_context().set_client_certificate_file(str(cert)) def private_key_file(self, key): """(SSL/SSH) Private key file name. Allows you to provide your private key in this separate file. Equivalent for <--key> argument with curl """ self._url.get_context().set_private_key_file(str(key)) def perform(self): """Perform curl perform. """ self._url.perform() def response(self): """Get response from latest perform result """ return self._url.get_context().get_response() def response_headers(self): """Get response headers from latest perform result for protocols having headers preceding the data (like HTTP) """ return self._url.get_context().get_response_headers() def parse_xml(self): """Parses an XML section of the response. Returns an root Element instance. """ return self._url.get_context().parse_response_xml() def xml_root_element(self): """Returns the result root Element instance of `Parse Xml` keyword. """ return self._url.get_context().get_xml_root_element() def find_elements(self, element, xpath): """Returns a list containing all matching elements in document order Examples: | Find Elements | ${root} | .//{http://ws.poc.jivalo/hello/v1}customer | | Find Elements | ${root} | .//name | """ assert element is not None, \ 'Element is Null.' xp = str(xpath) return element.findall(xp) def find_first_element(self, element, xpath): """Finds the first subelement matching *xpath*. Match may be a _tag name_ or _path_. Returns an element instance or None. Examples: | Find First Element | ${root} | .//{http://ws.poc.jivalo/hello/v1}customer | | Find First Element | ${root} | .//name | """ assert element is not None, \ 'Element is Null.' xp = str(xpath) return element.find(xp) def should_contain_element(self, element, xpath): """Fails if the *element* does not contain *xpath* element Examples: | Should Contain Element | ${root} | .//{http://ws.poc.jivalo/hello/v1}customer | | Should Contain Element | ${root} | .//name | """ elements = self.find_elements(element, xpath) assert elements, \ 'Element "%s" contains not XPaht element "%s".' % ( element.tag, xpath) def element_should_contain(self, element, text): """Fails if the *element* text value does not contain *text* Examples: | Element Should Contain | ${elem} | Hello, world! | """ assert text in element.text, \ 'Element "%s" does not contains text "%s".' % ( element.tag, text) def element_should_match(self, element, text): """Fails if the *element* text value does not match *text* Examples: | Element Should Match | ${elem} | Hello, world! | """ assert text == element.text, \ 'Element "%s" does not match text "%s".' % ( element.tag, text) def http_response_status(self): """Get response status from latest HTTP response status line """ return self._url.get_context().get_response_status() def response_status_should_contain(self, text): """Fails if the _Response Status_ does not contain *text* Examples: | Response Status Should Contain | 200 | """ assert str(text) in str(self.http_response_status()), \ 'Response Status "%s" does not contains text "%s".' % ( self.http_response_status(), text) def log_response(self, log_level='INFO'): """ Logs the response of the URL transfer. Specify *log_level* (default: "INFO") to set the log level. """ if self.response(): self._logger.write("Response body:", log_level) self._logger.write(self.response(), log_level) else: self._logger.debug("No response received", log_level) def log_response_headers(self, log_level='INFO'): """ Logs the response headers for protocols having headers preceding the data (like HTTP), line by line. Specify *log_level* (default: "INFO") to set the log level. """ if self.response_headers(): self._logger.write("HTTP Response headers:", log_level) for header in self.response_headers(): self._logger.write(header, log_level) else: self._logger.debug("No HTTP response headers received", log_level) def log_http_response_status(self, log_level='INFO'): """ Logs the HTTP response header status line. Specify *log_level* (default: "INFO") to set the log level. """ if self.http_response_status(): self._logger.write("HTTP Response status:", log_level) self._logger.write(self.http_response_status(), log_level) else: self._logger.debug("No HTTP response status received", log_level) def log_version(self, log_level='INFO'): """ Logs the PycURLLibrary Version. Specify *log_level* (default: "INFO") to set the log level. """ self._logger.write("PycURLLibrary version %s" % (self.ROBOT_LIBRARY_VERSION), log_level)
/robotframework-pycurllibrary-0.9.5.tar.gz/robotframework-pycurllibrary-0.9.5/src/PycURLLibrary/__init__.py
0.643105
0.289334
__init__.py
pypi
from robot.api import logger from _common import _CommonActions class _ExecutionKeywords(_CommonActions): """ Class that handles all keywords from group 'Execution'. """ def query(self, selectStatement): """ Performs query. *Arguments:* - selectStatement: string, sql select statement. *Return:* - Fetched result of performed query. *Examples:* | @{queryResults} | Query | select * from employee | """ cur = self._execute_sql(selectStatement) result = cur.fetchall() return result def description(self, selectStatement): """ Gets description of query. *Arguments:* - selectStatement: string, sql select statement. *Return:* - Description of performed query. *Examples:* | @{queryDescription} | Description | select * from employee | """ cur = self._execute_sql(selectStatement) description = cur.description return description def execute_sql(self, sqlStatement): """ Executes sql and commits it. *Arguments:* - sqlStatement: string, sql statement. *Return:* - None *Examples:* | Execute Sql | update name from employee where id=7 | """ self._execute_sql(sqlStatement, True) def read_single_value_from_table(self, tableName, columnName, whereClause): """ Reads single value from table. If there will be more than one row that satisfies performed query, \ then this will throw an AssertionError. *Arguments:* - tableName: string, table name. - columnName: string, column name or names divided by comma. *Return:* - Fetched single value. *Examples:* | @{queryResult} | Read Single Value From Table | employee \ | name, surname | age=27 | """ sqlStatement = 'SELECT %s FROM %s WHERE %s' % (columnName, tableName, whereClause) result = self.query(sqlStatement) assert len(result) == 1, \ ("Expected to have 1 row from '%s' " "but got %s rows : %s." % (sqlStatement, len(result), result)) logger.debug("Got 1 row from %s: %s." % (sqlStatement, result)) return result[0] def db_elements_are_equal(self, selectStatement, firstAliasOrIndex, secondAliasOrIndex): """ Checks that fetched results of performed query on two databases are equal. If DB elements will not be equal, then this will throw an AssertionError. *Arguments:* - selectStatement: string, sql select statement. - firstAliasOrIndex: string or int, alias or index of \ first database. - secondAliasOrIndex: string or int, alias or index of \ second database. *Return:* - None *Examples:* | DB Elements Are Equal | select name, surname from employee | \ SomeCompanyDB1 | SomeCompanyDB1 | """ result = self._get_elements_from_two_db(selectStatement, firstAliasOrIndex, secondAliasOrIndex) assert set(result[0]) == set(result[1]), \ "Expected to have equal elements but '%s' is not equal to '%s'" \ % (result[0], result[1]) logger.debug("Results fetched from %s on %s and %s databases are" " equal." % (selectStatement, firstAliasOrIndex, secondAliasOrIndex)) def db_elements_are_not_equal(self, selectStatement, firstAliasOrIndex, secondAliasOrIndex): """ Checks that fetched results of performed query on two databases are not equal. If DB elements will be equal, then this will throw an AssertionError. *Arguments:* - selectStatement: string, sql select statement. - firstAliasOrIndex: string or int, alias or index of \ first database. - secondAliasOrIndex: string or int, alias or index of \ second database. *Return:* - None *Examples:* | DB Elements Are Not Equal | select name, surname from employee | \ SomeCompanyDB1 | SomeCompanyDB1 | """ result = self._get_elements_from_two_db(selectStatement, firstAliasOrIndex, secondAliasOrIndex) assert set(result[0]) != set(result[1]), \ ("Expected to have not equal elements but they equal. " "Query result:'%s'" % (result[0])) logger.debug("Results fetched from %s on %s and %s databases are" " not equal." % (selectStatement, firstAliasOrIndex, secondAliasOrIndex)) def _get_elements_from_two_db(self, selectStatement, firstAliasOrIndex, secondAliasOrIndex): """ Gets fetched results of performed query on two databases. *Arguments:* - selectStatement: string, sql select statement. - firstAliasOrIndex: string or int, alias or index of \ first database. - secondAliasOrIndex: string or int, alias or index of \ second database. *Return:* - tuple of two results. """ currentDbIndex = self._connectionCache.current_index self.set_current_database(firstAliasOrIndex) firstResult = self.query(selectStatement) self.set_current_database(secondAliasOrIndex) secondResult = self.query(selectStatement) self.set_current_database(currentDbIndex) # Back to initial database. return firstResult, secondResult
/robotframework-pydblibrary-1.1.tar.gz/robotframework-pydblibrary-1.1/src/Pydblibrary/keywords/_execution.py
0.913657
0.553204
_execution.py
pypi
from robot.api import logger from _common import _CommonActions class _TableKeywords(_CommonActions): """ Class that handles all keywords from group 'Table'. """ def table_must_exist(self, tableName): """ Checks that table exists. If table not exist, then this will throw an AssertionError. *Arguments:* - tableName: string, table name. *Return:* - None *Examples:* | Table Must Exist | employee | """ selectStatement = ("SELECT * FROM information_schema.tables WHERE " "table_name='%s'") % tableName rowsCount = self.rows_count(selectStatement) assert rowsCount, 'Table %s does not exist.' % tableName logger.debug("Table %s exists." % tableName) def table_must_be_empty(self, tableName): """ Checks that table is empty. If table is not empty, then this will throw an AssertionError. *Arguments:* - tableName: string, table name. *Return:* - None *Examples:* | Table Must Be Empty | fired_employee | """ selectStatement = "SELECT * FROM %s" % tableName rowsCount = self.rows_count(selectStatement) assert not rowsCount, 'Table %s is not empty.' % tableName logger.debug("Table %s is empty." % tableName) def table_must_contain_less_than_number_of_rows(self, tableName, rowsNumber): """ Checks that table contains less number of rows than specified. If table contains more or equal number of rows than specified, \ then this will throw an AssertionError. *Arguments:* - tableName: string, table name. - rowsNumber: int, rows number. *Return:* - None *Examples:* | Table Must Contain Less Than Number Of Rows | fired_employee | 100 | """ selectStatement = "SELECT * FROM %s" % tableName rowsCount = self.rows_count(selectStatement) assert rowsCount < rowsNumber,\ ('Table %s has %s row(s) but should have less than %s row(s).' % (tableName, rowsCount, rowsNumber)) logger.debug("Table %s contains %s row(s)." % (tableName, rowsCount)) def table_must_contain_more_than_number_of_rows(self, tableName, rowsNumber): """ Checks that table contains more number of rows than specified. If table contains less or equal number of rows than specified, \ then this will throw an AssertionError. *Arguments:* - tableName: string, table name. - rowsNumber: int, rows number. *Return:* - None *Examples:* | Table Must Contain More Than Number Of Rows | employee | 1000 | """ selectStatement = "SELECT * FROM %s" % tableName rowsCount = self.rows_count(selectStatement) assert rowsCount > rowsNumber,\ ('Table %s has %s row(s) but should have more than %s row(s).' % (tableName, rowsCount, rowsNumber)) logger.debug("Table %s contains %s row(s)." % (tableName, rowsCount)) def table_must_contain_number_of_rows(self, tableName, rowsNumber): """ Checks that table contains equal number of rows to specified. If table contains less or nire number of rows than specified, \ then this will throw an AssertionError. *Arguments:* - tableName: string, table name. - rowsNumber: int, rows number. *Return:* - None *Examples:* | Table Must Contain Number Of Rows | chief_executive_officer | 1 | """ selectStatement = "SELECT * FROM %s" % tableName rowsCount = self.rows_count(selectStatement) assert rowsCount == rowsNumber,\ ('Table %s has %s row(s) but should have %s row(s).' % (tableName, rowsCount, rowsNumber)) logger.debug("Table %s contains %s row(s)." % (tableName, rowsCount)) def get_primary_key_columns_for_table(self, tableName): """ Gets primary key columns for specified table. *Note:* This method works only with 'psycopg2' driver. *Arguments:* - tableName: string, table name. *Return:* - Primary key columns. *Examples:* | ${key_columns} | Get Primary Key Columns For Table | employee | """ # // TODO: Extend this method to work with other drivers. driverName = self._connectionCache.current.driverName assert driverName == 'psycopg2',\ "Impossible to use this keyword with '%s' driver." % driverName selectStatement = """SELECT KU.table_name as tablename, column_name as primarykeycolumn FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME and ku.table_name='%s' ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION;""" % tableName primaryKeys = self.query(selectStatement) result = [] for table, columnName in primaryKeys: result.append(columnName.lower()) return result def check_primary_key_columns_for_table(self, tableName, columns): """ Checks that specified primary key columns equal to table key columns. If table contains less or greater number of rows than specified, then this will throw an AssertionError. *Note:* This method works only with 'psycopg2' driver. *Arguments:* - tableName: string, table name. - columns: list or string divided by comma, table columns. *Return:* - Primary key columns. *Examples:* | ${key_columns} | Check Primary Key Columns For Table \ | id, password_hash | """ tableColumns = self.get_primary_key_columns_for_table(tableName) if not isinstance(columns, list): columns = [c.strip().lower() for c in columns.split(',')] assert set(tableColumns) == set(columns),\ ('Primary key columns %s in table %s do not match ' 'with specified %s.' % (tableColumns, tableName, columns)) logger.debug("Primary key columns %s in table %s match with specified" " %s." % (tableColumns, tableName, columns)) def get_transaction_isolation_level(self): """ Gets transaction isolation level. *Note:* This method works only with 'psycopg2' driver. *Arguments:* - None *Return:* - Value that contains the name of the transaction isolation level Possible return values are: TRANSACTION_READ_UNCOMMITTED, \ TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, \ TRANSACTION_SERIALIZABLE or TRANSACTION_NONE. *Examples:* | ${isolation_level} | Get Transaction Isolation Level | """ # // TODO: Extend this method to work with other drivers. driverName = self._connectionCache.current.driverName assert driverName == 'psycopg2',\ "Impossible to use this keyword with '%s' driver." % driverName selectStatement = "SELECT CURRENT_SETTING('transaction_isolation');" result = 'TRANSACTION_%s' % \ self.query(selectStatement)[0][0].replace(' ', '_').upper() logger.debug("Transaction isolation level is %s." % result) return result def transaction_isolation_level_must_be(self, transactionLevel): """ Checks that transaction isolation level is equal to specified. If transaction isolation level is not equal to specified, then this \ will throw an AssertionError. *Note:* This method works only with 'psycopg2' driver. *Arguments:* - transactionLevel: string, transaction isolation level. Possible return values are: TRANSACTION_READ_UNCOMMITTED, \ TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, \ TRANSACTION_SERIALIZABLE or TRANSACTION_NONE. *Return:* - None *Examples:* | ${isolation_level} | Get Transaction Isolation Level | """ result = self.get_transaction_isolation_level() assert transactionLevel.upper() == result, \ ("Expected transaction isolation level '%s' " "but current is '%s'." % (transactionLevel.upper(), result)) logger.debug("Transaction isolation level is %s." % result)
/robotframework-pydblibrary-1.1.tar.gz/robotframework-pydblibrary-1.1/src/Pydblibrary/keywords/_table.py
0.761627
0.350255
_table.py
pypi
from robot.api import logger from _common import _CommonActions class _RowsKeywords(_CommonActions): """ Class that handles all keywords from group 'Rows'. """ def rows_count(self, selectStatement): """ Returns the number of rows fetched using 'selectStatement'. *Arguments:* - selectStatement: string, SQL query. *Return:* - int, rows count. *Examples:* | ${rows_count} | Rows Count | select * from TableName | """ cur = self._execute_sql(selectStatement) return cur.rowcount def rows_count_is_0(self, selectStatement): """ Verifies that 'selectStatement' query does not fetch any row. I.e. row count equals to 0. If the number of rows is greater than 0, \ then this will throw an AssertionError. *Arguments:* - selectStatement: string, SQL query. *Return:* - None. *Examples:* | Rows Count Is 0 | select * from TableName where name = 'Peter' | """ count = self.rows_count(selectStatement) assert not count, ("Expected to have 0 rows from '%s', " "but got %s rows." % (selectStatement, count)) logger.debug("Got 0 rows from %s." % selectStatement) def row_count_is_equal_to_x(self, selectStatement, numRows): """ Verifies that number of rows fetched using 'selectStatement' equals to 'numRows' value. If the number of rows does not equal to the 'numRows' value, \ then this will throw an AssertionError. *Arguments:* - selectStatement: string, SQL query; - numRows: int, expected number of rows. *Return:* - None. *Examples:* | Row Count Is Equal To X | select * from TableName | 125 | """ count = self.rows_count(selectStatement) assert count == numRows, ("Expected to have %s rows from '%s', but " "got %s rows." % (numRows, selectStatement, count)) logger.debug("Got %s rows from %s." % (numRows, selectStatement)) def row_count_is_greater_than_x(self, selectStatement, numRows): """ Verifies that number of rows fetched using 'selectStatement' is greater than 'numRows' value. If the number of rows equals to the 'numRows' value or is less than it, then this will throw an AssertionError. *Arguments:* - selectStatement: string, SQL query; - numRows: int, minimal number of rows. *Return:* - None. *Examples:* | Row Count Is Greater Than X | select * from TableName | 125 | """ count = self.rows_count(selectStatement) assert count > numRows, ("Expected to have greater than %s rows from " "'%s', but got %s rows." % (numRows, selectStatement, count)) logger.debug("Got %s rows from %s." % (numRows, selectStatement)) def row_count_is_less_than_x(self, selectStatement, numRows): """ Verifies that number of rows fetched using 'selectStatement' is less than 'numRows' value. If the number of rows equals to the 'numRows' value or is greater than it, then this will throw an AssertionError. *Arguments:* - selectStatement: string, SQL query; - numRows: int, maximal number of rows. *Return:* - None. *Examples:* | Row Count Is Less Than X | select * from TableName | 125 | """ count = self.rows_count(selectStatement) assert count < numRows, ("Expected to have less than %s rows from " "'%s', but got %s rows." % (numRows, selectStatement, count)) logger.debug("Got %s rows from %s." % (numRows, selectStatement)) def delete_all_rows_from_table(self, tableName): """ Deletes everything from the table with given name. *Arguments:* - tableName: string, table name. *Return:* - None. *Examples:* | Delete All Rows From Table | TableName | """ self._execute_sql("delete from %s" % tableName, True) logger.info("All rows are deleted from table '%s'." % tableName) def check_content_for_row_identified_by_rownum(self, colNames, expectedValues, tableName, rowNumValue): """ Fetches given columns from the table with given name. Verifies that received content in the row with number rowNumValue equal to the given expected values. If expected content will be not equal to actual, \ then this will throw an AssertionError. *Arguments:* - colNames: list, column names to be retrieved from DB; - expectedValues: list, expected fields values; - tableName: string, table name; - rowNumValue: int, number of row to be checked. *Return:* - None. *Examples:* | Check Content For Row Identified By Rownum | name,surname | 'John', \ 'Doe', | TableName | 50 | """ assert len(colNames) == len(expectedValues),\ "'colNames' and 'expectedValues' should have the same length." selectStatement = "select %s from %s" % (",".join(colNames), tableName) res = self.query(selectStatement) assert len(res) >= rowNumValue, ("Row %s does not exist for statement " "%s" % (rowNumValue, selectStatement)) actualValues = res[rowNumValue - 1] result = [] for i, col in enumerate(colNames): if expectedValues[i] != actualValues[i]: result.append((col, expectedValues[i], actualValues[i])) assert not result, ('\n'.join(["Expected that '%s' from row %s equals " "to '%s', but got '%s'." % (n, rowNumValue, e, a) for n, e, a in result])) logger.debug("Content for row %s equals to the expected values %s." % (rowNumValue, expectedValues)) def check_content_for_row_identified_by_where_clause(self, colNames, expectedValues, tableName, where): """ Fetches given columns from the 'tableName' table using where-clause. Where-clause should uniquely identify only one row. Verifies that content in the received row equals to the given expected values. If expected content will be not equal to actual, then this will throw an AssertionError. *Arguments:* - colNames: list, column names to be retrieved from DB; - expectedValues: list, expected fields values; - tableName: string, table name; - where: string, where-clause. *Return:* - None. *Examples:* | Check Content For Row Identified By Where Clause | id,surname | 50, \ 'Doe', | TableName | name = 'John' | """ assert len(colNames) == len(expectedValues),\ "'colNames' and 'expectedValues' should have the same length." actualValues = \ self.read_single_value_from_table(tableName, ",".join(colNames), where) result = [] for i, col in enumerate(colNames): if expectedValues[i] != actualValues[i]: result.append((col, expectedValues[i], actualValues[i])) assert not result, ('\n'.join(["Expected that '%s' equals to '%s', " "but got '%s'." % (n, e, a) for n, e, a in result])) logger.debug("Content for row which corresponds to the 'where %s'" "statement equals to the expected values %s." % (where, expectedValues)) def verify_number_of_rows_matching_where(self, tableName, where, rowNumValue): """ Fetches rows using given where-clause from the table with given 'tableName'. Verifies that number of rows equals to the given rowNumValue, otherwise AssertionError is thrown. If number of rows will be not equal to actual, \ then this will throw an AssertionError. *Arguments:* - tableName: string, table name; - where: string, where-clause; - rowNumValue: int, expected number of rows. *Return:* - None. *Examples:* | Verify Number Of Rows Matching Where | TableName | name='John' | 12 | """ selectStatement = "select * from %s where %s" % (tableName, where) count = self.rows_count(selectStatement) assert count == rowNumValue, ("Expected to get %s row(s) for where-" "clause statement '%s', but got %s." % (rowNumValue, where, count)) logger.debug("Number of rows matching 'where %s' statement equals to" "%s." % (where, rowNumValue)) def row_should_not_exist_in_table(self, tableName, where): """ Verifies that table with given 'tableName' doesn't have rows matching given where-clause statement. If the number of rows is greater than 0, \ then this will throw an AssertionError. *Arguments:* - tableName: string, table name - where: string, where-clause. *Return:* - None. *Examples:* | Row Should Not Exist In Table | TableName | surname = 'Doe' | """ selectStatement = "select * from %s where %s" % (tableName, where) actualValues = self.query(selectStatement) assert len(actualValues) == 0, ("Expected to get 0 rows for where-" "clause statement '%s', but got %s: " "%s." % (where, len(actualValues), actualValues)) logger .debug("There is no rows matching 'where %s' statement." % where)
/robotframework-pydblibrary-1.1.tar.gz/robotframework-pydblibrary-1.1/src/Pydblibrary/keywords/_rows.py
0.935465
0.547948
_rows.py
pypi
from robot.utils import ConnectionCache from robot.api import logger from pysphere import VIServer from .version import VERSION class PysphereLibrary(object): """Robot Framework test library for VMWare interaction The library has the following main usages: - Identifying available virtual machines on a vCenter or ESXi host - Starting and stopping VMs - Shutting down, rebooting VM guest OS - Checking VM status - Reverting VMs to a snapshot - Retrieving basic VM properties This library is essentially a wrapper around Pysphere http://code.google.com/p/pysphere/ adding connection caching consistent with other Robot Framework libraries. """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = VERSION def __init__(self): """ """ self._connections = ConnectionCache() def open_pysphere_connection(self, host, user, password, alias=None): """Opens a pysphere connection to the given `host` using the supplied `user` and `password`. The new connection is made active and any existing connectiosn are left open in the background. This keyword returns the index of the new connection which can be used later to switch back to it. Indices start from `1` and are reset when `Close All Pysphere Connections` is called. An optional `alias` can be supplied for the connection and used for switching between connections. See `Switch Pysphere Connection` for details. Example: | ${index}= | Open Pysphere Connection | my.vcenter.server.com | username | password | alias=myserver | """ server = VIServer() server.connect(host, user, password) connection_index = self._connections.register(server, alias) logger.info("Pysphere connection opened to host %s" % host) return connection_index def is_connected_to_pysphere(self): return self._connections.current.is_connected() def switch_pysphere_connection(self, index_or_alias): """Switches the active connection by index of alias. `index_or_alias` is either a connection index (an integer) or alias (a string). Index can be obtained by capturing the return value from `Open Pysphere Connection` and alias can be set as a named variable with the same method. Example: | ${my_connection}= | Open Pysphere Connection | myhost | myuser | mypassword | | Open Pysphere Connection | myotherhost | myuser | mypassword | alias=otherhost | | Switch Pysphere Connection | ${my_connection} | | Power On Vm | myvm | | Switch Pysphere Connection | otherhost | | Power On Vm | myothervm | """ old_index = self._connections.current_index if index_or_alias is not None: self._connections.switch(index_or_alias) logger.info("Pysphere connection switched to %s" % index_or_alias) else: logger.info("No index or alias given, pysphere connection has not been switched.") def close_pysphere_connection(self): """Closes the current pysphere connection. No other connection is made active by this keyword. use `Switch Pysphere Connection` to switch to another connection. Example: | ${my_connection}= | Open Pysphere Connection | myhost | myuser | mypassword | | Power On Vm | myvm | | Close Pysphere Connection | """ self._connections.current.disconnect() logger.info("Connection closed, there will no longer be a current pysphere connection.") self._connections.current = self._connections._no_current def close_all_pysphere_connections(self): """Closes all active pysphere connections. This keyword is appropriate for use in test or suite teardown. The assignment of connection indices resets after calling this keyword, and the next connection opened will be allocated index `1`. Example: | ${my_connection}= | Open Pysphere Connection | myhost | myuser | mypassword | | Open Pysphere Connection | myotherhost | myuser | mypassword | alias=otherhost | | Switch Pysphere Connection | ${myserver} | | Power On Vm | myvm | | Switch Pysphere Connection | otherhost | | Power On Vm | myothervm | | [Teardown] | Close All Pysphere Connections | """ self._connections.close_all(closer_method='disconnect') logger.info("All pysphere connections closed.") def get_vm_names(self): """Returns a list of all registered VMs for the currently active connection. """ return self._connections.current.get_registered_vms() def get_vm_properties(self, name): """Returns a dictionary of the properties associated with the named VM. """ vm = self._get_vm(name) return vm.get_properties(from_cache=False) def power_on_vm(self, name): """Power on the vm if it is not already running. This method blocks until the operation is completed. """ if not self.vm_is_powered_on(name): vm = self._get_vm(name) vm.power_on() logger.info("VM %s powered on." % name) else: logger.info("VM %s was already powered on." % name) def power_off_vm(self, name): """Power off the vm if it is not already powered off. This method blocks until the operation is completed. """ if not self.vm_is_powered_off(name): vm = self._get_vm(name) vm.power_off() logger.info("VM %s was powered off." % name) else: logger.info("VM %s was already powered off." % name) def reset_vm(self, name): """Perform a reset on the VM. This method blocks until the operation is completed. """ vm = self._get_vm(name) vm.reset() logger.info("VM %s reset." % name) def shutdown_vm_os(self, name): """Initiate a shutdown in the guest OS in the VM, returning immediately. """ vm = self._get_vm(name) vm.shutdown_guest() logger.info("VM %s shutdown initiated." % name) def reboot_vm_os(self, name): """Initiate a reboot in the guest OS in the VM, returning immediately. """ vm = self._get_vm(name) vm.reboot_guest() logger.info("VM %s reboot initiated." % name) def vm_is_powered_on(self, name): """Returns true if the VM is in the powered on state. """ vm = self._get_vm(name) return vm.is_powered_on() def vm_is_powered_off(self, name): """Returns true if the VM is in the powered off state. """ vm = self._get_vm(name) return vm.is_powered_off() def revert_vm_to_snapshot(self, name, snapshot_name=None): """Revert the named VM to a snapshot. If `snapshot_name` is supplied it is reverted to that snapshot, otherwise it is reverted to the current snapshot. This method blocks until the operation is completed. """ vm = self._get_vm(name) if snapshot_name is None: vm.revert_to_snapshot() logger.info("VM %s reverted to current snapshot." % name) else: vm.revert_to_named_snapshot(snapshot_name) logger.info("VM %s reverted to snapshot %s." % name, snapshot_name) def _get_vm(self, name): connection = self._connections.current return connection.get_vm_by_name(name)
/robotframework-pyspherelibrary-1.0.0.tar.gz/robotframework-pyspherelibrary-1.0.0/src/PysphereLibrary/library.py
0.821868
0.300361
library.py
pypi
Contribution guidelines ======================= These guidelines instruct how to submit issues and contribute code to the `Robot Framework project <https://github.com/robotframework/robotframework>`_. There are also many other projects in the larger `Robot Framework ecosystem <http://robotframework.org>`_ that you can contribute to. If you notice a library or tool missing, there is hardly any better way to contribute than creating your own project. Other great ways to contribute include answering questions and participating discussion on `robotframework-users <https://groups.google.com/forum/#!forum/robotframework-users>`_ mailing list and other forums as well as spreading the word about the framework one way or the other. .. contents:: :depth: 2 :local: Submitting issues ----------------- Bugs and enhancements are tracked in the `issue tracker <https://github.com/robotframework/robotframework/issues>`_. If you are unsure if something is a bug or is a feature worth implementing, you can first ask on `robotframework-users`_ list or `IRC <http://webchat.freenode.net/?channels=robotframework&prompt=1>`_ (#robotframework on irc.freenode.net). These and other similar forums, not the issue tracker, are also places where to ask general questions. Before submitting a new issue, it is always a good idea to check is the same bug or enhancement already reported. If it is, please add your comments to the existing issue instead of creating a new one. Reporting bugs ~~~~~~~~~~~~~~ Explain the bug you have encountered so that others can understand it and preferably also reproduce it. Key things to have in good bug report: 1. Version information - Robot Framework version - Python interpreter type (Python, Jython or IronPython) and version - Operating system name and version 2. Steps to reproduce the problem. With more complex problems it is often a good idea to create a `short, self contained, correct example (SSCCE) <http://sscce.org>`_. 3. Possible error message and traceback. Notice that all information in the issue tracker is public. Do not include any confidential information there. Enhancement requests ~~~~~~~~~~~~~~~~~~~~ Describe the new feature and use cases for it in as much detail as possible. Especially with larger enhancements, be prepared to contribute the code in form of a pull request as explained below or to pay someone for the work. Consider also would it be better to implement this functionality as a separate tool outside the core framework. Code contributions ------------------ If you have fixed a bug or implemented an enhancement, you can contribute your changes via GitHub's pull requests. This is not restricted to code, on the contrary, fixes and enhancements to documentation_ and tests_ alone are also very valuable. Choosing something to work on ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Often you already have a bug or an enhancement you want to work on in your mind, but you can also look at the `issue tracker`_ to find bugs and enhancements submitted by others. The issues vary significantly in complexity and difficulty, so you can try to find something that matches your skill level and knowledge. Pull requests ~~~~~~~~~~~~~ On GitHub pull requests are the main mechanism to contribute code. They are easy to use both for the contributor and for per person accepting the contribution, and with more complex contributions it is easy also for others to join the discussion. Preconditions for creating a pull requests are having a `GitHub account <https://github.com/>`_, installing `Git <https://git-scm.com>`_ and forking the `Robot Framework project`_. GitHub has good articles explaining how to `set up Git <https://help.github.com/articles/set-up-git/>`_, `fork a repository <https://help.github.com/articles/fork-a-repo/>`_ and `use pull requests <https://help.github.com/articles/using-pull-requests>`_ so we do not need to go through them in more detail here. We do, however, recommend to create dedicated branches for pull requests instead of creating them based on the master branch. This is especially important if you plan to work on multiple pull requests at the same time. Coding conventions ~~~~~~~~~~~~~~~~~~ Robot Framework uses the general Python code conventions defined in `PEP-8 <https://www.python.org/dev/peps/pep-0008/>`_. In addition to that, we try to write `idiomatic Python <http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html>`_ and follow the `SOLID principles <https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)>`_ with all new code. An important guideline is that the code should be clear enough that comments are generally not needed. Docstrings should be added to public APIs but are not needed in internal code. When docstrings are added, they should follow `PEP-257 <https://www.python.org/dev/peps/pep-0257/>`_. See `API documentation`_ section below for more details about documentation syntax, generating API docs, etc. We are pretty picky about using whitespace. We use blank lines and whitespace in expressions as dictated by `PEP-8`_, but we also follow these rules: - Indentation using spaces, not tabs. - No trailing spaces. - No extra empty lines at the end of the file. - Files must end with a newline. The above rules are good with most other code too. Any good editor or IDE can be configured to automatically format files according to them. Documentation ~~~~~~~~~~~~~ With new features adequate documentation is as important as the actual functionality. Different documentation is needed depending on the issue. User Guide '''''''''' Robot Framework's features are explained in the `User Guide <http://robotframework.org/robotframework/#user-guide>`_. It is generated using a custom script based on the source in `reStructuredText <http://docutils.sourceforge.net/rst.html>`_ format. For more details about editing and generating it see `<doc/userguide/README.rst>`_. Libraries ''''''''' If `standard libraries <http://robotframework.org/robotframework/#standard-libraries>`_ distributed with Robot Framework are enhanced, also their documentation needs to be updated. Keyword documentation is created from docstrings using the `Libdoc <http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#libdoc>`_ tool. Documentation must use Robot Framework's own `documentation formatting <http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#documentation-formatting>`_ and follow these guidelines: - Other keywords and sections in the library introduction can be referenced with internal links created with backticks like ```Example Keyword``` - When referring to arguments, argument names must use in inline code style created with double backticks like ````argument````. - Examples are recommended whenever the new keyword or enhanced functionality is not trivial. - All new enhancements or changes should have a note telling when the change was introduced. Often adding something like ``New in Robot Framework 2.9.`` is enough. Library documentation can be easily created using `<doc/libraries/lib2html.py>`_ script. Resulting docs should be verified before the code is committed. API documentation ''''''''''''''''' Modules and classes defined to be public should have API documentation. We do not generally use API docs with internal code because it is so hard to keep the docs in sync with the code. Instead we try to keep the code as clean and easy to understand as possible. API docs are created using docstrings following guidelines defined in `PEP-257`_. They are converted to HTML using `Sphinx <http://sphinx-doc.org/>`_ and its `autodoc <http://sphinx-doc.org/ext/autodoc.html>`_ extension. Documentation can be created locally using `<doc/api/generate.py>`_ script that unfortunately creates a lot of errors on the console. Releases API docs are visible at https://robot-framework.readthedocs.org/. Robot Framework's public API docs are lacking in many ways. All public classes are not yet documented, existing documentation is somewhat scarce, and there could be more examples. Documentation improvements are highly appreciated! Tests ~~~~~ When submitting a pull request with a new feature or a fix, you should always include tests for your changes. These tests prove that your changes work, help prevent bugs in the future, and help document what your changes do. Depending an the change, you may need `acceptance tests`_, `unit tests`_ or both. Make sure to run all of the tests before submitting a pull request to be sure that your changes do not break anything. If you can, test in multiple environments and interpreters (Windows, Linux, OS X, Python, Jython, IronPython, etc). Pull requests are also automatically tested on `continuous integration`_. Acceptance tests '''''''''''''''' Most of Robot Framework's testing is done using acceptance tests that naturally use Robot Framework itself for testing. Every new functionality or fix should generally get one or more acceptance tests. See `<atest/README.rst>`_ for more details for more details about creating and executing them. Unit tests '''''''''' Unit tests are great for testing internal logic and should be added when appropriate. For more details see `<utest/README.rst>`_. Continuous integration '''''''''''''''''''''' Robot Framework's continuous integration (CI) servers are visible through http://robot.radiaatto.ri.fi/. They automatically test all new commits to the repository both on Linux and on Windows, and pull requests can be tested there too. When a new pull request comes in, the CI will ask if one of the admins can verify the pull request. The admins are currently @jussimalinen and @pekkaklarck. The commands are: - ``robotci: once`` (run once) - ``robotci: enable`` (run whenever this pull request changes) - ``robotci: whitelist user`` (enable CI for all pull requests coming from this user) The commands can be anywhere on the comment. Adding the skip statement (``[skip ci]``, with the square brackets) to the pull request body will cause the job not to be executed. Finalizing pull requests ~~~~~~~~~~~~~~~~~~~~~~~~ Once you have code, documentation and tests ready, it is time to finalize the pull request. AUTHORS.txt ''''''''''' If you have done any non-trivial change and would like to be credited, add yourself to `<AUTHORS.txt>`_ file. Resolving conflicts ''''''''''''''''''' Conflicts can occur if there are new changes to the master that touch the same code as your changes. In that case you should `sync your fork <https://help.github.com/articles/syncing-a-fork>`_ and `resolve conflicts <https://help.github.com/articles/resolving-a-merge-conflict-from-the-command-line>`_ to allow for an easy merge. The most common conflicting file is the aforementioned `AUTHORS.txt`_, but luckily fixing those conflicts is typically easy. Squashing commits ''''''''''''''''' If the pull request contains multiple commits, it is recommended that you squash them into a single commit before the pull request is merged. See `Squashing Github pull requests into a single commit <http://eli.thegreenplace.net/2014/02/19/squashing-github-pull-requests-into-a-single-commit>`_ article for more details about why and how. Squashing is especially important if the pull request contains lots of temporary commits and changes that have been later reverted or redone. Squashing is not needed if the commit history is clean and individual commits are meaningful alone.
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/CONTRIBUTING.rst
0.841728
0.846006
CONTRIBUTING.rst
pypi
Installation instructions ========================= These instructions cover installing and uninstalling Robot Framework and its preconditions on different operating systems. If you already have `pip <http://pip-installer.org>`_ installed, it is enough to run:: pip install robotframework .. contents:: :depth: 2 :local: .. START USER GUIDE IGNORE .. These instructions are included also in the User Guide. Following role .. and link definitions are excluded when UG is built. .. default-role:: code .. role:: file(emphasis) .. role:: option(code) .. _supporting tools: http://robotframework.org/robotframework/#built-in-tools .. _post-process outputs: `supporting tools`_ .. END USER GUIDE IGNORE Introduction ------------ `Robot Framework <http://robotframework.org>`_ is implemented with `Python <http://python.org>`_ and also runs on `Jython <http://jython.org>`_ (JVM) and `IronPython <http://ironpython.net>`_ (.NET). Before installing the framework, an obvious precondition_ is installing at least one of these interpreters. Note that Python 3 is not yet supported, but there is an `un-official Python 3 port <https://pypi.python.org/pypi/robotframework-python3>`_ available. Different ways to install Robot Framework itself are listed below and explained more thoroughly in subsequent sections. `Package managers (e.g. pip)`_ Python package managers make installation trivial. For example, pip_ users just need to execute:: pip install robotframework As the standard Python package manager, pip is bundled in with the latest Python, Jython and IronPython installers. `Installing from source`_ This approach works regardless the operating system and the Python interpreter used. You can get the source code either by downloading and extracting a source distribution from `PyPI <https://pypi.python.org/pypi/robotframework>`_ or by cloning the `GitHub repository <https://github.com/robotframework/robotframework>`_ . `Using Windows installer`_ There are graphical installers for both 32 bit and 64 bit Windows systems, both available on PyPI_. `Standalone JAR distribution`_ If running tests with Jython is enough, the easiest approach is downloading the standalone ``robotframework-<version>.jar`` from `Maven central <http://search.maven.org/#search%7Cga%7C1%7Ca%3Arobotframework>`_. The JAR distribution contains both Jython and Robot Framework and thus only requires having `Java <http://java.com>`_ installed. `Manual installation`_ If you have special needs and nothing else works, you can always do a custom manual installation. Preconditions ------------- Robot Framework is supported on Python_, Jython_ (JVM) and IronPython_ (.NET) and runs also on `PyPy <http://pypy.org>`_. The interpreter you want to use should be installed before installing the framework. Which interpreter to use depends on the needed test libraries and test environment in general. Some libraries use tools or modules that only work with Python, while others may use Java tools that require Jython or need .NET and thus IronPython. There are also many tools and libraries that run fine with all interpreters. If you do not have special needs or just want to try out the framework, it is recommended to use Python. It is the most mature implementation, considerably faster than Jython or IronPython (especially start-up time is faster), and also readily available on most UNIX-like operating systems. Another good alternative is using the `standalone JAR distribution`_ that only has Java as a precondition. Python installation ~~~~~~~~~~~~~~~~~~~ On most UNIX-like systems such as Linux and OS X you have Python_ installed by default. If you are on Windows or otherwise need to install Python yourself, a good place to start is http://python.org. There you can download a suitable installer and get more information about the installation process and Python in general. Robot Framework 2.9 supports Python 2.6 and 2.7, and the plan is to support also Python 3 in the near future. If you need Python 3 support earlier, you can use the `un-official Python 3 port`_. If you need to use older Python versions, Robot Framework 2.5-2.8 support Python 2.5 and Robot Framework 2.0-2.1 support Python 2.3 and 2.4. On Windows it is recommended to install Python to all users and to run the installer as an administrator. Additionally, environment variable ``PYTHONCASEOK`` must not be set. After installing Python, you probably still want to `configure PATH`_ to make the ``pybot`` `runner script`_ executable on the command prompt. .. tip:: Latest Python Windows installers allow setting ``PATH`` as part of the installation. This is disabled by default, but `Add python.exe to Path` can be enabled on the `Customize Python` screen. Jython installation ~~~~~~~~~~~~~~~~~~~ Using test libraries implemented with Java_ or that use Java tools internally requires running Robot Framework on Jython_, which in turn requires Java Runtime Environment (JRE) or Java Development Kit (JDK). Installing either of these Java implementations is out of the scope of these instructions, but you can find more information from http://java.com if needed. Installing Jython is a fairly easy procedure, and the first step is getting an installer from http://jython.org. The installer is an executable JAR package, which you can run from the command line like `java -jar jython_installer-<version>.jar`. Depending on the system configuration, it may also be possible to just double-click the installer. Robot Framework 2.9 supports Jython 2.7 which requires Java 7 or newer. If older Jython or Java versions are needed, Robot Framework 2.5-2.8 support Jython 2.5 (requires Java 5 or newer) and Robot Framework 2.0-2.1 support Jython 2.2. After installing Jython, you probably still want to `configure PATH`_ to make the ``jybot`` `runner script`_ executable on the command prompt. IronPython installation ~~~~~~~~~~~~~~~~~~~~~~~ IronPython_ allows running Robot Framework on the `.NET platform <http://www.microsoft.com/net>`__ and interacting with C# and other .NET languages and APIs. Only IronPython 2.7 is supported. When using IronPython, an additional dependency is installing `elementtree <http://effbot.org/downloads/#elementtree>`__ module 1.2.7 preview release. This is required because the ``elementtree`` module distributed with IronPython is `broken <https://github.com/IronLanguages/main/issues/968>`__. You can install the package by downloading the source distribution, unzipping it, and running `ipy setup.py install` on the command prompt in the created directory. After installing IronPython, you probably still want to `configure PATH`_ to make the ``ipybot`` `runner script`_ executable on the command prompt. Configuring ``PATH`` ~~~~~~~~~~~~~~~~~~~~ The ``PATH`` environment variable lists locations where commands executed in a system are searched from. To make using Robot Framework easier from the command prompt, it is recommended to add the locations where the `runner scripts`_ are installed into the ``PATH``. The runner scripts themselves require the matching interpreter to be in the ``PATH`` and thus the interpreter installation directory must be added there too. When using Python on UNIX-like machines both Python itself and scripts installed with should be automatically in the ``PATH`` and no extra actions needed. On Windows and with other interpreters the ``PATH`` must be configured separately. .. tip:: Latest Python Windows installers allow setting ``PATH`` as part of the installation. This is disabled by default, but `Add python.exe to Path` can be enabled on the `Customize Python` screen. It will set both Python installation directory and :file:`Scripts` directory to ``PATH``. What directories to add to ``PATH`` ''''''''''''''''''''''''''''''''''' What directories you need to add to the ``PATH`` depends on the interpreter and the operating system. The first location is the installation directory of the interpreter (e.g. :file:`C:\\Python27`) and the other is the location where scripts are installed with that interpreter. Both Python and IronPython install scripts to :file:`Scripts` directory under the installation directory on Windows (e.g. :file:`C:\\Python27\\Scripts`) and Jython uses :file:`bin` directory regardless the operating system (e.g. :file:`C:\\jython2.5.3\\bin`). Notice that :file:`Scripts` and :file:`bin` directories may not be created as part of the interpreter installation but only later when Robot Framework or some other third party module is installed. Setting ``PATH`` on Windows ''''''''''''''''''''''''''' On Windows you can configure ``PATH`` by following the steps below. Notice that the exact setting names may be different on different Windows versions, but the basic approach should still be the same. 1. Open `Control Panel > System > Advanced > Environment Variables`. There are `User variables` and `System variables`, and the difference between them is that user variables affect only the current users, whereas system variables affect all users. 2. To edit an existing ``PATH`` value, select `Edit` and add `;<InstallationDir>;<ScriptsDir>` at the end of the value (e.g. `;C:\Python27;C:\Python27\Scripts`). Note that the semicolons (`;`) are important as they separate the different entries. To add a new ``PATH`` value, select `New` and set both the name and the value, this time without the leading semicolon. 3. Exit the dialog with `Ok` to save the changes. 4. Start a new command prompt for the changes to take effect. Notice that if you have multiple Python versions installed, the executed ``pybot`` script will always use the one that is *first* in the ``PATH`` regardless under what Python version that script is installed. To avoid that, you can always use the `direct entry points`_ with the interpreter of choice like `C:\Python26\python.exe -m robot.run`. Notice also that you should not add quotes around directories you add into the ``PATH`` (e.g. `"C:\Python27\Scripts"`). Quotes `can cause problems with Python programs <http://bugs.python.org/issue17023>`_ and they are not needed with the ``PATH`` even if the directory path would contain spaces. Setting ``PATH`` on UNIX-like systems ''''''''''''''''''''''''''''''''''''' On UNIX-like systems you typically need to edit either some system wide or user specific configuration file. Which file to edit and how depends on the system, and you need to consult your operating system documentation for more details. Setting ``https_proxy`` ~~~~~~~~~~~~~~~~~~~~~~~ If you are planning to `use pip for installation`_ and are behind a proxy, you need to set the ``https_proxy`` environment variable. It is needed both when installing pip and when using it to install Robot Framework and other Python packages. How to set the ``https_proxy`` depends on the operating system similarly as `configuring PATH`_. The value of this variable must be an URL of the proxy, for example, `http://10.0.0.42:8080`. Installing Robot Framework -------------------------- Package managers (e.g. pip) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The standard Python package manager is pip_, but there are also other alternatives such as `Buildout <http://buildout.org>`__ and `easy_install <http://peak.telecommunity.com/DevCenter/EasyInstall>`__. These instructions only cover using pip, but other package managers ought be able to install Robot Framework as well, at least if they search packages from PyPI_. Latest Python, Jython and IronPython versions contain pip bundled in. Which versions contain it and how to possibly activate it is discussed in sections below. If you need to install pip separately, latest installation instructions can be found from pip_ project pages. .. note:: If you are behind a proxy, you need to `set https_proxy`_ environment variable before installing and using pip. Only Robot Framework 2.7 and newer can be installed using pip. If you need an older version, you must use other installation approaches. Installing pip for Python ''''''''''''''''''''''''' Starting from Python 2.7.9, the standard Windows installer by default installs and activates pip. Assuming you also have `configured PATH`__ and possibly `set https_proxy`_, you can run `pip install robotframework` right after Python installation. Outside Windows and with older Python versions you need to install pip yourself. You may be able to do it using system package managers like `apt` on Linux, but you can always use manual installation instructions found from pip_ project pages. .. tip:: You can also run pip like `python -m pip install robotframework`. This is especially useful if you have pip installed also for other Python interpreters. __ `Configuring PATH`_ Installing pip for Jython ''''''''''''''''''''''''' Latest preview releases of the forthcoming Jython 2.7 contain pip bundled in. It just needs to be activated by running the following command before using it:: jython -m ensurepip Jython installs its own version of pip into `<JythonInstallation>/bin` directory. Does executing `pip` actually run it or possibly some other pip version depends on how ``PATH`` is configured. It can thus be safer to use `jython -m pip install robotframework` instead. Older Jython versions do not officially support pip. Installing pip for IronPython ''''''''''''''''''''''''''''' IronPython contains bundled pip starting from `version 2.7.5`__. Similarly as with Jython, it needs to be activated first:: ipy -X:Frames -m ensurepip Notice that with IronPython `-X:Frames` command line option is needed both when activating and using pip. IronPython installs its own version of pip into `<IronPythonInstallation>/Scripts` directory. Does executing `pip` actually run it or possibly some other pip version depends on how ``PATH`` is configured. It can thus be safer to use `ipy -X:Frames -m pip install robotframework` instead. Older IronPython versions do not officially support pip. __ http://blog.ironpython.net/2014/12/pip-in-ironpython-275.html Using pip ''''''''' Once you have pip installed, using it on the command line is very easy. The most common usages are shown below and pip_ documentation has more information and examples. .. sourcecode:: bash # Install the latest version pip install robotframework # Upgrade to the latest version pip install --upgrade robotframework # Install a specific version pip install robotframework==2.8.5 # Uninstall pip uninstall robotframework Notice that pip 1.4 and newer will only install stable releases by default. If you want to install an alpha, beta or release candidate, you need to either specify the version explicitly or use :option:`--pre` option: .. sourcecode:: bash # Install 2.9 beta 1 pip install robotframework==2.9b1 # Install the latest version even if it is a pre-release pip install --pre robotframework If you still use pip 1.3 or older and do not want to get the latest version when it is a pre-release, you need to explicitly specify which stable version you want to install. Installing from source ~~~~~~~~~~~~~~~~~~~~~~ This installation method can be used on any operating system with any of the supported interpreters. Installing *from source* can sound a bit scary, but the procedure is actually pretty straightforward. .. _source distribution: Getting source code ''''''''''''''''''' You typically get the source by downloading a *source distribution package* in `.tar.gz` format. Newer packages are available on PyPI_, but Robot Framework 2.8.1 and older can be found from the old `Google Code download page <https://code.google.com/p/robotframework/downloads/list?can=1>`_. Once you have downloaded the package, you need to extract it somewhere and, as a result, you get a directory named `robotframework-<version>`. The directory contains the source code and scripts needed for installing it. An alternative approach for getting the source code is cloning project's `GitHub repository`_ directly. By default you will get the latest code, but you can easily switch to different released versions or other tags. Installation '''''''''''' Robot Framework is installed from source using Python's standard ``setup.py`` script. The script is in the directory containing the sources and you can run it from the command line using any of the supported interpreters: .. sourcecode:: bash # Installing with Python. Creates `pybot` and `rebot` scripts. python setup.py install # Installing with Jython. Creates `jybot` and `jyrebot` scripts. jython setup.py install # Installing with IronPython. Creates `ipybot` and `ipyrebot` scripts. ipy setup.py install The ``setup.py`` script accepts several arguments allowing, for example, installation into a non-default location that does not require administrative rights. It is also used for creating different distribution packages. Run `python setup.py --help` for more details. Using Windows installer ~~~~~~~~~~~~~~~~~~~~~~~ There are separate graphical installers for 32 bit and 64 bit Windows systems with names in format ``robotframework-<version>.win32.exe`` and ``robotframework-<version>.win-amd64.exe``, respectively. Newer installers are on PyPI_ and Robot Framework 2.8.1 and older on the old `Google Code download page`_. Running the installer requires double-clicking it and following the simple instructions. Windows installers always run on Python and create the standard ``pybot`` and ``rebot`` `runner scripts`_. Unlike the other provided installers, these installers also automatically create ``jybot`` and ``ipybot`` scripts. To be able to use the created runner scripts, both the :file:`Scripts` directory containing them and the appropriate interpreters need to be in PATH_. Installing Robot Framework may require administrator privileges. In that case select `Run as administrator` from the context menu when starting the installer. Standalone JAR distribution ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Robot Framework is also distributed as a standalone Java archive that contains both Jython_ and Robot Framework and only requires Java_ a dependency. It is an easy way to get everything in one package that requires no installation, but has a downside that it does not work with the normal Python_ interpreter. The package is named ``robotframework-<version>.jar`` and it is available on the `Maven central`_. After downloading the package, you can execute tests with it like: .. sourcecode:: bash java -jar robotframework-2.9.jar mytests.robot java -jar robotframework-2.9.jar --variable name:value mytests.robot If you want to `post-process outputs`_ using Rebot or use other built-in `supporting tools`_, you need to give the command name ``rebot``, ``libdoc``, ``testdoc`` or ``tidy`` as the first argument to the JAR file: .. sourcecode:: bash java -jar robotframework-2.9.jar rebot output.xml java -jar robotframework-2.9.jar libdoc MyLibrary list For more information about the different commands, execute the JAR without arguments. Manual installation ~~~~~~~~~~~~~~~~~~~ If you do not want to use any automatic way of installing Robot Framework, you can always install it manually following these steps: 1. Get the source code. All the code is in a directory (a package in Python) called :file:`robot`. If you have a `source distribution`_ or a version control checkout, you can find it from the :file:`src` directory, but you can also get it from an earlier installation. 2. Copy the source code where you want to. 3. Create `runner scripts`_ you need or use the `direct entry points`_ with the interpreter of your choice. Verifying installation ~~~~~~~~~~~~~~~~~~~~~~ After a successful installation, you should be able to execute created `runner scripts`_ with :option:`--version` option and get both Robot Framework and interpreter versions as a result: .. sourcecode:: bash $ pybot --version Robot Framework 2.9 (Python 2.7.10 on linux2) $ rebot --version Rebot 2.9 (Python 2.7.10 on linux2) $ jybot --version Robot Framework 2.9 (Jython 2.7 on java1.7.0_60) If running the runner scripts fails with a message saying that the command is not found or recognized, a good first step is double-checking the PATH_ configuration. If that does not help, it is a good idea to re-read relevant sections from these instructions before searching help from the Internet or as asking help on `robotframework-users <http://groups.google.com/group/robotframework-users/>`__ mailing list or elsewhere. Where files are installed ~~~~~~~~~~~~~~~~~~~~~~~~~ When an automatic installer is used, Robot Framework source code is copied into a directory containing external Python modules. On UNIX-like operating systems where Python is pre-installed the location of this directory varies. If you have installed the interpreter yourself, it is normally :file:`Lib/site-packages` under the interpreter installation directory, for example, :file:`C:\\Python27\\Lib\\site-packages`. The actual Robot Framework code is in a directory named :file:`robot`. Robot Framework `runner scripts`_ are created and copied into another platform-specific location. When using Python on UNIX-like systems, they normally go to :file:`/usr/bin` or :file:`/usr/local/bin`. On Windows and with other interpreters, the scripts are typically either in :file:`Scripts` or :file:`bin` directory under the interpreter installation directory. Uninstallation and upgrading ---------------------------- Uninstallation ~~~~~~~~~~~~~~ How to uninstall Robot Framework depends on the original installation method. Notice that if you have set ``PATH`` or configured your environment otherwise, you need to undo these changes separately. Uninstallation using pip '''''''''''''''''''''''' If you have pip available, uninstallation is as easy as installation: .. sourcecode:: bash pip uninstall robotframework A nice pip feature is that it can uninstall packages even if installation has been done using some other approach. Uninstallation after using Windows installer '''''''''''''''''''''''''''''''''''''''''''' If `Windows installer`_ has been used, uninstallation can be done using `Control Panel > Add/Remove Programs`. Robot Framework is listed under Python applications. Manual uninstallation ''''''''''''''''''''' The framework can always be uninstalled manually. This requires removing the created :file:`robot` directory and the `runner scripts`_. See `where files are installed`_ section above to learn where they can be found. Upgrading ~~~~~~~~~ When upgrading or downgrading Robot Framework, it is safe to install a new version over the existing when switching between two minor versions, for example, from 2.8.4 to 2.8.5. This typically works also when upgrading to a new major version, for example, from 2.8.5 to 2.9, but uninstalling the old version is always safer. A very nice feature of pip package manager is that it automatically uninstalls old versions when upgrading. This happens both when changing to a specific version or when upgrading to the latest version: .. sourcecode:: bash pip install robotframework==2.7.1 pip install --upgrade robotframework Regardless on the version and installation method, you do not need to reinstall preconditions or set ``PATH`` environment variable again. Different entry points ---------------------- Runner scripts ~~~~~~~~~~~~~~ Robot Framework has different runner scripts for executing test cases and for post-processing outputs based on earlier test results. In addition to that, these scripts are different depending on the interpreter that is used: .. table:: Different runner scripts :class: tabular ============= ============== ================ Interpreter Test execution Post-processing ============= ============== ================ Python ``pybot`` ``rebot`` Jython ``jybot`` ``jyrebot`` IronPython ``ipybot`` ``ipyrebot`` ============= ============== ================ On UNIX-like operating systems such as Linux and OS X, the runner scripts are implemented using Python, and on Windows they are batch files. Regardless of the operating system, using any of these scripts requires that the appropriate interpreter is in PATH_. Direct entry points ~~~~~~~~~~~~~~~~~~~ In addition to the above runner scripts, it is possible to both run tests and post-process outputs by executing framework's entry points directly using a selected interpreter. It is possible to execute them as modules using Python's :option:`-m` option and, if you know where the framework is installed, to run them as scripts. The entry points are listed on the following table using Python, and examples below illustrate using them also with other interpreters. .. table:: Direct entry points :class: tabular ================== ======================= ============================ Entry point Run as module Run as script ================== ======================= ============================ Test execution `python -m robot.run` `python path/robot/run.py` Post-processing `python -m robot.rebot` `python path/robot/rebot.py` ================== ======================= ============================ .. sourcecode:: bash # Run tests with Python by executing `robot.run` module. python -m robot.run # Run tests with Jython by running `robot/run.py` script. jython path/to/robot/run.py # Create reports/logs with IronPython by executing `robot.rebot` module. ipy -m robot.rebot # Create reports/logs with Python by running `robot/rebot.py` script. python path/to/robot/rebot.py .. _runner script: `runner scripts`_ .. _precondition: preconditions_ .. _configure PATH: `Configuring PATH`_ .. _PATH: `Configuring PATH`_ .. _use pip for installation: `Package managers (e.g. pip)`_ .. _set https_proxy: `Setting https_proxy`_ .. _Windows installer: `Using Windows installer`_ .. _entry point: `direct entry points`_
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/INSTALL.rst
0.902987
0.663134
INSTALL.rst
pypi
from __future__ import print_function from six import string_types import os import os.path import re import shutil import sys import time import urllib import zipfile from fnmatch import fnmatchcase from invoke import task, run assert os.getcwd() == os.path.dirname(os.path.abspath(__file__)) VERSION_RE = re.compile('^((2\.\d+)(\.\d+)?)((a|b|rc|.dev)(\d+))?$') VERSION_FILE = os.path.join('src', 'robot', 'version.py') @task(default=True) def help(): """Show help, basically an alias for --help. This task can be removed once the fix to this issue is released: https://github.com/pyinvoke/invoke/issues/180 """ run('invoke --help') @task def tag_release(version): """Tag specified release. Updates version using `set_version`, creates tag, and pushes changes. """ version = set_version(version, push=True) run("git tag -a {0} -m 'Release {0}'".format(version)) run("git push --tags") @task def set_version(version, push=False): """Set version in `src/robot/version.py`. Version can have these values: - Actual version number to use. See below for supported formats. - String 'dev' to update version to latest development version (e.g. 2.8 -> 2.8.1.dev, 2.8.1 -> 2.8.2.dev, 2.8a1 -> 2.8.dev) with the current date added or updated. - String 'keep' to keep using the previously set version. Given version must be in one of these PEP-440 compatible formats: - Stable version in 'X.Y' or 'X.Y.Z' format (e.g. 2.8, 2.8.6) - Pre-releases with 'aN', 'bN' or 'rcN' postfix (e.g. 2.8a1, 2.8.6rc2) - Development releases with '.devYYYYMMDD' postfix (e.g. 2.8.6.dev20141001) or with '.dev' alone (e.g. 2.8.6.dev) in which case date is added automatically. Args: version: Version to use. See above for supported values and formats. push: Commit and push changes to the remote repository. """ if version and version != 'keep': version = validate_version(version) write_version_file(version) write_pom_file(version) version = get_version_from_file() print('Version:', version) if push: git_commit([VERSION_FILE, 'pom.xml'], 'Updated version to {}'.format(version), push=True) return version def validate_version(version): if version == 'dev': version = get_dev_version() if version.endswith('.dev'): version += time.strftime('%Y%m%d') if not VERSION_RE.match(version): raise ValueError("Invalid version '{}'.".format(version)) return version def get_dev_version(): previous = get_version_from_file() major, minor, pre = VERSION_RE.match(previous).groups()[1:4] if not pre: minor = '.{}'.format(int(minor[1:]) + 1 if minor else 1) if not minor: minor = '' return '{}{}.dev'.format(major, minor) def write_version_file(version): update_file(VERSION_FILE, "VERSION = '.*'", version) def write_pom_file(version): update_file('pom.xml', '<version>.*</version>', version) def update_file(path, pattern, replacement): replacement = pattern.replace('.*', replacement ) with open(path) as version_file: content = ''.join(re.sub(pattern, replacement, line) for line in version_file) with open(path, 'w') as version_file: version_file.write(content) def get_version_from_file(): namespace = {} execfile(VERSION_FILE, namespace) return namespace['get_version']() def git_commit(paths, message, push=False): paths = paths if isinstance(paths, string_types) else ' '.join(paths) run("git commit -m '{}' {}".format(message, paths)) if push: run('git push') @task def clean(remove_dist=True, create_dirs=False): """Clean workspace. By default deletes 'build' and 'dist' directories and removes '*.pyc' and '$py.class' files. Args: remove_dist: Remove also 'dist' (default). create_dirs: Re-create 'build' and 'dist' after removing them. """ directories = ['build', 'dist'] for name in directories: if os.path.isdir(name) and (name != 'dist' or remove_dist): shutil.rmtree(name) if create_dirs and not os.path.isdir(name): os.mkdir(name) for directory, _, files in os.walk('.'): for name in files: if name.endswith(('.pyc', '$py.class')): os.remove(os.path.join(directory, name)) @task def sdist(deploy=False, remove_dist=False): """Create source distribution. Args: deploy: Register and upload sdist to PyPI. remove_dist: Control is 'dist' directory initially removed or not. """ clean(remove_dist, create_dirs=True) run('python setup.py sdist' + (' register upload' if deploy else '')) announce() def announce(): print() print('Distributions:') for name in os.listdir('dist'): print(os.path.join('dist', name)) @task def wininst(remove_dist=False): """Create Windows installer. Args: remove_dist: Control is 'dist' directory initially removed or not. """ clean(remove_dist, create_dirs=True) run('python setup.py bdist_wininst ' '--bitmap robot.bmp --install-script robot_postinstall.py') announce() @task def jar(jython_version='2.7.0', remove_dist=False): """Create JAR distribution. Downloads Jython JAR if needed. Args: remove_dist: Control is 'dist' directory initially removed or not. jython_version: Jython version to use as a base. Must match version in `jython-standalone-<version>.jar` found from Maven central. Currently `2.7.0` by default. """ clean(remove_dist, create_dirs=True) jython_jar = get_jython_jar(jython_version) print('Using {}'.format(jython_jar)) compile_java_files(jython_jar) unzip_jar(jython_jar) copy_robot_files() compile_python_files(jython_jar) create_robot_jar(get_version_from_file()) announce() def get_jython_jar(version): lib = 'ext-lib' jar = os.path.join(lib, 'jython-standalone-{}.jar'.format(version)) if os.path.exists(jar): return jar url = ('http://search.maven.org/remotecontent?filepath=org/python/' 'jython-standalone/{0}/jython-standalone-{0}.jar').format(version) print('Jython not found, downloading it from {}.'.format(url)) if not os.path.exists(lib): os.mkdir(lib) urllib.urlretrieve(url, jar) return jar def compile_java_files(jython_jar, build_dir='build'): root = os.path.join('src', 'java', 'org', 'robotframework') files = [os.path.join(root, name) for name in os.listdir(root) if name.endswith('.java')] print('Compiling {} Java files.'.format(len(files))) run('javac -d {target} -target 1.5 -source 1.5 -cp {cp} {files}'.format( target=build_dir, cp=jython_jar, files=' '.join(files))) def unzip_jar(path, target='build'): zipfile.ZipFile(path).extractall(target) def copy_robot_files(build_dir='build'): source = os.path.join('src', 'robot') target = os.path.join(build_dir, 'Lib', 'robot') shutil.copytree(source, target, ignore=shutil.ignore_patterns('*.pyc')) shutil.rmtree(os.path.join(target, 'htmldata', 'testdata')) def compile_python_files(jython_jar, build_dir='build'): run('java -jar {} -m compileall {}'.format(jython_jar, build_dir)) # Jython will not work without its py-files, but robot will for directory, _, files in os.walk(os.path.join(build_dir, 'Lib', 'robot')): for name in files: if name.endswith('.py'): os.remove(os.path.join(directory, name)) def create_robot_jar(version, source='build'): write_manifest(version, source) target = os.path.join('dist', 'robotframework-{}.jar'.format(version)) run('jar cvfM {} -C {} .'.format(target, source)) def write_manifest(version, build_dir='build'): with open(os.path.join(build_dir, 'META-INF', 'MANIFEST.MF'), 'w') as mf: mf.write('''\ Manifest-Version: 1.0 Main-Class: org.robotframework.RobotFramework Specification-Version: 2 Implementation-Version: {version} '''.format(version=version)) @task def release_notes(version=get_version_from_file(), login=None, password=None): """Create release notes template based on issues on GitHub. Requires PyGithub <https://github.com/jacquev6/PyGithub>. Install it with: pip install PyGithub Args: version: Version to get the issues for. By default the current version. login: GitHub login. If not given, anonymous login is used. GitHub API has 60 request/hour limit in that case. password: The password for GitHub login. """ milestone, preview, preview_number = _split_version(version) issues = _get_issues(milestone, preview, preview_number, login, password) _print_header("Robot Framework {}".format(version), level=1) _print_intro(version) _print_if_label("Most important enhancements", issues, "prio-critical", "prio-high") _print_if_label("Backwards incompatible changes", issues, "bwic") _print_if_label("Deprecated features", issues, "depr") _print_header("Acknowledgements") print("*UPDATE* based on AUTHORS.txt.") _print_issue_table(issues, version, preview) def _split_version(version): match = VERSION_RE.match(version) if not match: raise ValueError("Invalid version '{}'".format(version)) milestone, _, _, _, preview, preview_number = match.groups() return milestone, preview, preview_number def _get_issues(milestone, preview, preview_number, login=None, password=None): try: from github import Github except ImportError: sys.exit("You need to install PyGithub:\n\tpip install PyGithub\n") repo = Github(login_or_token=login, password=password).get_repo("robotframework/robotframework") issues = [Issue(issue) for issue in repo.get_issues(milestone=_get_milestone(repo, milestone), state="all")] preview_matcher = PreviewMatcher(preview, preview_number) if preview_matcher: issues = [issue for issue in issues if preview_matcher.matches(issue.labels)] return sorted(issues) def _get_milestone(repo, milestone): for m in repo.get_milestones(state="all"): if m.title == milestone: return m raise AssertionError("Milestone {} not found from repository {}!".format(milestone, repo.name)) def _print_header(header, level=2): if level > 1: print() print("{} {}\n".format('#'*level, header)) def _print_if_label(header, issues, *labels): filtered = [issue for issue in issues if any(label in issue.labels for label in labels)] if filtered: _print_header(header) print('*EXPLAIN* or remove these.\n') for issue in filtered: print("* {} {}".format(issue.id, issue.summary), end="") print(" ({})".format(issue.preview) if issue.preview else "") def _print_intro(version): print(""" Robot Framework {version} is a new release with *UPDATE* \ enhancements and bug fixes. It was released on {date}. Questions and comments related to the release can be sent to the \ [robotframework-users](http://groups.google.com/group/robotframework-users) and \ possible bugs submitted to the \ [issue tracker](https://github.com/robotframework/robotframework/issues). If you have pip just run `pip install --update robotframework`. Otherwise see \ [installation instructions](https://github.com/robotframework/robotframework/blob/master/INSTALL.rst). """.format(version=version, date=time.strftime("%A %B %d, %Y")).strip()) def _print_issue_table(issues, version, preview): _print_header("Full list of fixes and enhancements") print("ID | Type | Priority | Summary" + (" | Added&nbsp;In" if preview else "")) print("--- | ---- | -------- | -------" + (" | --------" if preview else "")) for issue in issues: info = [issue.id, issue.type, issue.priority, issue.summary] if preview: info.append(issue.preview) print(" | ".join(info)) print() print("Altogether {} issues.".format(len(issues)), end="") version = VERSION_RE.match(version).group(1) print("See on [issue tracker](https://github.com/robotframework/robotframework/issues?q=milestone%3A{}).".format(version)) @task def print_issues(version=get_version_from_file(), login=None, password=None): """Get issues from GitHub issue tracker. Requires PyGithub <https://github.com/jacquev6/PyGithub>. Install it with: pip install PyGithub Args: version: Version to get the issues for. By default the current version. login: GitHub login. If not given, anonymous login is used. GitHub API has 60 request/hour limit in that case. password: The password for GitHub login. """ issues = _get_issues(version, login, password) print("{:5} {:11} {:8} {}".format("id", "type", "priority", "summary")) for issue in issues: print "{:5} {:11} {:8} {}".format(issue.id, issue.type, issue.priority, issue.summary) class Issue(object): PRIORITIES = ["critical", "high", "medium", "low", ""] def __init__(self, issue): self.id = "#{}".format(issue.number) self.summary = issue.title self.labels = [label.name for label in issue.get_labels()] self.type = self._get_label("bug", "enhancement") self.priority = self._get_priority() def _get_label(self, *values): for value in values: if value in self.labels: return value return None def _get_priority(self): labels = ['prio-' + p for p in self.PRIORITIES if p] priority = self._get_label(*labels) return priority.split('-')[1] if priority else '' def __cmp__(self, other): return cmp(self.order, other.order) @property def order(self): return (self.PRIORITIES.index(self.priority), 0 if self.type == 'bug' else 1, self.id) @property def preview(self): for label in self.labels: if label.startswith(('alpha ', 'beta ', 'rc ')): return label return '' class PreviewMatcher(object): def __init__(self, preview, number): self._patterns = self._get_patterns(preview, number) def _get_patterns(self, preview, number): if not preview: return () return {'a': (self._range('alpha', number),), 'b': ('alpha ?', self._range('beta', number)), 'rc': ('alpha ?', 'beta ?', self._range('rc', number))}[preview] def _range(self, name, number): return '%s [%s]' % (name, ''.join(str(i) for i in range(1, int(number)+1))) def matches(self, labels): return any(fnmatchcase(l, p) for p in self._patterns for l in labels) def __nonzero__(self): return bool(self._patterns)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/tasks.py
0.520009
0.214959
tasks.py
pypi
from __future__ import print_function import os import re from robot import utils from robot.utils.asserts import assert_equals from robot.result.resultbuilder import ExecutionResultBuilder from robot.result.executionresult import Result from robot.result.testsuite import TestSuite from robot.result.testcase import TestCase from robot.result.keyword import Keyword from robot.libraries.BuiltIn import BuiltIn class NoSlotsKeyword(Keyword): pass class NoSlotsTestCase(TestCase): keyword_class = NoSlotsKeyword class NoSlotsTestSuite(TestSuite): test_class = NoSlotsTestCase keyword_class = NoSlotsKeyword class TestCheckerLibrary: def process_output(self, path): path = path.replace('/', os.sep) try: print("Processing output '%s'" % path) result = Result(root_suite=NoSlotsTestSuite()) ExecutionResultBuilder(path).build(result) except: raise RuntimeError('Processing output failed: %s' % utils.get_error_message()) setter = BuiltIn().set_suite_variable setter('$SUITE', process_suite(result.suite)) setter('$STATISTICS', result.statistics) setter('$ERRORS', process_errors(result.errors)) def get_test_from_suite(self, suite, name): tests = self.get_tests_from_suite(suite, name) if len(tests) == 1: return tests[0] err = "No test '%s' found from suite '%s'" if not tests \ else "More than one test '%s' found from suite '%s'" raise RuntimeError(err % (name, suite.name)) def get_tests_from_suite(self, suite, name=None): tests = [test for test in suite.tests if name is None or utils.eq(test.name, name)] for subsuite in suite.suites: tests.extend(self.get_tests_from_suite(subsuite, name)) return tests def get_suite_from_suite(self, suite, name): suites = self.get_suites_from_suite(suite, name) if len(suites) == 1: return suites[0] err = "No suite '%s' found from suite '%s'" if not suites \ else "More than one suite '%s' found from suite '%s'" raise RuntimeError(err % (name, suite.name)) def get_suites_from_suite(self, suite, name): suites = [suite] if utils.eq(suite.name, name) else [] for subsuite in suite.suites: suites.extend(self.get_suites_from_suite(subsuite, name)) return suites def check_test_status(self, test, status=None, message=None): """Verifies that test's status and message are as expected. Expected status and message can be given as parameters. If expected status is not given, expected status and message are read from test's documentation. If documentation doesn't contain any of PASS, FAIL or ERROR, test's status is expected to be PASS. If status is given that is used. Expected message is documentation after given status. Expected message can also be regular expression. In that case expected match starts with REGEXP: , which is ignored in the regexp match. """ if status is not None: test.exp_status = status if message is not None: test.exp_message = message if test.exp_status != test.status: if test.exp_status == 'PASS': msg = "Test was expected to PASS but it FAILED. " msg += "Error message:\n" + test.message else: msg = "Test was expected to FAIL but it PASSED. " msg += "Expected message:\n" + test.exp_message raise AssertionError(msg) if test.exp_message == test.message: return if test.exp_message.startswith('REGEXP:'): pattern = test.exp_message.replace('REGEXP:', '', 1).strip() if re.match('^%s$' % pattern, test.message, re.DOTALL): return if test.exp_message.startswith('GLOB:'): pattern = test.exp_message.replace('GLOB:', '', 1).strip() matcher = utils.Matcher(pattern, caseless=False, spaceless=False) if matcher.match(test.message): return if test.exp_message.startswith('STARTS:'): start = test.exp_message.replace('STARTS:', '', 1).strip() if not start: raise RuntimeError("Empty 'STARTS:' is not allowed") if test.message.startswith(start): return raise AssertionError("Wrong message\n\n" "Expected:\n%s\n\nActual:\n%s\n" % (test.exp_message, test.message)) def should_contain_tests(self, suite, *names, **names_and_statuses): """Verify that specified tests exists in suite. 'names' contains test names to check. These tests are expected to pass/fail as their documentation says. Is same name is given multiple times, test ought to be executed multiple times too. 'names_and_statuses' contains test names with associated custom status in format `STATUS:Message`. Test is given both in 'names' and in 'names_and_statuses', only the latter has an effect. """ tests = self.get_tests_from_suite(suite) expected = [(n, None) for n in names if n not in names_and_statuses] expected.extend((n, s) for n, s in names_and_statuses.items()) tests_msg = "\nExpected tests : %s\nActual tests : %s" \ % (', '.join(sorted([e[0] for e in expected], key=lambda s: s.lower())), ', '.join(sorted([t.name for t in tests], key=lambda s: s.lower()))) if len(tests) != len(expected): raise AssertionError("Wrong number of tests." + tests_msg) for test in tests: print("Verifying test '%s'" % test.name) try: status = self._find_expected_status(test.name, expected) except IndexError: raise AssertionError("Test '%s' was not expected to be run.%s" % (test.name, tests_msg)) expected.pop(expected.index((test.name, status))) if status and ':' in status: status, message = status.split(':', 1) else: message = None self.check_test_status(test, status, message) assert not expected def _find_expected_status(self, test, expected): for name, status in expected: if name == test: return status raise IndexError def should_not_contain_tests(self, suite, *test_names): actual_names = [t.name for t in suite.tests] for name in test_names: if name in actual_names: raise AssertionError('Suite should not have contained test "%s"' % name) def should_contain_suites(self, suite, *expected): print('Suite has suites', suite.suites) expected = sorted(expected) actual = sorted(s.name for s in suite.suites) if len(actual) != len(expected): raise AssertionError("Wrong number of suites.\n" "Expected (%d): %s\n" "Actual (%d): %s" % (len(expected), ', '.join(expected), len(actual), ', '.join(actual))) for name in expected: if not utils.Matcher(name).match_any(actual): raise AssertionError('Suite %s not found' % name) def should_contain_tags(self, test, *tags): print('Test has tags', test.tags) assert_equals(len(test.tags), len(tags), 'Wrong number of tags') tags = sorted(tags, key=lambda s: s.lower().replace('_', '').replace(' ', '')) for act, exp in zip(test.tags, tags): assert_equals(act, exp) def should_contain_keywords(self, item, *kw_names): actual_names = [kw.name for kw in item.keywords] assert_equals(len(actual_names), len(kw_names), 'Wrong number of keywords') for act, exp in zip(actual_names, kw_names): assert_equals(act, exp) def test_should_have_correct_keywords(self, *kw_names, **config): get_var = BuiltIn().get_variable_value suite = get_var('${SUITE}') name = config.get('name', get_var('${TEST NAME}')) kw_index = int(config.get('kw_index', 0)) test = self.get_test_from_suite(suite, name) self.check_test_status(test) self.should_contain_keywords(test.keywords[kw_index], *kw_names) return test def process_suite(suite): for subsuite in suite.suites: process_suite(subsuite) for test in suite.tests: process_test(test) for kw in suite.keywords: process_keyword(kw) suite.setup = suite.keywords.setup suite.teardown = suite.keywords.teardown return suite def process_test(test): if 'FAIL' in test.doc: test.exp_status = 'FAIL' test.exp_message = test.doc.split('FAIL', 1)[1].lstrip() else: test.exp_status = 'PASS' test.exp_message = '' if 'PASS' not in test.doc else test.doc.split('PASS', 1)[1].lstrip() for kw in test.keywords: process_keyword(kw) test.setup = test.keywords.setup test.teardown = test.keywords.teardown test.keywords = test.kws = list(test.keywords.normal) test.keyword_count = test.kw_count = len(test.keywords) def process_keyword(kw): if kw is None: return kw.kws = kw.keywords kw.msgs = kw.messages kw.message_count = kw.msg_count = len(kw.messages) kw.keyword_count = kw.kw_count = len(list(kw.keywords.normal)) for subkw in kw.keywords: process_keyword(subkw) def process_errors(errors): errors.msgs = errors.messages errors.message_count = errors.msg_count = len(errors.messages) return errors
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/atest/resources/TestCheckerLibrary.py
0.548674
0.417034
TestCheckerLibrary.py
pypi
from six import text_type as unicode import os import re from os.path import abspath, dirname, join from subprocess import call, STDOUT import tempfile from robot.utils.asserts import assert_equals, assert_true from robot.utils import decode_output ROBOT_SRC = join(dirname(abspath(__file__)), '..', '..', '..', 'src') DATA_DIR = join(dirname(abspath(__file__)), '..', '..', 'testdata', 'tidy') TEMP_FILE = join(os.getenv('TEMPDIR'), 'tidy-test-dir', 'tidy-test-file.txt') class TidyLib(object): def __init__(self, interpreter): self._tidy = [interpreter, '-m', 'robot.tidy'] self._interpreter = interpreter def run_tidy(self, options, input, output=None, tidy=None): """Runs tidy in the operating system and returns output.""" command = (tidy or self._tidy)[:] if options: command.extend(options.split(' ')) command.append(self._path(input)) if output: command.append(output) print(' '.join(command)) with tempfile.TemporaryFile() as stdout: rc = call(command, stdout=stdout, stderr=STDOUT, cwd=ROBOT_SRC, shell=os.sep=='\\') stdout.seek(0) content = decode_output(stdout.read().strip()) if rc: raise RuntimeError(content) return content def run_tidy_and_check_result(self, options, input, output=TEMP_FILE, expected=None): """Runs tidy and checks that output matches content of file `expected`.""" result = self.run_tidy(options, input, output) return self.compare_tidy_results(output or result, expected or input) def run_tidy_as_a_script_and_check_result(self, options, input, output=TEMP_FILE, expected=None): """Runs tidy and checks that output matches content of file `expected`.""" tidy = [self._interpreter, join(ROBOT_SRC, 'robot', 'tidy.py')] result = self.run_tidy(options, input, output, tidy) return self.compare_tidy_results(output or result, expected or input) def compare_tidy_results(self, result, expected, *filters): if os.path.isfile(result): result = self._read(result) filters = [re.compile('^%s$' % f) for f in filters] expected = self._read(expected) result_lines = result.splitlines() expected_lines = expected.splitlines() msg = "Actual:\n%s\n\nExpected:\n%s\n\n" \ % (repr(result).replace('\\n', '\\n\n'), repr(expected).replace('\\n', '\\n\n')) assert_equals(len(result_lines), len(expected_lines), msg) for res, exp in zip(result_lines, expected_lines): filter = self._filter_matches(filters, exp) if not filter: assert_equals(repr(unicode(res)), repr(unicode(exp)), msg) else: assert_true(filter.match(res), '%s: %r does not match %r' % (msg, res, filter.pattern)) return result def _filter_matches(self, filters, expected): for filter in filters: if filter.match(expected): return filter return None def _path(self, path): return abspath(join(DATA_DIR, path.replace('/', os.sep))) def _read(self, path): with open(self._path(path), 'rb') as f: return f.read().decode('UTF-8')
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/atest/robot/tidy/TidyLib.py
0.617513
0.259955
TidyLib.py
pypi
.. _Documentation syntax: Documentation formatting ======================== It is possible to use simple HTML formatting with `test suite`__, `test case`__ and `user keyword`__ documentation and `free test suite metadata`_ in the test data, as well as when `documenting test libraries`__. The formatting is similar to the style used in most wikis, and it is designed to be understandable both as plain text and after the HTML transformation. __ `test suite documentation`_ __ `test case documentation`_ __ `user keyword documentation`_ __ `Documenting libraries`_ .. contents:: :depth: 2 :local: Representing newlines --------------------- Newlines in test data ~~~~~~~~~~~~~~~~~~~~~ When documenting test suites, test cases and keywords or adding metadata to test suites, newlines can be added manually using the `literal newline character sequence`__ (`\n`). __ `Handling whitespace`_ .. sourcecode:: robotframework *** Settings *** Documentation First line.\n\nSecond paragraph, this time\nwith multiple lines. Metadata Example Value\nin two lines Adding newlines manually to a long documentation takes some effort and extra characters also make the documentation harder to read. Starting from Robot Framework 2.7, this is not required as newlines are inserted automatically between `continued documentation and metadata lines`__. In practice this means that the above example could be written also as follows. .. sourcecode:: robotframework *** Settings *** Documentation ... First line. ... ... Second paragraph, this time ... with multiple lines. Metadata ... Example ... Value ... in two lines No automatic newline is added if a line already ends with a literal newline or if it ends with an `escaping backslash`__. If documentation or metadata is defined in multiple columns, cells in a same row are concatenated together with spaces. This kind of splitting can be a good idea especially when using the `HTML format`_ and columns are narrow. Different ways to split documentation are illustrated in the examples below where all test cases end up having the same two line documentation. __ `Dividing test data to several rows`_ __ Escaping_ .. sourcecode:: robotframework *** Test Cases *** Example 1 [Documentation] First line\n Second line in multiple parts No Operation Example 2 [Documentation] First line ... Second line in multiple parts No Operation Example 3 [Documentation] First line\n ... Second line in\ ... multiple parts No Operation Documentation in test libraries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With library documentations normal newlines are enough, and for example the following keyword documentation would create same end result as the test suite documentation in the previous section. .. sourcecode:: python def example_keyword(): """First line. Second paragraph, this time with multiple lines. """ pass Paragraphs ---------- Starting from Robot Framework 2.7.2, all regular text in the formatted HTML documentation is represented as paragraphs. In practice, lines separated by a single newline will be combined in a paragraph regardless whether the newline is added manually or automatically. Multiple paragraphs can be separated with an empty line (i.e. two newlines) and also tables, lists, and other specially formatted blocks discussed in subsequent sections end a paragraph. For example, the following test suite or resource file documentation: .. sourcecode:: robotframework *** Settings *** Documentation ... First paragraph has only one line. ... ... Second paragraph, this time created ... with multiple lines. will be formatted in HTML as: .. raw:: html <div class="doc"> <p>First paragraph has only one line.</p> <p>Second paragraph, this time created with multiple lines.</p> </div> .. note:: Prior to 2.7.2 handling paragraphs was inconsistent. In documentation generated with Libdoc_ lines were combined to paragraphs but in documentations shown in log and report they were not. Inline styles ------------- The documentation syntax supports inline styles **bold**, *italic* and `code`. Bold text can be created by having an asterisk before and after the selected word or words, for example `*this is bold*`. Italic style works similarly, but the special character to use is an underscore, for example, `_italic_`. It is also possible to have bold italic with the syntax `_*bold italic*_`. The code style is created using double backticks like :codesc:`\`\`code\`\``. The result is monospaced text with light gray background. Support for code style is new in Robot Framework 2.8.6. Asterisks, underscores or double backticks alone, or in the middle of a word, do not start formatting, but punctuation characters before or after them are allowed. When multiple lines form a paragraph__, all inline styles can span over multiple lines. __ paragraphs_ .. raw:: html <table class="tabular docutils"> <caption>Inline style examples</caption> <tr> <th>Unformatted</th> <th>Formatted</th> </tr> <tr> <td>*bold*</td> <td><b>bold</b></td> </tr> <tr> <td>_italic_</td> <td><i>italic</i></td> </tr> <tr> <td>_*bold italic*_</td> <td><i><b>bold italic</b></i></td> </tr> <tr> <td>``code``</td> <td><code>code</code></td> </tr> <tr> <td>*bold*, then _italic_ and finally ``some code``</td> <td><b>bold</b>, then <i>italic</i> and finally <code>some code</code></td> </tr> <tr> <td>This is *bold\n<br>on multiple\n<br>lines*.</td> <td>This is <b>bold</b><br><b>on multiple</b><br><b>lines</b>.</td> </tr> </table> URLs ---- All strings that look like URLs are automatically converted into clickable links. Additionally, URLs that end with extension :file:`.jpg`, :file:`.jpeg`, :file:`.png`, :file:`.gif` or :file:`.bmp` (case-insensitive) will automatically create images. For example, URLs like `http://example.com` are turned into links, and `http:///host/image.jpg` and `file:///path/chart.png` into images. The automatic conversion of URLs to links is applied to all the data in logs and reports, but creating images is done only for test suite, test case and keyword documentation, and for test suite metadata. Custom links and images ----------------------- Starting from Robot Framework 2.7, it is possible to create custom links and embed images using special syntax `[link|content]`. This creates a link or image depending are `link` and `content` images. They are considered images if they have the same image extensions that are special with URLs_. The surrounding square brackets and the pipe character between the parts are mandatory in all cases. Link with text content ~~~~~~~~~~~~~~~~~~~~~~ If neither `link` nor `content` is an image, the end result is a normal link where `link` is the link target and `content` the visible text:: [file.html|this file] -> <a href="file.html">this file</a> [http://host|that host] -> <a href="http://host">that host</a> Link with image content ~~~~~~~~~~~~~~~~~~~~~~~ If `content` is an image, you get a link where the link content is an image. Link target is created by `link` and it can be either text or image:: [robot.html|robot.png] -> <a href="robot.html"><img src="robot.png"></a> [image.jpg|thumb.jpg] -> <a href="image.jpg"><img src="thumb.jpg"></a> Image with title text ~~~~~~~~~~~~~~~~~~~~~ If `link` is an image but `content` is not, the syntax creates an image where the `content` is the title text shown when mouse is over the image:: [robot.jpeg|Robot rocks!] -> <img src="robot.jpeg" title="Robot rocks!"> Section titles -------------- If documentation gets longer, it is often a good idea to split it into sections. Starting from Robot Framework 2.7.5, it is possible to separate sections with titles using syntax `= My Title =`, where the number of equal signs denotes the level of the title:: = First section = == Subsection == Some text. == Second subsection == More text. = Second section = You probably got the idea. Notice that only three title levels are supported and that spaces between equal signs and the title text are mandatory. Tables ------ Tables are created using pipe characters with spaces around them as column separators and newlines as row separators. Header cells can be created by surrounding the cell content with equal signs and optional spaces like `= Header =` or `=Header=`. Tables cells can also contain links and formatting such as bold and italic:: | =A= | =B= | = C = | | _1_ | Hello | world! | | _2_ | Hi | The created table always has a thin border and normal text is left-aligned. Text in header cells is bold and centered. Empty cells are automatically added to make rows equally long. For example, the above example would be formatted like this in HTML: .. raw:: html <div class="doc"> <table> <tr><th>A</th><th>B</th><th>C</th></tr> <tr><td><i>1</i></td><td>Hello</td><td>world</td></tr> <tr><td><i>2</i></td><td>Hi</td><td></td></tr> </table> </div> .. note:: Support for table headers is a new feature in Robot Framework 2.8.2. Lists ----- Lists are created by starting a line with a hyphen and space ('- '). List items can be split into multiple lines by indenting continuing lines with one or more spaces. A line that does not start with '- ' and is not indented ends the list:: Example: - a list item - second list item is continued This is outside the list. The above documentation is formatted like this in HTML: .. raw:: html <div class="doc"> <p>Example:</p> <ul> <li>a list item</li> <li>second list item is continued</li> </ul> <p>This is outside the list.</p> </div> .. note:: Support for formatting lists was added in 2.7.2. Prior to that, the same syntax prevented Libdoc_ from combining lines to paragraphs, so the end result was similar. Support for splitting list items into multiple lines was added in 2.7.4. Preformatted text ----------------- Starting from Robot Framework 2.7, it is possible to embed blocks of preformatted text in the documentation. Preformatted block is created by starting lines with '| ', one space being mandatory after the pipe character except on otherwise empty lines. The starting '| ' sequence will be removed from the resulting HTML, but all other whitespace is preserved. In the following documentation, the two middle lines form a preformatted block when converted to HTML:: Doc before block: | inside block | some additional whitespace After block. The above documentation is formatted like this: .. raw:: html <div class="doc"> <p>Doc before block:</p> <pre>inside block some additional whitespace</pre> <p>After block.</p> </div> When documenting suites, tests or keywords in Robot Framework test data, having multiple spaces requires escaping with a backslash to `prevent ignoring spaces`_. The example above would thus be written like this:: Doc before block: | inside block | \ \ \ some \ \ additional whitespace After block. Horizontal ruler ---------------- Horizontal rulers (the `<hr>` tag) make it possible to separate larger sections from each others, and they can be created by having three or more hyphens alone on a line:: Some text here. --- More text... The above documentation is formatted like this: .. raw:: html <div class="doc"> <p>Some text here.</p> <hr> <p>More text...</p> </div>
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/Appendices/DocumentationFormatting.rst
0.896874
0.654004
DocumentationFormatting.rst
pypi
class LoggingLibrary: """Library for logging messages. = Table of contents = - `Usage` - `Valid log levels` - `Examples` - `Importing` - `Shortcuts` - `Keywords` = Usage = This library has several keyword, for example `Log Message`, for logging messages. In reality the library is used only for _Libdoc_ demonstration purposes. = Valid log levels = Valid log levels are ``INFO``, ``DEBUG``, and ``TRACE``. The default log level can be set during `importing`. = Examples = Notice how keywords are linked from examples. | `Log Message` | My message | | | | `Log Two Messages` | My message | Second message | level=DEBUG | | `Log Messages` | First message | Second message | Third message | """ ROBOT_LIBRARY_VERSION = '0.1' def __init__(self, default_level='INFO'): """The default log level can be given at library import time. See `Valid log levels` section for information about available log levels. Examples: | =Setting= | =Value= | =Value= | =Comment= | | Library | LoggingLibrary | | # Use default level (INFO) | | Library | LoggingLibrary | DEBUG | # Use the given level | """ self.default_level = self._verify_level(default_level) def _verify_level(self, level): level = level.upper() if level not in ['INFO', 'DEBUG', 'TRACE']: raise RuntimeError("Invalid log level'%s'. Valid levels are " "'INFO', 'DEBUG', and 'TRACE'") return level def log_message(self, message, level=None): """Writes given message to the log file using the specified log level. The message to log and the log level to use are defined using ``message`` and ``level`` arguments, respectively. If no log level is given, the default level given during `library importing` is used. """ level = self._verify_level(level) if level else self.default_level print "*%s* %s" % (level, message) def log_two_messages(self, message1, message2, level=None): """Writes given messages to the log file using the specified log level. See `Log Message` keyword for more information. """ self.log_message(message1, level) self.log_message(message2, level) def log_messages(self, *messages): """Logs given messages using the log level set during `importing`. See also `Log Message` and `Log Two Messages`. """ for msg in messages: self.log_message(msg)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/SupportingTools/LoggingLibrary.py
0.912175
0.460713
LoggingLibrary.py
pypi
Basic usage =========== Robot Framework test cases are executed from the command line, and the end result is, by default, an `output file`_ in XML format and an HTML report_ and log_. After the execution, output files can be combined and otherwise `post-processed`__ with the ``rebot`` tool. __ `Post-processing outputs`_ .. contents:: :depth: 2 :local: Starting test execution ----------------------- Synopsis ~~~~~~~~ :: pybot|jybot|ipybot [options] data_sources python|jython|ipy -m robot.run [options] data_sources python|jython|ipy path/to/robot/run.py [options] data_sources java -jar robotframework.jar [options] data_sources Test execution is normally started using ``pybot``, ``jybot`` or ``ipybot`` `runner script`_. These scripts are otherwise identical, but the first one executes tests using Python_, the second using Jython_, and the last one using IronPython_. Alternatively it is possible to use ``robot.run`` `entry point`_ either as a module or a script using any interpreter, or use the `standalone JAR distribution`_. Regardless of execution approach, the path (or paths) to the test data to be executed is given as an argument after the command. Additionally, different command line options can be used to alter the test execution or generated outputs in some way. Specifying test data to be executed ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Robot Framework test cases are created in files__ and directories__, and they are executed by giving the path to the file or directory in question to the selected runner script. The path can be absolute or, more commonly, relative to the directory where tests are executed from. The given file or directory creates the top-level test suite, which gets its name, unless overridden with the :option:`--name` option__, from the `file or directory name`__. Different execution possibilities are illustrated in the examples below. Note that in these examples, as well as in other examples in this section, only the ``pybot`` script is used, but other execution approaches could be used similarly. __ `Test case files`_ __ `Test suite directories`_ __ `Setting the name`_ __ `Test suite name and documentation`_ :: pybot test_cases.html pybot path/to/my_tests/ pybot c:\robot\tests.txt It is also possible to give paths to several test case files or directories at once, separated with spaces. In this case, Robot Framework creates the top-level test suite automatically, and the specified files and directories become its child test suites. The name of the created test suite is got from child suite names by catenating them together with an ampersand (&) and spaces. For example, the name of the top-level suite in the first example below is :name:`My Tests & Your Tests`. These automatically created names are often quite long and complicated. In most cases, it is thus better to use the :option:`--name` option for overriding it, as in the second example below:: pybot my_tests.html your_tests.html pybot --name Example path/to/tests/pattern_*.html Using command line options -------------------------- Robot Framework provides a number of command line options that can be used to control how test cases are executed and what outputs are generated. This section explains the option syntax, and what options actually exist. How they can be used is discussed elsewhere in this chapter. Using options ~~~~~~~~~~~~~ When options are used, they must always be given between the runner script and the data sources. For example:: pybot -L debug my_tests.txt pybot --include smoke --variable HOST:10.0.0.42 path/to/tests/ Short and long options ~~~~~~~~~~~~~~~~~~~~~~ Options always have a long name, such as :option:`--name`, and the most frequently needed options also have a short name, such as :option:`-N`. In addition to that, long options can be shortened as long as they are unique. For example, `--logle DEBUG` works, while `--lo log.html` does not, because the former matches only :option:`--loglevel`, but the latter matches several options. Short and shortened options are practical when executing test cases manually, but long options are recommended in `start-up scripts`_, because they are easier to understand. The long option format is case-insensitive, which facilitates writing option names in an easy-to-read format. For example, :option:`--SuiteStatLevel` is equivalent to, but easier to read than :option:`--suitestatlevel`. Setting option values ~~~~~~~~~~~~~~~~~~~~~ Most of the options require a value, which is given after the option name. Both short and long options accept the value separated from the option name with a space, as in `--include tag` or `-i tag`. With long options, the separator can also be the equals sign, for example `--include=tag`, and with short options the separator can be omitted, as in `-itag`. Some options can be specified several times. For example, `--variable VAR1:value --variable VAR2:another` sets two variables. If the options that take only one value are used several times, the value given last is effective. Disabling options accepting no values ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Options accepting no values can be disabled by using the same option again with `no` prefix added or dropped. The last option has precedence regardless of how many times options are used. For example, `--dryrun --dryrun --nodryrun --nostatusrc --statusrc` would not activate the dry-run mode and would return normal status rc. .. note:: Support for adding or dropping `no` prefix is a new feature in Robot Framework 2.9. In earlier versions options accepting no values could be disabled by using the exact same option again. Simple patterns ~~~~~~~~~~~~~~~ Many command line options take arguments as *simple patterns*. These `glob-like patterns`__ are matched according to the following rules: - `*` is a wildcard matching any string, even an empty string. - `?` is a wildcard matching any single character. - Unless noted otherwise, pattern matching is case, space, and underscore insensitive. Examples:: --test Example* # Matches tests with name starting 'Example', case insensitively. --include f?? # Matches tests with a tag that starts with 'f' or 'F' and is three characters long. __ http://en.wikipedia.org/wiki/Glob_(programming) Tag patterns ~~~~~~~~~~~~ Most tag related options accept arguments as *tag patterns*. They have all the same characteristics as `simple patterns`_, but they also support `AND`, `OR` and `NOT` operators explained below. These operators can be used for combining two or more individual tags or patterns together. `AND` or `&` The whole pattern matches if all individual patterns match. `AND` and `&` are equivalent:: --include fooANDbar # Matches tests containing tags 'foo' and 'bar'. --exclude xx&yy&zz # Matches tests containing tags 'xx', 'yy', and 'zz'. `OR` The whole pattern matches if any individual pattern matches:: --include fooORbar # Matches tests containing either tag 'foo' or tag 'bar'. --exclude xxORyyORzz # Matches tests containing any of tags 'xx', 'yy', or 'zz'. `NOT` The whole pattern matches if the pattern on the left side matches but the one on the right side does not. If used multiple times, none of the patterns after the first `NOT` must not match:: --include fooNOTbar # Matches tests containing tag 'foo' but not tag 'bar'. --exclude xxNOTyyNOTzz # Matches tests containing tag 'xx' but not tag 'yy' or tag 'zz'. Starting from Robot Framework 2.9 the pattern can also start with `NOT` in which case the pattern matches if the pattern after `NOT` does not match:: --include NOTfoo # Matches tests not containing tag 'foo' --include NOTfooANDbar # Matches tests not containing tags 'foo' and 'bar' The above operators can also be used together. The operator precedence, from highest to lowest, is `AND`, `OR` and `NOT`:: --include xANDyORz # Matches tests containing either tags 'x' and 'y', or tag 'z'. --include xORyNOTz # Matches tests containing either tag 'x' or 'y', but not tag 'z'. --include xNOTyANDz # Matches tests containing tag 'x', but not tags 'y' and 'z'. Although tag matching itself is case-insensitive, all operators are case-sensitive and must be written with upper case letters. If tags themselves happen to contain upper case `AND`, `OR` or `NOT`, they need to specified using lower case letters to avoid accidental operator usage:: --include port # Matches tests containing tag 'port', case-insensitively --include PORT # Matches tests containing tag 'P' or 'T', case-insensitively --exclude handoverORportNOTnotification .. note:: `OR` operator is new in Robot Framework 2.8.4. ``ROBOT_OPTIONS`` and ``REBOT_OPTIONS`` environment variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Environment variables ``ROBOT_OPTIONS`` and ``REBOT_OPTIONS`` can be used to specify default options for `test execution`_ and `result post-processing`__, respectively. The options and their values must be defined as a space separated list and they are placed in front of any explicit options on the command line. The main use case for these environment variables is setting global default values for certain options to avoid the need to repeat them every time tests are run or ``rebot`` used. .. sourcecode:: bash export ROBOT_OPTIONS="--critical regression --tagdoc mytag:Example_doc" pybot tests.txt export REBOT_OPTIONS="--reportbackground green:yellow:red" rebot --name example output.xml .. note:: Support for ``ROBOT_OPTIONS`` and ``REBOT_OPTIONS`` environment variables was added in Robot Framework 2.8.2. __ `Post-processing outputs`_ Test results ------------ Command line output ~~~~~~~~~~~~~~~~~~~ The most visible output from test execution is the output displayed in the command line. All executed test suites and test cases, as well as their statuses, are shown there in real time. The example below shows the output from executing a simple test suite with only two test cases:: ============================================================================== Example test suite ============================================================================== First test :: Possible test documentation | PASS | ------------------------------------------------------------------------------ Second test | FAIL | Error message is displayed here ============================================================================== Example test suite | FAIL | 2 critical tests, 1 passed, 1 failed 2 tests total, 1 passed, 1 failed ============================================================================== Output: /path/to/output.xml Report: /path/to/report.html Log: /path/to/log.html Starting from Robot Framework 2.7, there is also a notification on the console whenever a top-level keyword in a test case ends. A green dot is used if a keyword passes and a red F if it fails. These markers are written to the end of line and they are overwritten by the test status when the test itself ends. Writing the markers is disabled if console output is redirected to a file. Generated output files ~~~~~~~~~~~~~~~~~~~~~~ The command line output is very limited, and separate output files are normally needed for investigating the test results. As the example above shows, three output files are generated by default. The first one is in XML format and contains all the information about test execution. The second is a higher-level report and the third is a more detailed log file. These files and other possible output files are discussed in more detail in the section `Different output files`_. Return codes ~~~~~~~~~~~~ Runner scripts communicate the overall test execution status to the system running them using return codes. When the execution starts successfully and no `critical test`_ fail, the return code is zero. All possible return codes are explained in the table below. .. table:: Possible return codes :class: tabular ======== ========================================== RC Explanation ======== ========================================== 0 All critical tests passed. 1-249 Returned number of critical tests failed. 250 250 or more critical failures. 251 Help or version information printed. 252 Invalid test data or command line options. 253 Test execution stopped by user. 255 Unexpected internal error. ======== ========================================== Return codes should always be easily available after the execution, which makes it easy to automatically determine the overall execution status. For example, in bash shell the return code is in special variable `$?`, and in Windows it is in `%ERRORLEVEL%` variable. If you use some external tool for running tests, consult its documentation for how to get the return code. The return code can be set to 0 even if there are critical failures using the :option:`--NoStatusRC` command line option. This might be useful, for example, in continuous integration servers where post-processing of results is needed before the overall status of test execution can be determined. .. note:: Same return codes are also used with rebot_. Errors and warnings during execution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ During the test execution there can be unexpected problems like failing to import a library or a resource file or a keyword being deprecated__. Depending on the severity such problems are categorized as errors or warnings and they are written into the console (using the standard error stream), shown on a separate *Test Execution Errors* section in log files, and also written into Robot Framework's own `system log`_. Normally these errors and warnings are generated by Robot Framework itself, but libraries can also log `errors and warnings`_. Example below illustrates how errors and warnings look like in the log file. .. raw:: html <table class="messages"> <tr> <td class="time">20090322&nbsp;19:58:42.528</td> <td class="error level">ERROR</td> <td class="msg">Error in file '/home/robot/tests.html' in table 'Setting' in element on row 2: Resource file 'resource.html' does not exist</td> </tr> <tr> <td class="time">20090322&nbsp;19:58:43.931</td> <td class="warn level">WARN</td> <td class="msg">Keyword 'SomeLibrary.Example Keyword' is deprecated. Use keyword `Other Keyword` instead.</td> </tr> </table> __ `Deprecating keywords`_ Escaping complicated characters ------------------------------- Because spaces are used for separating options from each other, it is problematic to use them in option values. Some options, such as :option:`--name`, automatically convert underscores to spaces, but with others spaces must be escaped. Additionally, many special characters are complicated to use on the command line. Because escaping complicated characters with a backslash or quoting the values does not always work too well, Robot Framework has its own generic escaping mechanism. Another possibility is using `argument files`_ where options can be specified in the plain text format. Both of these mechanisms work when executing tests and when post-processing outputs, and also some of the external supporting tools have the same or similar capabilities. In Robot Framework's command line escaping mechanism, problematic characters are escaped with freely selected text. The command line option to use is :option:`--escape (-E)`, which takes an argument in the format `what:with`, where `what` is the name of the character to escape and `with` is the string to escape it with. Characters that can be escaped are listed in the table below: .. table:: Available escapes :class: tabular ========= ============= ========= ============= Character Name to use Character Name to use ========= ============= ========= ============= & amp ( paren1 ' apos ) paren2 @ at % percent \\ bslash \| pipe : colon ? quest , comma " quot { curly1 ; semic } curly2 / slash $ dollar \ space ! exclam [ square1 > gt ] square2 # hash \* star < lt \ \ ========= ============= ========= ============= The following examples make the syntax more clear. In the first example, the metadata `X` gets the value `Value with spaces`, and in the second example variable `${VAR}` is assigned to `"Hello, world!"`:: --escape space:_ --metadata X:Value_with_spaces -E space:SP -E quot:QU -E comma:CO -E exclam:EX -v VAR:QUHelloCOSPworldEXQU Note that all the given command line arguments, including paths to test data, are escaped. Escape character sequences thus need to be selected carefully. Argument files -------------- Argument files allow placing all or some command line options and arguments into an external file where they will be read. This avoids the problems with characters that are problematic on the command line. If lot of options or arguments are needed, argument files also prevent the command that is used on the command line growing too long. Argument files are taken into use with :option:`--argumentfile (-A)` option along with possible other command line options. Argument file syntax ~~~~~~~~~~~~~~~~~~~~ Argument files can contain both command line options and paths to the test data, one option or data source per line. Both short and long options are supported, but the latter are recommended because they are easier to understand. Argument files can contain any characters without escaping, but spaces in the beginning and end of lines are ignored. Additionally, empty lines and lines starting with a hash mark (#) are ignored:: --doc This is an example (where "special characters" are ok!) --metadata X:Value with spaces --variable VAR:Hello, world! # This is a comment path/to/my/tests In the above example the separator between options and their values is a single space. In Robot Framework 2.7.6 and newer it is possible to use either an equal sign (=) or any number of spaces. As an example, the following three lines are identical:: --name An Example --name=An Example --name An Example If argument files contain non-ASCII characters, they must be saved using UTF-8 encoding. Using argument files ~~~~~~~~~~~~~~~~~~~~ Argument files can be used either alone so that they contain all the options and paths to the test data, or along with other options and paths. When an argument file is used with other arguments, its contents are placed into the original list of arguments to the same place where the argument file option was. This means that options in argument files can override options before it, and its options can be overridden by options after it. It is possible to use :option:`--argumentfile` option multiple times or even recursively:: pybot --argumentfile all_arguments.txt pybot --name Example --argumentfile other_options_and_paths.txt pybot --argumentfile default_options.txt --name Example my_tests.html pybot -A first.txt -A second.txt -A third.txt tests.txt Reading argument files from standard input ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Special argument file name `STDIN` can be used to read arguments from the standard input stream instead of a file. This can be useful when generating arguments with a script:: generate_arguments.sh | pybot --argumentfile STDIN generate_arguments.sh | pybot --name Example --argumentfile STDIN tests.txt Getting help and version information ------------------------------------ Both when executing test cases and when post-processing outputs, it is possible to get command line help with the option :option:`--help (-h)`. These help texts have a short general overview and briefly explain the available command line options. All runner scripts also support getting the version information with the option :option:`--version`. This information also contains Python or Jython version and the platform type:: $ pybot --version Robot Framework 2.7 (Python 2.6.6 on linux2) $ jybot --version Robot Framework 2.7 (Jython 2.5.2 on java1.6.0_21) C:\>rebot --version Rebot 2.7 (Python 2.7.1 on win32) .. _start-up script: .. _start-up scripts: Creating start-up scripts ------------------------- Test cases are often executed automatically by a continuous integration system or some other mechanism. In such cases, there is a need to have a script for starting the test execution, and possibly also for post-processing outputs somehow. Similar scripts are also useful when running tests manually, especially if a large number of command line options are needed or setting up the test environment is complicated. In UNIX-like environments, shell scripts provide a simple but powerful mechanism for creating custom start-up scripts. Windows batch files can also be used, but they are more limited and often also more complicated. A platform-independent alternative is using Python or some other high-level programming language. Regardless of the language, it is recommended that long option names are used, because they are easier to understand than the short names. In the first examples, the same web tests are executed with different browsers and the results combined afterwards. This is easy with shell scripts, as practically you just list the needed commands one after another: .. sourcecode:: bash #!/bin/bash pybot --variable BROWSER:Firefox --name Firefox --log none --report none --output out/fx.xml login pybot --variable BROWSER:IE --name IE --log none --report none --output out/ie.xml login rebot --name Login --outputdir out --output login.xml out/fx.xml out/ie.xml Implementing the above example with Windows batch files is not very complicated, either. The most important thing to remember is that because ``pybot`` and ``rebot`` are implemented as batch files, ``call`` must be used when running them from another batch file. Otherwise execution would end when the first batch file is finished. .. sourcecode:: bat @echo off call pybot --variable BROWSER:Firefox --name Firefox --log none --report none --output out\fx.xml login call pybot --variable BROWSER:IE --name IE --log none --report none --output out\ie.xml login call rebot --name Login --outputdir out --output login.xml out\fx.xml out\ie.xml In the next examples, jar files under the :file:`lib` directory are put into ``CLASSPATH`` before starting the test execution. In these examples, start-up scripts require that paths to the executed test data are given as arguments. It is also possible to use command line options freely, even though some options have already been set in the script. All this is relatively straight-forward using bash: .. sourcecode:: bash #!/bin/bash cp=. for jar in lib/*.jar; do cp=$cp:$jar done export CLASSPATH=$cp jybot --ouputdir /tmp/logs --suitestatlevel 2 $* Implementing this using Windows batch files is slightly more complicated. The difficult part is setting the variable containing the needed JARs inside a For loop, because, for some reason, that is not possible without a helper function. .. sourcecode:: bat @echo off set CP=. for %%jar in (lib\*.jar) do ( call :set_cp %%jar ) set CLASSPATH=%CP% jybot --ouputdir c:\temp\logs --suitestatlevel 2 %* goto :eof :: Helper for setting variables inside a for loop :set_cp set CP=%CP%;%1 goto :eof Modifying Java startup parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sometimes when using Jython there is need to alter the Java startup parameters. The most common use case is increasing the JVM maximum memory size as the default value may not be enough for creating reports and logs when outputs are very big. There are several ways to configure JVM options: 1. Modify Jython start-up script (``jython`` shell script or ``jython.bat`` batch file) directly. This is a permanent configuration. 2. Set ``JYTHON_OPTS`` environment variable. This can be done permanently in operating system level or per execution in a custom start-up script. 3. Pass the needed Java parameters wit :option:`-J` option to Jython start-up script that will pass them forward to Java. This is especially easy when using `direct entry points`_:: jython -J-Xmx1024m -m robot.run some_tests.txt Debugging problems ------------------ A test case can fail because the system under test does not work correctly, in which case the test has found a bug, or because the test itself is buggy. The error message explaining the failure is shown on the `command line output`_ and in the `report file`_, and sometimes the error message alone is enough to pinpoint the problem. More often that not, however, `log files`_ are needed because they have also other log messages and they show which keyword actually failed. When a failure is caused by the tested application, the error message and log messages ought to be enough to understand what caused it. If that is not the case, the test library does not provide `enough information`__ and needs to be enhanced. In this situation running the same test manually, if possible, may also reveal more information about the issue. Failures caused by test cases themselves or by keywords they use can sometimes be hard to debug. If the error message, for example, tells that a keyword is used with wrong number of arguments fixing the problem is obviously easy, but if a keyword is missing or fails in unexpected way finding the root cause can be harder. The first place to look for more information is the `execution errors`_ section in the log file. For example, an error about a failed test library import may well explain why a test has failed due to a missing keyword. If the log file does not provide enough information by default, it is possible to execute tests with a lower `log level`_. For example tracebacks showing where in the code the failure occurred are logged using the `DEBUG` level, and this information is invaluable when the problem is in an individual keyword. If the log file still does not have enough information, it is a good idea to enable the syslog_ and see what information it provides. It is also possible to add some keywords to the test cases to see what is going on. Especially BuiltIn_ keywords :name:`Log` and :name:`Log Variables` are useful. If nothing else works, it is always possible to search help from `mailing lists`_ or elsewhere. __ `Communicating with Robot Framework`_ Using the Python debugger (pdb) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is also possible to use the pdb__ module from the Python standard library to set a break point and interactively debug a running test. The typical way of invoking pdb by inserting .. sourcecode:: python import pdb; pdb.set_trace() at the location you want to break into debugger will not work correctly with Robot Framework, though, as the standard output stream is redirected during keyword execution. Instead, you can use the following: .. sourcecode:: python import sys, pdb; pdb.Pdb(stdout=sys.__stdout__).set_trace() __ http://docs.python.org/2/library/pdb.html
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/ExecutingTestCases/BasicUsage.rst
0.942678
0.780056
BasicUsage.rst
pypi
Test execution ============== This section describes how the test suite structure created from the parsed test data is executed, how to continue executing a test case after failures, and how to stop the whole test execution gracefully. .. contents:: :depth: 2 :local: Execution flow -------------- Executed suites and tests ~~~~~~~~~~~~~~~~~~~~~~~~~ Test cases are always executed within a test suite. A test suite created from a `test case file`_ has tests directly, whereas suites created from directories__ have child test suites which either have tests or their own child suites. By default all the tests in an executed suite are run, but it is possible to `select tests`__ using options :option:`--test`, :option:`--suite`, :option:`--include` and :option:`--exclude`. Suites containing no tests are ignored. The execution starts from the top-level test suite. If the suite has tests they are executed one-by-one, and if it has suites they are executed recursively in depth-first order. When an individual test case is executed, the keywords it contains are run in a sequence. Normally the execution of the current test ends if any of the keywords fails, but it is also possible to `continue after failures`__. The exact `execution order`_ and how possible `setups and teardowns`_ affect the execution are discussed in the following sections. __ `Test suite directories`_ __ `Selecting test cases`_ __ `Continue on failure`_ Setups and teardowns ~~~~~~~~~~~~~~~~~~~~ Setups and teardowns can be used on `test suite`__, `test case`__ and `user keyword`__ levels. __ `Test setup and teardown`_ __ `Suite setup and teardown`_ __ `User keyword teardown`_ Suite setup ''''''''''' If a test suite has a setup, it is executed before its tests and child suites. If the suite setup passes, test execution continues normally. If it fails, all the test cases the suite and its child suites contain are marked failed. The tests and possible suite setups and teardowns in the child test suites are not executed. Suite setups are often used for setting up the test environment. Because tests are not run if the suite setup fails, it is easy to use suite setups for verifying that the environment is in state in which the tests can be executed. Suite teardown '''''''''''''' If a test suite has a teardown, it is executed after all its test cases and child suites. Suite teardowns are executed regardless of the test status and even if the matching suite setup fails. If the suite teardown fails, all tests in the suite are marked failed afterwards in reports and logs. Suite teardowns are mostly used for cleaning up the test environment after the execution. To ensure that all these tasks are done, `all the keywords used in the teardown are executed`__ even if some of them fail. __ `Continue on failure`_ Test setup '''''''''' Possible test setup is executed before the keywords of the test case. If the setup fails, the keywords are not executed. The main use for test setups is setting up the environment for that particular test case. Test teardown ''''''''''''' Possible test teardown is executed after the test case has been executed. It is executed regardless of the test status and also if test setup has failed. Similarly as suite teardown, test teardowns are used mainly for cleanup activities. Also they are executed fully even if some of their keywords fail. Keyword teardown '''''''''''''''' `User keywords`_ cannot have setups, but they can have teardowns that work exactly like other teardowns. Keyword teardowns are run after the keyword is executed otherwise, regardless the status, and they are executed fully even if some of their keywords fail. Execution order ~~~~~~~~~~~~~~~ Test cases in a test suite are executed in the same order as they are defined in the test case file. Test suites inside a higher level test suite are executed in case-insensitive alphabetical order based on the file or directory name. If multiple files and/or directories are given from the command line, they are executed in the order they are given. If there is a need to use certain test suite execution order inside a directory, it is possible to add prefixes like :file:`01` and :file:`02` into file and directory names. Such prefixes are not included in the generated test suite name if they are separated from the base name of the suite with two underscores:: 01__my_suite.html -> My Suite 02__another_suite.html -> Another Suite If the alphabetical ordering of test suites inside suites is problematic, a good workaround is giving them separately in the required order. This easily leads to overly long start-up commands, but `argument files`_ allow listing files nicely one file per line. It is also possible to `randomize the execution order`__ using the :option:`--randomize` option. __ `Randomizing execution order`_ Passing execution ~~~~~~~~~~~~~~~~~ Typically test cases, setups and teardowns are considered passed if all keywords they contain are executed and none of them fail. From Robot Framework 2.8 onwards, it is also possible to use BuiltIn_ keywords :name:`Pass Execution` and :name:`Pass Execution If` to stop execution with PASS status and skip the remaining keywords. How :name:`Pass Execution` and :name:`Pass Execution If` behave in different situations is explained below: - When used in any `setup or teardown`__ (suite, test or keyword), these keywords pass that setup or teardown. Possible teardowns of the started keywords are executed. Test execution or statuses are not affected otherwise. - When used in a test case outside setup or teardown, the keywords pass that particular test case. Possible test and keyword teardowns are executed. - Possible `continuable failures`__ that occur before these keyword are used, as well as failures in teardowns executed afterwards, will fail the execution. - It is mandatory to give an explanation message why execution was interrupted, and it is also possible to modify test case tags. For more details, and usage examples, see the `documentation of these keywords`__. 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`__. __ `Setups and teardowns`_ __ `Continue on failure`_ __ `BuiltIn`_ __ `Setting criticality`_ Continue on failure ------------------- Normally test cases are stopped immediately when any of their keywords fail. This behavior shortens test execution time and prevents subsequent keywords hanging or otherwise causing problems if the system under test is in unstable state. This has the drawback that often subsequent keywords would give more information about the state of the system. Hence Robot Framework offers several features to continue after failures. :name:`Run Keyword And Ignore Error` and :name:`Run Keyword And Expect Error` keywords ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BuiltIn_ keywords :name:`Run Keyword And Ignore Error` and :name:`Run Keyword And Expect Error` handle failures so that test execution is not terminated immediately. Though, using these keywords for this purpose often adds extra complexity to test cases, so the following features are worth considering to make continuing after failures easier. Special failures from keywords ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ `Library keywords`_ report failures using exceptions, and it is possible to use special exceptions to tell the core framework that execution can continue regardless the failure. How these exceptions can be created is explained in the `test library API chapter`__. When a test ends and there has been one or more continuable failure, the test will be marked failed. If there are more than one failure, all of them will be enumerated in the final error message:: Several failures occurred: 1) First error message. 2) Second error message ... Test execution ends also if a normal failure occurs after continuable failures. Also in that case all the failures will be listed in the final error message. The return value from failed keywords, possibly assigned to a variable, is always the Python `None`. __ `Continuing test execution despite of failures`_ :name:`Run Keyword And Continue On Failure` keyword ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BuiltIn_ keyword :name:`Run Keyword And Continue On Failure` allows converting any failure into a continuable failure. These failures are handled by the framework exactly the same way as continuable failures originating from library keywords. Execution continues on teardowns automatically ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To make it sure that all the cleanup activities are taken care of, the continue on failure mode is automatically on in `test and suite teardowns`__. In practice this means that in teardowns all the keywords in all levels are always executed. __ `Setups and teardowns`_ All top-level keywords are executed when tests have templates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When using `test templates`_, all the data rows are always executed to make it sure that all the different combinations are tested. In this usage continuing is limited to the top-level keywords, and inside them the execution ends normally if there are non-continuable failures. Stopping test execution gracefully ---------------------------------- Sometimes there is a need to stop the test execution before all the tests have finished, but so that logs and reports are created. Different ways how to accomplish this are explained below. In all these cases the remaining test cases are marked failed. Starting from Robot Framework 2.9 the tests that are automatically failed get `robot-exit` tag and the generated report will include `NOT robot-exit` `combined tag pattern`__ to easily see those tests that were not skipped. Note that the test in which the exit happened does not get the `robot-exit` tag. __ `Generating combined tag statistics`_ Pressing `Ctrl-C` ~~~~~~~~~~~~~~~~~ The execution is stopped when `Ctrl-C` is pressed in the console where the tests are running. When running the tests on Python, the execution is stopped immediately, but with Jython it ends only after the currently executing keyword ends. If `Ctrl-C` is pressed again, the execution ends immediately and reports and logs are not created. Using signals ~~~~~~~~~~~~~ On Unix-like machines it is possible to terminate test execution using signals `INT` and `TERM`. These signals can be sent from the command line using ``kill`` command, and sending signals can also be easily automated. Signals have the same limitation on Jython as pressing `Ctrl-C`. Similarly also the second signal stops the execution forcefully. Using keywords ~~~~~~~~~~~~~~ The execution can be stopped also by the executed keywords. There is a separate :name:`Fatal Error` BuiltIn_ keyword for this purpose, and custom keywords can use `fatal exceptions`__ when they fail. __ `Stopping test execution`_ Stopping when first test case fails ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If option :option:`--exitonfailure` is used, test execution stops immediately if any `critical test`_ fails. Also the remaining tests are marked as failed. Stopping on parsing or execution error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Robot Framework separates *failures* caused by failing keywords from *errors* caused by, for example, invalid settings or failed test library imports. By default these errors are reported as `test execution errors`__, but errors themselves do not fail tests or affect execution otherwise. If :option:`--exitonerror` option is used, however, all such errors are considered fatal and execution stopped so that remaining tests are marked failed. With parsing errors encountered before execution even starts, this means that no tests are actually run. .. note:: :option:`--exitonerror` is new in Robot Framework 2.8.6. __ `Errors and warnings during execution`_ Handling teardowns ~~~~~~~~~~~~~~~~~~ By default teardowns of the tests and suites that have been started are executed even if the test execution is stopped using one of the methods above. This allows clean-up activities to be run regardless how execution ends. It is also possible to skip teardowns when execution is stopped by using :option:`--skipteardownonexit` option. This can be useful if, for example, clean-up tasks take a lot of time.
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/ExecutingTestCases/TestExecution.rst
0.904513
0.826852
TestExecution.rst
pypi
Remote library interface ======================== The remote library interface provides means for having test libraries on different machines than where Robot Framework itself is running, and also for implementing libraries using other languages than the natively supported Python and Java. For a test library user remote libraries look pretty much the same as any other test library, and developing test libraries using the remote library interface is also very close to creating `normal test libraries`__. __ `Creating test libraries`_ .. contents:: :depth: 2 :local: Introduction ------------ There are two main reasons for using the remote library API: * It is possible to have actual libraries on different machines than where Robot Framework is running. This allows interesting possibilities for distributed testing. * Test libraries can be implemented using any language that supports `XML-RPC`_ protocol. At the time of this writing `there exists ready-made remote servers`__ for Python, Java, Ruby, .NET, Clojure, Perl and node.js. The remote library interface is provided by the Remote library that is one of the `standard libraries`_. This library does not have any keywords of its own, but it works as a proxy between the core framework and keywords implemented elsewhere. The Remote library interacts with actual library implementations through remote servers, and the Remote library and servers communicate using a simple `remote protocol`_ on top of an XML-RPC channel. The high level architecture of all this is illustrated in the picture below: .. figure:: src/ExtendingRobotFramework/remote.png Robot Framework architecture with Remote library .. note:: The remote client uses Python's standard xmlrpclib__ module. It does not support custom XML-RPC extensions implemented by some XML-RPC servers. __ https://code.google.com/p/robotframework/wiki/RemoteLibrary#Available_remote_servers __ http://docs.python.org/2/library/xmlrpclib.html Taking Remote library into use ------------------------------ Importing Remote library ~~~~~~~~~~~~~~~~~~~~~~~~ The Remote library needs to know the address of the remote server but otherwise importing it and using keywords that it provides is no different to how other libraries are used. If you need to use the Remote library multiple times in a test suite, or just want to give it a more descriptive name, you can import it using the `WITH NAME syntax`_. .. sourcecode:: robotframework *** Settings *** Library Remote http://127.0.0.1:8270 WITH NAME Example1 Library Remote http://example.com:8080/ WITH NAME Example2 Library Remote http://10.0.0.2/example 1 minute WITH NAME Example3 The URL used by the first example above is also the default address that the Remote library uses if no address is given. Similarly port `8270` is the port that remote servers are expected to use by default. (82 and 70 are the ASCII codes of letters `R` and `F`, respectively.) .. note:: When connecting to the local machine, it is recommended to use address `127.0.0.1` instead of `localhost`. This avoids address resolution that can be extremely slow `at least on Windows`__. Prior to Robot Framework 2.8.4 the Remote library itself used the potentially slow `localhost` by default. .. note:: Notice that if the URI contains no path after the server address, `xmlrpclib module`__ used by the Remote library will use `/RPC2` path by default. In practice using `http://127.0.0.1:8270` is thus identical to using `http://127.0.0.1:8270/RPC2`. Depending on the remote server this may or may not be a problem. No extra path is appended if the address has a path even if the path is just `/`. For example, neither `http://127.0.0.1:8270/` nor `http://127.0.0.1:8270/my/path` will be modified. The last example above shows how to give a custom timeout to the Remote library as an optional second argument. The timeout is used when initially connecting to the server and if a connection accidentally closes. Timeout can be given in Robot Framework `time format`_ like `60s` or `2 minutes 10 seconds`. The default timeout is typically several minutes, but it depends on the operating system and its configuration. Notice that setting a timeout that is shorter than keyword execution time will interrupt the keyword. .. note:: Support for timeouts is a new feature in Robot Framework 2.8.6. Timeouts do not work with Python/Jython 2.5 nor with IronPython. __ http://stackoverflow.com/questions/14504450/pythons-xmlrpc-extremely-slow-one-second-per-call __ https://docs.python.org/2/library/xmlrpclib.html Starting and stopping remote servers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before the Remote library can be imported, the remote server providing the actual keywords must be started. If the server is started before launching the test execution, it is possible to use the normal :setting:`Library` setting like in the above example. Alternatively other keywords, for example from Process_ or SSH__ libraries, can start the server up, but then you may need to use `Import Library keyword`__ because the library is not available when the test execution starts. How a remote server can be stopped depends on how it is implemented. Typically servers support the following methods: * Regardless of the library used, remote servers should provide :name:`Stop Remote Server` keyword that can be easily used by executed tests. * Remote servers should have `stop_remote_server` method in their XML-RPC interface. * Hitting `Ctrl-C` on the console where the server is running should stop the server. * The server process can be terminated using tools provided by the operating system (e.g. ``kill``). .. note:: Servers may be configured so that users cannot stop it with :name:`Stop Remote Server` keyword or `stop_remote_server` method. __ https://github.com/robotframework/SSHLibrary __ `Using Import Library keyword`_ Supported argument and return value types ----------------------------------------- Because the XML-RPC protocol does not support all possible object types, the values transferred between the Remote library and remote servers must be converted to compatible types. This applies to the keyword arguments the Remote library passes to remote servers and to the return values servers give back to the Remote library. Both the Remote library and the Python remote server handle Python values according to the following rules. Other remote servers should behave similarly. * Strings, numbers and Boolean values are passed without modifications. * Python `None` is converted to an empty string. * All lists, tuples, and other iterable objects (except strings and dictionaries) are passed as lists so that their contents are converted recursively. * Dictionaries and other mappings are passed as dicts so that their keys are converted to strings and values converted to supported types recursively. * Returned dictionaries are converted to so called *dot-accessible dicts* that allow accessing keys as attributes using the `extended variable syntax`_ like `${result.key}`. This works also with nested dictionaries like `${root.child.leaf}`. * Strings containing bytes in the ASCII range that cannot be represented in XML (e.g. the null byte) are sent as `Binary objects`__ that internally use XML-RPC base64 data type. Received Binary objects are automatically converted to byte strings. * Other types are converted to strings. .. note:: Prior to Robot Framework 2.8.3, only lists, tuples, and dictionaries were handled according to the above rules. General iterables and mappings were not supported. Additionally binary support is new in Robot Framework 2.8.4 and returning dot-accessible dictionaries new in Robot Framework 2.9. __ http://docs.python.org/2/library/xmlrpclib.html#binary-objects Remote protocol --------------- This section explains the protocol that is used between the Remote library and remote servers. This information is mainly targeted for people who want to create new remote servers. The provided Python and Ruby servers can also be used as examples. The remote protocol is implemented on top of `XML-RPC`_, which is a simple remote procedure call protocol using XML over HTTP. Most mainstream languages (Python, Java, C, Ruby, Perl, Javascript, PHP, ...) have a support for XML-RPC either built-in or as an extension. Required methods ~~~~~~~~~~~~~~~~ A remote server is an XML-RPC server that must have the same methods in its public interface as the `dynamic library API`_ has. Only `get_keyword_names` and `run_keyword` are actually required, but `get_keyword_arguments` and `get_keyword_documentation` are also recommended. Notice that using camelCase format in method names is not possible currently. How the actual keywords are implemented is not relevant for the Remote library. A remote server can either act as a wrapper for real test libraries, like the provided Python and Ruby servers do, or it can implement keywords itself. Remote servers should additionally have `stop_remote_server` method in their public interface to ease stopping them. They should also automatically expose this method as :name:`Stop Remote Server` keyword to allow using it in the test data regardless of the test library. Allowing users to stop the server is not always desirable, and servers may support disabling this functionality somehow. The method, and also the exposed keyword, should return `True` or `False` depending was stopping allowed or not. That makes it possible for external tools to know did stopping the server succeed. The provided Python remote server can be used as a reference implementation. Getting remote keyword names and other information ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Remote library gets a list of keywords that the remote server provides using `get_keyword_names` method. This method must return the keyword names as a list of strings. Remote servers can, and should, also implement `get_keyword_arguments` and `get_keyword_documentation` methods to provide more information about the keywords. Both of these keywords get the name of the keyword as an argument. Arguments must be returned as a list of strings in the `same format as with dynamic libraries`__, and documentation must be returned `as a string`__. Remote servers can also provide `general library documentation`__ to be used when generating documentation with the Libdoc_ tool. __ `Getting keyword arguments`_ __ `Getting keyword documentation`_ __ `Getting general library documentation`_ Executing remote keywords ~~~~~~~~~~~~~~~~~~~~~~~~~ When the Remote library wants the server to execute some keyword, it calls remote server's `run_keyword` method and passes it the keyword name, a list of arguments, and possibly a dictionary of `free keyword arguments`__. Base types can be used as arguments directly, but more complex types are `converted to supported types`__. The server must return results of the execution in a result dictionary (or map, depending on terminology) containing items explained in the following table. Notice that only the `status` entry is mandatory, others can be omitted if they are not applicable. .. table:: Entries in the remote result dictionary :class: tabular +------------+-------------------------------------------------------------+ | Name | Explanation | +============+=============================================================+ | status | Mandatory execution status. Either PASS or FAIL. | +------------+-------------------------------------------------------------+ | output | Possible output to write into the log file. Must be given | | | as a single string but can contain multiple messages and | | | different `log levels`__ in format `*INFO* First | | | message\n*HTML* <b>2nd</b>\n*WARN* Another message`. It | | | is also possible to embed timestamps_ to the log messages | | | like `*INFO:1308435758660* Message with timestamp`. | +------------+-------------------------------------------------------------+ | return | Possible return value. Must be one of the `supported | | | types`__. | +------------+-------------------------------------------------------------+ | error | Possible error message. Used only when the execution fails. | +------------+-------------------------------------------------------------+ | traceback | Possible stack trace to `write into the log file`__ using | | | DEBUG level when the execution fails. | +------------+-------------------------------------------------------------+ | continuable| When set to `True`, or any value considered | | | `True` in Python, the occurred failure is considered | | | continuable__. New in Robot Framework 2.8.4. | +------------+-------------------------------------------------------------+ | fatal | Like `continuable`, but denotes that the occurred | | | failure is fatal__. Also new in Robot Framework 2.8.4. | +------------+-------------------------------------------------------------+ __ `Different argument syntaxes`_ __ `Supported argument and return value types`_ __ `Logging information`_ __ `Supported argument and return value types`_ __ `Reporting keyword status`_ __ `Continue on failure`_ __ `Stopping test execution gracefully`_ Different argument syntaxes ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Remote library is a `dynamic library`_, and in general it handles different argument syntaxes `according to the same rules`__ as any other dynamic library. This includes mandatory arguments, default values, varargs, as well as `named argument syntax`__. Also free keyword arguments (`**kwargs`) works mostly the `same way as with other dynamic libraries`__. First of all, the `get_keyword_arguments` must return an argument specification that contains `**kwargs` exactly like with any other dynamic library. The main difference is that remote servers' `run_keyword` method must have optional third argument that gets the kwargs specified by the user. The third argument must be optional because, for backwards-compatibility reasons, the Remote library passes kwargs to the `run_keyword` method only when they have been used in the test data. In practice `run_keyword` should look something like the following Python and Java examples, depending on how the language handles optional arguments. .. sourcecode:: python def run_keyword(name, args, kwargs=None): # ... .. sourcecode:: java public Map run_keyword(String name, List args) { // ... } public Map run_keyword(String name, List args, Map kwargs) { // ... } .. note:: Remote library supports `**kwargs` starting from Robot Framework 2.8.3. __ `Getting keyword arguments`_ __ `Named argument syntax with dynamic libraries`_ __ `Free keyword arguments with dynamic libraries`_
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/ExtendingRobotFramework/RemoteLibrary.rst
0.94025
0.687866
RemoteLibrary.rst
pypi
Creating test libraries ======================= Robot Framework's actual testing capabilities are provided by test libraries. There are many existing libraries, some of which are even bundled with the core framework, but there is still often a need to create new ones. This task is not too complicated because, as this chapter illustrates, Robot Framework's library API is simple and straightforward. .. contents:: :depth: 2 :local: Introduction ------------ Supported programming languages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Robot Framework itself is written with Python_ and naturally test libraries extending it can be implemented using the same language. When running the framework on Jython_, libraries can also be implemented using Java_. Pure Python code works both on Python and Jython, assuming that it does not use syntax or modules that are not available on Jython. When using Python, it is also possible to implement libraries with C using `Python C API`__, although it is often easier to interact with C code from Python libraries using ctypes__ module. Libraries implemented using these natively supported languages can also act as wrappers to functionality implemented using other programming languages. A good example of this approach is the `Remote library`_, and another widely used approaches is running external scripts or tools as separate processes. .. tip:: `Python Tutorial for Robot Framework Test Library Developers`__ covers enough of Python language to get started writing test libraries using it. It also contains a simple example library and test cases that you can execute and otherwise investigate on your machine. __ http://docs.python.org/c-api/index.html __ http://docs.python.org/library/ctypes.html __ http://code.google.com/p/robotframework/wiki/PythonTutorial Different test library APIs ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Robot Framework has three different test library APIs. Static API The simplest approach is having a module (in Python) or a class (in Python or Java) with methods which map directly to `keyword names`_. Keywords also take the same `arguments`__ as the methods implementing them. Keywords `report failures`__ with exceptions, `log`__ by writing to standard output and can `return values`__ using the `return` statement. Dynamic API Dynamic libraries are classes that implement a method to get the names of the keywords they implement, and another method to execute a named keyword with given arguments. The names of the keywords to implement, as well as how they are executed, can be determined dynamically at runtime, but reporting the status, logging and returning values is done similarly as in the static API. Hybrid API This is a hybrid between the static and the dynamic API. Libraries are classes with a method telling what keywords they implement, but those keywords must be available directly. Everything else except discovering what keywords are implemented is similar as in the static API. All these APIs are described in this chapter. Everything is based on how the static API works, so its functions are discussed first. How the `dynamic library API`_ and the `hybrid library API`_ differ from it is then discussed in sections of their own. The examples in this chapter are mainly about using Python, but they should be easy to understand also for Java-only developers. In those few cases where APIs have differences, both usages are explained with adequate examples. __ `Keyword arguments`_ __ `Reporting keyword status`_ __ `Logging information`_ __ `Returning values`_ Creating test library class or module ------------------------------------- Test libraries can be implemented as Python modules and Python or Java classes. Test library names ~~~~~~~~~~~~~~~~~~ The name of a test library that is used when a library is imported is the same as the name of the module or class implementing it. For example, if you have a Python module `MyLibrary` (that is, file :file:`MyLibrary.py`), it will create a library with name :name:`MyLibrary`. Similarly, a Java class `YourLibrary`, when it is not in any package, creates a library with exactly that name. Python classes are always inside a module. If the name of a class implementing a library is the same as the name of the module, Robot Framework allows dropping the class name when importing the library. For example, class `MyLib` in :file:`MyLib.py` file can be used as a library with just name :name:`MyLib`. This also works with submodules so that if, for example, `parent.MyLib` module has class `MyLib`, importing it using just :name:`parent.MyLib` works. If the module name and class name are different, libraries must be taken into use using both module and class names, such as :name:`mymodule.MyLibrary` or :name:`parent.submodule.MyLib`. Java classes in a non-default package must be taken into use with the full name. For example, class `MyLib` in `com.mycompany.myproject` package must be imported with name :name:`com.mycompany.myproject.MyLib`. .. note:: Dropping class names with submodules works only in Robot Framework 2.8.4 and newer. With earlier versions you need to include also the class name like :name:`parent.MyLib.MyLib`. .. tip:: If the library name is really long, for example when the Java package name is long, it is recommended to give the library a simpler alias by using the `WITH NAME syntax`_. Providing arguments to test libraries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All test libraries implemented as classes can take arguments. These arguments are specified in the Setting table after the library name, and when Robot Framework creates an instance of the imported library, it passes them to its constructor. Libraries implemented as a module cannot take any arguments, so trying to use those results in an error. The number of arguments needed by the library is the same as the number of arguments accepted by the library's constructor. The default values and variable number of arguments work similarly as with `keyword arguments`_, with the exception that there is no variable argument support for Java libraries. Arguments passed to the library, as well as the library name itself, can be specified using variables, so it is possible to alter them, for example, from the command line. .. sourcecode:: robotframework *** Settings *** Library MyLibrary 10.0.0.1 8080 Library AnotherLib ${VAR} Example implementations, first one in Python and second in Java, for the libraries used in the above example: .. sourcecode:: python from example import Connection class MyLibrary: def __init__(self, host, port=80): self._conn = Connection(host, int(port)) def send_message(self, message): self._conn.send(message) .. sourcecode:: java public class AnotherLib { private String setting = null; public AnotherLib(String setting) { setting = setting; } public void doSomething() { if setting.equals("42") { // do something ... } } } Test library scope ~~~~~~~~~~~~~~~~~~ Libraries implemented as classes can have an internal state, which can be altered by keywords and with arguments to the constructor of the library. Because the state can affect how keywords actually behave, it is important to make sure that changes in one test case do not accidentally affect other test cases. These kind of dependencies may create hard-to-debug problems, for example, when new test cases are added and they use the library inconsistently. Robot Framework attempts to keep test cases independent from each other: by default, it creates new instances of test libraries for every test case. However, this behavior is not always desirable, because sometimes test cases should be able to share a common state. Additionally, all libraries do not have a state and creating new instances of them is simply not needed. Test libraries can control when new libraries are created with a class attribute `ROBOT_LIBRARY_SCOPE` . This attribute must be a string and it can have the following three values: `TEST CASE` A new instance is created for every test case. A possible suite setup and suite teardown share yet another instance. This is the default. `TEST SUITE` A new instance is created for every test suite. The lowest-level test suites, created from test case files and containing test cases, have instances of their own, and higher-level suites all get their own instances for their possible setups and teardowns. `GLOBAL` Only one instance is created during the whole test execution and it is shared by all test cases and test suites. Libraries created from modules are always global. .. note:: If a library is imported multiple times with different arguments__, a new instance is created every time regardless the scope. When the `TEST SUITE` or `GLOBAL` scopes are used with test libraries that have a state, it is recommended that libraries have some special keyword for cleaning up the state. This keyword can then be used, for example, in a suite setup or teardown to ensure that test cases in the next test suites can start from a known state. For example, :name:`SeleniumLibrary` uses the `GLOBAL` scope to enable using the same browser in different test cases without having to reopen it, and it also has the :name:`Close All Browsers` keyword for easily closing all opened browsers. Example Python library using the `TEST SUITE` scope: .. sourcecode:: python class ExampleLibrary: ROBOT_LIBRARY_SCOPE = 'TEST SUITE' def __init__(self): self._counter = 0 def count(self): self._counter += 1 print self._counter def clear_counter(self): self._counter = 0 Example Java library using the `GLOBAL` scope: .. sourcecode:: java public class ExampleLibrary { public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL"; private int counter = 0; public void count() { counter += 1; System.out.println(counter); } public void clearCounter() { counter = 0; } } __ `Providing arguments to test libraries`_ Specifying library version ~~~~~~~~~~~~~~~~~~~~~~~~~~ When a test library is taken into use, Robot Framework tries to determine its version. This information is then written into the syslog_ to provide debugging information. Library documentation tool Libdoc_ also writes this information into the keyword documentations it generates. Version information is read from attribute `ROBOT_LIBRARY_VERSION`, similarly as `test library scope`_ is read from `ROBOT_LIBRARY_SCOPE`. If `ROBOT_LIBRARY_VERSION` does not exist, information is tried to be read from `__version__` attribute. These attributes must be class or module attributes, depending whether the library is implemented as a class or a module. For Java libraries the version attribute must be declared as `static final`. An example Python module using `__version__`: .. sourcecode:: python __version__ = '0.1' def keyword(): pass A Java class using `ROBOT_LIBRARY_VERSION`: .. sourcecode:: java public class VersionExample { public static final String ROBOT_LIBRARY_VERSION = "1.0.2"; public void keyword() { } } Specifying documentation format ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Starting from Robot Framework 2.7.5, library documentation tool Libdoc_ supports documentation in multiple formats. If you want to use something else than Robot Framework's own `documentation formatting`_, you can specify the format in the source code using `ROBOT_LIBRARY_DOC_FORMAT` attribute similarly as scope__ and version__ are set with their own `ROBOT_LIBRARY_*` attributes. The possible case-insensitive values for documentation format are `ROBOT` (default), `HTML`, `TEXT` (plain text), and `reST` (reStructuredText_). Using the `reST` format requires the docutils_ module to be installed when documentation is generated. Setting the documentation format is illustrated by the following Python and Java examples that use reStructuredText and HTML formats, respectively. See `Documenting libraries`_ section and Libdoc_ chapter for more information about documenting test libraries in general. .. sourcecode:: python """A library for *documentation format* demonstration purposes. This documentation is created using reStructuredText__. Here is a link to the only \`Keyword\`. __ http://docutils.sourceforge.net """ ROBOT_LIBRARY_DOC_FORMAT = 'reST' def keyword(): """**Nothing** to see here. Not even in the table below. ======= ===== ===== Table here has nothing to see. ======= ===== ===== """ pass .. sourcecode:: java /** * A library for <i>documentation format</i> demonstration purposes. * * This documentation is created using <a href="http://www.w3.org/html">HTML</a>. * Here is a link to the only `Keyword`. */ public class DocFormatExample { public static final String ROBOT_LIBRARY_DOC_FORMAT = "HTML"; /**<b>Nothing</b> to see here. Not even in the table below. * * <table> * <tr><td>Table</td><td>here</td><td>has</td></tr> * <tr><td>nothing</td><td>to</td><td>see.</td></tr> * </table> */ public void keyword() { } } __ `Test library scope`_ __ `Specifying library version`_ Library acting as listener ~~~~~~~~~~~~~~~~~~~~~~~~~~ `Listener interface`_ allows external listeners to get notifications about test execution. They are called, for example, when suites, tests, and keywords start and end. Sometimes getting such notifications is also useful for test libraries, and they can register a custom listener by using `ROBOT_LIBRARY_LISTENER` attribute. The value of this attribute should be an instance of the listener to use, possibly the library itself. For more information and examples see `Test libraries as listeners`_ section. Creating static keywords ------------------------ What methods are considered keywords ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When the static library API is used, Robot Framework uses reflection to find out what public methods the library class or module implements. It will exclude all methods starting with an underscore, and with Java libraries also methods that are implemented only in `java.lang.Object` are ignored. All the methods that are not ignored are considered keywords. For example, the Python and Java libraries below implement single keyword :name:`My Keyword`. .. sourcecode:: python class MyLibrary: def my_keyword(self, arg): return self._helper_method(arg) def _helper_method(self, arg): return arg.upper() .. sourcecode:: java public class MyLibrary { public String myKeyword(String arg) { return helperMethod(arg); } private String helperMethod(String arg) { return arg.toUpperCase(); } } When the library is implemented as a Python module, it is also possible to limit what methods are keywords by using Python's `__all__` attribute. If `__all__` is used, only methods listed in it can be keywords. For example, the library below implements keywords :name:`Example Keyword` and :name:`Second Example`. Without `__all__`, it would implement also keywords :name:`Not Exposed As Keyword` and :name:`Current Thread`. The most important usage for `__all__` is making sure imported helper methods, such as `current_thread` in the example below, are not accidentally exposed as keywords. .. sourcecode:: python from threading import current_thread __all__ = ['example_keyword', 'second_example'] def example_keyword(): if current_thread().name == 'MainThread': print 'Running in main thread' def second_example(): pass def not_exposed_as_keyword(): pass Keyword names ~~~~~~~~~~~~~ Keyword names used in the test data are compared with method names to find the method implementing these keywords. Name comparison is case-insensitive, and also spaces and underscores are ignored. For example, the method `hello` maps to the keyword name :name:`Hello`, :name:`hello` or even :name:`h e l l o`. Similarly both the `do_nothing` and `doNothing` methods can be used as the :name:`Do Nothing` keyword in the test data. Example Python library implemented as a module in the :file:`MyLibrary.py` file: .. sourcecode:: python def hello(name): print "Hello, %s!" % name def do_nothing(): pass Example Java library implemented as a class in the :file:`MyLibrary.java` file: .. sourcecode:: java public class MyLibrary { public void hello(String name) { System.out.println("Hello, " + name + "!"); } public void doNothing() { } } The example below illustrates how the example libraries above can be used. If you want to try this yourself, make sure that the library is in the `module search path`_. .. sourcecode:: robotframework *** Settings *** Library MyLibrary *** Test Cases *** My Test Do Nothing Hello world Using a custom keyword name ''''''''''''''''''''''''''' It is possible to expose a different name for a keyword instead of the default keyword name which maps to the method name. This can be accomplished by setting the `robot_name` attribute on the method to the desired custom name. The decorator `robot.api.deco.keyword` may be used as a shortcut for setting this attribute when used as follows: .. sourcecode:: python from robot.api.deco import keyword @keyword('Login Via User Panel') def login(username, password): # ... .. sourcecode:: robotframework *** Test Cases *** My Test Login Via User Panel ${username} ${password} Using this decorator without an argument will have no effect on the exposed keyword name, but will still create the `robot_name` attribute. This can be useful for `Marking methods to expose as keywords`_ without actually changing keyword names. Setting a custom keyword name can also enable library keywords to accept arguments using `Embedded Arguments`__ syntax. __ `Embedding arguments into keyword names`_ Keyword tags ~~~~~~~~~~~~ Starting from Robot Framework 2.9, library keywords and `user keywords`__ can have tags. Library keywords can define them by setting the `robot_tags` attribute on the method to a list of desired tags. The `robot.api.deco.keyword` decorator may be used as a shortcut for setting this attribute when used as follows: .. sourcecode:: python from robot.api.deco import keyword @keyword(tags=['tag1', 'tag2']) def login(username, password): # ... @keyword('Custom name', ['tags', 'here']) def another_example(): # ... Another option for setting tags is giving them on the last line of `keyword documentation`__ with `Tags:` prefix and separated by a comma. For example: .. sourcecode:: python def login(username, password): """Log user in to SUT. Tags: tag1, tag2 """ # ... __ `User keyword tags`_ __ `Documenting libraries`_ Keyword arguments ~~~~~~~~~~~~~~~~~ With a static and hybrid API, the information on how many arguments a keyword needs is got directly from the method that implements it. Libraries using the `dynamic library API`_ have other means for sharing this information, so this section is not relevant to them. The most common and also the simplest situation is when a keyword needs an exact number of arguments. In this case, both the Python and Java methods simply take exactly those arguments. For example, a method implementing a keyword with no arguments takes no arguments either, a method implementing a keyword with one argument also takes one argument, and so on. Example Python keywords taking different numbers of arguments: .. sourcecode:: python def no_arguments(): print "Keyword got no arguments." def one_argument(arg): print "Keyword got one argument '%s'." % arg def three_arguments(a1, a2, a3): print "Keyword got three arguments '%s', '%s' and '%s'." % (a1, a2, a3) .. note:: A major limitation with Java libraries using the static library API is that they do not support the `named argument syntax`_. If this is a blocker, it is possible to either use Python or switch to the `dynamic library API`_. Default values to keywords ~~~~~~~~~~~~~~~~~~~~~~~~~~ It is often useful that some of the arguments that a keyword uses have default values. Python and Java have different syntax for handling default values to methods, and the natural syntax of these languages can be used when creating test libraries for Robot Framework. Default values with Python '''''''''''''''''''''''''' In Python a method has always exactly one implementation and possible default values are specified in the method signature. The syntax, which is familiar to all Python programmers, is illustrated below: .. sourcecode:: python def one_default(arg='default'): print "Argument has value %s" % arg def multiple_defaults(arg1, arg2='default 1', arg3='default 2'): print "Got arguments %s, %s and %s" % (arg1, arg2, arg3) The first example keyword above can be used either with zero or one arguments. If no arguments are given, `arg` gets the value `default`. If there is one argument, `arg` gets that value, and calling the keyword with more than one argument fails. In the second example, one argument is always required, but the second and the third one have default values, so it is possible to use the keyword with one to three arguments. .. sourcecode:: robotframework *** Test Cases *** Defaults One Default One Default argument Multiple Defaults required arg Multiple Defaults required arg optional Multiple Defaults required arg optional 1 optional 2 Default values with Java '''''''''''''''''''''''' In Java one method can have several implementations with different signatures. Robot Framework regards all these implementations as one keyword, which can be used with different arguments. This syntax can thus be used to provide support for the default values. This is illustrated by the example below, which is functionally identical to the earlier Python example: .. sourcecode:: java public void oneDefault(String arg) { System.out.println("Argument has value " + arg); } public void oneDefault() { oneDefault("default"); } public void multipleDefaults(String arg1, String arg2, String arg3) { System.out.println("Got arguments " + arg1 + ", " + arg2 + " and " + arg3); } public void multipleDefaults(String arg1, String arg2) { multipleDefaults(arg1, arg2, "default 2"); } public void multipleDefaults(String arg1) { multipleDefaults(arg1, "default 1"); } Variable number of arguments (`*varargs`) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Robot Framework supports also keywords that take any number of arguments. Similarly as with the default values, the actual syntax to use in test libraries is different in Python and Java. Variable number of arguments with Python '''''''''''''''''''''''''''''''''''''''' Python supports methods accepting any number of arguments. The same syntax works in libraries and, as the examples below show, it can also be combined with other ways of specifying arguments: .. sourcecode:: python def any_arguments(*args): print "Got arguments:" for arg in args: print arg def one_required(required, *others): print "Required: %s\nOthers:" % required for arg in others: print arg def also_defaults(req, def1="default 1", def2="default 2", *rest): print req, def1, def2, rest .. sourcecode:: robotframework *** Test Cases *** Varargs Any Arguments Any Arguments argument Any Arguments arg 1 arg 2 arg 3 arg 4 arg 5 One Required required arg One Required required arg another arg yet another Also Defaults required Also Defaults required these two have defaults Also Defaults 1 2 3 4 5 6 Variable number of arguments with Java '''''''''''''''''''''''''''''''''''''' Robot Framework supports `Java varargs syntax`__ for defining variable number of arguments. For example, the following two keywords are functionally identical to the above Python examples with same names: .. sourcecode:: java public void anyArguments(String... varargs) { System.out.println("Got arguments:"); for (String arg: varargs) { System.out.println(arg); } } public void oneRequired(String required, String... others) { System.out.println("Required: " + required + "\nOthers:"); for (String arg: others) { System.out.println(arg); } } It is also possible to use variable number of arguments also by having an array or, starting from Robot Framework 2.8.3, `java.util.List` as the last argument, or second to last if `free keyword arguments (**kwargs)`_ are used. This is illustrated by the following examples that are functionally identical to the previous ones: .. sourcecode:: java public void anyArguments(String[] varargs) { System.out.println("Got arguments:"); for (String arg: varargs) { System.out.println(arg); } } public void oneRequired(String required, List<String> others) { System.out.println("Required: " + required + "\nOthers:"); for (String arg: others) { System.out.println(arg); } } .. note:: Only `java.util.List` is supported as varargs, not any of its sub types. The support for variable number of arguments with Java keywords has one limitation: it works only when methods have one signature. Thus it is not possible to have Java keywords with both default values and varargs. In addition to that, only Robot Framework 2.8 and newer support using varargs with `library constructors`__. __ http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html __ `Providing arguments to test libraries`_ Free keyword arguments (`**kwargs`) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Robot Framework 2.8 added the support for free keyword arguments using Python's `**kwargs` syntax. How to use the syntax in the test data is discussed in `Free keyword arguments`_ section under `Creating test cases`_. In this section we take a look at how to actually use it in custom test libraries. Free keyword arguments with Python '''''''''''''''''''''''''''''''''' If you are already familiar how kwargs work with Python, understanding how they work with Robot Framework test libraries is rather simple. The example below shows the basic functionality: .. sourcecode:: python def example_keyword(**stuff): for name, value in stuff.items(): print name, value .. sourcecode:: robotframework *** Test Cases *** Keyword Arguments Example Keyword hello=world # Logs 'hello world'. Example Keyword foo=1 bar=42 # Logs 'foo 1' and 'bar 42'. Basically, all arguments at the end of the keyword call that use the `named argument syntax`_ `name=value`, and that do not match any other arguments, are passed to the keyword as kwargs. To avoid using a literal value like `foo=quux` as a free keyword argument, it must be escaped__ like `foo\=quux`. The following example illustrates how normal arguments, varargs, and kwargs work together: .. sourcecode:: python def various_args(arg, *varargs, **kwargs): print 'arg:', arg for value in varargs: print 'vararg:', value for name, value in sorted(kwargs.items()): print 'kwarg:', name, value .. sourcecode:: robotframework *** Test Cases *** Positional Various Args hello world # Logs 'arg: hello' and 'vararg: world'. Named Various Args arg=value # Logs 'arg: value'. Kwargs Various Args a=1 b=2 c=3 # Logs 'kwarg: a 1', 'kwarg: b 2' and 'kwarg: c 3'. Various Args c=3 a=1 b=2 # Same as above. Order does not matter. Positional and kwargs Various Args 1 2 kw=3 # Logs 'arg: 1', 'vararg: 2' and 'kwarg: kw 3'. Named and kwargs Various Args arg=value hello=world # Logs 'arg: value' and 'kwarg: hello world'. Various Args hello=world arg=value # Same as above. Order does not matter. For a real world example of using a signature exactly like in the above example, see :name:`Run Process` and :name:`Start Keyword` keywords in the Process_ library. __ Escaping_ Free keyword arguments with Java '''''''''''''''''''''''''''''''' Starting from Robot Framework 2.8.3, also Java libraries support the free keyword arguments syntax. Java itself has no kwargs syntax, but keywords can have `java.util.Map` as the last argument to specify that they accept kwargs. If a Java keyword accepts kwargs, Robot Framework will automatically pack all arguments in `name=value` syntax at the end of the keyword call into a `Map` and pass it to the keyword. For example, following example keywords can be used exactly like the previous Python examples: .. sourcecode:: java public void exampleKeyword(Map<String, String> stuff): for (String key: stuff.keySet()) System.out.println(key + " " + stuff.get(key)); public void variousArgs(String arg, List<String> varargs, Map<String, Object> kwargs): System.out.println("arg: " + arg); for (String varg: varargs) System.out.println("vararg: " + varg); for (String key: kwargs.keySet()) System.out.println("kwarg: " + key + " " + kwargs.get(key)); .. note:: The type of the kwargs argument must be exactly `java.util.Map`, not any of its sub types. .. note:: Similarly as with the `varargs support`__, a keyword supporting kwargs cannot have more than one signature. __ `Variable number of arguments with Java`_ Argument types ~~~~~~~~~~~~~~ Normally keyword arguments come to Robot Framework as strings. If keywords require some other types, it is possible to either use variables_ or convert strings to required types inside keywords. With `Java keywords`__ base types are also coerced automatically. __ `Argument types with Java`_ Argument types with Python '''''''''''''''''''''''''' Because arguments in Python do not have any type information, there is no possibility to automatically convert strings to other types when using Python libraries. Calling a Python method implementing a keyword with a correct number of arguments always succeeds, but the execution fails later if the arguments are incompatible. Luckily with Python it is simple to convert arguments to suitable types inside keywords: .. sourcecode:: python def connect_to_host(address, port=25): port = int(port) # ... Argument types with Java '''''''''''''''''''''''' Arguments to Java methods have types, and all the base types are handled automatically. This means that arguments that are normal strings in the test data are coerced to correct type at runtime. The types that can be coerced are: - integer types (`byte`, `short`, `int`, `long`) - floating point types (`float` and `double`) - the `boolean` type - object versions of the above types e.g. `java.lang.Integer` The coercion is done for arguments that have the same or compatible type across all the signatures of the keyword method. In the following example, the conversion can be done for keywords `doubleArgument` and `compatibleTypes`, but not for `conflictingTypes`. .. sourcecode:: java public void doubleArgument(double arg) {} public void compatibleTypes(String arg1, Integer arg2) {} public void compatibleTypes(String arg2, Integer arg2, Boolean arg3) {} public void conflictingTypes(String arg1, int arg2) {} public void conflictingTypes(int arg1, String arg2) {} The coercion works with the numeric types if the test data has a string containing a number, and with the boolean type the data must contain either string `true` or `false`. Coercion is only done if the original value was a string from the test data, but it is of course still possible to use variables containing correct types with these keywords. Using variables is the only option if keywords have conflicting signatures. .. sourcecode:: robotframework *** Test Cases *** Coercion Double Argument 3.14 Double Argument 2e16 Compatible Types Hello, world! 1234 Compatible Types Hi again! -10 true No Coercion Double Argument ${3.14} Conflicting Types 1 ${2} # must use variables Conflicting Types ${1} 2 Starting from Robot Framework 2.8, argument type coercion works also with `Java library constructors`__. __ `Providing arguments to test libraries`_ Using decorators ~~~~~~~~~~~~~~~~ When writing static keywords, it is sometimes useful to modify them with Python's decorators. However, decorators modify function signatures, and can confuse Robot Framework's introspection when determining which arguments keywords accept. This is especially problematic when creating library documentation with Libdoc_ and when using RIDE_. To avoid this issue, either do not use decorators, or use the handy `decorator module`__ to create signature-preserving decorators. __ http://micheles.googlecode.com/hg/decorator/documentation.html Embedding arguments into keyword names ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Library keywords can also accept arguments which are passed using `Embedded Argument syntax`__. The `robot.api.deco.keyword` decorator can be used to create a `custom keyword name`__ for the keyword which includes the desired syntax. __ `Embedding arguments into keyword name`_ __ `Using a custom keyword name`_ .. sourcecode:: python from robot.api.deco import keyword @keyword('Add ${quantity:\d+} Copies Of ${item} To Cart') def add_copies_to_cart(quantity, item): # ... .. sourcecode:: robotframework *** Test Cases *** My Test Add 7 Copies Of Coffee To Cart Communicating with Robot Framework ---------------------------------- After a method implementing a keyword is called, it can use any mechanism to communicate with the system under test. It can then also send messages to Robot Framework's log file, return information that can be saved to variables and, most importantly, report if the keyword passed or not. Reporting keyword status ~~~~~~~~~~~~~~~~~~~~~~~~ Reporting keyword status is done simply using exceptions. If an executed method raises an exception, the keyword status is `FAIL`, and if it returns normally, the status is `PASS`. The error message shown in logs, reports and the console is created from the exception type and its message. With generic exceptions (for example, `AssertionError`, `Exception`, and `RuntimeError`), only the exception message is used, and with others, the message is created in the format `ExceptionType: Actual message`. Starting from Robot Framework 2.8.2, it is possible to avoid adding the exception type as a prefix to failure message also with non generic exceptions. This is done by adding a special `ROBOT_SUPPRESS_NAME` attribute with value `True` to your exception. Python: .. sourcecode:: python class MyError(RuntimeError): ROBOT_SUPPRESS_NAME = True Java: .. sourcecode:: java public class MyError extends RuntimeException { public static final boolean ROBOT_SUPPRESS_NAME = true; } In all cases, it is important for the users that the exception message is as informative as possible. HTML in error messages '''''''''''''''''''''' Starting from Robot Framework 2.8, it is also possible have HTML formatted error messages by starting the message with text `*HTML*`: .. sourcecode:: python raise AssertionError("*HTML* <a href='robotframework.org'>Robot Framework</a> rulez!!") This method can be used both when raising an exception in a library, like in the example above, and `when users provide an error message in the test data`__. __ `Failures`_ Cutting long messages automatically ''''''''''''''''''''''''''''''''''' If the error message is longer than 40 lines, it will be automatically cut from the middle to prevent reports from getting too long and difficult to read. The full error message is always shown in the log message of the failed keyword. Tracebacks '''''''''' The traceback of the exception is also logged using `DEBUG` `log level`_. These messages are not visible in log files by default because they are very rarely interesting for normal users. When developing libraries, it is often a good idea to run tests using `--loglevel DEBUG`. Stopping test execution ~~~~~~~~~~~~~~~~~~~~~~~ It is possible to fail a test case so that `the whole test execution is stopped`__. This is done simply by having a special `ROBOT_EXIT_ON_FAILURE` attribute with `True` value set on the exception raised from the keyword. This is illustrated in the examples below. Python: .. sourcecode:: python class MyFatalError(RuntimeError): ROBOT_EXIT_ON_FAILURE = True Java: .. sourcecode:: java public class MyFatalError extends RuntimeException { public static final boolean ROBOT_EXIT_ON_FAILURE = true; } __ `Stopping test execution gracefully`_ Continuing test execution despite of failures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is possible to `continue test execution even when there are failures`__. The way to signal this from test libraries is adding a special `ROBOT_CONTINUE_ON_FAILURE` attribute with `True` value to the exception used to communicate the failure. This is demonstrated by the examples below. Python: .. sourcecode:: python class MyContinuableError(RuntimeError): ROBOT_CONTINUE_ON_FAILURE = True Java: .. sourcecode:: java public class MyContinuableError extends RuntimeException { public static final boolean ROBOT_CONTINUE_ON_FAILURE = true; } __ `Continue on failure`_ Logging information ~~~~~~~~~~~~~~~~~~~ Exception messages are not the only way to give information to the users. In addition to them, methods can also send messages to `log files`_ simply by writing to the standard output stream (stdout) or to the standard error stream (stderr), and they can even use different `log levels`_. Another, and often better, logging possibility is using the `programmatic logging APIs`_. By default, everything written by a method into the standard output is written to the log file as a single entry with the log level `INFO`. Messages written into the standard error are handled similarly otherwise, but they are echoed back to the original stderr after the keyword execution has finished. It is thus possible to use the stderr if you need some messages to be visible on the console where tests are executed. Using log levels '''''''''''''''' To use other log levels than `INFO`, or to create several messages, specify the log level explicitly by embedding the level into the message in the format `*LEVEL* Actual log message`, where `*LEVEL*` must be in the beginning of a line and `LEVEL` is one of the available logging levels `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR` and `HTML`. Errors and warnings ''''''''''''''''''' Messages with `ERROR` or `WARN` level are automatically written to the console and a separate `Test Execution Errors section`__ in the log files. This makes these messages more visible than others and allows using them for reporting important but non-critical problems to users. .. note:: In Robot Framework 2.9, new functionality was added to automatically add ERRORs logged by keywords to the Test Execution Errors section. __ `Errors and warnings during execution`_ Logging HTML '''''''''''' Everything normally logged by the library will be converted into a format that can be safely represented as HTML. For example, `<b>foo</b>` will be displayed in the log exactly like that and not as **foo**. If libraries want to use formatting, links, display images and so on, they can use a special pseudo log level `HTML`. Robot Framework will write these messages directly into the log with the `INFO` level, so they can use any HTML syntax they want. Notice that this feature needs to be used with care, because, for example, one badly placed `</table>` tag can ruin the log file quite badly. When using the `public logging API`_, various logging methods have optional `html` attribute that can be set to `True` to enable logging in HTML format. Timestamps '''''''''' By default messages logged via the standard output or error streams get their timestamps when the executed keyword ends. This means that the timestamps are not accurate and debugging problems especially with longer running keywords can be problematic. Keywords have a possibility to add an accurate timestamp to the messages they log if there is a need. The timestamp must be given as milliseconds since the `Unix epoch`__ and it must be placed after the `log level`__ separated from it with a colon:: *INFO:1308435758660* Message with timestamp *HTML:1308435758661* <b>HTML</b> message with timestamp As illustrated by the examples below, adding the timestamp is easy both using Python and Java. If you are using Python, it is, however, even easier to get accurate timestamps using the `programmatic logging APIs`_. A big benefit of adding timestamps explicitly is that this approach works also with the `remote library interface`_. Python: .. sourcecode:: python import time def example_keyword(): print '*INFO:%d* Message with timestamp' % (time.time()*1000) Java: .. sourcecode:: java public void exampleKeyword() { System.out.println("*INFO:" + System.currentTimeMillis() + "* Message with timestamp"); } __ http://en.wikipedia.org/wiki/Unix_epoch __ `Using log levels`_ Logging to console '''''''''''''''''' If libraries need to write something to the console they have several options. As already discussed, warnings and all messages written to the standard error stream are written both to the log file and to the console. Both of these options have a limitation that the messages end up to the console only after the currently executing keyword finishes. A bonus is that these approaches work both with Python and Java based libraries. Another option, that is only available with Python, is writing messages to `sys.__stdout__` or `sys.__stderr__`. When using this approach, messages are written to the console immediately and are not written to the log file at all: .. sourcecode:: python import sys def my_keyword(arg): sys.__stdout__.write('Got arg %s\n' % arg) The final option is using the `public logging API`_: .. sourcecode:: python from robot.api import logger def log_to_console(arg): logger.console('Got arg %s' % arg) def log_to_console_and_log_file(arg) logger.info('Got arg %s' % arg, also_console=True) Logging example ''''''''''''''' In most cases, the `INFO` level is adequate. The levels below it, `DEBUG` and `TRACE`, are useful for writing debug information. These messages are normally not shown, but they can facilitate debugging possible problems in the library itself. The `WARN` or `ERROR` level can be used to make messages more visible and `HTML` is useful if any kind of formatting is needed. The following examples clarify how logging with different levels works. Java programmers should regard the code `print 'message'` as pseudocode meaning `System.out.println("message");`. .. sourcecode:: python print 'Hello from a library.' print '*WARN* Warning from a library.' print '*ERROR* Something unexpected happen that may indicate a problem in the test.' print '*INFO* Hello again!' print 'This will be part of the previous message.' print '*INFO* This is a new message.' print '*INFO* This is <b>normal text</b>.' print '*HTML* This is <b>bold</b>.' print '*HTML* <a href="http://robotframework.org">Robot Framework</a>' .. raw:: html <table class="messages"> <tr> <td class="time">16:18:42.123</td> <td class="info level">INFO</td> <td class="msg">Hello from a library.</td> </tr> <tr> <td class="time">16:18:42.123</td> <td class="warn level">WARN</td> <td class="msg">Warning from a library.</td> </tr> <tr> <td class="time">16:18:42.123</td> <td class="error level">ERROR</td> <td class="msg">Something unexpected happen that may indicate a problem in the test.</td> </tr> <tr> <td class="time">16:18:42.123</td> <td class="info level">INFO</td> <td class="msg">Hello again!<br>This will be part of the previous message.</td> </tr> <tr> <td class="time">16:18:42.123</td> <td class="info level">INFO</td> <td class="msg">This is a new message.</td> </tr> <tr> <td class="time">16:18:42.123</td> <td class="info level">INFO</td> <td class="msg">This is &lt;b&gt;normal text&lt;/b&gt;.</td> </tr> <tr> <td class="time">16:18:42.123</td> <td class="info level">INFO</td> <td class="msg">This is <b>bold</b>.</td> </tr> <tr> <td class="time">16:18:42.123</td> <td class="info level">INFO</td> <td class="msg"><a href="http://robotframework.org">Robot Framework</a></td> </tr> </table> Programmatic logging APIs ~~~~~~~~~~~~~~~~~~~~~~~~~ Programmatic APIs provide somewhat cleaner way to log information than using the standard output and error streams. Currently these interfaces are available only to Python bases test libraries. Public logging API '''''''''''''''''' Robot Framework has a Python based logging API for writing messages to the log file and to 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 a lot cleaner to use, this API has a benefit that the log messages have accurate timestamps_. The public logging API `is thoroughly documented`__ as part of the API documentation at https://robot-framework.readthedocs.org. Below is a simple usage example: .. sourcecode:: python 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) logger.console('Hello, console!') An obvious limitation is that test libraries using this logging API have a dependency to Robot Framework. Before version 2.8.7 Robot also had to be running for the logging to work. Starting from Robot Framework 2.8.7 if Robot is not running the messages are redirected automatically to Python's standard logging__ module. __ https://robot-framework.readthedocs.org/en/latest/autodoc/robot.api.html#module-robot.api.logger __ http://docs.python.org/library/logging.html Using Python's standard `logging` module '''''''''''''''''''''''''''''''''''''''' In addition to the new `public logging API`_, Robot Framework offers a built-in support to Python's standard logging__ module. This works so that all messages that are received by the root logger of the module are automatically propagated to Robot Framework's log file. Also this API produces log messages with accurate timestamps_, but logging HTML messages or writing messages to the console are not supported. A big benefit, illustrated also by the simple example below, is that using this logging API creates no dependency to Robot Framework. .. sourcecode:: python import logging def my_keyword(arg): logging.debug('Got argument %s' % arg) do_something() logging.info('This is a boring example') The `logging` module has slightly different log levels than Robot Framework. Its levels `DEBUG`, `INFO`, `WARNING` and `ERROR` are mapped directly to the matching Robot Framework log levels, and `CRITICAL` is mapped to `ERROR`. Custom log levels are mapped to the closest standard level smaller than the custom level. For example, a level between `INFO` and `WARNING` is mapped to Robot Framework's `INFO` level. __ http://docs.python.org/library/logging.html Logging during library initialization ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Libraries can also log during the test library import and initialization. These messages do not appear in the `log file`_ like the normal log messages, but are instead written to the `syslog`_. This allows logging any kind of useful debug information about the library initialization. Messages logged using the `WARN` or `ERROR` levels are also visible in the `test execution errors`_ section in the log file. Logging during the import and initialization is possible both using the `standard output and error streams`__ and the `programmatic logging APIs`_. Both of these are demonstrated below. Java library logging via stdout during initialization: .. sourcecode:: java public class LoggingDuringInitialization { public LoggingDuringInitialization() { System.out.println("*INFO* Initializing library"); } public void keyword() { // ... } } Python library logging using the logging API during import: .. sourcecode:: python from robot.api import logger logger.debug("Importing library") def keyword(): # ... .. note:: If you log something during initialization, i.e. in Python `__init__` or in Java constructor, the messages may be logged multiple times depending on the `test library scope`_. __ `Logging information`_ Returning values ~~~~~~~~~~~~~~~~ The final way for keywords to communicate back to the core framework is returning information retrieved from the system under test or generated by some other means. The returned values can be `assigned to variables`__ in the test data and then used as inputs for other keywords, even from different test libraries. Values are returned using the `return` statement both from the Python and Java methods. Normally, one value is assigned into one `scalar variable`__, as illustrated in the example below. This example also illustrates that it is possible to return any objects and to use `extended variable syntax`_ to access object attributes. __ `Return values from keywords`_ __ `Scalar variables`_ .. sourcecode:: python from mymodule import MyObject def return_string(): return "Hello, world!" def return_object(name): return MyObject(name) .. sourcecode:: robotframework *** Test Cases *** Returning one value ${string} = Return String Should Be Equal ${string} Hello, world! ${object} = Return Object Robot Should Be Equal ${object.name} Robot Keywords can also return values so that they can be assigned into several `scalar variables`_ at once, into `a list variable`__, or into scalar variables and a list variable. All these usages require that returned values are Python lists or tuples or in Java arrays, Lists, or Iterators. __ `List variables`_ .. sourcecode:: python def return_two_values(): return 'first value', 'second value' def return_multiple_values(): return ['a', 'list', 'of', 'strings'] .. sourcecode:: robotframework *** Test Cases *** Returning multiple values ${var1} ${var2} = Return Two Values Should Be Equal ${var1} first value Should Be Equal ${var2} second value @{list} = Return Two Values Should Be Equal @{list}[0] first value Should Be Equal @{list}[1] second value ${s1} ${s2} @{li} = Return Multiple Values Should Be Equal ${s1} ${s2} a list Should Be Equal @{li}[0] @{li}[1] of strings Communication when using threads ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If a library uses threads, it should generally communicate with the framework only from the main thread. If a worker thread has, for example, a failure to report or something to log, it should pass the information first to the main thread, which can then use exceptions or other mechanisms explained in this section for communication with the framework. This is especially important when threads are run on background while other keywords are running. Results of communicating with the framework in that case are undefined and can in the worst case cause a crash or a corrupted output file. If a keyword starts something on background, there should be another keyword that checks the status of the worker thread and reports gathered information accordingly. Messages logged by non-main threads using the normal logging methods from `programmatic logging APIs`_ are silently ignored. There is also a `BackgroundLogger` in separate robotbackgroundlogger__ project, with a similar API as the standard `robot.api.logger`. Normal logging methods will ignore messages from other than main thread, but the `BackgroundLogger` will save the background messages so that they can be later logged to Robot's log. __ https://github.com/robotframework/robotbackgroundlogger Distributing test libraries --------------------------- Documenting libraries ~~~~~~~~~~~~~~~~~~~~~ A test library without documentation about what keywords it contains and what those keywords do is rather useless. To ease maintenance, it is highly recommended that library documentation is included in the source code and generated from it. Basically, that means using docstrings_ with Python and Javadoc_ with Java, as in the examples below. .. sourcecode:: python class MyLibrary: """This is an example library with some documentation.""" def keyword_with_short_documentation(self, argument): """This keyword has only a short documentation""" pass def keyword_with_longer_documentation(self): """First line of the documentation is here. Longer documentation continues here and it can contain multiple lines or paragraphs. """ pass .. sourcecode:: java /** * This is an example library with some documentation. */ public class MyLibrary { /** * This keyword has only a short documentation */ public void keywordWithShortDocumentation(String argument) { } /** * First line of the documentation is here. * * Longer documentation continues here and it can contain * multiple lines or paragraphs. */ public void keywordWithLongerDocumentation() { } } Both Python and Java have tools for creating an API documentation of a library documented as above. However, outputs from these tools can be slightly technical for some users. Another alternative is using Robot Framework's own documentation tool Libdoc_. This tool can create a library documentation from both Python and Java libraries using the static library API, such as the ones above, but it also handles libraries using the `dynamic library API`_ and `hybrid library API`_. The first line of a keyword documentation is used for a special purpose and should contain a short overall description of the keyword. It is used as a *short documentation*, for example as a tool tip, by Libdoc_ and also shown in the test logs. However, the latter does not work with Java libraries using the static API, because their documentations are lost in compilation and not available at runtime. By default documentation is considered to follow Robot Framework's `documentation formatting`_ rules. This simple format allows often used styles like `*bold*` and `_italic_`, tables, lists, links, etc. Starting from Robot Framework 2.7.5, it is possible to use also HTML, plain text and reStructuredText_ formats. See `Specifying documentation format`_ section for information how to set the format in the library source code and Libdoc_ chapter for more information about the formats in general. .. note:: If you want to use non-ASCII characters in the documentation of Python libraries, you must either use UTF-8 as your `source code encoding`__ or create docstrings as Unicode. .. _docstrings: http://www.python.org/dev/peps/pep-0257 .. _javadoc: http://java.sun.com/j2se/javadoc/writingdoccomments/index.html __ http://www.python.org/dev/peps/pep-0263 Testing libraries ~~~~~~~~~~~~~~~~~ Any non-trivial test library needs to be thoroughly tested to prevent bugs in them. Of course, this testing should be automated to make it easy to rerun tests when libraries are changed. Both Python and Java have excellent unit testing tools, and they suite very well for testing libraries. There are no major differences in using them for this purpose compared to using them for some other testing. The developers familiar with these tools do not need to learn anything new, and the developers not familiar with them should learn them anyway. It is also easy to use Robot Framework itself for testing libraries and that way have actual end-to-end acceptance tests for them. There are plenty of useful keywords in the BuiltIn_ library for this purpose. One worth mentioning specifically is :name:`Run Keyword And Expect Error`, which is useful for testing that keywords report errors correctly. Whether to use a unit- or acceptance-level testing approach depends on the context. If there is a need to simulate the actual system under test, it is often easier on the unit level. On the other hand, acceptance tests ensure that keywords do work through Robot Framework. If you cannot decide, of course it is possible to use both the approaches. Packaging libraries ~~~~~~~~~~~~~~~~~~~ After a library is implemented, documented, and tested, it still needs to be distributed to the users. With simple libraries consisting of a single file, it is often enough to ask the users to copy that file somewhere and set the `module search path`_ accordingly. More complicated libraries should be packaged to make the installation easier. Since libraries are normal programming code, they can be packaged using normal packaging tools. With Python, good options include distutils_, contained by Python's standard library, and the newer setuptools_. A benefit of these tools is that library modules are installed into a location that is automatically in the `module search path`_. When using Java, it is natural to package libraries into a JAR archive. The JAR package must be put into the `module search path`_ before running tests, but it is easy to create a `start-up script`_ that does that automatically. Deprecating keywords ~~~~~~~~~~~~~~~~~~~~ Sometimes there is a need to replace existing keywords with new ones or remove them altogether. Just informing the users about the change may not always be enough, and it is more efficient to get warnings at runtime. To support that, Robot Framework has a capability to mark keywords *deprecated*. This makes it easier to find old keywords from the test data and remove or replace them. Keywords can be deprecated by starting their documentation with text `*DEPRECATED`, case-sensitive, and having a closing `*` also on the first line of the documentation. For example, `*DEPRECATED*`, `*DEPRECATED.*`, and `*DEPRECATED in version 1.5.*` are all valid markers. When a deprecated keyword is executed, a deprecation warning is logged and the warning is shown also in `the console and the Test Execution Errors section in log files`__. The deprecation warning starts with text `Keyword '<name>' is deprecated.` and has rest of the `short documentation`__ after the deprecation marker, if any, afterwards. For example, if the following keyword is executed, there will be a warning like shown below in the log file. .. sourcecode:: python def example_keyword(argument): """*DEPRECATED!!* Use keyword `Other Keyword` instead. This keyword does something to given ``argument`` and returns results. """ return do_something(argument) .. raw:: html <table class="messages"> <tr> <td class="time">20080911&nbsp;16:00:22.650</td> <td class="warn level">WARN</td> <td class="msg">Keyword 'SomeLibrary.Example Keyword' is deprecated. Use keyword `Other Keyword` instead.</td> </tr> </table> This deprecation system works with most test libraries and also with `user keywords`__. The only exception are keywords implemented in a Java test library that uses the `static library interface`__ because their documentation is not available at runtime. With such keywords, it possible to use user keywords as wrappers and deprecate them. .. note:: Prior to Robot Framework 2.9 the documentation must start with `*DEPRECATED*` exactly without any extra content before the closing `*`. __ `Errors and warnings during execution`_ __ `Documenting libraries`_ __ `User keyword name and documentation`_ __ `Creating static keywords`_ .. _Dynamic library: Dynamic library API ------------------- The dynamic API is in most ways similar to the static API. For example, reporting the keyword status, logging, and returning values works exactly the same way. Most importantly, there are no differences in importing dynamic libraries and using their keywords compared to other libraries. In other words, users do not need to know what APIs their libraries use. Only differences between static and dynamic libraries are how Robot Framework discovers what keywords a library implements, what arguments and documentation these keywords have, and how the keywords are actually executed. With the static API, all this is done using reflection (except for the documentation of Java libraries), but dynamic libraries have special methods that are used for these purposes. One of the benefits of the dynamic API is that you have more flexibility in organizing your library. With the static API, you must have all keywords in one class or module, whereas with the dynamic API, you can, for example, implement each keyword as a separate class. This use case is not so important with Python, though, because its dynamic capabilities and multi-inheritance already give plenty of flexibility, and there is also possibility to use the `hybrid library API`_. Another major use case for the dynamic API is implementing a library so that it works as proxy for an actual library possibly running on some other process or even on another machine. This kind of a proxy library can be very thin, and because keyword names and all other information is got dynamically, there is no need to update the proxy when new keywords are added to the actual library. This section explains how the dynamic API works between Robot Framework and dynamic libraries. It does not matter for Robot Framework how these libraries are actually implemented (for example, how calls to the `run_keyword` method are mapped to a correct keyword implementation), and many different approaches are possible. However, if you use Java, you may want to examine `JavalibCore <https://github.com/robotframework/JavalibCore>`__ before implementing your own system. This collection of reusable tools supports several ways of creating keywords, and it is likely that it already has a mechanism that suites your needs. .. _`Getting dynamic keyword names`: Getting keyword names ~~~~~~~~~~~~~~~~~~~~~ Dynamic libraries tell what keywords they implement with the `get_keyword_names` method. The method also has the alias `getKeywordNames` that is recommended when using Java. This method cannot take any arguments, and it must return a list or array of strings containing the names of the keywords that the library implements. If the returned keyword names contain several words, they can be returned separated with spaces or underscores, or in the camelCase format. For example, `['first keyword', 'second keyword']`, `['first_keyword', 'second_keyword']`, and `['firstKeyword', 'secondKeyword']` would all be mapped to keywords :name:`First Keyword` and :name:`Second Keyword`. Dynamic libraries must always have this method. If it is missing, or if calling it fails for some reason, the library is considered a static library. Marking methods to expose as keywords ''''''''''''''''''''''''''''''''''''' If a dynamic library should contain both methods which are meant to be keywords and methods which are meant to be private helper methods, it may be wise to mark the keyword methods as such so it is easier to implement `get_keyword_names`. The `robot.api.deco.keyword` decorator allows an easy way to do this since it creates a custom `robot_name` attribute on the decorated method. This allows generating the list of keywords just by checking for the `robot_name` attribute on every method in the library during `get_keyword_names`. See `Using a custom keyword name`_ for more about this decorator. .. sourcecode:: python from robot.api.deco import keyword class DynamicExample: def get_keyword_names(self): return [name for name in dir(self) if hasattr(getattr(self, name), 'robot_name')] def helper_method(self): # ... @keyword def keyword_method(self): # ... .. _`Running dynamic keywords`: Running keywords ~~~~~~~~~~~~~~~~ Dynamic libraries have a special `run_keyword` (alias `runKeyword`) method for executing their keywords. When a keyword from a dynamic library is used in the test data, Robot Framework uses the library's `run_keyword` method to get it executed. This method takes two or three arguments. The first argument is a string containing the name of the keyword to be executed in the same format as returned by `get_keyword_names`. The second argument is a list or array of arguments given to the keyword in the test data. The optional third argument is a dictionary (map in Java) that gets possible `free keyword arguments`_ (`**kwargs`) passed to the keyword. See `free keyword arguments with dynamic libraries`_ section for more details about using kwargs with dynamic test libraries. After getting keyword name and arguments, the library can execute the keyword freely, but it must use the same mechanism to communicate with the framework as static libraries. This means using exceptions for reporting keyword status, logging by writing to the standard output or by using provided logging APIs, and using the return statement in `run_keyword` for returning something. Every dynamic library must have both the `get_keyword_names` and `run_keyword` methods but rest of the methods in the dynamic API are optional. The example below shows a working, albeit trivial, dynamic library implemented in Python. .. sourcecode:: python class DynamicExample: def get_keyword_names(self): return ['first keyword', 'second keyword'] def run_keyword(self, name, args): print "Running keyword '%s' with arguments %s." % (name, args) Getting keyword arguments ~~~~~~~~~~~~~~~~~~~~~~~~~ If a dynamic library only implements the `get_keyword_names` and `run_keyword` methods, Robot Framework does not have any information about the arguments that the implemented keywords need. For example, both :name:`First Keyword` and :name:`Second Keyword` in the example above could be used with any number of arguments. This is problematic, because most real keywords expect a certain number of keywords, and under these circumstances they would need to check the argument counts themselves. Dynamic libraries can tell Robot Framework what arguments the keywords it implements expect by using the `get_keyword_arguments` (alias `getKeywordArguments`) method. This method takes the name of a keyword as an argument, and returns a list or array of strings containing the arguments accepted by that keyword. Similarly as static keywords, dynamic keywords can require any number of arguments, have default values, and accept variable number of arguments and free keyword arguments. The syntax for how to represent all these different variables is explained in the following table. Note that the examples use Python syntax for lists, but Java developers should use Java lists or String arrays instead. .. table:: Representing different arguments with `get_keyword_arguments` :class: tabular +--------------------+----------------------------+------------------------------+----------+ | Expected | How to represent | Examples | Limits | | arguments | | | (min/max)| +====================+============================+==============================+==========+ | No arguments | Empty list. | | `[]` | | 0/0 | +--------------------+----------------------------+------------------------------+----------+ | One or more | List of strings containing | | `['one_argument']` | | 1/1 | | argument | argument names. | | `['a1', 'a2', 'a3']` | | 3/3 | +--------------------+----------------------------+------------------------------+----------+ | Default values | Default values separated | | `['arg=default value']` | | 0/1 | | for arguments | from names with `=`. | | `['a', 'b=1', 'c=2']` | | 1/3 | | | Default values are always | | | | | considered to be strings. | | | +--------------------+----------------------------+------------------------------+----------+ | Variable number | Last (or second last with | | `['*varargs']` | | 0/any | | of arguments | kwargs) argument has `*` | | `['a', 'b=42', '*rest']` | | 1/any | | (varargs) | before its name. | | | +--------------------+----------------------------+------------------------------+----------+ | Free keyword | Last arguments has | | `['**kwargs']` | | 0/0 | | arguments (kwargs) | `**` before its name. | | `['a', 'b=42', '**kws']` | | 1/2 | | | | | `['*varargs', '**kwargs']` | | 0/any | +--------------------+----------------------------+------------------------------+----------+ When the `get_keyword_arguments` is used, Robot Framework automatically calculates how many positional arguments the keyword requires and does it support free keyword arguments or not. If a keyword is used with invalid arguments, an error occurs and `run_keyword` is not even called. The actual argument names and default values that are returned are also important. They are needed for `named argument support`__ and the Libdoc_ tool needs them to be able to create a meaningful library documentation. If `get_keyword_arguments` is missing or returns `None` or `null` for a certain keyword, that keyword gets an argument specification accepting all arguments. This automatic argument spec is either `[*varargs, **kwargs]` or `[*varargs]`, depending does `run_keyword` `support kwargs`__ by having three arguments or not. __ `Named argument syntax with dynamic libraries`_ __ `Free keyword arguments with dynamic libraries`_ Getting keyword documentation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The final special method that dynamic libraries can implement is `get_keyword_documentation` (alias `getKeywordDocumentation`). It takes a keyword name as an argument and, as the method name implies, returns its documentation as a string. The returned documentation is used similarly as the keyword documentation string with static libraries implemented with Python. The main use case is getting keywords' documentations into a library documentation generated by Libdoc_. Additionally, the first line of the documentation (until the first `\n`) is shown in test logs. Getting keyword tags ~~~~~~~~~~~~~~~~~~~~ Dynamic libraries do not have any other way for defining `keyword tags`_ than by specifying them on the last row of the documentation with `Tags:` prefix. Separate `get_keyword_tags` method can be added to the dynamic API later if there is a need. Getting general library documentation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The `get_keyword_documentation` method can also be used for specifying overall library documentation. This documentation is not used when tests are executed, but it can make the documentation generated by Libdoc_ much better. Dynamic libraries can provide both general library documentation and documentation related to taking the library into use. The former is got by calling `get_keyword_documentation` with special value `__intro__`, and the latter is got using value `__init__`. How the documentation is presented is best tested with Libdoc_ in practice. Python based dynamic libraries can also specify the general library documentation directly in the code as the docstring of the library class and its `__init__` method. If a non-empty documentation is got both directly from the code and from the `get_keyword_documentation` method, the latter has precedence. Named argument syntax with dynamic libraries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Starting from Robot Framework 2.8, also the dynamic library API supports the `named argument syntax`_. Using the syntax works based on the argument names and default values `got from the library`__ using the `get_keyword_arguments` method. For the most parts, the named arguments syntax works with dynamic keywords exactly like it works with any other keyword supporting it. The only special case is the situation where a keyword has multiple arguments with default values, and only some of the latter ones are given. In that case the framework fills the skipped optional arguments based on the default values returned by the `get_keyword_arguments` method. Using the named argument syntax with dynamic libraries is illustrated by the following examples. All the examples use a keyword :name:`Dynamic` that has been specified to have argument specification `[arg1, arg2=xxx, arg3=yyy]`. The comment shows the arguments that the keyword is actually called with. .. sourcecode:: robotframework *** Test Cases *** Only positional Dynamic a # [a] Dynamic a b # [a, b] Dynamic a b c # [a, b, c] Named Dynamic a arg2=b # [a, b] Dynamic a b arg3=c # [a, b, c] Dynamic a arg2=b arg3=c # [a, b, c] Dynamic arg1=a arg2=b arg3=c # [a, b, c] Fill skipped Dynamic a arg3=c # [a, xxx, c] __ `Getting keyword arguments`_ Free keyword arguments with dynamic libraries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Starting from Robot Framework 2.8.2, dynamic libraries can also support `free keyword arguments`_ (`**kwargs`). A mandatory precondition for this support is that the `run_keyword` method `takes three arguments`__: the third one will get kwargs when they are used. Kwargs are passed to the keyword as a dictionary (Python) or Map (Java). What arguments a keyword accepts depends on what `get_keyword_arguments` `returns for it`__. If the last argument starts with `**`, that keyword is recognized to accept kwargs. Using the free keyword argument syntax with dynamic libraries is illustrated by the following examples. All the examples use a keyword :name:`Dynamic` that has been specified to have argument specification `[arg1=xxx, arg2=yyy, **kwargs]`. The comment shows the arguments that the keyword is actually called with. .. sourcecode:: robotframework *** Test Cases *** No arguments Dynamic # [], {} Only positional Dynamic a # [a], {} Dynamic a b # [a, b], {} Only kwargs Dynamic a=1 # [], {a: 1} Dynamic a=1 b=2 c=3 # [], {a: 1, b: 2, c: 3} Positional and kwargs Dynamic a b=2 # [a], {b: 2} Dynamic a b=2 c=3 # [a], {b: 2, c: 3} Named and kwargs Dynamic arg1=a b=2 # [a], {b: 2} Dynamic arg2=a b=2 c=3 # [xxx, a], {b: 2, c: 3} __ `Running dynamic keywords`_ __ `Getting keyword arguments`_ Summary ~~~~~~~ All special methods in the dynamic API are listed in the table below. Method names are listed in the underscore format, but their camelCase aliases work exactly the same way. .. table:: All special methods in the dynamic API :class: tabular =========================== ========================= ======================================================= Name Arguments Purpose =========================== ========================= ======================================================= `get_keyword_names` `Return names`__ of the implemented keywords. `run_keyword` `name, arguments, kwargs` `Execute the specified keyword`__ with given arguments. `kwargs` is optional. `get_keyword_arguments` `name` Return keywords' `argument specifications`__. Optional method. `get_keyword_documentation` `name` Return keywords' and library's `documentation`__. Optional method. =========================== ========================= ======================================================= __ `Getting dynamic keyword names`_ __ `Running dynamic keywords`_ __ `Getting keyword arguments`_ __ `Getting keyword documentation`_ It is possible to write a formal interface specification in Java as below. However, remember that libraries *do not need* to implement any explicit interface, because Robot Framework directly checks with reflection if the library has the required `get_keyword_names` and `run_keyword` methods or their camelCase aliases. Additionally, `get_keyword_arguments` and `get_keyword_documentation` are completely optional. .. sourcecode:: java public interface RobotFrameworkDynamicAPI { List<String> getKeywordNames(); Object runKeyword(String name, List arguments); Object runKeyword(String name, List arguments, Map kwargs); List<String> getKeywordArguments(String name); String getKeywordDocumentation(String name); } .. note:: In addition to using `List`, it is possible to use also arrays like `Object[]` or `String[]`. A good example of using the dynamic API is Robot Framework's own `Remote library`_. Hybrid library API ------------------ The hybrid library API is, as its name implies, a hybrid between the static API and the dynamic API. Just as with the dynamic API, it is possible to implement a library using the hybrid API only as a class. Getting keyword names ~~~~~~~~~~~~~~~~~~~~~ Keyword names are got in the exactly same way as with the dynamic API. In practice, the library needs to have the `get_keyword_names` or `getKeywordNames` method returning a list of keyword names that the library implements. Running keywords ~~~~~~~~~~~~~~~~ In the hybrid API, there is no `run_keyword` method for executing keywords. Instead, Robot Framework uses reflection to find methods implementing keywords, similarly as with the static API. A library using the hybrid API can either have those methods implemented directly or, more importantly, it can handle them dynamically. In Python, it is easy to handle missing methods dynamically with the `__getattr__` method. This special method is probably familiar to most Python programmers and they can immediately understand the following example. Others may find it easier to consult `Python Reference Manual`__ first. __ http://docs.python.org/reference/datamodel.html#attribute-access .. sourcecode:: python from somewhere import external_keyword class HybridExample: def get_keyword_names(self): return ['my_keyword', 'external_keyword'] def my_keyword(self, arg): print "My Keyword called with '%s'" % arg def __getattr__(self, name): if name == 'external_keyword': return external_keyword raise AttributeError("Non-existing attribute '%s'" % name) Note that `__getattr__` does not execute the actual keyword like `run_keyword` does with the dynamic API. Instead, it only returns a callable object that is then executed by Robot Framework. Another point to be noted is that Robot Framework uses the same names that are returned from `get_keyword_names` for finding the methods implementing them. Thus the names of the methods that are implemented in the class itself must be returned in the same format as they are defined. For example, the library above would not work correctly, if `get_keyword_names` returned `My Keyword` instead of `my_keyword`. The hybrid API is not very useful with Java, because it is not possible to handle missing methods with it. Of course, it is possible to implement all the methods in the library class, but that brings few benefits compared to the static API. Getting keyword arguments and documentation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When this API is used, Robot Framework uses reflection to find the methods implementing keywords, similarly as with the static API. After getting a reference to the method, it searches for arguments and documentation from it, in the same way as when using the static API. Thus there is no need for special methods for getting arguments and documentation like there is with the dynamic API. Summary ~~~~~~~ When implementing a test library in Python, the hybrid API has the same dynamic capabilities as the actual dynamic API. A great benefit with it is that there is no need to have special methods for getting keyword arguments and documentation. It is also often practical that the only real dynamic keywords need to be handled in `__getattr__` and others can be implemented directly in the main library class. Because of the clear benefits and equal capabilities, the hybrid API is in most cases a better alternative than the dynamic API when using Python. One notable exception is implementing a library as a proxy for an actual library implementation elsewhere, because then the actual keyword must be executed elsewhere and the proxy can only pass forward the keyword name and arguments. A good example of using the hybrid API is Robot Framework's own Telnet_ library. Using Robot Framework's internal modules ---------------------------------------- Test libraries implemented with Python can use Robot Framework's internal modules, for example, to get information about the executed tests and the settings that are used. This powerful mechanism to communicate with the framework should be used with care, though, because all Robot Framework's APIs are not meant to be used by externally and they might change radically between different framework versions. Available APIs ~~~~~~~~~~~~~~ Starting from Robot Framework 2.7, `API documentation`_ is hosted separately at the excellent `Read the Docs`_ service. If you are unsure how to use certain API or is using them forward compatible, please send a question to `mailing list`_. Using BuiltIn library ~~~~~~~~~~~~~~~~~~~~~ The safest API to use are methods implementing keywords in the BuiltIn_ library. Changes to keywords are rare and they are always done so that old usage is first deprecated. One of the most useful methods is `replace_variables` which allows accessing currently available variables. The following example demonstrates how to get `${OUTPUT_DIR}` which is one of the many handy `automatic variables`_. It is also possible to set new variables from libraries using `set_test_variable`, `set_suite_variable` and `set_global_variable`. .. sourcecode:: python import os.path from robot.libraries.BuiltIn import BuiltIn def do_something(argument): output = do_something_that_creates_a_lot_of_output(argument) outputdir = BuiltIn().replace_variables('${OUTPUTDIR}') path = os.path.join(outputdir, 'results.txt') f = open(path, 'w') f.write(output) f.close() print '*HTML* Output written to <a href="results.txt">results.txt</a>' The only catch with using methods from `BuiltIn` is that all `run_keyword` method variants must be handled specially. Methods that use `run_keyword` methods have to be registered as *run keywords* themselves using `register_run_keyword` method in `BuiltIn` module. This method's documentation explains why this needs to be done and obviously also how to do it. Extending existing test libraries --------------------------------- This section explains different approaches how to add new functionality to existing test libraries and how to use them in your own libraries otherwise. Modifying original source code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you have access to the source code of the library you want to extend, you can naturally modify the source code directly. The biggest problem of this approach is that it can be hard for you to update the original library without affecting your changes. For users it may also be confusing to use a library that has different functionality than the original one. Repackaging the library may also be a big extra task. This approach works extremely well if the enhancements are generic and you plan to submit them back to the original developers. If your changes are applied to the original library, they are included in the future releases and all the problems discussed above are mitigated. If changes are non-generic, or you for some other reason cannot submit them back, the approaches explained in the subsequent sections probably work better. Using inheritance ~~~~~~~~~~~~~~~~~ Another straightforward way to extend an existing library is using inheritance. This is illustrated by the example below that adds new :name:`Title Should Start With` keyword to the SeleniumLibrary_. This example uses Python, but you can obviously extend an existing Java library in Java code the same way. .. sourcecode:: python from SeleniumLibrary import SeleniumLibrary class ExtendedSeleniumLibrary(SeleniumLibrary): def title_should_start_with(self, expected): title = self.get_title() if not title.startswith(expected): raise AssertionError("Title '%s' did not start with '%s'" % (title, expected)) A big difference with this approach compared to modifying the original library is that the new library has a different name than the original. A benefit is that you can easily tell that you are using a custom library, but a big problem is that you cannot easily use the new library with the original. First of all your new library will have same keywords as the original meaning that there is always conflict__. Another problem is that the libraries do not share their state. This approach works well when you start to use a new library and want to add custom enhancements to it from the beginning. Otherwise other mechanisms explained in this section are probably better. __ `Handling keywords with same names`_ Using other libraries directly ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Because test libraries are technically just classes or modules, a simple way to use another library is importing it and using its methods. This approach works great when the methods are static and do not depend on the library state. This is illustrated by the earlier example that uses `Robot Framework's BuiltIn library`__. If the library has state, however, things may not work as you would hope. The library instance you use in your library will not be the same as the framework uses, and thus changes done by executed keywords are not visible to your library. The next section explains how to get an access to the same library instance that the framework uses. __ `Using Robot Framework's internal modules`_ Getting active library instance from Robot Framework ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BuiltIn_ keyword :name:`Get Library Instance` can be used to get the currently active library instance from the framework itself. The library instance returned by this keyword is the same as the framework itself uses, and thus there is no problem seeing the correct library state. Although this functionality is available as a keyword, it is typically used in test libraries directly by importing the :name:`BuiltIn` library class `as discussed earlier`__. The following example illustrates how to implement the same :name:`Title Should Start With` keyword as in the earlier example about `using inheritance`_. __ `Using Robot Framework's internal modules`_ .. sourcecode:: python 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)) This approach is clearly better than importing the library directly and using it when the library has a state. The biggest benefit over inheritance is that you can use the original library normally and use the new library in addition to it when needed. That is demonstrated in the example below where the code from the previous examples is expected to be available in a new library :name:`SeLibExtensions`. .. sourcecode:: robotframework *** Settings *** Library SeleniumLibrary Library SeLibExtensions *** Test Cases *** Example Open Browser http://example # SeleniumLibrary Title Should Start With Example # SeLibExtensions Libraries using dynamic or hybrid API ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test libraries that use the dynamic__ or `hybrid library API`_ often have their own systems how to extend them. With these libraries you need to ask guidance from the library developers or consult the library documentation or source code. __ `dynamic library API`_
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/ExtendingRobotFramework/CreatingTestLibraries.rst
0.945626
0.799677
CreatingTestLibraries.rst
pypi
Using listener interface ======================== Robot Framework has a listener interface that can be used to receive notifications about test execution. Listeners are classes or modules with certain special methods, and they can be implemented both with Python and Java. Example uses of the listener interface include external test monitors, sending a mail message when a test fails, and communicating with other systems. .. contents:: :depth: 2 :local: Taking listeners into use ------------------------- Listeners are taken into use from the command line with the :option:`--listener` option, so that the name of the listener is given to it as an argument. The listener name is got from the name of the class or module implementing the listener interface, similarly as `test library names`_ are got from classes implementing them. The specified listeners must be in the same `module search path`_ where test libraries are searched from when they are imported. Other option is to give an absolute or a relative path to the listener file `similarly as with test libraries`__. It is possible to take multiple listeners into use by using this option several times:: pybot --listener MyListener tests.robot jybot --listener com.company.package.Listener tests.robot pybot --listener path/to/MyListener.py tests.robot pybot --listener module.Listener --listener AnotherListener tests.robot It is also possible to give arguments to listener classes from the command line. Arguments are specified after the listener name (or path) using a colon (`:`) as a separator. If a listener is given as an absolute Windows path, the colon after the drive letter is not considered a separator. Starting from Robot Framework 2.8.7, it is possible to use a semicolon (`;`) as an alternative argument separator. This is useful if listener arguments themselves contain colons, but requires surrounding the whole value with quotes on UNIX-like operating systems:: pybot --listener listener.py:arg1:arg2 tests.robot pybot --listener "listener.py;arg:with:colons" tests.robot pybot --listener C:\\Path\\Listener.py;D:\\data;E:\\extra tests.robot __ `Using physical path to library`_ Available listener interface methods ------------------------------------ Robot Framework creates an instance of the listener class with given arguments when test execution starts. During the test execution, Robot Framework calls listeners' methods when test suites, test cases and keywords start and end. It also calls the appropriate methods when output files are ready, and finally at the end it calls the `close` method. A listener is not required to implement any official interface, and it only needs to have the methods it actually needs. Listener interface versions ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The signatures of methods related to test execution progress were changed in Robot Framework 2.1. This change was made to allow new information to be added to the listener interface without breaking existing listeners. A listener must have attribute `ROBOT_LISTENER_API_VERSION` with value 2, either as a string or as an integer, to be recognized as a new style listener. The old listener interface has been deprecated in Robot Framework 2.9 and will be removed in the next major release. All new listeners should be implemented as new style listeners with method signatures described in the next section. Also all following examples are implemented as new style listeners. Documentation of the old listener interface API can be found from `Robot Framework User Guide`__ version 2.0.4. __ http://robotframework.org/robotframework/#user-guide Listener interface method signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All listener methods related to test execution progress have the same signature `method(name, attributes)`, where `attributes` is a dictionary containing details of the event. The following table lists all the available methods in the listener interface and the contents of the `attributes` dictionary, where applicable. Keys of the dictionary are strings. All of these methods have also `camelCase` aliases. Thus, for example, `startSuite` is a synonym to `start_suite`. .. table:: Available methods in the listener interface :class: tabular +------------------+------------------+----------------------------------------------------------------+ | Method | Arguments | Attributes / Explanation | +==================+==================+================================================================+ | start_suite | name, attributes | Keys in the attribute dictionary: | | | | | | | | * `id`: Suite id. `s1` for the top level suite, `s1-s1` | | | | for its first child suite, `s1-s2` for the second | | | | child, and so on. New in RF 2.8.5. | | | | * `longname`: Suite name including parent suites. | | | | * `doc`: Suite documentation. | | | | * `metadata`: `Free test suite metadata`_ as a dictionary/map. | | | | * `source`: An absolute path of the file/directory the suite | | | | was created from. New in RF 2.7. | | | | * `suites`: Names of the direct child suites this suite has | | | | as a list. | | | | * `tests`: Names of the tests this suite has as a list.ding | | | | Does not include tests of the possible child suites. | | | | * `totaltests`: The total number of tests in this suite. | | | | and all its sub-suites as an integer. | | | | * `starttime`: Suite execution start time. | +------------------+------------------+----------------------------------------------------------------+ | end_suite | name, attributes | Keys in the attribute dictionary: | | | | | | | | * `id`: Same as in `start_suite`. | | | | * `longname`: Same as in `start_suite`. | | | | * `doc`: Same as in `start_suite`. | | | | * `metadata`: Same as in `start_suite`. | | | | * `source`: Same as in `start_suite`. | | | | * `starttime`: Same as in `start_suite`. | | | | * `endtime`: Suite execution end time. | | | | * `elapsedtime`: Total execution time in milliseconds as | | | | an integer | | | | * `status`: Suite status as string `PASS` or `FAIL`. | | | | * `statistics`: Suite statistics (number of passed | | | | and failed tests in the suite) as a string. | | | | * `message`: Error message if suite setup or teardown | | | | has failed, empty otherwise. | +------------------+------------------+----------------------------------------------------------------+ | start_test | name, attributes | Keys in the attribute dictionary: | | | | | | | | * `id`: Test id in format like `s1-s2-t2`, where | | | | the beginning is the parent suite id and the last part | | | | shows test index in that suite. New in RF 2.8.5. | | | | * `longname`: Test name including parent suites. | | | | * `doc`: Test documentation. | | | | * `tags`: Test tags as a list of strings. | | | | * `critical`: `yes` or `no` depending is test considered | | | | critical or not. | | | | * `template`: The name of the template used for the test. | | | | An empty string if the test not templated. | | | | * `starttime`: Test execution execution start time. | +------------------+------------------+----------------------------------------------------------------+ | end_test | name, attributes | Keys in the attribute dictionary: | | | | | | | | * `id`: Same as in `start_test`. | | | | * `longname`: Same as in `start_test`. | | | | * `doc`: Same as in `start_test`. | | | | * `tags`: Same as in `start_test`. | | | | * `critical`: Same as in `start_test`. | | | | * `template`: Same as in `start_test`. | | | | * `starttime`: Same as in `start_test`. | | | | * `endtime`: Test execution execution end time. | | | | * `elapsedtime`: Total execution time in milliseconds as | | | | an integer | | | | * `status`: Test status as string `PASS` or `FAIL`. | | | | * `message`: Status message. Normally an error | | | | message or an empty string. | +------------------+------------------+----------------------------------------------------------------+ | start_keyword | name, attributes | `name` is the full keyword name containing | | | | possible library or resource name as a prefix. | | | | For example, `MyLibrary.Example Keyword`. | | | | | | | | Keys in the attribute dictionary: | | | | | | | | * `type`: String `Keyword` for normal | | | | keywords and `Test Setup`, `Test | | | | Teardown`, `Suite Setup` or `Suite | | | | Teardown` for keywords used in suite/test | | | | setup/teardown. | | | | * `kwname`: Name of the keyword without library or | | | | resource prefix. New in RF 2.9. | | | | * `libname`: Name of the library or resource the | | | | keyword belongs to, or an empty string when | | | | the keyword is in a test case file. New in RF 2.9. | | | | * `doc`: Keyword documentation. | | | | * `args`: Keyword's arguments as a list of strings. | | | | * `assign`: A list of variable names that keyword's | | | | return value is assigned to. New in RF 2.9. | | | | * `starttime`: Keyword execution start time. | +------------------+------------------+----------------------------------------------------------------+ | end_keyword | name, attributes | `name` is the full keyword name containing | | | | possible library or resource name as a prefix. | | | | For example, `MyLibrary.Example Keyword`. | | | | | | | | Keys in the attribute dictionary: | | | | | | | | * `type`: Same as with `start_keyword`. | | | | * `kwname`: Same as with `start_keyword`. | | | | * `libname`: Same as with `start_keyword`. | | | | * `doc`: Same as with `start_keyword`. | | | | * `args`: Same as with `start_keyword`. | | | | * `assign`: Same as with `start_keyword`. | | | | * `starttime`: Same as with `start_keyword`. | | | | * `endtime`: Keyword execution end time. | | | | * `elapsedtime`: Total execution time in milliseconds as | | | | an integer | | | | * `status`: Keyword status as string `PASS` or `FAIL`. | +------------------+------------------+----------------------------------------------------------------+ | log_message | message | Called when an executed keyword writes a log | | | | message. `message` is a dictionary with | | | | the following keys: | | | | | | | | * `message`: The content of the message. | | | | * `level`: `Log level`_ used in logging the message. | | | | * `timestamp`: Message creation time in format | | | | `YYYY-MM-DD hh:mm:ss.mil`. | | | | * `html`: String `yes` or `no` denoting whether the message | | | | should be interpreted as HTML or not. | +------------------+------------------+----------------------------------------------------------------+ | message | message | Called when the framework itself writes a syslog_ | | | | message. `message` is a dictionary with | | | | same keys as with `log_message` method. | +------------------+------------------+----------------------------------------------------------------+ | library_import | name, attributes | Called when a library has been imported. `name` is the name of | | | | the imported library. If the library has been imported using | | | | the `WITH NAME syntax`_, `name` is the specified alias. | | | | | | | | Keys in the attribute dictionary: | | | | | | | | * `args`: Arguments passed to the library as a list. | | | | * `originalname`: The original library name when using the | | | | WITH NAME syntax, otherwise same as `name`. | | | | * `source`: An absolute path to the library source. `None` | | | | with libraries implemented with Java or if getting the | | | | source of the library failed for some reason. | | | | * `importer`: An absolute path to the file importing the | | | | library. `None` when BuiltIn_ is imported well as when | | | | using the :name:`Import Library` keyword. | | | | | | | | New in Robot Framework 2.9. | +------------------+------------------+----------------------------------------------------------------+ | resource_import | name, attributes | Called when a resource file has been imported. `name` is | | | | the name of the imported resource file without the file | | | | extension. | | | | | | | | Keys in the attribute dictionary: | | | | | | | | * `source`: An absolute path to the imported resource file. | | | | * `importer`: An absolute path to the file importing the | | | | resource file. `None` when using the :name:`Import Resource` | | | | keyword. | | | | | | | | New in Robot Framework 2.9. | +------------------+------------------+----------------------------------------------------------------+ | variables_import | name, attributes | Called when a variable file has been imported. `name` is | | | | the name of the imported variable file with the file | | | | extension. | | | | | | | | Keys in the attribute dictionary: | | | | | | | | * `args`: Arguments passed to the variable file as a list. | | | | * `source`: An absolute path to the imported variable file. | | | | * `importer`: An absolute path to the file importing the | | | | resource file. `None` when using the :name:`Import | | | | Variables` keyword. | | | | | | | | New in Robot Framework 2.9. | +------------------+------------------+----------------------------------------------------------------+ | output_file | path | Called when writing to an output file is | | | | finished. The path is an absolute path to the file. | +------------------+------------------+----------------------------------------------------------------+ | log_file | path | Called when writing to a log file is | | | | finished. The path is an absolute path to the file. | +------------------+------------------+----------------------------------------------------------------+ | report_file | path | Called when writing to a report file is | | | | finished. The path is an absolute path to the file. | +------------------+------------------+----------------------------------------------------------------+ | debug_file | path | Called when writing to a debug file is | | | | finished. The path is an absolute path to the file. | +------------------+------------------+----------------------------------------------------------------+ | close | | Called after all test suites, and test cases in | | | | them, have been executed. With `library listeners`__ called | | | | when the library goes out of scope. | +------------------+------------------+----------------------------------------------------------------+ The available methods and their arguments are also shown in a formal Java interface specification below. Contents of the `java.util.Map attributes` are as in the table above. It should be remembered that a listener *does not* need to implement any explicit interface or have all these methods. .. sourcecode:: java public interface RobotListenerInterface { public static final int ROBOT_LISTENER_API_VERSION = 2; void startSuite(String name, java.util.Map attributes); void endSuite(String name, java.util.Map attributes); void startTest(String name, java.util.Map attributes); void endTest(String name, java.util.Map attributes); void startKeyword(String name, java.util.Map attributes); void endKeyword(String name, java.util.Map attributes); void logMessage(java.util.Map message); void message(java.util.Map message); void outputFile(String path); void logFile(String path); void reportFile(String path); void debugFile(String path); void close(); } __ `Test libraries as listeners`_ Listeners logging ----------------- Robot Framework offers a `programmatic logging APIs`_ that listeners can utilize. There are some limitations, however, and how different listener methods can log messages is explained in the table below. .. table:: How listener methods can log :class: tabular +----------------------+---------------------------------------------------+ | Methods | Explanation | +======================+===================================================+ | start_keyword, | Messages are logged to the normal `log file`_ | | end_keyword, | under the executed keyword. | | log_message | | +----------------------+---------------------------------------------------+ | start_suite, | Messages are logged to the syslog_. Warnings are | | end_suite, | shown also in the `execution errors`_ section of | | start_test, end_test | the normal log file. | +----------------------+---------------------------------------------------+ | message | Messages are normally logged to the syslog. If | | | this method is used while a keyword is executing, | | | messages are logged to the normal log file. | +----------------------+---------------------------------------------------+ | Other methods | Messages are only logged to the syslog. | +----------------------+---------------------------------------------------+ .. note:: To avoid recursion, messages logged by listeners are not sent to listener methods `log_message` and `message`. Listener examples ----------------- The first simple example is implemented in a Python module. It mainly illustrates that using the listener interface is not very complicated. .. sourcecode:: python ROBOT_LISTENER_API_VERSION = 2 def start_test(name, attrs): print 'Executing test %s' % name def start_keyword(name, attrs): print 'Executing keyword %s with arguments %s' % (name, attrs['args']) def log_file(path): print 'Test log available at %s' % path def close(): print 'All tests executed' The second example, which still uses Python, is slightly more complicated. It writes all the information it gets into a text file in a temporary directory without much formatting. The filename may be given from the command line, but also has a default value. Note that in real usage, the `debug file`_ functionality available through the command line option :option:`--debugfile` is probably more useful than this example. .. sourcecode:: python import os.path import tempfile class PythonListener: ROBOT_LISTENER_API_VERSION = 2 def __init__(self, filename='listen.txt'): outpath = os.path.join(tempfile.gettempdir(), filename) self.outfile = open(outpath, 'w') def start_suite(self, name, attrs): self.outfile.write("%s '%s'\n" % (name, attrs['doc'])) def start_test(self, name, attrs): tags = ' '.join(attrs['tags']) self.outfile.write("- %s '%s' [ %s ] :: " % (name, attrs['doc'], tags)) def end_test(self, name, attrs): if attrs['status'] == 'PASS': self.outfile.write('PASS\n') else: self.outfile.write('FAIL: %s\n' % attrs['message']) def end_suite(self, name, attrs): self.outfile.write('%s\n%s\n' % (attrs['status'], attrs['message'])) def close(self): self.outfile.close() The third example implements the same functionality as the previous one, but uses Java instead of Python. .. sourcecode:: java import java.io.*; import java.util.Map; import java.util.List; public class JavaListener { public static final int ROBOT_LISTENER_API_VERSION = 2; public static final String DEFAULT_FILENAME = "listen_java.txt"; private BufferedWriter outfile = null; public JavaListener() throws IOException { this(DEFAULT_FILENAME); } public JavaListener(String filename) throws IOException { String tmpdir = System.getProperty("java.io.tmpdir"); String sep = System.getProperty("file.separator"); String outpath = tmpdir + sep + filename; outfile = new BufferedWriter(new FileWriter(outpath)); } public void startSuite(String name, Map attrs) throws IOException { outfile.write(name + " '" + attrs.get("doc") + "'\n"); } public void startTest(String name, Map attrs) throws IOException { outfile.write("- " + name + " '" + attrs.get("doc") + "' [ "); List tags = (List)attrs.get("tags"); for (int i=0; i < tags.size(); i++) { outfile.write(tags.get(i) + " "); } outfile.write(" ] :: "); } public void endTest(String name, Map attrs) throws IOException { String status = attrs.get("status").toString(); if (status.equals("PASS")) { outfile.write("PASS\n"); } else { outfile.write("FAIL: " + attrs.get("message") + "\n"); } } public void endSuite(String name, Map attrs) throws IOException { outfile.write(attrs.get("status") + "\n" + attrs.get("message") + "\n"); } public void close() throws IOException { outfile.close(); } } Test libraries as listeners --------------------------- Sometimes it is useful also for `test libraries`_ to get notifications about test execution. This allows them, for example, to perform certain clean-up activities automatically when a test suite or the whole test execution ends. .. note:: This functionality is new in Robot Framework 2.8.5. Registering listener ~~~~~~~~~~~~~~~~~~~~ A test library can register a listener by using `ROBOT_LIBRARY_LISTENER` attribute. The value of this attribute should be an instance of the listener to use. It may be a totally independent listener or the library itself can act as a listener. To avoid listener methods to be exposed as keywords in the latter case, it is possible to prefix them with an underscore. For example, instead of using `end_suite` or `endSuite`, it is possible to use `_end_suite` or `_endSuite`. Following examples illustrates using an external listener as well as library acting as a listener itself: .. sourcecode:: java import my.project.Listener; public class JavaLibraryWithExternalListener { public static final Listener ROBOT_LIBRARY_LISTENER = new Listener(); public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL"; // actual library code here ... } .. sourcecode:: python class PythonLibraryAsListenerItself(object): ROBOT_LIBRARY_SCOPE = 'TEST SUITE' ROBOT_LISTENER_API_VERSION = 2 def __init__(self): self.ROBOT_LIBRARY_LISTENER = self def _end_suite(self, name, attrs): print 'Suite %s (%s) ending.' % (name, attrs['id']) # actual library code here ... As the seconds example above already demonstrated, library listeners can specify `listener interface versions`_ using `ROBOT_LISTENER_API_VERSION` attribute exactly like any other listener. Starting from version 2.9, you can also provide any list like object of instances in the `ROBOT_LIBRARY_LISTENER` attribute. This will cause all instances of the list to be registered as listeners. Called listener methods ~~~~~~~~~~~~~~~~~~~~~~~ Library's listener will get notifications about all events in suites where the library is imported. In practice this means that `start_suite`, `end_suite`, `start_test`, `end_test`, `start_keyword`, `end_keyword`, `log_message`, and `message` methods are called inside those suites. If the library creates a new listener instance every time when the library itself is instantiated, the actual listener instance to use will change according to the `test library scope`_. In addition to the previously listed listener methods, `close` method is called when the library goes out of the scope. See `Listener interface method signatures`_ section above for more information about all these methods.
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/ExtendingRobotFramework/ListenerInterface.rst
0.916913
0.779616
ListenerInterface.rst
pypi
Variables ========= .. contents:: :depth: 2 :local: Introduction ------------ Variables are an integral feature of Robot Framework, and they can be used in most places in test data. Most commonly, they are used in arguments for keywords in test case tables and keyword tables, but also all settings allow variables in their values. A normal keyword name *cannot* be specified with a variable, but the BuiltIn_ keyword :name:`Run Keyword` can be used to get the same effect. Robot Framework has its own variables that can be used as scalars__, lists__ or `dictionaries`__ using syntax `${SCALAR}`, `@{LIST}` and `&{DICT}`, respectively. In addition to this, `environment variables`_ can be used directly with syntax `%{ENV_VAR}`. Variables are useful, for example, in these cases: - When strings change often in the test data. With variables you only need to make these changes in one place. - When creating system-independent and operating-system-independent test data. Using variables instead of hard-coded strings eases that considerably (for example, `${RESOURCES}` instead of `c:\resources`, or `${HOST}` instead of `10.0.0.1:8080`). Because variables can be `set from the command line`__ when tests are started, changing system-specific variables is easy (for example, `--variable HOST:10.0.0.2:1234 --variable RESOURCES:/opt/resources`). This also facilitates localization testing, which often involves running the same tests with different strings. - When there is a need to have objects other than strings as arguments for keywords. This is not possible without variables. - When different keywords, even in different test libraries, need to communicate. You can assign a return value from one keyword to a variable and pass it as an argument to another. - When values in the test data are long or otherwise complicated. For example, `${URL}` is shorter than `http://long.domain.name:8080/path/to/service?foo=1&bar=2&zap=42`. If a non-existent variable is used in the test data, the keyword using it fails. If the same syntax that is used for variables is needed as a literal string, it must be `escaped with a backslash`__ as in `\${NAME}`. __ `Scalar variables`_ __ `List variables`_ __ `Dictionary variables`_ __ `Setting variables in command line`_ __ Escaping_ Variable types -------------- Different variable types are explained in this section. How variables can be created is discussed in subsequent sections. Robot Framework variables, similarly as keywords, are case-insensitive, and also spaces and underscores are ignored. However, it is recommended to use capital letters with global variables (for example, `${PATH}` or `${TWO WORDS}`) and small letters with variables that are only available in certain test cases or user keywords (for example, `${my var}` or `${myVar}`). Much more importantly, though, cases should be used consistently. Variable name consists of the variable type identifier (`$`, `@`, `&`, `%`), curly braces (`{`, `}`) and actual variable name between the braces. Unlike in some programming languages where similar variable syntax is used, curly braces are always mandatory. Variable names can basically have any characters between the curly braces. However, using only alphabetic characters from a to z, numbers, underscore and space is recommended, and it is even a requirement for using the `extended variable syntax`_. .. _scalar variable: Scalar variables ~~~~~~~~~~~~~~~~ When scalar variables are used in the test data, they are replaced with the value they are assigned to. While scalar variables are most commonly used for simple strings, you can assign any objects, including lists, to them. The scalar variable syntax, for example `${NAME}`, should be familiar to most users, as it is also used, for example, in shell scripts and Perl programming language. The example below illustrates the usage of scalar variables. Assuming that the variables `${GREET}` and `${NAME}` are available and assigned to strings `Hello` and `world`, respectively, both the example test cases are equivalent. .. sourcecode:: robotframework *** Test Cases *** Constants Log Hello Log Hello, world!! Variables Log ${GREET} Log ${GREET}, ${NAME}!! When a scalar variable is used as the only value in a test data cell, the scalar variable is replaced with the value it has. The value may be any object. When a scalar variable is used in a test data cell with anything else (constant strings or other variables), its value is first converted into a Unicode string and then catenated to whatever is in that cell. Converting the value into a string means that the object's method `__unicode__` (in Python, with `__str__` as a fallback) or `toString` (in Java) is called. .. note:: Variable values are used as-is without conversions also when passing arguments to keywords using the `named arguments`_ syntax like `argname=${var}`. The example below demonstrates the difference between having a variable in a cell alone or with other content. First, let us assume that we have a variable `${STR}` set to a string `Hello, world!` and `${OBJ}` set to an instance of the following Java object: .. sourcecode:: java public class MyObj { public String toString() { return "Hi, tellus!"; } } With these two variables set, we then have the following test data: .. sourcecode:: robotframework *** Test Cases *** Objects KW 1 ${STR} KW 2 ${OBJ} KW 3 I said "${STR}" KW 4 You said "${OBJ}" Finally, when this test data is executed, different keywords receive the arguments as explained below: - :name:`KW 1` gets a string `Hello, world!` - :name:`KW 2` gets an object stored to variable `${OBJ}` - :name:`KW 3` gets a string `I said "Hello, world!"` - :name:`KW 4` gets a string `You said "Hi, tellus!"` .. Note:: Converting variables to Unicode obviously fails if the variable cannot be represented as Unicode. This can happen, for example, if you try to use byte sequences as arguments to keywords so that you catenate the values together like `${byte1}${byte2}`. A workaround is creating a variable that contains the whole value and using it alone in the cell (e.g. `${bytes}`) because then the value is used as-is. .. _list variable: List variables ~~~~~~~~~~~~~~ When a variable is used as a scalar like `${EXAMPLE}`, its value will be used as-is. If a variable value is a list or list-like, it is also possible to use as a list variable like `@{EXAMPLE}`. In this case individual list items are passed in as arguments separately. This is easiest to explain with an example. Assuming that a variable `@{USER}` has value `['robot','secret']`, the following two test cases are equivalent: .. sourcecode:: robotframework *** Test Cases *** Constants Login robot secret List Variable Login @{USER} Robot Framework stores its own variables in one internal storage and allows using them as scalars, lists or dictionaries. Using a variable as a list requires its value to be a Python list or list-like object. Robot Framework does not allow strings to be used as lists, but other iterable objects such as tuples or dictionaries are accepted. Prior to Robot Framework 2.9, scalar and list variables were stored separately, but it was possible to use list variables as scalars and scalar variables as lists. This caused lot of confusion when there accidentally was a scalar variable and a list variable with same name but different value. Using list variables with other data '''''''''''''''''''''''''''''''''''' It is possible to use list variables with other arguments, including other list variables. .. sourcecode:: robotframework *** Test Cases *** Example Keyword @{LIST} more args Keyword ${SCALAR} @{LIST} constant Keyword @{LIST} @{ANOTHER} @{ONE MORE} If a list variable is used in a cell with other data (constant strings or other variables), the final value will contain a string representation of the variable value. The end result is thus exactly the same as when using the variable as a scalar with other data in the same cell. Accessing individual list items ''''''''''''''''''''''''''''''' It is possible to access a certain value of a list variable with the syntax `@{NAME}[index]`, where `index` is the index of the selected value. Indexes start from zero, and trying to access a value with too large an index causes an error. Indices are automatically converted to integers, and it is also possible to use variables as indices. List items accessed in this manner can be used similarly as scalar variables. .. sourcecode:: robotframework *** Test Cases *** Constants Login robot secret Title Should Be Welcome robot! List Variable Login @{USER} Title Should Be Welcome @{USER}[0]! Variable Index Log @{LIST}[${INDEX}] Using list variables with settings '''''''''''''''''''''''''''''''''' List variables can be used only with some of the settings__. They can be used in arguments to imported libraries and variable files, but library and variable file names themselves cannot be list variables. Also with setups and teardowns list variable can not be used as the name of the keyword, but can be used in arguments. With tag related settings they can be used freely. Using scalar variables is possible in those places where list variables are not supported. .. sourcecode:: robotframework *** Settings *** Library ExampleLibrary @{LIB ARGS} # This works Library ${LIBRARY} @{LIB ARGS} # This works Library @{NAME AND ARGS} # This does not work Suite Setup Some Keyword @{KW ARGS} # This works Suite Setup ${KEYWORD} @{KW ARGS} # This works Suite Setup @{KEYWORD} # This does not work Default Tags @{TAGS} # This works __ `All available settings in test data`_ .. _dictionary variable: Dictionary variables ~~~~~~~~~~~~~~~~~~~~ As discussed above, a variable containing a list can be used as a `list variable`_ to pass list items to a keyword as individual arguments. Similarly a variable containing a Python dictionary or a dictionary-like object can be used as a dictionary variable like `&{EXAMPLE}`. In practice this means that individual items of the dictionary are passed as `named arguments`_ to the keyword. Assuming that a variable `&{USER}` has value `{'name': 'robot', 'password': 'secret'}`, the following two test cases are equivalent. .. sourcecode:: robotframework *** Test Cases *** Strings Login name=robot password=secret List Variable Login &{USER} Dictionary variables are new in Robot Framework 2.9. Using dictionary variables with other data '''''''''''''''''''''''''''''''''''''''''' It is possible to use dictionary variables with other arguments, including other dictionary variables. Because `named argument syntax`_ requires positional arguments to be before named argument, dictionaries can only be followed by named arguments or other dictionaries. .. sourcecode:: robotframework *** Test Cases *** Example Keyword &{DICT} named=arg Keyword positional @{LIST} &{DICT} Keyword &{DICT} &{ANOTHER} &{ONE MORE} If a dictionary variable is used in a cell with other data (constant strings or other variables), the final value will contain a string representation of the variable value. The end result is thus exactly the same as when using the variable as a scalar with other data in the same cell. Accessing individual dictionary items ''''''''''''''''''''''''''''''''''''' It is possible to access a certain value of a dictionary variable with the syntax `&{NAME}[key]`, where `key` is the name of the selected value. Keys are considered to be strings, but non-strings keys can be used as variables. Dictionary items accessed in this manner can be used similarly as scalar variables: .. sourcecode:: robotframework *** Test Cases *** Constants Login name=robot password=secret Title Should Be Welcome robot! Dict Variable Login &{USER} Title Should Be Welcome &{USER}[name]! Variable Key Log Many &{DICT}[${KEY}] &{DICT}[${42}] Using dictionary variables with settings '''''''''''''''''''''''''''''''''''''''' Dictionary variables cannot generally be used with settings. The only exception are imports, setups and teardowns where dictionaries can be used as arguments. .. sourcecode:: robotframework *** Settings *** Library ExampleLibrary &{LIB ARGS} Suite Setup Some Keyword &{KW ARGS} named=arg .. _environment variable: Environment variables ~~~~~~~~~~~~~~~~~~~~~ Robot Framework allows using environment variables in the test data using the syntax `%{ENV_VAR_NAME}`. They are limited to string values. Environment variables set in the operating system before the test execution are available during it, and it is possible to create new ones with the keyword :name:`Set Environment Variable` or delete existing ones with the keyword :name:`Delete Environment Variable`, both available in the OperatingSystem_ library. Because environment variables are global, environment variables set in one test case can be used in other test cases executed after it. However, changes to environment variables are not effective after the test execution. .. sourcecode:: robotframework *** Test Cases *** Env Variables Log Current user: %{USER} Run %{JAVA_HOME}${/}javac Java system properties ~~~~~~~~~~~~~~~~~~~~~~ When running tests with Jython, it is possible to access `Java system properties`__ using same syntax as `environment variables`_. If an environment variable and a system property with same name exist, the environment variable will be used. .. sourcecode:: robotframework *** Test Cases *** System Properties Log %{user.name} running tests on %{os.name} __ http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html Creating variables ------------------ Variables can spring into existence from different sources. Variable table ~~~~~~~~~~~~~~ The most common source for variables are Variable tables in `test case files`_ and `resource files`_. Variable tables are convenient, because they allow creating variables in the same place as the rest of the test data, and the needed syntax is very simple. Their main disadvantages are that values are always strings and they cannot be created dynamically. If either of these is a problem, `variable files`_ can be used instead. Creating scalar variables ''''''''''''''''''''''''' The simplest possible variable assignment is setting a string into a scalar variable. This is done by giving the variable name (including `${}`) in the first column of the Variable table and the value in the second one. If the second column is empty, an empty string is set as a value. Also an already defined variable can be used in the value. .. sourcecode:: robotframework *** Variables *** ${NAME} Robot Framework ${VERSION} 2.0 ${ROBOT} ${NAME} ${VERSION} It is also possible, but not obligatory, to use the equals sign `=` after the variable name to make assigning variables slightly more explicit. .. sourcecode:: robotframework *** Variables *** ${NAME} = Robot Framework ${VERSION} = 2.0 If a scalar variable has a long value, it can be split to multiple columns and rows__. By default cells are catenated together using a space, but this can be changed by having `SEPARATOR=<sep>` in the first cell. .. sourcecode:: robotframework *** Variables *** ${EXAMPLE} This value is joined together with a space ${MULTILINE} SEPARATOR=\n First line ... Second line Third line Joining long values like above is a new feature in Robot Framework 2.9. Creating a scalar variable with multiple values was a syntax error in Robot Framework 2.8 and with earlier versions it created a variable with a list value. __ `Dividing test data to several rows`_ Creating list variables ''''''''''''''''''''''' Creating list variables is as easy as creating scalar variables. Again, the variable name is in the first column of the Variable table and values in the subsequent columns. A list variable can have any number of values, starting from zero, and if many values are needed, they can be `split into several rows`__. __ `Dividing test data to several rows`_ .. sourcecode:: robotframework *** Variables *** @{NAMES} Matti Teppo @{NAMES2} @{NAMES} Seppo @{NOTHING} @{MANY} one two three four ... five six seven Creating dictionary variables ''''''''''''''''''''''''''''' Dictionary variables can be created in the variable table similarly as list variables. The difference is that items need to be created using `name=value` syntax or existing dictionary variables. If there are multiple items with same name, the last value has precedence. If a name contains an equal sign, it can be escaped__ with a backslash like `\=`. .. sourcecode:: robotframework *** Variables *** &{USER 1} name=Matti address=xxx phone=123 &{USER 2} name=Teppo address=yyy phone=456 &{MANY} first=1 second=${2} ${3}=third &{EVEN MORE} &{MANY} first=override empty= ... =empty key\\=here=value Dictionary variables created in variable table have two extra properties compared to normal Python dictionaries. First of all, values of these dictionaries can be accessed like attributes, which means that it is possible to use `extended variable syntax`_ like `${VAR.key}`. This only works if the key is a valid attribute name and does not match any normal attribute Python dictionaries have. For example, individual value `&{USER}[name]` can also be accessed like `${USER.name}` (notice that `$` is needed in this context), but `&{MANY}[${3}]` does not work as `${MANY.3}`. Another special property of dictionaries created in the variable table is that they are ordered. This means that if these dictionaries are iterated, their items always come in the order they are defined. This can be useful if dictionaries are used as `list variables`_ with `for loops`_ or otherwise. When a dictionary is used as a list variable, the actual value contains dictionary keys. For example, `@{MANY}` variable would have value `['first', 'second', 3]`. __ Escaping_ Variable file ~~~~~~~~~~~~~ Variable files are the most powerful mechanism for creating different kind of variables. It is possible to assign variables to any object using them, and they also enable creating variables dynamically. The variable file syntax and taking variable files into use is explained in section `Resource and variable files`_. Setting variables in command line ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Variables can be set from the command line either individually with the :option:`--variable (-v)` option or using a variable file with the :option:`--variablefile (-V)` option. Variables set from the command line are globally available for all executed test data files, and they also override possible variables with the same names in the Variable table and in variable files imported in the test data. The syntax for setting individual variables is :option:`--variable name:value`, where `name` is the name of the variable without `${}` and `value` is its value. Several variables can be set by using this option several times. Only scalar variables can be set using this syntax and they can only get string values. Many special characters are difficult to represent in the command line, but they can be escaped__ with the :option:`--escape` option. __ `Escaping complicated characters`_ .. sourcecode:: bash --variable EXAMPLE:value --variable HOST:localhost:7272 --variable USER:robot --variable ESCAPED:Qquotes_and_spacesQ --escape quot:Q --escape space:_ In the examples above, variables are set so that - `${EXAMPLE}` gets the value `value` - `${HOST}` and `${USER}` get the values `localhost:7272` and `robot` - `${ESCAPED}` gets the value `"quotes and spaces"` The basic syntax for taking `variable files`_ into use from the command line is :option:`--variablefile path/to/variables.py`, and `Taking variable files into use`_ section has more details. What variables actually are created depends on what variables there are in the referenced variable file. If both variable files and individual variables are given from the command line, the latter have `higher priority`__. __ `Variable priorities and scopes`_ Return values from keywords ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Return values from keywords can also be set into variables. This allows communication between different keywords even in different test libraries. Variables set in this manner are otherwise similar to any other variables, but they are available only in the `local scope`_ where they are created. Thus it is not possible, for example, to set a variable like this in one test case and use it in another. This is because, in general, automated test cases should not depend on each other, and accidentally setting a variable that is used elsewhere could cause hard-to-debug errors. If there is a genuine need for setting a variable in one test case and using it in another, it is possible to use BuiltIn_ keywords as explained in the next section. Assigning scalar variables '''''''''''''''''''''''''' Any value returned by a keyword can be assigned to a `scalar variable`_. As illustrated by the example below, the required syntax is very simple. .. sourcecode:: robotframework *** Test Cases *** Returning ${x} = Get X an argument Log We got ${x}! In the above example the value returned by the :name:`Get X` keyword is first set into the variable `${x}` and then used by the :name:`Log` keyword. Having the equals sign `=` after the variable name is not obligatory, but it makes the assignment more explicit. Creating local variables like this works both in test case and user keyword level. Notice that although a value is assigned to a scalar variable, it can be used as a `list variable`_ if it has a list-like value and as a `dictionary variable`_ if it has a dictionary-like value. .. sourcecode:: robotframework *** Test Cases *** Example ${list} = Create List first second third Length Should Be ${list} 3 Log Many @{list} Assigning list variables '''''''''''''''''''''''' If a keyword returns a list or any list-like object, it is possible to assign it to a `list variable`_. .. sourcecode:: robotframework *** Test Cases *** Example @{list} = Create List first second third Length Should Be ${list} 3 Log Many @{list} Because all Robot Framework variables are stored in same namespace, there is not much difference between assigning a value to a scalar variable or a list variable. This can be seen by comparing the last two examples above. The main differences are that when creating a list variable, Robot Framework automatically verifies that the value is a list or list-like, and the stored variable value will be a new list created from the return value. When assigning to a scalar variable, the return value is not verified and the stored value will be the exact same object that was returned. Assigning dictionary variables '''''''''''''''''''''''''''''' If a keyword returns a dictionary or any dictionary-like object, it is possible to assign it to a `dictionary variable`_. .. sourcecode:: robotframework *** Test Cases *** Example &{dict} = Create Dictionary first=1 second=${2} ${3}=third Length Should Be ${dict} 3 Do Something &{dict} Log ${dict.first} Because all Robot Framework variables are stored in same namespace, it would also be possible to assign a dictionary into a scalar variable and use it later as a dictionary when needed. There are, however, some actual benefits in creating a dictionary variable explicitly. First of all, Robot Framework verifies that the returned value is a dictionary or dictionary-like similarly as it verifies that list variables can only get a list-like value. Another benefit is that Robot Framework converts the value into a special dictionary it uses also when `creating dictionary variables`_ in the variable table. These dictionaries are sortable and their values can be accessed using attribute access like `${dict.first}` in the above example. Assigning multiple variables '''''''''''''''''''''''''''' If a keyword returns a list or a list-like object, it is possible to assign individual values into multiple scalar variables or into scalar variables and a list variable. .. sourcecode:: robotframework *** Test Cases *** Assign Multiple ${a} ${b} ${c} = Get Three ${first} @{rest} = Get Three @{before} ${last} = Get Three ${begin} @{middle} ${end} = Get Three Assuming that the keyword :name:`Get Three` returns a list `[1, 2, 3]`, the following variables are created: - `${a}`, `${b}` and `${c}` with values `1`, `2`, and `3`, respectively. - `${first}` with value `1`, and `@{rest}` with value `[2, 3]`. - `@{before}` with value `[1, 2]` and `${last}` with value `3`. - `${begin}` with value `1`, `@{middle}` with value `[2]` and ${end} with value `3`. It is an error if the returned list has more or less values than there are scalar variables to assign. Additionally, only one list variable is allowed and dictionary variables can only be assigned alone. The support for assigning multiple variables was slightly changed in Robot Framework 2.9. Prior to it a list variable was only allowed as the last assigned variable, but nowadays it can be used anywhere. Additionally, it was possible to return more values than scalar variables. In that case the last scalar variable was magically turned into a list containing the extra values. Using :name:`Set Test/Suite/Global Variable` keywords ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The BuiltIn_ library has keywords :name:`Set Test Variable`, :name:`Set Suite Variable` and :name:`Set Global Variable` which can be used for setting variables dynamically during the test execution. If a variable already exists within the new scope, its value will be overwritten, and otherwise a new variable is created. Variables set with :name:`Set Test Variable` 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. Variables set with :name:`Set Suite Variable` 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. Variables set with :name:`Set Global Variable` 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 :option:`--variable` or :option:`--variablefile`. Because this keyword can change variables everywhere, it should be used with care. .. note:: :name:`Set Test/Suite/Global Variable` keywords set named variables directly into `test, suite or global variable scope`__ and return nothing. On the other hand, another BuiltIn_ keyword :name:`Set Variable` sets local variables using `return values`__. __ `Setting variables in command line`_ __ `Variable scopes`_ __ `Return values from keywords`_ .. _built-in variable: Built-in variables ------------------ Robot Framework provides some built-in variables that are available automatically. Operating-system variables ~~~~~~~~~~~~~~~~~~~~~~~~~~ Built-in variables related to the operating system ease making the test data operating-system-agnostic. .. table:: Available operating-system-related built-in variables :class: tabular +------------+------------------------------------------------------------------+ | Variable | Explanation | +============+==================================================================+ | ${CURDIR} | An absolute path to the directory where the test data | | | file is located. This variable is case-sensitive. | +------------+------------------------------------------------------------------+ | ${TEMPDIR} | An absolute path to the system temporary directory. In UNIX-like | | | systems this is typically :file:`/tmp`, and in Windows | | | :file:`c:\\Documents and Settings\\<user>\\Local Settings\\Temp`.| +------------+------------------------------------------------------------------+ | ${EXECDIR} | An absolute path to the directory where test execution was | | | started from. | +------------+------------------------------------------------------------------+ | ${/} | The system directory path separator. `/` in UNIX-like | | | systems and :codesc:`\\` in Windows. | +------------+------------------------------------------------------------------+ | ${:} | The system path element separator. `:` in UNIX-like | | | systems and `;` in Windows. | +------------+------------------------------------------------------------------+ | ${\\n} | The system line separator. :codesc:`\\n` in UNIX-like systems and| | | :codesc:`\\r\\n` in Windows. New in version 2.7.5. | +------------+------------------------------------------------------------------+ .. sourcecode:: robotframework *** Test Cases *** Example Create Binary File ${CURDIR}${/}input.data Some text here${\\n}on two lines Set Environment Variable CLASSPATH ${TEMPDIR}${:}${CURDIR}${/}foo.jar Number variables ~~~~~~~~~~~~~~~~ The variable syntax can be used for creating both integers and floating point numbers, as illustrated in the example below. This is useful when a keyword expects to get an actual number, and not a string that just looks like a number, as an argument. .. sourcecode:: robotframework *** Test Cases *** Example 1A Connect example.com 80 # Connect gets two strings as arguments Example 1B Connect example.com ${80} # Connect gets a string and an integer Example 2 Do X ${3.14} ${-1e-4} # Do X gets floating point numbers 3.14 and -0.0001 It is possible to create integers also from binary, octal, and hexadecimal values using `0b`, `0o` and `0x` prefixes, respectively. The syntax is case insensitive. .. sourcecode:: robotframework *** Test Cases *** Example Should Be Equal ${0b1011} ${11} Should Be Equal ${0o10} ${8} Should Be Equal ${0xff} ${255} Should Be Equal ${0B1010} ${0XA} Boolean and None/null variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Also Boolean values and Python `None` and Java `null` can be created using the variable syntax similarly as numbers. .. sourcecode:: robotframework *** Test Cases *** Boolean Set Status ${true} # Set Status gets Boolean true as an argument Create Y something ${false} # Create Y gets a string and Boolean false None Do XYZ ${None} # Do XYZ gets Python None as an argument Null ${ret} = Get Value arg # Checking that Get Value returns Java null Should Be Equal ${ret} ${null} These variables are case-insensitive, so for example `${True}` and `${true}` are equivalent. Additionally, `${None}` and `${null}` are synonyms, because when running tests on the Jython interpreter, Jython automatically converts `None` and `null` to the correct format when necessary. Space and empty variables ~~~~~~~~~~~~~~~~~~~~~~~~~ It is possible to create spaces and empty strings using variables `${SPACE}` and `${EMPTY}`, respectively. These variables are useful, for example, when there would otherwise be a need to `escape spaces or empty cells`__ with a backslash. If more than one space is needed, it is possible to use the `extended variable syntax`_ like `${SPACE * 5}`. In the following example, :name:`Should Be Equal` keyword gets identical arguments but those using variables are easier to understand than those using backslashes. .. sourcecode:: robotframework *** Test Cases *** One Space Should Be Equal ${SPACE} \ \ Four Spaces Should Be Equal ${SPACE * 4} \ \ \ \ \ Ten Spaces Should Be Equal ${SPACE * 10} \ \ \ \ \ \ \ \ \ \ \ Quoted Space Should Be Equal "${SPACE}" " " Quoted Spaces Should Be Equal "${SPACE * 2}" " \ " Empty Should Be Equal ${EMPTY} \ There is also an empty `list variable`_ `@{EMPTY}` and an empty `dictionary variable`_ `&{EMPTY}`. Because they have no content, they basically vanish when used somewhere in the test data. They are useful, for example, with `test templates`_ when the `template keyword is used without arguments`__ or when overriding list or dictionary variables in different scopes. Modifying the value of `@{EMPTY}` or `&{EMPTY}` is not possible. .. sourcecode:: robotframework *** Test Cases *** Template [Template] Some keyword @{EMPTY} Override Set Global Variable @{LIST} @{EMPTY} Set Suite Variable &{DICT} &{EMPTY} .. note:: `@{EMPTY}` is new in Robot Framework 2.7.4 and `&{EMPTY}` in Robot Framework 2.9. __ Escaping_ __ https://groups.google.com/group/robotframework-users/browse_thread/thread/ccc9e1cd77870437/4577836fe946e7d5?lnk=gst&q=templates#4577836fe946e7d5 Automatic variables ~~~~~~~~~~~~~~~~~~~ Some automatic variables can also be used in the test data. These variables can have different values during the test execution and some of them are not even available all the time. Altering the value of these variables does not affect the original values, but some values can be changed dynamically using keywords from the `BuiltIn`_ library. .. table:: Available automatic variables :class: tabular +------------------------+-------------------------------------------------------+------------+ | Variable | Explanation | Available | +========================+=======================================================+============+ | ${TEST NAME} | The name of the current test case. | Test case | +------------------------+-------------------------------------------------------+------------+ | @{TEST TAGS} | Contains the tags of the current test case in | Test case | | | alphabetical order. Can be modified dynamically using | | | | :name:`Set Tags` and :name:`Remove Tags` keywords. | | +------------------------+-------------------------------------------------------+------------+ | ${TEST DOCUMENTATION} | The documentation of the current test case. Can be set| Test case | | | dynamically using using :name:`Set Test Documentation`| | | | keyword. New in Robot Framework 2.7. | | +------------------------+-------------------------------------------------------+------------+ | ${TEST STATUS} | The status of the current test case, either PASS or | `Test | | | FAIL. | teardown`_ | +------------------------+-------------------------------------------------------+------------+ | ${TEST MESSAGE} | The message of the current test case. | `Test | | | | teardown`_ | +------------------------+-------------------------------------------------------+------------+ | ${PREV TEST NAME} | The name of the previous test case, or an empty string| Everywhere | | | if no tests have been executed yet. | | +------------------------+-------------------------------------------------------+------------+ | ${PREV TEST STATUS} | The status of the previous test case: either PASS, | Everywhere | | | FAIL, or an empty string when no tests have been | | | | executed. | | +------------------------+-------------------------------------------------------+------------+ | ${PREV TEST MESSAGE} | The possible error message of the previous test case. | Everywhere | +------------------------+-------------------------------------------------------+------------+ | ${SUITE NAME} | The full name of the current test suite. | Everywhere | +------------------------+-------------------------------------------------------+------------+ | ${SUITE SOURCE} | An absolute path to the suite file or directory. | Everywhere | +------------------------+-------------------------------------------------------+------------+ | ${SUITE DOCUMENTATION} | The documentation of the current test suite. Can be | Everywhere | | | set dynamically using using :name:`Set Suite | | | | Documentation` keyword. New in Robot Framework 2.7. | | +------------------------+-------------------------------------------------------+------------+ | &{SUITE METADATA} | The free metadata of the current test suite. Can be | Everywhere | | | set using :name:`Set Suite Metadata` keyword. | | | | New in Robot Framework 2.7.4. | | +------------------------+-------------------------------------------------------+------------+ | ${SUITE STATUS} | The status of the current test suite, either PASS or | `Suite | | | FAIL. | teardown`_ | +------------------------+-------------------------------------------------------+------------+ | ${SUITE MESSAGE} | The full message of the current test suite, including | `Suite | | | statistics. | teardown`_ | +------------------------+-------------------------------------------------------+------------+ | ${KEYWORD STATUS} | The status of the current keyword, either PASS or | `User | | | FAIL. New in Robot Framework 2.7 | keyword | | | | teardown`_ | +------------------------+-------------------------------------------------------+------------+ | ${KEYWORD MESSAGE} | The possible error message of the current keyword. | `User | | | New in Robot Framework 2.7. | keyword | | | | teardown`_ | +------------------------+-------------------------------------------------------+------------+ | ${LOG LEVEL} | Current `log level`_. New in Robot Framework 2.8. | Everywhere | +------------------------+-------------------------------------------------------+------------+ | ${OUTPUT FILE} | An absolute path to the `output file`_. | Everywhere | +------------------------+-------------------------------------------------------+------------+ | ${LOG FILE} | An absolute path to the `log file`_ or string NONE | Everywhere | | | when no log file is created. | | +------------------------+-------------------------------------------------------+------------+ | ${REPORT FILE} | An absolute path to the `report file`_ or string NONE | Everywhere | | | when no report is created. | | +------------------------+-------------------------------------------------------+------------+ | ${DEBUG FILE} | An absolute path to the `debug file`_ or string NONE | Everywhere | | | when no debug file is created. | | +------------------------+-------------------------------------------------------+------------+ | ${OUTPUT DIR} | An absolute path to the `output directory`_. | Everywhere | +------------------------+-------------------------------------------------------+------------+ Suite related variables `${SUITE SOURCE}`, `${SUITE NAME}`, `${SUITE DOCUMENTATION}` and `&{SUITE METADATA}` are available already when test libraries and variable files are imported, except to Robot Framework 2.8 and 2.8.1 where this support was broken. Possible variables in these automatic variables are not yet resolved at the import time, though. Variable priorities and scopes ------------------------------ Variables coming from different sources have different priorities and are available in different scopes. Variable priorities ~~~~~~~~~~~~~~~~~~~ *Variables from the command line* Variables `set in the command line`__ have the highest priority of all variables that can be set before the actual test execution starts. They override possible variables created in Variable tables in test case files, as well as in resource and variable files imported in the test data. Individually set variables (:option:`--variable` option) override the variables set using `variable files`_ (:option:`--variablefile` option). If you specify same individual variable multiple times, the one specified last will override earlier ones. This allows setting default values for variables in a `start-up script`_ and overriding them from the command line. Notice, though, that if multiple variable files have same variables, the ones in the file specified first have the highest priority. __ `Setting variables in command line`_ *Variable table in a test case file* Variables created using the `Variable table`_ in a test case file are available for all the test cases in that file. These variables override possible variables with same names in imported resource and variable files. Variables created in the variable tables are available in all other tables in the file where they are created. This means that they can be used also in the Setting table, for example, for importing more variables from resource and variable files. *Imported resource and variable files* Variables imported from the `resource and variable files`_ have the lowest priority of all variables created in the test data. Variables from resource files and variable files have the same priority. If several resource and/or variable file have same variables, the ones in the file imported first are taken into use. If a resource file imports resource files or variable files, variables in its own Variable table have a higher priority than variables it imports. All these variables are available for files that import this resource file. Note that variables imported from resource and variable files are not available in the Variable table of the file that imports them. This is due to the Variable table being processed before the Setting table where the resource files and variable files are imported. *Variables set during test execution* Variables set during the test execution either using `return values from keywords`_ or `using Set Test/Suite/Global Variable keywords`_ always override possible existing variables in the scope where they are set. In a sense they thus have the highest priority, but on the other hand they do not affect variables outside the scope they are defined. *Built-in variables* `Built-in variables`_ like `${TEMPDIR}` and `${TEST_NAME}` have the highest priority of all variables. They cannot be overridden using Variable table or from command line, but even they can be reset during the test execution. An exception to this rule are `number variables`_, which are resolved dynamically if no variable is found otherwise. They can thus be overridden, but that is generally a bad idea. Additionally `${CURDIR}` is special because it is replaced already during the test data processing time. Variable scopes ~~~~~~~~~~~~~~~ Depending on where and how they are created, variables can have a global, test suite, test case or local scope. Global scope '''''''''''' Global variables are available everywhere in the test data. These variables are normally `set from the command line`__ with the :option:`--variable` and :option:`--variablefile` options, but it is also possible to create new global variables or change the existing ones with the BuiltIn_ keyword :name:`Set Global Variable` anywhere in the test data. Additionally also `built-in variables`_ are global. It is recommended to use capital letters with all global variables. Test suite scope '''''''''''''''' Variables with the test suite scope are available anywhere in the test suite where they are defined or imported. They can be created in Variable tables, imported from `resource and variable files`_, or set during the test execution using the BuiltIn_ keyword :name:`Set Suite Variable`. The test suite scope *is not recursive*, which means that variables available in a higher-level test suite *are not available* in lower-level suites. If necessary, `resource and variable files`_ can be used for sharing variables. Since these variables can be considered global in the test suite where they are used, it is recommended to use capital letters also with them. Test case scope ''''''''''''''' Variables with the test case scope are visible in a test case and in all user keywords the test uses. Initially there are no variables in this scope, but it is possible to create them by using the BuiltIn_ keyword :name:`Set Test Variable` anywhere in a test case. Also variables in the test case scope are to some extend global. It is thus generally recommended to use capital letters with them too. Local scope ''''''''''' Test cases and user keywords have a local variable scope that is not seen by other tests or keywords. Local variables can be created using `return values`__ from executed keywords and user keywords also get them as arguments__. It is recommended to use lower-case letters with local variables. .. note:: Prior to Robot Framework 2.9 variables in the local scope `leaked to lower level user keywords`__. This was never an intended feature, and variables should be set or passed explicitly also with earlier versions. __ `Setting variables in command line`_ __ `Return values from keywords`_ __ `User keyword arguments`_ __ https://github.com/robotframework/robotframework/issues/532 Advanced variable features -------------------------- Extended variable syntax ~~~~~~~~~~~~~~~~~~~~~~~~ Extended variable syntax allows accessing attributes of an object assigned to a variable (for example, `${object.attribute}`) and even calling its methods (for example, `${obj.getName()}`). It works both with scalar and list variables, but is mainly useful with the former Extended variable syntax is a powerful feature, but it should be used with care. Accessing attributes is normally not a problem, on the contrary, because one variable containing an object with several attributes is often better than having several variables. On the other hand, calling methods, especially when they are used with arguments, can make the test data pretty complicated to understand. If that happens, it is recommended to move the code into a test library. The most common usages of extended variable syntax are illustrated in the example below. First assume that we have the following `variable file`_ and test case: .. sourcecode:: python class MyObject: def __init__(self, name): self.name = name def eat(self, what): return '%s eats %s' % (self.name, what) def __str__(self): return self.name OBJECT = MyObject('Robot') DICTIONARY = {1: 'one', 2: 'two', 3: 'three'} .. sourcecode:: robotframework *** Test Cases *** Example KW 1 ${OBJECT.name} KW 2 ${OBJECT.eat('Cucumber')} KW 3 ${DICTIONARY[2]} When this test data is executed, the keywords get the arguments as explained below: - :name:`KW 1` gets string `Robot` - :name:`KW 2` gets string `Robot eats Cucumber` - :name:`KW 3` gets string `two` The extended variable syntax is evaluated in the following order: 1. The variable is searched using the full variable name. The extended variable syntax is evaluated only if no matching variable is found. 2. The name of the base variable is created. The body of the name consists of all the characters after the opening `{` until the first occurrence of a character that is not an alphanumeric character or a space. For example, base variables of `${OBJECT.name}` and `${DICTIONARY[2]}`) are `OBJECT` and `DICTIONARY`, respectively. 3. A variable matching the body is searched. If there is no match, an exception is raised and the test case fails. 4. The expression inside the curly brackets is evaluated as a Python expression, so that the base variable name is replaced with its value. If the evaluation fails because of an invalid syntax or that the queried attribute does not exist, an exception is raised and the test fails. 5. The whole extended variable is replaced with the value returned from the evaluation. If the object that is used is implemented with Java, the extended variable syntax allows you to access attributes using so-called bean properties. In essence, this means that if you have an object with the `getName` method set into a variable `${OBJ}`, then the syntax `${OBJ.name}` is equivalent to but clearer than `${OBJ.getName()}`. The Python object used in the previous example could thus be replaced with the following Java implementation: .. sourcecode:: java public class MyObject: private String name; public MyObject(String name) { name = name; } public String getName() { return name; } public String eat(String what) { return name + " eats " + what; } public String toString() { return name; } } Many standard Python objects, including strings and numbers, have methods that can be used with the extended variable syntax either explicitly or implicitly. Sometimes this can be really useful and reduce the need for setting temporary variables, but it is also easy to overuse it and create really cryptic test data. Following examples show few pretty good usages. .. sourcecode:: robotframework *** Test Cases *** String ${string} = Set Variable abc Log ${string.upper()} # Logs 'ABC' Log ${string * 2} # Logs 'abcabc' Number ${number} = Set Variable ${-2} Log ${number * 10} # Logs -20 Log ${number.__abs__()} # Logs 2 Note that even though `abs(number)` is recommended over `number.__abs__()` in normal Python code, using `${abs(number)}` does not work. This is because the variable name must be in the beginning of the extended syntax. Using `__xxx__` methods in the test data like this is already a bit questionable, and it is normally better to move this kind of logic into test libraries. Extended variable syntax works also in `list variable`_ context. If, for example, an object assigned to a variable `${EXTENDED}` has an attribute `attribute` that contains a list as a value, it can be used as a list variable `@{EXTENDED.attribute}`. Extended variable assignment ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Starting from Robot Framework 2.7, it is possible to set attributes of objects stored to scalar variables using `keyword return values`__ and a variation of the `extended variable syntax`_. Assuming we have variable `${OBJECT}` from the previous examples, attributes could be set to it like in the example below. __ `Return values from keywords`_ .. sourcecode:: robotframework *** Test Cases *** Example ${OBJECT.name} = Set Variable New name ${OBJECT.new_attr} = Set Variable New attribute The extended variable assignment syntax is evaluated using the following rules: 1. The assigned variable must be a scalar variable and have at least one dot. Otherwise the extended assignment syntax is not used and the variable is assigned normally. 2. If there exists a variable with the full name (e.g. `${OBJECT.name}` in the example above) that variable will be assigned a new value and the extended syntax is not used. 3. The name of the base variable is created. The body of the name consists of all the characters between the opening `${` and the last dot, for example, `OBJECT` in `${OBJECT.name}` and `foo.bar` in `${foo.bar.zap}`. As the second example illustrates, the base name may contain normal extended variable syntax. 4. The name of the attribute to set is created by taking all the characters between the last dot and the closing `}`, for example, `name` in `${OBJECT.name}`. If the name does not start with a letter or underscore and contain only these characters and numbers, the attribute is considered invalid and the extended syntax is not used. A new variable with the full name is created instead. 5. A variable matching the base name is searched. If no variable is found, the extended syntax is not used and, instead, a new variable is created using the full variable name. 6. If the found variable is a string or a number, the extended syntax is ignored and a new variable created using the full name. This is done because you cannot add new attributes to Python strings or numbers, and this way the new syntax is also less backwards-incompatible. 7. If all the previous rules match, the attribute is set to the base variable. If setting fails for any reason, an exception is raised and the test fails. .. note:: Unlike when assigning variables normally using `return values from keywords`_, changes to variables done using the extended assign syntax are not limited to the current scope. Because no new variable is created but instead the state of an existing variable is changed, all tests and keywords that see that variable will also see the changes. Variables inside variables ~~~~~~~~~~~~~~~~~~~~~~~~~~ Variables are allowed also inside variables, and when this syntax is used, variables are resolved from the inside out. For example, if you have a variable `${var${x}}`, then `${x}` is resolved first. If it has the value `name`, the final value is then the value of the variable `${varname}`. There can be several nested variables, but resolving the outermost fails, if any of them does not exist. In the example below, :name:`Do X` gets the value `${JOHN HOME}` or `${JANE HOME}`, depending on if :name:`Get Name` returns `john` or `jane`. If it returns something else, resolving `${${name} HOME}` fails. .. sourcecode:: robotframework *** Variables *** ${JOHN HOME} /home/john ${JANE HOME} /home/jane *** Test Cases *** Example ${name} = Get Name Do X ${${name} HOME}
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/CreatingTestData/Variables.rst
0.934932
0.661099
Variables.rst
pypi
Creating test cases =================== This section describes the overall test case syntax. Organizing test cases into `test suites`_ using `test case files`_ and `test suite directories`_ is discussed in the next section. .. contents:: :depth: 2 :local: Test case syntax ---------------- Basic syntax ~~~~~~~~~~~~ Test cases are constructed in test case tables from the available keywords. Keywords can be imported from `test libraries`_ or `resource files`_, or created in the `keyword table`_ of the test case file itself. .. _keyword table: `user keywords`_ The first column in the test case table contains test case names. A test case starts from the row with something in this column and continues to the next test case name or to the end of the table. It is an error to have something between the table headers and the first test. The second column normally has keyword names. An exception to this rule is `setting variables from keyword return values`_, when the second and possibly also the subsequent columns contain variable names and a keyword name is located after them. In either case, columns after the keyword name contain possible arguments to the specified keyword. .. _setting variables from keyword return values: `User keyword return values`_ .. _example-tests: .. sourcecode:: robotframework *** Test Cases *** Valid Login Open Login Page Input Username demo Input Password mode Submit Credentials Welcome Page Should Be Open Setting Variables Do Something first argument second argument ${value} = Get Some Value Should Be Equal ${value} Expected value Settings in the Test Case table ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test cases can also have their own settings. Setting names are always in the second column, where keywords normally are, and their values are in the subsequent columns. Setting names have square brackets around them to distinguish them from keywords. The available settings are listed below and explained later in this section. `[Documentation]`:setting: Used for specifying a `test case documentation`_. `[Tags]`:setting: Used for `tagging test cases`_. `[Setup]`:setting:, `[Teardown]`:setting: Specify `test setup and teardown`_. Have also synonyms :setting:`[Precondition]` and :setting:`[Postcondition]`, respectively. `[Template]`:setting: Specifies the `template keyword`_ to use. The test itself will contain only data to use as arguments to that keyword. `[Timeout]`:setting: Used for setting a `test case timeout`_. Timeouts_ are discussed in their own section. Example test case with settings: .. sourcecode:: robotframework *** Test Cases *** Test With Settings [Documentation] Another dummy test [Tags] dummy owner-johndoe Log Hello, world! Test case related settings in the Setting table ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Setting table can have the following test case related settings. These settings are mainly default values for the test case specific settings listed earlier. `Force Tags`:setting:, `Default Tags`:setting: The forced and default values for tags_. `Test Setup`:setting:, `Test Teardown`:setting: The default values for `test setup and teardown`_. Have also synonyms :setting:`Test Precondition` and :setting:`Test Postcondition`, respectively. `Test Template`:setting: The default `template keyword`_ to use. `Test Timeout`:setting: The default value for `test case timeout`_. Timeouts_ are discussed in their own section. Using arguments --------------- The earlier examples have already demonstrated keywords taking different arguments, and this section discusses this important functionality more thoroughly. How to actually implement `user keywords`__ and `library keywords`__ with different arguments is discussed in separate sections. Keywords can accept zero or more arguments, and some arguments may have default values. What arguments a keyword accepts depends on its implementation, and typically the best place to search this information is keyword's documentation. In the examples in this section the documentation is expected to be generated using the Libdoc_ tool, but the same information is available on documentation generated by generic documentation tools such as ``javadoc``. __ `User keyword arguments`_ __ `Keyword arguments`_ Mandatory arguments ~~~~~~~~~~~~~~~~~~~ Most keywords have a certain number of arguments that must always be given. In the keyword documentation this is denoted by specifying the argument names separated with a comma like `first, second, third`. The argument names actually do not matter in this case, except that they should explain what the argument does, but it is important to have exactly the same number of arguments as specified in the documentation. Using too few or too many arguments will result in an error. The test below uses keywords :name:`Create Directory` and :name:`Copy File` from the OperatingSystem_ library. Their arguments are specified as `path` and `source, destination`, which means that they take one and two arguments, respectively. The last keyword, :name:`No Operation` from BuiltIn_, takes no arguments. .. sourcecode:: robotframework *** Test Cases *** Example Create Directory ${TEMPDIR}/stuff Copy File ${CURDIR}/file.txt ${TEMPDIR}/stuff No Operation Default values ~~~~~~~~~~~~~~ Arguments often have default values which can either be given or not. In the documentation the default value is typically separated from the argument name with an equal sign like `name=default value`, but with keywords implemented using Java there may be `multiple implementations`__ of the same keyword with different arguments instead. It is possible that all the arguments have default values, but there cannot be any positional arguments after arguments with default values. __ `Default values with Java`_ Using default values is illustrated by the example below that uses :name:`Create File` keyword which has arguments `path, content=, encoding=UTF-8`. Trying to use it without any arguments or more than three arguments would not work. .. sourcecode:: robotframework *** Test Cases *** Example Create File ${TEMPDIR}/empty.txt Create File ${TEMPDIR}/utf-8.txt Hyvä esimerkki Create File ${TEMPDIR}/iso-8859-1.txt Hyvä esimerkki ISO-8859-1 .. _varargs: Variable number of arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is also possible that a keyword accepts any number of arguments. These so called *varargs* can be combined with mandatory arguments and arguments with default values, but they are always given after them. In the documentation they have an asterisk before the argument name like `*varargs`. For example, :name:`Remove Files` and :name:`Join Paths` keywords from the OperatingSystem_ library have arguments `*paths` and `base, *parts`, respectively. The former can be used with any number of arguments, but the latter requires at least one argument. .. sourcecode:: robotframework *** Test Cases *** Example Remove Files ${TEMPDIR}/f1.txt ${TEMPDIR}/f2.txt ${TEMPDIR}/f3.txt @{paths} = Join Paths ${TEMPDIR} f1.txt f2.txt f3.txt f4.txt .. _Named argument syntax: Named arguments ~~~~~~~~~~~~~~~ The named argument syntax makes using arguments with `default values`_ more flexible, and allows explicitly labeling what a certain argument value means. Technically named arguments work exactly like `keyword arguments`__ in Python. __ http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments Basic syntax '''''''''''' It is possible to name an argument given to a keyword by prefixing the value with the name of the argument like `arg=value`. This is especially useful when multiple arguments have default values, as it is possible to name only some the arguments and let others use their defaults. For example, if a keyword accepts arguments `arg1=a, arg2=b, arg3=c`, and it is called with one argument `arg3=override`, arguments `arg1` and `arg2` get their default values, but `arg3` gets value `override`. If this sounds complicated, the `named arguments example`_ below hopefully makes it more clear. The named argument syntax is both case and space sensitive. The former means that if you have an argument `arg`, you must use it like `arg=value`, and neither `Arg=value` nor `ARG=value` works. The latter means that spaces are not allowed before the `=` sign, and possible spaces after it are considered part of the given value. When the named argument syntax is used with `user keywords`_, the argument names must be given without the `${}` decoration. For example, user keyword with arguments `${arg1}=first, ${arg2}=second` must be used like `arg2=override`. Using normal positional arguments after named arguments like, for example, `| Keyword | arg=value | positional |`, does not work. Starting from Robot Framework 2.8 this causes an explicit error. The relative order of the named arguments does not matter. .. note:: Prior to Robot Framework 2.8 it was not possible to name arguments that did not have a default value. Named arguments with variables '''''''''''''''''''''''''''''' It is possible to use `variables`_ in both named argument names and values. If the value is a single `scalar variable`_, it is passed to the keyword as-is. This allows using any objects, not only strings, as values also when using the named argument syntax. For example, calling a keyword like `arg=${object}` will pass the variable `${object}` to the keyword without converting it to a string. If variables are used in named argument names, variables are resolved before matching them against argument names. This is a new feature in Robot Framework 2.8.6. The named argument syntax requires the equal sign to be written literally in the keyword call. This means that variable alone can never trigger the named argument syntax, not even if it has a value like `foo=bar`. This is important to remember especially when wrapping keywords into other keywords. If, for example, a keyword takes a `variable number of arguments`_ like `@{args}` and passes all of them to another keyword using the same `@{args}` syntax, possible `named=arg` syntax used in the calling side is not recognized. This is illustrated by the example below. .. sourcecode:: robotframework *** Test Cases *** Example Run Program shell=True # This will not come as a named argument to Run Process *** Keywords *** Run Program [Arguments] @{args} Run Process program.py @{args} # Named arguments are not recognized from inside @{args} If keyword needs to accept and pass forward any named arguments, it must be changed to accept `free keyword arguments`_. See `kwargs examples`_ for a wrapper keyword version that can pass both positional and named arguments forward. Escaping named arguments syntax ''''''''''''''''''''''''''''''' The named argument syntax is used only when the part of the argument before the equal sign matches one of the keyword's arguments. It is possible that there is a positional argument with a literal value like `foo=quux`, and also an unrelated argument with name `foo`. In this case the argument `foo` either incorrectly gets the value `quux` or, more likely, there is a syntax error. In these rare cases where there are accidental matches, it is possible to use the backslash character to escape__ the syntax like `foo\=quux`. Now the argument will get a literal value `foo=quux`. Note that escaping is not needed if there are no arguments with name `foo`, but because it makes the situation more explicit, it may nevertheless be a good idea. __ Escaping_ Where named arguments are supported ''''''''''''''''''''''''''''''''''' As already explained, the named argument syntax works with keywords. In addition to that, it also works when `importing libraries`_. Naming arguments is supported by `user keywords`_ and by most `test libraries`_. The only exception are Java based libraries that use the `static library API`_. Library documentation generated with Libdoc_ has a note does the library support named arguments or not. .. note:: Prior to Robot Framework 2.8 named argument syntax did not work with test libraries using the `dynamic library API`_. Named arguments example ''''''''''''''''''''''' The following example demonstrates using the named arguments syntax with library keywords, user keywords, and when importing the Telnet_ test library. .. sourcecode:: robotframework *** Settings *** Library Telnet prompt=$ default_log_level=DEBUG *** Test Cases *** Example Open connection 10.0.0.42 port=${PORT} alias=example List files options=-lh List files path=/tmp options=-l *** Keywords *** List files [Arguments] ${path}=. ${options}= List files options=-lh Execute command ls ${options} ${path} Free keyword arguments ~~~~~~~~~~~~~~~~~~~~~~ Robot Framework 2.8 added support for `Python style free keyword arguments`__ (`**kwargs`). What this means is that keywords can receive all arguments that use the `name=value` syntax and do not match any other arguments as kwargs. Free keyword arguments support variables similarly as `named arguments <Named arguments with variables_>`__. In practice that means that variables can be used both in names and values, but the escape sign must always be visible literally. For example, both `foo=${bar}` and `${foo}=${bar}` are valid, as long as the variables that are used exist. An extra limitation is that free keyword argument names must always be strings. Support for variables in names is a new feature in Robot Framework 2.8.6, prior to that possible variables were left un-resolved. Initially free keyword arguments only worked with Python based libraries, but Robot Framework 2.8.2 extended the support to the `dynamic library API`_ and Robot Framework 2.8.3 extended it further to Java based libraries and to the `remote library interface`_. Finally, user keywords got `kwargs support <Kwargs with user keywords_>`__ in Robot Framework 2.9. In other words, all keywords can nowadays support kwargs. __ http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments Kwargs examples ''''''''''''''' As the first example of using kwargs, let's take a look at :name:`Run Process` keyword in the Process_ library. It has a signature `command, *arguments, **configuration`, which means that it takes the command to execute (`command`), its arguments as `variable number of arguments`_ (`*arguments`) and finally optional configuration parameters as free keyword arguments (`**configuration`). The example below also shows that variables work with free keyword arguments exactly like when `using the named argument syntax`__. .. sourcecode:: robotframework *** Test Cases *** Using Kwargs Run Process program.py arg1 arg2 cwd=/home/user Run Process program.py argument shell=True env=${ENVIRON} See `Free keyword arguments (**kwargs)`_ section under `Creating test libraries`_ for more information about using the kwargs syntax in your custom test libraries. As the second example, let's create a wrapper `user keyword`_ for running the `program.py` in the above example. The wrapper keyword :name:`Run Program` accepts any number of arguments and kwargs, and passes them forward for :name:`Run Process` along with the name of the command to execute. .. sourcecode:: robotframework *** Test Cases *** Using Kwargs Run Program arg1 arg2 cwd=/home/user Run Program argument shell=True env=${ENVIRON} *** Keywords *** Run Program [Arguments] @{arguments} &{configuration} Run Process program.py @{arguments} &{configuration} __ `Named arguments with variables`_ Arguments embedded to keyword names ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A totally different approach to specify arguments is embedding them into keyword names. This syntax is supported by both `test library keywords`__ and `user keywords`__. __ `Embedding arguments into keyword names`_ __ `Embedding arguments into keyword name`_ Failures -------- When test case fails ~~~~~~~~~~~~~~~~~~~~ A test case fails if any of the keyword it uses fails. Normally this means that execution of that test case is stopped, possible `test teardown`_ is executed, and then execution continues from the next test case. It is also possible to use special `continuable failures`__ if stopping test execution is not desired. Error messages ~~~~~~~~~~~~~~ The error message assigned to a failed test case is got directly from the failed keyword. Often the error message is created by the keyword itself, but some keywords allow configuring them. In some circumstances, for example when continuable failures are used, a test case can fail multiple times. In that case the final error message is got by combining the individual errors. Very long error messages are automatically cut from the middle to keep reports_ easier to read. Full error messages are always visible in log_ file as a message of the failed keyword. By default error messages are normal text, but starting from Robot Framework 2.8 they can `contain HTML formatting`__. This is enabled by starting the error message with marker string `*HTML*`. This marker will be removed from the final error message shown in reports and logs. Using HTML in a custom message is shown in the second example below. .. sourcecode:: robotframework *** Test Cases *** Normal Error Fail This is a rather boring example... HTML Error ${number} = Get Number Should Be Equal ${number} 42 *HTML* Number is not my <b>MAGIC</b> number. __ `Continue on failure`_ __ `HTML in error messages`_ Test case name and documentation -------------------------------- The test case name comes directly from the Test Case table: it is exactly what is entered into the test case column. Test cases in one test suite should have unique names. Pertaining to this, you can also use the `automatic variable`_ `${TEST_NAME}` within the test itself to refer to the test name. It is available whenever a test is being executed, including all user keywords, as well as the test setup and the test teardown. The :setting:`[Documentation]` setting allows you to set a free documentation for a test case. That text is shown in the command line output, as well as the resulting test logs and test reports. It is possible to use simple `HTML formatting`_ in documentation and variables_ can be used to make the documentation dynamic. If documentation is split into multiple columns, cells in one row are concatenated together with spaces. This is mainly be useful when using the `HTML format`_ and columns are narrow. If documentation is `split into multiple rows`__, the created documentation lines themselves are `concatenated using newlines`__. Newlines are not added if a line already ends with a newline or an `escaping backslash`__. __ `Dividing test data to several rows`_ __ `Newlines in test data`_ __ `Escaping`_ .. sourcecode:: robotframework *** Test Cases *** Simple [Documentation] Simple documentation No Operation Formatting [Documentation] *This is bold*, _this is italic_ and here is a link: http://robotframework.org No Operation Variables [Documentation] Executed at ${HOST} by ${USER} No Operation Splitting [Documentation] This documentation is split into multiple columns No Operation Many lines [Documentation] Here we have ... an automatic newline No Operation It is important that test cases have clear and descriptive names, and in that case they normally do not need any documentation. If the logic of the test case needs documenting, it is often a sign that keywords in the test case need better names and they are to be enhanced, instead of adding extra documentation. Finally, metadata, such as the environment and user information in the last example above, is often better specified using tags_. .. _test case tags: Tagging test cases ------------------ Using tags in Robot Framework is a simple, yet powerful mechanism for classifying test cases. Tags are free text and they can be used at least for the following purposes: - Tags are shown in test reports_, logs_ and, of course, in the test data, so they provide metadata to test cases. - Statistics__ about test cases (total, passed, failed are automatically collected based on tags). - With tags, you can `include or exclude`__ test cases to be executed. - With tags, you can specify which test cases are considered `critical`_. __ `Configuring statistics`_ __ `By tag names`_ In this section it is only explained how to set tags for test cases, and different ways to do it are listed below. These approaches can naturally be used together. `Force Tags`:setting: in the Setting table All test cases in a test case file with this setting always get specified tags. If it is used in the `test suite initialization file`, all test cases in sub test suites get these tags. `Default Tags`:setting: in the Setting table Test cases that do not have a :setting:`[Tags]` setting of their own get these tags. Default tags are not supported in test suite initialization files. `[Tags]`:setting: in the Test Case table A test case always gets these tags. Additionally, it does not get the possible tags specified with :setting:`Default Tags`, so it is possible to override the :setting:`Default Tags` by using empty value. It is also possible to use value `NONE` to override default tags. `--settag`:option: command line option All executed test cases get tags set with this option in addition to tags they got elsewhere. `Set Tags`:name:, `Remove Tags`:name:, `Fail`:name: and `Pass Execution`:name: keywords These BuiltIn_ keywords can be used to manipulate tags dynamically during the test execution. Tags are free text, but they are normalized so that they are converted to lowercase and all spaces are removed. If a test case gets the same tag several times, other occurrences than the first one are removed. Tags can be created using variables, assuming that those variables exist. .. sourcecode:: robotframework *** Settings *** Force Tags req-42 Default Tags owner-john smoke *** Variables *** ${HOST} 10.0.1.42 *** Test Cases *** No own tags [Documentation] This test has tags owner-john, smoke and req-42. No Operation With own tags [Documentation] This test has tags not_ready, owner-mrx and req-42. [Tags] owner-mrx not_ready No Operation Own tags with variables [Documentation] This test has tags host-10.0.1.42 and req-42. [Tags] host-${HOST} No Operation Empty own tags [Documentation] This test has only tag req-42. [Tags] No Operation Set Tags and Remove Tags Keywords [Documentation] This test has tags mytag and owner-john. Set Tags mytag Remove Tags smoke req-* Reserved tags ~~~~~~~~~~~~~ Users are generally free to use whatever tags that work in their context. There are, however, certain tags that have a predefined meaning for Robot Framework itself, and using them for other purposes can have unexpected results. All special tags Robot Framework has and will have in the future have a `robot-` prefix. To avoid problems, users should thus not use any tag with a `robot-` prefix unless actually activating the special functionality. At the time of writing, the only special tag is `robot-exit` that is automatically added to tests when `stopping test execution gracefully`_. More usages are likely to be added in the future, though. Test setup and teardown ----------------------- Robot Framework has similar test setup and teardown functionality as many other test automation frameworks. In short, a test setup is something that is executed before a test case, and a test teardown is executed after a test case. In Robot Framework setups and teardowns are just normal keywords with possible arguments. Setup and teardown are always a single keyword. If they need to take care of multiple separate tasks, it is possible to create higher-level `user keywords`_ for that purpose. An alternative solution is executing multiple keywords using the BuiltIn_ keyword :name:`Run Keywords`. The test teardown is special in two ways. First of all, it is executed also when a test case fails, so it can be used for clean-up activities that must be done regardless of the test case status. In addition, all the keywords in the teardown are also executed even if one of them fails. This `continue on failure`_ functionality can be used also with normal keywords, but inside teardowns it is on by default. The easiest way to specify a setup or a teardown for test cases in a test case file is using the :setting:`Test Setup` and :setting:`Test Teardown` settings in the Setting table. Individual test cases can also have their own setup or teardown. They are defined with the :setting:`[Setup]` or :setting:`[Teardown]` settings in the test case table and they override possible :setting:`Test Setup` and :setting:`Test Teardown` settings. Having no keyword after a :setting:`[Setup]` or :setting:`[Teardown]` setting means having no setup or teardown. It is also possible to use value `NONE` to indicate that a test has no setup/teardown. .. sourcecode:: robotframework *** Settings *** Test Setup Open Application App A Test Teardown Close Application *** Test Cases *** Default values [Documentation] Setup and teardown from setting table Do Something Overridden setup [Documentation] Own setup, teardown from setting table [Setup] Open Application App B Do Something No teardown [Documentation] Default setup, no teardown at all Do Something [Teardown] No teardown 2 [Documentation] Setup and teardown can be disabled also with special value NONE Do Something [Teardown] NONE Using variables [Documentation] Setup and teardown specified using variables [Setup] ${SETUP} Do Something [Teardown] ${TEARDOWN} Often when creating use-case-like test cases, the terms *precondition* and *postcondition* are preferred over the terms setup and teardown. Robot Framework supports also this terminology, so that a precondition is a synonym to a setup and a postcondition to a teardown. .. table:: Setup and teardown synonyms :class: tabular ================= =================== Test Setup Test Precondition Test Teardown Test Postcondition [Setup] [Precondition] [Teardown] [Postcondition] ================= =================== The name of the keyword to be executed as a setup or a teardown can be a variable. This facilitates having different setups or teardowns in different environments by giving the keyword name as a variable from the command line. .. note:: `Test suites can have a setup and teardown of their own`__. A suite setup is executed before any test cases or sub test suites in that test suite, and similarly a suite teardown is executed after them. __ `Suite setup and teardown`_ Test templates -------------- Test templates convert normal `keyword-driven`_ test cases into `data-driven`_ tests. Whereas the body of a keyword-driven test case is constructed from keywords and their possible arguments, test cases with template contain only the arguments for the template keyword. Instead of repeating the same keyword multiple times per test and/or with all tests in a file, it is possible to use it only per test or just once per file. Template keywords can accept both normal positional and named arguments, as well as arguments embedded to the keyword name. Unlike with other settings, it is not possible to define a template using a variable. Basic usage ~~~~~~~~~~~ How a keyword accepting normal positional arguments can be used as a template is illustrated by the following example test cases. These two tests are functionally fully identical. .. sourcecode:: robotframework *** Test Cases ** Normal test case Example keyword first argument second argument Templated test case [Template] Example keyword first argument second argument As the example illustrates, it is possible to specify the template for an individual test case using the :setting:`[Template]` setting. An alternative approach is using the :setting:`Test Template` setting in the Setting table, in which case the template is applied for all test cases in that test case file. The :setting:`[Template]` setting overrides the possible template set in the Setting table, and an empty value for :setting:`[Template]` means that the test has no template even when :setting:`Test Template` is used. It is also possible to use value `NONE` to indicate that a test has no template. If a templated test case has multiple data rows in its body, the template is applied for all the rows one by one. This means that the same keyword is executed multiple times, once with data on each row. Templated tests are also special so that all the rounds are executed even if one or more of them fails. It is possible to use this kind of `continue on failure`_ mode with normal tests too, but with the templated tests the mode is on automatically. .. sourcecode:: robotframework *** Settings *** Test Template Example keyword *** Test Cases *** Templated test case first round 1 first round 2 second round 1 second round 2 third round 1 third round 2 Using arguments with `default values`_ or `varargs`_, as well as using `named arguments`_ and `free keyword arguments`_, work with templates exactly like they work otherwise. Using variables_ in arguments is also supported normally. Templates with embedded arguments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Starting from Robot Framework 2.8.2, templates support a variation of the `embedded argument syntax`_. With templates this syntax works so that if the template keyword has variables in its name, they are considered placeholders for arguments and replaced with the actual arguments used with the template. The resulting keyword is then used without positional arguments. This is best illustrated with an example: .. sourcecode:: robotframework *** Test Cases *** Normal test case with embedded arguments The result of 1 + 1 should be 2 The result of 1 + 2 should be 3 Template with embedded arguments [Template] The result of ${calculation} should be ${expected} 1 + 1 2 1 + 2 3 *** Keywords *** The result of ${calculation} should be ${expected} ${result} = Calculate ${calculation} Should Be Equal ${result} ${expected} When embedded arguments are used with templates, the number of arguments in the template keyword name must match the number of arguments it is used with. The argument names do not need to match the arguments of the original keyword, though, and it is also possible to use different arguments altogether: .. sourcecode:: robotframework *** Test Cases *** Different argument names [Template] The result of ${foo} should be ${bar} 1 + 1 2 1 + 2 3 Only some arguments [Template] The result of ${calculation} should be 3 1 + 2 4 - 1 New arguments [Template] The ${meaning} of ${life} should be 42 result 21 * 2 The main benefit of using embedded arguments with templates is that argument names are specified explicitly. When using normal arguments, the same effect can be achieved by naming the columns that contain arguments. This is illustrated by the `data-driven style`_ example in the next section. Templates with for loops ~~~~~~~~~~~~~~~~~~~~~~~~ If templates are used with `for loops`_, the template is applied for all the steps inside the loop. The continue on failure mode is in use also in this case, which means that all the steps are executed with all the looped elements even if there are failures. .. sourcecode:: robotframework *** Test Cases *** Template and for [Template] Example keyword :FOR ${item} IN @{ITEMS} \ ${item} 2nd arg :FOR ${index} IN RANGE 42 \ 1st arg ${index} Different test case styles -------------------------- There are several different ways in which test cases may be written. Test cases that describe some kind of *workflow* may be written either in keyword-driven or behavior-driven style. Data-driven style can be used to test the same workflow with varying input data. Keyword-driven style ~~~~~~~~~~~~~~~~~~~~ Workflow tests, such as the :name:`Valid Login` test described earlier_, are constructed from several keywords and their possible arguments. Their normal structure is that first the system is taken into the initial state (:name:`Open Login Page` in the :name:`Valid Login` example), then something is done to the system (:name:`Input Name`, :name:`Input Password`, :name:`Submit Credentials`), and finally it is verified that the system behaved as expected (:name:`Welcome Page Should Be Open`). .. _earlier: example-tests_ Data-driven style ~~~~~~~~~~~~~~~~~ Another style to write test cases is the *data-driven* approach where test cases use only one higher-level keyword, normally created as a `user keyword`_, that hides the actual test workflow. These tests are very useful when there is a need to test the same scenario with different input and/or output data. It would be possible to repeat the same keyword with every test, but the `test template`_ functionality allows specifying the keyword to use only once. .. sourcecode:: robotframework *** Settings *** Test Template Login with invalid credentials should fail *** Test Cases *** USERNAME PASSWORD Invalid User Name invalid ${VALID PASSWORD} Invalid Password ${VALID USER} invalid Invalid User Name and Password invalid invalid Empty User Name ${EMPTY} ${VALID PASSWORD} Empty Password ${VALID USER} ${EMPTY} Empty User Name and Password ${EMPTY} ${EMPTY} .. tip:: Naming columns like in the example above makes tests easier to understand. This is possible because on the header row other cells except the first one `are ignored`__. The above example has six separate tests, one for each invalid user/password combination, and the example below illustrates how to have only one test with all the combinations. When using `test templates`_, all the rounds in a test are executed even if there are failures, so there is no real functional difference between these two styles. In the above example separate combinations are named so it is easier to see what they test, but having potentially large number of these tests may mess-up statistics. Which style to use depends on the context and personal preferences. .. sourcecode:: robotframework *** Test Cases *** Invalid Password [Template] Login with invalid credentials should fail invalid ${VALID PASSWORD} ${VALID USER} invalid invalid whatever ${EMPTY} ${VALID PASSWORD} ${VALID USER} ${EMPTY} ${EMPTY} ${EMPTY} __ `Ignored data`_ Behavior-driven style ~~~~~~~~~~~~~~~~~~~~~ It is also possible to write test cases as requirements that also non-technical project stakeholders must understand. These *executable requirements* are a corner stone of a process commonly called `Acceptance Test Driven Development`__ (ATDD) or `Specification by Example`__. One way to write these requirements/tests is *Given-When-Then* style popularized by `Behavior Driven Development`__ (BDD). When writing test cases in this style, the initial state is usually expressed with a keyword starting with word :name:`Given`, the actions are described with keyword starting with :name:`When` and the expectations with a keyword starting with :name:`Then`. Keyword starting with :name:`And` or :name:`But` may be used if a step has more than one action. .. sourcecode:: robotframework *** Test Cases *** Valid Login Given login page is open When valid username and password are inserted and credentials are submitted Then welcome page should be open __ http://testobsessed.com/2008/12/08/acceptance-test-driven-development-atdd-an-overview __ http://en.wikipedia.org/wiki/Specification_by_example __ http://en.wikipedia.org/wiki/Behavior_Driven_Development Ignoring :name:`Given/When/Then/And/But` prefixes ''''''''''''''''''''''''''''''''''''''''''''''''' Prefixes :name:`Given`, :name:`When`, :name:`Then`, :name:`And` and :name:`But` are dropped when matching keywords are searched, if no match with the full name is found. This works for both user keywords and library keywords. For example, :name:`Given login page is open` in the above example can be implemented as user keyword either with or without the word :name:`Given`. Ignoring prefixes also allows using the same keyword with different prefixes. For example :name:`Welcome page should be open` could also used as :name:`And welcome page should be open`. .. note:: Ignoring :name:`But` prefix is new in Robot Framework 2.8.7. Embedding data to keywords '''''''''''''''''''''''''' When writing concrete examples it is useful to be able pass actual data to keyword implementations. User keywords support this by allowing `embedding arguments into keyword name`_.
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/CreatingTestData/CreatingTestCases.rst
0.958392
0.883588
CreatingTestCases.rst
pypi
Advanced features ================= .. contents:: :depth: 2 :local: Handling keywords with same names --------------------------------- Keywords that are used with Robot Framework are either `library keywords`_ or `user keywords`_. The former come from `standard libraries`_ or `external libraries`_, and the latter are either created in the same file where they are used or then imported from `resource files`_. When many keywords are in use, it is quite common that some of them have the same name, and this section describes how to handle possible conflicts in these situations. Keyword scopes ~~~~~~~~~~~~~~ When only a keyword name is used and there are several keywords with that name, Robot Framework attempts to determine which keyword has the highest priority based on its scope. The keyword's scope is determined on the basis of how the keyword in question is created: 1. Created as a user keyword in the same file where it is used. These keywords have the highest priority and they are always used, even if there are other keywords with the same name elsewhere. 2. Created in a resource file and imported either directly or indirectly from another resource file. This is the second-highest priority. 3. Created in an external test library. These keywords are used, if there are no user keywords with the same name. However, if there is a keyword with the same name in the standard library, a warning is displayed. 4. Created in a standard library. These keywords have the lowest priority. Specifying a keyword explicitly ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Scopes alone are not a sufficient solution, because there can be keywords with the same name in several libraries or resources, and thus, they provide a mechanism to use only the keyword of the highest priority. In such cases, it is possible to use *the full name of the keyword*, where the keyword name is prefixed with the name of the resource or library and a dot is a delimiter. With library keywords, the long format means only using the format :name:`LibraryName.Keyword Name`. For example, the keyword :name:`Run` from the OperatingSystem_ library could be used as :name:`OperatingSystem.Run`, even if there was another :name:`Run` keyword somewhere else. If the library is in a module or package, the full module or package name must be used (for example, :name:`com.company.Library.Some Keyword`). If a custom name is given to a library using the `WITH NAME syntax`_, the specified name must be used also in the full keyword name. Resource files are specified in the full keyword name, similarly as library names. The name of the resource is derived from the basename of the resource file without the file extension. For example, the keyword :name:`Example` in a resource file :file:`myresources.html` can be used as :name:`myresources.Example`. Note that this syntax does not work, if several resource files have the same basename. In such cases, either the files or the keywords must be renamed. The full name of the keyword is case-, space- and underscore-insensitive, similarly as normal keyword names. Specifying explicit priority between libraries and resources ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If there are multiple conflicts between keywords, specifying all the keywords in the long format can be quite a lot work. Using the long format also makes it impossible to create dynamic test cases or user keywords that work differently depending on which libraries or resources are available. A solution to both of these problems is specifying the keyword priorities explicitly using the keyword :name:`Set Library Search Order` from the BuiltIn_ library. .. note:: Although the keyword has the word *library* in its name, it works also with resource files. As discussed above, keywords in resources always have higher priority than keywords in libraries, though. The :name:`Set Library Search Order` accepts an ordered list or libraries and resources as arguments. When a keyword name in the test data matches multiple keywords, the first library or resource containing the keyword is selected and that keyword implementation used. If the keyword is not found from any of the specified libraries or resources, execution fails for conflict the same way as when the search order is not set. For more information and examples, see the documentation of the keyword. Timeouts -------- Keywords may be problematic in situations where they take exceptionally long to execute or just hang endlessly. Robot Framework allows you to set timeouts both for `test cases`_ and `user keywords`_, and if a test or keyword is not finished within the specified time, the keyword that is currently being executed is forcefully stopped. Stopping keywords in this manner may leave the library or system under test to an unstable state, and timeouts are recommended only when there is no safer option available. In general, libraries should be implemented so that keywords cannot hang or that they have their own timeout mechanism, if necessary. Test case timeout ~~~~~~~~~~~~~~~~~ The test case timeout can be set either by using the :setting:`Test Timeout` setting in the Setting table or the :setting:`[Timeout]` setting in the Test Case table. :setting:`Test Timeout` in the Setting table defines a default test timeout value for all the test cases in the test suite, whereas :setting:`[Timeout]` in the Test Case table applies a timeout to an individual test case and overrides the possible default value. Using an empty :setting:`[Timeout]` means that the test has no timeout even when :setting:`Test Timeout` is used. It is also possible to use value `NONE` for this purpose. Regardless of where the test timeout is defined, the first cell after the setting name contains the duration of the timeout. The duration must be given in Robot Framework's `time format`_, that is, either directly in seconds or in a format like `1 minute 30 seconds`. It must be noted that there is always some overhead by the framework, and timeouts shorter than one second are thus not recommended. The default error message displayed when a test timeout occurs is `Test timeout <time> exceeded`. It is also possible to use custom error messages, and these messages are written into the cells after the timeout duration. The message can be split into multiple cells, similarly as documentations. Both the timeout value and the error message may contain variables. If there is a timeout, the keyword running is stopped at the expiration of the timeout and the test case fails. However, keywords executed as `test teardown`_ are not interrupted if a test timeout occurs, because they are normally engaged in important clean-up activities. If necessary, it is possible to interrupt also these keywords with `user keyword timeouts`_. .. sourcecode:: robotframework *** Settings *** Test Timeout 2 minutes *** Test Cases *** Default Timeout [Documentation] Timeout from the Setting table is used Some Keyword argument Override [Documentation] Override default, use 10 seconds timeout [Timeout] 10 Some Keyword argument Custom Message [Documentation] Override default and use custom message [Timeout] 1min 10s This is my custom error Some Keyword argument Variables [Documentation] It is possible to use variables too [Timeout] ${TIMEOUT} Some Keyword argument No Timeout [Documentation] Empty timeout means no timeout even when Test Timeout has been used [Timeout] Some Keyword argument No Timeout 2 [Documentation] Disabling timeout with NONE works too and is more explicit. [Timeout] NONE Some Keyword argument User keyword timeout ~~~~~~~~~~~~~~~~~~~~ A timeout can be set for a user keyword using the :setting:`[Timeout]` setting in the Keyword table. The syntax for setting it, including how timeout values and possible custom messages are given, is identical to the syntax used with `test case timeouts`_. If no custom message is provided, the default error message `Keyword timeout <time> exceeded` is used if a timeout occurs. .. sourcecode:: robotframework *** Keywords *** Timed Keyword [Documentation] Set only the timeout value and not the custom message. [Timeout] 1 minute 42 seconds Do Something Do Something Else Timed-out Wrapper [Arguments] @{args} [Documentation] This keyword is a wrapper that adds a timeout to another keyword. [Timeout] 2 minutes Original Keyword didn't finish in 2 minutes Original Keyword @{args} A user keyword timeout is applicable during the execution of that user keyword. If the total time of the whole keyword is longer than the timeout value, the currently executed keyword is stopped. User keyword timeouts are applicable also during a test case teardown, whereas test timeouts are not. If both the test case and some of its keywords (or several nested keywords) have a timeout, the active timeout is the one with the least time left. .. warning:: Using timeouts might slow down test execution when using Python 2.5 elsewhere than on Windows. Prior to Robot Framework 2.7 timeouts slowed down execution with all Python versions on all platforms. .. _for loop: For loops --------- Repeating same actions several times is quite a common need in test automation. With Robot Framework, test libraries can have any kind of loop constructs, and most of the time loops should be implemented in them. Robot Framework also has its own for loop syntax, which is useful, for example, when there is a need to repeat keywords from different libraries. For loops can be used with both test cases and user keywords. Except for really simple cases, user keywords are better, because they hide the complexity introduced by for loops. The basic for loop syntax, `FOR item IN sequence`, is derived from Python, but similar syntax is possible also in shell scripts or Perl. Normal for loop ~~~~~~~~~~~~~~~ In a normal for loop, one variable is assigned from a list of values, one value per iteration. The syntax starts with `:FOR`, where colon is required to separate the syntax from normal keywords. The next cell contains the loop variable, the subsequent cell must have `IN`, and the final cells contain values over which to iterate. These values can contain variables_, including `list variables`_. The keywords used in the for loop are on the following rows and they must be indented one cell to the right. When using the `plain text format`_, the indented cells must be `escaped with a backslash`__, but with other data formats the cells can be just left empty. The for loop ends when the indentation returns back to normal or the table ends. .. sourcecode:: robotframework *** Test Cases *** Example 1 :FOR ${animal} IN cat dog \ Log ${animal} \ Log 2nd keyword Log Outside loop Example 2 :FOR ${var} IN one two ... ${3} four ${last} \ Log ${var} The for loop in :name:`Example 1` above is executed twice, so that first the loop variable `${animal}` has the value `cat` and then `dog`. The loop consists of two :name:`Log` keywords. In the second example, loop values are `split into two rows`__ and the loop is run altogether five times. It is often convenient to use for loops with `list variables`_. This is illustrated by the example below, where `@{ELEMENTS}` contains an arbitrarily long list of elements and keyword :name:`Start Element` is used with all of them one by one. .. sourcecode:: robotframework *** Test Cases *** Example :FOR ${element} IN @{ELEMENTS} \ Start Element ${element} Nested for loops ~~~~~~~~~~~~~~~~ Having nested for loops is not supported directly, but it is possible to use a user keyword inside a for loop and have another for loop there. .. sourcecode:: robotframework *** Keywords *** Handle Table [Arguments] @{table} :FOR ${row} IN @{table} \ Handle Row @{row} Handle Row [Arguments] @{row} :FOR ${cell} IN @{row} \ Handle Cell ${cell} __ `Dividing test data to several rows`_ __ Escaping_ Using several loop variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is also possible to use several loop variables. The syntax is the same as with the normal for loop, but all loop variables are listed in the cells between `:FOR` and `IN`. There can be any number of loop variables, but the number of values must be evenly dividable by the number of variables. If there are lot of values to iterate, it is often convenient to organize them below the loop variables, as in the first loop of the example below: .. sourcecode:: robotframework *** Test Cases *** Three loop variables :FOR ${index} ${english} ${finnish} IN ... 1 cat kissa ... 2 dog koira ... 3 horse hevonen \ Add to dictionary ${english} ${finnish} ${index} :FOR ${name} ${id} IN @{EMPLOYERS} \ Create ${name} ${id} For-in-range loop ~~~~~~~~~~~~~~~~~ Earlier for loops always iterated over a sequence, and this is also the most common use case. Sometimes it is still convenient to have a for loop that is executed a certain number of times, and Robot Framework has a special `FOR index IN RANGE limit` syntax for this purpose. This syntax is derived from the similar Python idiom. Similarly as other for loops, the for-in-range loop starts with `:FOR` and the loop variable is in the next cell. In this format there can be only one loop variable and it contains the current loop index. The next cell must contain `IN RANGE` and the subsequent cells loop limits. In the simplest case, only the upper limit of the loop is specified. In this case, loop indexes start from zero and increase by one until, but excluding, the limit. It is also possible to give both the start and end limits. Then indexes start from the start limit, but increase similarly as in the simple case. Finally, it is possible to give also the step value that specifies the increment to use. If the step is negative, it is used as decrement. It is possible to use simple arithmetics such as addition and subtraction with the range limits. This is especially useful when the limits are specified with variables. Starting from Robot Framework 2.8.7, it is possible to use float values for lower limit, upper limit and step. .. sourcecode:: robotframework *** Test Cases *** Only upper limit [Documentation] Loops over values from 0 to 9 :FOR ${index} IN RANGE 10 \ Log ${index} Start and end [Documentation] Loops over values from 1 to 10 :FOR ${index} IN RANGE 1 11 \ Log ${index} Also step given [Documentation] Loops over values 5, 15, and 25 :FOR ${index} IN RANGE 5 26 10 \ Log ${index} Negative step [Documentation] Loops over values 13, 3, and -7 :FOR ${index} IN RANGE 13 -13 -10 \ Log ${index} Arithmetics [Documentation] Arithmetics with variable :FOR ${index} IN RANGE ${var}+1 \ Log ${index} Float parameters [Documentation] Loops over values 3.14, 4.34, and 5.34 :FOR ${index} IN RANGE 3.14 6.09 1.2 \ Log ${index} For-in-enumerate loop ~~~~~~~~~~~~~~~~~~~~~ Sometimes it is useful to loop over a list and also keep track of your location inside the list. Robot Framework has a special `FOR index ... IN ENUMERATE ...` syntax for this situation. This syntax is derived from the `Python built-in function <https://docs.python.org/2/library/functions.html#enumerate>`_. For-in-enumerate loops work just like regular for loops, except the cell after its loop variables must say `IN ENUMERATE`, and they must have an additional index variable before any other loop-variables. That index variable has a value of `0` for the first iteration, `1` for the second, etc. For example, the following two test cases do the same thing: .. sourcecode:: robotframework *** Variables *** @{LIST} a b c *** Test Cases *** Manage index manually ${index} = Set Variable -1 : FOR ${item} IN @{LIST} \ ${index} = Evaluate ${index} + 1 \ My Keyword ${index} ${item} For-in-enumerate : FOR ${index} ${item} IN ENUMERATE @{LIST} \ My Keyword ${index} ${item} Just like with regular for loops, you can loop over multiple values per loop iteration as long as the number of values in your list is evenly divisible by the number of loop-variables (excluding the first, index variable). .. sourcecode:: robotframework *** Test Case *** For-in-enumerate with two values per iteration :FOR ${index} ${english} ${finnish} IN ENUMERATE ... cat kissa ... dog koira ... horse hevonen \ Add to dictionary ${english} ${finnish} ${index} For-in-enumerate loops are new in Robot Framework 2.9. For-in-zip loop ~~~~~~~~~~~~~~~ Some tests build up several related lists, then loop over them together. Robot Framework has a shortcut for this case: `FOR ... IN ZIP ...`, which is derived from the `Python built-in zip function <https://docs.python.org/2/library/functions.html#zip>`_. This may be easiest to show with an example: .. sourcecode:: robotframework *** Variables *** @{NUMBERS} ${1} ${2} ${5} @{NAMES} one two five *** Test Cases *** Iterate over two lists manually ${length}= Get Length ${NUMBERS} : FOR ${idx} IN RANGE ${length} \ Number Should Be Named ${NUMBERS}[${idx}] ${NAMES}[${idx}] For-in-zip : FOR ${number} ${name} IN ZIP ${NUMBERS} ${NAMES} \ Number Should Be Named ${number} ${name} Similarly as for-in-range and for-in-enumerate loops, for-in-zip loops require the cell after the loop variables to read `IN ZIP`. Values used with for-in-zip loops must be lists or list-like objects, and there must be same number of loop variables as lists to loop over. Looping will stop when the shortest list is exhausted. Note that any lists used with for-in-zip should usually be given as `scalar variables`_ like `${list}`. A `list variable`_ only works if its items themselves are lists. For-in-zip loops are new in Robot Framework 2.9. Exiting for loop ~~~~~~~~~~~~~~~~ Normally for loops are executed until all the loop values have been iterated or a keyword used inside the loop fails. If there is a need to exit the loop earlier, BuiltIn_ keywords :name:`Exit For Loop` and :name:`Exit For Loop If` can be used to accomplish that. They works similarly as `break` statement in Python, Java, and many other programming languages. :name:`Exit For Loop` and :name:`Exit For Loop If` keywords can be used directly inside a for loop or in a keyword that the loop uses. In both cases test execution continues after the loop. It is an error to use these keywords outside a for loop. .. sourcecode:: robotframework *** Test Cases *** Exit Example ${text} = Set Variable ${EMPTY} :FOR ${var} IN one two \ Run Keyword If '${var}' == 'two' Exit For Loop \ ${text} = Set Variable ${text}${var} Should Be Equal ${text} one In the above example it would be possible to use :name:`Exit For Loop If` instead of using :name:`Exit For Loop` with :name:`Run Keyword If`. For more information about these keywords, including more usage examples, see their documentation in the BuiltIn_ library. .. note:: :name:`Exit For Loop If` keyword was added in Robot Framework 2.8. Continuing for loop ~~~~~~~~~~~~~~~~~~~ In addition to exiting a for loop prematurely, it is also possible to continue to the next iteration of the loop before all keywords have been executed. This can be done using BuiltIn_ keywords :name:`Continue For Loop` and :name:`Continue For Loop If`, that work like `continue` statement in many programming languages. :name:`Continue For Loop` and :name:`Continue For Loop If` keywords can be used directly inside a for loop or in a keyword that the loop uses. In both cases rest of the keywords in that iteration are skipped and execution continues from the next iteration. If these keywords are used on the last iteration, execution continues after the loop. It is an error to use these keywords outside a for loop. .. sourcecode:: robotframework *** Test Cases *** Continue Example ${text} = Set Variable ${EMPTY} :FOR ${var} IN one two three \ Continue For Loop If '${var}' == 'two' \ ${text} = Set Variable ${text}${var} Should Be Equal ${text} onethree For more information about these keywords, including usage examples, see their documentation in the BuiltIn_ library. .. note:: Both :name:`Continue For Loop` and :name:`Continue For Loop If` were added in Robot Framework 2.8. Removing unnecessary keywords from outputs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For loops with multiple iterations often create lots of output and considerably increase the size of the generated output_ and log_ files. Starting from Robot Framework 2.7, it is possible to `remove unnecessary keywords`__ from the outputs using :option:`--RemoveKeywords FOR` command line option. __ `Removing and flattening keywords`_ Repeating single keyword ~~~~~~~~~~~~~~~~~~~~~~~~ For loops can be excessive in situations where there is only a need to repeat a single keyword. In these cases it is often easier to use BuiltIn_ keyword :name:`Repeat Keyword`. This keyword takes a keyword and how many times to repeat it as arguments. The times to repeat the keyword can have an optional postfix `times` or `x` to make the syntax easier to read. .. sourcecode:: robotframework *** Test Cases *** Example Repeat Keyword 5 Some Keyword arg1 arg2 Repeat Keyword 42 times My Keyword Repeat Keyword ${var} Another Keyword argument Conditional execution --------------------- In general, it is not recommended to have conditional logic in test cases, or even in user keywords, because it can make them hard to understand and maintain. Instead, this kind of logic should be in test libraries, where it can be implemented using natural programming language constructs. However, some conditional logic can be useful at times, and even though Robot Framework does not have an actual if/else construct, there are several ways to get the same effect. - The name of the keyword used as a setup or a teardown of both `test cases`__ and `test suites`__ can be specified using a variable. This facilitates changing them, for example, from the command line. - The BuiltIn_ keyword :name:`Run Keyword` takes a keyword to actually execute as an argument, and it can thus be a variable. The value of the variable can, for example, be got dynamically from an earlier keyword or given from the command line. - The BuiltIn_ keywords :name:`Run Keyword If` and :name:`Run Keyword Unless` execute a named keyword only if a certain expression is true or false, respectively. They are ideally suited to creating simple if/else constructs. For an example, see the documentation of the former. - Another BuiltIn_ keyword, :name:`Set Variable If`, can be used to set variables dynamically based on a given expression. - There are several BuiltIn_ keywords that allow executing a named keyword only if a test case or test suite has failed or passed. __ `Test setup and teardown`_ __ `Suite setup and teardown`_ Parallel execution of keywords ------------------------------ When parallel execution is needed, it must be implemented in test library level so that the library executes the code on background. Typically this means that the library needs a keyword like :name:`Start Something` that starts the execution and returns immediately, and another keyword like :name:`Get Results From Something` that waits until the result is available and returns it. See OperatingSystem_ library keywords :name:`Start Process` and :name:`Read Process Output` for an example.
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/CreatingTestData/AdvancedFeatures.rst
0.945096
0.78789
AdvancedFeatures.rst
pypi
Creating test suites ==================== Robot Framework test cases are created in test case files, which can be organized into directories. These files and directories create a hierarchical test suite structure. .. contents:: :depth: 2 :local: Test case files --------------- Robot Framework test cases `are created`__ using test case tables in test case files. Such a file automatically creates a test suite from all the test cases it contains. There is no upper limit for how many test cases there can be, but it is recommended to have less than ten, unless the `data-driven approach`_ is used, where one test case consists of only one high-level keyword. The following settings in the Setting table can be used to customize the test suite: `Documentation`:setting: Used for specifying a `test suite documentation`_ `Metadata`:setting: Used for setting `free test suite metadata`_ as name-value pairs. `Suite Setup`:setting:, `Suite Teardown`:setting: Specify `suite setup and teardown`_. Have also synonyms :setting:`Suite Precondition` and :setting:`Suite Postcondition`, respectively. .. note:: All setting names can optionally include a colon at the end, for example :setting:`Documentation:`. This can make reading the settings easier especially when using the plain text format. __ `Test case syntax`_ Test suite directories ---------------------- Test case files can be organized into directories, and these directories create higher-level test suites. A test suite created from a directory cannot have any test cases directly, but it contains other test suites with test cases, instead. These directories can then be placed into other directories creating an even higher-level suite. There are no limits for the structure, so test cases can be organized as needed. When a test directory is executed, the files and directories it contains are processed recursively as follows: - Files and directories with names starting with a dot (:file:`.`) or an underscore (:file:`_`) are ignored. - Directories with the name :file:`CVS` are ignored (case-sensitive). - Files not having one of the `recognized extensions`__ (:file:`.html`, :file:`.xhtml`, :file:`.htm`, :file:`.tsv`, :file:`.txt`, :file:`.rst`, or :file:`.rest`) are ignored (case-insensitive). - Other files and directories are processed. If a file or directory that is processed does not contain any test cases, it is silently ignored (a message is written to the syslog_) and the processing continues. __ `Supported file formats`_ Warning on invalid files ~~~~~~~~~~~~~~~~~~~~~~~~ Normally files that do not have a valid test case table are silently ignored with a message written to the syslog_. It is possible to use a command line option :option:`--warnonskippedfiles`, which turns the message into a warning shown in `test execution errors`__. __ `Errors and warnings during execution`_ Initialization files ~~~~~~~~~~~~~~~~~~~~ A test suite created from a directory can have similar settings as a suite created from a test case file. Because a directory alone cannot have that kind of information, it must be placed into a special test suite initialization file. An initialization file name must always be of the format :file:`__init__.ext`, where the extension must be one of the `supported file formats`_ (for example, :file:`__init__.robot` or :file:`__init__.html`). The name format is borrowed from Python, where files named in this manner denote that a directory is a module. Initialization files have the same structure and syntax as test case files, except that they cannot have test case tables and not all settings are supported. Variables and keywords created or imported in initialization files *are not* available in the lower level test suites. If you need to share variables or keywords, you can put them into `resource files`_ that can be imported both by initialization and test case files. The main usage for initialization files is specifying test suite related settings similarly as in `test case files`_, but setting some `test case related settings`__ is also possible. How to use different settings in the initialization files is explained below. `Documentation`:setting:, `Metadata`:setting:, `Suite Setup`:setting:, `Suite Teardown`:setting: These test suite specific settings work the same way as in test case files. `Force Tags`:setting: Specified tags are unconditionally set to all test cases in all test case files this directory contains directly or recursively. `Test Setup`:setting:, `Test Teardown`:setting:, `Test Timeout`:setting: Set the default value for test setup/teardown or test timeout to all test cases this directory contains. Can be overridden on lower level. Support for defining test timeout in initialization files was added in Robot Framework 2.7. `Default Tags`:setting:, `Test Template`:setting: Not supported in initialization files. .. sourcecode:: robotframework *** Settings *** Documentation Example suite Suite Setup Do Something ${MESSAGE} Force Tags example Library SomeLibrary *** Variables *** ${MESSAGE} Hello, world! *** Keywords *** Do Something [Arguments] ${args} Some Keyword ${arg} Another Keyword __ `Test case related settings in the Setting table`_ Test suite name and documentation --------------------------------- The test suite name is constructed from the file or directory name. The name is created so that the extension is ignored, possible underscores are replaced with spaces, and names fully in lower case are title cased. For example, :file:`some_tests.html` becomes :name:`Some Tests` and :file:`My_test_directory` becomes :name:`My test directory`. The file or directory name can contain a prefix to control the `execution order`_ of the suites. The prefix is separated from the base name by two underscores and, when constructing the actual test suite name, both the prefix and underscores are removed. For example files :file:`01__some_tests.txt` and :file:`02__more_tests.txt` create test suites :name:`Some Tests` and :name:`More Tests`, respectively, and the former is executed before the latter. The documentation for a test suite is set using the :setting:`Documentation` setting in the Setting table. It can be used in test case files or, with higher-level suites, in test suite initialization files. Test suite documentation has exactly the same characteristics regarding to where it is shown and how it can be created as `test case documentation`_. .. sourcecode:: robotframework *** Settings *** Documentation An example test suite documentation with *some* _formatting_. ... See test documentation for more documentation examples. Both the name and documentation of the top-level test suite can be overridden in test execution. This can be done with the command line options :option:`--name` and :option:`--doc`, respectively, as explained in section `Setting metadata`_. Free test suite metadata ------------------------ Test suites can also have other metadata than the documentation. This metadata is defined in the Setting table using the :setting:`Metadata` setting. Metadata set in this manner is shown in test reports and logs. The name and value for the metadata are located in the columns following :setting:`Metadata`. The value is handled similarly as documentation, which means that it can be split `into several cells`__ (joined together with spaces) or `into several rows`__ (joined together with newlines), simple `HTML formatting`_ works and even variables_ can be used. __ `Dividing test data to several rows`_ __ `Newlines in test data`_ .. sourcecode:: robotframework *** Settings *** Metadata Version 2.0 Metadata More Info For more information about *Robot Framework* see http://robotframework.org Metadata Executed At ${HOST} For top-level test suites, it is possible to set metadata also with the :option:`--metadata` command line option. This is discussed in more detail in section `Setting metadata`_. Suite setup and teardown ------------------------ Not only `test cases`__ but also test suites can have a setup and a teardown. A suite setup is executed before running any of the suite's test cases or child test suites, and a test teardown is executed after them. All test suites can have a setup and a teardown; with suites created from a directory they must be specified in a `test suite initialization file`_. __ `Test setup and teardown`_ Similarly as with test cases, a suite setup and teardown are keywords that may take arguments. They are defined in the Setting table with :setting:`Suite Setup` and :setting:`Suite Teardown` settings, respectively. They also have similar synonyms, :setting:`Suite Precondition` and :setting:`Suite Postcondition`, as a test case setup and teardown have. Keyword names and possible arguments are located in the columns after the setting name. If a suite setup fails, all test cases in it and its child test suites are immediately assigned a fail status and they are not actually executed. This makes suite setups ideal for checking preconditions that must be met before running test cases is possible. A suite teardown is normally used for cleaning up after all the test cases have been executed. It is executed even if the setup of the same suite fails. If the suite teardown fails, all test cases in the suite are marked failed, regardless of their original execution status. Note that all the keywords in suite teardowns are executed even if one of them fails. The name of the keyword to be executed as a setup or a teardown can be a variable. This facilitates having different setups or teardowns in different environments by giving the keyword name as a variable from the command line.
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/CreatingTestData/CreatingTestSuites.rst
0.876964
0.738858
CreatingTestSuites.rst
pypi
Using test libraries ==================== Test libraries contain those lowest-level keywords, often called *library keywords*, which actually interact with the system under test. All test cases always use keywords from some library, often through higher-level `user keywords`_. This section explains how to take test libraries into use and how to use the keywords they provide. `Creating test libraries`_ is described in a separate section. .. contents:: :depth: 2 :local: Importing libraries ------------------- Test libraries are typically imported using the :setting:`Library` setting, but it is also possible to use the :name:`Import Library` keyword. Using `Library` setting ~~~~~~~~~~~~~~~~~~~~~~~ Test libraries are normally imported using the :setting:`Library` setting in the Setting table and having the library name in the subsequent column. The library name is case-sensitive (it is the name of the module or class implementing the library and must be exactly correct), but any spaces in it are ignored. With Python libraries in modules or Java libraries in packages, the full name including the module or package name must be used. In those cases where the library needs arguments, they are listed in the columns after the library name. It is possible to use default values, variable number of arguments, and named arguments in test library imports similarly as with `arguments to keywords`__. Both the library name and arguments can be set using variables. __ `Using arguments`_ .. sourcecode:: robotframework *** Settings *** Library OperatingSystem Library com.company.TestLib Library MyLibrary arg1 arg2 Library ${LIBRARY} It is possible to import test libraries in `test case files`_, `resource files`_ and `test suite initialization files`_. In all these cases, all the keywords in the imported library are available in that file. With resource files, those keywords are also available in other files using them. Using `Import Library` keyword ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Another possibility to take a test library into use is using the keyword :name:`Import Library` from the BuiltIn_ library. This keyword takes the library name and possible arguments similarly as the :setting:`Library` setting. Keywords from the imported library are available in the test suite where the :name:`Import Library` keyword was used. This approach is useful in cases where the library is not available when the test execution starts and only some other keywords make it available. .. sourcecode:: robotframework *** Test Cases *** Example Do Something Import Library MyLibrary arg1 arg2 KW From MyLibrary Specifying library to import ---------------------------- Libraries to import can be specified either by using the library name or the path to the library. These approaches work the same way regardless is the library imported using the :setting:`Library` setting or the :name:`Import Library` keyword. Using library name ~~~~~~~~~~~~~~~~~~ The most common way to specify a test library to import is using its name, like it has been done in all the examples in this section. In these cases Robot Framework tries to find the class or module implementing the library from the `module search path`_. Libraries that are installed somehow ought to be in the module search path automatically, but with other libraries the search path may need to be configured separately. The biggest benefit of this approach is that when the module search path has been configured, often using a custom `start-up script`_, normal users do not need to think where libraries actually are installed. The drawback is that getting your own, possible very simple, libraries into the search path may require some additional configuration. Using physical path to library ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Another mechanism for specifying the library to import is using a path to it in the file system. This path is considered relative to the directory where current test data file is situated similarly as paths to `resource and variable files`_. The main benefit of this approach is that there is no need to configure the module search path. If the library is a file, the path to it must contain extension. For Python libraries the extension is naturally :file:`.py` and for Java libraries it can either be :file:`.class` or :file:`.java`, but the class file must always be available. If Python library is implemented as a directory, the path to it must have a trailing forward slash (`/`). Following examples demonstrate these different usages. .. sourcecode:: robotframework *** Settings *** Library PythonLib.py Library /absolute/path/JavaLib.java Library relative/path/PythonDirLib/ possible arguments Library ${RESOURCES}/Example.class A limitation of this approach is that libraries implemented as Python classes `must be in a module with the same name as the class`__. Additionally, importing libraries distributed in JAR or ZIP packages is not possible with this mechanism. __ `Test library names`_ Setting custom name to test library ----------------------------------- The library name is shown in test logs before keyword names, and if multiple keywords have the same name, they must be used so that the `keyword name is prefixed with the library name`__. The library name is got normally from the module or class name implementing it, but there are some situations where changing it is desirable: __ `Handling keywords with same names`_ - There is a need to import the same library several times with different arguments. This is not possible otherwise. - The library name is inconveniently long. This can happen, for example, if a Java library has a long package name. - You want to use variables to import different libraries in different environments, but refer to them with the same name. - The library name is misleading or otherwise poor. In this case, changing the actual name is, of course, a better solution. The basic syntax for specifying the new name is having the text `WITH NAME` (case-insensitive) after the library name and then having the new name in the next cell. The specified name is shown in logs and must be used in the test data when using keywords' full name (:name:`LibraryName.Keyword Name`). .. sourcecode:: robotframework *** Settings *** Library com.company.TestLib WITH NAME TestLib Library ${LIBRARY} WITH NAME MyName Possible arguments to the library are placed into cells between the original library name and the `WITH NAME` text. The following example illustrates how the same library can be imported several times with different arguments: .. sourcecode:: robotframework *** Settings *** Library SomeLibrary localhost 1234 WITH NAME LocalLib Library SomeLibrary server.domain 8080 WITH NAME RemoteLib *** Test Cases *** My Test LocalLib.Some Keyword some arg second arg RemoteLib.Some Keyword another arg whatever LocalLib.Another Keyword Setting a custom name to a test library works both when importing a library in the Setting table and when using the :name:`Import Library` keyword. Standard libraries ------------------ Some test libraries are distributed with Robot Framework and these libraries are called *standard libraries*. The BuiltIn_ library is special, because it is taken into use automatically and thus its keywords are always available. Other standard libraries need to be imported in the same way as any other libraries, but there is no need to install them. Normal standard libraries ~~~~~~~~~~~~~~~~~~~~~~~~~ The available normal standard libraries are listed below with links to their documentations: - BuiltIn_ - Collections_ - DateTime_ - Dialogs_ - OperatingSystem_ - Process_ - Screenshot_ - String_ - Telnet_ - XML_ .. _BuiltIn: ../libraries/BuiltIn.html .. _Collections: ../libraries/Collections.html .. _DateTime: ../libraries/DateTime.html .. _Dialogs: ../libraries/Dialogs.html .. _OperatingSystem: ../libraries/OperatingSystem.html .. _Process: ../libraries/Process.html .. _String: ../libraries/String.html .. _Screenshot: ../libraries/Screenshot.html .. _Telnet: ../libraries/Telnet.html .. _XML: ../libraries/XML.html Remote library ~~~~~~~~~~~~~~ In addition to the normal standard libraries listed above, there is also :name:`Remote` library that is totally different than the other standard libraries. It does not have any keywords of its own but it works as a proxy between Robot Framework and actual test library implementations. These libraries can be running on other machines than the core framework and can even be implemented using languages not supported by Robot Framework natively. See separate `Remote library interface`_ section for more information about this concept. External libraries ------------------ Any test library that is not one of the standard libraries is, by definition, *an external library*. The Robot Framework open source community has implemented several generic libraries, such as Selenium2Library_ and SwingLibrary_, which are not packaged with the core framework. A list of publicly available libraries can be found from http://robotframework.org. Generic and custom libraries can obviously also be implemented by teams using Robot Framework. See `Creating test libraries`_ section for more information about that topic. Different external libraries can have a totally different mechanism for installing them and taking them into use. Sometimes they may also require some other dependencies to be installed separately. All libraries should have clear installation and usage documentation and they should preferably automate the installation process.
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/doc/userguide/src/CreatingTestData/UsingTestLibraries.rst
0.958343
0.703919
UsingTestLibraries.rst
pypi
from six import text_type as unicode """Exceptions and return codes used internally. External libraries should not used exceptions defined here. """ # 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 unicode(self) 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 caught by keywords that run other keywords (e.g. `Run Keyword And Expect Error`). """ class VariableError(DataError): """Used when variable does not exist. VariableErrors are caught by keywords that run other keywords (e.g. `Run Keyword And Expect Error`). """ 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`). """ 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') from robot.utils import cut_long_message RobotError.__init__(self, 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 @property def continue_on_failure(self): return self._continue_on_failure @continue_on_failure.setter def 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 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] @property def status(self): return 'FAIL' class HandlerExecutionFailed(ExecutionFailed): def __init__(self, details): timeout = isinstance(details.error, TimeoutError) syntax = isinstance(details.error, DataError) \ and not isinstance(details.error, VariableError) 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 def _get(self, error, attr): return bool(getattr(error, 'ROBOT_' + attr, False)) 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): from robot.utils import printable_name return "Invalid '%s' usage." \ % 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) @property def status(self): return 'PASS' if not self._earlier_failures else 'FAIL' 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
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/errors.py
0.77827
0.268537
errors.py
pypi
from .listeners import Listeners, ListenerProxy from .loggerhelper import AbstractLoggerProxy class LibraryListeners(Listeners): def __init__(self): self._running_test = False self._setup_or_teardown_type = None self._global_listeners = {} def __bool__(self): return True #PY2 def __nonzero__(self): return self.__bool__() def _notify_end_test(self, listener, test): Listeners._notify_end_test(self, listener, test) if listener.library_scope == 'TESTCASE': listener.call_method(listener.close) def _notify_end_suite(self, listener, suite): Listeners._notify_end_suite(self, listener, suite) if listener.library_scope == 'TESTSUITE': listener.call_method(listener.close) def end_suite(self, suite): for listener in self._listeners: self._notify_end_suite(listener, suite) if not suite.parent: for listener in self._global_listeners.values(): listener.call_method(listener.close) @property def _listeners(self): from robot.running import EXECUTION_CONTEXTS if not EXECUTION_CONTEXTS.current: return [] listeners = [_LibraryListenerProxy(library, listener) for library in EXECUTION_CONTEXTS.current.namespace.libraries if library.has_listener for listener in library.listeners] for listener in listeners: if listener.library_scope == 'GLOBAL': self._global_listeners[listener.logger] = listener return listeners class _LibraryListenerProxy(ListenerProxy): def __init__(self, library, listener): AbstractLoggerProxy.__init__(self, listener) self.name = listener.__class__.__name__ self.version = self._get_version(listener) self.library_scope = library.scope def _get_method_names(self, name): names = ListenerProxy._get_method_names(self, name) return names + ['_' + name for name in names]
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/output/librarylisteners.py
0.607197
0.157331
librarylisteners.py
pypi
from robot.errors import DataError from robot.model import Message as BaseMessage from robot.utils import get_timestamp, is_unicode, unic LEVELS = { 'NONE' : 6, 'FAIL' : 5, 'ERROR' : 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 get_timestamp() BaseMessage.__init__(self, message, level, html, timestamp) def _normalize_message(self, msg): if callable(msg): return msg if not is_unicode(msg): msg = 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 @property def message(self): if callable(self._message): self._message = self._message() return self._message @message.setter def message(self, message): self._message = 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): for method_name in self._get_method_names(name): if hasattr(logger, method_name): return getattr(logger, method_name) return self._no_method def _get_method_names(self, name): return [name, self._toCamelCase(name)] def _toCamelCase(self, name): parts = name.split('_') return ''.join([parts[0]] + [part.capitalize() for part in parts[1:]])
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/output/loggerhelper.py
0.688887
0.249905
loggerhelper.py
pypi
# Windows highlighting code adapted from color_console.py. It is copyright # Andre Burgaud, licensed under the MIT License, and available here: # http://www.burgaud.com/bring-colors-to-the-windows-console-with-python/ from contextlib import contextmanager import os import sys try: from ctypes import windll, Structure, c_short, c_ushort, byref except ImportError: # Not on Windows or using Jython windll = None from robot.errors import DataError from robot.utils import encode_output, isatty class HighlightingStream(object): def __init__(self, stream, colors='AUTO'): self.stream = stream self._highlighter = self._get_highlighter(stream, colors) def _get_highlighter(self, stream, colors): options = {'AUTO': Highlighter if isatty(stream) else NoHighlighting, 'ON': Highlighter, 'OFF': NoHighlighting, 'ANSI': AnsiHighlighter} try: highlighter = options[colors.upper()] except KeyError: raise DataError("Invalid console color value '%s'. Available " "'AUTO', 'ON', 'OFF' and 'ANSI'." % colors) return highlighter(stream) def write(self, text, flush=True): self.stream.write(encode_output(text)) if flush: self.flush() def flush(self): self.stream.flush() def highlight(self, text, status=None, flush=True): with self._highlighting(status or text): self.write(text, flush) def error(self, message, level): self.write('[ ', flush=False) self.highlight(level, flush=False) self.write(' ] %s\n' % message) @contextmanager def _highlighting(self, status): highlighter = self._highlighter start = {'PASS': highlighter.green, 'FAIL': highlighter.red, 'ERROR': highlighter.red, 'WARN': highlighter.yellow}[status] start() try: yield finally: highlighter.reset() def Highlighter(stream): if os.sep == '/': return AnsiHighlighter(stream) return DosHighlighter(stream) if windll else NoHighlighting(stream) class AnsiHighlighter(object): _ANSI_GREEN = '\033[32m' _ANSI_RED = '\033[31m' _ANSI_YELLOW = '\033[33m' _ANSI_RESET = '\033[0m' def __init__(self, stream): self._stream = stream def green(self): self._set_color(self._ANSI_GREEN) def red(self): self._set_color(self._ANSI_RED) def yellow(self): self._set_color(self._ANSI_YELLOW) def reset(self): self._set_color(self._ANSI_RESET) def _set_color(self, color): self._stream.write(color) class NoHighlighting(AnsiHighlighter): def _set_color(self, color): pass class DosHighlighter(object): _FOREGROUND_GREEN = 0x2 _FOREGROUND_RED = 0x4 _FOREGROUND_YELLOW = 0x6 _FOREGROUND_GREY = 0x7 _FOREGROUND_INTENSITY = 0x8 _BACKGROUND_MASK = 0xF0 _STDOUT_HANDLE = -11 _STDERR_HANDLE = -12 def __init__(self, stream): self._handle = self._get_std_handle(stream) self._orig_colors = self._get_colors() self._background = self._orig_colors & self._BACKGROUND_MASK def green(self): self._set_foreground_colors(self._FOREGROUND_GREEN) def red(self): self._set_foreground_colors(self._FOREGROUND_RED) def yellow(self): self._set_foreground_colors(self._FOREGROUND_YELLOW) def reset(self): self._set_colors(self._orig_colors) def _get_std_handle(self, stream): handle = self._STDOUT_HANDLE \ if stream is sys.__stdout__ else self._STDERR_HANDLE return windll.kernel32.GetStdHandle(handle) def _get_colors(self): csbi = _CONSOLE_SCREEN_BUFFER_INFO() ok = windll.kernel32.GetConsoleScreenBufferInfo(self._handle, byref(csbi)) if not ok: # Call failed, return default console colors (gray on black) return self._FOREGROUND_GREY return csbi.wAttributes def _set_foreground_colors(self, colors): self._set_colors(colors | self._FOREGROUND_INTENSITY | self._background) def _set_colors(self, colors): windll.kernel32.SetConsoleTextAttribute(self._handle, colors) if windll: class _COORD(Structure): _fields_ = [("X", c_short), ("Y", c_short)] class _SMALL_RECT(Structure): _fields_ = [("Left", c_short), ("Top", c_short), ("Right", c_short), ("Bottom", c_short)] class _CONSOLE_SCREEN_BUFFER_INFO(Structure): _fields_ = [("dwSize", _COORD), ("dwCursorPosition", _COORD), ("wAttributes", c_ushort), ("srWindow", _SMALL_RECT), ("dwMaximumWindowSize", _COORD)]
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/output/console/highlighting.py
0.566978
0.168156
highlighting.py
pypi
from six import PY3 from robot.errors import DataError from robot.utils import (DotDict, is_dict_like, is_list_like, NormalizedDict, type_name) from .isvar import validate_var from .notfound import variable_not_found from .tablesetter import VariableTableValueBase class VariableStore(object): def __init__(self, variables): self.data = NormalizedDict(ignore='_') self._variables = variables def resolve_delayed(self): items = self.data.items() if PY3: # need list() because items can be removed during loop items = list(items) for name, value in items: try: self._resolve_delayed(name, value) except DataError: pass def _resolve_delayed(self, name, value): if not isinstance(value, VariableTableValueBase): return value try: self.data[name] = value.resolve(self._variables) except DataError as err: # Recursive resolving may have already removed variable. if name in self: self.remove(name) value.report_error(err) variable_not_found('${%s}' % name, self.data, "Variable '${%s}' not found." % name) return self.data[name] def __getitem__(self, name): return self._resolve_delayed(name, self.data[name]) def update(self, store): self.data.update(store.data) def clear(self): self.data.clear() def add(self, name, value, overwrite=True, decorated=True): if decorated: name, value = self._undecorate(name, value) if overwrite or name not in self.data: self.data[name] = value def _undecorate(self, name, value): validate_var(name) if name[0] == '@': if not is_list_like(value): self._raise_cannot_set_type(name, value, 'list') value = list(value) if name[0] == '&': if not is_dict_like(value): self._raise_cannot_set_type(name, value, 'dictionary') value = DotDict(value) return name[2:-1], value def _raise_cannot_set_type(self, name, value, expected): raise DataError("Cannot set variable '%s': Expected %s-like value, " "got %s." % (name, expected, type_name(value))) def remove(self, name): if name in self.data: self.data.pop(name) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __contains__(self, name): return name in self.data def as_dict(self, decoration=True): if decoration: variables = (self._decorate(name, self[name]) for name in self) else: variables = self.data return NormalizedDict(variables, ignore='_') def _decorate(self, name, value): if is_dict_like(value): name = '&{%s}' % name elif is_list_like(value): name = '@{%s}' % name else: name = '${%s}' % name return name, value
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/variables/store.py
0.502197
0.20091
store.py
pypi
import os import tempfile from robot.errors import DataError from robot.output import LOGGER from robot.utils import abspath, find_file, get_error_details, NormalizedDict from .variables import Variables class VariableScopes(object): def __init__(self, settings): self._global = GlobalVariables(settings) self._suite = None self._test = None self._scopes = [self._global] self._variables_set = SetVariables() @property def current(self): return self._scopes[-1] @property def _all_scopes(self): return reversed(self._scopes) @property def _scopes_until_suite(self): for scope in self._all_scopes: yield scope if scope is self._suite: break @property def _scopes_until_test(self): for scope in self._scopes_until_suite: yield scope if scope is self._test: break def start_suite(self): self._suite = self._global.copy() self._scopes.append(self._suite) self._variables_set.start_suite() self._variables_set.update(self._suite) def end_suite(self): self._scopes.pop() self._suite = self._scopes[-1] if len(self._scopes) > 1 else None self._variables_set.end_suite() def start_test(self): self._test = self._suite.copy() self._scopes.append(self._test) self._variables_set.start_test() def end_test(self): self._scopes.pop() self._test = None self._variables_set.end_test() def start_keyword(self): kw = self._suite.copy() self._variables_set.start_keyword() self._variables_set.update(kw) self._scopes.append(kw) def end_keyword(self): self._scopes.pop() self._variables_set.end_keyword() def __getitem__(self, name): return self.current[name] def __setitem__(self, name, value): self.current[name] = value def __contains__(self, name): return name in self.current def replace_list(self, items, replace_until=None): return self.current.replace_list(items, replace_until) def replace_scalar(self, items): return self.current.replace_scalar(items) def replace_string(self, string, ignore_errors=False): return self.current.replace_string(string, ignore_errors=ignore_errors) def set_from_file(self, path, args, overwrite=False): variables = None for scope in self._scopes_until_suite: if variables is None: variables = scope.set_from_file(path, args, overwrite) else: scope.set_from_file(variables, overwrite=overwrite) def set_from_variable_table(self, variables, overwrite=False): for scope in self._scopes_until_suite: scope.set_from_variable_table(variables, overwrite) def resolve_delayed(self): for scope in self._scopes_until_suite: scope.resolve_delayed() def set_global(self, name, value): for scope in self._all_scopes: name, value = self._set_global_suite_or_test(scope, name, value) self._variables_set.set_global(name, value) def _set_global_suite_or_test(self, scope, name, value): scope[name] = value # Avoid creating new list/dict objects in different scopes. if name[0] != '$': name = '$' + name[1:] value = scope[name] return name, value def set_suite(self, name, value, top=False, children=False): if top: self._scopes[1][name] = value return for scope in self._scopes_until_suite: name, value = self._set_global_suite_or_test(scope, name, value) if children: self._variables_set.set_suite(name, value) def set_test(self, name, value): if self._test is None: raise DataError('Cannot set test variable when no test is started.') for scope in self._scopes_until_test: name, value = self._set_global_suite_or_test(scope, name, value) self._variables_set.set_test(name, value) def set_keyword(self, name, value): self.current[name] = value self._variables_set.set_keyword(name, value) def as_dict(self, decoration=True): return self.current.as_dict(decoration=decoration) class GlobalVariables(Variables): def __init__(self, settings): Variables.__init__(self) self._set_cli_variables(settings) self._set_built_in_variables(settings) def _set_cli_variables(self, settings): for path, args in settings.variable_files: try: path = find_file(path, file_type='Variable file') self.set_from_file(path, args) except: msg, details = get_error_details() LOGGER.error(msg) LOGGER.info(details) for varstr in settings.variables: try: name, value = varstr.split(':', 1) except ValueError: name, value = varstr, '' self['${%s}' % name] = value def _set_built_in_variables(self, settings): for name, value in [('${TEMPDIR}', abspath(tempfile.gettempdir())), ('${EXECDIR}', abspath('.')), ('${/}', os.sep), ('${:}', os.pathsep), ('${\\n}', os.linesep), ('${SPACE}', ' '), ('${True}', True), ('${False}', False), ('${None}', None), ('${null}', None), ('${OUTPUT_DIR}', settings.output_directory), ('${OUTPUT_FILE}', settings.output or 'NONE'), ('${REPORT_FILE}', settings.report or 'NONE'), ('${LOG_FILE}', settings.log or 'NONE'), ('${DEBUG_FILE}', settings.debug_file or 'NONE'), ('${LOG_LEVEL}', settings.log_level), ('${PREV_TEST_NAME}', ''), ('${PREV_TEST_STATUS}', ''), ('${PREV_TEST_MESSAGE}', '')]: self[name] = value class SetVariables(object): def __init__(self): self._suite = None self._test = None self._scopes = [] def start_suite(self): if not self._scopes: self._suite = NormalizedDict(ignore='_') else: self._suite = self._scopes[-1].copy() self._scopes.append(self._suite) def end_suite(self): self._scopes.pop() self._suite = self._scopes[-1] if self._scopes else None def start_test(self): self._test = self._scopes[-1].copy() self._scopes.append(self._test) def end_test(self): self._test = None self._scopes.pop() def start_keyword(self): self._scopes.append(self._scopes[-1].copy()) def end_keyword(self): self._scopes.pop() def set_global(self, name, value): for scope in self._scopes: if name in scope: scope.pop(name) def set_suite(self, name, value): self._suite[name] = value def set_test(self, name, value): for scope in reversed(self._scopes): scope[name] = value if scope is self._test: break def set_keyword(self, name, value): self._scopes[-1][name] = value def update(self, variables): for name, value in self._scopes[-1].items(): variables[name] = value
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/variables/scopes.py
0.546254
0.16529
scopes.py
pypi
from six import text_type as unicode from contextlib import contextmanager from robot.errors import DataError from robot.utils import split_from_equals, unic, is_string, DotDict from .isvar import validate_var from .splitter import VariableSplitter class VariableTableSetter(object): def __init__(self, store): self._store = store def set(self, variables, overwrite=False): for name, value in VariableTableReader().read(variables): self._store.add(name, value, overwrite, decorated=False) class VariableTableReader(object): def read(self, variables): for var in variables: if not var: continue try: yield self._get_name_and_value(var.name, var.value, var.report_invalid_syntax) except DataError as err: var.report_invalid_syntax(err) def _get_name_and_value(self, name, value, error_reporter): return name[2:-1], VariableTableValue(value, name, error_reporter) def VariableTableValue(value, name, error_reporter=None): validate_var(name) VariableTableValue = {'$': ScalarVariableTableValue, '@': ListVariableTableValue, '&': DictVariableTableValue}[name[0]] return VariableTableValue(value, error_reporter) class VariableTableValueBase(object): def __init__(self, values, error_reporter=None): self._values = self._format_values(values) self._error_reporter = error_reporter self._resolving = False def _format_values(self, values): return values def resolve(self, variables): with self._avoid_recursion: return self._replace_variables(self._values, variables) @property @contextmanager def _avoid_recursion(self): if self._resolving: raise DataError('Recursive variable definition.') self._resolving = True try: yield finally: self._resolving = False def _replace_variables(self, value, variables): raise NotImplementedError def report_error(self, error): if self._error_reporter: self._error_reporter(unicode(error)) class ScalarVariableTableValue(VariableTableValueBase): def _format_values(self, values): separator = None if is_string(values): values = [values] elif values and values[0].startswith('SEPARATOR='): separator = values.pop(0)[10:] return separator, values def _replace_variables(self, values, variables): separator, values = values if (separator is None and len(values) == 1 and not VariableSplitter(values[0]).is_list_variable()): return variables.replace_scalar(values[0]) if separator is None: separator = ' ' separator = variables.replace_string(separator) values = variables.replace_list(values) return separator.join(unic(item) for item in values) class ListVariableTableValue(VariableTableValueBase): def _replace_variables(self, values, variables): return variables.replace_list(values) class DictVariableTableValue(VariableTableValueBase): def _format_values(self, values): return list(self._yield_formatted(values)) def _yield_formatted(self, values): for item in values: if VariableSplitter(item).is_dict_variable(): yield item else: name, value = split_from_equals(item) if value is None: raise DataError("Dictionary item '%s' does not contain " "'=' separator." % item) yield name, value def _replace_variables(self, values, variables): try: return DotDict(self._yield_replaced(values, variables.replace_scalar)) except TypeError as err: raise DataError('Creating dictionary failed: %s' % err) def _yield_replaced(self, values, replace_scalar): for item in values: if isinstance(item, tuple): key, values = item yield replace_scalar(key), replace_scalar(values) else: for key, values in replace_scalar(item).items(): yield key, values
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/variables/tablesetter.py
0.591251
0.260754
tablesetter.py
pypi
from robot.errors import DataError, VariableError from robot.output import LOGGER from robot.utils import escape, unescape, unic, is_string from .splitter import VariableSplitter class VariableReplacer(object): def __init__(self, variables): self._variables = variables def replace_list(self, items, replace_until=None): """Replaces variables from a list of items. If an item in a list is a @{list} variable its value is returned. Possible variables from other items are replaced using 'replace_scalar'. Result is always a list. 'replace_until' can be used to limit replacing arguments to certain index from the beginning. Used with Run Keyword variants that only want to resolve some of the arguments in the beginning and pass others to called keywords unmodified. """ items = list(items or []) if replace_until is not None: return self._replace_list_until(items, replace_until) return list(self._replace_list(items)) def _replace_list_until(self, items, replace_until): # @{list} variables can contain more or less arguments than needed. # Therefore we need to go through items one by one, and escape possible # extra items we got. replaced = [] while len(replaced) < replace_until and items: replaced.extend(self._replace_list([items.pop(0)])) if len(replaced) > replace_until: replaced[replace_until:] = [escape(item) for item in replaced[replace_until:]] return replaced + items def _replace_list(self, items): for item in items: if self._cannot_have_variables(item): yield unescape(item) else: splitter = VariableSplitter(item) value = self._replace_scalar(item, splitter) if splitter.is_list_variable(): for v in value: yield v else: yield value def replace_scalar(self, item): """Replaces variables from a scalar item. If the item is not a string it is returned as is. If it is a ${scalar} variable its value is returned. Otherwise variables are replaced with 'replace_string'. Result may be any object. """ if self._cannot_have_variables(item): return unescape(item) return self._replace_scalar(item) def _replace_scalar(self, item, splitter=None): if not splitter: splitter = VariableSplitter(item) if not splitter.identifier: return unescape(item) if splitter.is_variable(): return self._get_variable(splitter) return self._replace_string(item, splitter) def _cannot_have_variables(self, item): return not (is_string(item) and '{' in item) def replace_string(self, string, ignore_errors=False): """Replaces variables from a string. Result is always a string.""" if not is_string(string): return unic(string) if self._cannot_have_variables(string): return unescape(string) return self._replace_string(string, ignore_errors=ignore_errors) def _replace_string(self, string, splitter=None, ignore_errors=False): if not splitter: splitter = VariableSplitter(string) return ''.join(self._yield_replaced(string, splitter, ignore_errors)) def _yield_replaced(self, string, splitter, ignore_errors=False): while splitter.identifier: yield unescape(string[:splitter.start]) try: value = self._get_variable(splitter) except DataError: if not ignore_errors: raise value = string[splitter.start:splitter.end] yield unic(value) string = string[splitter.end:] splitter = VariableSplitter(string) yield unescape(string) def _get_variable(self, splitter): if splitter.identifier not in '$@&%': return self._get_reserved_variable(splitter) if splitter.index is None: return self._get_normal_variable(splitter) if splitter.identifier == '@': return self._get_list_variable_item(splitter) return self._get_dict_variable_item(splitter) def _get_reserved_variable(self, splitter): value = splitter.get_replaced_variable(self) LOGGER.warn("Syntax '%s' is reserved for future use. Please " "escape it like '\\%s'." % (value, value)) return value def _get_normal_variable(self, splitter): name = splitter.get_replaced_variable(self) return self._variables[name] def _get_list_variable_item(self, splitter): name = splitter.get_replaced_variable(self) variable = self._variables[name] index = self.replace_string(splitter.index) try: index = int(index) except ValueError: raise VariableError("List variable '%s' used with invalid index '%s'." % (name, index)) try: return variable[index] except IndexError: raise VariableError("List variable '%s' has no item in index %d." % (name, index)) def _get_dict_variable_item(self, splitter): name = splitter.get_replaced_variable(self) variable = self._variables[name] key = self.replace_scalar(splitter.index) try: return variable[key] except KeyError: raise VariableError("Dictionary variable '%s' has no key '%s'." % (name, key)) except TypeError as err: raise VariableError("Dictionary variable '%s' used with invalid key: %s" % (name, err))
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/variables/replacer.py
0.799168
0.314406
replacer.py
pypi
import inspect try: import yaml except ImportError: yaml = None from robot.errors import DataError from robot.output import LOGGER from robot.utils import (get_error_message, is_dict_like, is_list_like, is_string, seq2str2, type_name, DotDict, Importer) class VariableFileSetter(object): def __init__(self, store): self._store = store def set(self, path_or_variables, args=None, overwrite=False): variables = self._import_if_needed(path_or_variables, args) self._set(variables, overwrite) return variables def _import_if_needed(self, path_or_variables, args=None): if not is_string(path_or_variables): return path_or_variables LOGGER.info("Importing variable file '%s' with args %s" % (path_or_variables, args)) if path_or_variables.lower().endswith('.yaml'): importer = YamlImporter() else: importer = PythonImporter() try: return importer.import_variables(path_or_variables, args) except: args = 'with arguments %s ' % seq2str2(args) if args else '' raise DataError("Processing variable file '%s' %sfailed: %s" % (path_or_variables, args, get_error_message())) def _set(self, variables, overwrite=False): for name, value in variables: self._store.add(name, value, overwrite) class YamlImporter(object): def __init__(self): if not yaml: raise DataError('Using YAML variable files requires PyYAML module ' 'to be installed. Typically you can install it ' 'by running `pip install pyyaml`.') def import_variables(self, path, args=None): if args: raise DataError('YAML variable files do not accept arguments.') variables = self._import(path) return [('${%s}' % name, self._dot_dict(value)) for name, value in variables] def _import(self, path): with open(path) as stream: variables = yaml.load(stream) if not is_dict_like(variables): raise DataError('YAML variable file must be a mapping, got %s.' % type_name(variables)) return variables.items() def _dot_dict(self, value): if is_dict_like(value): value = DotDict((n, self._dot_dict(v)) for n, v in value.items()) return value class PythonImporter(object): def import_variables(self, path, args=None): importer = Importer('variable file').import_class_or_module_by_path var_file = importer(path, instantiate_with_args=()) return self._get_variables(var_file, args) def _get_variables(self, var_file, args): if self._is_dynamic(var_file): variables = self._get_dynamic(var_file, args) else: variables = self._get_static(var_file) return list(self._decorate_and_validate(variables)) def _is_dynamic(self, var_file): return (hasattr(var_file, 'get_variables') or hasattr(var_file, 'getVariables')) def _get_dynamic(self, var_file, args): get_variables = (getattr(var_file, 'get_variables', None) or getattr(var_file, 'getVariables')) variables = get_variables(*args) if is_dict_like(variables): return variables.items() raise DataError("Expected '%s' to return dict-like value, got %s." % (get_variables.__name__, type_name(variables))) def _get_static(self, var_file): names = [attr for attr in dir(var_file) if not attr.startswith('_')] if hasattr(var_file, '__all__'): names = [name for name in names if name in var_file.__all__] variables = [(name, getattr(var_file, name)) for name in names] if not inspect.ismodule(var_file): variables = [(n, v) for n, v in variables if not callable(v)] return variables def _decorate_and_validate(self, variables): for name, value in variables: name = self._decorate(name) self._validate(name, value) yield name, value def _decorate(self, name): if name.startswith('LIST__'): return '@{%s}' % name[6:] if name.startswith('DICT__'): return '&{%s}' % name[6:] return '${%s}' % name def _validate(self, name, value): if name[0] == '@' and not is_list_like(value): raise DataError("Invalid variable '%s': Expected list-like value, " "got %s." % (name, type_name(value))) if name[0] == '&' and not is_dict_like(value): raise DataError("Invalid variable '%s': Expected dict-like value, " "got %s." % (name, type_name(value)))
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/variables/filesetter.py
0.506103
0.152379
filesetter.py
pypi
from robot.utils import is_string class VariableSplitter(object): def __init__(self, string, identifiers='$@%&*'): self.identifier = None self.base = None self.index = None self.start = -1 self.end = -1 self._identifiers = identifiers self._may_have_internal_variables = False if not is_string(string): self._max_end = -1 return self._max_end = len(string) try: self._split(string) except ValueError: pass else: self._finalize() def get_replaced_variable(self, replacer): if self._may_have_internal_variables: base = replacer.replace_string(self.base) else: base = self.base # This omits possible list/dict variable index. return '%s{%s}' % (self.identifier, base) def is_variable(self): return bool(self.identifier and self.base and self.start == 0 and self.end == self._max_end) def is_list_variable(self): return bool(self.identifier == '@' and self.base and self.start == 0 and self.end == self._max_end and self.index is None) def is_dict_variable(self): return bool(self.identifier == '&' and self.base and self.start == 0 and self.end == self._max_end and self.index is None) def _finalize(self): self.identifier = self._variable_chars[0] self.base = ''.join(self._variable_chars[2:-1]) self.end = self.start + len(self._variable_chars) if self._has_index(): self.index = ''.join(self._index_chars[1:-1]) self.end += len(self._index_chars) def _has_index(self): return self._index_chars and self._index_chars[-1] == ']' def _split(self, string): start_index, max_index = self._find_variable(string) self.start = start_index self._open_curly = 1 self._state = self._variable_state self._variable_chars = [string[start_index], '{'] self._index_chars = [] self._string = string start_index += 2 for index, char in enumerate(string[start_index:]): index += start_index # Giving start to enumerate only in Py 2.6+ try: self._state(char, index) except StopIteration: return if index == max_index and not self._scanning_index(): return def _scanning_index(self): return self._state in (self._waiting_index_state, self._index_state) def _find_variable(self, string): max_end_index = string.rfind('}') if max_end_index == -1: raise ValueError('No variable end found') if self._is_escaped(string, max_end_index): return self._find_variable(string[:max_end_index]) start_index = self._find_start_index(string, 1, max_end_index) if start_index == -1: raise ValueError('No variable start found') return start_index, max_end_index def _find_start_index(self, string, start, end): while True: index = string.find('{', start, end) - 1 if index < 0: return -1 if self._start_index_is_ok(string, index): return index start = index + 2 def _start_index_is_ok(self, string, index): return string[index] in self._identifiers \ and not self._is_escaped(string, index) def _is_escaped(self, string, index): escaped = False while index > 0 and string[index-1] == '\\': index -= 1 escaped = not escaped return escaped def _variable_state(self, char, index): self._variable_chars.append(char) if char == '}' and not self._is_escaped(self._string, index): self._open_curly -= 1 if self._open_curly == 0: if not self._can_contain_index(): raise StopIteration self._state = self._waiting_index_state elif char in self._identifiers: self._state = self._internal_variable_start_state def _can_contain_index(self): return self._variable_chars[0] in '@&' def _internal_variable_start_state(self, char, index): self._state = self._variable_state if char == '{': self._variable_chars.append(char) self._open_curly += 1 self._may_have_internal_variables = True else: self._variable_state(char, index) def _waiting_index_state(self, char, index): if char != '[': raise StopIteration self._index_chars.append(char) self._state = self._index_state def _index_state(self, char, index): self._index_chars.append(char) if char == ']': raise StopIteration class VariableIterator(object): def __init__(self, string, identifiers='$@%&*'): self._string = string self._identifiers = identifiers def __iter__(self): string = self._string while True: var = VariableSplitter(string, self._identifiers) if var.identifier is None: break before = string[:var.start] variable = '%s{%s}' % (var.identifier, var.base) string = string[var.end:] yield before, variable, string def __len__(self): return sum(1 for _ in self) def __bool__(self): try: next(iter(self)) except StopIteration: return False else: return True #PY2 def __nonzero__(self): return self.__bool__()
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/variables/splitter.py
0.468061
0.27027
splitter.py
pypi
import re from six.moves import zip from itertools import chain from robot.errors import DataError from robot.utils import (format_assign_message, get_error_message, prepr, type_name, is_number, is_string) class VariableAssigner(object): _valid_extended_attr = re.compile('^[_a-zA-Z]\w*$') def __init__(self, assignment): validator = AssignmentValidator() try: self.assignment = [validator.validate(var) for var in assignment] self.error = None except DataError as err: self.assignment = assignment self.error = err def validate_assignment(self): if self.error: raise self.error def assign(self, context, return_value): self.validate_assignment() context.trace(lambda: 'Return: %s' % prepr(return_value)) resolver = ReturnValueResolver(self.assignment) for name, value in resolver.resolve(return_value): if not self._extended_assign(name, value, context.variables): value = self._normal_assign(name, value, context.variables) context.info(format_assign_message(name, value)) def _extended_assign(self, name, value, variables): if name[0] != '$' or '.' not in name or name in variables: return False base, attr = self._split_extended_assign(name) try: var = variables[base] except DataError: return False if not (self._variable_supports_extended_assign(var) and self._is_valid_extended_attribute(attr)): return False try: setattr(var, attr, value) except: raise DataError("Setting attribute '%s' to variable '%s' failed: %s" % (attr, base, get_error_message())) return True def _split_extended_assign(self, name): base, attr = name.rsplit('.', 1) return base.strip() + '}', attr[:-1].strip() def _variable_supports_extended_assign(self, var): return not (is_string(var) or is_number(var)) def _is_valid_extended_attribute(self, attr): return self._valid_extended_attr.match(attr) is not None def _normal_assign(self, name, value, variables): variables[name] = value return variables[name] class AssignmentValidator(object): def __init__(self): self._seen_list = False self._seen_dict = False self._seen_any_var = False self._seen_assign_mark = False def validate(self, variable): variable = self._validate_assign_mark(variable) self._validate_state(is_list=variable[0] == '@', is_dict=variable[0] == '&') return variable def _validate_assign_mark(self, variable): if self._seen_assign_mark: raise DataError("Assign mark '=' can be used only with the last " "variable.") self._seen_assign_mark = variable.endswith('=') return variable.rstrip('= ') def _validate_state(self, is_list, is_dict): if is_list and self._seen_list: raise DataError('Assignment can contain only one list variable.') if self._seen_dict or is_dict and self._seen_any_var: raise DataError('Dictionary variable cannot be assigned with ' 'other variables.') self._seen_list += is_list self._seen_dict += is_dict self._seen_any_var = True def ReturnValueResolver(assignment): if not assignment: return NoReturnValueResolver() if len(assignment) == 1: return OneReturnValueResolver(assignment[0]) if any(a[0] == '@' for a in assignment): return ScalarsAndListReturnValueResolver(assignment) return ScalarsOnlyReturnValueResolver(assignment) class NoReturnValueResolver(object): def resolve(self, return_value): return [] class OneReturnValueResolver(object): def __init__(self, variable): self._variable = variable def resolve(self, return_value): if return_value is None: identifier = self._variable[0] return_value = {'$': None, '@': [], '&': {}}[identifier] return [(self._variable, return_value)] class _MultiReturnValueResolver(object): def __init__(self, variables): self._variables = variables self._min_count = len(variables) def resolve(self, return_value): return_value = self._convert_to_list(return_value) self._validate(len(return_value)) return self._resolve(return_value) def _convert_to_list(self, return_value): if return_value is None: return [None] * self._min_count if is_string(return_value): self._raise_expected_list(return_value) try: return list(return_value) except TypeError: self._raise_expected_list(return_value) def _raise_expected_list(self, ret): self._raise('Expected list-like value, got %s.' % type_name(ret)) def _raise(self, error): raise DataError('Cannot set variables: %s' % error) def _validate(self, return_count): raise NotImplementedError def _resolve(self, return_value): raise NotImplementedError class ScalarsOnlyReturnValueResolver(_MultiReturnValueResolver): def _validate(self, return_count): if return_count != self._min_count: self._raise('Expected %d return values, got %d.' % (self._min_count, return_count)) def _resolve(self, return_value): return zip(self._variables, return_value) class ScalarsAndListReturnValueResolver(_MultiReturnValueResolver): def __init__(self, variables): _MultiReturnValueResolver.__init__(self, variables) self._min_count -= 1 def _validate(self, return_count): if return_count < self._min_count: self._raise('Expected %d or more return values, got %d.' % (self._min_count, return_count)) def _resolve(self, return_value): before_vars, list_var, after_vars \ = self._split_variables(self._variables) before_items, list_items, after_items \ = self._split_return(return_value, before_vars, after_vars) return list(chain(zip(before_vars, before_items), [(list_var, list_items)], zip(after_vars, after_items))) def _split_variables(self, variables): list_index = [v[0] for v in variables].index('@') return (variables[:list_index], variables[list_index], variables[list_index+1:]) def _split_return(self, return_value, before_vars, after_vars): list_start = len(before_vars) list_end = len(return_value) - len(after_vars) return (return_value[:list_start], return_value[list_start:list_end], return_value[list_end:])
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/variables/assigner.py
0.533397
0.201106
assigner.py
pypi
import logging from robot.output import librarylogger from robot.running.context import EXECUTION_CONTEXTS 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``. """ if EXECUTION_CONTEXTS.current is not None: librarylogger.write(msg, level, html) else: logger = logging.getLogger("RobotFramework") level = {'TRACE': logging.DEBUG//2, 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'HTML': logging.INFO, 'WARN': logging.WARN, 'ERROR': logging.ERROR}[level] logger.log(level, msg) def trace(msg, html=False): """Writes the message to the log file using the ``TRACE`` level.""" write(msg, 'TRACE', html) def debug(msg, html=False): """Writes the message to the log file using the ``DEBUG`` level.""" write(msg, 'DEBUG', 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. """ write(msg, 'INFO', html) if also_console: console(msg) def warn(msg, html=False): """Writes the message to the log file using the ``WARN`` level.""" write(msg, 'WARN', html) def error(msg, html=False): """Writes the message to the log file using the ``ERROR`` level.""" write(msg, 'ERROR', 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)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/api/logger.py
0.633524
0.270081
logger.py
pypi
import os from robot.result.visitor import ResultVisitor from robot.utils import XmlWriter class XUnitWriter(object): def __init__(self, execution_result, skip_noncritical): self._execution_result = execution_result self._skip_noncritical = skip_noncritical def write(self, output): writer = XUnitFileWriter(XmlWriter(output, encoding='UTF-8'), self._skip_noncritical) self._execution_result.visit(writer) class XUnitFileWriter(ResultVisitor): """Provides an xUnit-compatible result file. Attempts to adhere to the de facto schema guessed by Peter Reilly, see: http://marc.info/?l=ant-dev&m=123551933508682 """ def __init__(self, xml_writer, skip_noncritical=False): self._writer = xml_writer self._root_suite = None self._skip_noncritical = skip_noncritical def start_suite(self, suite): if self._root_suite: return self._root_suite = suite tests, failures, skip = self._get_stats(suite.statistics) attrs = {'name': suite.name, 'tests': tests, 'errors': '0', 'failures': failures, 'skip': skip} self._writer.start('testsuite', attrs) def _get_stats(self, statistics): if self._skip_noncritical: failures = statistics.critical.failed skip = statistics.all.total - statistics.critical.total else: failures = statistics.all.failed skip = 0 return str(statistics.all.total), str(failures), str(skip) def end_suite(self, suite): if suite is self._root_suite: self._writer.end('testsuite') def visit_test(self, test): self._writer.start('testcase', {'classname': test.parent.longname, 'name': test.name, 'time': self._time_as_seconds(test.elapsedtime)}) if self._skip_noncritical and not test.critical: self._skip_test(test) elif not test.passed: self._fail_test(test) self._writer.end('testcase') def _skip_test(self, test): self._writer.element('skipped', '%s: %s' % (test.status, test.message) if test.message else test.status) def _fail_test(self, test): self._writer.element('failure', attrs={'message': test.message, 'type': 'AssertionError'}) def _time_as_seconds(self, millis): return str(int(round(millis, -3) / 1000)) def visit_keyword(self, kw): pass def visit_statistics(self, stats): pass def visit_errors(self, errors): pass def end_result(self, result): self._writer.close()
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/reporting/xunitwriter.py
0.628179
0.214105
xunitwriter.py
pypi
from six import text_type as unicode from robot.conf import RebotSettings from robot.errors import DataError from robot.model import ModelModifier from robot.output import LOGGER from robot.result import ExecutionResult, Result from robot.utils import unic from .jsmodelbuilders import JsModelBuilder from .logreportwriters import LogWriter, ReportWriter from .xunitwriter import XUnitWriter class ResultWriter(object): """A class to create log, report, output XML and xUnit files. :param sources: Either one :class:`~robot.result.executionresult.Result` object, or one or more paths to existing output XML files. By default writes ``report.html`` and ``log.html``, but no output XML or xUnit files. Custom file names can be given and results disabled or enabled using ``settings`` or ``options`` passed to the :meth:`write_results` method. The latter is typically more convenient:: writer = ResultWriter(result) writer.write_results(report='custom.html', log=None, xunit='xunit.xml') """ def __init__(self, *sources): self._sources = sources def write_results(self, settings=None, **options): """Writes results based on the given ``settings`` or ``options``. :param settings: :class:`~robot.conf.settings.RebotSettings` object to configure result writing. :param options: Used to construct new :class:`~robot.conf.settings.RebotSettings` object if ``settings`` are not given. """ settings = settings or RebotSettings(options) results = Results(settings, *self._sources) if settings.output: self._write_output(results.result, settings.output) if settings.xunit: self._write_xunit(results.result, settings.xunit, settings.xunit_skip_noncritical) if settings.log: config = dict(settings.log_config, minLevel=results.js_result.min_level) self._write_log(results.js_result, settings.log, config) if settings.report: results.js_result.remove_data_not_needed_in_report() self._write_report(results.js_result, settings.report, settings.report_config) return results.return_code def _write_output(self, result, path): self._write('Output', result.save, path) def _write_xunit(self, result, path, skip_noncritical): self._write('XUnit', XUnitWriter(result, skip_noncritical).write, path) def _write_log(self, js_result, path, config): self._write('Log', LogWriter(js_result).write, path, config) def _write_report(self, js_result, path, config): self._write('Report', ReportWriter(js_result).write, path, config) def _write(self, name, writer, path, *args): try: writer(path, *args) except DataError as err: LOGGER.error(unicode(err)) except EnvironmentError as err: # `err.filename` can be different than `path` at least if reading # log/report templates or writing split log fails. # `unic` is needed due to http://bugs.jython.org/issue1825. LOGGER.error("Writing %s file '%s' failed: %s: %s" % (name.lower(), path, err.strerror, unic(err.filename))) else: LOGGER.output_file(name, path) class Results(object): def __init__(self, settings, *sources): self._settings = settings self._sources = sources if len(sources) == 1 and isinstance(sources[0], Result): self._result = sources[0] self._prune = False self.return_code = self._result.return_code else: self._result = None self._prune = True self.return_code = -1 self._js_result = None @property def result(self): if self._result is None: include_keywords = bool(self._settings.log or self._settings.output) flattened = self._settings.flatten_keywords self._result = ExecutionResult(include_keywords=include_keywords, flattened_keywords=flattened, merge=self._settings.merge, *self._sources) self._result.configure(self._settings.status_rc, self._settings.suite_config, self._settings.statistics_config) modifier = ModelModifier(self._settings.pre_rebot_modifiers, self._settings.process_empty_suite, LOGGER) self._result.suite.visit(modifier) self.return_code = self._result.return_code return self._result @property def js_result(self): if self._js_result is None: builder = JsModelBuilder(log_path=self._settings.log, split_log=self._settings.split_log, prune_input_to_save_memory=self._prune) self._js_result = builder.build_from(self.result) if self._prune: self._result = None return self._js_result
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/reporting/resultwriter.py
0.824462
0.202089
resultwriter.py
pypi
import re from robot.output import LOGGER 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): # TODO: Remove support for olde style metadata in RF 2.10. LOGGER.warn("Setting suite metadata using '%s' syntax is deprecated. " "Use 'Metadata' setting with name and value in separate " "cells instead." % self.head) 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 __bool__(self): return bool(self.cells or self.comments) #PY2 def __nonzero__(self): return self.__bool__()
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/parsing/datarow.py
0.475849
0.407982
datarow.py
pypi
import os import copy from robot.errors import DataError from robot.variables import is_var from robot.output import LOGGER from robot.writer import DataFileWriter from robot.utils import abspath, is_string, normalize, NormalizedDict 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 = abspath(source) if source else None self.children = [] self._tables = 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 __bool__(self): return bool(self._header or len(self)) #PY2 def __nonzero__(self): return self.__bool__() 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 = 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 __bool__(self): return True #PY2 def __nonzero__(self): return self.__bool__() 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 is_string(value): value = [value] 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 __bool__(self): return self.has_data() #PY2 def __nonzero__(self): return self.__bool__() 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.tags = Tags('[Tags]', 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, 'tags': lambda s: s.tags.populate} def _add_to_parent(self, test): self.parent.keywords.append(test) @property def settings(self): return [self.args, self.doc, self.tags, self.timeout, self.teardown, self.return_] def __iter__(self): for element in [self.args, self.doc, self.tags, self.timeout] \ + self.steps + [self.teardown, self.return_]: yield element class ForLoop(_WithSteps): """The parsed representation of a for-loop. :param list declaration: The literal cell values that declare the loop (excluding ":FOR"). :param str comment: A comment, default None. :ivar str flavor: The value of the 'IN' item, uppercased. Typically 'IN', 'IN RANGE', 'IN ZIP', or 'IN ENUMERATE'. :ivar list vars: Variables set per-iteration by this loop. :ivar list items: Loop values that come after the 'IN' item. :ivar str comment: A comment, or None. :ivar list steps: A list of steps in the loop. """ def __init__(self, declaration, comment=None): self.flavor, index = self._get_flavors_and_index(declaration) self.vars = declaration[:index] self.items = declaration[index+1:] self.comment = Comment(comment) self.steps = [] def _get_flavors_and_index(self, declaration): for index, item in enumerate(declaration): item = item.upper() if item.replace(' ', '').startswith('IN'): return item, index return 'IN', len(declaration) def is_comment(self): return False def is_for_loop(self): return True def as_list(self, indent=False, include_comment=True): comments = self.comment.as_list() if include_comment else [] return [': FOR'] + self.vars + [self.flavor] + 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.name = content[len(self.assign)] except IndexError: self.name = 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.name 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.name] if self.name 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
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/parsing/model.py
0.695752
0.255715
model.py
pypi
from six import text_type as unicode from contextlib import contextmanager from robot.errors import DataError class ExecutionContexts(object): def __init__(self): self._contexts = [] @property def current(self): return self._contexts[-1] if self._contexts else None @property def top(self): return self._contexts[0] if self._contexts else None def __iter__(self): return iter(self._contexts) @property def namespaces(self): return (context.namespace for context in self) def start_suite(self, namespace, output, dry_run=False): self._contexts.append(_ExecutionContext(namespace, output, dry_run)) return self.current def end_suite(self): self._contexts.pop() # This is ugly but currently needed e.g. by BuiltIn EXECUTION_CONTEXTS = ExecutionContexts() class _ExecutionContext(object): _started_keywords_threshold = 42 # Jython on Windows don't work with higher def __init__(self, namespace, output, dry_run=False): self.namespace = namespace self.output = output self.dry_run = dry_run self.in_suite_teardown = False self.in_test_teardown = False self.in_keyword_teardown = 0 self._started_keywords = 0 self.timeout_occurred = False self.failure_in_test_teardown = False # TODO: namespace should not have suite, test, or uk_handlers. @property def suite(self): return self.namespace.suite @property def test(self): return self.namespace.test @property def keywords(self): return self.namespace.uk_handlers @contextmanager def suite_teardown(self): self.in_suite_teardown = True try: yield finally: self.in_suite_teardown = False @contextmanager def test_teardown(self, test): self.variables.set_test('${TEST_STATUS}', test.status) self.variables.set_test('${TEST_MESSAGE}', test.message) self.in_test_teardown = True try: yield finally: self.in_test_teardown = False self.failure_in_test_teardown = False @contextmanager def keyword_teardown(self, error): self.variables.set_keyword('${KEYWORD_STATUS}', 'FAIL' if error else 'PASS') self.variables.set_keyword('${KEYWORD_MESSAGE}', unicode(error or '')) self.in_keyword_teardown += 1 try: yield finally: self.in_keyword_teardown -= 1 @contextmanager def user_keyword(self, kw): self.namespace.start_user_keyword(kw) try: yield finally: self.namespace.end_user_keyword() @property def in_teardown(self): return bool(self.in_suite_teardown or self.in_test_teardown or self.in_keyword_teardown) @property def variables(self): return self.namespace.variables # TODO: Move start_suite here from EXECUTION_CONTEXT def end_suite(self, suite): for name in ['${PREV_TEST_NAME}', '${PREV_TEST_STATUS}', '${PREV_TEST_MESSAGE}']: self.variables.set_global(name, self.variables[name]) self.output.end_suite(suite) self.namespace.end_suite() EXECUTION_CONTEXTS.end_suite() def set_suite_variables(self, suite): self.variables['${SUITE_NAME}'] = suite.longname self.variables['${SUITE_SOURCE}'] = suite.source or '' self.variables['${SUITE_DOCUMENTATION}'] = suite.doc self.variables['${SUITE_METADATA}'] = suite.metadata.copy() def report_suite_status(self, status, message): self.variables['${SUITE_STATUS}'] = status self.variables['${SUITE_MESSAGE}'] = message def start_test(self, test): self.namespace.start_test(test) self.variables.set_test('${TEST_NAME}', test.name) self.variables.set_test('${TEST_DOCUMENTATION}', test.doc) self.variables.set_test('@{TEST_TAGS}', list(test.tags)) def end_test(self, test): self.namespace.end_test() self.variables.set_suite('${PREV_TEST_NAME}', test.name) self.variables.set_suite('${PREV_TEST_STATUS}', test.status) self.variables.set_suite('${PREV_TEST_MESSAGE}', test.message) self.timeout_occurred = False # Should not need separate start/end_keyword and start/end_user_keyword def start_keyword(self, keyword): self._started_keywords += 1 if self._started_keywords > self._started_keywords_threshold: raise DataError('Maximum limit of started keywords exceeded.') self.output.start_keyword(keyword) def end_keyword(self, keyword): self.output.end_keyword(keyword) self._started_keywords -= 1 if self.in_test_teardown and not keyword.passed: self.failure_in_test_teardown = True def get_handler(self, name): return self.namespace.get_handler(name) def trace(self, message): self.output.trace(message) def debug(self, message): self.output.debug(message) def info(self, message): self.output.info(message) def warn(self, message): self.output.warn(message) def fail(self, message): self.output.fail(message)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/running/context.py
0.449151
0.213726
context.py
pypi
from robot.errors import DataError from robot.utils import (get_error_message, unic, is_java_method, is_string, is_unicode) from .arguments import JavaArgumentParser, PythonArgumentParser def no_dynamic_method(*args): pass class _DynamicMethod(object): _underscore_name = NotImplemented def __init__(self, lib): self.method = self._get_method(lib) def _get_method(self, lib): for name in self._underscore_name, self._camelCaseName: method = getattr(lib, name, None) if callable(method): return method return no_dynamic_method @property def _camelCaseName(self): tokens = self._underscore_name.split('_') return ''.join([tokens[0]] + [t.capitalize() for t in tokens[1:]]) @property def name(self): return self.method.__name__ def __call__(self, *args): try: return self._handle_return_value(self.method(*args)) except: raise DataError("Calling dynamic method '%s' failed: %s" % (self.method.__name__, get_error_message())) def _handle_return_value(self, value): raise NotImplementedError def _to_string(self, value): if not is_string(value): raise DataError('Return value must be string.') return value if is_unicode(value) else unic(value, 'UTF-8') def _to_list_of_strings(self, value): try: return [self._to_string(v) for v in value] except (TypeError, DataError): raise DataError('Return value must be list of strings.') def __bool__(self): return self.method is not no_dynamic_method #PY2 def __nonzero__(self): return self.__bool__() class GetKeywordNames(_DynamicMethod): _underscore_name = 'get_keyword_names' def _handle_return_value(self, value): return self._to_list_of_strings(value or []) class RunKeyword(_DynamicMethod): _underscore_name = 'run_keyword' @property def supports_kwargs(self): if is_java_method(self.method): return self._supports_java_kwargs(self.method) return self._supports_python_kwargs(self.method) def _supports_python_kwargs(self, method): spec = PythonArgumentParser().parse(method) return len(spec.positional) == 3 def _supports_java_kwargs(self, method): func = self.method.__func__ if hasattr(method, 'im_func') else method signatures = func.argslist[:func.nargs] spec = JavaArgumentParser().parse(signatures) return (self._java_single_signature_kwargs(spec) or self._java_multi_signature_kwargs(spec)) def _java_single_signature_kwargs(self, spec): return len(spec.positional) == 1 and spec.varargs and spec.kwargs def _java_multi_signature_kwargs(self, spec): return len(spec.positional) == 3 and not (spec.varargs or spec.kwargs) class GetKeywordDocumentation(_DynamicMethod): _underscore_name = 'get_keyword_documentation' def _handle_return_value(self, value): return self._to_string(value or '') class GetKeywordArguments(_DynamicMethod): _underscore_name = 'get_keyword_arguments' def __init__(self, lib): _DynamicMethod.__init__(self, lib) self._supports_kwargs = RunKeyword(lib).supports_kwargs def _handle_return_value(self, value): if value is None: if self._supports_kwargs: return ['*varargs', '**kwargs'] return ['*varargs'] return self._to_list_of_strings(value)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/running/dynamicmethods.py
0.785638
0.240418
dynamicmethods.py
pypi
import warnings from robot import model from robot.conf import RobotSettings from robot.output import LOGGER, Output, pyloggingconf from robot.utils import setter from .randomizer import Randomizer class Keyword(model.Keyword): """Running model for single keyword.""" __slots__ = [] message_class = None # TODO: Remove from base model? def run(self, context): from .keywordrunner import KeywordRunner return KeywordRunner(context).run_keyword(self) class ForLoop(Keyword): __slots__ = ['flavor'] keyword_class = Keyword def __init__(self, variables, values, flavor): Keyword.__init__(self, assign=variables, args=values, type=Keyword.FOR_LOOP_TYPE) self.flavor = flavor @property def variables(self): return self.assign @property def values(self): return self.args class TestCase(model.TestCase): """Running model for single test case.""" __slots__ = ['template'] keyword_class = Keyword def __init__(self, name='', doc='', tags=None, timeout=None, template=None): model.TestCase.__init__(self, name, doc, tags, timeout) #: Name of the keyword that has been used as template #: when building the test. `None` if no is template used. self.template = template @setter def timeout(self, timeout): """Timeout limit of the test case as an instance of :class:`~.Timeout. """ return Timeout(*timeout) if timeout else None class TestSuite(model.TestSuite): """Running model for single test suite.""" __slots__ = ['resource'] test_class = TestCase keyword_class = Keyword def __init__(self, name='', doc='', metadata=None, source=None): model.TestSuite.__init__(self, name, doc, metadata, source) #: :class:`ResourceFile` instance containing imports, variables and #: keywords the suite owns. When data is parsed from the file system, #: this data comes from the same test case file that creates the suite. self.resource = ResourceFile(source=source) # TODO: Remote deprecated propertys below in RF 3.0. @property def imports(self): warnings.warn("'TestSuite.imports' is deprecated. Use " "'TestSuite.resource.imports' instead.", DeprecationWarning) return self.resource.imports @property def variables(self): warnings.warn("'TestSuite.variables' is deprecated. Use " "'TestSuite.resource.variables' instead.", DeprecationWarning) return self.resource.variables @property def user_keywords(self): warnings.warn("'TestSuite.user_keywords' is deprecated. Use" "'TestSuite.resource.keywords' instead.", DeprecationWarning) return self.resource.keywords def configure(self, randomize_suites=False, randomize_tests=False, randomize_seed=None, **options): model.TestSuite.configure(self, **options) self.randomize(randomize_suites, randomize_tests, randomize_seed) def randomize(self, suites=True, tests=True, seed=None): """Randomizes the order of suites and/or tests, recursively.""" self.visit(Randomizer(suites, tests, seed)) def run(self, settings=None, **options): """Executes the suite based based the given ``settings`` or ``options``. :param settings: :class:`~robot.conf.settings.RobotSettings` object to configure test execution. :param options: Used to construct new :class:`~robot.conf.settings.RobotSettings` object if ``settings`` are not given. :return: :class:`~robot.result.executionresult.Result` object with information about executed suites and tests. If ``options`` are used, their names are the same as long command line options except without hyphens, and they also have the same semantics. Options that can be given on the command line multiple times can be passed as lists like ``variable=['VAR1:value1', 'VAR2:value2']``. If such an option is used only once, it can be given also as a single string like ``variable='VAR:value'``. Additionally listener option allows passing object directly instead of listener name, e.g. `run('tests.robot', listener=Listener())`. To capture stdout and/or stderr streams, pass open file objects in as special keyword arguments `stdout` and `stderr`, respectively. Note that this works only in version 2.8.4 and newer. Only options related to the actual test execution have an effect. For example, options related to selecting test cases or creating logs and reports are silently ignored. The output XML generated as part of the execution can be configured, though. This includes disabling it with ``output=None``. Example:: stdout = StringIO() result = suite.run(variable='EXAMPLE:value', critical='regression', output='example.xml', exitonfailure=True, stdout=stdout) print result.return_code To save memory, the returned :class:`~robot.result.executionresult.Result` object does not have any information about the executed keywords. If that information is needed, the created output XML file needs to be read using the :class:`~robot.result.resultbuilder.ExecutionResult` factory method. See the :mod:`package level <robot.running>` documentation for more examples, including how to construct executable test suites and how to create logs and reports based on the execution results. See the :func:`robot.run <robot.run.run>` function for a higher-level API for executing tests in files or directories. """ from .namespace import IMPORTER from .signalhandler import STOP_SIGNAL_MONITOR from .runner import Runner with LOGGER: if not settings: settings = RobotSettings(options) LOGGER.register_console_logger(**settings.console_output_config) with pyloggingconf.robot_handler_enabled(settings.log_level): with STOP_SIGNAL_MONITOR: IMPORTER.reset() output = Output(settings) runner = Runner(output, settings) self.visit(runner) output.close(runner.result) return runner.result class Variable(object): def __init__(self, name, value, source=None): # TODO: check name and value self.name = name self.value = value self.source = source def report_invalid_syntax(self, message, level='ERROR'): LOGGER.write("Error in file '%s': Setting variable '%s' failed: %s" % (self.source or '<unknown>', self.name, message), level) class Timeout(object): def __init__(self, value, message=None): self.value = value self.message = message def __str__(self): return self.value class ResourceFile(object): def __init__(self, doc='', source=None): self.doc = doc self.source = source self.imports = [] self.keywords = [] self.variables = [] @setter def imports(self, imports): return model.Imports(self.source, imports) @setter def keywords(self, keywords): return model.ItemList(UserKeyword, items=keywords) @setter def variables(self, variables): return model.ItemList(Variable, {'source': self.source}, items=variables) class UserKeyword(object): def __init__(self, name, args=(), doc='', tags=(), return_=None, timeout=None): self.name = name self.args = args self.doc = doc self.tags = tags self.return_ = return_ or () self.timeout = timeout self.keywords = [] @setter def keywords(self, keywords): return model.Keywords(Keyword, self, keywords) @setter def timeout(self, timeout): """Timeout limit of the keyword as an instance of :class:`~.Timeout. """ return Timeout(*timeout) if timeout else None @setter def tags(self, tags): return model.Tags(tags)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/running/model.py
0.683631
0.292532
model.py
pypi
from six import text_type as unicode from robot.errors import DataError from robot.parsing import TestData, ResourceFile as ResourceData from robot.running.defaults import TestDefaults from robot.utils import abspath, is_string from robot.variables import VariableIterator from .model import ForLoop, ResourceFile, TestSuite class TestSuiteBuilder(object): def __init__(self, include_suites=None, warn_on_skipped=False): """Create programmatically executable :class:`~robot.running.model.TestSuite` objects based on existing data on the file system. See example of usage in :mod:`.running` package. """ self.include_suites = include_suites self.warn_on_skipped = warn_on_skipped self._create_step = StepBuilder().build def build(self, *paths): if not paths: raise DataError('One or more source paths required.') if len(paths) == 1: return self._parse_and_build(paths[0]) root = TestSuite() for path in paths: root.suites.append(self._parse_and_build(path)) return root def _parse_and_build(self, path): suite = self._build_suite(self._parse(path)) suite.remove_empty_suites() return suite def _parse(self, path): try: return TestData(source=abspath(path), include_suites=self.include_suites, warn_on_skipped=self.warn_on_skipped) except DataError as err: raise DataError("Parsing '%s' failed: %s" % (path, unicode(err))) def _build_suite(self, data, parent_defaults=None): defaults = TestDefaults(data.setting_table, parent_defaults) suite = TestSuite(name=data.name, source=data.source, doc=unicode(data.setting_table.doc), metadata=self._get_metadata(data.setting_table)) self._create_setup(suite, data.setting_table.suite_setup) self._create_teardown(suite, data.setting_table.suite_teardown) for test_data in data.testcase_table.tests: self._create_test(suite, test_data, defaults) for child in data.children: suite.suites.append(self._build_suite(child, defaults)) ResourceFileBuilder().build(data, target=suite.resource) return suite def _get_metadata(self, settings): # Must return as a list to preserve ordering return [(meta.name, meta.value) for meta in settings.metadata] def _create_test(self, suite, data, defaults): values = defaults.get_test_values(data) test = suite.tests.create(name=data.name, doc=unicode(data.doc), tags=values.tags.value, template=self._get_template(values.template), timeout=self._get_timeout(values.timeout)) self._create_setup(test, values.setup) for step_data in data.steps: self._create_step(test, step_data, template=values.template) self._create_teardown(test, values.teardown) def _get_timeout(self, timeout): return (timeout.value, timeout.message) if timeout else None def _get_template(self, template): return unicode(template) if template.is_active() else None def _create_setup(self, parent, data): if data.is_active(): self._create_step(parent, data, kw_type='setup') def _create_teardown(self, parent, data): if data.is_active(): self._create_step(parent, data, kw_type='teardown') class ResourceFileBuilder(object): def __init__(self): self._create_step = StepBuilder().build def build(self, path_or_data, target=None): data, source = self._import_resource_if_needed(path_or_data) if not target: target = ResourceFile(doc=data.setting_table.doc.value, source=source) for import_data in data.setting_table.imports: self._create_import(target, import_data) for var_data in data.variable_table.variables: self._create_variable(target, var_data) for kw_data in data.keyword_table.keywords: self._create_keyword(target, kw_data) return target def _import_resource_if_needed(self, path_or_data): if not is_string(path_or_data): return path_or_data, path_or_data.source return ResourceData(path_or_data).populate(), path_or_data def _create_import(self, target, data): target.imports.create(type=data.type, name=data.name, args=tuple(data.args), alias=data.alias) def _create_variable(self, target, data): if data: target.variables.create(name=data.name, value=data.value) def _create_keyword(self, target, data): kw = target.keywords.create(name=data.name, args=tuple(data.args), doc=unicode(data.doc), tags=tuple(data.tags), return_=tuple(data.return_), timeout=self._get_timeout(data.timeout)) for step_data in data.steps: self._create_step(kw, step_data) if data.teardown.is_active(): self._create_step(kw, data.teardown, kw_type='teardown') def _get_timeout(self, timeout): return (timeout.value, timeout.message) if timeout else None class StepBuilder(object): def build(self, parent, data, template=None, kw_type='kw'): if not data or data.is_comment(): return if data.is_for_loop(): self._create_for_loop(parent, data, template) elif template and template.is_active(): self._create_templated(parent, data, template) else: parent.keywords.create(name=data.name, args=tuple(data.args), assign=tuple(data.assign), type=kw_type) def _create_templated(self, parent, data, template): args = data.as_list(include_comment=False) template, args = self._format_template(unicode(template), args) parent.keywords.create(name=template, args=tuple(args)) def _format_template(self, template, args): iterator = VariableIterator(template, identifiers='$') variables = len(iterator) if not variables or variables != len(args): return template, args temp = [] for before, variable, after in iterator: temp.extend([before, args.pop(0)]) temp.append(after) return ''.join(temp), () def _create_for_loop(self, parent, data, template): loop = parent.keywords.append(ForLoop(variables=data.vars, values=data.items, flavor=data.flavor)) for step in data.steps: self.build(loop, step, template=template)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/running/builder.py
0.719778
0.383988
builder.py
pypi
from java.lang import Byte, Short, Integer, Long, Boolean, Float, Double from robot.variables import contains_var from robot.utils import is_string, is_list_like class JavaArgumentCoercer(object): def __init__(self, signatures, argspec): self._argspec = argspec self._coercers = CoercerFinder().find_coercers(signatures) self._varargs_handler = VarargsHandler(argspec) def coerce(self, arguments, named, dryrun=False): arguments = self._varargs_handler.handle(arguments) arguments = [c.coerce(a, dryrun) for c, a in zip(self._coercers, arguments)] if self._argspec.kwargs: arguments.append(named) return arguments class CoercerFinder(object): def find_coercers(self, signatures): return [self._get_coercer(types, position) for position, types in self._parse_types(signatures)] def _parse_types(self, signatures): types = {} for sig in signatures: for index, arg in enumerate(sig.args): types.setdefault(index + 1, []).append(arg) return sorted(types.items()) def _get_coercer(self, types, position): possible = [BooleanCoercer(position), IntegerCoercer(position), FloatCoercer(position), NullCoercer(position)] coercers = [self._get_coercer_for_type(t, possible) for t in types] if self._coercers_conflict(*coercers): return NullCoercer() return coercers[0] def _get_coercer_for_type(self, type, coercers): for coercer in coercers: if coercer.handles(type): return coercer def _coercers_conflict(self, first, *rest): return not all(coercer is first for coercer in rest) class _Coercer(object): _name = '' _types = [] _primitives = [] def __init__(self, position=None): self._position = position def handles(self, type): return type in self._types or type.__name__ in self._primitives def coerce(self, argument, dryrun=False): if not is_string(argument) \ or (dryrun and contains_var(argument)): return argument try: return self._coerce(argument) except ValueError: raise ValueError('Argument at position %d cannot be coerced to %s.' % (self._position, self._name)) def _coerce(self, argument): raise NotImplementedError class BooleanCoercer(_Coercer): _name = 'boolean' _types = [Boolean] _primitives = ['boolean'] def _coerce(self, argument): try: return {'false': False, 'true': True}[argument.lower()] except KeyError: raise ValueError class IntegerCoercer(_Coercer): _name = 'integer' _types = [Byte, Short, Integer, Long] _primitives = ['byte', 'short', 'int', 'long'] def _coerce(self, argument): return int(argument) class FloatCoercer(_Coercer): _name = 'floating point number' _types = [Float, Double] _primitives = ['float', 'double'] def _coerce(self, argument): return float(argument) class NullCoercer(_Coercer): def handles(self, argument): return True def _coerce(self, argument): return argument class VarargsHandler(object): def __init__(self, argspec): self._index = argspec.minargs if argspec.varargs else -1 def handle(self, arguments): if self._index > -1 and not self._passing_list(arguments): arguments[self._index:] = [arguments[self._index:]] return arguments def _passing_list(self, arguments): return self._correct_count(arguments) and is_list_like(arguments[-1]) def _correct_count(self, arguments): return len(arguments) == self._index + 1
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/running/arguments/javaargumentcoercer.py
0.802903
0.234516
javaargumentcoercer.py
pypi
from robot.errors import DataError from robot.utils import plural_or_not from robot.variables import is_list_var class ArgumentValidator(object): def __init__(self, argspec): self._argspec = argspec def validate(self, positional, named, dryrun=False): if dryrun and any(is_list_var(arg) for arg in positional): return self._validate_no_multiple_values(positional, named, self._argspec) self._validate_limits(positional, named, self._argspec) self._validate_no_mandatory_missing(positional, named, self._argspec) def _validate_limits(self, positional, named, spec): count = len(positional) + self._named_positionals(named, spec) if not spec.minargs <= count <= spec.maxargs: self._raise_wrong_count(count, spec) def _named_positionals(self, named, spec): if not spec.supports_named: return 0 return sum(1 for n in named if n in spec.positional) def _raise_wrong_count(self, count, spec): minend = plural_or_not(spec.minargs) if spec.minargs == spec.maxargs: expected = '%d argument%s' % (spec.minargs, minend) elif not spec.varargs: expected = '%d to %d arguments' % (spec.minargs, spec.maxargs) else: expected = 'at least %d argument%s' % (spec.minargs, minend) if spec.kwargs: expected = expected.replace('argument', 'non-keyword argument') raise DataError("%s '%s' expected %s, got %d." % (spec.type, spec.name, expected, count)) def _validate_no_multiple_values(self, positional, named, spec): for name in spec.positional[:len(positional)]: if name in named and spec.supports_named: raise DataError("%s '%s' got multiple values for argument '%s'." % (spec.type, spec.name, name)) def _validate_no_mandatory_missing(self, positional, named, spec): for name in spec.positional[len(positional):spec.minargs]: if name not in named: raise DataError("%s '%s' missing value for argument '%s'." % (spec.type, spec.name, name))
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/running/arguments/argumentvalidator.py
0.796649
0.323567
argumentvalidator.py
pypi
import re from robot.errors import DataError from robot.utils import get_error_message from robot.variables import VariableIterator class EmbeddedArguments(object): def __init__(self, name): if '${' in name: self.name, self.args = EmbeddedArgumentParser().parse(name) else: self.name, self.args = None, [] def __bool__(self): return self.name is not None #PY2 def __nonzero__(self): return self.__bool__() class EmbeddedArgumentParser(object): _regexp_extension = re.compile(r'(?<!\\)\(\?.+\)') _regexp_group_start = re.compile(r'(?<!\\)\((.*?)\)') _regexp_group_escape = r'(?:\1)' _default_pattern = '.*?' _variable_pattern = r'\$\{[^\}]+\}' def parse(self, string): args = [] name_regexp = ['^'] for before, variable, string in VariableIterator(string, identifiers='$'): name, pattern = self._get_name_and_pattern(variable[2:-1]) args.append(name) name_regexp.extend([re.escape(before), '(%s)' % pattern]) name_regexp.extend([re.escape(string), '$']) name = self._compile_regexp(name_regexp) if args else None return name, args def _get_name_and_pattern(self, name): if ':' not in name: return name, self._default_pattern name, pattern = name.split(':', 1) return name, self._format_custom_regexp(pattern) def _format_custom_regexp(self, pattern): for formatter in (self._regexp_extensions_are_not_allowed, self._make_groups_non_capturing, self._unescape_closing_curly, self._add_automatic_variable_pattern): pattern = formatter(pattern) return pattern def _regexp_extensions_are_not_allowed(self, pattern): if not self._regexp_extension.search(pattern): return pattern raise DataError('Regexp extensions are not allowed in embedded ' 'arguments.') def _make_groups_non_capturing(self, pattern): return self._regexp_group_start.sub(self._regexp_group_escape, pattern) def _unescape_closing_curly(self, pattern): return pattern.replace('\\}', '}') def _add_automatic_variable_pattern(self, pattern): return '%s|%s' % (pattern, self._variable_pattern) def _compile_regexp(self, pattern): try: return re.compile(''.join(pattern), re.IGNORECASE) except: raise DataError("Compiling embedded arguments regexp failed: %s" % get_error_message())
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/running/arguments/embedded.py
0.577614
0.178777
embedded.py
pypi
from robot.errors import DataError from robot.utils import is_string, is_dict_like, split_from_equals, DotDict from robot.variables import VariableSplitter from .argumentvalidator import ArgumentValidator class ArgumentResolver(object): def __init__(self, argspec, resolve_named=True, resolve_variables_until=None, dict_to_kwargs=False): self._named_resolver = NamedArgumentResolver(argspec) \ if resolve_named else NullNamedArgumentResolver() self._variable_replacer = VariableReplacer(resolve_variables_until) self._dict_to_kwargs = DictToKwargs(argspec, dict_to_kwargs) self._argument_validator = ArgumentValidator(argspec) def resolve(self, arguments, variables=None): positional, named = self._named_resolver.resolve(arguments, variables) positional, named = self._variable_replacer.replace(positional, named, variables) positional, named = self._dict_to_kwargs.handle(positional, named) self._argument_validator.validate(positional, named, dryrun=not variables) return positional, named class NamedArgumentResolver(object): def __init__(self, argspec): self._argspec = argspec def resolve(self, arguments, variables=None): positional = [] named = [] for arg in arguments: if self._is_dict_var(arg): named.append(arg) elif self._is_named(arg, variables): named.append(split_from_equals(arg)) elif named: self._raise_positional_after_named() else: positional.append(arg) return positional, named def _is_dict_var(self, arg): return (is_string(arg) and VariableSplitter(arg).is_dict_variable()) def _is_named(self, arg, variables=None): if not (is_string(arg) and '=' in arg): return False name, value = split_from_equals(arg) if value is None: return False if self._argspec.kwargs: return True if not self._argspec.supports_named: return False if variables: name = variables.replace_scalar(name) return name in self._argspec.positional def _raise_positional_after_named(self): raise DataError("%s '%s' got positional argument after named arguments." % (self._argspec.type, self._argspec.name)) class NullNamedArgumentResolver(object): def resolve(self, arguments, variables=None): return arguments, {} class DictToKwargs(object): def __init__(self, argspec, enabled=False): self._maxargs = argspec.maxargs self._enabled = enabled and bool(argspec.kwargs) def handle(self, positional, named): if self._enabled and self._extra_arg_has_kwargs(positional, named): named = positional.pop() return positional, named def _extra_arg_has_kwargs(self, positional, named): if named or len(positional) != self._maxargs + 1: return False return is_dict_like(positional[-1]) class VariableReplacer(object): def __init__(self, resolve_until=None): self._resolve_until = resolve_until def replace(self, positional, named, variables=None): # `variables` is None in dry-run mode and when using Libdoc if variables: positional = variables.replace_list(positional, self._resolve_until) named = DotDict(self._replace_named(named, variables.replace_scalar)) else: positional = list(positional) named = DotDict(item for item in named if isinstance(item, tuple)) return positional, named def _replace_named(self, named, replace_scalar): for item in named: for name, value in self._get_replaced_named(item, replace_scalar): if not is_string(name): raise DataError('Argument names must be strings.') yield name, value def _get_replaced_named(self, item, replace_scalar): if not isinstance(item, tuple): return replace_scalar(item).items() name, value = item return [(replace_scalar(name), replace_scalar(value))]
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/running/arguments/argumentresolver.py
0.824356
0.228307
argumentresolver.py
pypi
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(kwname=elem.get('name', ''), libname=elem.get('library', ''), timeout=elem.get('timeout'), type=elem.get('type', 'kw')) def _children(self): return [DocHandler(), ArgumentsHandler(), AssignHandler(), TagsHandler(), KeywordStatusHandler(), MessageHandler(), self] class MessageHandler(_Handler): tag = 'msg' def end(self, elem, result): result.messages.create(elem.text or '', elem.get('level', 'INFO'), 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 AssignHandler(_Handler): tag = 'assign' def _children(self): return [AssignVarHandler()] class AssignVarHandler(_Handler): tag = 'var' def end(self, elem, result): result.assign += (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
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/result/xmlelementhandlers.py
0.658308
0.197464
xmlelementhandlers.py
pypi
from robot.errors import DataError from robot.model import SuiteVisitor, TagPattern from robot.utils import Matcher, plural_or_not def KeywordRemover(how): upper = how.upper() if upper.startswith('NAME:'): return ByNameKeywordRemover(pattern=how[5:]) if upper.startswith('TAG:'): return ByTagKeywordRemover(pattern=how[4:]) 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_warning_or_error(self, item): return not item.passed or self._warning_or_error(item) def _warning_or_error(self, item): finder = WarningAndErrorFinder() item.visit(finder) return finder.found 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._warning_or_error(keyword): self._clear_content(keyword) def visit_test(self, test): if not self._failed_or_warning_or_error(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._warning_or_error(kw): self._clear_content(kw) class ByTagKeywordRemover(_KeywordRemover): def __init__(self, pattern): _KeywordRemover.__init__(self) self._pattern = TagPattern(pattern) def start_keyword(self, kw): if self._pattern.match(kw.tags) and not self._warning_or_error(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_warning_or_error(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._warning_or_error(kw)] class WarningAndErrorFinder(SuiteVisitor): def __init__(self): self.found = False def start_suite(self, suite): return not self.found def start_test(self, test): return not self.found def start_keyword(self, keyword): return not self.found def visit_message(self, msg): if msg.level in ('WARN', 'ERROR'): self.found = 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()
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/result/keywordremover.py
0.587707
0.228038
keywordremover.py
pypi
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:`~.result.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:`~.result.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)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/result/executionresult.py
0.924236
0.380327
executionresult.py
pypi
from robot import model from robot.utils import is_string, secs_to_timestamp, timestamp_to_secs 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 is_string(value): return [value] return value def _get_time(self, timestamp): if not timestamp: return None try: secs = timestamp_to_secs(timestamp, seps=' :.-_') except ValueError: return None return 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
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/result/configurer.py
0.849301
0.470919
configurer.py
pypi
from robot.model import SuiteVisitor class ResultVisitor(SuiteVisitor): """Abstract class to conveniently travel :class:`~robot.result.executionresult.Result` objects. A visitor implementation can be given to the :meth:`visit` method of a result object. This will cause the result object to be traversed and the visitor's :meth:`visit_x`, :meth:`start_x`, and :meth:`end_x` methods to be called for each suite, test, keyword and message, as well as for errors, statistics, and other information in the result object. See methods below for a full list of available visitor methods. See the :mod:`result package level <robot.result>` documentation for more information about handling results and a concrete visitor example. For more information about the visitor algorithm see documentation in :mod:`robot.model.visitor` module. """ 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
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/result/visitor.py
0.867457
0.776792
visitor.py
pypi
from robot.errors import DataError from robot.model import SuiteVisitor class Merger(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: self.current = self._find_suite(self.current, suite.name) except IndexError: suite.message = self._create_add_message(suite, test=False) self.current.suites.append(suite) return False def _find_suite(self, parent, name): if not parent: suite = self._find_root(name) else: suite = self._find(parent.suites, name) suite.starttime = suite.endtime = None return suite def _find_root(self, name): if self.root.name == name: return self.root raise DataError("Cannot merge outputs containing different root " "suites. Original suite is '%s' and merged is '%s'." % (self.root.name, name)) def _find(self, items, name): for item in items: if item.name == name: return item raise IndexError 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 IndexError: test.message = self._create_add_message(test) self.current.tests.append(test) else: test.message = self._create_merge_message(test, old) index = self.current.tests.index(old) self.current.tests[index] = test def _create_add_message(self, item, test=True): prefix = '%s added from merged output.' % ('Test' if test else 'Suite') if not item.message: return prefix return '\n'.join([prefix, '- - -', item.message]) def _create_merge_message(self, new, old): return '\n'.join(['Re-executed test has been merged.', '- - -', 'New status: %s' % new.status, 'New message: %s' % new.message, '- - -', 'Old status: %s' % old.status, 'Old message: %s' % old.message])
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/result/merger.py
0.560132
0.342544
merger.py
pypi
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
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/libdocpkg/consoleviewer.py
0.551574
0.151624
consoleviewer.py
pypi
import sys 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): doc, tags = utils.split_tags_from_doc(self._get_doc(method)) return KeywordDoc( name=utils.printable_name(method.name(), code_style=True), args=self._get_keyword_arguments(method), doc=doc, tags=tags ) 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) if sys.platform[4:7] < '1.8': # API changed in Java 8 root = jdoctool.getRootDocImpl('en', 'utf-8', filter, java_names, List.nil(), False, List.nil(), List.nil(), False, False, True) else: root = jdoctool.getRootDocImpl('en', 'utf-8', filter, java_names, List.nil(), List.nil(), False, List.nil(), List.nil(), False, False, True) return root.classes()[0]
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/libdocpkg/javabuilder.py
0.409457
0.17266
javabuilder.py
pypi
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. = 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 when `importing` the library and using `Set Screenshot Directory` keyword during execution. It is also possible to save screenshots using an absolute path. """ 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 | """ 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 __bool__(self): return self.module != 'no' #PY2 def __nonzero__(self): return self.__bool__() 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.App(False) 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)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/libraries/Screenshot.py
0.627723
0.197328
Screenshot.py
pypi
from six import PY3, text_type as unicode import sys from robot.api import logger from robot.utils import (is_dict_like, is_string, is_truthy, plural_or_not, seq2str, seq2str2, type_name, unic, Matcher) from robot.utils.asserts import assert_equals from robot.version import get_version class _List(object): def convert_to_list(self, item): """Converts the given ``item`` to a Python ``list`` type. 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 occurrences of given ``values`` from ``list``. It is not an error if 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 and including the end, use ``None`` (default) as the end value. Using ``start`` or ``end`` not found on the list is the same as using the largest (or smallest) available index. Examples (incl. Python equivalents 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 with `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 with `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 the keyword fails, the default error messages is ``<list> does not contain value '<value>'``. A custom message can be given using the ``msg`` argument. """ 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`` gets a value considered true (see `Boolean arguments`), the error message starts with the given ``msg`` followed by a newline and the default message. - If ``msg`` is given and ``values`` is not given a true value, the error message is just the given ``msg``. Optional ``names`` argument 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 is_dict_like(names): 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 as 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 `Lists Should Be Equal` for more information about configuring the error message with ``msg`` and ``values`` arguments. """ 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(object): def convert_to_dictionary(self, item): """Converts the given ``item`` to a Python ``dict`` type. Mainly useful for converting other mappings to dictionaries. Use `Create Dictionary` from the BuiltIn library for constructing new dictionaries. New in Robot Framework 2.9. """ return dict(item) def set_to_dictionary(self, dictionary, *key_value_pairs, **items): """Adds the given ``key_value_pairs`` and ``items`` to the ``dictionary``. Giving items as ``key_value_pairs`` means giving keys and values as separate arguments: | Set To Dictionary | ${D1} | key | value | second | ${2} | => | ${D1} = {'a': 1, 'key': 'value', 'second': 2} Starting from Robot Framework 2.8.1, items can also be given as kwargs using ``key=value`` syntax: | Set To Dictionary | ${D1} | key=value | second=${2} | The latter syntax is typically more convenient to use, but it has a limitation that keys must be strings. If given keys already exist in the dictionary, their values are updated. """ 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. In *Python 3* keys are not sorted, because most builtin types are not comparable to each other. This issue needs a better solution in future releases... Maybe imitate Python 2 sorting? Any suggestions? :) Example: | ${keys} = | Get Dictionary Keys | ${D3} | => | ${keys} = ['a', 'b', 'c'] """ #TODO: Sorting causes problems when key types are not comparable, # especially in Python 3 where even basic types like int and str # are not comparable to each other. if PY3: return list(dictionary) # TODO: Possibility to disable sorting. Can be handy with OrderedDicts. 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. In *Python 3* values are not sorted. See `Get Dictionary Keys` for more details. 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. In *Python 3* items are not sorted. See `Get Dictionary Keys` for more details. 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 more information about configuring the error message with ``msg`` and ``values`` arguments. 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 more information about configuring the error message with ``msg`` and ``values`` arguments. 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 as 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`). = Related keywords in BuiltIn = Following keywords in the BuiltIn library can also be used with lists and dictionaries: | = Keyword Name = | = Applicable With = | = Comment = | | `Create List` | lists | | `Create Dictionary` | dicts | Was in Collections until RF 2.9. | | `Get Length` | both | | `Length Should Be` | both | | `Should Be Empty` | both | | `Should Not Be Empty` | both | | `Should Contain` | both | | `Should Not Contain` | both | | `Should Contain X Times` | lists | | `Should Not Contain X Times` | lists | | `Get Count` | lists | = Using with list-like and dictionary-like objects = 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 Python ``list`` objects. Similarly dictionary keywords can, for most parts, be used with other mappings. `Convert To Dictionary` can be used if real Python ``dict`` objects are needed. = Boolean arguments = Some keywords accept arguments that are handled as Boolean values true or false. If such an argument is given as a string, it is considered false if it is either empty or case-insensitively equal to ``false`` or ``no``. Keywords verifying something that allow dropping actual and expected values from the possible error message also consider string ``no values`` as false. Other strings are considered true regardless their value, 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: | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=True | # Strings are generally true. | | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=yes | # Same as the above. | | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=${TRUE} | # Python ``True`` is true. | | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=${42} | # Numbers other than 0 are true. | False examples: | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=False | # String ``false`` is false. | | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=no | # Also string ``no`` is false. | | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=${EMPTY} | # Empty string is false. | | `Should Contain Match` | ${list} | ${pattern} | case_insensitive=${FALSE} | # Python ``False`` is false. | | `Lists Should Be Equal` | ${x} | ${y} | Custom error | values=no values | # ``no values`` works with ``values`` argument | Note that prior to Robot Framework 2.9 some keywords considered all non-empty strings, including ``False``, to be true. = Data in examples = List related keywords use variables in format ``${Lx}`` in their examples. They mean lists 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 should_contain_match(self, list, pattern, msg=None, case_insensitive=False, whitespace_insensitive=False): """Fails if ``pattern`` is not found in ``list``. See `List Should Contain Value` for an explanation of ``msg``. By default, pattern matching is similar to matching files in a shell and is case-sensitive and whitespace-sensitive. In the pattern syntax, ``*`` matches to anything and ``?`` matches to any single character. You can also prepend ``glob=`` to your pattern to explicitly use this pattern matching behavior. If you prepend ``regexp=`` to your pattern, your pattern will be used according to the Python [http://docs.python.org/2/library/re.html|re module] regular expression syntax. Important note: Backslashes are an escape character, and must be escaped with another backslash (e.g. ``regexp=\\\\d{6}`` to search for ``\\d{6}``). See `BuiltIn.Should Match Regexp` for more details. If ``case_insensitive`` is given a true value (see `Boolean arguments`), the pattern matching will ignore case. If ``whitespace_insensitive`` is given a true value (see `Boolean arguments`), the pattern matching will ignore whitespace. Non-string values in lists are ignored when matching patterns. The given list is never altered by this keyword. See also ``Should Not Contain Match``. Examples: | Should Contain Match | ${list} | a* | | | # Match strings beginning with 'a'. | | Should Contain Match | ${list} | regexp=a.* | | | # Same as the above but with regexp. | | Should Contain Match | ${list} | regexp=\\\\d{6} | | | # Match strings containing six digits. | | Should Contain Match | ${list} | a* | case_insensitive=True | | # Match strings beginning with 'a' or 'A'. | | Should Contain Match | ${list} | ab* | whitespace_insensitive=yes | | # Match strings beginning with 'ab' with possible whitespace ignored. | | Should Contain Match | ${list} | ab* | whitespace_insensitive=true | case_insensitive=true | # Same as the above but also ignore case. | New in Robot Framework 2.8.6. """ matches = _get_matches_in_iterable(list, pattern, case_insensitive, whitespace_insensitive) default = "%s does not contain match for pattern '%s'." \ % (seq2str2(list), pattern) _verify_condition(matches, default, msg) def should_not_contain_match(self, list, pattern, msg=None, case_insensitive=False, whitespace_insensitive=False): """Fails if ``pattern`` is found in ``list``. Exact opposite of `Should Contain Match` keyword. See that keyword for information about arguments and usage in general. New in Robot Framework 2.8.6. """ matches = _get_matches_in_iterable(list, pattern, case_insensitive, whitespace_insensitive) default = "%s contains match for pattern '%s'." \ % (seq2str2(list), pattern) _verify_condition(not matches, default, msg) def get_matches(self, list, pattern, case_insensitive=False, whitespace_insensitive=False): """Returns a list of matches to ``pattern`` in ``list``. For more information on ``pattern``, ``case_insensitive``, and ``whitespace_insensitive``, see `Should Contain Match`. Examples: | ${matches}= | Get Matches | ${list} | a* | # ${matches} will contain any string beginning with 'a' | | ${matches}= | Get Matches | ${list} | regexp=a.* | # ${matches} will contain any string beginning with 'a' (regexp version) | | ${matches}= | Get Matches | ${list} | a* | case_insensitive=${True} | # ${matches} will contain any string beginning with 'a' or 'A' | New in Robot Framework 2.8.6. """ return _get_matches_in_iterable(list, pattern, case_insensitive, whitespace_insensitive) def get_match_count(self, list, pattern, case_insensitive=False, whitespace_insensitive=False): """Returns the count of matches to ``pattern`` in ``list``. For more information on ``pattern``, ``case_insensitive``, and ``whitespace_insensitive``, see `Should Contain Match`. Examples: | ${count}= | Get Match Count | ${list} | a* | # ${count} will be the count of strings beginning with 'a' | | ${count}= | Get Match Count | ${list} | regexp=a.* | # ${matches} will be the count of strings beginning with 'a' (regexp version) | | ${count}= | Get Match Count | ${list} | a* | case_insensitive=${True} | # ${matches} will be the count of strings beginning with 'a' or 'A' | New in Robot Framework 2.8.6. """ return len(self.get_matches(list, pattern, case_insensitive, whitespace_insensitive)) def _verify_condition(condition, default_msg, msg, values=False): if condition: return if not msg: msg = default_msg elif is_truthy(values) and str(values).upper() != 'NO VALUES': msg += '\n' + default_msg raise AssertionError(msg) def _get_matches_in_iterable(iterable, pattern, case_insensitive=False, whitespace_insensitive=False): if not is_string(pattern): raise TypeError("Pattern must be string, got '%s'." % type_name(pattern)) regexp = False if pattern.startswith('regexp='): pattern = pattern[7:] regexp = True elif pattern.startswith('glob='): pattern = pattern[5:] matcher = Matcher(pattern, caseless=is_truthy(case_insensitive), spaceless=is_truthy(whitespace_insensitive), regexp=regexp) return [string for string in iterable if is_string(string) and matcher.match(string)]
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/libraries/Collections.py
0.705481
0.553324
Collections.py
pypi
from datetime import datetime, timedelta import time import re from robot.version import get_version from robot.utils import (elapsed_time_to_string, is_falsy, is_number, is_string, secs_to_timestr, timestr_to_secs, type_name, IRONPYTHON) __version__ = get_version() __all__ = ['convert_time', 'convert_date', 'subtract_date_from_date', 'subtract_time_from_date', 'subtract_time_from_time', 'add_time_to_time', 'add_time_to_date', 'get_current_date'] def get_current_date(time_zone='local', increment=0, result_format='timestamp', exclude_millis=False): """Returns current local or UTC time with an optional increment. Arguments: - ``time_zone:`` Get the current time on this time zone. Currently only ``local`` (default) and ``UTC`` are supported. - ``increment:`` Optional time increment to add to the returned date in one of the supported `time formats`. Can be negative. - ``result_format:`` Format of the returned date (see `date formats`). - ``exclude_millis:`` When set to any true value, rounds and drops milliseconds as explained in `millisecond handling`. Examples: | ${date} = | Get Current Date | | Should Be Equal | ${date} | 2014-06-12 20:00:58.946 | | ${date} = | Get Current Date | UTC | | Should Be Equal | ${date} | 2014-06-12 17:00:58.946 | | ${date} = | Get Current Date | increment=02:30:00 | | Should Be Equal | ${date} | 2014-06-12 22:30:58.946 | | ${date} = | Get Current Date | UTC | - 5 hours | | Should Be Equal | ${date} | 2014-06-12 12:00:58.946 | | ${date} = | Get Current Date | result_format=datetime | | Should Be Equal | ${date.year} | ${2014} | | Should Be Equal | ${date.month} | ${6} | """ if time_zone.upper() == 'LOCAL': dt = datetime.now() elif time_zone.upper() == 'UTC': dt = datetime.utcnow() else: raise ValueError("Unsupported timezone '%s'." % time_zone) date = Date(dt) + Time(increment) return date.convert(result_format, millis=is_falsy(exclude_millis)) def convert_date(date, result_format='timestamp', exclude_millis=False, date_format=None): """Converts between supported `date formats`. Arguments: - ``date:`` Date in one of the supported `date formats`. - ``result_format:`` Format of the returned date. - ``exclude_millis:`` When set to any true value, rounds and drops milliseconds as explained in `millisecond handling`. - ``date_format:`` Specifies possible `custom timestamp` format. Examples: | ${date} = | Convert Date | 20140528 12:05:03.111 | | Should Be Equal | ${date} | 2014-05-28 12:05:03.111 | | ${date} = | Convert Date | ${date} | epoch | | Should Be Equal | ${date} | ${1401267903.111} | | ${date} = | Convert Date | 5.28.2014 12:05 | exclude_millis=yes | date_format=%m.%d.%Y %H:%M | | Should Be Equal | ${date} | 2014-05-28 12:05:00 | """ return Date(date, date_format).convert(result_format, millis=is_falsy(exclude_millis)) def convert_time(time, result_format='number', exclude_millis=False): """Converts between supported `time formats`. Arguments: - ``time:`` Time in one of the supported `time formats`. - ``result_format:`` Format of the returned time. - ``exclude_millis:`` When set to any true value, rounds and drops milliseconds as explained in `millisecond handling`. Examples: | ${time} = | Convert Time | 10 seconds | | Should Be Equal | ${time} | ${10} | | ${time} = | Convert Time | 1:00:01 | verbose | | Should Be Equal | ${time} | 1 hour 1 second | | ${time} = | Convert Time | ${3661.5} | timer | exclude_milles=yes | | Should Be Equal | ${time} | 01:01:02 | """ return Time(time).convert(result_format, millis=is_falsy(exclude_millis)) def subtract_date_from_date(date1, date2, result_format='number', exclude_millis=False, date1_format=None, date2_format=None): """Subtracts date from another date and returns time between. Arguments: - ``date1:`` Date to subtract another date from in one of the supported `date formats`. - ``date2:`` Date that is subtracted in one of the supported `date formats`. - ``result_format:`` Format of the returned time (see `time formats`). - ``exclude_millis:`` When set to any true value, rounds and drops milliseconds as explained in `millisecond handling`. - ``date1_format:`` Possible `custom timestamp` format of ``date1``. - ``date2_format:`` Possible `custom timestamp` format of ``date2``. Examples: | ${time} = | Subtract Date From Date | 2014-05-28 12:05:52 | 2014-05-28 12:05:10 | | Should Be Equal | ${time} | ${42} | | ${time} = | Subtract Date From Date | 2014-05-28 12:05:52 | 2014-05-27 12:05:10 | verbose | | Should Be Equal | ${time} | 1 day 42 seconds | """ time = Date(date1, date1_format) - Date(date2, date2_format) return time.convert(result_format, millis=is_falsy(exclude_millis)) def add_time_to_date(date, time, result_format='timestamp', exclude_millis=False, date_format=None): """Adds time to date and returns the resulting date. Arguments: - ``date:`` Date to add time to in one of the supported `date formats`. - ``time:`` Time that is added in one of the supported `time formats`. - ``result_format:`` Format of the returned date. - ``exclude_millis:`` When set to any true value, rounds and drops milliseconds as explained in `millisecond handling`. - ``date_format:`` Possible `custom timestamp` format of ``date``. Examples: | ${date} = | Add Time To Date | 2014-05-28 12:05:03.111 | 7 days | | Should Be Equal | ${date} | 2014-06-04 12:05:03.111 | | | ${date} = | Add Time To Date | 2014-05-28 12:05:03.111 | 01:02:03:004 | | Should Be Equal | ${date} | 2014-05-28 13:07:06.115 | """ date = Date(date, date_format) + Time(time) return date.convert(result_format, millis=is_falsy(exclude_millis)) def subtract_time_from_date(date, time, result_format='timestamp', exclude_millis=False, date_format=None): """Subtracts time from date and returns the resulting date. Arguments: - ``date:`` Date to subtract time from in one of the supported `date formats`. - ``time:`` Time that is subtracted in one of the supported `time formats`. - ``result_format:`` Format of the returned date. - ``exclude_millis:`` When set to any true value, rounds and drops milliseconds as explained in `millisecond handling`. - ``date_format:`` Possible `custom timestamp` format of ``date``. Examples: | ${date} = | Subtract Time From Date | 2014-06-04 12:05:03.111 | 7 days | | Should Be Equal | ${date} | 2014-05-28 12:05:03.111 | | ${date} = | Subtract Time From Date | 2014-05-28 13:07:06.115 | 01:02:03:004 | | Should Be Equal | ${date} | 2014-05-28 12:05:03.111 | """ date = Date(date, date_format) - Time(time) return date.convert(result_format, millis=is_falsy(exclude_millis)) def add_time_to_time(time1, time2, result_format='number', exclude_millis=False): """Adds time to another time and returns the resulting time. Arguments: - ``time1:`` First time in one of the supported `time formats`. - ``time2:`` Second time in one of the supported `time formats`. - ``result_format:`` Format of the returned time. - ``exclude_millis:`` When set to any true value, rounds and drops milliseconds as explained in `millisecond handling`. Examples: | ${time} = | Add Time To Time | 1 minute | 42 | | Should Be Equal | ${time} | ${102} | | ${time} = | Add Time To Time | 3 hours 5 minutes | 01:02:03 | timer | exclude_millis=yes | | Should Be Equal | ${time} | 04:07:03 | """ time = Time(time1) + Time(time2) return time.convert(result_format, millis=is_falsy(exclude_millis)) def subtract_time_from_time(time1, time2, result_format='number', exclude_millis=False): """Subtracts time from another time and returns the resulting time. Arguments: - ``time1:`` Time to subtract another time from in one of the supported `time formats`. - ``time2:`` Time to subtract in one of the supported `time formats`. - ``result_format:`` Format of the returned time. - ``exclude_millis:`` When set to any true value, rounds and drops milliseconds as explained in `millisecond handling`. Examples: | ${time} = | Subtract Time From Time | 00:02:30 | 100 | | Should Be Equal | ${time} | ${50} | | ${time} = | Subtract Time From Time | ${time} | 1 minute | compact | | Should Be Equal | ${time} | - 10s | """ time = Time(time1) - Time(time2) return time.convert(result_format, millis=is_falsy(exclude_millis)) class Date(object): def __init__(self, date, input_format=None): self.seconds = self._convert_date_to_seconds(date, input_format) def _convert_date_to_seconds(self, date, input_format): if is_string(date): return self._string_to_epoch(date, input_format) elif isinstance(date, datetime): return self._mktime_with_millis(date) elif is_number(date): return float(date) raise ValueError("Unsupported input '%s'." % date) @property def datetime(self): return self._datetime_from_seconds(self.seconds) def _string_to_epoch(self, ts, input_format): if not input_format: ts = self._normalize_timestamp(ts) input_format = '%Y-%m-%d %H:%M:%S.%f' if self._need_to_handle_f_directive(input_format): return self._handle_un_supported_f_directive(ts, input_format) return self._mktime_with_millis(datetime.strptime(ts, input_format)) def _normalize_timestamp(self, date): ts = ''.join(d for d in date if d.isdigit()) if len(ts) < 8: raise ValueError("Invalid timestamp '%s'." % date) ts = ts.ljust(20, '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:]) def _need_to_handle_f_directive(self, format): # https://github.com/IronLanguages/main/issues/1169 return IRONPYTHON and '%f' in format def _handle_un_supported_f_directive(self, ts, input_format): input_format = self._remove_f_from_format(input_format) micro = re.search('\d+$', ts).group(0) ts = ts[:-len(micro)] epoch = time.mktime(time.strptime(ts, input_format)) epoch += float(micro) / 10**len(micro) return epoch def _remove_f_from_format(self, format): if not format.endswith('%f'): raise ValueError('%f directive is supported only at the end of ' 'the format string on this Python interpreter.') return format[:-2] def _mktime_with_millis(self, dt): return time.mktime(dt.timetuple()) + dt.microsecond / 1e6 def convert(self, format, millis=True): #PY3: round() needs explicit ndigits arg to return float seconds = self.seconds if millis else round(self.seconds, 0) if '%' in format: return self._convert_to_custom_timestamp(seconds, format) try: result_converter = getattr(self, '_convert_to_%s' % format.lower()) except AttributeError: raise ValueError("Unknown format '%s'." % format) return result_converter(seconds, millis) def _convert_to_custom_timestamp(self, seconds, format): dt = self._datetime_from_seconds(seconds) if not self._need_to_handle_f_directive(format): return dt.strftime(format) format = self._remove_f_from_format(format) micro = round(seconds % 1 * 1e6) return '%s%06d' % (dt.strftime(format), micro) def _convert_to_timestamp(self, seconds, millis=True): milliseconds = int(round(seconds % 1 * 1000)) if milliseconds == 1000: seconds = round(seconds) milliseconds = 0 dt = self._datetime_from_seconds(seconds) ts = dt.strftime('%Y-%m-%d %H:%M:%S') if millis: ts += '.%03d' % milliseconds return ts def _datetime_from_seconds(self, ts): # Workaround microsecond rounding errors with IronPython: # https://github.com/IronLanguages/main/issues/1170 # Also Jython had similar problems, but they seem to be fixed in 2.7. dt = datetime.fromtimestamp(ts) return dt.replace(microsecond=int(round(ts % 1 * 1e6))) def _convert_to_epoch(self, seconds, millis=True): return seconds def _convert_to_datetime(self, seconds, millis=True): return self._datetime_from_seconds(seconds) def __add__(self, other): if isinstance(other, Time): return Date(self.datetime + other.timedelta) raise TypeError('Can only add Time to Date, got %s.' % type_name(other)) def __sub__(self, other): if isinstance(other, Date): return Time(self.datetime - other.datetime) if isinstance(other, Time): return Date(self.datetime - other.timedelta) raise TypeError('Can only subtract Date or Time from Date, got %s.' % type_name(other)) class Time(object): def __init__(self, time): self.seconds = self._convert_time_to_seconds(time) def _convert_time_to_seconds(self, time): if isinstance(time, timedelta): # timedelta.total_seconds() is new in Python 2.7 return (time.days * 24 * 60 * 60 + time.seconds + time.microseconds / 1e6) return timestr_to_secs(time, round_to=None) @property def timedelta(self): return timedelta(seconds=self.seconds) def convert(self, format, millis=True): try: result_converter = getattr(self, '_convert_to_%s' % format.lower()) except AttributeError: raise ValueError("Unknown format '%s'." % format) #PY3: round() needs explicit ndigits arg to return float seconds = self.seconds if millis else round(self.seconds, 0) return result_converter(seconds, millis) def _convert_to_number(self, seconds, millis=True): return seconds def _convert_to_verbose(self, seconds, millis=True): return secs_to_timestr(seconds) def _convert_to_compact(self, seconds, millis=True): return secs_to_timestr(seconds, compact=True) def _convert_to_timer(self, seconds, millis=True): return elapsed_time_to_string(seconds * 1000, include_millis=millis) def _convert_to_timedelta(self, seconds, millis=True): return timedelta(seconds=seconds) def __add__(self, other): if isinstance(other, Time): return Time(self.seconds + other.seconds) raise TypeError('Can only add Time to Time, got %s.' % type_name(other)) def __sub__(self, other): if isinstance(other, Time): return Time(self.seconds - other.seconds) raise TypeError('Can only subtract Time from Time, got %s.' % type_name(other))
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/libraries/DateTime.py
0.916589
0.438064
DateTime.py
pypi
from contextlib import contextmanager import inspect import re import struct import telnetlib import time try: import pyte except ImportError: pyte = None from robot.api import logger from robot.utils import (ConnectionCache, is_bytes, is_string, is_truthy, is_unicode, secs_to_timestr, seq2str, timestr_to_secs) from robot.version import get_version class Telnet(object): """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` - `Boolean arguments` - `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`, `Set Default Log Level` and `Set Telnetlib 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. Prompt can be set to be a regular expression by giving ``prompt_is_regexp`` argument a true value (see `Boolean arguments`). Examples: | `Open Connection` | lolcathost | prompt=$ | | `Set Prompt` | (> |# ) | prompt_is_regexp=true | == 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 by giving ``terminal_emulation`` argument a true value (see `Boolean arguments`) either in the library initialization or with `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 prerequisite 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. By default these messages are written using ``TRACE`` level. Starting with Robot Framework 2.8.7 the level is configurable with the ``telnetlib_log_level`` option either in the library initialization, to the `Open Connection` or by using the `Set Telnetlib Log Level` keyword to the active connection. Special level ``NONE`` con be used to disable the logging altogether. = Time string format = Timeouts and other times used must be given as a time string using 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://robotframework.org/robotframework/#user-guide|Robot Framework User Guide]. = Boolean arguments = Some keywords accept arguments that are handled as Boolean values true or false. If such an argument is given as a string, it is considered false if it is either empty or case-insensitively equal to ``false`` or ``no``. Other strings are considered true regardless their value, 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: | `Open Connection` | lolcathost | terminal_emulation=True | # Strings are generally true. | | `Open Connection` | lolcathost | terminal_emulation=yes | # Same as the above. | | `Open Connection` | lolcathost | terminal_emulation=${TRUE} | # Python ``True`` is true. | | `Open Connection` | lolcathost | terminal_emulation=${42} | # Numbers other than 0 are true. | False examples: | `Open Connection` | lolcathost | terminal_emulation=False | # String ``false`` is false. | | `Open Connection` | lolcathost | terminal_emulation=no | # Also string ``no`` is false. | | `Open Connection` | lolcathost | terminal_emulation=${EMPTY} | # Empty string is false. | | `Open Connection` | lolcathost | terminal_emulation=${FALSE} | # Python ``False`` is false. | Note that prior to Robot Framework 2.9 some keywords considered all non-empty strings, including ``false`` and ``no``, to be true. """ 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, telnetlib_log_level='TRACE'): """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 ...` `keywords`. See these keywords as well as `Configuration`, `Terminal emulation` and `Logging` sections above for more information about these parameters and their possible values. See `Time string format` and `Boolean arguments` sections for information about using arguments accepting times and Boolean values, respectively. Examples (use only one of these): | = Setting = | = Value = | = Value = | = Value = | = Value = | = Comment = | | Library | Telnet | | | | # default values | | Library | Telnet | 5 seconds | | | # set only timeout | | Library | Telnet | newline=LF | encoding=ISO-8859-1 | | # set newline and encoding using named arguments | | Library | Telnet | prompt=$ | | | # set prompt | | Library | Telnet | prompt=(> |# ) | prompt_is_regexp=yes | | # 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 | | Library | Telnet | telnetlib_log_level=NONE | | | # disable logging messages from the underlying telnetlib | """ self._timeout = timeout or 3.0 self._newline = newline or 'CRLF' self._prompt = (prompt, prompt_is_regexp) self._encoding = encoding self._encoding_errors = encoding_errors self._default_log_level = default_log_level self._window_size = window_size self._environ_user = environ_user self._terminal_emulation = terminal_emulation self._terminal_type = terminal_type self._telnetlib_log_level = telnetlib_log_level self._cache = 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=None, terminal_type=None, telnetlib_log_level=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``, ``terminal_type`` and ``telnetlib_log_level`` arguments get default values when the library is [#Importing|imported]. Setting them here overrides those values for the opened connection. See `Configuration`, `Terminal emulation` and `Logging` sections for more information about these parameters and their possible values. 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 if terminal_emulation is None: terminal_emulation = self._terminal_emulation terminal_type = terminal_type or self._terminal_type telnetlib_log_level = telnetlib_log_level or self._telnetlib_log_level 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, is_truthy(prompt_is_regexp), encoding, encoding_errors, default_log_level, window_size, environ_user, is_truthy(terminal_emulation), terminal_type, telnetlib_log_level) return self._cache.register(self._conn, alias) def _parse_window_size(self, window_size): if not window_size: return None try: cols, rows = window_size.split('x', 1) return int(cols), int(rows) except ValueError: raise ValueError("Invalid window size '%s'. Should be " "<rows>x<columns>." % window_size) 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_log_level='TRACE'): 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) self._set_telnetlib_log_level(telnetlib_log_level) self._opt_responses = list() 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 secs_to_timestr(old) def _set_timeout(self, timeout): self._timeout = 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): newline = str(newline).upper() self._newline = newline.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 a true value (see `Boolean arguments`), 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 is_truthy(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 is_bytes(text): 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_telnetlib_log_level(self, level): """Sets the log level used for `logging` in the underlying ``telnetlib``. Note that ``telnetlib`` can be very noisy thus using the level ``NONE`` can shutdown the messages generated by this library. New in Robot Framework 2.8.7. """ self._verify_connection() old = self._telnetlib_log_level self._set_telnetlib_log_level(level) return old def _set_telnetlib_log_level(self, level): if level.upper() == 'NONE': self._telnetlib_log_level = 'NONE' elif self._is_valid_log_level(level) is False: raise AssertionError("Invalid log level '%s'" % level) self._telnetlib_log_level = level.upper() 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 is_string(level): 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(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 = timestr_to_secs(timeout) retry_interval = 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 write_control_character(self, character): """Writes the given control character into the connection. The control character is preprended with an IAC (interpret as command) character. The following control character names are supported: BRK, IP, AO, AYT, EC, EL, NOP. Additionally, you can use arbitrary numbers to send any control character. Example: | Write Control Character | BRK | # Send Break command | | Write Control Character | 241 | # Send No operation command | """ self._verify_connection() self.sock.sendall(telnetlib.IAC + self._get_control_character(character)) def _get_control_character(self, int_or_name): try: return chr(int(int_or_name)) except ValueError: return self._convert_control_code_name_to_character(int_or_name) def _convert_control_code_name_to_character(self, name): code_names = { 'BRK' : telnetlib.BRK, 'IP' : telnetlib.IP, 'AO' : telnetlib.AO, 'AYT' : telnetlib.AYT, 'EC' : telnetlib.EC, 'EL' : telnetlib.EL, 'NOP' : telnetlib.NOP } try: return code_names[name] except KeyError: raise RuntimeError("Unsupported control character '%s'." % name) 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 is_unicode(exp) 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 is_string(exp) else exp.pattern for exp in expected] raise NoMatchError(expected, self._timeout, output) return output def read_until_prompt(self, loglevel=None, strip_prompt=False): """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. By default, 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]. If you want to exclude the prompt from the returned output, set ``strip_prompt`` to a true value (see `Boolean arguments`). If your prompt is a regular expression, make sure that the expression spans the whole prompt, because only the part of the output that matches the regular expression is stripped away. See `Logging` section for more information about log levels. Optionally stripping prompt is a new feature in Robot Framework 2.8.7. """ 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, secs_to_timestr(self._timeout))) if is_truthy(strip_prompt): output = self._strip_prompt(output) 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 _strip_prompt(self, output): prompt, regexp = self._prompt if not regexp: length = len(prompt) else: match = prompt.search(output) length = match.end() - match.start() return output[:-length] def execute_command(self, command, loglevel=None, strip_prompt=False): """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 and `Read Until Prompt` for more information about the ``strip_prompt`` parameter. """ self.write(command, loglevel) return self.read_until_prompt(loglevel, strip_prompt) @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): # We don't have state changes in our accepted telnet options. # Therefore, we just track if we've already responded to an option. If # this is the case, we must not send any response. if cmd in (telnetlib.DO, telnetlib.DONT, telnetlib.WILL, telnetlib.WONT): if (cmd, opt) in self._opt_responses: return else: self._opt_responses.append((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 if self._telnetlib_log_level != 'NONE': logger.write(msg % args, self._telnetlib_log_level) 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_history_screen(self._screen.history.top) + self._newline return '' def _get_history_screen(self, deque): return self._newline.join(''.join(c.data for c in row).rstrip() for row in deque).rstrip(self._newline) def _get_screen(self, screen): return self._newline.join(row.rstrip() for row in screen.display).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 = secs_to_timestr(timeout) self.output = output AssertionError.__init__(self, self._get_message()) def _get_message(self): expected = "'%s'" % self.expected \ if is_string(self.expected) \ else 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
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/libraries/Telnet.py
0.809464
0.553023
Telnet.py
pypi
import sys 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 is_bytes, is_string, is_truthy, is_unicode, lower, 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 convert_to_lowercase(self, string): """Converts string to lowercase. Examples: | ${str1} = | Convert To Lowercase | ABC | | ${str2} = | Convert To Lowercase | 1A2c3D | | Should Be Equal | ${str1} | abc | | Should Be Equal | ${str2} | 1a2c3d | New in Robot Framework 2.8.6. """ # Custom `lower` needed due to IronPython bug. See its code and # comments for more details. return lower(string) def convert_to_uppercase(self, string): """Converts string to uppercase. Examples: | ${str1} = | Convert To Uppercase | abc | | ${str2} = | Convert To Uppercase | 1a2C3d | | Should Be Equal | ${str1} | ABC | | Should Be Equal | ${str2} | 1A2C3D | New in Robot Framework 2.8.6. """ return string.upper() 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): """Splits the given string to 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 | Use `Split To Lines` if all lines are needed. """ 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, not a glob or regexp pattern. A line matches if the ``pattern`` is found anywhere on it. The match is case-sensitive by default, but giving ``case_insensitive`` a true value makes it case-insensitive. The value is considered true if it is a non-empty string that is not equal to ``false`` or ``no``. If the value is not a string, its truth value is got directly in Python. 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 is_truthy(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. The match is case-sensitive by default, but giving ``case_insensitive`` a true value makes it case-insensitive. The value is considered true if it is a non-empty string that is not equal to ``false`` or ``no``. If the value is not a string, its truth value is got directly in Python. 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=true | See `Get Lines Matching Regexp` if you need more complex patterns and `Get Lines Containing String` if searching literal strings is enough. """ if is_truthy(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, partial_match=False): """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. By default lines match only if they match the pattern fully, but partial matching can be enabled by giving the ``partial_match`` argument a true value. The value is considered true if it is a non-empty string that is not equal to ``false`` or ``no``. If the value is not a string, its truth value is got directly in Python. If the pattern is empty, it matches only empty lines by default. When partial matching is enabled, empty pattern matches all lines. Notice that to make the match case-insensitive, you need to prefix the pattern with case-insensitive flag ``(?i)``. Lines are returned as one string concatenated 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 | | ${lines} = | Get Lines Matching Regexp | ${result} | Reg\\\\w{3} example | partial_match=true | | ${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). ``partial_match`` argument is new in Robot Framework 2.9. In earlier versions exact match was always required. """ if not is_truthy(partial_match): pattern = '^%s$' % pattern return self._get_matching_lines(string, re.compile(pattern).search) 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 get_regexp_matches(self, string, pattern, *groups): """Returns a list of all non-overlapping matches in the given string. ``string`` is the string to find matches from and ``pattern`` is the 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 no groups are used, the returned list contains full matches. If one group is used, the list contains only contents of that group. If multiple groups are used, the list contains tuples that contain individual group contents. All groups can be given as indexes (starting from 1) and named groups also as names. Examples: | ${no match} = | Get Regexp Matches | the string | xxx | | ${matches} = | Get Regexp Matches | the string | t.. | | ${one group} = | Get Regexp Matches | the string | t(..) | 1 | | ${named group} = | Get Regexp Matches | the string | t(?P<name>..) | name | | ${two groups} = | Get Regexp Matches | the string | t(.)(.) | 1 | 2 | => | ${no match} = [] | ${matches} = ['the', 'tri'] | ${one group} = ['he', 'ri'] | ${named group} = ['he', 'ri'] | ${two groups} = [('h', 'e'), ('r', 'i')] New in Robot Framework 2.9. """ regexp = re.compile(pattern) groups = [self._parse_group(g) for g in groups] return [m.group(*groups) for m in regexp.finditer(string)] def _parse_group(self, group): try: return int(group) except ValueError: return group 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 range(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 is_string(item): 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 is_string(item): 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 is_unicode(item): 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 is_bytes(item): 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`. """ 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`. """ 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`. """ 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)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/libraries/String.py
0.768646
0.555616
String.py
pypi
from robot.version import get_version from robot.utils import IRONPYTHON, JYTHON, is_truthy if JYTHON: from .dialogs_jy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog elif IRONPYTHON: from .dialogs_ipy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog else: from .dialogs_py import MessageDialog, PassFailDialog, InputDialog, SelectionDialog __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 a true value, the value typed by the user is hidden. ``hidden`` is considered true if it is a non-empty string not equal to ``false`` or ``no``, case-insensitively. If it is not a string, its truth value is got directly using same [http://docs.python.org/2/library/stdtypes.html#truth-value-testing|rules as in Python]. Example: | ${username} = | Get Value From User | Input user name | default | | ${password} = | Get Value From User | Input password | hidden=yes | Possibility to hide the typed in value is new in Robot Framework 2.8.4. Considering strings ``false`` and ``no`` to be false is new in 2.9. """ return _validate_user_input(InputDialog(message, default_value, is_truthy(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
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/libraries/Dialogs.py
0.838151
0.261131
Dialogs.py
pypi
import copy import re try: from lxml import etree as lxml_etree except ImportError: lxml_etree = None from robot.api import logger from robot.libraries.BuiltIn import BuiltIn from robot.utils import (asserts, ET, ETSource, is_string, is_truthy, 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 [https://docs.python.org/2/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`). By default this library uses ElementTree module for parsing XML, but it can be configured to use [http://lxml.de|lxml] instead when `importing` the library. The main benefit of using lxml is that it supports richer xpath syntax than the standard ElementTree. It also enables using `Evaluate Xpath` keyword and preserves possible namespace prefixes when saving XML. The lxml support is new in Robot Framework 2.8.5. == Table of contents == - `Parsing XML` - `Example` - `Finding elements with xpath` - `Element attributes` - `Handling XML namespaces` - `Boolean arguments` - `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`. Notice that keywords that modify XML do not write those changes back to disk even if the source would be given as a path to a fike. Changes must always saved explicitly using `Save XML` keyword. 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 2.7 supports richer syntax than earlier versions. 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. If lxml support is enabled when `importing` the library, the whole [http://www.w3.org/TR/xpath/|xpath 1.0 standard] is supported. That includes everything listed below but also lot of other useful constructs. == 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 and lxml handle 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 look identical. == Namespaces with lxml == Namespaces are handled the same way also if lxml mode is enabled when `importing` the library. The only difference is that lxml stores information about namespace prefixes and thus they are preserved if XML is saved. == 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 | = Boolean arguments = Some keywords accept arguments that are handled as Boolean values true or false. If such an argument is given as a string, it is considered false if it is either empty or case-insensitively equal to ``false`` or ``no``. Other strings are considered true regardless their value, 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: | `Parse XML` | ${XML} | keep_clark_notation=True | # Strings are generally true. | | `Parse XML` | ${XML} | keep_clark_notation=yes | # Same as the above. | | `Parse XML` | ${XML} | keep_clark_notation=${TRUE} | # Python ``True`` is true. | | `Parse XML` | ${XML} | keep_clark_notation=${42} | # Numbers other than 0 are true. | False examples: | `Parse XML` | ${XML} | keep_clark_notation=False | # String ``false`` is false. | | `Parse XML` | ${XML} | keep_clark_notation=no | # Also string ``no`` is false. | | `Parse XML` | ${XML} | keep_clark_notation=${EMPTY} | # Empty string is false. | | `Parse XML` | ${XML} | keep_clark_notation=${FALSE} | # Python ``False`` is false. | Note that prior to Robot Framework 2.9, all non-empty strings, including ``false`` and ``no``, were considered true. """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() _whitespace = re.compile('\s+') _xml_declaration = re.compile('^<\?xml .*\?>\n') def __init__(self, use_lxml=False): """Import library with optionally lxml mode enabled. By default this library uses Python's standard [https://docs.python.org/2/library/xml.etree.elementtree.html|ElementTree] module for parsing XML. If ``use_lxml`` argument is given a true value (see `Boolean arguments`), the library will use [http://lxml.de|lxml] instead. See `introduction` for benefits provided by lxml. Using lxml requires that the lxml module is installed on the system. If lxml mode is enabled but the module is not installed, this library will emit a warning and revert back to using the standard ElementTree. The support for lxml is new in Robot Framework 2.8.5. """ use_lxml = is_truthy(use_lxml) if use_lxml and lxml_etree: self.etree = lxml_etree self.modern_etree = True self.lxml_etree = True else: self.etree = ET self.modern_etree = ET.VERSION >= '1.3' self.lxml_etree = False if use_lxml and not lxml_etree: logger.warn('XML library reverted to use standard ElementTree ' 'because lxml module is not installed.') 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 (see `Boolean arguments`). 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 = self.etree.parse(source).getroot() if self.lxml_etree: self._remove_comments(root) if not is_truthy(keep_clark_notation): NameSpaceStripper().strip(root) return root def _remove_comments(self, node): for comment in node.xpath('//comment()'): parent = comment.getparent() if parent: self._preserve_tail(comment, parent) parent.remove(comment) 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 `Example`: | ${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. Many other keywords use this keyword internally, and keywords modifying XML are typically documented to both to modify the given source and to return it. Modifying the source does not apply if the source is given as a string. The XML structure parsed based on the string and then modified is nevertheless returned. """ 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 `Example`: | ${children} = | Get Elements | ${XML} | third/child | | Length Should Be | ${children} | 2 | | | ${children} = | Get Elements | ${XML} | first/child | | Should Be Empty | ${children} | | | """ if is_string(source): source = self.parse_xml(source) finder = ElementFinder(self.etree, self.modern_etree, self.lxml_etree) return finder.find_all(source, 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 `Example`: | ${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. 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 a true value (see `Boolean arguments`), 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 `Example`: | ${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 is_truthy(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 `Example`: | @{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 `Example`: | 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 `Example`: | 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 `Example`: | ${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 `Example`: | ${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 dict(self.get_element(source, xpath).attrib) 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 `Example`: | 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 `Example`: | 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 `Example`: | 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 a true value (see `Boolean arguments`). 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 a 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 `Example`: | ${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 `Example`: | ${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 is_truthy(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. The element whose tag to set is specified using ``source`` and ``xpath``. They have exactly the same semantics as with `Get Element` keyword. The resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. 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 | Can only set the tag of a single element. Use `Set Elements Tag` to set the tag of multiple elements in one call. New in Robot Framework 2.7.5. """ source = self.get_element(source) self.get_element(source, xpath).tag = tag return source def set_elements_tag(self, source, tag, xpath='.'): """Sets the tag of the specified elements. Like `Set Element Tag` but sets the tag of all elements matching the given ``xpath``. New in Robot Framework 2.8.6. """ for elem in self.get_elements(source, xpath): self.set_element_tag(elem, tag) 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 resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. 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 | Can only set the text/tail of a single element. Use `Set Elements Text` to set the text/tail of multiple elements in one call. 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_elements_text(self, source, text=None, tail=None, xpath='.'): """Sets text and/or tail text of the specified elements. Like `Set Element Text` but sets the text or tail of all elements matching the given ``xpath``. New in Robot Framework 2.8.6. """ for elem in self.get_elements(source, xpath): self.set_element_text(elem, text, tail) 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 resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. 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 | Can only set an attribute of a single element. Use `Set Elements Attribute` to set an attribute of multiple elements in one call. 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 set_elements_attribute(self, source, name, value, xpath='.'): """Sets attribute ``name`` of the specified elements to ``value``. Like `Set Element Attribute` but sets the attribute of all elements matching the given ``xpath``. New in Robot Framework 2.8.6. """ for elem in self.get_elements(source, xpath): self.set_element_attribute(elem, name, value) 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 resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. 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 | Can only remove an attribute from a single element. Use `Remove Elements Attribute` to remove an attribute of multiple elements in one call. 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_elements_attribute(self, source, name, xpath='.'): """Removes attribute ``name`` from the specified elements. Like `Remove Element Attribute` but removes the attribute of all elements matching the given ``xpath``. New in Robot Framework 2.8.6. """ for elem in self.get_elements(source, xpath): self.remove_element_attribute(elem, name) 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 resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. 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 | Can only remove attributes from a single element. Use `Remove Elements Attributes` to remove all attributes of multiple elements in one call. New in Robot Framework 2.7.5. """ source = self.get_element(source) self.get_element(source, xpath).attrib.clear() return source def remove_elements_attributes(self, source, xpath='.'): """Removes all attributes from the specified elements. Like `Remove Element Attributes` but removes all attributes of all elements matching the given ``xpath``. New in Robot Framework 2.8.6. """ for elem in self.get_elements(source, xpath): self.remove_element_attributes(elem) 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 resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. 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 resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. 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 (see `Boolean arguments`). 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 resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. It is not a failure if ``xpath`` matches no elements. Use `Remove Element` to remove exactly one element. 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 not is_truthy(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): if not element.tail: return 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 resulting XML structure is returned, and if the ``source`` is an already parsed XML structure, it is also modified in place. 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 (see `Boolean arguments`). 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 is_truthy(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 = self.etree.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. """ elem = self.get_element(source) if self.lxml_etree: NameSpaceStripper().unstrip(elem) tree = self.etree.ElementTree(elem) xml_declaration = {'xml_declaration': True} if self.modern_etree 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. # Opening in binary mode is important for Python 3, # because the ElementTree writes encoded bytes. with open(path, 'wb') as output: tree.write(output, encoding=encoding, **xml_declaration) def evaluate_xpath(self, source, expression, context='.'): """Evaluates the given xpath expression and returns results. The element in which context the expression is executed is specified using ``source`` and ``context`` arguments. They have exactly the same semantics as ``source`` and ``xpath`` arguments have with `Get Element` keyword. The xpath expression to evaluate is given as ``expression`` argument. The result of the evaluation is returned as-is. Examples using ``${XML}`` structure from `Example`: | ${count} = | Evaluate Xpath | ${XML} | count(third/*) | | Should Be Equal | ${count} | ${3} | | ${text} = | Evaluate Xpath | ${XML} | string(descendant::second[last()]/@id) | | Should Be Equal | ${text} | child | | ${bold} = | Evaluate Xpath | ${XML} | boolean(preceding-sibling::*[1] = 'bold') | context=html/p/i | | Should Be Equal | ${bold} | ${True} | This keyword works only if lxml mode is taken into use when `importing` the library. New in Robot Framework 2.8.5. """ if not self.lxml_etree: raise RuntimeError("'Evaluate Xpath' keyword only works in lxml mode.") return self.get_element(source, context).xpath(expression) class NameSpaceStripper(object): def strip(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.attrib['xmlns'] = ns current_ns = ns elif current_ns: elem.attrib['xmlns'] = '' current_ns = None for child in elem: self.strip(child, current_ns) def unstrip(self, elem, current_ns=None): ns = elem.attrib.pop('xmlns', current_ns) if ns: elem.tag = '{%s}%s' % (ns, elem.tag) for child in elem: self.unstrip(child, ns) class ElementFinder(object): def __init__(self, etree, modern=True, lxml=False): self.etree = etree self.modern = modern self.lxml = lxml def find_all(self, elem, xpath): xpath = self._get_xpath(xpath) if xpath == '.': # ET < 1.3 does not support '.' alone. return [elem] if not self.lxml: return elem.findall(xpath) finder = self.etree.ETXPath(xpath) return finder(elem) def _get_xpath(self, xpath): if not xpath: raise RuntimeError('No xpath given.') if self.modern: return 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 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 = is_truthy(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)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/libraries/XML.py
0.849909
0.565659
XML.py
pypi
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 from .robottypes import is_integer, is_list_like, is_string 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(object): _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._flag_opts = [] 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 as 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 is_list_like(value): 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._get_default_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._flag_opts: opts[name] = True elif name.startswith('no') and name[2:] in self._flag_opts: opts[name[2:]] = False else: opts[name] = value return opts def _get_default_opts(self): defaults = {} for opt in self._long_opts: opt = opt.rstrip('=') if opt.startswith('no') and opt[2:] in self._flag_opts: continue defaults[opt] = [] if opt in self._multi_opts else None return defaults 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 _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): self._verify_long_not_already_used(long_opt, not takes_arg) 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: if long_opt.startswith('no'): long_opt = long_opt[2:] self._long_opts.append('no' + long_opt) self._flag_opts.append(long_opt) self._long_opts.append(long_opt) self._short_opts += (''.join(short_opts)) def _verify_long_not_already_used(self, opt, flag=False): if flag: if opt.startswith('no'): opt = opt[2:] self._verify_long_not_already_used(opt) self._verify_long_not_already_used('no' + opt) elif opt in [o.rstrip('=') for o in self._long_opts]: self._raise_option_multiple_times_in_usage('--' + opt) def _get_pythonpath(self, paths): if is_string(paths): 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.ascii_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.maxsize if is_integer(arg_limits): return arg_limits, arg_limits if len(arg_limits) == 1: return arg_limits[0], sys.maxsize 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.maxsize: 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) as err: raise DataError("Opening argument file '%s' failed: %s" % (path, err)) def _read_from_stdin(self): return decode_output(sys.__stdin__.read()) 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 '='
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/utils/argumentparser.py
0.524151
0.196807
argumentparser.py
pypi
import difflib class RecommendationFinder(object): def __init__(self, normalizer=None): self.normalizer = normalizer or (lambda x: x) def find_recommendations(self, name, candidates, max_matches=10): """Return a list of close matches to `name` from `candidates`.""" if not name or not candidates: return [] norm_name = self.normalizer(name) norm_candidates = self._get_normalized_candidates(candidates) cutoff = self._calculate_cutoff(norm_name) norm_matches = difflib.get_close_matches(norm_name, norm_candidates, n=max_matches, cutoff=cutoff) return self._get_original_candidates(norm_candidates, norm_matches) @staticmethod def format_recommendations(msg, recommendations): """Add recommendations to the given message. The recommendation string looks like: <msg> Did you mean: <recommendations[0]> <recommendations[1]> <recommendations[2]> """ if recommendations: msg += " Did you mean:" for rec in recommendations: msg += "\n %s" % rec return msg def _get_normalized_candidates(self, candidates): norm_candidates = {} # sort before normalization for consistent Python/Jython ordering for cand in sorted(candidates): norm = self.normalizer(cand) norm_candidates.setdefault(norm, []).append(cand) return norm_candidates def _get_original_candidates(self, norm_candidates, norm_matches): candidates = [] for norm_match in norm_matches: candidates.extend(norm_candidates[norm_match]) return candidates def _calculate_cutoff(self, string, min_cutoff=.5, max_cutoff=.85, step=.03): """Calculate a cutoff depending on string length. Default values determined by manual tuning until the results "look right". """ cutoff = min_cutoff + len(string) * step return min(cutoff, max_cutoff)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/utils/recommendations.py
0.87142
0.279561
recommendations.py
pypi
from six import PY3 if PY3: from collections import MutableMapping as DictMixin else: from UserDict import DictMixin class OrderedDict(dict, DictMixin): def __init__(self, *args, **kwds): if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__end except AttributeError: self.clear() self.update(*args, **kwds) def clear(self): self.__end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.__map = {} # key --> [key, prev, next] dict.clear(self) def __setitem__(self, key, value): if key not in self: end = self.__end curr = end[1] curr[2] = end[1] = self.__map[key] = [key, curr, end] dict.__setitem__(self, key, value) def __delitem__(self, key): dict.__delitem__(self, key) key, prev, next = self.__map.pop(key) prev[2] = next next[1] = prev def __iter__(self): end = self.__end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): end = self.__end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def popitem(self, last=True): if not self: raise KeyError('dictionary is empty') if last: key = reversed(self).next() else: key = iter(self).next() value = self.pop(key) return key, value def __reduce__(self): items = [[k, self[k]] for k in self] tmp = self.__map, self.__end del self.__map, self.__end inst_dict = vars(self).copy() self.__map, self.__end = tmp if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,) def keys(self): return list(self) setdefault = DictMixin.setdefault update = DictMixin.update pop = DictMixin.pop values = DictMixin.values items = DictMixin.items if PY3: iterkeys = DictMixin.keys itervalues = DictMixin.values iteritems = DictMixin.items else: iterkeys = DictMixin.iterkeys itervalues = DictMixin.itervalues iteritems = DictMixin.iteritems def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) def copy(self): return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): if isinstance(other, OrderedDict): if len(self) != len(other): return False for p, q in zip(self.items(), other.items()): if p != q: return False return True return dict.__eq__(self, other) def __ne__(self, other): return not self == other
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/utils/ordereddict.py
0.502441
0.220636
ordereddict.py
pypi
from six import unichr import re from .robottypes import is_string _CONTROL_WORDS_TO_BE_ESCAPED = ('ELSE', 'ELSE IF', 'AND') _SEQUENCES_TO_BE_ESCAPED = ('\\', '${', '@{', '%{', '&{', '*{', '=') def escape(item): if not is_string(item): return item if item in _CONTROL_WORDS_TO_BE_ESCAPED: return '\\' + item for seq in _SEQUENCES_TO_BE_ESCAPED: if seq in item: item = item.replace(seq, '\\' + seq) return item def unescape(item): if not (is_string(item) 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():] def split_from_equals(string): index = _get_split_index(string) if index == -1: return string, None return string[:index], string[index+1:] def _get_split_index(string): index = 0 while '=' in string[index:]: index += string[index:].index('=') if _not_escaping(string[:index]): return index index += 1 return -1 def _not_escaping(name): backslashes = len(name) - len(name.rstrip('\\')) return backslashes % 2 == 0
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/utils/escaping.py
0.40439
0.1844
escaping.py
pypi
import re from functools import partial from .normalizing import normalize from .robottypes import is_string 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, regexp=False): self.pattern = pattern self._normalize = partial(normalize, ignore=ignore, caseless=caseless, spaceless=spaceless) self._regexp = self._get_and_compile_regexp(self._normalize(pattern), regexp=regexp) def _get_and_compile_regexp(self, pattern, regexp=False): if not regexp: pattern = '^%s$' % ''.join(self._glob_pattern_to_regexp(pattern)) return re.compile(pattern, re.DOTALL) def _glob_pattern_to_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) def __bool__(self): return bool(self._normalize(self.pattern)) #PY2 def __nonzero__(self): return self.__bool__() class MultiMatcher(object): def __init__(self, patterns=None, ignore=(), caseless=True, spaceless=True, match_if_no_patterns=False, regexp=False): self._matchers = [Matcher(pattern, ignore, caseless, spaceless, regexp) 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 is_string(patterns): 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
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/utils/match.py
0.61231
0.249025
match.py
pypi
from .robottypes import type_name 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 as 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 as 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)
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/utils/asserts.py
0.688154
0.291182
asserts.py
pypi
import re import sys from collections import MutableMapping from .robottypes import is_dict_like _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 # http://ironpython.codeplex.com/workitem/33133 if sys.platform == 'cli' and sys.version_info < (2, 7, 5): def lower(string): return ('A' + string).lower()[1:] else: def lower(string): return string.lower() class NormalizedDict(MutableMapping): """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. """ self._data = {} self._keys = {} self._normalize = lambda s: normalize(s, ignore, caseless, spaceless) if initial: self._add_initial(initial) def _add_initial(self, initial): items = initial.items() if hasattr(initial, 'items') else initial for key, value in items: self[key] = value def __getitem__(self, key): return self._data[self._normalize(key)] def __setitem__(self, key, value): norm_key = self._normalize(key) self._data[norm_key] = value self._keys.setdefault(norm_key, key) def __delitem__(self, key): norm_key = self._normalize(key) del self._data[norm_key] del self._keys[norm_key] def __iter__(self): return (self._keys[norm_key] for norm_key in sorted(self._keys)) def __len__(self): return len(self._data) def __str__(self): return str(dict(self.items())) def __eq__(self, other): if not is_dict_like(other): return False if not isinstance(other, NormalizedDict): other = NormalizedDict(other) return self._data == other._data def copy(self): copy = NormalizedDict() copy._data = self._data.copy() copy._keys = self._keys.copy() copy._normalize = self._normalize return copy def clear(self): # Faster than default implementation of MutableMapping.clear self._data.clear() self._keys.clear()
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/utils/normalizing.py
0.584627
0.326701
normalizing.py
pypi
from six import PY3, integer_types import sys class JsonWriter(object): def __init__(self, output, separator=''): self._writer = JsonDumper(output) self._separator = separator def write_json(self, prefix, data, postfix=';\n', mapping=None, separator=True): self._writer.write(prefix) self._writer.dump(data, mapping) self._writer.write(postfix) self._write_separator(separator) def write(self, string, postfix=';\n', separator=True): self._writer.write(string + postfix) self._write_separator(separator) def _write_separator(self, separator): if separator and self._separator: self._writer.write(self._separator) class JsonDumper(object): def __init__(self, output): self._output = output self._dumpers = (MappingDumper(self), IntegerDumper(self), TupleListDumper(self), StringDumper(self), BytesDumper(self), # Only Python 3 NoneDumper(self), DictDumper(self)) def dump(self, data, mapping=None): for dumper in self._dumpers: if dumper.handles(data, mapping): dumper.dump(data, mapping) return raise ValueError('Dumping %s not supported' % type(data)) def write(self, data): self._output.write(data) class _Dumper(object): _handled_types = None def __init__(self, jsondumper): self._dump = jsondumper.dump self._write = jsondumper.write def handles(self, data, mapping): return isinstance(data, self._handled_types) def dump(self, data, mapping): raise NotImplementedError class StringDumper(_Dumper): _handled_types = str if PY3 else basestring _search_and_replace = [('\\', '\\\\'), ('"', '\\"'), ('\t', '\\t'), ('\n', '\\n'), ('\r', '\\r'), ('</', '\\x3c/')] def dump(self, data, mapping): self._write('"%s"' % (self._encode(data) if data else '')) def _encode(self, string): for search, replace in self._search_and_replace: if search in string: string = string.replace(search, replace) if PY3: return string return string.encode('UTF-8') # For Python 3 class BytesDumper(StringDumper): try: _handled_types = bytes except NameError: pass def _encode(self, string): return StringDumper._encode(self, string.decode()) class IntegerDumper(_Dumper): _handled_types = integer_types + (bool,) def dump(self, data, mapping): self._write(str(data).lower()) class DictDumper(_Dumper): _handled_types = dict def dump(self, data, mapping): self._write('{') last_index = len(data) - 1 for index, key in enumerate(sorted(data)): self._dump(key, mapping) self._write(':') self._dump(data[key], mapping) if index < last_index: self._write(',') self._write('}') class TupleListDumper(_Dumper): _handled_types = (tuple, list) def dump(self, data, mapping): self._write('[') last_index = len(data) - 1 for index, item in enumerate(data): self._dump(item, mapping) if index < last_index: self._write(',') self._write(']') class MappingDumper(_Dumper): def handles(self, data, mapping): try: return mapping and data in mapping except TypeError: return False def dump(self, data, mapping): self._write(mapping[data]) class NoneDumper(_Dumper): def handles(self, data, mapping): return data is None def dump(self, data, mapping): self._write('null')
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/htmldata/jsonwriter.py
0.422028
0.158989
jsonwriter.py
pypi
import itertools class RowSplitter(object): _comment_mark = '#' _empty_cell_escape = '${EMPTY}' _line_continuation = '...' _setting_table = 'setting' _indented_tables = ('test case', 'keyword') _split_from = ('ELSE', 'ELSE IF', 'AND') def __init__(self, cols=8, split_multiline_doc=True): self._cols = cols self._split_multiline_doc = split_multiline_doc def split(self, row, table_type): if not row: return self._split_empty_row() indent = self._get_indent(row, table_type) if self._split_multiline_doc and self._is_doc_row(row, table_type): return self._split_doc_row(row, indent) return self._split_row(row, indent) def _split_empty_row(self): yield [] def _get_indent(self, row, table_type): indent = self._get_first_non_empty_index(row) min_indent = 1 if table_type in self._indented_tables else 0 return max(indent, min_indent) def _get_first_non_empty_index(self, row, indented=False): ignore = ['', '...'] if indented else [''] return len(list(itertools.takewhile(lambda x: x in ignore, row))) def _is_doc_row(self, row, table_type): if table_type == self._setting_table: return len(row) > 1 and row[0] == 'Documentation' if table_type in self._indented_tables: return len(row) > 2 and row[1] == '[Documentation]' return False def _split_doc_row(self, row, indent): first, rest = self._split_doc(row[indent+1]) yield row[:indent+1] + [first] + row[indent+2:] while rest: current, rest = self._split_doc(rest) row = [current] if current else [] yield self._continue_row(row, indent) def _split_doc(self, doc): if '\\n' not in doc: return doc, '' if '\\n ' in doc: doc = doc.replace('\\n ', '\\n') return doc.split('\\n', 1) def _split_row(self, row, indent): while row: current, row = self._split(row) yield self._escape_last_cell_if_empty(current) if row: row = self._continue_row(row, indent) def _split(self, data): index = min(self._get_possible_split_indices(data)) current, rest = data[:index], data[index:] rest = self._comment_rest_if_needed(current, rest) return current, rest def _get_possible_split_indices(self, data): min_index = self._get_first_non_empty_index(data, indented=True) + 1 for marker in self._split_from: if marker in data[min_index:]: yield data[min_index:].index(marker) + min_index yield self._cols def _comment_rest_if_needed(self, current, rest): if rest and any(c.startswith(self._comment_mark) for c in current) \ and not rest[0].startswith(self._comment_mark): rest = [self._comment_mark + ' ' + rest[0]] + rest[1:] return rest def _escape_last_cell_if_empty(self, row): if row and not row[-1].strip(): row = row[:-1] + [self._empty_cell_escape] return row def _continue_row(self, row, indent): row = [self._line_continuation] + row if indent + 1 < self._cols: row = [''] * indent + row return row
/robotframework-python3-2.9.tar.gz/robotframework-python3-2.9/src/robot/writer/rowsplitter.py
0.489748
0.271988
rowsplitter.py
pypi