code
stringlengths
1
1.72M
language
stringclasses
1 value
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import copy from robot import utils from robot.errors import FrameworkError, DataError from robot.variables import GLOBAL_VARIABLES, is_scalar_var from robot.common import UserErrorHandler from robot.output import LOGGER from robot.parsing.settings import Library, Variables, Resource import robot from userkeyword import UserLibrary from importer import Importer, ImportCache from runkwregister import RUN_KW_REGISTER from handlers import _XTimesHandler STDLIB_NAMES = ['BuiltIn', 'Collections', 'Dialogs', 'Easter', 'OperatingSystem', 'Remote', 'Reserved', 'Screenshot', 'String', 'Telnet'] IMPORTER = Importer() class Namespace: """A database for keywords and variables. A new instance of this class is created for each test suite. """ def __init__(self, suite, parent_vars, skip_imports=False): if suite is not None: LOGGER.info("Initializing namespace for test suite '%s'" % suite.longname) self.variables = _VariableScopes(suite, parent_vars) self.suite = suite self.test = None self.uk_handlers = [] self.library_search_order = [] self._testlibs = {} self._userlibs = [] self._imported_resource_files = ImportCache() self._imported_variable_files = ImportCache() self.import_library('BuiltIn') self.import_library('Reserved') self.import_library('Easter') if suite.source and not skip_imports: self._handle_imports(suite.imports) robot.running.NAMESPACES.start_suite(self) self.variables['${SUITE_NAME}'] = suite.longname self.variables['${SUITE_SOURCE}'] = suite.source def _handle_imports(self, import_settings): for item in import_settings: try: if not item.name: raise DataError('%s setting requires a name' % item.type) self._import(item) except: item.report_invalid_syntax(utils.get_error_message()) def _import(self, import_setting): try: action = {'Library': self._import_library, 'Resource': self._import_resource, 'Variables': self._import_variables}[import_setting.type] action(import_setting, self.variables.current) except KeyError: raise FrameworkError("Invalid import setting: %s" % import_setting) def import_resource(self, name): self._import_resource(Resource(None, name)) def _import_resource(self, import_setting, variables=None): path = self._resolve_name(import_setting, variables) if path not in self._imported_resource_files: self._imported_resource_files.add(path) resource = IMPORTER.import_resource(path) self.variables.set_from_variable_table(resource.variable_table) self._userlibs.append(UserLibrary(resource.keyword_table.keywords, resource.source)) self._handle_imports(resource.setting_table.imports) else: LOGGER.info("Resource file '%s' already imported by suite '%s'" % (path, self.suite.longname)) def import_variables(self, name, args, overwrite=False, variables=None): self._import_variables(Variables(None, name, args), variables, overwrite) def _import_variables(self, import_setting, variables, overwrite=False): path = self._resolve_name(import_setting, variables) args = self._resolve_args(import_setting, variables) if (path, args) not in self._imported_variable_files: self._imported_variable_files.add((path,args)) self.variables.set_from_file(path, args, overwrite) else: msg = "Variable file '%s'" % path if args: msg += " with arguments %s" % utils.seq2str2(args) LOGGER.info("%s already imported by suite '%s'" % (msg, self.suite.longname)) def import_library(self, name, args=None, alias=None, variables=None): self._import_library(Library(None, name, args=args, alias=alias), variables) def _import_library(self, import_setting, variables): name = self._get_library_name(import_setting, variables) lib = IMPORTER.import_library(name, import_setting.args, import_setting.alias, variables) if lib.name in self._testlibs: LOGGER.info("Test library '%s' already imported by suite '%s'" % (lib.name, self.suite.longname)) return self._testlibs[lib.name] = lib lib.start_suite() if self.test: lib.start_test() self._import_deprecated_standard_libs(lib.name) def _get_library_name(self, import_setting, variables): name = self._resolve_name(import_setting, variables) if os.path.exists(name): return name return name.replace(' ', '') def _resolve_name(self, import_setting, variables): """Resolves variables from the import_setting name Returns absolute path to file if it exists or resolved import_setting name. """ if variables: try: name = variables.replace_string(import_setting.name) except DataError, err: self._report_replacing_vars_failed(import_setting, err) else: name = import_setting.name basedir = import_setting.directory or '' return self._get_path(import_setting.type, name, basedir) def _report_replacing_vars_failed(self, import_setting, err): raise DataError("Replacing variables from setting '%s' failed: %s" % (import_setting.type, unicode(err))) def _resolve_args(self, import_setting, variables): if not variables: return import_setting.args try: return variables.replace_list(import_setting.args) except DataError, err: self._report_replacing_vars_failed(import_setting, err) def _get_path(self, setting_name, path, basedir): if setting_name == 'Library' and not self._is_library_by_path(path, basedir): return path path = self._resolve_path(setting_name, path.replace('/', os.sep), basedir) return utils.abspath(path) def _is_library_by_path(self, path, basedir): return path.lower().endswith(('.py', '.java', '.class', '/')) def _resolve_path(self, setting_name, path, basedir): for base in [basedir] + sys.path: if not os.path.isdir(base): continue ret = os.path.join(base, path) if os.path.isfile(ret): return ret if os.path.isdir(ret) and os.path.isfile(os.path.join(ret, '__init__.py')): return ret name = {'Library': 'Test library', 'Variables': 'Variable file', 'Resource': 'Resource file'}[setting_name] raise DataError("%s '%s' does not exist." % (name, path)) def _import_deprecated_standard_libs(self, name): if name in ['BuiltIn', 'OperatingSystem']: self.import_library('Deprecated' + name) def start_test(self, test): self.variables.start_test(test) self.test = test for lib in self._testlibs.values(): lib.start_test() self.variables['${TEST_NAME}'] = test.name self.variables['@{TEST_TAGS}'] = test.tags def end_test(self): self.test = None self.variables.end_test() self.uk_handlers = [] for lib in self._testlibs.values(): lib.end_test() def set_test_status_before_teardown(self, message, status): self.variables['${TEST_MESSAGE}'] = message self.variables['${TEST_STATUS}'] = status def end_suite(self): self.suite = None self.variables.end_suite() for lib in self._testlibs.values(): lib.end_suite() robot.running.NAMESPACES.end_suite() def start_user_keyword(self, handler): self.variables.start_uk(handler) self.uk_handlers.append(handler) def end_user_keyword(self): self.variables.end_uk() self.uk_handlers.pop() def get_library_instance(self, libname): try: return self._testlibs[libname.replace(' ', '')].get_instance() except KeyError: raise DataError("No library with name '%s' found." % libname) def get_handler(self, name): try: handler = self._get_handler(name) if handler is None: raise DataError("No keyword with name '%s' found." % name) except: error = utils.get_error_message() handler = UserErrorHandler(name, error) self._replace_variables_from_user_handlers(handler) return handler def _replace_variables_from_user_handlers(self, handler): if hasattr(handler, 'replace_variables'): handler.replace_variables(self.variables) def _get_handler(self, name): handler = None if not name: raise DataError('Keyword name cannot be empty.') if '.' in name: handler = self._get_explicit_handler(name) if not handler: handler = self._get_implicit_handler(name) if not handler: handler = self._get_bdd_style_handler(name) if not handler: handler = self._get_x_times_handler(name) return handler def _get_x_times_handler(self, name): if not self._is_old_x_times_syntax(name): return None return _XTimesHandler(self._get_handler('Repeat Keyword'), name) def _is_old_x_times_syntax(self, name): if not name.lower().endswith('x'): return False times = name[:-1].strip() if is_scalar_var(times): return True try: int(times) except ValueError: return False else: return True def _get_bdd_style_handler(self, name): for prefix in ['given ', 'when ', 'then ', 'and ']: if name.lower().startswith(prefix): handler = self._get_handler(name[len(prefix):]) if handler: handler = copy.copy(handler) handler.name = name return handler return None def _get_implicit_handler(self, name): for method in [self._get_handler_from_test_case_file_user_keywords, self._get_handler_from_resource_file_user_keywords, self._get_handler_from_library_keywords]: handler = method(name) if handler: return handler return None def _get_handler_from_test_case_file_user_keywords(self, name): if self.suite.user_keywords.has_handler(name): return self.suite.user_keywords.get_handler(name) def _get_handler_from_resource_file_user_keywords(self, name): found = [lib.get_handler(name) for lib in self._userlibs if lib.has_handler(name)] if not found: return None if len(found) == 1: return found[0] self._raise_multiple_keywords_found(name, found) def _get_handler_from_library_keywords(self, name): found = [lib.get_handler(name) for lib in self._testlibs.values() if lib.has_handler(name)] if not found: return None if len(found) > 1: found = self._get_handler_based_on_library_search_order(found) if len(found) == 2: found = self._filter_stdlib_handler(found[0], found[1]) if len(found) == 1: return found[0] self._raise_multiple_keywords_found(name, found) def _get_handler_based_on_library_search_order(self, handlers): for libname in self.library_search_order: libname = libname.replace(' ', '') for handler in handlers: if handler.library.name.replace(' ', '') == libname: return [handler] return handlers def _filter_stdlib_handler(self, handler1, handler2): if handler1.library.orig_name in STDLIB_NAMES: standard, external = handler1, handler2 elif handler2.library.orig_name in STDLIB_NAMES: standard, external = handler2, handler1 else: return [handler1, handler2] if not RUN_KW_REGISTER.is_run_keyword(external.library.orig_name, external.name): LOGGER.warn( "Keyword '%s' found both from a user created test library " "'%s' and Robot Framework standard library '%s'. The user " "created keyword is used. To select explicitly, and to get " "rid of this warning, use either '%s' or '%s'." % (standard.name, external.library.orig_name, standard.library.orig_name, external.longname, standard.longname)) return [external] def _get_explicit_handler(self, name): libname, kwname = self._split_keyword_name(name) # 1) Find matching lib(s) libs = [lib for lib in self._userlibs + self._testlibs.values() if utils.eq(lib.name, libname)] if not libs: return None # 2) Find matching kw from found libs found = [lib.get_handler(kwname) for lib in libs if lib.has_handler(kwname)] if len(found) > 1: self._raise_multiple_keywords_found(name, found, implicit=False) return found and found[0] or None def _split_keyword_name(self, name): parts = name.split('.') kwname = parts.pop() # pop last part libname = '.'.join(parts) # and rejoin rest return libname, kwname def _raise_multiple_keywords_found(self, name, found, implicit=True): error = "Multiple keywords with name '%s' found.\n" % name if implicit: error += "Give the full name of the keyword you want to use.\n" names = sorted(handler.longname for handler in found) error += "Found: %s" % utils.seq2str(names) raise DataError(error) class _VariableScopes: def __init__(self, suite, parent_vars): # suite and parent are None only when used by copy_all if suite is not None: suite.variables.update(GLOBAL_VARIABLES) self._suite = self.current = suite.variables else: self._suite = self.current = None self._parents = [] if parent_vars is not None: self._parents.append(parent_vars.current) self._parents.extend(parent_vars._parents) self._test = None self._uk_handlers = [] def __len__(self): if self.current: return len(self.current) return 0 def copy_all(self): vs = _VariableScopes(None, None) vs._suite = self._suite vs._test = self._test vs._uk_handlers = self._uk_handlers[:] vs._parents = self._parents[:] vs.current = self.current return vs def replace_list(self, items): return self.current.replace_list(items) def replace_scalar(self, items): return self.current.replace_scalar(items) def replace_string(self, string): return self.current.replace_string(string) def replace_from_beginning(self, how_many, args): # There might be @{list} variables and those might have more or less # arguments that is needed. Therefore we need to go through arguments # one by one. processed = [] while len(processed) < how_many and args: processed += self.current.replace_list([args.pop(0)]) # In case @{list} variable is unpacked, the arguments going further # needs to be escaped, otherwise those are unescaped twice. processed[how_many:] = [utils.escape(arg) for arg in processed[how_many:]] return processed + args def set_from_file(self, path, args, overwrite=False): variables = self._suite.set_from_file(path, args, overwrite) if self._test is not None: self._test._set_from_file(variables, overwrite=True, path=path) for varz in self._uk_handlers: varz._set_from_file(variables, overwrite=True, path=path) if self._uk_handlers: self.current._set_from_file(variables, overwrite=True, path=path) def set_from_variable_table(self, rawvariables): self._suite.set_from_variable_table(rawvariables) # TODO: This should be removed so that these objects themselves had # the capability of resolving variables. def replace_meta(self, name, item, errors): error = None for varz in [self.current] + self._parents: try: if name == 'Documentation': return varz.replace_string(item, ignore_errors=True) elif isinstance(item, basestring): return varz.replace_string(item) return varz.replace_list(item) except DataError, error: pass errors.append("Replacing variables from setting '%s' failed: %s" % (name, error)) return utils.unescape(item) def __getitem__(self, name): return self.current[name] def __setitem__(self, name, value): self.current[name] = value def end_suite(self): self._suite = self._test = self.current = None def start_test(self, test): self._test = self.current = self._suite.copy() def end_test(self): self.current = self._suite def start_uk(self, handler): self._uk_handlers.append(self.current) self.current = self.current.copy() def end_uk(self): self.current = self._uk_handlers.pop() def set_global(self, name, value): GLOBAL_VARIABLES.__setitem__(name, value) for ns in robot.running.NAMESPACES: ns.variables.set_suite(name, value) def set_suite(self, name, value): self._suite.__setitem__(name, value) self.set_test(name, value, False) def set_test(self, name, value, fail_if_no_test=True): if self._test is not None: self._test.__setitem__(name, value) elif fail_if_no_test: raise DataError("Cannot set test variable when no test is started") for varz in self._uk_handlers: varz.__setitem__(name, value) self.current.__setitem__(name, value) def keys(self): return self.current.keys() def has_key(self, key): return self.current.has_key(key)
Python
#!/usr/bin/env python # Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rebot -- Robot Framework Report and Log Generator Version: <VERSION> Usage: rebot [options] robot_outputs or: interpreter /path/robot/rebot.py [options] robot_outputs or python -m robot.rebot [options] robot_outputs Inputs to Rebot are XML output files generated by Robot Framework test runs or earlier Rebot executions. Rebot can be used to generate logs, reports and summary reports in HTML format. It can also produce new XML output files which can be further processed with Rebot or other tools. When more than one input file is given, a new combined test suite containing information from given files is created. This allows combining multiple outputs together to create higher level reports. For more information about Robot Framework run 'pybot --help' or go to http://robotframework.org. Options: -N --name name Set the name of the top level test suite. Underscores in the name are converted to spaces. Default name is created from the name of the executed data source. -D --doc documentation Set the documentation of the top level test suite. Underscores in the documentation are converted to spaces and it may also contain simple HTML formatting (e.g. *bold* and http://url/). -M --metadata name:value * Set metadata of the top level test suite. Underscores in the name and value are converted to spaces. Value can contain same HTML formatting as --doc. Example: '--metadata version:1.2' -G --settag tag * Sets given tag(s) to all executed test cases. -t --test name * Select test cases to run by name or long name. Name is case and space insensitive and it can also be a simple pattern where '*' matches anything and '?' matches any char. If using '*' and '?' in the console is problematic see --escape and --argumentfile. -s --suite name * Select test suites by name. When this option is used with --test, --include or --exclude, only test cases in matching suites and also matching other filtering criteria are selected. Given name can be a simple pattern similarly as with --test. -i --include tag * Select test cases to run by tag. Similarly as name in --test, tag is case and space insensitive. There are three ways to include test based on tags: 1) One tag as a simple pattern. Tests having a tag matching the pattern are included. Example: 'it-*' 2) Two or more tags (or patterns) separated by '&' or 'AND'. Only tests having all these tags are included. Examples: 'tag1&tag2', 'smokeANDowner-*ANDit-10' 3) Two or more tags (or patterns) separated by 'NOT'. Tests having the first tag but not any of the latter ones are included. Example: 'it-10NOTsmoke' -e --exclude tag * Select test cases not to run by tag. These tests are not run even if they are included with --include. Tags are excluded using the rules explained in --include. -c --critical tag * Tests having given tag are considered critical. If no critical tags are set, all tags are critical. Tags can be given as a pattern like e.g. with --test. Resets possible critical tags set earlier. -n --noncritical tag * Tests with given tag are not critical even if they have a tag set with --critical. Tag can be a pattern. Resets possible non critical tags set earlier. -d --outputdir dir Where to create output files. The default is the directory where Rebot is run from and the given path is considered relative to that unless it is absolute. -o --output file XML output file. Not created unless this option is specified. Given path, similarly as paths given to --log, --report and --summary, is relative to --outputdir unless given as an absolute path. Default is 'output.xml'. Example: '--output out.xml' -l --log file HTML log file. Can be disabled by giving a special name 'NONE'. Examples: '--log mylog.html', '-l none' -r --report file HTML report file. Can be disabled with 'NONE' similarly as --log. Default is 'report.html'. -S --summary file HTML summary report. Not created unless this option is specified. Example: '--summary summary.html' -x --xunitfile file xUnit compatible result file. Not created unless this option is specified. -T --timestampoutputs When this option is used, timestamp in a format 'YYYYMMDD-hhmmss' is added to all generated output files between their basename and extension. For example '-T -o output.xml -r report.html -l none' creates files like 'output-20070503-154410.xml' and 'report-20070503-154410.html'. --splitoutputs level Splitting outputs is not supported in version 2.6 or newer. This option will be removed altogether in 2.7. --logtitle title Title for the generated test log. The default title is '<Name Of The Suite> Test Log'. Underscores in the title are converted into spaces in all titles. --reporttitle title Title for the generated test report. The default title is '<Name Of The Suite> Test Report'. --summarytitle title Title for the generated summary report. The default title is '<Name Of The Suite> Summary Report'. --reportbackground colors Background colors to use in report and summary. Either 'all_passed:critical_passed:failed' or 'passed:failed'. Both color names and codes work. Examples: --reportbackground green:yellow:red --reportbackground #00E:#E00 -L --loglevel level Threshold for selecting messages. Available levels: TRACE (default), DEBUG, INFO, WARN, NONE (no msgs) --suitestatlevel level How many levels to show in 'Statistics by Suite' in log and report. By default all suite levels are shown. Example: --suitestatlevel 3 --tagstatinclude tag * Include only matching tags in 'Statistics by Tag' and 'Test Details' in log and report. By default all tags set in test cases are shown. Given 'tag' can also be a simple pattern (see e.g. --test). --tagstatexclude tag * Exclude matching tags from 'Statistics by Tag' and 'Test Details'. This option can be used with --tagstatinclude similarly as --exclude is used with --include. --tagstatcombine tags:name * Create combined statistics based on tags. These statistics are added into 'Statistics by Tag' and matching tests into 'Test Details'. If optional 'name' is not given, name of the combined tag is got from the specified tags. Tags are combined using the rules explained in --include. Examples: --tagstatcombine tag1ANDtag2:My_name --tagstatcombine requirement-* --tagdoc pattern:doc * Add documentation to tags matching given pattern. Documentation is shown in 'Test Details' and also as a tooltip in 'Statistics by Tag'. Pattern can contain characters '*' (matches anything) and '?' (matches any char). Documentation can contain formatting similarly as with --doc option. Examples: --tagdoc mytag:My_documentation --tagdoc regression:*See*_http://info.html --tagdoc owner-*:Original_author --tagstatlink pattern:link:title * Add external links into 'Statistics by Tag'. Pattern can contain characters '*' (matches anything) and '?' (matches any char). Characters matching to wildcard expressions can be used in link and title with syntax %N, where N is index of the match (starting from 1). In title underscores are automatically converted to spaces. Examples: --tagstatlink mytag:http://my.domain:Link --tagstatlink bug-*:http://tracker/id=%1:Bug_Tracker --removekeywords all|passed Remove keyword data from generated outputs. Keyword data is not needed when creating reports and removing it can make the size of an output file considerably smaller. 'all' - remove data from all keywords 'passed' - remove data only from keywords in passed test cases and suites --starttime timestamp Set starting time of test execution when creating reports. Timestamp must be given in format '2007-10-01 15:12:42.268' where all separators are optional (e.g. '20071001151242268' is ok too) and parts from milliseconds to hours can be omitted if they are zero (e.g. '2007-10-01'). This can be used to override starttime of the suite when reports are created from a single suite or to set starttime for combined suite, which is otherwise set to 'N/A'. --endtime timestamp Same as --starttime but for ending time. If both options are used, elapsed time of the suite is calculated based on them. For combined suites, it is otherwise calculated by adding elapsed times of combined test suites together. --nostatusrc Sets the return code to zero regardless of failures in test cases. Error codes are returned normally. -C --monitorcolors on|off|force Using ANSI colors in console. Normally colors work in unixes but not in Windows. Default is 'on'. 'on' - use colors in unixes but not in Windows 'off' - never use colors 'force' - always use colors (also in Windows) -E --escape what:with * Escape characters which are problematic in console. 'what' is the name of the character to escape and 'with' is the string to escape it with. Note that all given arguments, incl. data sources, are escaped so escape characters ought to be selected carefully. <---------------------ESCAPES-----------------------> Examples: --escape space:_ --metadata X:Value_with_spaces -E space:SP -E quot:Q -v var:QhelloSPworldQ -A --argumentfile path * Text file to read more arguments from. File can have both options and data sources one per line. Contents don't need to be escaped but spaces in the beginning and end of lines are removed. Empty lines and lines starting with a hash character (#) are ignored. Example file: | --include regression | --name Regression Tests | # This is a comment line | my_tests.html | path/to/test/directory/ -h -? --help Print usage instructions. --version Print version information. Options that are marked with an asterisk (*) can be specified multiple times. For example '--test first --test third' selects test cases with name 'first' and 'third'. If other options are given multiple times, the last value is used. Long option format is case-insensitive. For example --SuiteStatLevel is equivalent to, but easier to read than, --suitestatlevel. Long options can also be shortened as long as they are unique. For example '--logti Title' works while '--lo log.html' does not because the former matches only --logtitle but latter matches both --log and --logtitle. Environment Variables: ROBOT_SYSLOG_FILE Path to the syslog file. If not specified, or set to special value 'NONE', writing to syslog file is disabled. Path must be absolute. ROBOT_SYSLOG_LEVEL Log level to use when writing to the syslog file. Available levels are the same as for --loglevel option to Robot and the default is INFO. Examples: # Simple Rebot run that creates log and report with default names. $ rebot output.xml # Using options. Note that this is one long command split into multiple lines. $ rebot --log none --report myreport.html --reporttitle My_Report --summary mysummary.html --summarytitle My_Summary --TagStatCombine smokeANDmytag path/to/myoutput.xml # Running 'robot/rebot.py' directly and creating combined outputs. $ python /path/robot/rebot.py -N Project_X -l x.html -r x.html outputs/*.xml """ import sys try: import pythonpathsetter except ImportError: # Get here when run as 'python -m robot.rebot' and then importing robot # works without this and pythonpathsetter is imported again later. pass import robot if __name__ == '__main__': rc = robot.rebot_from_cli(sys.argv[1:], __doc__) sys.exit(rc)
Python
#!/usr/bin/env python # Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Robot Framework -- A keyword-driven test automation framework Version: <VERSION> Usage: pybot [options] data_sources or: jybot [options] data_sources or: interpreter /path/robot/runner.py [options] data_sources or: python -m robot.runner [options] data_sources Robot Framework is a Python-based keyword-driven test automation framework for acceptance level testing and acceptance test-driven development (ATDD). It has an easy-to-use tabular syntax for creating test cases and its testing capabilities can be extended by test libraries implemented either with Python or Java. Users can also create new keywords from existing ones using the same simple syntax that is used for creating test cases. Robot Framework has two start-up scripts, 'pybot' and 'jybot', which run it on Python and Jython interpreters, respectively. Alternatively it is possible to directly call 'robot/runner.py' script using a selected interpreter. Data sources given to Robot Framework are either test case files or directories containing them and/or other directories. Single test case file creates a test suite containing all the test cases in it and a directory containing test case files creates a higher level test suite with test case files or other directories as sub test suites. If multiple data sources are given, a virtual test suite containing suites generated from given data sources is created. By default Robot Framework creates an XML output file and a log and a report in HTML format, but this can be configured using various options listed below. Outputs in HTML format are for human consumption and XML output for integration with other systems. XML outputs can also be combined and otherwise further processed with Rebot tool. Run 'rebot --help' for more information. Robot Framework is open source software released under Apache License 2.0. Its copyrights are owned and development supported by Nokia Siemens Networks. For more information about the framework see http://robotframework.org. Options: -N --name name Set the name of the top level test suite. Underscores in the name are converted to spaces. Default name is created from the name of the executed data source. -D --doc documentation Set the documentation of the top level test suite. Underscores in the documentation are converted to spaces and it may also contain simple HTML formatting (e.g. *bold* and http://url/). -M --metadata name:value * Set metadata of the top level test suite. Underscores in the name and value are converted to spaces. Value can contain same HTML formatting as --doc. Example: '--metadata version:1.2' -G --settag tag * Sets given tag(s) to all executed test cases. -t --test name * Select test cases to run by name or long name. Name is case and space insensitive and it can also be a simple pattern where '*' matches anything and '?' matches any char. If using '*' and '?' in the console is problematic see --escape and --argumentfile. -s --suite name * Select test suites to run by name. When this option is used with --test, --include or --exclude, only test cases in matching suites and also matching other filtering criteria are selected. Name can be a simple pattern similarly as with --test and it can contain parent name separated with a dot. For example '-s X.Y' selects suite 'Y' only if its parent is 'X'. -i --include tag * Select test cases to run by tag. Similarly as name in --test, tag is case and space insensitive. There are three ways to include test based on tags: 1) One tag as a simple pattern. Tests having a tag matching the pattern are included. Example: 'it-*' 2) Two or more tags (or patterns) separated by '&' or 'AND'. Only tests having all these tags are included. Examples: 'tag1&tag2', 'smokeANDowner-*ANDit-10' 3) Two or more tags (or patterns) separated by 'NOT'. Tests having the first tag but not any of the latter ones are included. Example: 'it-10NOTsmoke' -e --exclude tag * Select test cases not to run by tag. These tests are not run even if they are included with --include. Tags are excluded using the rules explained in --include. -c --critical tag * Tests having given tag are considered critical. If no critical tags are set, all tags are critical. Tags can be given as a pattern like e.g. with --test. -n --noncritical tag * Tests with given tag are not critical even if they have a tag set with --critical. Tag can be a pattern. -v --variable name:value * Set variables in the test data. Only scalar variables are supported and name is given without '${}'. See --escape for how to use special characters and --variablefile for a more powerful variable setting mechanism that allows also list variables. Examples: --variable str:Hello => ${str} = 'Hello' -v str:Hi_World -E space:_ => ${str} = 'Hi World' -v x: -v y:42 => ${x} = '', ${y} = '42' -V --variablefile path * File to read variables from (e.g. 'path/vars.py'). Example file: | import random | __all__ = ['scalar','LIST__var','integer'] | scalar = 'Hello world!' | LIST__var = ['Hello','list','world'] | integer = random.randint(1,10) => ${scalar} = 'Hello world!' @{var} = ['Hello','list','world'] ${integer} = <random integer from 1 to 10> -d --outputdir dir Where to create output files. The default is the directory where tests are run from and the given path is considered relative to that unless it is absolute. -o --output file XML output file. Given path, similarly as paths given to --log, --report, --summary, --debugfile and --xunitfile, is relative to --outputdir unless given as an absolute path. Other output files are created from XML output file after the test execution and XML output can also be further processed with Rebot tool (e.g. combined with other XML output files). Can be disabled by giving a special value 'NONE'. In this case, also log and report are automatically disabled. Default: output.xml -l --log file HTML log file. Can be disabled by giving a special value 'NONE'. Default: log.html Examples: '--log mylog.html', '-l NONE' -r --report file HTML report file. Can be disabled with 'NONE' similarly as --log. Default: report.html -S --summary file HTML summary report. Not created unless this option is specified. Example: '--summary summary.html' -x --xunitfile file xUnit compatible result file. Not created unless this option is specified. -b --debugfile file Debug file written during execution. Not created unless this option is specified. -T --timestampoutputs When this option is used, timestamp in a format 'YYYYMMDD-hhmmss' is added to all generated output files between their basename and extension. For example '-T -o output.xml -r report.html -l none' creates files like 'output-20070503-154410.xml' and 'report-20070503-154410.html'. --splitoutputs level Splitting outputs is not supported in version 2.6 or newer. This option will be removed altogether in 2.7. --logtitle title Title for the generated test log. The default title is '<Name Of The Suite> Test Log'. Underscores in the title are converted into spaces in all titles. --reporttitle title Title for the generated test report. The default title is '<Name Of The Suite> Test Report'. --summarytitle title Title for the generated summary report. The default title is '<Name Of The Suite> Summary Report'. --reportbackground colors Background colors to use in report and summary. Either 'all_passed:critical_passed:failed' or 'passed:failed'. Both color names and codes work. Examples: --reportbackground green:yellow:red --reportbackground #00E:#E00 -L --loglevel level Threshold level for logging. Available levels: TRACE, DEBUG, INFO (default), WARN, NONE (no logging) --suitestatlevel level How many levels to show in 'Statistics by Suite' in log and report. By default all suite levels are shown. Example: --suitestatlevel 3 --tagstatinclude tag * Include only matching tags in 'Statistics by Tag' and 'Test Details' in log and report. By default all tags set in test cases are shown. Given 'tag' can also be a simple pattern (see e.g. --test). --tagstatexclude tag * Exclude matching tags from 'Statistics by Tag' and 'Test Details'. This option can be used with --tagstatinclude similarly as --exclude is used with --include. --tagstatcombine tags:name * Create combined statistics based on tags. These statistics are added into 'Statistics by Tag' and matching tests into 'Test Details'. If optional 'name' is not given, name of the combined tag is got from the specified tags. Tags are combined using the rules explained in --include. Examples: --tagstatcombine tag1ANDtag2:My_name --tagstatcombine requirement-* --tagdoc pattern:doc * Add documentation to tags matching given pattern. Documentation is shown in 'Test Details' and also as a tooltip in 'Statistics by Tag'. Pattern can contain characters '*' (matches anything) and '?' (matches any char). Documentation can contain formatting similarly as with --doc option. Examples: --tagdoc mytag:My_documentation --tagdoc regression:*See*_http://info.html --tagdoc owner-*:Original_author --tagstatlink pattern:link:title * Add external links into 'Statistics by Tag'. Pattern can contain characters '*' (matches anything) and '?' (matches any char). Characters matching to wildcard expressions can be used in link and title with syntax %N, where N is index of the match (starting from 1). In title underscores are automatically converted to spaces. Examples: --tagstatlink mytag:http://my.domain:Link --tagstatlink bug-*:http://tracker/id=%1:Bug_Tracker --listener class * A class for monitoring test execution. Gets notifications e.g. when a test case starts and ends. Arguments to listener class can be given after class name, using colon as separator. For example: --listener MyListenerClass:arg1:arg2 --warnonskippedfiles If this option is used, skipped files will cause a warning that is visible to console output and log files. By default skipped files only cause an info level syslog message. --nostatusrc Sets the return code to zero regardless of failures in test cases. Error codes are returned normally. --runemptysuite Executes tests also if the top level test suite is empty. Useful e.g. with --include/--exclude when it is not an error that no test matches the condition. --runmode mode * Possible values are 'Random:Test', 'Random:Suite', 'Random:All', 'ExitOnFailure', 'SkipTeardownOnExit', and 'DryRun' (case-insensitive). First three change the execution order of tests, suites, or both. 'ExitOnFailure' stops test execution if a critical test fails. 'SkipTeardownOnExit' causes teardowns to be skipped if test execution is stopped prematurely. In the 'DryRun' test data is verified and tests run so that library keywords are not executed. -W --monitorwidth chars Width of the monitor output. Default is 78. -C --monitorcolors auto|on|off Use colors on console output or not. auto: use colors when output not redirected (default) on: always use colors off: never use colors Note that colors do not work with Jython on Windows. -P --pythonpath path * Additional locations (directories, ZIPs, JARs) where to search test libraries from when they are imported. Multiple paths can be given by separating them with a colon (':') or using this option several times. Given path can also be a glob pattern matching multiple paths but then it normally must be escaped or quoted. Examples: --pythonpath libs/ --pythonpath /opt/testlibs:mylibs.zip:yourlibs -E star:STAR -P lib/STAR.jar -P mylib.jar -E --escape what:with * Escape characters which are problematic in console. 'what' is the name of the character to escape and 'with' is the string to escape it with. Note that all given arguments, incl. data sources, are escaped so escape characters ought to be selected carefully. <--------------------ESCAPES------------------------> Examples: --escape space:_ --metadata X:Value_with_spaces -E space:SP -E quot:Q -v var:QhelloSPworldQ -A --argumentfile path * Text file to read more arguments from. Use special path 'STDIN' to read contents from the standard input stream. File can have both options and data sources one per line. Contents do not need to be escaped but spaces in the beginning and end of lines are removed. Empty lines and lines starting with a hash character (#) are ignored. Example file: | --include regression | --name Regression Tests | # This is a comment line | my_tests.html | path/to/test/directory/ Examples: --argumentfile argfile.txt --argumentfile STDIN -h -? --help Print usage instructions. --version Print version information. Options that are marked with an asterisk (*) can be specified multiple times. For example '--test first --test third' selects test cases with name 'first' and 'third'. If other options are given multiple times, the last value is used. Long option format is case-insensitive. For example --SuiteStatLevel is equivalent to, but easier to read than, --suitestatlevel. Long options can also be shortened as long as they are unique. For example '--logle DEBUG' works while '--lo log.html' does not because the former matches only --loglevel but latter matches --log, --logtitle and --loglevel. Environment Variables: ROBOT_SYSLOG_FILE Path to the syslog file. If not specified, or set to special value 'NONE', writing to syslog file is disabled. Path must be absolute. ROBOT_SYSLOG_LEVEL Log level to use when writing to the syslog file. Available levels are the same as for --loglevel option and the default is INFO. Examples: # Simple test run with 'pybot' without options. $ pybot tests.html # Using options and running with 'jybot'. $ jybot --include smoke --name Smoke_Tests /path/to/tests.html # Running 'robot/runner.py' directly and using test data in TSV format. $ python /path/to/robot/runner.py tests.tsv # Using custom start-up script, giving multiple options and executing a dir. $ runtests.sh --test test1 --test test2 testdir/ # Executing multiple data sources and using case-insensitive long options. $ pybot --SuiteStatLevel 2 /my/tests/*.html /your/tests.html # Setting syslog file before running tests. $ export ROBOT_SYSLOG_FILE=/tmp/syslog.txt $ pybot tests.html """ import sys try: import pythonpathsetter except ImportError: # Get here when run as 'python -m robot.runner' and then importing robot # works without this and pythonpathsetter is imported again later. pass import robot if __name__ == '__main__': rc = robot.run_from_cli(sys.argv[1:], __doc__) sys.exit(rc)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import xmlrpclib import socket import time import sys try: from xml.parsers.expat import ExpatError except ImportError: ExpatError = None # Support for Jython 2.2(.x) from robot import utils from robot.errors import RemoteError class Remote: ROBOT_LIBRARY_SCOPE = 'TEST SUITE' def __init__(self, uri='http://localhost:8270'): if '://' not in uri: uri = 'http://' + uri self._client = XmlRpcRemoteClient(uri) def get_keyword_names(self, attempts=5): for i in range(attempts): try: return self._client.get_keyword_names() except TypeError, err: time.sleep(1) raise RuntimeError('Connecting remote server failed: %s' % err) def get_keyword_arguments(self, name): try: return self._client.get_keyword_arguments(name) except TypeError: return ['*args'] def get_keyword_documentation(self, name): try: return self._client.get_keyword_documentation(name) except TypeError: return '' def run_keyword(self, name, args): args = [ self._handle_argument(arg) for arg in args ] result = RemoteResult(self._client.run_keyword(name, args)) sys.stdout.write(result.output) if result.status != 'PASS': raise RemoteError(result.error, result.traceback) return result.return_ def _handle_argument(self, arg): if isinstance(arg, (basestring, int, long, float)): return arg if isinstance(arg, (tuple, list)): return [ self._handle_argument(item) for item in arg ] if isinstance(arg, dict): return dict([ (self._str(key), self._handle_argument(value)) for key, value in arg.items() ]) return self._str(arg) def _str(self, item): if item is None: return '' return utils.unic(item) class RemoteResult: def __init__(self, result): try: self.status = result['status'] self.output = result.get('output', '') self.return_ = result.get('return', '') self.error = result.get('error', '') self.traceback = result.get('traceback', '') except (KeyError, AttributeError): raise RuntimeError('Invalid remote result dictionary: %s' % result) class XmlRpcRemoteClient: def __init__(self, uri): self._server = xmlrpclib.ServerProxy(uri, encoding='UTF-8') def get_keyword_names(self): try: return self._server.get_keyword_names() except socket.error, (errno, err): raise TypeError(err) except xmlrpclib.Error, err: raise TypeError(err) def get_keyword_arguments(self, name): try: return self._server.get_keyword_arguments(name) except xmlrpclib.Error: raise TypeError def get_keyword_documentation(self, name): try: return self._server.get_keyword_documentation(name) except xmlrpclib.Error: raise TypeError def run_keyword(self, name, args): try: return self._server.run_keyword(name, args) except xmlrpclib.Error, err: raise RuntimeError(err.faultString) except socket.error, (errno, err): raise RuntimeError('Connection to remote server broken: %s' % err) except ExpatError, err: raise RuntimeError('Processing XML-RPC return value failed. ' 'Most often this happens when the return value ' 'contains characters that are not valid in XML. ' 'Original error was: ExpatError: %s' % err)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import telnetlib import time import re import inspect from robot.version import get_version from robot import utils class Telnet: """A test library providing communication over Telnet connections. `Telnet` is Robot Framework's standard library that makes it possible to connect to Telnet servers and execute commands on the opened connections. See `Open Connection` and `Switch Connection` for details on how to handle multiple simultaneous connections. The responses are expected to be ASCII encoded and all non-ASCII characters are silently ignored. """ ROBOT_LIBRARY_SCOPE = 'TEST_SUITE' ROBOT_LIBRARY_VERSION = get_version() def __init__(self, timeout=3.0, newline='CRLF', prompt=None, prompt_is_regexp=False): """Telnet library can be imported with optional arguments. Initialization parameters are used as default values when new connections are opened with `Open Connection` keyword. They can also be set after opening the connection using the `Set Timeout`, `Set Newline` and `Set Prompt` keywords. See these keywords for more information. Examples (use only one of these): | *Setting* | *Value* | *Value* | *Value* | *Value* | *Value* | *Comment* | | Library | Telnet | | | | | # default values | | Library | Telnet | 0.5 | | | | # set only timeout | | Library | Telnet | | LF | | | # set only newline | | Library | Telnet | 2.0 | LF | | | # set timeout and newline | | Library | Telnet | 2.0 | CRLF | $ | | # set also prompt | | Library | Telnet | 2.0 | LF | ($|~) | True | # set prompt with simple regexp | """ self._timeout = timeout == '' and 3.0 or timeout self._newline = newline == '' and 'CRLF' or newline self._prompt = (prompt, prompt_is_regexp) self._cache = utils.ConnectionCache() self._conn = None self._conn_kws = self._lib_kws = None def get_keyword_names(self): return self._get_library_keywords() + self._get_connection_keywords() def _get_library_keywords(self): if self._lib_kws is None: self._lib_kws = [ name for name in dir(self) if not name.startswith('_') and name != 'get_keyword_names' and inspect.ismethod(getattr(self, name)) ] return self._lib_kws def _get_connection_keywords(self): if self._conn_kws is None: conn = self._get_connection() excluded = [ name for name in dir(telnetlib.Telnet()) if name not in ['write', 'read', 'read_until'] ] self._conn_kws = [ name for name in dir(conn) if not name.startswith('_') and name not in excluded and inspect.ismethod(getattr(conn, name)) ] return self._conn_kws def __getattr__(self, name): if name not in self._get_connection_keywords(): raise AttributeError(name) # If no connection is initialized, get attributes from a non-active # connection. This makes it possible for Robot to create keyword # handlers when it imports the library. conn = self._conn is None and self._get_connection() or self._conn return getattr(conn, name) def open_connection(self, host, alias=None, port=23, timeout=None, newline=None, prompt=None, prompt_is_regexp=False): """Opens a new Telnet connection to the given host and port. Possible already opened connections are cached. Returns the index of this connection, which can be used later to switch back to the connection. The index starts from 1 and is reset back to it when the `Close All Connections` keyword is used. The optional `alias` is a name for the connection, and it can be used for switching between connections, similarly as the index. See `Switch Connection` for more details about that. The `timeout`, `newline`, `prompt` and `prompt_is_regexp` arguments get default values when the library is taken into use, but setting them here overrides those values for this connection. See `importing` for more information. """ if timeout is None or timeout == '': timeout = self._timeout if newline is None: newline = self._newline if prompt is None: prompt, prompt_is_regexp = self._prompt print '*INFO* Opening connection to %s:%s with prompt: %s' \ % (host, port, self._prompt) self._conn = self._get_connection(host, port, timeout, newline, prompt, prompt_is_regexp) return self._cache.register(self._conn, alias) def _get_connection(self, *args): """Can be overridden to use a custom connection.""" return TelnetConnection(*args) def switch_connection(self, index_or_alias): """Switches between active connections using an index or alias. The index is got from `Open Connection` keyword, and an alias can be given to it. Returns the index of previously active connection. Example: | Open Connection | myhost.net | | | | Login | john | secret | | | Write | some command | | | | Open Connection | yourhost.com | 2nd conn | | | Login | root | password | | | Write | another cmd | | | | ${old index}= | Switch Connection | 1 | # index | | Write | something | | | | Switch Connection | 2nd conn | # alias | | | Write | whatever | | | | Switch Connection | ${old index} | # back to original again | | [Teardown] | Close All Connections | | The example above expects that there were no other open connections when opening the first one, because it used index '1' when switching to the connection later. If you are not sure about that, you can store the index into a variable as shown below. | ${id} = | Open Connection | myhost.net | | # Do something ... | | | | Switch Connection | ${id} | | """ old_index = self._cache.current_index self._conn = self._cache.switch(index_or_alias) return old_index def close_all_connections(self): """Closes all open connections and empties the connection cache. After this keyword, new indexes got from the `Open Connection` keyword are reset to 1. This keyword should be used in a test or suite teardown to make sure all connections are closed. """ self._conn = self._cache.close_all() class TelnetConnection(telnetlib.Telnet): def __init__(self, host=None, port=23, timeout=3.0, newline='CRLF', prompt=None, prompt_is_regexp=False): port = port == '' and 23 or int(port) telnetlib.Telnet.__init__(self, host, port) self.set_timeout(timeout) self.set_newline(newline) self.set_prompt(prompt, prompt_is_regexp) self._default_log_level = 'INFO' self.set_option_negotiation_callback(self._negotiate_echo_on) def set_timeout(self, timeout): """Sets the timeout used in read operations to the given value. `timeout` is given in Robot Framework's time format (e.g. 1 minute 20 seconds) that is explained in the User Guide. Read operations that expect some output to appear (`Read Until`, `Read Until Regexp`, `Read Until Prompt`) use this timeout and fail if the expected output has not appeared when this timeout expires. The old timeout is returned and can be used to restore it later. Example: | ${tout} = | Set Timeout | 2 minute 30 seconds | | Do Something | | Set Timeout | ${tout} | """ old = getattr(self, '_timeout', 3.0) self._timeout = utils.timestr_to_secs(timeout) return utils.secs_to_timestr(old) def set_newline(self, newline): """Sets the newline used by the `Write` keyword. Newline can be given either in escaped format using '\\n' and '\\r', or with special 'LF' and 'CR' syntax. Examples: | Set Newline | \\n | | Set Newline | CRLF | Correct newline to use depends on the system and the default value is 'CRLF'. The old newline is returned and can be used to restore it later. See `Set Prompt` or `Set Timeout` for an example. """ old = getattr(self, '_newline', 'CRLF') self._newline = newline.upper().replace('LF','\n').replace('CR','\r') return old def close_connection(self, loglevel=None): """Closes the current Telnet connection and returns any remaining output. See `Read` for more information on `loglevel`. """ telnetlib.Telnet.close(self) ret = self.read_all().decode('ASCII', 'ignore') self._log(ret, loglevel) return ret def login(self, username, password, login_prompt='login: ', password_prompt='Password: '): """Logs in to the Telnet server with the given user information. The login keyword reads from the connection until login_prompt is encountered and then types the user name. Then it reads until password_prompt is encountered and types the password. The rest of the output (if any) is also read, and all the text that has been read is returned as a single string. If a prompt has been set to this connection, either with `Open Connection` or `Set Prompt`, this keyword reads the output until the prompt is found. Otherwise, the keyword sleeps for a second and reads everything that is available. """ ret = self.read_until(login_prompt, 'TRACE').decode('ASCII', 'ignore') self.write_bare(username + self._newline) ret += username + '\n' ret += self.read_until(password_prompt, 'TRACE').decode('ASCII', 'ignore') self.write_bare(password + self._newline) ret += '*' * len(password) + '\n' if self._prompt_is_set(): try: ret += self.read_until_prompt('TRACE') except AssertionError: self._verify_login(ret) raise else: ret += self._verify_login(ret) self._log(ret) return ret def _verify_login(self, ret): # It is necessary to wait for the 'login incorrect' message to appear. time.sleep(1) while True: try: ret += self.read_until('\n', 'TRACE').decode('ASCII', 'ignore') except AssertionError: return ret else: if 'Login incorrect' in ret: self._log(ret) raise AssertionError("Login incorrect") def write(self, text, loglevel=None): """Writes the given text over the connection and appends a newline. Consumes the written text (until the appended newline) from the output and returns it. The given text must not contain newlines. Note: This keyword does not return the possible output of the executed command. To get the output, one of the `Read XXX` keywords must be used. See `Read` for more information on `loglevel`. """ if self._newline in text: raise RuntimeError("Write cannot be used with string containing " "newlines. Use 'Write Bare' instead.") text += self._newline self.write_bare(text) # Can't read until 'text' because long lines are cut strangely in the output return self.read_until(self._newline, loglevel) def write_bare(self, text): """Writes the given text over the connection without appending a newline. Does not consume the written text. """ try: text = str(text) except UnicodeError: raise ValueError('Only ASCII characters are allowed in Telnet. ' 'Got: %s' % text) telnetlib.Telnet.write(self, text) def write_until_expected_output(self, text, expected, timeout, retry_interval, loglevel=None): """Writes the given text repeatedly, until `expected` appears in the output. `text` is written without appending a newline. `retry_interval` defines the time waited before writing `text` again. `text` is consumed from the output before `expected` is tried to be read. If `expected` does not appear in the output within `timeout`, this keyword fails. See `Read` for more information on `loglevel`. Example: | Write Until Expected Output | ps -ef| grep myprocess\\n | myprocess | | ... | 5s | 0.5s | This writes the 'ps -ef | grep myprocess\\n', until 'myprocess' appears on the output. The command is written every 0.5 seconds and the keyword ,fails if 'myprocess' does not appear in the output in 5 seconds. """ timeout = utils.timestr_to_secs(timeout) retry_interval = utils.timestr_to_secs(retry_interval) starttime = time.time() while time.time() - starttime < timeout: self.write_bare(text) self.read_until(text, loglevel) ret = telnetlib.Telnet.read_until(self, expected, retry_interval).decode('ASCII', 'ignore') self._log(ret, loglevel) if ret.endswith(expected): return ret raise AssertionError("No match found for '%s' in %s" % (expected, utils.secs_to_timestr(timeout))) def read(self, loglevel=None): """Reads and returns/logs everything that is currently available in the output. The read message is always returned and logged. The default log level is either 'INFO', or the level set with `Set Default Log Level`. `loglevel` can be used to override the default log level, and the available levels are TRACE, DEBUG, INFO, and WARN. """ ret = self.read_very_eager().decode('ASCII', 'ignore') self._log(ret, loglevel) return ret def read_until(self, expected, loglevel=None): """Reads from the current output, until expected is encountered. Text up to and including the match is returned. If no match is found, the keyword fails. See `Read` for more information on `loglevel`. """ ret = telnetlib.Telnet.read_until(self, expected, self._timeout).decode('ASCII', 'ignore') self._log(ret, loglevel) if not ret.endswith(expected): raise AssertionError("No match found for '%s' in %s" % (expected, utils.secs_to_timestr(self._timeout))) return ret def read_until_regexp(self, *expected): """Reads from the current output, until a match to a regexp in expected. Expected is a list of regular expression patterns as strings, or compiled regular expressions. The keyword returns the text up to and including the first match to any of the regular expressions. If the last argument in `*expected` is a valid log level, it is used as `loglevel` in the keyword `Read`. Examples: | Read Until Regexp | (#|$) | | Read Until Regexp | first_regexp | second_regexp | | Read Until Regexp | some regexp | DEBUG | """ expected = list(expected) if self._is_valid_log_level(expected[-1]): loglevel = expected[-1] expected = expected[:-1] else: loglevel = 'INFO' try: index, _, ret = self.expect(expected, self._timeout) except TypeError: index, ret = -1, '' ret = ret.decode('ASCII', 'ignore') self._log(ret, loglevel) if index == -1: expected = [ exp if isinstance(exp, basestring) else exp.pattern for exp in expected ] raise AssertionError("No match found for %s in %s" % (utils.seq2str(expected, lastsep=' or '), utils.secs_to_timestr(self._timeout))) return ret def read_until_prompt(self, loglevel=None): """Reads from the current output, until a prompt is found. The prompt must have been set, either in the library import or at login time, or by using the `Set Prompt` keyword. See `Read` for more information on `loglevel`. """ if not self._prompt_is_set(): raise RuntimeError('Prompt is not set') prompt, regexp = self._prompt if regexp: return self.read_until_regexp(prompt, loglevel) return self.read_until(prompt, loglevel) def execute_command(self, command, loglevel=None): """Executes given command and reads and returns everything until prompt. This is a convenience keyword; following two are functionally identical: | ${out} = | Execute Command | Some command | | Write | Some command | | ${out} = | Read Until Prompt | This keyword expects a prompt to be set, see `Read Until Prompt` for details. See `Read` for more information on `loglevel`. """ self.write(command, loglevel) return self.read_until_prompt(loglevel) def set_prompt(self, prompt, prompt_is_regexp=False): """Sets the prompt used in this connection to `prompt`. If `prompt_is_regexp` is a non-empty string, the given prompt is considered to be a regular expression. The old prompt is returned and can be used to restore it later. Example: | ${prompt} | ${regexp} = | Set Prompt | $ | | Do Something | | Set Prompt | ${prompt} | ${regexp} | """ old = hasattr(self, '_prompt') and self._prompt or (None, False) if prompt_is_regexp: self._prompt = (re.compile(prompt), True) else: self._prompt = (prompt, False) if old[1]: return old[0].pattern, True return old def _prompt_is_set(self): return self._prompt[0] is not None def set_default_log_level(self, level): """Sets the default log level used by all read keywords. The possible values are TRACE, DEBUG, INFO and WARN. The default is INFO. The old value is returned and can be used to restore it later, similarly as with `Set Timeout`. """ self._is_valid_log_level(level, raise_if_invalid=True) old = self._default_log_level self._default_log_level = level.upper() return old def _log(self, msg, level=None): self._is_valid_log_level(level, raise_if_invalid=True) msg = msg.strip() if level is None: level = self._default_log_level if msg != '': print '*%s* %s' % (level.upper(), msg) def _is_valid_log_level(self, level, raise_if_invalid=False): if level is None: return True if isinstance(level, basestring) and \ level.upper() in ['TRACE', 'DEBUG', 'INFO', 'WARN']: return True if not raise_if_invalid: return False raise AssertionError("Invalid log level '%s'" % level) def _negotiate_echo_on(self, sock, cmd, opt): # This is supposed to turn server side echoing on and turn other options off. if opt == telnetlib.ECHO and cmd in (telnetlib.WILL, telnetlib.WONT): self.sock.sendall(telnetlib.IAC + telnetlib.DO + opt) elif opt != telnetlib.NOOPT: if cmd in (telnetlib.DO, telnetlib.DONT): self.sock.sendall(telnetlib.IAC + telnetlib.WONT + opt) elif cmd in (telnetlib.WILL, telnetlib.WONT): self.sock.sendall(telnetlib.IAC + telnetlib.DONT + opt)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.version import get_version from robot import utils class _List: def convert_to_list(self, item): """Converts the given `item` to a list. Mainly useful for converting tuples and other iterable to lists. Use `Create List` from the BuiltIn library for constructing new lists. """ return list(item) def append_to_list(self, list_, *values): """Adds `values` to the end of `list`. Example: | Append To List | ${L1} | xxx | | | | Append To List | ${L2} | x | y | z | => - ${L1} = ['a', 'xxx'] - ${L2} = ['a', 'b', 'x', 'y', 'z'] """ for value in values: list_.append(value) def insert_into_list(self, list_, index, value): """Inserts `value` into `list` to the position specified with `index`. Index '0' adds the value into the first position, '1' to the second, and so on. Inserting from right works with negative indices so that '-1' is the second last position, '-2' third last, and so on. Use `Append To List` to add items to the end of the list. If the absolute value of the index is greater than the length of the list, the value is added at the end (positive index) or the beginning (negative index). An index can be given either as an integer or a string that can be converted to an integer. Example: | Insert Into List | ${L1} | 0 | xxx | | Insert Into List | ${L2} | ${-1} | xxx | => - ${L1} = ['xxx', 'a'] - ${L2} = ['a', 'xxx', 'b'] """ list_.insert(self._index_to_int(index), value) def combine_lists(self, *lists): """Combines the given `lists` together and returns the result. The given lists are never altered by this keyword. Example: | ${x} = | Combine List | ${L1} | ${L2} | | | ${y} = | Combine List | ${L1} | ${L2} | ${L1} | => - ${x} = ['a', 'a', 'b'] - ${y} = ['a', 'a', 'b', 'a'] - ${L1} and ${L2} are not changed. """ ret = [] for item in lists: ret.extend(item) return ret def set_list_value(self, list_, index, value): """Sets the value of `list` specified by `index` to the given `value`. Index '0' means the first position, '1' the second and so on. Similarly, '-1' is the last position, '-2' second last, and so on. Using an index that does not exist on the list causes an error. The index can be either an integer or a string that can be converted to an integer. Example: | Set List Value | ${L3} | 1 | xxx | | Set List Value | ${L3} | -1 | yyy | => - ${L3} = ['a', 'xxx', 'yyy'] """ try: list_[self._index_to_int(index)] = value except IndexError: self._index_error(list_, index) def remove_values_from_list(self, list_, *values): """Removes all occurences of given `values` from `list`. It is not an error is a value does not exist in the list at all. Example: | Remove Values From List | ${L4} | a | c | e | f | => - ${L4} = ['b', 'd'] """ for value in values: while value in list_: list_.remove(value) def remove_from_list(self, list_, index): """Removes and returns the value specified with an `index` from `list`. Index '0' means the first position, '1' the second and so on. Similarly, '-1' is the last position, '-2' the second last, and so on. Using an index that does not exist on the list causes an error. The index can be either an integer or a string that can be converted to an integer. Example: | ${x} = | Remove From List | ${L2} | 0 | => - ${x} = 'a' - ${L2} = ['b'] """ try: return list_.pop(self._index_to_int(index)) except IndexError: self._index_error(list_, index) def get_from_list(self, list_, index): """Returns the value specified with an `index` from `list`. The given list is never altered by this keyword. Index '0' means the first position, '1' the second, and so on. Similarly, '-1' is the last position, '-2' the second last, and so on. Using an index that does not exist on the list causes an error. The index can be either an integer or a string that can be converted to an integer. Examples (including Python equivalents in comments): | ${x} = | Get From List | ${L5} | 0 | # L5[0] | | ${y} = | Get From List | ${L5} | -2 | # L5[-2] | => - ${x} = 'a' - ${y} = 'd' - ${L5} is not changed """ try: return list_[self._index_to_int(index)] except IndexError: self._index_error(list_, index) def get_slice_from_list(self, list_, start=0, end=None): """Returns a slice of the given list between `start` and `end` indexes. The given list is never altered by this keyword. If both `start` and `end` are given, a sublist containing values from `start` to `end` is returned. This is the same as 'list[start:end]' in Python. To get all items from the beginning, use 0 as the start value, and to get all items until the end, use 'None' as the end value. 'None' is also a default value, so in this case, it is enough to give only `start`. If only `end` is given, `start` gets the value 0. Using `start` or `end` not found on the list is the same as using the largest (or smallest) available index. Examples (incl. Python equivelants in comments): | ${x} = | Get Slice From List | ${L5} | 2 | 4 | # L5[2:4] | | ${y} = | Get Slice From List | ${L5} | 1 | | # L5[1:None] | | ${z} = | Get Slice From List | ${L5} | | -2 | # L5[0:-2] | => - ${x} = ['c', 'd'] - ${y} = ['b', 'c', 'd', 'e'] - ${z} = ['a', 'b', 'c'] - ${L5} is not changed """ start = self._index_to_int(start, True) if end is not None: end = self._index_to_int(end) return list_[start:end] def count_values_in_list(self, list_, value, start=0, end=None): """Returns the number of occurrences of the given `value` in `list`. The search can be narrowed to the selected sublist by the `start` and `end` indexes having the same semantics as in the `Get Slice From List` keyword. The given list is never altered by this keyword. Example: | ${x} = | Count Values In List | ${L3} | b | => - ${x} = 1 - ${L3} is not changed """ return self.get_slice_from_list(list_, start, end).count(value) def get_index_from_list(self, list_, value, start=0, end=None): """Returns the index of the first occurrence of the `value` on the list. The search can be narrowed to the selected sublist by the `start` and `end` indexes having the same semantics as in the `Get Slice From List` keyword. In case the value is not found, -1 is returned. The given list is never altered by this keyword. Example: | ${x} = | Get Index From List | ${L5} | d | => - ${x} = 3 - ${L5} is not changed """ if start == '': start = 0 list_ = self.get_slice_from_list(list_, start, end) try: return int(start) + list_.index(value) except ValueError: return -1 def copy_list(self, list_): """Returns a copy of the given list. The given list is never altered by this keyword. """ return list_[:] def reverse_list(self, list_): """Reverses the given list in place. Note that the given list is changed and nothing is returned. Use `Copy List` first, if you need to keep also the original order. | Reverse List | ${L3} | => - ${L3} = ['c', 'b', 'a'] """ list_.reverse() def sort_list(self, list_): """Sorts the given list in place. The strings are sorted alphabetically and the numbers numerically. Note that the given list is changed and nothing is returned. Use `Copy List` first, if you need to keep also the original order. ${L} = [2,1,'a','c','b'] | Sort List | ${L} | => - ${L} = [1, 2, 'a', 'b', 'c'] """ list_.sort() def list_should_contain_value(self, list_, value, msg=None): """Fails if the `value` is not found from `list`. If `msg` is not given, the default error message "[ a | b | c ] does not contain the value 'x'" is shown in case of a failure. Otherwise, the given `msg` is used in case of a failure. """ default = "%s does not contain value '%s'" % (utils.seq2str2(list_), value) _verify_condition(value in list_, default, msg) def list_should_not_contain_value(self, list_, value, msg=None): """Fails if the `value` is not found from `list`. See `List Should Contain Value` for an explanation of `msg`. """ default = "%s contains value '%s'" % (utils.seq2str2(list_), value) _verify_condition(value not in list_, default, msg) def list_should_not_contain_duplicates(self, list_, msg=None): """Fails if any element in the `list` is found from it more than once. The default error message lists all the elements that were found from the `list` multiple times, but it can be overridden by giving a custom `msg`. All multiple times found items and their counts are also logged. This keyword works with all iterables that can be converted to a list. The original iterable is never altered. """ if not isinstance(list_, list): list_ = list(list_) dupes = [] for item in list_: if item not in dupes: count = list_.count(item) if count > 1: print "*INFO* '%s' found %d times" % (item, count) dupes.append(item) if dupes: if not msg: msg = '%s found multiple times' % utils.seq2str(dupes) raise AssertionError(msg) def lists_should_be_equal(self, list1, list2, msg=None, values=True): """Fails if given lists are unequal. The keyword first verifies that the lists have equal lengths, and then it checks are all the values equal. Possible differences between the values are listed in the default error message. - If `msg` is not given, the default error message is used. - If `msg` is given and `values` is either Boolean False or a string 'False' or 'No Values', the error message is simply `msg`. - Otherwise the error message is `msg` + 'new line' + default. """ len1 = len(list1); len2 = len(list2) default = 'Lengths are different: %d != %d' % (len1, len2) _verify_condition(len1 == len2, default, msg, values) diffs = [ 'Index %d: %s != %s' % (i, list1[i], list2[i]) for i in range(len1) if list1[i] != list2[i] ] default = 'Lists are different:\n' + '\n'.join(diffs) _verify_condition(diffs == [], default, msg, values) def list_should_contain_sub_list(self, list1, list2, msg=None, values=True): """Fails if not all of the elements in `list2` are found in `list1`. The order of values and the number of values are not taken into account. See the use of `msg` and `values` from the `Lists Should Be Equal` keyword. """ diffs = ', '.join([ utils.unic(item) for item in list2 if item not in list1 ]) default = 'Following values were not found from first list: ' + diffs _verify_condition(diffs == '', default, msg, values) def log_list(self, list_, level='INFO'): """Logs the length and contents of the `list` using given `level`. Valid levels are TRACE, DEBUG, INFO (default), and WARN. If you only want to the length, use keyword `Get Length` from the BuiltIn library. """ print '*%s* ' % level.upper(), if len(list_) == 0: print 'List is empty' elif len(list_) == 1: print 'List has one item:\n%s' % list_[0] else: print 'List length is %d and it contains following items:' \ % len(list_) for index, item in enumerate(list_): print '%s: %s' % (index, item) def _index_to_int(self, index, empty_to_zero=False): if empty_to_zero and not index: return 0 try: return int(index) except ValueError: raise ValueError("Cannot convert index '%s' to an integer" % index) def _index_error(self, list_, index): raise IndexError('Given index %s is out of the range 0-%d' % (index, len(list_)-1)) class _Dictionary: def create_dictionary(self, *key_value_pairs): """Creates and returns a dictionary from the given `key_value_pairs`. Examples: | ${x} = | Create Dictionary | name | value | | | | ${y} = | Create Dictionary | a | 1 | b | 2 | | ${z} = | Create Dictionary | a | ${1} | b | ${2} | => - ${x} = {'name': 'value'} - ${y} = {'a': '1', 'b': '2'} - ${z} = {'a': 1, 'b': 2} """ if len(key_value_pairs) % 2 != 0: raise ValueError("Creating a dictionary failed. There should be " "an even number of key-value-pairs.") return self.set_to_dictionary({}, *key_value_pairs) def set_to_dictionary(self, dictionary, *key_value_pairs): """Adds the given `key_value_pairs` to the `dictionary`. Example: | Set To Dictionary | ${D1} | key | value | => - ${D1} = {'a': 1, 'key': 'value'} """ if len(key_value_pairs) % 2 != 0: raise ValueError("Adding data to a dictionary failed. There " "should be an even number of key-value-pairs.") for i in range(0, len(key_value_pairs), 2): dictionary[key_value_pairs[i]] = key_value_pairs[i+1] return dictionary def remove_from_dictionary(self, dictionary, *keys): """Removes the given `keys` from the `dictionary`. If the given `key` cannot be found from the `dictionary`, it is ignored. Example: | Remove From Dictionary | ${D3} | b | x | y | => - ${D3} = {'a': 1, 'c': 3} """ for key in keys: try: value = dictionary.pop(key) print "Removed item with key '%s' and value '%s'" % (key, value) except KeyError: print "Key '%s' not found" % (key) def keep_in_dictionary(self, dictionary, *keys): """Keeps the given `keys` in the `dictionary` and removes all other. If the given `key` cannot be found from the `dictionary`, it is ignored. Example: | Keep In Dictionary | ${D5} | b | x | d | => - ${D5} = {'b': 2, 'd': 4} """ remove_keys = [ key for key in dictionary.keys() if not key in keys ] self.remove_from_dictionary(dictionary, *remove_keys) def copy_dictionary(self, dictionary): """Returns a copy of the given dictionary. The given dictionary is never altered by this keyword. """ return dictionary.copy() def get_dictionary_keys(self, dictionary): """Returns `keys` of the given `dictionary`. `Keys` are returned in sorted order. The given `dictionary` is never altered by this keyword. Example: | ${keys} = | Get Dictionary Keys | ${D3} | => - ${keys} = ['a', 'b', 'c'] """ keys = dictionary.keys() keys.sort() return keys def get_dictionary_values(self, dictionary): """Returns values of the given dictionary. Values are returned sorted according to keys. The given dictionary is never altered by this keyword. Example: | ${values} = | Get Dictionary Values | ${D3} | => - ${values} = [1, 2, 3] """ return [ dictionary[k] for k in self.get_dictionary_keys(dictionary) ] def get_dictionary_items(self, dictionary): """Returns items of the given `dictionary`. Items are returned sorted by keys. The given `dictionary` is never altered by this keyword. Example: | ${items} = | Get Dictionary Items | ${D3} | => - ${items} = ['a', 1, 'b', 2, 'c', 3] """ ret = [] for key in self.get_dictionary_keys(dictionary): ret.extend((key, dictionary[key])) return ret def get_from_dictionary(self, dictionary, key): """Returns a value from the given `dictionary` based on the given `key`. If the given `key` cannot be found from the `dictionary`, this keyword fails. The given dictionary is never altered by this keyword. Example: | ${value} = | Get From Dictionary | ${D3} | b | => - ${value} = 2 """ try: return dictionary[key] except KeyError: raise RuntimeError("Dictionary does not contain key '%s'" % key) def dictionary_should_contain_key(self, dictionary, key, msg=None): """Fails if `key` is not found from `dictionary`. See `List Should Contain Value` for an explanation of `msg`. The given dictionary is never altered by this keyword. """ default = "Dictionary does not contain key '%s'" % key _verify_condition(dictionary.has_key(key), default, msg) def dictionary_should_not_contain_key(self, dictionary, key, msg=None): """Fails if `key` is found from `dictionary`. See `List Should Contain Value` for an explanation of `msg`. The given dictionary is never altered by this keyword. """ default = "Dictionary contains key '%s'" % key _verify_condition(not dictionary.has_key(key), default, msg) def dictionary_should_contain_value(self, dictionary, value, msg=None): """Fails if `value` is not found from `dictionary`. See `List Should Contain Value` for an explanation of `msg`. The given dictionary is never altered by this keyword. """ default = "Dictionary does not contain value '%s'" % value _verify_condition(value in dictionary.values(), default, msg) def dictionary_should_not_contain_value(self, dictionary, value, msg=None): """Fails if `value` is found from `dictionary`. See `List Should Contain Value` for an explanation of `msg`. The given dictionary is never altered by this keyword. """ default = "Dictionary contains value '%s'" % value _verify_condition(not value in dictionary.values(), default, msg) def dictionaries_should_be_equal(self, dict1, dict2, msg=None, values=True): """Fails if the given dictionaries are not equal. First the equality of dictionaries' keys is checked and after that all the key value pairs. If there are differences between the values, those are listed in the error message. See `Lists Should Be Equal` for an explanation of `msg`. The given dictionaries are never altered by this keyword. """ keys = self._keys_should_be_equal(dict1, dict2, msg, values) self._key_values_should_be_equal(keys, dict1, dict2, msg, values) def dictionary_should_contain_sub_dictionary(self, dict1, dict2, msg=None, values=True): """Fails unless all items in `dict2` are found from `dict1`. See `Lists Should Be Equal` for an explanation of `msg`. The given dictionaries are never altered by this keyword. """ keys = self.get_dictionary_keys(dict2) diffs = [ utils.unic(k) for k in keys if k not in dict1 ] default = "Following keys missing from first dictionary: %s" \ % ', '.join(diffs) _verify_condition(diffs == [], default, msg, values) self._key_values_should_be_equal(keys, dict1, dict2, msg, values) def log_dictionary(self, dictionary, level='INFO'): """Logs the size and contents of the `dictionary` using given `level`. Valid levels are TRACE, DEBUG, INFO (default), and WARN. If you only want to log the size, use keyword `Get Length` from the BuiltIn library. """ print '*%s* ' % level.upper(), if len(dictionary) == 0: print 'Dictionary is empty' elif len(dictionary) == 1: print 'Dictionary has one item:' else: print 'Dictionary size is %d and it contains following items:' \ % len(dictionary) for key in self.get_dictionary_keys(dictionary): print '%s: %s' % (key, dictionary[key]) def _keys_should_be_equal(self, dict1, dict2, msg, values): keys1 = self.get_dictionary_keys(dict1) keys2 = self.get_dictionary_keys(dict2) miss1 = [ utils.unic(k) for k in keys2 if k not in dict1 ] miss2 = [ utils.unic(k) for k in keys1 if k not in dict2 ] error = [] if miss1: error += [ 'Following keys missing from first dictionary: %s' % ', '.join(miss1) ] if miss2: error += [ 'Following keys missing from second dictionary: %s' % ', '.join(miss2) ] _verify_condition(error == [], '\n'.join(error), msg, values) return keys1 def _key_values_should_be_equal(self, keys, dict1, dict2, msg, values): diffs = [ 'Key %s: %s != %s' % (k, dict1[k], dict2[k]) for k in keys if dict1[k] != dict2[k] ] default = 'Following keys have different values:\n' + '\n'.join(diffs) _verify_condition(diffs == [], default, msg, values) class Collections(_List, _Dictionary): """A test library providing keywords for handling lists and dictionaries. `Collections` is Robot Framework's standard library that provides a set of keywords for handling Python lists and dictionaries. This library has keywords, for example, for modifying and getting values from lists and dictionaries (e.g. `Append To List`, `Get From Dictionary`) and for verifying their contents (e.g. `Lists Should Be Equal`, `Dictionary Should Contain Value`). Following keywords from the BuiltIn library can also be used with lists and dictionaries: | *Keyword Name* | *Applicable With* | | `Create List` | lists | | `Get Length` | both | | `Length Should Be` | both | | `Should Be Empty` | both | | `Should Not Be Empty` | both | | `Should Contain` | lists | | `Should Not Contain` | lists | | `Should Contain X Times` | lists | | `Should Not Contain X Times` | lists | | `Get Count` | lists | All list keywords expect a scalar variable (e.g. ${list}) as an argument. It is, however, possible to use list variables (e.g. @{list}) as scalars simply by replacing '@' with '$'. List keywords that do not alter the given list can also be used with tuples, and to some extend also with other iterables. `Convert To List` can be used to convert tuples and other iterables to lists. ------- List related keywords use variables in format ${Lx} in their examples, which means a list with as many alphabetic characters as specified by 'x'. For example ${L1} means ['a'] and ${L3} means ['a', 'b', 'c']. Dictionary keywords use similar ${Dx} variables. For example ${D1} means {'a': 1} and ${D3} means {'a': 1, 'b': 2, 'c': 3}. -------- """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() def _verify_condition(condition, default_msg, given_msg, include_default=False): if not condition: if not given_msg: raise AssertionError(default_msg) if _include_default_message(include_default): raise AssertionError(given_msg + '\n' + default_msg) raise AssertionError(given_msg) def _include_default_message(include): if isinstance(include, basestring): return include.lower() not in ['no values', 'false'] return bool(include)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. RESERVED_KEYWORDS = [ 'for', 'while', 'break', 'continue', 'end', 'if', 'else', 'elif', 'else if', 'return' ] class Reserved: ROBOT_LIBRARY_SCOPE = 'GLOBAL' def get_keyword_names(self): return RESERVED_KEYWORDS def run_keyword(self, name, args): raise Exception("'%s' is a reserved keyword" % name.title())
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import time import glob import fnmatch import shutil try: from robot.output import LOGGER from robot.version import get_version from robot.utils import (ConnectionCache, seq2str, timestr_to_secs, secs_to_timestr, plural_or_not, get_time, abspath, secs_to_timestamp, parse_time, unic, decode_output) __version__ = get_version() PROCESSES = ConnectionCache('No active processes') except ImportError: from os.path import abspath __version__ = '<unknown>' seq2str = lambda items: ', '.join("'%s'" % item for item in items) timestr_to_secs = int plural_or_not = lambda count: count != 1 and 's' or '' secs_to_timestr = lambda secs: '%d second%s' % (secs, plural_or_not(secs)) unic = unicode decode_output = lambda string: string class _NotImplemented: def __getattr__(self, name): raise NotImplementedError('This usage requires Robot Framework ' 'to be installed.') LOGGER = get_time = secs_to_timestamp = parse_time = PROCESSES \ = _NotImplemented() class OperatingSystem: """A test library providing keywords for OS related tasks. `OperatingSystem` is Robot Framework's standard library that enables various operating system related tasks to be performed in the system where Robot Framework is running. It can, among other things, execute commands (e.g. `Run`), create and remove files and directories (e.g. `Create File`, `Remove Directory`), check whether files or directories exists or contain something (e.g. `File Should Exist`, `Directory Should Be Empty`) and manipulate environment variables (e.g. `Set Environment Variable`). *Pattern matching* Some keywords allow their arguments to be specified as _glob patterns_ where: | * | matches anything, even an empty string | | ? | matches any single character | | [chars] | matches any character inside square brackets (e.g. '[abc]' matches either 'a', 'b' or 'c') | | [!chars] | matches any character not inside square brackets | Unless otherwise noted, matching is case-insensitive on case-insensitive operating systems such as Windows. Pattern matching is implemented using Python's `fnmatch` module: http://docs.python.org/library/fnmatch.html *Path separators* All keywords expecting paths as arguments accept a forward slash (`/`) as a path separator regardless the operating system. Notice that this *does not work when the path is part of an argument*, like it often is with `Run` and `Start Process` keywords. In such cases the built-in variable `${/}` can be used to keep the test data platform independent. *Example* | *Setting* | *Value* | | Library | OperatingSystem | | *Variable* | *Value* | | ${PATH} | ${CURDIR}/example.txt | | *Test Case* | *Action* | *Argument* | *Argument* | | Example | Create File | ${PATH} | Some text | | | File Should Exist | ${PATH} | | | | Copy File | ${PATH} | ${TEMPDIR}/stuff | | | ${output} = | Run | ${CURDIR}${/}script.py arg | """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = __version__ def run(self, command): """Runs the given command in the system and returns the output. The execution status of the command *is not checked* by this keyword, and it must be done separately based on the returned output. If the execution return code is needed, either `Run And Return RC` or `Run And Return RC And Output` can be used. The standard error stream is automatically redirected to the standard output stream by adding `2>&1` after the executed command. This automatic redirection is done only when the executed command does not contain additional output redirections. You can thus freely forward the standard error somewhere else, for example, like `my_command 2>stderr.txt`. The returned output contains everything written into the standard output or error streams by the command (unless either of them is redirected explicitly). Many commands add an extra newline (`\\n`) after the output to make it easier to read in the console. To ease processing the returned output, this possible trailing newline is stripped by this keyword. Examples: | ${output} = | Run | ls -lhF /tmp | | Log | ${output} | | ${result} = | Run | ${CURDIR}${/}tester.py arg1 arg2 | | Should Not Contain | ${result} | FAIL | | ${stdout} = | Run | /opt/script.sh 2>/tmp/stderr.txt | | Should Be Equal | ${stdout} | TEST PASSED | | File Should Be Empty | /tmp/stderr.txt | """ return self._run(command)[1] def run_and_return_rc(self, command): """Runs the given command in the system and returns the return code. The return code (RC) is returned as a positive integer in range from 0 to 255 as returned by the executed command. On some operating systems (notable Windows) original return codes can be something else, but this keyword always maps them to the 0-255 range. Since the RC is an integer, it must be checked e.g. with the keyword `Should Be Equal As Integers` instead of `Should Be Equal` (both are built-in keywords). Examples: | ${rc} = | Run and Return RC | ${CURDIR}${/}script.py arg | | Should Be Equal As Integers | ${rc} | 0 | | ${rc} = | Run and Return RC | /path/to/example.rb arg1 arg2 | | Should Be True | 0 < ${rc} < 42 | See `Run` and `Run And Return RC And Output` if you need to get the output of the executed command. """ return self._run(command)[0] def run_and_return_rc_and_output(self, command): """Runs the given command in the system and returns the RC and output. The return code (RC) is returned similarly as with `Run And Return RC` and the output similarly as with `Run`. Examples: | ${rc} | ${output} = | Run and Return RC and Output | ${CURDIR}${/}mytool | | Should Be Equal As Integers | ${rc} | 0 | | Should Not Contain | ${output} | FAIL | | ${rc} | ${stdout} = | Run and Return RC and Output | /opt/script.sh 2>/tmp/stderr.txt | | Should Be True | ${rc} > 42 | | Should Be Equal | ${stdout} | TEST PASSED | | File Should Be Empty | /tmp/stderr.txt | """ return self._run(command) def _run(self, command): process = _Process(command) self._info("Running command '%s'" % process) stdout = process.read() rc = process.close() return rc, stdout def start_process(self, command, stdin=None, alias=None): """Starts the given command as a background process. Starts the process in the background and sets this process as the current process. The following calls of the keywords `Read Process Output` or `Stop Process` affect this process, unless the keyword `Switch Process` is used. If the command needs input through the standard input stream, it can be defined with the `stdin` argument. It is not possible to give input to the command later. Possible command line arguments must be given as part of the command like '/tmp/script.sh arg1 arg2'. Returns the index of this process. The indexing starts from 1, and it can be used to switch between the processes with the `Switch Process` keyword. To end all processes and reset indexing, the `Stop All Processes` keyword must be used. The optional `alias` is a name for this process that may be used with `Switch Process` instead of the returned index. The standard error stream is redirected to the standard input stream automatically by adding '2>&1' after the executed command. This is done the same way, and for the same reasons, as with `Run` keyword. Example: | Start Process | /path/longlasting.sh | | Do Something | | | ${output} = | Read Process Output | | Should Contain | ${output} | Expected text | | [Teardown] | Stop All Processes | """ process = _Process2(command, stdin) self._info("Running command '%s'" % process) return PROCESSES.register(process, alias) def switch_process(self, index_or_alias): """Switches the active process to the specified process. The index is the return value of the `Start Process` keyword and an alias may have been defined to it. Example: | Start Process | /path/script.sh arg | | 1st process | | ${2nd} = | Start Process | /path/script2.sh | | Switch Process | 1st process | | ${out1} = | Read Process Output | | Switch Process | ${2nd} | | ${out2} = | Read Process Output | | Log Many | 1st process: ${out1} | 2nd process: ${out1} | | [Teardown] | Stop All Processes | """ PROCESSES.switch(index_or_alias) def read_process_output(self): """Waits for the process to finish and returns its output. As mentioned in the documentation of `Start Process` keyword, and documented thoroughly in `Run` keyword, the standard error stream is automatically redirected to the standard output. This keyword thus always returns all the output procuded by the command. Note that although the process is finished, it is not removed from the process list. Trying to read from a stopped process nevertheless fails. To reset the process list (and indexes and aliases), `Stop All Processes` must be used. See `Start Process` and `Switch Process` for more information and examples about running processes. """ output = PROCESSES.current.read() PROCESSES.current.close() return output def stop_process(self): """Stops the current process without reading from it. Stopping a process does not remove it from the process list. To reset the process list (and indexes and aliases), `Stop All Processes` must be used. Stopping an already stopped process has no effect. See `Start Process` and `Switch Process` for more information. """ PROCESSES.current.close() def stop_all_processes(self): """Stops all the processes and removes them from the process list. Resets the indexing that `Start Process` uses. All aliases are also deleted. It does not matter have some of the processes already been closed or not. It is highly recommended to use this keyword in test or suite level teardown to make sure all the started processes are closed. """ PROCESSES.close_all() def get_file(self, path, encoding='UTF-8'): """Returns the contents of a specified file. This keyword reads the specified file and returns the contents. Line breaks in content are converted to platform independent form. See also `Get Binary File`. `encoding` defines the encoding of the file. By default the value is 'UTF-8', which means that UTF-8 and ASCII-encoded files are read correctly. """ content = self.get_binary_file(path) return unicode(content, encoding).replace('\r\n', '\n') def get_binary_file(self, path): """Returns the contents of a specified file. This keyword reads the specified file and returns the contents as is. See also `Get File`. New in Robot Framework 2.5.5. """ path = self._absnorm(path) self._link("Getting file '%s'", path) f = open(path, 'rb') try: return f.read() finally: f.close() def grep_file(self, path, pattern, encoding='UTF-8'): """Returns the lines of the specified file that match the `pattern`. This keyword reads a file from the file system using the defined `path` and `encoding` similarly as `Get File`. A difference is that only the lines that match the given `pattern` are returned. Lines are returned as a single string catenated back together with newlines and the number of matched lines is automatically logged. Possible trailing newline is never returned. A line matches if it contains the `pattern` anywhere in it and it *does not need to match the pattern fully*. The pattern matching syntax is explained in `introduction`, and in this case matching is case-sensitive. Support for different pattern types were removed in Robot Framework 2.5. Examples: | ${errors} = | Grep File | /var/log/myapp.log | ERROR | | ${ret} = | Grep File | ${CURDIR}/file.txt | [Ww]ildc??d ex*ple | If more complex pattern matching is needed, it is possible to use `Get File` in combination with String library keywords like `Get Lines Matching Regexp`. """ pattern = '*%s*' % pattern orig = self.get_file(path, encoding).splitlines() lines = [ line for line in orig if fnmatch.fnmatchcase(line, pattern) ] self._info('%d out of %d lines matched' % (len(lines), len(orig))) return '\n'.join(lines) def log_file(self, path, encoding='UTF-8'): """Wrapper for `Get File` that also logs the returned file. The file is logged with the INFO level. If you want something else, just use `Get File` and the built-in keyword `Log` with the desired level. """ content = self.get_file(path, encoding) self._info(content) return content # File and directory existence def should_exist(self, path, msg=None): """Fails unless the given path (file or directory) exists. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) if not glob.glob(path): self._fail(msg, "Path '%s' does not match any file or directory" % path) self._link("Path '%s' exists", path) def should_not_exist(self, path, msg=None): """Fails if the given path (file or directory) exists. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = glob.glob(path) if not matches: self._link("Path '%s' does not exist", path) return if not msg: if self._is_pattern_path(path): matches.sort() msg = "Path '%s' matches %s" % (path, seq2str(matches)) else: msg = "Path '%s' exists" % path raise AssertionError(msg) def file_should_exist(self, path, msg=None): """Fails unless the given `path` points to an existing file. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = [ p for p in glob.glob(path) if os.path.isfile(p) ] if not matches: self._fail(msg, "Path '%s' does not match any file" % path) self._link("File '%s' exists", path) def file_should_not_exist(self, path, msg=None): """Fails if the given path points to an existing file. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = [ p for p in glob.glob(path) if os.path.isfile(p) ] if not matches: self._link("File '%s' does not exist", path) return if not msg: if self._is_pattern_path(path): matches.sort() name = len(matches) == 1 and 'file' or 'files' msg = "Path '%s' matches %s %s" % (path, name, seq2str(matches)) else: msg = "File '%s' exists" % path raise AssertionError(msg) def directory_should_exist(self, path, msg=None): """Fails unless the given path points to an existing directory. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = [ p for p in glob.glob(path) if os.path.isdir(p) ] if not matches: self._fail(msg, "Path '%s' does not match any directory" % path) self._link("Directory '%s' exists", path) def directory_should_not_exist(self, path, msg=None): """Fails if the given path points to an existing file. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) matches = [ p for p in glob.glob(path) if os.path.isdir(p) ] if not matches: self._link("Directory '%s' does not exist", path) return if not msg: if self._is_pattern_path(path): matches.sort() name = len(matches) == 1 and 'directory' or 'directories' msg = "Path '%s' matches %s %s" % (path, name, seq2str(matches)) else: msg = "Directory '%s' exists" % path raise AssertionError(msg) def _is_pattern_path(self, path): return '*' in path or '?' in path or ('[' in path and ']' in path) # Waiting file/dir to appear/disappear def wait_until_removed(self, path, timeout='1 minute'): """Waits until the given file or directory is removed. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. If the path is a pattern, the keyword waits until all matching items are removed. The optional `timeout` can be used to control the maximum time of waiting. The timeout is given as a timeout string, e.g. in a format '15 seconds', '1min 10s' or just '10'. The time string format is described in an appendix of Robot Framework User Guide. If the timeout is negative, the keyword is never timed-out. The keyword returns immediately, if the path does not exist in the first place. """ path = self._absnorm(path) timeout = timestr_to_secs(timeout) maxtime = time.time() + timeout while glob.glob(path): time.sleep(0.1) if timeout >= 0 and time.time() > maxtime: raise AssertionError("'%s' was not removed in %s" % (path, secs_to_timestr(timeout))) self._link("'%s' was removed", path) def wait_until_created(self, path, timeout='1 minute'): """Waits until the given file or directory is created. The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. If the path is a pattern, the keyword returns when an item matching it is created. The optional `timeout` can be used to control the maximum time of waiting. The timeout is given as a timeout string, e.g. in a format '15 seconds', '1min 10s' or just '10'. The time string format is described in an appendix of Robot Framework User Guide. If the timeout is negative, the keyword is never timed-out. The keyword returns immediately, if the path already exists. """ path = self._absnorm(path) timeout = timestr_to_secs(timeout) maxtime = time.time() + timeout while not glob.glob(path): time.sleep(0.1) if timeout >= 0 and time.time() > maxtime: raise AssertionError("'%s' was not created in %s" % (path, secs_to_timestr(timeout))) self._link("'%s' was created", path) # Dir/file empty def directory_should_be_empty(self, path, msg=None): """Fails unless the specified directory is empty. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) items = self._list_dir(path) if items: if not msg: msg = "Directory '%s' is not empty. Contents: %s" \ % (path, seq2str(items, lastsep=', ')) raise AssertionError(msg) self._link("Directory '%s' is empty.", path) def directory_should_not_be_empty(self, path, msg=None): """Fails if the specified directory is empty. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) count = len(self._list_dir(path)) if count == 0: self._fail(msg, "Directory '%s' is empty." % path) plural = plural_or_not(count) self._link("Directory '%%s' contains %d item%s." % (count, plural), path) def file_should_be_empty(self, path, msg=None): """Fails unless the specified file is empty. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) if not os.path.isfile(path): raise AssertionError("File '%s' does not exist" % path) size = os.stat(path).st_size if size > 0: self._fail(msg, "File '%s' is not empty. Size: %d bytes" % (path, size)) self._link("File '%s' is empty", path) def file_should_not_be_empty(self, path, msg=None): """Fails if the specified directory is empty. The default error message can be overridden with the `msg` argument. """ path = self._absnorm(path) if not os.path.isfile(path): raise AssertionError("File '%s' does not exist" % path) size = os.stat(path).st_size if size == 0: self._fail(msg, "File '%s' is empty." % path) self._link("File '%%s' contains %d bytes" % size, path) # Creating and removing files and directory def create_file(self, path, content='', encoding='UTF-8'): """Creates a file with the given content and encoding. If the directory where to create file does not exist it, and possible intermediate missing directories, are created. Use `Append To File` if you want to append to an existing file, and use `File Should Not Exist` if you want to avoid overwriting existing files. """ path = self._write_to_file(path, content, encoding, 'w') self._link("Created file '%s'", path) def append_to_file(self, path, content, encoding='UTF-8'): """Appends the given contend to the specified file. If the file does not exists, this keyword works exactly the same way as `Create File With Encoding`. """ path = self._write_to_file(path, content, encoding, 'a') self._link("Appended to file '%s'", path) def _write_to_file(self, path, content, encoding, mode): path = self._absnorm(path) parent = os.path.dirname(path) if not os.path.exists(parent): os.makedirs(parent) f = open(path, mode+'b') try: f.write(content.encode(encoding)) finally: f.close() return path def remove_file(self, path): """Removes a file with the given path. Passes if the file does not exist, but fails if the path does not point to a regular file (e.g. it points to a directory). The path can be given as an exact path or as a glob pattern. The pattern matching syntax is explained in `introduction`. If the path is a pattern, all files matching it are removed. """ path = self._absnorm(path) matches = glob.glob(path) if not matches: self._link("File '%s' does not exist", path) for match in matches: if not os.path.isfile(match): raise RuntimeError("Path '%s' is not a file" % match) os.remove(match) self._link("Removed file '%s'", match) def remove_files(self, *paths): """Uses `Remove File` to remove multiple files one-by-one. Example: | Remove Files | ${TEMPDIR}${/}foo.txt | ${TEMPDIR}${/}bar.txt | ${TEMPDIR}${/}zap.txt | """ for path in paths: self.remove_file(path) def empty_directory(self, path): """Deletes all the content (incl. subdirectories) from the given directory.""" path = self._absnorm(path) items = [ os.path.join(path, item) for item in self._list_dir(path) ] for item in items: if os.path.isdir(item): shutil.rmtree(item) else: os.remove(item) self._link("Emptied directory '%s'", path) def create_directory(self, path): """Creates the specified directory. Also possible intermediate directories are created. Passes if the directory already exists, and fails if the path points to a regular file. """ path = self._absnorm(path) if os.path.isdir(path): self._link("Directory '%s' already exists", path ) return if os.path.exists(path): raise RuntimeError("Path '%s' already exists but is not a directory" % path) os.makedirs(path) self._link("Created directory '%s'", path) def remove_directory(self, path, recursive=False): """Removes the directory pointed to by the given `path`. If the second argument `recursive` is set to any non-empty string, the directory is removed recursively. Otherwise removing fails if the directory is not empty. If the directory pointed to by the `path` does not exist, the keyword passes, but it fails, if the `path` points to a file. """ path = self._absnorm(path) if not os.path.exists(path): self._link("Directory '%s' does not exist", path) return if os.path.isfile(path): raise RuntimeError("Path '%s' is not a directory" % path) if recursive: shutil.rmtree(path) else: msg = "Directory '%s' is not empty." % path self.directory_should_be_empty(path, msg) os.rmdir(path) self._link("Removed directory '%s'", path) # Moving and copying files and directories def copy_file(self, source, destination): """Copies the source file into a new destination. 1) If the destination is an existing file, the source file is copied over it. 2) If the destination is an existing directory, the source file is copied into it. A possible file with the same name is overwritten. 3) If the destination does not exist and it ends with a path separator ('/' or '\\'), it is considered a directory. That directory is created and a source file copied into it. Possible missing intermediate directories are also created. 4) If the destination does not exist and it does not end with a path separator, it is considered a file. If the path to the file does not exist, it is created. """ source, destination = self._copy_file(source, destination) self._link("Copied file from '%s' to '%s'", source, destination) def move_file(self, source, destination): """Moves the source file into a new destination. Uses `Copy File` keyword internally, and `source` and `destination` arguments have exactly same semantics as with that keyword. """ source, destination = self._copy_file(source, destination) os.remove(source) self._link("Moved file from '%s' to '%s'", source, destination) def _copy_file(self, source, dest): source = self._absnorm(source) dest = dest.replace('/', os.sep) dest_is_dir = dest.endswith(os.sep) dest = self._absnorm(dest) if not os.path.exists(source): raise RuntimeError("Source file '%s' does not exist" % source) if not os.path.isfile(source): raise RuntimeError("Source file '%s' is not a regular file" % source) if not os.path.exists(dest): if dest_is_dir: parent = dest else: parent = os.path.dirname(dest) if not os.path.exists(parent): os.makedirs(parent) shutil.copy(source, dest) return source, dest def copy_directory(self, source, destination): """Copies the source directory into the destination. If the destination exists, the source is copied under it. Otherwise the destination directory and the possible missing intermediate directories are created. """ source, destination = self._copy_dir(source, destination) self._link("Copied directory from '%s' to '%s'", source, destination) def move_directory(self, source, destination): """Moves the source directory into a destination. Uses `Copy Directory` keyword internally, and `source` and `destination` arguments have exactly same semantics as with that keyword. """ source, destination = self._copy_dir(source, destination) shutil.rmtree(source) self._link("Moved directory from '%s' to '%s'", source, destination) def _copy_dir(self, source, dest): source = self._absnorm(source) dest = self._absnorm(dest) if not os.path.exists(source): raise RuntimeError("Source directory '%s' does not exist" % source) if not os.path.isdir(source): raise RuntimeError("Source directory '%s' is not a directory" % source) if os.path.exists(dest) and not os.path.isdir(dest): raise RuntimeError("Destination '%s' exists but is not a directory" % dest) if os.path.exists(dest): base = os.path.basename(source) dest = os.path.join(dest, base) else: parent = os.path.dirname(dest) if not os.path.exists(parent): os.makedirs(parent) shutil.copytree(source, dest) return source, dest # Environment Variables def get_environment_variable(self, name, default=None): """Returns the value of an environment variable with the given name. If no such environment variable is set, returns the default value, if given. Otherwise fails the test case. Note that you can also access environment variables directly using the variable syntax `%{ENV_VAR_NAME}`. """ ret = os.environ.get(name, default) if ret is None: raise RuntimeError("Environment variable '%s' does not exist" % name) return ret def set_environment_variable(self, name, value): """Sets an environment variable to a specified value. Starting from Robot Framework 2.1.1, values are converted to strings automatically. """ # Cannot convert to Unicode because they aren't generally supported in # environment variables, but don't want to change deliberately given # Unicode strings either. if not isinstance(value, basestring): value = str(value) os.environ[name] = value self._info("Environment variable '%s' set to value '%s'" % (name, value)) def remove_environment_variable(self, name): """Deletes the specified environment variable. Does nothing if the environment variable is not set. """ if os.environ.has_key(name): del os.environ[name] self._info("Environment variable '%s' deleted" % name) else: self._info("Environment variable '%s' does not exist" % name) def environment_variable_should_be_set(self, name, msg=None): """Fails if the specified environment variable is not set. The default error message can be overridden with the `msg` argument. """ try: value = os.environ[name] except KeyError: self._fail(msg, "Environment variable '%s' is not set" % name) else: self._info("Environment variable '%s' is set to '%s'" % (name, value)) def environment_variable_should_not_be_set(self, name, msg=None): """Fails if the specified environment variable is set. The default error message can be overridden with the `msg` argument. """ try: value = os.environ[name] except KeyError: self._info("Environment variable '%s' is not set" % name) else: self._fail(msg, "Environment variable '%s' is set to '%s'" % (name, value)) # Path def join_path(self, base, *parts): """Joins the given path part(s) to the given base path. The path separator ('/' or '\\') is inserted when needed and the possible absolute paths handled as expected. The resulted path is also normalized. Examples: | ${path} = | Join Path | my | path | | ${p2} = | Join Path | my/ | path/ | | ${p3} = | Join Path | my | path | my | file.txt | | ${p4} = | Join Path | my | /path | | ${p5} = | Join Path | /my/path/ | .. | path2 | => - ${path} = 'my/path' - ${p2} = 'my/path' - ${p3} = 'my/path/my/file.txt' - ${p4} = '/path' - ${p5} = '/my/path2' """ base = base.replace('/', os.sep) parts = [ p.replace('/', os.sep) for p in parts ] return self.normalize_path(os.path.join(base, *parts)) def join_paths(self, base, *paths): """Joins given paths with base and returns resulted paths. See `Join Path` for more information. Examples: | @{p1} = | Join Path | base | example | other | | | @{p2} = | Join Path | /my/base | /example | other | | | @{p3} = | Join Path | my/base | example/path/ | other | one/more | => - @{p1} = ['base/example', 'base/other'] - @{p2} = ['/example', '/my/base/other'] - @{p3} = ['my/base/example/path', 'my/base/other', 'my/base/one/more'] """ return [ self.join_path(base, path) for path in paths ] def normalize_path(self, path): """Normalizes the given path. Examples: | ${path} = | Normalize Path | abc | | ${p2} = | Normalize Path | abc/ | | ${p3} = | Normalize Path | abc/../def | | ${p4} = | Normalize Path | abc/./def | | ${p5} = | Normalize Path | abc//def | => - ${path} = 'abc' - ${p2} = 'abc' - ${p3} = 'def' - ${p4} = 'abc/def' - ${p5} = 'abc/def' """ ret = os.path.normpath(path.replace('/', os.sep)) if ret == '': return '.' return ret def split_path(self, path): """Splits the given path from the last path separator ('/' or '\\'). The given path is first normalized (e.g. a possible trailing path separator is removed, special directories '..' and '.' removed). The parts that are split are returned as separate components. Examples: | ${path1} | ${dir} = | Split Path | abc/def | | ${path2} | ${file} = | Split Path | abc/def/ghi.txt | | ${path3} | ${d2} = | Split Path | abc/../def/ghi/ | => - ${path1} = 'abc' & ${dir} = 'def' - ${path2} = 'abc/def' & ${file} = 'ghi.txt' - ${path3} = 'def' & ${d2} = 'ghi' """ return os.path.split(self.normalize_path(path)) def split_extension(self, path): """Splits the extension from the given path. The given path is first normalized (e.g. possible trailing path separators removed, special directories '..' and '.' removed). The base path and extension are returned as separate components so that the dot used as an extension separator is removed. If the path contains no extension, an empty string is returned for it. Possible leading and trailing dots in the file name are never considered to be extension separators. Examples: | ${path} | ${ext} = | Split Extension | file.extension | | ${p2} | ${e2} = | Split Extension | path/file.ext | | ${p3} | ${e3} = | Split Extension | path/file | | ${p4} | ${e4} = | Split Extension | p1/../p2/file.ext | | ${p5} | ${e5} = | Split Extension | path/.file.ext | | ${p6} | ${e6} = | Split Extension | path/.file | => - ${path} = 'file' & ${ext} = 'extension' - ${p2} = 'path/file' & ${e2} = 'ext' - ${p3} = 'path/file' & ${e3} = '' - ${p4} = 'p2/file' & ${e4} = 'ext' - ${p5} = 'path/.file' & ${e5} = 'ext' - ${p6} = 'path/.file' & ${e6} = '' """ path = self.normalize_path(path) basename = os.path.basename(path) if basename.startswith('.' * basename.count('.')): return path, '' if path.endswith('.'): path2 = path.rstrip('.') trailing_dots = '.' * (len(path) - len(path2)) path = path2 else: trailing_dots = '' basepath, ext = os.path.splitext(path) if ext.startswith('.'): ext = ext[1:] if ext: ext += trailing_dots else: basepath += trailing_dots return basepath, ext # Misc def get_modified_time(self, path, format='timestamp'): """Returns the last modification time of a file or directory. How time is returned is determined based on the given `format` string as follows. Note that all checks are case-insensitive. Returned time is also automatically logged. 1) If `format` contains the word 'epoch', the time is returned in seconds after the UNIX epoch. The return value is always an integer. 2) If `format` contains any of the words 'year', 'month', 'day', 'hour', 'min' or 'sec', only the selected parts are returned. The order of the returned parts is always the one in the previous sentence and the order of the words in `format` is not significant. The parts are returned as zero-padded strings (e.g. May -> '05'). 3) Otherwise, and by default, the time is returned as a timestamp string in the format '2006-02-24 15:08:31'. Examples (when the modified time of the ${CURDIR} is 2006-03-29 15:06:21): | ${time} = | Get Modified Time | ${CURDIR} | | ${secs} = | Get Modified Time | ${CURDIR} | epoch | | ${year} = | Get Modified Time | ${CURDIR} | return year | | ${y} | ${d} = | Get Modified Time | ${CURDIR} | year,day | | @{time} = | Get Modified Time | ${CURDIR} | year,month,day,hour,min,sec | => - ${time} = '2006-03-29 15:06:21' - ${secs} = 1143637581 - ${year} = '2006' - ${y} = '2006' & ${d} = '29' - @{time} = ['2006', '03', '29', '15', '06', '21'] """ path = self._absnorm(path) if not os.path.exists(path): raise RuntimeError("Getting modified time of '%s' failed: " "Path does not exist" % path) mtime = get_time(format, os.stat(path).st_mtime) self._link("Last modified time of '%%s' is %s" % mtime, path) return mtime def set_modified_time(self, path, mtime): """Sets the file modification time. Changes the modification and access times of the given file to the value determined by `mtime`, which can be given in four different ways. 1) If `mtime` is a floating point number, it is interpreted as seconds since epoch (Jan 1, 1970 0:00:00). This documentation is written about 1177654467 seconds since epoch. 2) If `mtime` is a valid timestamp, that time will be used. Valid timestamp formats are 'YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss'. 3) If `mtime` is equal to 'NOW' (case-insensitive), the current time is used. 4) If `mtime` is in the format 'NOW - 1 day' or 'NOW + 1 hour 30 min', the current time plus/minus the time specified with the time string is used. The time string format is described in an appendix of Robot Framework User Guide. Examples: | Set Modified Time | /path/file | 1177654467 | #(2007-04-27 9:14:27) | | Set Modified Time | /path/file | 2007-04-27 9:14:27 | | Set Modified Time | /path/file | NOW | # The time of execution | | Set Modified Time | /path/file | NOW - 1d | # 1 day subtracted from NOW | | Set Modified Time | /path/file | NOW + 1h 2min 3s | # 1h 2min 3s added to NOW | """ path = self._absnorm(path) try: if not os.path.exists(path): raise ValueError('File does not exist') if not os.path.isfile(path): raise ValueError('Modified time can only be set to regular files') mtime = parse_time(mtime) except ValueError, err: raise RuntimeError("Setting modified time of '%s' failed: %s" % (path, unicode(err))) os.utime(path, (mtime, mtime)) time.sleep(0.1) # Give os some time to really set these times tstamp = secs_to_timestamp(mtime, ('-',' ',':')) self._link("Set modified time of '%%s' to %s" % tstamp, path) def get_file_size(self, path): """Returns and logs file size as an integer in bytes""" path = self._absnorm(path) if not os.path.isfile(path): raise RuntimeError("File '%s' does not exist." % path) size = os.stat(path).st_size plural = plural_or_not(size) self._link("Size of file '%%s' is %d byte%s" % (size, plural), path) return size def list_directory(self, path, pattern=None, absolute=False): """Returns and logs items in a directory, optionally filtered with `pattern`. File and directory names are returned in case-sensitive alphabetical order, e.g. ['A Name', 'Second', 'a lower case name', 'one more']. Implicit directories '.' and '..' are not returned. The returned items are automatically logged. By default, the file and directory names are returned relative to the given path (e.g. 'file.txt'). If you want them be returned in the absolute format (e.g. '/home/robot/file.txt'), set the `absolute` argument to any non-empty string. If `pattern` is given, only items matching it are returned. The pattern matching syntax is explained in `introduction`, and in this case matching is case-sensitive. Examples (using also other `List Directory` variants): | @{items} = | List Directory | ${TEMPDIR} | | @{files} = | List Files In Directory | /tmp | *.txt | absolute | | ${count} = | Count Files In Directory | ${CURDIR} | ??? | """ items = self._list_dir(path, pattern, absolute) self._info('%d item%s:\n%s' % (len(items), plural_or_not(items), '\n'.join(items))) return items def list_files_in_directory(self, path, pattern=None, absolute=False): """A wrapper for `List Directory` that returns only files.""" files = self._list_files_in_dir(path, pattern, absolute) self._info('%d file%s:\n%s' % (len(files), plural_or_not(files), '\n'.join(files))) return files def list_directories_in_directory(self, path, pattern=None, absolute=False): """A wrapper for `List Directory` that returns only directories.""" dirs = self._list_dirs_in_dir(path, pattern, absolute) self._info('%d director%s:\n%s' % (len(dirs), 'y' if len(dirs) == 1 else 'ies', '\n'.join(dirs))) return dirs def count_items_in_directory(self, path, pattern=None): """Returns and logs the number of all items in the given directory. The argument `pattern` has the same semantics as in the `List Directory` keyword. The count is returned as an integer, so it must be checked e.g. with the built-in keyword `Should Be Equal As Integers`. """ count = len(self._list_dir(path, pattern)) self._info("%s item%s." % (count, plural_or_not(count))) return count def count_files_in_directory(self, path, pattern=None): """A wrapper for `Count Items In Directory` returning onlyt directory count.""" count = len(self._list_files_in_dir(path, pattern)) self._info("%s file%s." % (count, plural_or_not(count))) return count def count_directories_in_directory(self, path, pattern=None): """A wrapper for `Count Items In Directory` returning only file count.""" count = len(self._list_dirs_in_dir(path, pattern)) self._info("%s director%s." % (count, 'y' if count == 1 else 'ies')) return count def _list_dir(self, path, pattern=None, absolute=False): path = self._absnorm(path) self._link("Listing contents of directory '%s'.", path) if not os.path.isdir(path): raise RuntimeError("Directory '%s' does not exist" % path) # result is already unicode but unic also handles NFC normalization items = sorted(unic(item) for item in os.listdir(path)) if pattern: items = [i for i in items if fnmatch.fnmatchcase(i, pattern)] if absolute: path = os.path.normpath(path) items = [os.path.join(path,item) for item in items] return items def _list_files_in_dir(self, path, pattern=None, absolute=False): return [item for item in self._list_dir(path, pattern, absolute) if os.path.isfile(os.path.join(path, item))] def _list_dirs_in_dir(self, path, pattern=None, absolute=False): return [item for item in self._list_dir(path, pattern, absolute) if os.path.isdir(os.path.join(path, item))] def touch(self, path): """Emulates the UNIX touch command. Creates a file, if it does not exist. Otherwise changes its access and modification times to the current time. Fails if used with the directories or the parent directory of the given file does not exist. """ path = self._absnorm(path) if os.path.isdir(path): raise RuntimeError("Cannot touch '%s' because it is a directory" % path) if not os.path.exists(os.path.dirname(path)): raise RuntimeError("Cannot touch '%s' because its parent directory " "does not exist" % path) if os.path.exists(path): mtime = round(time.time()) os.utime(path, (mtime, mtime)) self._link("Touched existing file '%s'", path) else: open(path, 'w').close() self._link("Touched new file '%s'", path) def _absnorm(self, path): try: return abspath(path.replace('/', os.sep)) except ValueError: # http://ironpython.codeplex.com/workitem/29489 return os.path.normpath(path.replace('/', os.sep)) def _fail(self, error, default): raise AssertionError(error or default) def _info(self, msg): self._log(msg, 'INFO') def _link(self, msg, *paths): paths = tuple('<a href="file://%s">%s</a>' % (p, p) for p in paths) self._log(msg % paths, 'HTML') def _warn(self, msg): self._log(msg, 'WARN') def _log(self, msg, level): print '*%s* %s' % (level, msg) class _Process: def __init__(self, command): self._command = self._process_command(command) self._process = os.popen(self._command) def __str__(self): return self._command def read(self): return self._process_output(self._process.read()) def close(self): try: rc = self._process.close() except IOError: # Has occurred sometimes in Windows return 255 if rc is None: return 0 # In Windows (Python and Jython) return code is value returned by # command (can be almost anything) # In other OS: # In Jython return code can be between '-255' - '255' # In Python return code must be converted with 'rc >> 8' and it is # between 0-255 after conversion if os.sep == '\\' or sys.platform.startswith('java'): return rc % 256 return rc >> 8 def _process_command(self, command): if self._is_jython(2, 2): # os.popen doesn't handle Unicode in Jython 2.2 as explained in # http://jython.org/bugs/1735774. command = str(command) if '>' not in command: if command.endswith('&'): command = command[:-1] + ' 2>&1 &' else: command += ' 2>&1' return self._encode_to_file_system(command) def _encode_to_file_system(self, string): enc = sys.getfilesystemencoding() return string.encode(enc) if enc else string def _process_output(self, stdout): stdout = stdout.replace('\r\n', '\n') # http://bugs.jython.org/issue1566 if stdout.endswith('\n'): stdout = stdout[:-1] if self._is_jython(2, 2): return stdout return decode_output(stdout) def _is_jython(self, *version): return sys.platform.startswith('java') and sys.version_info[:2] == version class _Process2(_Process): def __init__(self, command, input_): self._command = self._process_command(command) stdin, self.stdout = os.popen2(self._command) if input_: stdin.write(input_) stdin.close() self.closed = False def read(self): if self.closed: raise RuntimeError('Cannot read from a closed process') return self._process_output(self.stdout.read()) def close(self): if not self.closed: self.stdout.close() self.closed = True
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def none_shall_pass(who): if who is not None: raise AssertionError('None shall pass!') print '*HTML* <object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/dhRUe-gz690&hl=en_US&fs=1&rel=0&color1=0x234900&color2=0x4e9e00"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/dhRUe-gz690&hl=en_US&fs=1&rel=0&color1=0x234900&color2=0x4e9e00" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>'
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import OperatingSystem OPSYS = OperatingSystem.OperatingSystem() class DeprecatedOperatingSystem: ROBOT_LIBRARY_SCOPE = 'GLOBAL' delete_environment_variable = OPSYS.remove_environment_variable environment_variable_is_set = OPSYS.environment_variable_should_be_set environment_variable_is_not_set = OPSYS.environment_variable_should_not_be_set fail_unless_exists = OPSYS.should_exist fail_if_exists = OPSYS.should_not_exist fail_unless_file_exists = OPSYS.file_should_exist fail_if_file_exists = OPSYS.file_should_not_exist fail_unless_dir_exists = OPSYS.directory_should_exist fail_if_dir_exists = OPSYS.directory_should_not_exist fail_unless_dir_empty = OPSYS.directory_should_be_empty fail_if_dir_empty = OPSYS.directory_should_not_be_empty fail_unless_file_empty = OPSYS.file_should_be_empty fail_if_file_empty = OPSYS.file_should_not_be_empty empty_dir = OPSYS.empty_directory remove_dir = OPSYS.remove_directory copy_dir = OPSYS.copy_directory move_dir = OPSYS.move_directory create_dir = OPSYS.create_directory list_dir = OPSYS.list_directory list_files_in_dir = OPSYS.list_files_in_directory list_dirs_in_dir = OPSYS.list_directories_in_directory count_items_in_dir = OPSYS.count_items_in_directory count_files_in_dir = OPSYS.count_files_in_directory count_dirs_in_dir = OPSYS.count_directories_in_directory
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os if sys.platform.startswith('java'): from java.awt import Toolkit, Robot, Rectangle from javax.imageio import ImageIO from java.io import File else: try: import wx _wx_app_reference = wx.PySimpleApp() except ImportError: wx = None try: from gtk import gdk except ImportError: gdk = None try: from PIL import ImageGrab # apparently available only on Windows except ImportError: ImageGrab = None from robot.version import get_version from robot import utils from robot.libraries.BuiltIn import BuiltIn class Screenshot(object): """A test library for taking screenshots and embedding them into log files. *Using with Jython* On Jython this library uses Java AWT APIs. They are always available and thus no external modules are needed. *Using with Python* On Python you need to have one of the following modules installed to be able to use this library. The first module that is found will be used. - wxPython :: http://wxpython.org :: Required also by RIDE so many Robot Framework users already have this module installed. - PyGTK :: http://pygtk.org :: This module is available by default on most Linux distributions. - Python Imaging Library (PIL) :: http://www.pythonware.com/products/pil :: This module can take screenshots only on Windows. Python support was added in Robot Framework 2.5.5. *Where screenshots are saved* By default screenshots are saved into the same directory where the Robot Framework log file is written. If no log is created, screenshots are saved into the directory where the XML output file is written. It is possible to specify a custom location for screenshots using `screenshot_directory` argument in `importing` and `Set Screenshot Directory` keyword during execution. It is also possible to save screenshots using an absolute path. Note that prior to Robot Framework 2.5.5 the default screenshot location was system's temporary directory. *Changes in Robot Framework 2.5.5 and Robot Framework 2.6* This library was heavily enhanced in Robot Framework 2.5.5 release. The changes are listed below and explained more thoroughly in affected places. - The support for using this library on Python (see above) was added. - The default location where screenshots are saved was changed (see above). - New `Take Screenshot` and `Take Screenshot Without Embedding` keywords were added. These keywords should be used for taking screenshots in the future. Other screenshot taking keywords will be deprecated and removed later. - `log_file_directory` argument was deprecated everywhere it was used. In Robot Framework 2.6, following additional changes were made: - `log_file_directory` argument was removed altogether. - `Set Screenshot Directories` keyword was removed. - `Save Screenshot`, `Save Screenshot To` and `Log Screenshot` keywords were deprecated. They will be removed in 2.7 version. """ ROBOT_LIBRARY_SCOPE = 'TEST SUITE' ROBOT_LIBRARY_VERSION = get_version() def __init__(self, screenshot_directory=None): """Configure where screenshots are saved. If `screenshot_directory` is not given, screenshots are saved into same directory as the log file. The directory can also be set using `Set Screenshot Directory` keyword. Examples (use only one of these): | *Setting* | *Value* | *Value* | *Value* | | Library | Screenshot | | # Default location | | Library | Screenshot | ${TEMPDIR} | # System temp (this was default prior to 2.5.5) | """ self._given_screenshot_dir = self._norm_path(screenshot_directory) self._screenshot_taker = ScreenshotTaker() def _norm_path(self, path): if not path: return path return os.path.normpath(path.replace('/', os.sep)) @property def _screenshot_dir(self): return self._given_screenshot_dir or self._log_dir @property def _log_dir(self): variables = BuiltIn().get_variables() outdir = variables['${OUTPUTDIR}'] log = variables['${LOGFILE}'] log = os.path.dirname(log) if log != 'NONE' else '.' return self._norm_path(os.path.join(outdir, log)) def set_screenshot_directory(self, path): """Sets the directory where screenshots are saved. It is possible to use `/` as a path separator in all operating systems. Path to the old directory is returned. The directory can also be set in `importing`. """ path = self._norm_path(path) if not os.path.isdir(path): raise RuntimeError("Directory '%s' does not exist." % path) old = self._screenshot_dir self._given_screenshot_dir = path return old def save_screenshot_to(self, path): """*DEPRECATED* Use `Take Screenshot` or `Take Screenshot Without Embedding` instead.""" path = self._screenshot_to_file(path) self._link_screenshot(path) return path def save_screenshot(self, basename="screenshot", directory=None): """*DEPRECATED* Use `Take Screenshot` or `Take Screenshot Without Embedding` instead.""" path = self._save_screenshot(basename, directory) self._link_screenshot(path) return path def log_screenshot(self, basename='screenshot', directory=None, width='100%'): """*DEPRECATED* Use `Take Screenshot` or `Take Screenshot Without Embedding` instead.""" path = self._save_screenshot(basename, directory) self._embed_screenshot(path, width) return path def take_screenshot(self, name="screenshot", width="800px"): """Takes a screenshot and embeds it into the log file. Name of the file where the screenshot is stored is derived from `name`. If `name` ends with extension `.jpg` or `.jpeg`, the screenshot will be stored with that name. Otherwise a unique name is created by adding underscore, a running index and extension to the `name`. The name will be interpreted to be relative to the directory where the log file is written. It is also possible to use absolute paths. `width` specifies the size of the screenshot in the log file. The path where the screenshot is saved is returned. Examples: (LOGDIR is determined automatically by the library) | Take Screenshot | | | # LOGDIR/screenshot_1.jpg (index automatically incremented) | | Take Screenshot | mypic | | # LOGDIR/mypic_1.jpg (index automatically incremented) | | Take Screenshot | ${TEMPDIR}/mypic | | # /tmp/mypic_1.jpg (index automatically incremented) | | Take Screenshot | pic.jpg | | # LOGDIR/pic.jpg (always uses this file) | | Take Screenshot | images/login.jpg | 80% | # Specify both name and width. | | Take Screenshot | width=550px | | # Specify only width. | Screenshots can be only taken in JPEG format. It is possible to use `/` as a path separator in all operating systems. """ path = self._save_screenshot(name) self._embed_screenshot(path, width) return path def take_screenshot_without_embedding(self, name="screenshot"): """Takes a screenshot and links it from the log file. This keyword is otherwise identical to `Take Screenshot` but the saved screenshot is not embedded into the log file. The screenshot is linked so it is nevertheless easily available. """ path = self._save_screenshot(name) self._link_screenshot(path) return path def _save_screenshot(self, basename, directory=None): path = self._get_screenshot_path(basename, directory) return self._screenshot_to_file(path) def _screenshot_to_file(self, path): path = utils.abspath(self._norm_path(path)) self._validate_screenshot_path(path) print '*DEBUG* Using %s modules for taking screenshot.' \ % self._screenshot_taker.module self._screenshot_taker(path) return path def _validate_screenshot_path(self, path): if not os.path.exists(os.path.dirname(path)): raise RuntimeError("Directory '%s' where to save the screenshot does " "not exist" % os.path.dirname(path)) def _get_screenshot_path(self, basename, directory): directory = self._norm_path(directory) if directory else self._screenshot_dir if basename.lower().endswith(('.jpg', '.jpeg')): return os.path.join(directory, basename) index = 0 while True: index += 1 path = os.path.join(directory, "%s_%d.jpg" % (basename, index)) if not os.path.exists(path): return path def _embed_screenshot(self, path, width): link = utils.get_link_path(path, self._log_dir) print '*HTML* <a href="%s"><img src="%s" width="%s" /></a>' \ % (link, link, width) def _link_screenshot(self, path): link = utils.get_link_path(path, self._log_dir) print "*HTML* Screenshot saved to '<a href=\"%s\">%s</a>'." % (link, path) class ScreenshotTaker(object): def __init__(self, module_name=None): self._screenshot = self._get_screenshot_taker(module_name) self.module = self._screenshot.__name__.split('_')[1] def __call__(self, path): self._screenshot(path) def _get_screenshot_taker(self, module_name): if sys.platform.startswith('java'): return self._java_screenshot if module_name: method_name = '_%s_screenshot' % module_name.lower() if hasattr(self, method_name): return getattr(self, method_name) return self._get_default_screenshot_taker() def _get_default_screenshot_taker(self): for module, screenshot_taker in [(wx, self._wx_screenshot), (gdk, self._gtk_screenshot), (ImageGrab, self._pil_screenshot), (True, self._no_screenshot)]: if module: return screenshot_taker def _java_screenshot(self, path): size = Toolkit.getDefaultToolkit().getScreenSize() rectangle = Rectangle(0, 0, size.width, size.height) image = Robot().createScreenCapture(rectangle) ImageIO.write(image, 'jpg', File(path)) def _wx_screenshot(self, path): context = wx.ScreenDC() width, height = context.GetSize() bitmap = wx.EmptyBitmap(width, height, -1) memory = wx.MemoryDC() memory.SelectObject(bitmap) memory.Blit(0, 0, width, height, context, -1, -1) memory.SelectObject(wx.NullBitmap) bitmap.SaveFile(path, wx.BITMAP_TYPE_JPEG) def _gtk_screenshot(self, path): window = gdk.get_default_root_window() if not window: raise RuntimeError('Taking screenshot failed') width, height = window.get_size() pb = gdk.Pixbuf(gdk.COLORSPACE_RGB, False, 8, width, height) pb = pb.get_from_drawable(window, window.get_colormap(), 0, 0, 0, 0, width, height) if not pb: raise RuntimeError('Taking screenshot failed') pb.save(path, 'jpeg') def _pil_screenshot(self, path): ImageGrab.grab().save(path, 'JPEG') def _no_screenshot(self, path): raise RuntimeError('Taking screenshots is not supported on this platform ' 'by default. See library documentation for details.') if __name__ == "__main__": if len(sys.argv) not in [2, 3]: print "Usage: %s path [wx|gtk|pil]" % os.path.basename(sys.argv[0]) sys.exit(1) path = utils.abspath(sys.argv[1]) module = sys.argv[2] if len(sys.argv) == 3 else None shooter = ScreenshotTaker(module) print 'Using %s modules' % shooter.module shooter(path) print path
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re import fnmatch from robot.utils import asserts import BuiltIn BUILTIN = BuiltIn.BuiltIn() class DeprecatedBuiltIn: ROBOT_LIBRARY_SCOPE = 'GLOBAL' integer = BUILTIN.convert_to_integer float = BUILTIN.convert_to_number string = BUILTIN.convert_to_string boolean = BUILTIN.convert_to_boolean list = BUILTIN.create_list equal = equals = fail_unless_equal = BUILTIN.should_be_equal not_equal = not_equals = fail_if_equal = BUILTIN.should_not_be_equal is_true = fail_unless = BUILTIN.should_be_true is_false = fail_if = BUILTIN.should_not_be_true fail_if_ints_equal = ints_not_equal = BUILTIN.should_not_be_equal_as_integers ints_equal = fail_unless_ints_equal = BUILTIN.should_be_equal_as_integers floats_not_equal = fail_if_floats_equal = BUILTIN.should_not_be_equal_as_numbers floats_equal = fail_unless_floats_equal = BUILTIN.should_be_equal_as_numbers does_not_start = fail_if_starts = BUILTIN.should_not_start_with starts = fail_unless_starts = BUILTIN.should_start_with does_not_end = fail_if_ends = BUILTIN.should_not_end_with ends = fail_unless_ends = BUILTIN.should_end_with does_not_contain = fail_if_contains = BUILTIN.should_not_contain contains = fail_unless_contains = BUILTIN.should_contain does_not_match = fail_if_matches = BUILTIN.should_not_match matches = fail_unless_matches = BUILTIN.should_match does_not_match_regexp = fail_if_regexp_matches = BUILTIN.should_not_match_regexp matches_regexp = fail_unless_regexp_matches = BUILTIN.should_match_regexp noop = BUILTIN.no_operation set_ = BUILTIN.set_variable message = BUILTIN.comment variable_exists = fail_unless_variable_exists = BUILTIN.variable_should_exist variable_does_not_exist = fail_if_variable_exists = BUILTIN.variable_should_not_exist def error(self, msg=None): """Errors the test immediately with the given message.""" asserts.error(msg) def grep(self, text, pattern, pattern_type='literal string'): lines = self._filter_lines(text.splitlines(), pattern, pattern_type) return '\n'.join(lines) def _filter_lines(self, lines, pattern, ptype): ptype = ptype.lower().replace(' ','').replace('-','') if not pattern: filtr = lambda line: True elif 'simple' in ptype or 'glob' in ptype: if 'caseinsensitive' in ptype: pattern = pattern.lower() filtr = lambda line: fnmatch.fnmatchcase(line.lower(), pattern) else: filtr = lambda line: fnmatch.fnmatchcase(line, pattern) elif 'regularexpression' in ptype or 'regexp' in ptype: pattern = re.compile(pattern) filtr = lambda line: pattern.search(line) elif 'caseinsensitive' in ptype: pattern = pattern.lower() filtr = lambda line: pattern in line.lower() else: filtr = lambda line: pattern in line return [ line for line in lines if filtr(line) ]
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from fnmatch import fnmatchcase from random import randint from string import ascii_lowercase, ascii_uppercase, digits from robot.version import get_version class String: """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 the BuiltIn library can also be used with strings: - `Catenate` - `Get Length` - `Length Should Be` - `Should (Not) Match (Regexp)` - `Should (Not) Be Empty` - `Should (Not) Be Equal (As Strings/Integers/Numbers)` - `Should (Not) Contain` - `Should (Not) Start With` - `Should (Not) End With` """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() def get_line_count(self, string): """Returns and logs the number of lines in the given `string`.""" count = len(string.splitlines()) print '*INFO* %d lines' % count return count def split_to_lines(self, string, start=0, end=None): """Converts the `string` into a list of lines. It is possible to get only a selection of lines from `start` to `end` so that `start` index is inclusive and `end` is exclusive. Line numbering starts from 0, and it is possible to use negative indices to refer to lines from the end. Lines are returned without the newlines. The number of returned lines is automatically logged. Examples: | @{lines} = | Split To Lines | ${manylines} | | | | @{ignore first} = | Split To Lines | ${manylines} | 1 | | | @{ignore last} = | Split To Lines | ${manylines} | | -1 | | @{5th to 10th} = | Split To Lines | ${manylines} | 4 | 10 | | @{first two} = | Split To Lines | ${manylines} | | 1 | | @{last two} = | Split To Lines | ${manylines} | -2 | | Use `Get Line` if you only need to get a single line. """ start = self._convert_to_index(start, 'start') end = self._convert_to_index(end, 'end') lines = string.splitlines()[start:end] print '*INFO* %d lines returned' % len(lines) return lines def get_line(self, string, line_number): """Returns the specified line from the given `string`. Line numbering starts from 0 and it is possible to use negative indices to refer to lines from the end. The line is returned without the newline character. Examples: | ${first} = | Get Line | ${string} | 0 | | ${2nd last} = | Get Line | ${string} | -2 | """ line_number = self._convert_to_integer(line_number, 'line_number') return string.splitlines()[line_number] def get_lines_containing_string(self, string, pattern, case_insensitive=False): """Returns lines of the given `string` that contain the `pattern`. The `pattern` is always considered to be a normal string and a line matches if the `pattern` is found anywhere in it. By default the match is case-sensitive, but setting `case_insensitive` to any value makes it case-insensitive. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: | ${lines} = | Get Lines Containing String | ${result} | An example | | ${ret} = | Get Lines Containing String | ${ret} | FAIL | case-insensitive | See `Get Lines Matching Pattern` and `Get Lines Matching Regexp` if you need more complex pattern matching. """ if case_insensitive: pattern = pattern.lower() contains = lambda line: pattern in line.lower() else: contains = lambda line: pattern in line return self._get_matching_lines(string, contains) def get_lines_matching_pattern(self, string, pattern, case_insensitive=False): """Returns lines of the given `string` that match the `pattern`. The `pattern` is a _glob pattern_ where: | * | matches everything | | ? | matches any single character | | [chars] | matches any character inside square brackets (e.g. '[abc]' matches either 'a', 'b' or 'c') | | [!chars] | matches any character not inside square brackets | A line matches only if it matches the `pattern` fully. By default the match is case-sensitive, but setting `case_insensitive` to any value makes it case-insensitive. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: | ${lines} = | Get Lines Matching Pattern | ${result} | Wild???? example | | ${ret} = | Get Lines Matching Pattern | ${ret} | FAIL: * | case-insensitive | See `Get Lines Matching Regexp` if you need more complex patterns and `Get Lines Containing String` if searching literal strings is enough. """ if case_insensitive: pattern = pattern.lower() matches = lambda line: fnmatchcase(line.lower(), pattern) else: matches = lambda line: fnmatchcase(line, pattern) return self._get_matching_lines(string, matches) def get_lines_matching_regexp(self, string, pattern): """Returns lines of the given `string` that match the regexp `pattern`. See `BuiltIn.Should Match Regexp` for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. A line matches only if it matches the `pattern` fully. Notice that to make the match case-insensitive, you need to embed case-insensitive flag into the pattern. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: | ${lines} = | Get Lines Matching Regexp | ${result} | Reg\\\\w{3} example | | ${ret} = | Get Lines Matching Regexp | ${ret} | (?i)FAIL: .* | See `Get Lines Matching Pattern` and `Get Lines Containing String` if you do not need full regular expression powers (and complexity). """ regexp = re.compile('^%s$' % pattern) return self._get_matching_lines(string, regexp.match) def _get_matching_lines(self, string, matches): lines = string.splitlines() matching = [ line for line in lines if matches(line) ] print '*INFO* %d out of %d lines matched' % (len(matching), len(lines)) return '\n'.join(matching) def replace_string(self, string, search_for, replace_with, count=-1): """Replaces `search_for` in the given `string` with `replace_with`. `search_for` is used as a literal string. See `Replace String Using Regexp` if more powerful pattern matching is needed. If 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 | ${str} | Hello | Hi | | | ${str} = | Replace String | ${str} | world | tellus | 1 | """ 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. Examples: | ${str} = | Replace String Using Regexp | ${str} | (Hello|Hi) | Hei | | | ${str} = | Replace String Using Regexp | ${str} | 20\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d | <DATE> | 2 | """ count = self._convert_to_integer(count, 'count') # re.sub handles 0 and negative counts differently than string.replace if count < 0: count = 0 elif count == 0: count = -1 return re.sub(pattern, replace_with, string, count) 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} | ${others} = | Split String | ${string} | - | 1 | | ${others} | ${last} = | Split String From Right | ${string} | - | 1 | """ # Strings in Jython 2.2 don't have 'rsplit' methods reversed = self.split_string(string[::-1], separator, max_split) return [ r[::-1] for r in reversed ][::-1] 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: | _[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 i in xrange(length) ]) def get_substring(self, string, start, end=None): """Returns a substring from `start` index to `end` index. The `start` index is inclusive and `end` is exclusive. Indexing starts from 0, and it is possible to use negative indices to refer to characters from the end. Examples: | ${ignore first} = | Get Substring | ${string} | 1 | | | ${ignore last} = | Get Substring | ${string} | | -1 | | ${5th to 10th} = | Get Substring | ${string} | 4 | 10 | | ${first two} = | Get Substring | ${string} | | 1 | | ${last two} = | Get Substring | ${string} | -2 | | """ start = self._convert_to_index(start, 'start') end = self._convert_to_index(end, 'end') return string[start:end] def should_be_string(self, item, msg=None): """Fails if the given `item` is not a string. The default error message can be overridden with the optional `msg` argument. """ if not isinstance(item, basestring): if not msg: msg = "Given item '%s' is not a string" % item raise AssertionError(msg) def should_not_be_string(self, item, msg=None): """Fails if the given `item` is a string. The default error message can be overridden with the optional `msg` argument. """ if isinstance(item, basestring): if not msg: msg = "Given item '%s' is a string" % item raise AssertionError(msg) def should_be_lowercase(self, string, msg=None): """Fails if the given `string` is not in lowercase. The default error message can be overridden with the optional `msg` argument. For example 'string' and 'with specials!' would pass, and 'String', '' and ' ' would fail. See also `Should Be Uppercase` and `Should Be Titlecase`. All these keywords were added in Robot Framework 2.1.2. """ if not string.islower(): raise AssertionError(msg or "'%s' is not lowercase" % string) def should_be_uppercase(self, string, msg=None): """Fails if the given `string` is not in uppercase. The default error message can be overridden with the optional `msg` argument. For example 'STRING' and 'WITH SPECIALS!' would pass, and 'String', '' and ' ' would fail. See also `Should Be Titlecase` and `Should Be Lowercase`. All these keywords were added in Robot Framework 2.1.2. """ if not string.isupper(): raise AssertionError(msg or "'%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. The default error message can be overridden with the optional `msg` argument. For example 'This Is Title' would pass, and 'Word In UPPER', 'Word In lower', '' and ' ' would fail. See also `Should Be Uppercase` and `Should Be Lowercase`. All theses keyword were added in Robot Framework 2.1.2. """ if not string.istitle(): raise AssertionError(msg or "'%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))
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A test library providing dialogs for interacting with users. `Dialogs` is Robot Framework's standard library that provides means for pausing the test execution and getting input from users. The dialogs are slightly different depending on are tests run on Python or Jython but they provide the same functionality. Note: Dialogs library cannot be used with timeouts on Windows with Python. """ __all__ = ['execute_manual_step', 'get_value_from_user', 'get_selection_from_user', 'pause_execution'] import sys try: from robot.version import get_version as _get_version except ImportError: __version__ = 'unknown' else: __version__ = _get_version() DIALOG_TITLE = 'Robot Framework' def pause_execution(message='Test execution paused. Press OK to continue.'): """Pauses the test execution and shows dialog with the text `message`. """ MessageDialog(message) def execute_manual_step(message, default_error=''): """Pauses the test execution until user sets the keyword status. `message` is the instruction shown in the dialog. User can select PASS or FAIL, and in the latter case an additional dialog is opened for defining the error message. `default_error` is the possible default value shown in the error message dialog. """ if not PassFailDialog(message).result: msg = get_value_from_user('Give error message:', default_error) raise AssertionError(msg) def get_value_from_user(message, default_value=''): """Pauses the test execution and asks user to input a value. `message` is the instruction shown in the dialog. `default_value` is the possible default value shown in the input field. Selecting 'Cancel' fails the keyword. """ return _validate_user_input(InputDialog(message, default_value).result) def get_selection_from_user(message, *values): """Pauses the test execution and asks user to select value `message` is the instruction shown in the dialog. and `values` are the options given to the user. Selecting 'Cancel' fails the keyword. This keyword was added into Robot Framework 2.1.2. """ return _validate_user_input(SelectionDialog(message, values).result) def _validate_user_input(value): if value is None: raise ValueError('No value provided by user') return value if not sys.platform.startswith('java'): from Tkinter import (Tk, Toplevel, Frame, Listbox, Label, Button, BOTH, END, LEFT) import tkMessageBox import tkSimpleDialog from threading import currentThread def prevent_execution_with_timeouts(method): def check_timeout(*args): if 'linux' not in sys.platform \ and currentThread().getName() != 'MainThread': raise RuntimeError('Dialogs library is not supported with ' 'timeouts on Python on this platform.') return method(*args) return check_timeout class _AbstractTkDialog(Toplevel): @prevent_execution_with_timeouts def __init__(self, title): parent = Tk() parent.withdraw() Toplevel.__init__(self, parent) self._init_dialog(parent, title) self._create_body() self._create_buttons() self.result = None self._initial_focus.focus_set() self.wait_window(self) def _init_dialog(self, parent, title): self.title(title) self.grab_set() self.protocol("WM_DELETE_WINDOW", self._right_clicked) self.geometry("+%d+%d" % (parent.winfo_rootx()+150, parent.winfo_rooty()+150)) def _create_body(self): frame = Frame(self) self._initial_focus = self.create_components(frame) frame.pack(padx=5, pady=5, expand=1, fill=BOTH) def _create_buttons(self): frame = Frame(self) self._create_button(frame, self._left_button, self._left_clicked) self._create_button(frame, self._right_button, self._right_clicked) self.bind("<Escape>", self._right_clicked) frame.pack() def _create_button(self, parent, label, command): w = Button(parent, text=label, width=10, command=command) w.pack(side=LEFT, padx=5, pady=5) def _left_clicked(self, event=None): if not self.validate(): self._initial_focus.focus_set() return self.withdraw() self.apply() self.destroy() def _right_clicked(self, event=None): self.destroy() def create_components(self, parent): raise NotImplementedError() def validate(self): raise NotImplementedError() def apply(self): raise NotImplementedError() class MessageDialog(object): @prevent_execution_with_timeouts def __init__(self, message): Tk().withdraw() tkMessageBox.showinfo(DIALOG_TITLE, message) class InputDialog(object): @prevent_execution_with_timeouts def __init__(self, message, default): Tk().withdraw() self.result = tkSimpleDialog.askstring(DIALOG_TITLE, message, initialvalue=default) class SelectionDialog(_AbstractTkDialog): _left_button = 'OK' _right_button = 'Cancel' def __init__(self, message, values): self._message = message self._values = values _AbstractTkDialog.__init__(self, "Select one option") def create_components(self, parent): Label(parent, text=self._message).pack(fill=BOTH) self._listbox = Listbox(parent) self._listbox.pack(fill=BOTH) for item in self._values: self._listbox.insert(END, item) return self._listbox def validate(self): return bool(self._listbox.curselection()) def apply(self): self.result = self._listbox.get(self._listbox.curselection()) class PassFailDialog(_AbstractTkDialog): _left_button = 'PASS' _right_button = 'FAIL' def __init__(self, message): self._message = message _AbstractTkDialog.__init__(self, DIALOG_TITLE) def create_components(self, parent): label = Label(parent, text=self._message) label.pack(fill=BOTH) return label def validate(self): return True def apply(self): self.result = True else: import time from javax.swing import JOptionPane from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \ YES_NO_OPTION, OK_CANCEL_OPTION, DEFAULT_OPTION class _AbstractSwingDialog: def __init__(self, message): self.result = self._show_dialog(message) def _show_dialog(self, message): self._init_dialog(message) self._show_dialog_and_wait_it_to_be_closed() return self._get_value() def _show_dialog_and_wait_it_to_be_closed(self): dialog = self._pane.createDialog(None, DIALOG_TITLE) dialog.setModal(0); dialog.show() while dialog.isShowing(): time.sleep(0.2) dialog.dispose() def _get_value(self): value = self._pane.getInputValue() if value == UNINITIALIZED_VALUE: return None return value class MessageDialog(_AbstractSwingDialog): def _init_dialog(self, message): self._pane = JOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION) class InputDialog(_AbstractSwingDialog): def __init__(self, message, default): self._default = default _AbstractSwingDialog.__init__(self, message) def _init_dialog(self, message): self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION) self._pane.setWantsInput(True) self._pane.setInitialSelectionValue(self._default) class SelectionDialog(_AbstractSwingDialog): def __init__(self, message, options): self._options = options _AbstractSwingDialog.__init__(self, message) def _init_dialog(self, message): self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION) self._pane.setWantsInput(True) self._pane.setSelectionValues(self._options) class PassFailDialog(_AbstractSwingDialog): def _init_dialog(self, message): self._buttons = ['PASS', 'FAIL'] self._pane = JOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION, None, self._buttons, 'PASS') def _get_value(self): value = self._pane.getValue() if value in self._buttons and self._buttons.index(value) == 0: return True return False
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import time from robot.output import LOGGER, Message from robot.errors import DataError, ExecutionFailed, ExecutionFailures from robot import utils from robot.utils import asserts from robot.variables import is_var, is_list_var from robot.running import Keyword, NAMESPACES, RUN_KW_REGISTER from robot.running.model import ExecutionContext from robot.version import get_version if utils.is_jython: from java.lang import String, Number try: bin # available since Python 2.6 except NameError: def bin(integer): if not isinstance(integer, (int, long)): raise TypeError if integer >= 0: prefix = '0b' else: prefix = '-0b' integer = abs(integer) bins = [] while integer > 1: integer, remainder = divmod(integer, 2) bins.append(str(remainder)) bins.append(str(integer)) return prefix + ''.join(reversed(bins)) class _Converter: def convert_to_integer(self, item, base=None): """Converts the given item to an integer number. If the given item is a string, it is by default expected to be an integer in base 10. Starting from Robot Framework 2.6 there are two ways to convert from other bases: 1) Give base explicitly to the keyword as `base` argument. 2) Prefix the given string with the base so that `0b` means binary (base 2), `0o` means octal (base 8), and `0x` means hex (base 16). The prefix is considered only when `base` argument is not given and may itself be prefixed with a plus or minus sign. The syntax is case-insensitive and possible spaces are ignored. Examples: | ${result} = | Convert To Integer | 100 | | # Result is 100 | | ${result} = | Convert To Integer | FF AA | 16 | # Result is 65450 | | ${result} = | Convert To Integer | 100 | 8 | # Result is 64 | | ${result} = | Convert To Integer | -100 | 2 | # Result is -4 | | ${result} = | Convert To Integer | 0b100 | | # Result is 4 | | ${result} = | Convert To Integer | -0x100 | | # Result is -256 | See also `Convert To Number`, `Convert To Binary`, `Convert To Octal` and `Convert To Hex`. """ self._log_types(item) return self._convert_to_integer(item, base) def _convert_to_integer(self, orig, base=None): try: item = self._handle_java_numbers(orig) item, base = self._get_base(item, base) if base: return int(item, self._convert_to_integer(base)) return int(item) except: raise RuntimeError("'%s' cannot be converted to an integer: %s" % (orig, utils.get_error_message())) def _handle_java_numbers(self, item): if not utils.is_jython: return item if isinstance(item, String): return utils.unic(item) if isinstance(item, Number): return item.doubleValue() return item def _get_base(self, item, base): if not isinstance(item, basestring): return item, base item = utils.normalize(item) if item.startswith(('-', '+')): sign = item[0] item = item[1:] else: sign = '' bases = {'0b': 2, '0o': 8, '0x': 16} if base or not item.startswith(tuple(bases)): return sign+item, base return sign+item[2:], bases[item[:2]] def convert_to_binary(self, item, base=None, prefix=None, length=None): """Converts the given item to a binary string. The `item`, with an optional `base`, is first converted to an integer using `Convert To Integer` internally. After that it is converted to a binary number (base 2) represented as a string such as `'1011'`. The returned value can contain an optional `prefix` and can be required to be of minimum `length` (excluding the prefix and a possible minus sign). If the value is initially shorter than the required length, it is padded with zeros. Examples: | ${result} = | Convert To Binary | 10 | | | # Result is 1010 | | ${result} = | Convert To Binary | F | base=16 | prefix=0b | # Result is 0b1111 | | ${result} = | Convert To Binary | -2 | prefix=B | length=4 | # Result is -B0010 | This keyword was added in Robot Framework 2.6. See also `Convert To Integer`, `Convert To Octal` and `Convert To Hex`. """ return self._convert_to_bin_oct_hex(bin, item, base, prefix, length) def convert_to_octal(self, item, base=None, prefix=None, length=None): """Converts the given item to an octal string. The `item`, with an optional `base`, is first converted to an integer using `Convert To Integer` internally. After that it is converted to an octal number (base 8) represented as a string such as `'775'`. The returned value can contain an optional `prefix` and can be required to be of minimum `length` (excluding the prefix and a possible minus sign). If the value is initially shorter than the required length, it is padded with zeros. Examples: | ${result} = | Convert To Octal | 10 | | | # Result is 12 | | ${result} = | Convert To Octal | -F | base=16 | prefix=0 | # Result is -017 | | ${result} = | Convert To Octal | 16 | prefix=oct | length=4 | # Result is oct0020 | This keyword was added in Robot Framework 2.6. See also `Convert To Integer`, `Convert To Binary` and `Convert To Hex`. """ return self._convert_to_bin_oct_hex(oct, item, base, prefix, length) def convert_to_hex(self, item, base=None, prefix=None, length=None, lowercase=False): """Converts the given item to a hexadecimal string. The `item`, with an optional `base`, is first converted to an integer using `Convert To Integer` internally. After that it is converted to a hexadecimal number (base 16) represented as a string such as `'FF0A'`. The returned value can contain an optional `prefix` and can be required to be of minimum `length` (excluding the prefix and a possible minus sign). If the value is initially shorter than the required length, it is padded with zeros. By default the value is returned as an upper case string, but giving any non-empty value to the `lowercase` argument turns the value (but not the prefix) to lower case. Examples: | ${result} = | Convert To Hex | 255 | | | # Result is FF | | ${result} = | Convert To Hex | -10 | prefix=0x | length=2 | # Result is -0x0A | | ${result} = | Convert To Hex | 255 | prefix=X | lowercase=yes | # Result is Xff | This keyword was added in Robot Framework 2.6. See also `Convert To Integer`, `Convert To Binary` and `Convert To Octal`. """ return self._convert_to_bin_oct_hex(hex, item, base, prefix, length, lowercase) def _convert_to_bin_oct_hex(self, method, item, base, prefix, length, lowercase=False): self._log_types(item) ret = method(self._convert_to_integer(item, base)).upper() prefix = prefix or '' if ret[0] == '-': prefix = '-' + prefix ret = ret[1:] if len(ret) > 1: # oct(0) -> '0' (i.e. has no prefix) prefix_length = {bin: 2, oct: 1, hex: 2}[method] ret = ret[prefix_length:] if length: ret = ret.rjust(self._convert_to_integer(length), '0') if lowercase: ret = ret.lower() return prefix + ret def convert_to_number(self, item, precision=None): """Converts the given item to a floating point number. If the optional `precision` is positive or zero, the returned number is rounded to that number of decimal digits. Negative precision means that the number is rounded to the closest multiple of 10 to the power of the absolute precision. The support for precision was added in Robot Framework 2.6. Examples: | ${result} = | Convert To Number | 42.512 | | # Result is 42.512 | | ${result} = | Convert To Number | 42.512 | 1 | # Result is 42.5 | | ${result} = | Convert To Number | 42.512 | 0 | # Result is 43.0 | | ${result} = | Convert To Number | 42.512 | -1 | # Result is 40.0 | Notice that machines generally cannot store floating point numbers accurately. This may cause surprises with these numbers in general and also when they are rounded. For more information see, for example, this floating point arithmetic tutorial: http://docs.python.org/tutorial/floatingpoint.html If you need an integer number, use `Convert To Integer` instead. """ self._log_types(item) return self._convert_to_number(item, precision) def _convert_to_number(self, item, precision=None): number = self._convert_to_number_without_precision(item) if precision: number = round(number, self._convert_to_integer(precision)) return number def _convert_to_number_without_precision(self, item): try: if utils.is_jython: item = self._handle_java_numbers(item) return float(item) except: error = utils.get_error_message() try: return float(self._convert_to_integer(item)) except RuntimeError: raise RuntimeError("'%s' cannot be converted to a floating " "point number: %s" % (item, error)) def convert_to_string(self, item): """Converts the given item to a Unicode string. Uses '__unicode__' or '__str__' method with Python objects and 'toString' with Java objects. """ self._log_types(item) return self._convert_to_string(item) def _convert_to_string(self, item): return utils.unic(item) def convert_to_boolean(self, item): """Converts the given item to Boolean true or false. Handles strings 'True' and 'False' (case-insensitive) as expected, otherwise returns item's truth value using Python's 'bool' method. For more information about truth values, see http://docs.python.org/lib/truth.html. """ self._log_types(item) if isinstance(item, basestring): if utils.eq(item, 'True'): return True if utils.eq(item, 'False'): return False return bool(item) def create_list(self, *items): """Returns a list containing given items. The returned list can be assigned both to ${scalar} and @{list} variables. The earlier can be used e.g. with Java keywords expecting an array as an argument. Examples: | @{list} = | Create List | a | b | c | | ${scalar} = | Create List | a | b | c | | ${ints} = | Create List | ${1} | ${2} | ${3} | """ return list(items) class _Verify: def fail(self, msg=None): """Fails the test immediately with the given (optional) message. See `Fatal Error` if you need to stop the whole test execution. """ raise AssertionError(msg) if msg else AssertionError() def fatal_error(self, msg=None): """Stops the whole test execution. The test or suite where this keyword is used fails with the provided message, and subsequent tests fail with a canned message. Possible teardowns will nevertheless be executed. See `Fail` if you only want to stop one test case unconditionally. """ error = AssertionError(msg) if msg else AssertionError() error.ROBOT_EXIT_ON_FAILURE = True raise error def exit_for_loop(self): """Immediately stops executing the enclosing for loop. This keyword can be used directly in a for loop or in a keyword that the for loop uses. In both cases the test execution continues after the for loop. If executed outside of a for loop, the test fails. Example: | :FOR | ${var} | IN | @{SOME LIST} | | | Run Keyword If | '${var}' == 'EXIT' | Exit For Loop | | | Do Something | ${var} | New in Robot Framework 2.5.2. """ # Error message is shown only if there is no enclosing for loop error = AssertionError('Exit for loop without enclosing for loop.') error.ROBOT_EXIT_FOR_LOOP = True raise error def should_not_be_true(self, condition, msg=None): """Fails if the given condition is true. See `Should Be True` for details about how `condition` is evaluated and how `msg` can be used to override the default error message. """ if not msg: msg = "'%s' should not be true" % condition asserts.fail_if(self._is_true(condition), msg) def should_be_true(self, condition, msg=None): """Fails if the given condition is not true. If `condition` is a string (e.g. '${rc} < 10'), it is evaluated as a Python expression using the built-in 'eval' function and the keyword status is decided based on the result. If a non-string item is given, the status is got directly from its truth value as explained at http://docs.python.org/lib/truth.html. The default error message ('<condition> should be true') is not very informative, but it can be overridden with the `msg` argument. Examples: | Should Be True | ${rc} < 10 | | Should Be True | '${status}' == 'PASS' | # Strings must be quoted | | Should Be True | ${number} | # Passes if ${number} is not zero | | Should Be True | ${list} | # Passes if ${list} is not empty | """ if not msg: msg = "'%s' should be true" % condition asserts.fail_unless(self._is_true(condition), msg) def should_be_equal(self, first, second, msg=None, values=True): """Fails if the given objects are unequal. - If `msg` is not given, the error message is 'first != second'. - If `msg` is given and `values` is either Boolean False or the string 'False' or 'No Values', the error message is simply `msg`. - Otherwise the error message is '`msg`: `first` != `second`'. """ self._log_types(first, second) self._should_be_equal(first, second, msg, values) def _should_be_equal(self, first, second, msg, values): asserts.fail_unless_equal(first, second, msg, self._include_values(values)) def _log_types(self, *args): msg = ["Argument types are:"] + [str(type(a)) for a in args] self.log('\n'.join(msg)) def _include_values(self, values): if isinstance(values, basestring): return values.lower() not in ['no values', 'false'] return bool(values) def should_not_be_equal(self, first, second, msg=None, values=True): """Fails if the given objects are equal. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) self._should_not_be_equal(first, second, msg, values) def _should_not_be_equal(self, first, second, msg, values): asserts.fail_if_equal(first, second, msg, self._include_values(values)) def should_not_be_equal_as_integers(self, first, second, msg=None, values=True, base=None): """Fails if objects are equal after converting them to integers. See `Convert To Integer` for information how to convert integers from other bases than 10 using `base` argument or `0b/0o/0x` prefixes. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. See `Should Be Equal As Integers` for some usage examples. """ self._log_types(first, second) self._should_not_be_equal(self._convert_to_integer(first, base), self._convert_to_integer(second, base), msg, values) def should_be_equal_as_integers(self, first, second, msg=None, values=True, base=None): """Fails if objects are unequal after converting them to integers. See `Convert To Integer` for information how to convert integers from other bases than 10 using `base` argument or `0b/0o/0x` prefixes. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. Examples: | Should Be Equal As Integers | 42 | ${42} | Error message | | Should Be Equal As Integers | ABCD | abcd | base=16 | | Should Be Equal As Integers | 0b1011 | 11 | """ self._log_types(first, second) self._should_be_equal(self._convert_to_integer(first, base), self._convert_to_integer(second, base), msg, values) def should_not_be_equal_as_numbers(self, first, second, msg=None, values=True, precision=6): """Fails if objects are equal after converting them to real numbers. The conversion is done with `Convert To Number` keyword using the given `precision`. The support for giving precision was added in Robot Framework 2.6, in earlier versions it was hard-coded to 6. See `Should Be Equal As Numbers` for examples on how to use `precision` and why it does not always work as expected. See also `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) first = self._convert_to_number(first, precision) second = self._convert_to_number(second, precision) self._should_not_be_equal(first, second, msg, values) def should_be_equal_as_numbers(self, first, second, msg=None, values=True, precision=6): """Fails if objects are unequal after converting them to real numbers. The conversion is done with `Convert To Number` keyword using the given `precision`. The support for giving precision was added in Robot Framework 2.6, in earlier versions it was hard-coded to 6. Examples: | Should Be Equal As Numbers | ${x} | 1.1 | | # Passes if ${x} is 1.1 | | Should Be Equal As Numbers | 1.123 | 1.1 | precision=1 | # Passes | | Should Be Equal As Numbers | 1.123 | 1.4 | precision=0 | # Passes | | Should Be Equal As Numbers | 112.3 | 75 | precision=-2 | # Passes | As discussed in the documentation of `Convert To Number`, machines generally cannot store floating point numbers accurately. Because of this limitation, comparing floats for equality is problematic and a correct approach to use depends on the context. This keyword uses a very naive approach of rounding the numbers before comparing them, which is both prone to rounding errors and does not work very well if numbers are really big or small. For more information about comparing floats, and ideas on how to implement your own context specific comparison algorithm, see this great article: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm See `Should Not Be Equal As Numbers` for a negative version of this keyword and `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) first = self._convert_to_number(first, precision) second = self._convert_to_number(second, precision) self._should_be_equal(first, second, msg, values) def should_not_be_equal_as_strings(self, first, second, msg=None, values=True): """Fails if objects are equal after converting them to strings. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) first, second = [self._convert_to_string(i) for i in first, second] self._should_not_be_equal(first, second, msg, values) def should_be_equal_as_strings(self, first, second, msg=None, values=True): """Fails if objects are unequal after converting them to strings. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ self._log_types(first, second) first, second = [self._convert_to_string(i) for i in first, second] self._should_be_equal(first, second, msg, values) def should_not_start_with(self, str1, str2, msg=None, values=True): """Fails if the string `str1` starts with the string `str2`. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(str1, str2, msg, values, 'starts with') asserts.fail_if(str1.startswith(str2), msg) def should_start_with(self, str1, str2, msg=None, values=True): """Fails if the string `str1` does not start with the string `str2`. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(str1, str2, msg, values, 'does not start with') asserts.fail_unless(str1.startswith(str2), msg) def should_not_end_with(self, str1, str2, msg=None, values=True): """Fails if the string `str1` ends with the string `str2`. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(str1, str2, msg, values, 'ends with') asserts.fail_if(str1.endswith(str2), msg) def should_end_with(self, str1, str2, msg=None, values=True): """Fails if the string `str1` does not end with the string `str2`. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(str1, str2, msg, values, 'does not end with') asserts.fail_unless(str1.endswith(str2), msg) def should_not_contain(self, item1, item2, msg=None, values=True): """Fails if `item1` contains `item2` one or more times. Works with strings, lists, and anything that supports Python's 'in' keyword. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. Examples: | Should Not Contain | ${output} | FAILED | | Should Not Contain | ${some_list} | value | """ msg = self._get_string_msg(item1, item2, msg, values, 'contains') asserts.fail_if(item2 in item1, msg) def should_contain(self, item1, item2, msg=None, values=True): """Fails if `item1` does not contain `item2` one or more times. Works with strings, lists, and anything that supports Python's 'in' keyword. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. Examples: | Should Contain | ${output} | PASS | | Should Contain | ${some_list} | value | """ msg = self._get_string_msg(item1, item2, msg, values, 'does not contain') asserts.fail_unless(item2 in item1, msg) def should_contain_x_times(self, item1, item2, count, msg=None): """Fails if `item1` does not contain `item2` `count` times. Works with strings, lists and all objects that `Get Count` works with. The default error message can be overridden with `msg` and the actual count is always logged. Examples: | Should Contain X Times | ${output} | hello | 2 | | Should Contain X Times | ${some list} | value | 3 | """ if not msg: msg = "'%s' does not contain '%s' %s times" % (item1, item2, count) self.should_be_equal_as_integers(self.get_count(item1, item2), count, msg, values=False) def get_count(self, item1, item2): """Returns and logs how many times `item2` is found from `item1`. This keyword works with Python strings and lists and all objects that either have 'count' method or can be converted to Python lists. Example: | ${count} = | Get Count | ${some item} | interesting value | | Should Be True | 5 < ${count} < 10 | """ if not hasattr(item1, 'count'): try: item1 = list(item1) except: raise RuntimeError("Converting '%s' to list failed: %s" % (item1, utils.get_error_message())) count = item1.count(item2) self.log('Item found from the first item %d time%s' % (count, utils.plural_or_not(count))) return count def should_not_match(self, string, pattern, msg=None, values=True): """Fails if the given `string` matches the given `pattern`. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern '*' matches to anything and '?' matches to any single character. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(string, pattern, msg, values, 'matches') asserts.fail_if(self._matches(string, pattern), msg) def should_match(self, string, pattern, msg=None, values=True): """Fails unless the given `string` matches the given `pattern`. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern, '*' matches to anything and '?' matches to any single character. See `Should Be Equal` for an explanation on how to override the default error message with `msg` and `values`. """ msg = self._get_string_msg(string, pattern, msg, values, 'does not match') asserts.fail_unless(self._matches(string, pattern), msg) def should_match_regexp(self, string, pattern, msg=None, values=True): """Fails if `string` does not match `pattern` as a regular expression. Regular expression check is done using the Python 're' module, which has a pattern syntax derived from Perl, and thus also very similar to the one in Java. See the following documents for more details about regular expressions in general and Python implementation in particular. * http://docs.python.org/lib/module-re.html * http://www.amk.ca/python/howto/regex/ Things to note about the regexp syntax in Robot Framework test data: 1) Backslash is an escape character in the test data, and possible backslashes in the pattern must thus be escaped with another backslash (e.g. '\\\\d\\\\w+'). 2) Strings that may contain special characters, but should be handled as literal strings, can be escaped with the `Regexp Escape` keyword. 3) The given pattern does not need to match the whole string. For example, the pattern 'ello' matches the string 'Hello world!'. If a full match is needed, the '^' and '$' characters can be used to denote the beginning and end of the string, respectively. For example, '^ello$' only matches the exact string 'ello'. 4) Possible flags altering how the expression is parsed (e.g. re.IGNORECASE, re.MULTILINE) can be set by prefixing the pattern with the '(?iLmsux)' group (e.g. '(?im)pattern'). The available flags are 'IGNORECASE': 'i', 'MULTILINE': 'm', 'DOTALL': 's', 'VERBOSE': 'x', 'UNICODE': 'u', and 'LOCALE': 'L'. If this keyword passes, it returns the portion of the string that matched the pattern. Additionally, the possible captured groups are returned. See the `Should Be Equal` keyword for an explanation on how to override the default error message with the `msg` and `values` arguments. Examples: | Should Match Regexp | ${output} | \\\\d{6} | # Output contains six numbers | | Should Match Regexp | ${output} | ^\\\\d{6}$ | # Six numbers and nothing more | | ${ret} = | Should Match Regexp | Foo: 42 | (?i)foo: \\\\d+ | | ${match} | ${group1} | ${group2} = | | ... | Should Match Regexp | Bar: 43 | (Foo|Bar): (\\\\d+) | => - ${ret} = 'Foo: 42' - ${match} = 'Bar: 43' - ${group1} = 'Bar' - ${group2} = '43' """ msg = self._get_string_msg(string, pattern, msg, values, 'does not match') res = re.search(pattern, string) asserts.fail_if_none(res, msg, False) match = res.group(0) groups = res.groups() if groups: return [match] + list(groups) return match def should_not_match_regexp(self, string, pattern, msg=None, values=True): """Fails if `string` matches `pattern` as a regular expression. See `Should Match Regexp` for more information about arguments. """ msg = self._get_string_msg(string, pattern, msg, values, 'matches') asserts.fail_unless_none(re.search(pattern, string), msg, False) def get_length(self, item): """Returns and logs the length of the given item. The item can be anything that has a length, for example, a string, a list, or a mapping. The keyword first tries to get the length with the Python function `len`, which calls the item's `__len__` method internally. If that fails, the keyword tries to call the item's possible `length` and `size` methods directly. The final attempt is trying to get the value of the item's `length` attribute. If all these attempts are unsuccessful, the keyword fails. It is possible to use this keyword also with list variables (e.g. `@{LIST}`), but you need to use them as scalars (e.g. `${LIST}`). """ length = self._get_length(item) self.log('Length is %d' % length) return length def _get_length(self, item): try: return len(item) except utils.RERAISED_EXCEPTIONS: raise except: try: return item.length() except utils.RERAISED_EXCEPTIONS: raise except: try: return item.size() except utils.RERAISED_EXCEPTIONS: raise except: try: return item.length except utils.RERAISED_EXCEPTIONS: raise except: raise RuntimeError("Could not get length of '%s'" % item) def length_should_be(self, item, length, msg=None): """Verifies that the length of the given item is correct. The length of the item is got using the `Get Length` keyword. The default error message can be overridden with the `msg` argument. """ length = self._convert_to_integer(length) if self.get_length(item) != length: if not msg: msg = "Length of '%s' should be %d but it is %d" \ % (item, length, self.get_length(item)) raise AssertionError(msg) def should_be_empty(self, item, msg=None): """Verifies that the given item is empty. The length of the item is got using the `Get Length` keyword. The default error message can be overridden with the `msg` argument. """ if self.get_length(item) > 0: raise AssertionError(msg or "'%s' should be empty" % item) def should_not_be_empty(self, item, msg=None): """Verifies that the given item is not empty. The length of the item is got using the `Get Length` keyword. The default error message can be overridden with the `msg` argument. """ if self.get_length(item) == 0: raise AssertionError(msg or "'%s' should not be empty" % item) def _get_string_msg(self, str1, str2, msg, values, delim): default = "'%s' %s '%s'" % (str1, delim, str2) if not msg: msg = default elif values is True: msg = '%s: %s' % (msg, default) return msg class _Variables: def get_variables(self): """Returns a dictionary containing all variables in the current scope.""" return self._namespace.variables def get_variable_value(self, name, default=None): """Returns variable value or `default` if the variable does not exist. The name of the variable can be given either as a normal variable name (e.g. `${NAME}`) or in escaped format (e.g. `\\${NAME}`). Notice that the former has some limitations explained in `Set Suite Variable`. Examples: | ${x} = | Get Variable Value | ${a} | default | | ${y} = | Get Variable Value | ${a} | ${b} | | ${z} = | Get Variable Value | ${z} | | => - ${x} gets value of ${a} if ${a} exists and string "default" otherwise - ${y} gets value of ${a} if ${a} exists and value of ${b} otherwise - ${z} is set to Python `None` if it does not exist previously This keyword was added in Robot Framework 2.6. See `Set Variable If` for another keyword to set variables dynamically. """ name = self._get_var_name(name) variables = self.get_variables() try: return variables[name] except DataError: return variables.replace_scalar(default) def log_variables(self, level='INFO'): """Logs all variables in the current scope with given log level.""" variables = self.get_variables() for name in sorted(variables.keys(), key=lambda s: s.lower()): msg = utils.format_assign_message(name, variables[name], cut_long=False) self.log(msg, level) def variable_should_exist(self, name, msg=None): """Fails unless the given variable exists within the current scope. The name of the variable can be given either as a normal variable name (e.g. `${NAME}`) or in escaped format (e.g. `\\${NAME}`). Notice that the former has some limitations explained in `Set Suite Variable`. The default error message can be overridden with the `msg` argument. """ name = self._get_var_name(name) variables = self.get_variables() msg = variables.replace_string(msg) if msg \ else "Variable %s does not exist" % name asserts.fail_unless(variables.has_key(name), msg) def variable_should_not_exist(self, name, msg=None): """Fails if the given variable exists within the current scope. The name of the variable can be given either as a normal variable name (e.g. `${NAME}`) or in escaped format (e.g. `\\${NAME}`). Notice that the former has some limitations explained in `Set Suite Variable`. The default error message can be overridden with the `msg` argument. """ name = self._get_var_name(name) variables = self.get_variables() msg = variables.replace_string(msg) if msg \ else "Variable %s exists" % name asserts.fail_if(variables.has_key(name), msg) def replace_variables(self, text): """Replaces variables in the given text with their current values. If the text contains undefined variables, this keyword fails. Example: The file 'template.txt' contains 'Hello ${NAME}!' and variable '${NAME}' has the value 'Robot'. | ${template} = | Get File | ${CURDIR}/template.txt | | ${message} = | Replace Variables | ${template} | | Should Be Equal | ${message} | Hello Robot! | If the given `text` contains only a single variable, its value is returned as-is and it can be any object. Otherwise this keyword always returns a string. """ return self.get_variables().replace_scalar(text) def set_variable(self, *values): """Returns the given values which can then be assigned to a variables. This keyword is mainly used for setting scalar variables. Additionally it can be used for converting a scalar variable containing a list to a list variable or to multiple scalar variables. It is recommended to use `Create List' when creating new lists. Examples: | ${hi} = | Set Variable | Hello, world! | | ${hi2} = | Set Variable | I said: ${hi} | | ${var1} | ${var2} = | Set Variable | Hello | world | | @{list} = | Set Variable | ${list with some items} | | ${item1} | ${item2} = | Set Variable | ${list with 2 items} | Variables created with this keyword are available only in the scope where they are created. See `Set Global Variable`, `Set Test Variable` and `Set Suite Variable` for information on how to set variables so that they are available also in a larger scope. """ if len(values) == 0: return '' elif len(values) == 1: return values[0] else: return list(values) def set_test_variable(self, name, *values): """Makes a variable available everywhere within the scope of the current test. Variables set with this keyword are available everywhere within the scope of the currently executed test case. For example, if you set a variable in a user keyword, it is available both in the test case level and also in all other user keywords used in the current test. Other test cases will not see variables set with this keyword. See `Set Suite Variable` for more information and examples. """ name = self._get_var_name(name) value = self._get_var_value(name, values) self.get_variables().set_test(name, value) self._log_set_variable(name, value) def set_suite_variable(self, name, *values): """Makes a variable available everywhere within the scope of the current suite. Variables set with this keyword are available everywhere within the scope of the currently executed test suite. Setting variables with this keyword thus has the same effect as creating them using the Variable table in the test data file or importing them from variable files. Other test suites, including possible child test suites, will not see variables set with this keyword. The name of the variable can be given either as a normal variable name (e.g. `${NAME}`) or in escaped format as `\\${NAME}` or `$NAME`. If a variable already exists within the new scope, its value will be overwritten. Otherwise a new variable is created. If a variable already exists within the current scope, the value can be left empty and the variable within the new scope gets the value within the current scope. Examples: | Set Suite Variable | ${GREET} | Hello, world! | | ${ID} = | Get ID | | Set Suite Variable | ${ID} | *NOTE:* If the variable has value which itself is a variable (escaped or not), you must always use the escaped format to reset the variable: Example: | ${NAME} = | Set Variable | \${var} | | Set Suite Variable | ${NAME} | value | # Sets variable ${var} | | Set Suite Variable | \${NAME} | value | # Sets variable ${NAME} | This limitation applies also to `Set Test/Suite/Global Variable`, `Variable Should (Not) Exist`, and `Get Variable Value` keywords. """ name = self._get_var_name(name) value = self._get_var_value(name, values) self.get_variables().set_suite(name, value) self._log_set_variable(name, value) def set_global_variable(self, name, *values): """Makes a variable available globally in all tests and suites. Variables set with this keyword are globally available in all test cases and suites executed after setting them. Setting variables with this keyword thus has the same effect as creating from the command line using the options '--variable' or '--variablefile'. Because this keyword can change variables everywhere, it should be used with care. See `Set Suite Variable` for more information and examples. """ name = self._get_var_name(name) value = self._get_var_value(name, values) self.get_variables().set_global(name, value) self._log_set_variable(name, value) # Helpers def _get_var_name(self, orig): name = self._resolve_possible_variable(orig) try: return self._unescape_variable_if_needed(name) except ValueError: raise RuntimeError("Invalid variable syntax '%s'" % orig) def _resolve_possible_variable(self, name): try: resolved = self.get_variables()[name] return self._unescape_variable_if_needed(resolved) except (KeyError, ValueError, DataError): return name def _unescape_variable_if_needed(self, name): if not (isinstance(name, basestring) and len(name) > 1): raise ValueError if name.startswith('\\'): name = name[1:] elif name[0] in ['$','@'] and name[1] != '{': name = '%s{%s}' % (name[0], name[1:]) if is_var(name): return name # Support for possible internal variables (issue 397) name = '%s{%s}' % (name[0], self.replace_variables(name[2:-1])) if is_var(name): return name raise ValueError def _get_var_value(self, name, values): variables = self.get_variables() if not values: return variables[name] values = variables.replace_list(values) if len(values) == 1 and name[0] == '$': return values[0] return list(values) def _log_set_variable(self, name, value): self.log(utils.format_assign_message(name, value)) class _RunKeyword: # If you use any of these run keyword variants from another library, you # should register those keywords with 'register_run_keyword' method. See # the documentation of that method at the end of this file. There are also # other run keyword variant keywords in BuiltIn which can also be seen # at the end of this file. def run_keyword(self, name, *args): """Executes the given keyword with the given arguments. Because the name of the keyword to execute is given as an argument, it can be a variable and thus set dynamically, e.g. from a return value of another keyword or from the command line. """ if not isinstance(name, basestring): raise RuntimeError('Keyword name must be a string') kw = Keyword(name, list(args)) return kw.run(ExecutionContext(self._namespace, self._output)) def run_keywords(self, *names): """Executes all the given keywords in a sequence without arguments. This keyword is mainly useful in setups and teardowns when they need to take care of multiple actions and creating a new higher level user keyword is overkill. User keywords must nevertheless be used if the executed keywords need to take arguments. Example: | *Setting* | *Value* | *Value* | *Value* | | Suite Setup | Run Keywords | Initialize database | Start servers | """ errors = [] for kw in self.get_variables().replace_list(names): try: self.run_keyword(kw) except ExecutionFailed, err: errors.extend(err.get_errors()) context = ExecutionContext(self._namespace, self._output) if not err.can_continue(context.teardown): break if errors: raise ExecutionFailures(errors) def run_keyword_if(self, condition, name, *args): """Runs the given keyword with the given arguments, if `condition` is true. The given `condition` is evaluated similarly as with `Should Be True` keyword, and `name` and `*args` have same semantics as with `Run Keyword`. Example, a simple if/else construct: | ${status} | ${value} = | Run Keyword And Ignore Error | My Keyword | | Run Keyword If | '${status}' == 'PASS' | Some Action | | Run Keyword Unless | '${status}' == 'PASS' | Another Action | In this example, only either 'Some Action' or 'Another Action' is executed, based on the status of 'My Keyword'. """ if self._is_true(condition): return self.run_keyword(name, *args) def run_keyword_unless(self, condition, name, *args): """Runs the given keyword with the given arguments, if `condition` is false. See `Run Keyword If` for more information and an example. """ if not self._is_true(condition): return self.run_keyword(name, *args) def run_keyword_and_ignore_error(self, name, *args): """Runs the given keyword with the given arguments and ignores possible error. This keyword returns two values, so that the first is either 'PASS' or 'FAIL', depending on the status of the executed keyword. The second value is either the return value of the keyword or the received error message. The keyword name and arguments work as in `Run Keyword`. See `Run Keyword If` for a usage example. Starting from Robot Framework 2.5 errors caused by invalid syntax, timeouts, or fatal exceptions are not caught by this keyword. """ try: return 'PASS', self.run_keyword(name, *args) except ExecutionFailed, err: if err.dont_cont: raise return 'FAIL', unicode(err) def run_keyword_and_continue_on_failure(self, name, *args): """Runs the keyword and continues execution even if a failure occurs. The keyword name and arguments work as with `Run Keyword`. Example: | Run Keyword And Continue On Failure | Fail | This is a stupid example | | Log | This keyword is executed | This keyword was added in Robot Framework 2.5. The execution is not continued if the failure is caused by invalid syntax, timeout, or fatal exception. """ try: return self.run_keyword(name, *args) except ExecutionFailed, err: if not err.dont_cont: err.cont = True raise err def run_keyword_and_expect_error(self, expected_error, name, *args): """Runs the keyword and checks that the expected error occurred. The expected error must be given in the same format as in Robot Framework reports. It can be a pattern containing characters '?', which matches to any single character and '*', which matches to any number of any characters. `name` and `*args` have same semantics as with `Run Keyword`. If the expected error occurs, the error message is returned and it can be further processed/tested, if needed. If there is no error, or the error does not match the expected error, this keyword fails. Examples: | Run Keyword And Expect Error | My error | Some Keyword | arg1 | arg2 | | ${msg} = | Run Keyword And Expect Error | * | My KW | | Should Start With | ${msg} | Once upon a time in | Starting from Robot Framework 2.5 errors caused by invalid syntax, timeouts, or fatal exceptions are not caught by this keyword. """ try: self.run_keyword(name, *args) except ExecutionFailed, err: if err.dont_cont: raise else: raise AssertionError("Expected error '%s' did not occur" % expected_error) if not self._matches(unicode(err), expected_error): raise AssertionError("Expected error '%s' but got '%s'" % (expected_error, err)) return unicode(err) def repeat_keyword(self, times, name, *args): """Executes the specified keyword multiple times. `name` and `args` define the keyword that is executed similarly as with `Run Keyword`, and `times` specifies how many the keyword should be executed. `times` can be given as an integer or as a string that can be converted to an integer. It can also have postfix 'times' or 'x' (case and space insensitive) to make the expression easier to read. If `times` is zero or negative, the keyword is not executed at all. This keyword fails immediately if any of the execution rounds fails. Examples: | Repeat Keyword | 5 times | Goto Previous Page | | Repeat Keyword | ${var} | Some Keyword | arg1 | arg2 | """ times = utils.normalize(str(times)) if times.endswith('times'): times = times[:-5] elif times.endswith('x'): times = times[:-1] times = self._convert_to_integer(times) if times <= 0: self.log("Keyword '%s' repeated zero times" % name) for i in xrange(times): self.log("Repeating keyword, round %d/%d" % (i+1, times)) self.run_keyword(name, *args) def wait_until_keyword_succeeds(self, timeout, retry_interval, name, *args): """Waits until the specified keyword succeeds or the given timeout expires. `name` and `args` define the keyword that is executed similarly as with `Run Keyword`. If the specified keyword does not succeed within `timeout`, this keyword fails. `retry_interval` is the time to wait before trying to run the keyword again after the previous run has failed. Both `timeout` and `retry_interval` must be given in Robot Framework's time format (e.g. '1 minute', '2 min 3 s', '4.5'). Example: | Wait Until Keyword Succeeds | 2 min | 5 sec | My keyword | arg1 | arg2 | Starting from Robot Framework 2.5 errors caused by invalid syntax, timeouts, or fatal exceptions are not caught by this keyword. """ timeout = utils.timestr_to_secs(timeout) retry_interval = utils.timestr_to_secs(retry_interval) maxtime = time.time() + timeout error = None while not error: try: return self.run_keyword(name, *args) except ExecutionFailed, err: if err.dont_cont: raise if time.time() > maxtime: error = unicode(err) else: time.sleep(retry_interval) raise AssertionError("Timeout %s exceeded. The last error was: %s" % (utils.secs_to_timestr(timeout), error)) def set_variable_if(self, condition, *values): """Sets variable based on the given condition. The basic usage is giving a condition and two values. The given condition is first evaluated the same way as with the `Should Be True` keyword. If the condition is true, then the first value is returned, and otherwise the second value is returned. The second value can also be omitted, in which case it has a default value None. This usage is illustrated in the examples below, where ${rc} is assumed to be zero. | ${var1} = | Set Variable If | ${rc} == 0 | zero | nonzero | | ${var2} = | Set Variable If | ${rc} > 0 | value1 | value2 | | ${var3} = | Set Variable If | ${rc} > 0 | whatever | | => - ${var1} = 'zero' - ${var2} = 'value2' - ${var3} = None It is also possible to have 'Else If' support by replacing the second value with another condition, and having two new values after it. If the first condition is not true, the second is evaluated and one of the values after it is returned based on its truth value. This can be continued by adding more conditions without a limit. | ${var} = | Set Variable If | ${rc} == 0 | zero | | ... | ${rc} > 0 | greater than zero | less then zero | | | | ${var} = | Set Variable If | | ... | ${rc} == 0 | zero | | ... | ${rc} == 1 | one | | ... | ${rc} == 2 | two | | ... | ${rc} > 2 | greater than two | | ... | ${rc} < 0 | less than zero | Use `Get Variable Value` if you need to set variables dynamically based on whether a variable exist or not. """ values = self._verify_values_for_set_variable_if(list(values)) if self._is_true(condition): return self._namespace.variables.replace_scalar(values[0]) values = self._verify_values_for_set_variable_if(values[1:], True) if len(values) == 1: return self._namespace.variables.replace_scalar(values[0]) return self.run_keyword('BuiltIn.Set Variable If', *values[0:]) def _verify_values_for_set_variable_if(self, values, default=False): if not values: if default: return [None] raise RuntimeError('At least one value is required') if is_list_var(values[0]): values[:1] = [utils.escape(item) for item in self._namespace.variables[values[0]]] return self._verify_values_for_set_variable_if(values) return values def run_keyword_if_test_failed(self, name, *args): """Runs the given keyword with the given arguments, if the test failed. This keyword can only be used in a test teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ test = self._get_test_in_teardown('Run Keyword If Test Failed') if test.status == 'FAIL': return self.run_keyword(name, *args) def run_keyword_if_test_passed(self, name, *args): """Runs the given keyword with the given arguments, if the test passed. This keyword can only be used in a test teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ test = self._get_test_in_teardown('Run Keyword If Test Passed') if test.status == 'PASS': return self.run_keyword(name, *args) def run_keyword_if_timeout_occurred(self, name, *args): """Runs the given keyword if either a test or a keyword timeout has occurred. This keyword can only be used in a test teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. Available in Robot Framework 2.5 and newer. """ test = self._get_test_in_teardown('Run Keyword If Timeout Occurred') if test.timeout.any_timeout_occurred(): return self.run_keyword(name, *args) def _get_test_in_teardown(self, kwname): test = self._namespace.test if test and test.status != 'RUNNING': return test raise RuntimeError("Keyword '%s' can only be used in test teardown" % kwname) def run_keyword_if_all_critical_tests_passed(self, name, *args): """Runs the given keyword with the given arguments, if all critical tests passed. This keyword can only be used in suite teardown. Trying to use it in any other place will result in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ suite = self._get_suite_in_teardown('Run Keyword If ' 'All Critical Tests Passed') if suite.critical_stats.failed == 0: return self.run_keyword(name, *args) def run_keyword_if_any_critical_tests_failed(self, name, *args): """Runs the given keyword with the given arguments, if any critical tests failed. This keyword can only be used in a suite teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ suite = self._get_suite_in_teardown('Run Keyword If ' 'Any Critical Tests Failed') if suite.critical_stats.failed > 0: return self.run_keyword(name, *args) def run_keyword_if_all_tests_passed(self, name, *args): """Runs the given keyword with the given arguments, if all tests passed. This keyword can only be used in a suite teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ suite = self._get_suite_in_teardown('Run Keyword If All Tests Passed') if suite.all_stats.failed == 0: return self.run_keyword(name, *args) def run_keyword_if_any_tests_failed(self, name, *args): """Runs the given keyword with the given arguments, if one or more tests failed. This keyword can only be used in a suite teardown. Trying to use it anywhere else results in an error. Otherwise, this keyword works exactly like `Run Keyword`, see its documentation for more details. """ suite = self._get_suite_in_teardown('Run Keyword If Any Tests Failed') if suite.all_stats.failed > 0: return self.run_keyword(name, *args) def _get_suite_in_teardown(self, kwname): if self._namespace.suite.status == 'RUNNING': raise RuntimeError("Keyword '%s' can only be used in suite teardown" % kwname) return self._namespace.suite class _Misc: def no_operation(self): """Does absolutely nothing.""" def sleep(self, time_, reason=None): """Pauses the test executed for the given time. `time` may be either a number or a time string. Time strings are in a format such as '1 day 2 hours 3 minutes 4 seconds 5milliseconds' or '1d 2h 3m 4s 5ms', and they are fully explained in an appendix of Robot Framework User Guide. Optional `reason` can be used to explain why sleeping is necessary. Both the time slept and the reason are logged. Examples: | Sleep | 42 | | Sleep | 1.5 | | Sleep | 2 minutes 10 seconds | | Sleep | 10s | Wait for a reply | """ seconds = utils.timestr_to_secs(time_) # Python hangs with negative values if seconds < 0: seconds = 0 time.sleep(seconds) self.log('Slept %s' % utils.secs_to_timestr(seconds)) if reason: self.log(reason) def catenate(self, *items): """Catenates the given items together and returns the resulted string. By default, items are catenated with spaces, but if the first item contains the string 'SEPARATOR=<sep>', the separator '<sep>' is used. Items are converted into strings when necessary. Examples: | ${str1} = | Catenate | Hello | world | | | ${str2} = | Catenate | SEPARATOR=--- | Hello | world | | ${str3} = | Catenate | SEPARATOR= | Hello | world | => - ${str1} = 'Hello world' - ${str2} = 'Hello---world' - ${str3} = 'Helloworld' """ if not items: return '' items = [utils.unic(item) for item in items] if items[0].startswith('SEPARATOR='): sep = items[0][len('SEPARATOR='):] items = items[1:] else: sep = ' ' return sep.join(items) def log(self, message, level="INFO"): """Logs the given message with the given level. Valid levels are TRACE, DEBUG, INFO (default), HTML and WARN. The HTML level is special because it allows writing messages without HTML code in them being escaped. For example, logging a message '<img src="image.png">' using the HTML level creates an image, but with other levels the message would be that exact string. Notice that invalid HTML can easily corrupt the whole log file so this feature should be used with care. The actual log level used for HTML messages is INFO. Messages logged with the WARN level will be visible also in the console and in the Test Execution Errors section in the log file. """ LOGGER.log_message(Message(message, level)) def log_many(self, *messages): """Logs the given messages as separate entries with the INFO level.""" for msg in messages: self.log(msg) def comment(self, *messages): """Displays the given messages in the log file as keyword arguments. This keyword does nothing with the arguments it receives, but as they are visible in the log, this keyword can be used to display simple messages. Given arguments are ignored so thoroughly that they can even contain non-existing variables. If you are interested about variable values, you can use the `Log` or `Log Many` keywords. """ pass def set_log_level(self, level): """Sets the log threshold to the specified level and returns the old level. Messages below the level will not logged. The default logging level is INFO, but it can be overridden with the command line option '--loglevel'. The available levels: TRACE, DEBUG, INFO (default), WARN and NONE (no logging). """ try: old = self._output.set_log_level(level) except DataError, err: raise RuntimeError(unicode(err)) self.log('Log level changed from %s to %s' % (old, level.upper())) return old def import_library(self, name, *args): """Imports a library with the given name and optional arguments. This functionality allows dynamic importing of libraries while tests are running. That may be necessary, if the library itself is dynamic and not yet available when test data is processed. In a normal case, libraries should be imported using the Library setting in the Setting table. This keyword supports importing libraries both using library names and physical paths. When path are used, they must be given in absolute format. Forward slashes can be used as path separators in all operating systems. It is possible to use arguments as well as to give a custom name with 'WITH NAME' syntax. For more information about importing libraries, see Robot Framework User Guide. Examples: | Import Library | MyLibrary | | Import Library | ${CURDIR}/Library.py | some | args | | Import Library | ${CURDIR}/../libs/Lib.java | arg | WITH NAME | JavaLib | """ try: self._namespace.import_library(name.replace('/', os.sep), list(args)) except DataError, err: raise RuntimeError(unicode(err)) def import_variables(self, path, *args): """Imports a variable file with the given path and optional arguments. Variables imported with this keyword are set into the test suite scope similarly when importing them in the Setting table using the Variables setting. These variables override possible existing variables with the same names and this functionality can thus be used to import new variables, e.g. for each test in a test suite. The given path must be absolute. Forward slashes can be used as path separator regardless the operating system. Examples: | Import Variables | ${CURDIR}/variables.py | | | | Import Variables | ${CURDIR}/../vars/env.py | arg1 | arg2 | New in Robot Framework 2.5.4. """ try: self._namespace.import_variables(path.replace('/', os.sep), list(args), overwrite=True) except DataError, err: raise RuntimeError(unicode(err)) def import_resource(self, path): """Imports a resource file with the given path. Resources imported with this keyword are set into the test suite scope similarly when importing them in the Setting table using the Resource setting. The given path must be absolute. Forward slashes can be used as path separator regardless the operating system. Examples: | Import Resource | ${CURDIR}/resource.txt | | Import Resource | ${CURDIR}/../resources/resource.html | """ try: self._namespace.import_resource(path.replace('/', os.sep)) except DataError, err: raise RuntimeError(unicode(err)) def set_library_search_order(self, *libraries): """Sets the resolution order to use when a name matches multiple keywords. The library search order is used to resolve conflicts when a keyword name in the test data matches multiple keywords. The first library containing the keyword is selected and that keyword implementation used. If keyword is not found from any library, or the library search order is not set, executing the specified keyword fails. When this keyword is used, there is no need to use the long `LibraryName.Keyword Name` notation. For example, instead of having | MyLibrary.Keyword | arg | | MyLibrary.Another Keyword | | MyLibrary.Keyword | xxx | you can have | Set Library Search Order | MyLibrary | | Keyword | arg | | Another Keyword | | Keyword | xxx | The library search order is valid only in the suite where this keyword is used in. The old order is returned and can be used to reset the search order later. """ old_order = self._namespace.library_search_order self._namespace.library_search_order = libraries return old_order def get_time(self, format='timestamp', time_='NOW'): """Returns the given time in the requested format. How time is returned is determined based on the given `format` string as follows. Note that all checks are case-insensitive. 1) If `format` contains the word 'epoch', the time is returned in seconds after the UNIX epoch (Jan 1, 1970 0:00:00). The return value is always an integer. 2) If `format` contains any of the words 'year', 'month', 'day', 'hour', 'min', or 'sec', only the selected parts are returned. The order of the returned parts is always the one in the previous sentence and the order of words in `format` is not significant. The parts are returned as zero-padded strings (e.g. May -> '05'). 3) Otherwise (and by default) the time is returned as a timestamp string in the format '2006-02-24 15:08:31'. By default this keyword returns the current time, but that can be altered using `time` argument as explained below. 1) If `time` is a floating point number, it is interpreted as seconds since the epoch. This documentation is written about 1177654467 seconds after the epoch. 2) If `time` is a valid timestamp, that time will be used. Valid timestamp formats are 'YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss'. 3) If `time` is equal to 'NOW' (case-insensitive), the current time is used. 4) If `time` is in the format 'NOW - 1 day' or 'NOW + 1 hour 30 min', the current time plus/minus the time specified with the time string is used. The time string format is described in an appendix of Robot Framework User Guide. Examples (expecting the current time is 2006-03-29 15:06:21): | ${time} = | Get Time | | | | | ${secs} = | Get Time | epoch | | | | ${year} = | Get Time | return year | | | | ${yyyy} | ${mm} | ${dd} = | Get Time | year,month,day | | @{time} = | Get Time | year month day hour min sec | | | | ${y} | ${s} = | Get Time | seconds and year | | => - ${time} = '2006-03-29 15:06:21' - ${secs} = 1143637581 - ${year} = '2006' - ${yyyy} = '2006', ${mm} = '03', ${dd} = '29' - @{time} = ['2006', '03', '29', '15', '06', '21'] - ${y} = '2006' - ${s} = '21' | ${time} = | Get Time | | 1177654467 | | ${secs} = | Get Time | sec | 2007-04-27 09:14:27 | | ${year} = | Get Time | year | NOW | # The time of execution | | ${day} = | Get Time | day | NOW - 1d | # 1 day subtraced from NOW | | @{time} = | Get Time | hour min sec | NOW + 1h 2min 3s | # 1h 2min 3s added to NOW | => - ${time} = '2007-04-27 09:14:27' - ${secs} = 27 - ${year} = '2006' - ${day} = '28' - @{time} = ['16', '08', '24'] """ return utils.get_time(format, utils.parse_time(time_)) def evaluate(self, expression, modules=None): """Evaluates the given expression in Python and returns the results. `modules` argument can be used to specify a comma separated list of Python modules to be imported and added to the namespace of the evaluated `expression`. Examples (expecting ${result} is 3.14): | ${status} = | Evaluate | 0 < ${result} < 10 | | ${down} = | Evaluate | int(${result}) | | ${up} = | Evaluate | math.ceil(${result}) | math | | ${random} = | Evaluate | random.randint(0, sys.maxint) | random,sys | => - ${status} = True - ${down} = 3 - ${up} = 4.0 - ${random} = <random integer> Notice that instead of creating complicated expressions, it is recommended to move the logic into a test library. """ modules = modules.replace(' ','').split(',') if modules else [] namespace = dict((m, __import__(m)) for m in modules if m != '') try: return eval(expression, namespace) except: raise RuntimeError("Evaluating expression '%s' failed: %s" % (expression, utils.get_error_message())) def call_method(self, object, method_name, *args): """Calls the named method of the given object with the provided arguments. The possible return value from the method is returned and can be assigned to a variable. Keyword fails both if the object does not have a method with the given name or if executing the method raises an exception. Examples: | Call Method | ${hashtable} | put | myname | myvalue | | ${isempty} = | Call Method | ${hashtable} | isEmpty | | | Should Not Be True | ${isempty} | | | | | ${value} = | Call Method | ${hashtable} | get | myname | | Should Be Equal | ${value} | myvalue | | | """ try: method = getattr(object, method_name) except AttributeError: raise RuntimeError("Object '%s' does not have a method '%s'" % (object, method_name)) return method(*args) def regexp_escape(self, *patterns): """Returns each argument string escaped for use as a regular expression. This keyword can be used to escape strings to be used with `Should Match Regexp` and `Should Not Match Regexp` keywords. Escaping is done with Python's re.escape() function. Examples: | ${escaped} = | Regexp Escape | ${original} | | @{strings} = | Regexp Escape | @{strings} | """ if len(patterns) == 0: return '' if len(patterns) == 1: return re.escape(patterns[0]) return [re.escape(p) for p in patterns] def set_test_message(self, message): """Sets message for for the current test. This is overridden by possible failure message, except when this keyword is used in test case teardown. In test case teardown this overrides messages even for failed tests. This keyword can not be used in suite setup or suite teardown. """ test = self._namespace.test if not test: raise RuntimeError("'Set Test Message' keyword cannot be used in " "suite setup or teardown") test.message = message self.log('Set test message to:\n%s' % message) def set_tags(self, *tags): """Adds given `tags` for the current test or all tests in a suite. When this keyword is used inside a test case, that test gets the specified tags and other tests are not affected. If this keyword is used in a suite setup, all test cases in that suite, recursively, gets the given tags. It is a failure to use this keyword in a suite teardown. See `Remove Tags` for another keyword to modify tags at test execution time. """ tags = utils.normalize_tags(tags) handler = lambda test: utils.normalize_tags(test.tags + tags) self._set_or_remove_tags(handler) self.log('Set tag%s %s.' % (utils.plural_or_not(tags), utils.seq2str(tags))) def remove_tags(self, *tags): """Removes given `tags` from the current test or all tests in a suite. Tags can be given exactly or using a pattern where '*' matches anything and '?' matches one character. This keyword can affect either one test case or all test cases in a test suite similarly as `Set Tags` keyword. Example: | Remove Tags | mytag | something-* | ?ython | """ tags = utils.normalize_tags(tags) handler = lambda test: [t for t in test.tags if not utils.matches_any(t, tags)] self._set_or_remove_tags(handler) self.log('Removed tag%s %s.' % (utils.plural_or_not(tags), utils.seq2str(tags))) def _set_or_remove_tags(self, handler, suite=None, test=None): if not (suite or test): ns = self._namespace if ns.test is None: if ns.suite.status != 'RUNNING': raise RuntimeError("'Set Tags' and 'Remove Tags' keywords " "cannot be used in suite teardown.") self._set_or_remove_tags(handler, suite=ns.suite) else: self._set_or_remove_tags(handler, test=ns.test) ns.variables.set_test('@{TEST_TAGS}', ns.test.tags) ns.suite._set_critical_tags(ns.suite.critical) elif suite: for sub in suite.suites: self._set_or_remove_tags(handler, suite=sub) for test in suite.tests: self._set_or_remove_tags(handler, test=test) else: test.tags = handler(test) def get_library_instance(self, name): """Returns the currently active instance of the specified test library. This keyword makes it easy for test libraries to interact with other test libraries that have state. This is illustrated by the Python example below: | from robot.libraries.BuiltIn import BuiltIn | | def title_should_start_with(expected): | seleniumlib = BuiltIn().get_library_instance('SeleniumLibrary') | title = seleniumlib.get_title() | if not title.startswith(expected): | raise AssertionError("Title '%s' did not start with '%s'" | % (title, expected)) It is also possible to use this keyword in the test data and pass the returned library instance to another keyword. If a library is imported with a custom name, the `name` used to get the instance must be that name and not the original library name. """ try: return self._namespace.get_library_instance(name) except DataError, err: raise RuntimeError(unicode(err)) class BuiltIn(_Verify, _Converter, _Variables, _RunKeyword, _Misc): """An always available standard library with often needed keywords. `BuiltIn` is Robot Framework's standard library that provides a set of generic keywords needed often. It is imported automatically and thus always available. The provided keywords can be used, for example, for verifications (e.g. `Should Be Equal`, `Should Contain`), conversions (e.g. `Convert To Integer`) and for various other purposes (e.g. `Log`, `Sleep`, `Run Keyword If`, `Set Global Variable`). """ ROBOT_LIBRARY_SCOPE = 'GLOBAL' ROBOT_LIBRARY_VERSION = get_version() @property def _output(self): # OUTPUT is initially set to None and gets real value only when actual # execution starts. If BuiltIn is used externally before that, OUTPUT # gets None value. For more information see this bug report: # http://code.google.com/p/robotframework/issues/detail?id=654 # TODO: Refactor running so that OUTPUT is available via context from robot.output import OUTPUT return OUTPUT @property def _namespace(self): return NAMESPACES.current def _matches(self, string, pattern): # Must use this instead of fnmatch when string may contain newlines. return utils.matches(string, pattern, caseless=False, spaceless=False) def _is_true(self, condition): if isinstance(condition, basestring): try: condition = eval(condition) except: raise RuntimeError("Evaluating condition '%s' failed: %s" % (condition, utils.get_error_message())) return bool(condition) def register_run_keyword(library, keyword, args_to_process=None): """Registers 'run keyword' so that its arguments can be handled correctly. 1) Why is this method needed Keywords running other keywords internally (normally using `Run Keyword` or some variants of it in BuiltIn) must have the arguments meant to the internally executed keyword handled specially to prevent processing them twice. This is done ONLY for keywords registered using this method. If the register keyword has same name as any keyword from Robot Framework standard libraries, it can be used without getting warnings. Normally there is a warning in such cases unless the keyword is used in long format (e.g. MyLib.Keyword). Starting from Robot Framework 2.5.2, keywords executed by registered run keywords can be tested with dryrun runmode with following limitations: - Registered keyword must have 'name' argument which takes keyword's name or Registered keyword must have '*names' argument which takes keywords' names - Keyword name does not contain variables 2) How to use this method `library` is the name of the library where the registered keyword is implemented. `keyword` can be either a function or method implementing the keyword, or name of the implemented keyword as a string. `args_to_process` is needed when `keyword` is given as a string, and it defines how many of the arguments to the registered keyword must be processed normally. When `keyword` is a method or function, this information is got directly from it so that varargs (those specified with syntax '*args') are not processed but others are. 3) Examples from robot.libraries.BuiltIn import BuiltIn, register_run_keyword def my_run_keyword(name, *args): # do something return BuiltIn().run_keyword(name, *args) # Either one of these works register_run_keyword(__name__, my_run_keyword) register_run_keyword(__name__, 'My Run Keyword', 1) ------------- from robot.libraries.BuiltIn import BuiltIn, register_run_keyword class MyLibrary: def my_run_keyword_if(self, expression, name, *args): # do something return BuiltIn().run_keyword_if(expression, name, *args) # Either one of these works register_run_keyword('MyLibrary', MyLibrary.my_run_keyword_if) register_run_keyword('MyLibrary', 'my_run_keyword_if', 2) """ RUN_KW_REGISTER.register_run_keyword(library, keyword, args_to_process) for name in [attr for attr in dir(_RunKeyword) if not attr.startswith('_')]: register_run_keyword('BuiltIn', getattr(_RunKeyword, name)) for name in ['set_test_variable', 'set_suite_variable', 'set_global_variable', 'variable_should_exist', 'variable_should_not_exist', 'comment', 'get_variable_value']: register_run_keyword('BuiltIn', name, 0) del name, attr
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.output import XmlLogger class OutputWriter(XmlLogger): def __init__(self, path): XmlLogger.__init__(self, path, generator='Rebot') def message(self, msg): self._write_message(msg)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement import os import re import codecs import tempfile import robot from robot.output import LOGGER from robot import utils WEBCONTENT_PATH = os.path.join(os.path.dirname(robot.__file__), 'webcontent') class _Builder(object): def __init__(self, data, settings): self._settings = settings self._data = data self._path = self._parse_file(self._type) def build(self): raise NotImplementedError(self.__class__.__name__) def _parse_file(self, name): value = self._settings[name] return value if value != 'NONE' else None class OutputBuilder(_Builder): _type = 'Output' _temp_file = None def build(self): output_file = self._output_file() self._data.serialize_output(output_file, log=not self._temp_file) return output_file def _output_file(self): if self._path: return self._path handle, output_file = tempfile.mkstemp(suffix='.xml', prefix='rebot-') os.close(handle) self._temp_file = output_file return output_file def finalize(self): if self._temp_file: os.remove(self._temp_file) class XUnitBuilder(_Builder): _type = 'XUnitFile' def build(self): if self._path: self._data.serialize_xunit(self._path) class _HTMLFileBuilder(_Builder): _type = NotImplemented def build(self): if self._path: self._data.set_settings(self._get_settings()) self._build() LOGGER.output_file(self._type, self._path) def _url_from_path(self, source, destination): if not destination: return None return utils.get_link_path(destination, os.path.dirname(source)) def _write_file(self): with codecs.open(self._path, 'w', encoding='UTF-8') as outfile: writer = HTMLFileWriter(outfile, self._data) with open(self._template, 'r') as tmpl: for line in tmpl: writer.line(line) class LogBuilder(_HTMLFileBuilder): _type = 'Log' _template = os.path.join(WEBCONTENT_PATH,'log.html') def _build(self): self._write_file() def _get_settings(self): return { 'title': self._settings['LogTitle'], 'reportURL': self._url_from_path(self._path, self._parse_file('Report')) } class ReportBuilder(_HTMLFileBuilder): _type = 'Report' _template = os.path.join(WEBCONTENT_PATH, 'report.html') def _build(self): self._data.remove_errors() self._data.remove_keywords() self._write_file() def _get_settings(self): return { 'title': self._settings['ReportTitle'], 'background' : self._resolve_background_colors(), 'logURL': self._url_from_path(self._path, self._parse_file('Log')) } def _resolve_background_colors(self): color_str = self._settings['ReportBackground'] if color_str and color_str.count(':') not in [1, 2]: LOGGER.error("Invalid background color '%s'." % color_str) color_str = None if not color_str: color_str = '#99FF66:#FF3333' colors = color_str.split(':', 2) if len(colors) == 2: colors.insert(1, colors[0]) return {'pass': colors[0], 'nonCriticalFail': colors[1], 'fail': colors[2]} class HTMLFileWriter(object): _js_file_matcher = re.compile('src=\"([^\"]+)\"') _css_file_matcher = re.compile('href=\"([^\"]+)\"') _css_media_matcher = re.compile('media=\"([^\"]+)\"') def __init__(self, outfile, output): self._outfile = outfile self._output = output def line(self, line): if self._is_output_js(line): self._write_output_js() elif self._is_js_line(line): self._inline_js_file(line) elif self._is_css_line(line): self._inline_css_file(line) else: self._write(line) def _is_output_js(self, line): return line.startswith('<!-- OUTPUT JS -->') def _is_css_line(self, line): return line.startswith('<link rel') def _is_js_line(self, line): return line.startswith('<script type="text/javascript" src=') def _write_output_js(self): separator = '</script>\n<script type="text/javascript">\n' self._write_tag('script', 'type="text/javascript"', lambda: self._output.write_to(self._outfile, separator)) def _inline_js_file(self, line): self._write_tag('script', 'type="text/javascript"', lambda: self._inline_file(line, self._js_file_matcher)) def _inline_css_file(self, line): attrs = 'type="text/css" media="%s"' % self._parse_css_media_type(line) self._write_tag('style', attrs, lambda: self._inline_file(line, self._css_file_matcher)) def _parse_css_media_type(self, line): return self._css_media_matcher.search(line).group(1) def _inline_file(self, line, filename_matcher): file_name = self._file_name(line, filename_matcher) self._write_file_content(file_name) def _file_name(self, line, filename_regexp): return self._relative_path(filename_regexp.search(line).group(1)) def _relative_path(self, filename): return os.path.join(WEBCONTENT_PATH, filename.replace('/', os.path.sep)) def _write(self, content): self._outfile.write(content) def _write_tag(self, tag_name, attrs, content_writer): self._write('<%s %s>\n' % (tag_name, attrs)) content_writer() self._write('</%s>\n\n' % tag_name) def _write_file_content(self, source): with codecs.open(source, 'r', encoding='UTF-8') as content: for line in content: self._write(line) self._write('\n')
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot import utils class XUnitWriter: """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, output): self._writer = utils.XmlWriter(output) self._root_suite = None self._detail_serializer = _NopSerializer() def close(self): self._writer.close() def start_suite(self, suite): if self._root_suite: return self._root_suite = suite attrs = {'name': suite.name, 'tests': str(suite.get_test_count()), 'errors': '0', 'failures': str(suite.all_stats.failed), 'skip': '0'} self._writer.start('testsuite', attrs) def end_suite(self, suite): if suite is self._root_suite: self._writer.end('testsuite') def start_test(self, test): attrs = {'classname': test.parent.get_long_name(), 'name': test.name, 'time': self._time_as_seconds(test.elapsedtime)} self._writer.start('testcase', attrs) if test.status == 'FAIL': self._detail_serializer = _FailedTestSerializer(self._writer, test) def _time_as_seconds(self, millis): return str(int(round(millis, -3) / 1000)) def end_test(self, test): self._detail_serializer.end_test() self._detail_serializer = _NopSerializer() self._writer.end('testcase') def start_keyword(self, kw): pass def end_keyword(self, kw): pass def message(self, msg): self._detail_serializer.message(msg) class _FailedTestSerializer: """Specific policy to serialize a failed test case details""" def __init__(self, writer, test): self._writer = writer self._writer.start('failure', {'message': test.message, 'type': 'AssertionError'}) def end_test(self): self._writer.end('failure') def message(self, msg): """Populates the <failure> section, normally only with a 'Stacktrace'. There is a weakness here because filtering is based on message level: - DEBUG level is used by RF for 'Tracebacks' (what is expected here) - INFO and TRACE are used for keywords and arguments (not errors) - first FAIL message is already reported as <failure> attribute """ if msg.level == 'DEBUG': self._writer.content(msg.message) class _NopSerializer: """Default policy when there's no detail to serialize""" def end_test(self): pass def message(self, msg): pass
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement from xml import sax from robot.result.elementhandlers import RootHandler, Context from robot.result.jsondatamodel import DataModel def create_datamodel_from(input_filename): robot = _RobotOutputHandler(Context()) with open(input_filename, 'r') as input: sax.parse(input, robot) return robot.datamodel def parse_js(input_filename, output): create_datamodel_from(input_filename).write_to(output) class _RobotOutputHandler(sax.handler.ContentHandler): def __init__(self, context): self._context = context self._root_handler = RootHandler(context) self._handler_stack = [self._root_handler] @property def datamodel(self): return DataModel(self._root_handler.data) def startElement(self, name, attrs): handler = self._handler_stack[-1].get_handler_for(name, attrs) self._charbuffer = [] self._handler_stack.append(handler) def endElement(self, name): handler = self._handler_stack.pop() self._handler_stack[-1].add_child_data(handler.end_element(self.text)) def characters(self, content): self._charbuffer += [content] @property def text(self): return ''.join(self._charbuffer)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from robot import utils import json from robot.result.elementhandlers import TextIndex class DataModel(object): def __init__(self, robot_data): self._robot_data = robot_data self._settings = None self._set_generated(time.localtime()) def _set_generated(self, timetuple): genMillis = long(time.mktime(timetuple) * 1000) -\ self._robot_data['baseMillis'] self._set_attr('generatedMillis', genMillis) self._set_attr('generatedTimestamp', utils.format_time(timetuple, gmtsep=' ')) def _set_attr(self, name, value): self._robot_data[name] = value def set_settings(self, settings): self._settings = settings def write_to(self, output, separator='', split_threshold=9500): output.write('window.output = {};\n') output.write(separator) for key, value in self._robot_data.items(): self._write_output_element(key, output, separator, split_threshold, value) output.write(separator) self._dump_json('window.settings = ', self._settings, output) def _write_output_element(self, key, output, separator, split_threshold, value): if key == 'suite': splitWriter = SplittingSuiteWriter(self, output, separator, split_threshold) data, mapping = splitWriter.write(self._robot_data['suite']) self._dump_json('window.output["suite"] = ', data, output, mapping) elif key in ['integers', 'strings']: self._dump_and_split_list(key, output, separator, split_threshold) else: self._dump_json('window.output["%s"] = ' % key, value, output) def _dump_and_split_list(self, name, output, separator, split_threshold): lst = self._robot_data[name] output.write('window.output["%s"] = [];\n' % name) while lst: output.write(separator) output.write('window.output["%s"] = window.output["%s"].concat(' % (name, name)) json.json_dump(lst[:split_threshold], output) output.write(');\n') lst = lst[split_threshold:] def _dump_json(self, name, data, output, mappings=None): output.write(name) json.json_dump(data, output, mappings=mappings) output.write(';\n') def remove_keywords(self): self._robot_data['suite'] = self._remove_keywords_from(self._robot_data['suite']) self._prune_unused_indices() # TODO: this and remove_keywords should be removed # instead there should be a reportify or write_for_report_to method def remove_errors(self): self._robot_data.pop('errors') def _remove_keywords_from(self, data): if not isinstance(data, list): return data return [self._remove_keywords_from(item) for item in data if not self._is_ignorable_keyword(item)] def _is_ignorable_keyword(self, item): # Top level teardown is kept to make tests fail if suite teardown failed # TODO: Could we store information about failed suite teardown otherwise? # TODO: Cleanup? return item and \ isinstance(item, list) and \ (isinstance(item[0], TextIndex)) and \ self._robot_data['strings'][item[0]] in \ ['*kw', '*setup', '*forloop', '*foritem'] def _prune_unused_indices(self): used = self._collect_used_indices(self._robot_data['suite'], set()) remap = {} self._robot_data['strings'] = \ list(self._prune(self._robot_data['strings'], used, remap)) self._remap_indices(self._robot_data['suite'], remap) def _prune(self, data, used, index_remap, map_index=None, offset_increment=1): offset = 0 for index, text in enumerate(data): index = map_index(index) if map_index else index if index in used: index_remap[index] = index - offset yield text else: offset += offset_increment def _remap_indices(self, data, remap): for i, item in enumerate(data): if isinstance(item, TextIndex): data[i] = remap[item] elif isinstance(item, list): self._remap_indices(item, remap) def _collect_used_indices(self, data, result): for item in data: if isinstance(item, (int, long)): result.add(item) elif isinstance(item, list): self._collect_used_indices(item, result) elif isinstance(item, dict): self._collect_used_indices(item.values(), result) self._collect_used_indices(item.keys(), result) return result class _SubResult(object): def __init__(self, data_block, size, mapping): self.data_block = data_block self.size = size self.mapping = mapping def update(self, subresult): self.data_block += [subresult.data_block] self.size += subresult.size if subresult.mapping: self.mapping.update(subresult.mapping) def link(self, name): key = object() return _SubResult(key, 1, {key:name}) class SplittingSuiteWriter(object): def __init__(self, writer, output, separator, split_threshold): self._index = 0 self._output = output self._writer = writer self._separator = separator self._split_threshold = split_threshold def write(self, data_block): result = self._write(data_block) return result.data_block, result.mapping def _write(self, data_block): if not isinstance(data_block, list): return _SubResult(data_block, 1, None) result = _SubResult([], 1, {}) for item in data_block: result.update(self._write(item)) if result.size > self._split_threshold: result = self._dump_suite_part(result) return result def _list_name(self): return 'window.sPart%s' % self._index def _dump_suite_part(self, result): self._writer._dump_json(self._list_name()+' = ', result.data_block, self._output, result.mapping) self._write_separator() new_result = result.link(self._list_name()) self._index += 1 return new_result def _write_separator(self): self._output.write(self._separator)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TODO: Various tasks # - Rename this module so that it is not confused with standard json module # - Consider moving under utils # - Cleanup def encode_basestring(string): def get_matching_char(c): val = ord(c) if val < 127 and val > 31: return c return '\\u' + hex(val)[2:].rjust(4,'0') # TODO: Our log doesn't contain all these control chars string = string.replace('\\', '\\\\') string = string.replace('"', '\\"') string = string.replace('\b', '\\b') string = string.replace('\f', '\\f') string = string.replace('\n', '\\n') string = string.replace('\r', '\\r') string = string.replace('\t', '\\t') return '"%s"' % ''.join(get_matching_char(c) for c in string) def json_dump(data, output, mappings=None): if data is None: output.write('null') elif isinstance(data, dict): output.write('{') for index, key in enumerate(data): json_dump(key, output, mappings) output.write(':') json_dump(data[key], output, mappings) if index < len(data)-1: output.write(',') output.write('}') elif isinstance(data, (list, tuple)): output.write('[') for index, item in enumerate(data): json_dump(item, output, mappings) if index < len(data)-1: output.write(',') output.write(']') elif mappings and data in mappings: output.write(mappings[data]) elif isinstance(data, (int, long)): output.write(str(data)) elif isinstance(data, basestring): output.write(encode_basestring(data)) else: raise Exception('Data type (%s) serialization not supported' % type(data))
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from resultwriter import ResultWriter
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.common import Statistics from robot.output import LOGGER, process_outputs from outputwriter import OutputWriter from xunitwriter import XUnitWriter from builders import LogBuilder, ReportBuilder, XUnitBuilder, OutputBuilder import jsparser class ResultWriter(object): def __init__(self, settings): self._xml_result = None self._suite = None self._settings = settings def write_robot_results(self, data_source): data_model = jsparser.create_datamodel_from(data_source) LogBuilder(data_model, self._settings).build() ReportBuilder(data_model, self._settings).build() XUnitBuilder(self._result_from_xml([data_source]), self._settings).build() def _result_from_xml(self, data_sources): if not self._xml_result: self._suite, errs = process_outputs(data_sources, self._settings) self._suite.set_options(self._settings) self._xml_result = ResultFromXML(self._suite, errs, self._settings) return self._xml_result def write_rebot_results(self, *data_sources): builder = OutputBuilder(self._result_from_xml(data_sources), self._settings) self.write_robot_results(builder.build()) builder.finalize() return self._suite class ResultFromXML(object): def __init__(self, suite, exec_errors, settings=None): self.suite = suite self.exec_errors = exec_errors if settings: params = (settings['SuiteStatLevel'], settings['TagStatInclude'], settings['TagStatExclude'], settings['TagStatCombine'], settings['TagDoc'], settings['TagStatLink']) else: params = () self.statistics = Statistics(suite, *params) self._generator = 'Robot' def serialize_output(self, path, log=True): if path == 'NONE': return serializer = OutputWriter(path) self.suite.serialize(serializer) self.statistics.serialize(serializer) self.exec_errors.serialize(serializer) serializer.close() if log: LOGGER.output_file('Output', path) def serialize_xunit(self, path): if path == 'NONE': return serializer = XUnitWriter(path) try: self.suite.serialize(serializer) finally: serializer.close() LOGGER.output_file('XUnit', path)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import zlib import base64 from operator import itemgetter from robot import utils class _Handler(object): def __init__(self, context, attrs=None): self._context = context self._data_from_children = [] self._handlers = { 'robot' : _RobotHandler, 'suite' : _SuiteHandler, 'test' : _TestHandler, 'statistics' : _StatisticsHandler, 'stat' : _StatItemHandler, 'errors' : _Handler, 'doc' : _HtmlTextHandler, 'kw' : _KeywordHandler, 'arg' : _ArgumentHandler, 'arguments' : _ArgumentsHandler, 'tag' : _TextHandler, 'tags' : _Handler, 'msg' : _MsgHandler, 'status' : _StatusHandler, 'metadata' : _MetadataHandler, 'item' : _MetadataItemHandler, } def get_handler_for(self, name, attrs): return self._handlers[name](self._context, attrs) def add_child_data(self, data): self._data_from_children.append(data) def end_element(self, text): return self._data_from_children def _get_id(self, item): return self._context.get_id(item) def _get_ids(self, items): return [self._context.get_id(i) for i in items] class RootHandler(_Handler): # TODO: Combine _RootHandler and _RobotHandler @property def data(self): return self._data_from_children[0] class _RobotHandler(_Handler): def __init__(self, context, attrs): _Handler.__init__(self, context) self._generator = attrs.get('generator') def end_element(self, text): return {'generator': self._generator, 'suite': self._data_from_children[0], 'stats': self._data_from_children[1], 'errors': self._data_from_children[2], 'baseMillis': self._context.basemillis, 'strings': self._context.dump_texts()} class _SuiteHandler(_Handler): def __init__(self, context, attrs): _Handler.__init__(self, context) self._name = attrs.get('name') self._source = attrs.get('source') or '' self._suites = [] self._tests = [] self._keywords = [] self._current_children = None self._context.start_suite(self._name) self._context.collect_stats() def get_handler_for(self, name, attrs): self._current_children = { 'suite': self._suites, 'test': self._tests, 'kw': self._keywords }.get(name, self._data_from_children) return _Handler.get_handler_for(self, name, attrs) def add_child_data(self, data): self._current_children.append(data) def end_element(self, text): result = self._get_ids([self._source, self._name]) + \ self._data_from_children + [self._suites] + \ [self._tests] + [self._keywords] + \ [self._get_ids(self._context.dump_stats())] self._context.end_suite() return result class _TestHandler(_Handler): def __init__(self, context, attrs): _Handler.__init__(self, context) self._name = attrs.get('name') self._timeout = attrs.get('timeout') self._keywords = [] self._current_children = None self._context.start_test(self._name) def get_handler_for(self, name, attrs): if name == 'status': # TODO: Use 1/0 instead of Y/N. Possibly also 1/0/-1 instead of P/F/N. self._critical = 'Y' if attrs.get('critical') == 'yes' else 'N' self._current_children = { 'kw': self._keywords }.get(name, self._data_from_children) return _Handler.get_handler_for(self, name, attrs) def add_child_data(self, data): self._current_children.append(data) def end_element(self, text): result = self._get_ids([self._name, self._timeout, self._critical]) + \ self._data_from_children + [self._keywords] # TODO: refactor self._context.add_test(self._critical == 'Y', result[-2][0] == self._get_id('P')) self._context.end_test() return result class _KeywordHandler(_Handler): def __init__(self, context, attrs): _Handler.__init__(self, context) self._context.start_keyword() self._type = attrs.get('type') if self._type == 'for': self._type = 'forloop' self._name = attrs.get('name') self._timeout = attrs.get('timeout') self._keywords = [] self._messages = [] self._current_children = None def get_handler_for(self, name, attrs): if name == 'status': # TODO: Use 1/0 instead of Y/N. Possibly also 1/0/-1 instead of P/F/N. self._critical = 'Y' if attrs.get('critical') == 'yes' else 'N' self._current_children = { 'kw': self._keywords, 'msg': self._messages }.get(name, self._data_from_children) return _Handler.get_handler_for(self, name, attrs) def add_child_data(self, data): self._current_children.append(data) def end_element(self, text): if self._type == 'teardown' and self._data_from_children[-1][0] == self._get_id('F'): self._context.teardown_failed() self._context.end_keyword() return self._get_ids([self._type, self._name, self._timeout]) + \ self._data_from_children + [self._keywords] + [self._messages] # TODO: StatisticsHandler and StatItemHandler should be separated somehow from suite handlers class _StatisticsHandler(_Handler): def get_handler_for(self, name, attrs): return _Handler(self._context, attrs) class _StatItemHandler(_Handler): def __init__(self, context, attrs): _Handler.__init__(self, context) self._attrs = dict(attrs) self._attrs['pass'] = int(self._attrs['pass']) self._attrs['fail'] = int(self._attrs['fail']) if 'doc' in self._attrs: self._attrs['doc'] = utils.html_format(self._attrs['doc']) # TODO: Should we only dump attrs that have value? # Tag stats have many attrs that are normally empty def end_element(self, text): self._attrs.update(label=text) return self._attrs class _StatusHandler(_Handler): def __init__(self, context, attrs): self._context = context self._status = attrs.get('status')[0] self._starttime = self._context.timestamp(attrs.get('starttime')) endtime = self._context.timestamp(attrs.get('endtime')) self._elapsed = self._calculate_elapsed(endtime) def _calculate_elapsed(self, endtime): # Both start and end may be 0 so must compare against None if self._starttime is None or endtime is None: return None return endtime - self._starttime def end_element(self, text): result = [self._status, self._starttime, self._elapsed] if text: result.append(text) return self._get_ids(result) class _ArgumentHandler(_Handler): def end_element(self, text): return text class _ArgumentsHandler(_Handler): def end_element(self, text): return self._get_id(', '.join(self._data_from_children)) class _TextHandler(_Handler): def end_element(self, text): return self._get_id(text) class _HtmlTextHandler(_Handler): def end_element(self, text): return self._get_id(utils.html_format(text)) class _MetadataHandler(_Handler): def __init__(self, context, attrs): _Handler.__init__(self, context) self._metadata = [] def add_child_data(self, data): self._metadata.extend(data) def end_element(self, text): return self._metadata class _MetadataItemHandler(_Handler): def __init__(self, context, attrs): _Handler.__init__(self, context) self._name = attrs.get('name') def end_element(self, text): return self._get_ids([self._name, utils.html_format(text)]) class _MsgHandler(_Handler): def __init__(self, context, attrs): _Handler.__init__(self, context) self._msg = [self._context.timestamp(attrs.get('timestamp')), attrs.get('level')[0]] self._is_html = attrs.get('html') self._is_linkable = attrs.get("linkable") == "yes" def end_element(self, text): self._msg.append(text if self._is_html else utils.html_escape(text)) self._handle_warning_linking() return self._get_ids(self._msg) def _handle_warning_linking(self): # TODO: should perhaps use the id version of this list for indexing? if self._is_linkable: self._msg.append(self._context.link_to(self._msg)) elif self._msg[1] == 'W': self._context.create_link_to_current_location(self._msg) class Context(object): def __init__(self): self._texts = TextCache() self._basemillis = 0 self._stats = Stats() self._current_place = [] self._kw_index = [] self._links = {} @property def basemillis(self): return self._basemillis def collect_stats(self): self._stats = self._stats.new_child() return self def dump_stats(self): try: return self._stats.dump() finally: self._stats = self._stats.parent def get_id(self, value): if value is None: return None if isinstance(value, basestring): return self._get_text_id(value) if isinstance(value, (int, long)): return value raise AssertionError('Unsupported type of value '+str(type(value))) def _get_text_id(self, text): return self._texts.add(text) def dump_texts(self): return self._texts.dump() def timestamp(self, time): if time == 'N/A': return None millis = int(utils.timestamp_to_secs(time, millis=True) * 1000) if not self._basemillis: self._basemillis = millis return millis - self.basemillis def start_suite(self, name): self._current_place.append(('suite', name)) self._kw_index.append(0) def end_suite(self): self._current_place.pop() self._kw_index.pop() def start_test(self, name): self._current_place.append(('test', name)) self._kw_index.append(0) def end_test(self): self._current_place.pop() self._kw_index.pop() def start_keyword(self): self._current_place.append(('keyword', self._kw_index[-1])) self._kw_index[-1] += 1 self._kw_index.append(0) def end_keyword(self): self._current_place.pop() self._kw_index.pop() def create_link_to_current_location(self, key): self._links[tuple(key)] = self._create_link() def _create_link(self): return "keyword_"+".".join(str(v) for _, v in self._current_place) def link_to(self, key): return self._links[tuple(key)] def add_test(self, critical, passed): self._stats.add_test(critical, passed) def teardown_failed(self): self._stats.fail_all() class Stats(object): TOTAL = 0 TOTAL_PASSED = 1 CRITICAL = 2 CRITICAL_PASSED = 3 def __init__(self, parent=None): self.parent = parent self._stats = [0,0,0,0] self._children = [] def new_child(self): self._children.append(Stats(self)) return self._children[-1] def add_test(self, critical, passed): self._stats[Stats.TOTAL] += 1 if passed: self._stats[Stats.TOTAL_PASSED] +=1 if critical: self._stats[Stats.CRITICAL] += 1 if passed: self._stats[Stats.CRITICAL_PASSED] += 1 def dump(self): if self.parent: for i in range(4): self.parent._stats[i] += self._stats[i] return self._stats def fail_all(self): self._stats[1] = 0 self._stats[3] = 0 for child in self._children: child.fail_all() class TextIndex(int): pass ZERO_TEXT_INDEX = TextIndex(0) class TextCache(object): # TODO: Tune compressing thresholds _compress_threshold = 20 _use_compressed_threshold = 1.1 def __init__(self): self.texts = {'*': ZERO_TEXT_INDEX} self.index = 1 def add(self, text): if not text: return 0 text = self._encode(text) if text not in self.texts: self.texts[text] = TextIndex(self.index) self.index += 1 return self.texts[text] def _encode(self, text): raw = self._raw(text) if raw in self.texts or len(raw) < self._compress_threshold: return raw compressed = self._compress(text) if len(compressed) * self._use_compressed_threshold < len(raw): return compressed return raw def _compress(self, text): return base64.b64encode(zlib.compress(text.encode('UTF-8'), 9)) def _raw(self, text): return '*'+text def dump(self): # TODO: Could we yield or return an iterator? # TODO: Duplicate with IntegerCache.dump return [item[0] for item in sorted(self.texts.iteritems(), key=itemgetter(1))]
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from org.robotframework import RobotRunner from robot import runner, run_from_cli, rebot, rebot_from_cli class JarRunner(RobotRunner): """Used for Java-Jython interop when RF is executed from .jar file""" def run(self, args): try: if args and args[0] == 'rebot': rebot_from_cli(args[1:], rebot.__doc__) else: run_from_cli(args, runner.__doc__) except SystemExit, err: return err.code
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os if __name__ == '__main__': sys.stderr.write("Use 'runner' or 'rebot' for executing.\n") sys.exit(252) # 252 == DATA_ERROR # Global workaround for os.listdir bug http://bugs.jython.org/issue1593 # This bug has been fixed in Jython 2.5.2 RC 2 if sys.platform.startswith('java') and sys.version_info[:3] < (2,5,2): from java.lang import String def listdir(path): items = os._listdir(path) if isinstance(path, unicode): items = [unicode(String(i).toString()) for i in items] return items os._listdir = os.listdir os.listdir = listdir # Global workaround for os.stat bug http://bugs.jython.org/issue1658 # Jython 2.5.2 RC 2 still contains this bug, but additionally the workaround used # here does not work on that version either. if sys.platform.startswith('java') and os.sep == '\\' and sys.version_info < (2,5,2): os._posix = os.JavaPOSIX(os.PythonPOSIXHandler()) os._native_posix = False if 'pythonpathsetter' not in sys.modules: import pythonpathsetter from output import Output, LOGGER, pyloggingconf from conf import RobotSettings, RebotSettings from running import TestSuite, STOP_SIGNAL_MONITOR from robot.result import ResultWriter from errors import (DataError, Information, INFO_PRINTED, DATA_ERROR, STOPPED_BY_USER, FRAMEWORK_ERROR) from variables import init_global_variables from version import get_version, get_full_version import utils __version__ = get_version() def run_from_cli(args, usage): LOGGER.info(get_full_version('Robot Framework')) return _run_or_rebot_from_cli(run, args, usage, pythonpath='pythonpath') def rebot_from_cli(args, usage): LOGGER.info(get_full_version('Rebot')) return _run_or_rebot_from_cli(run_rebot, args, usage) def _run_or_rebot_from_cli(method, cliargs, usage, **argparser_config): LOGGER.register_file_logger() try: options, datasources = _parse_arguments(cliargs, usage, **argparser_config) except Information, msg: print utils.encode_output(unicode(msg)) return INFO_PRINTED except DataError, err: _report_error(unicode(err), help=True) return DATA_ERROR LOGGER.info('Data sources: %s' % utils.seq2str(datasources)) return _execute(method, datasources, options) def _parse_arguments(cliargs, usage, **argparser_config): ap = utils.ArgumentParser(usage, get_full_version()) return ap.parse_args(cliargs, argfile='argumentfile', unescape='escape', help='help', version='version', check_args=True, **argparser_config) def _execute(method, datasources, options): try: suite = method(*datasources, **options) except DataError, err: _report_error(unicode(err), help=True) return DATA_ERROR except (KeyboardInterrupt, SystemExit): _report_error('Execution stopped by user.') return STOPPED_BY_USER except: error, details = utils.get_error_details() _report_error('Unexpected error: %s' % error, details) return FRAMEWORK_ERROR else: return suite.return_code def run(*datasources, **options): """Executes given Robot data sources with given options. Data sources are paths to files and directories, similarly as when running pybot/jybot from command line. Options are given as keywords arguments and their names are same as long command line options without hyphens. Examples: run('/path/to/tests.html') run('/path/to/tests.html', '/path/to/tests2.html', log='mylog.html') Equivalent command line usage: pybot /path/to/tests.html pybot --log mylog.html /path/to/tests.html /path/to/tests2.html """ STOP_SIGNAL_MONITOR.start() settings = RobotSettings(options) LOGGER.register_console_logger(settings['MonitorWidth'], settings['MonitorColors']) output = Output(settings) init_global_variables(settings) suite = TestSuite(datasources, settings) suite.run(output) LOGGER.info("Tests execution ended. Statistics:\n%s" % suite.get_stat_message()) output.close(suite) if settings.is_rebot_needed(): output, settings = settings.get_rebot_datasource_and_settings() ResultWriter(settings).write_robot_results(output) LOGGER.close() return suite def run_rebot(*datasources, **options): """Creates reports/logs from given Robot output files with given options. Given input files are paths to Robot output files similarly as when running rebot from command line. Options are given as keywords arguments and their names are same as long command line options without hyphens. Examples: run_rebot('/path/to/output.xml') run_rebot('/path/out1.xml', '/path/out2.xml', report='myrep.html', log='NONE') Equivalent command line usage: rebot /path/to/output.xml rebot --report myrep.html --log NONE /path/out1.xml /path/out2.xml """ settings = RebotSettings(options) LOGGER.register_console_logger(colors=settings['MonitorColors']) LOGGER.disable_message_cache() suite = ResultWriter(settings).write_rebot_results(*datasources) LOGGER.close() return suite def _report_error(message, details=None, help=False): if help: message += '\n\nTry --help for usage information.' LOGGER.error(message) if details: LOGGER.info(details)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from normalizing import NormalizedDict class ConnectionCache: """Connection cache for different Robot test libraries that use connections. This cache stores connections and allows switching between them using generated indexes or user given aliases. Can be used for example by web testing libraries where there's need for multiple concurrent connections. Note that in most cases there should be only one instance of this class but this is not enforced. """ def __init__(self, no_current_msg='No open connection'): self.current = self._no_current = _NoConnection(no_current_msg) self.current_index = None self._connections = [] self._aliases = NormalizedDict() self._no_current_msg = no_current_msg def register(self, connection, alias=None): """Registers given connection with optional alias and returns its index. Given connection is set to be the current connection. Alias must be a string. The index of the first connection after initialization or close_all or empty_cache is 1, second is 2, etc. """ self.current = connection self._connections.append(connection) self.current_index = len(self._connections) if isinstance(alias, basestring): self._aliases[alias] = self.current_index return self.current_index def switch(self, index_or_alias): """Switches to the connection specified by given index or alias. If alias is given it must be a string. Indexes can be either integers or strings that can be converted into integer. Raises RuntimeError if no connection with given index or alias found. """ try: index = self._get_index(index_or_alias) except ValueError: raise RuntimeError("Non-existing index or alias '%s'" % index_or_alias) self.current = self._connections[index-1] self.current_index = index return self.current def close_all(self, closer_method='close'): """Closes connections using given closer method and empties cache. If simply calling the closer method is not adequate for closing connections, clients should close connections themselves and use empty_cache afterwards. """ for conn in self._connections: getattr(conn, closer_method)() self.empty_cache() return self.current def empty_cache(self): """Empties the connections cache. Indexes of new connections starts from 1 after this.""" self.current = self._no_current self.current_index = None self._connections = [] self._aliases = NormalizedDict() def _get_index(self, index_or_alias): try: return self._resolve_alias(index_or_alias) except ValueError: return self._resolve_index(index_or_alias) def _resolve_alias(self, alias): if isinstance(alias, basestring): try: return self._aliases[alias] except KeyError: pass raise ValueError def _resolve_index(self, index): index = int(index) if not 0 < index <= len(self._connections): raise ValueError return index class _NoConnection: def __init__(self, msg): self._msg = msg def __getattr__(self, name): if name.startswith('__') and name.endswith('__'): raise AttributeError raise RuntimeError(self._msg) def __nonzero__(self): return False
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from abstractxmlwriter import AbstractXmlWriter def XmlWriter(path): if path == 'NONE': return FakeXMLWriter() if os.name == 'java': from jyxmlwriter import XmlWriter else: from pyxmlwriter import XmlWriter return XmlWriter(path) class FakeXMLWriter(AbstractXmlWriter): closed = False _start = _content = _end = _close = lambda self, *args: None
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from java.io import FileOutputStream from javax.xml.transform.sax import SAXTransformerFactory from javax.xml.transform.stream import StreamResult from org.xml.sax.helpers import AttributesImpl from abstractxmlwriter import AbstractXmlWriter class XmlWriter(AbstractXmlWriter): def __init__(self, path): self.path = path self._output = FileOutputStream(path) self._writer = SAXTransformerFactory.newInstance().newTransformerHandler() self._writer.setResult(StreamResult(self._output)) self._writer.startDocument() self.content('\n') self.closed = False def _start(self, name, attrs): self._writer.startElement('', '', name, self._get_attrs_impl(attrs)) def _get_attrs_impl(self, attrs): ai = AttributesImpl() for name, value in attrs.items(): ai.addAttribute('', '', name, '', value) return ai def _content(self, content): self._writer.characters(content, 0, len(content)) def _end(self, name): self._writer.endElement('', '', name)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import threading class Thread(threading.Thread): """A subclass of threading.Thread, with a stop() method. Original version posted by Connelly Barnes to python-list and available at http://mail.python.org/pipermail/python-list/2004-May/219465.html This version mainly has kill() changed to stop() to match java.lang.Thread. This is a hack but seems to be the best way the get this done. Only used in Python because in Jython we can use java.lang.Thread. """ def __init__(self, runner): threading.Thread.__init__(self, target=runner) self._stopped = False def start(self): self.__run_backup = self.run self.run = self.__run threading.Thread.start(self) def stop(self): self._stopped = True def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self._globaltrace) self.__run_backup() self.run = self.__run_backup def _globaltrace(self, frame, why, arg): if why == 'call': return self._localtrace else: return None def _localtrace(self, frame, why, arg): if self._stopped: if why == 'line': raise SystemExit() return self._localtrace
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys # Need different unic implementations for different Pythons because: # 1) Importing unicodedata module on Jython takes a very long time, and doesn't # seem to be necessary as Java probably already handles normalization. # Furthermore, Jython on Java 1.5 doesn't even have unicodedata.normalize. # 2) IronPython 2.6 doesn't have unicodedata and probably doesn't need it. # 3) CPython doesn't automatically normalize Unicode strings. if sys.platform.startswith('java'): from java.lang import Object, Class def unic(item, *args): # http://bugs.jython.org/issue1564 if isinstance(item, Object) and not isinstance(item, Class): item = item.toString() # http://bugs.jython.org/issue1563 return _unic(item, *args) elif sys.platform == 'cli': def unic(item, *args): return _unic(item, *args) else: from unicodedata import normalize def unic(item, *args): return normalize('NFC', _unic(item, *args)) def _unic(item, *args): # Based on a recipe from http://code.activestate.com/recipes/466341 try: return unicode(item, *args) except UnicodeError: try: ascii_text = str(item).encode('string_escape') except UnicodeError: return u"<unrepresentable object '%s'>" % item.__class__.__name__ else: return unicode(ascii_text) def safe_repr(item): try: return unic(repr(item)) except UnicodeError: return repr(unic(item))
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from normalizing import normalize from misc import plural_or_not def _get_timetuple(epoch_secs=None): if _CURRENT_TIME: return _CURRENT_TIME if epoch_secs is None: # can also be 0 (at least in unit tests) epoch_secs = time.time() secs, millis = _float_secs_to_secs_and_millis(epoch_secs) timetuple = time.localtime(secs)[:6] # from year to secs return timetuple + (millis,) def _float_secs_to_secs_and_millis(secs): isecs = int(secs) millis = int(round((secs - isecs) * 1000)) return (isecs, millis) if millis < 1000 else (isecs+1, 0) _CURRENT_TIME = None # Seam for mocking time-dependent tests START_TIME = _get_timetuple() def timestr_to_secs(timestr): """Parses time in format like '1h 10s' and returns time in seconds (float). Given time must be in format '1d 2h 3m 4s 5ms' with following rules. - Time parts having zero value can be ignored (e.g. '3m 4s' is ok) - Format is case and space insensitive - Instead of 'd' it is also possible to use 'day' or 'days' - Instead of 'h' also 'hour' and 'hours' are ok - Instead of 'm' also 'minute', 'minutes', 'min' and 'mins' are ok - Instead of 's' also 'second', 'seconds', 'sec' and 'secs' are ok - Instead of 'ms' also 'millisecond', 'milliseconds' and 'millis' are ok - It is possible to give time only as a float and then it is considered to be seconds (e.g. '123', '123.0', '123s', '2min 3s' are all equivelant) """ try: secs = _timestr_to_secs(timestr) except (ValueError, TypeError): raise ValueError("Invalid time string '%s'" % timestr) return round(secs, 3) def _timestr_to_secs(timestr): timestr = _normalize_timestr(timestr) if timestr == '': raise ValueError try: return float(timestr) except ValueError: pass millis = secs = mins = hours = days = 0 if timestr[0] == '-': sign = -1 timestr = timestr[1:] else: sign = 1 temp = [] for c in timestr: if c == 'x': millis = float(''.join(temp)); temp = [] elif c == 's': secs = float(''.join(temp)); temp = [] elif c == 'm': mins = float(''.join(temp)); temp = [] elif c == 'h': hours = float(''.join(temp)); temp = [] elif c == 'p': days = float(''.join(temp)); temp = [] else: temp.append(c) if temp: raise ValueError return sign * (millis/1000 + secs + mins*60 + hours*60*60 + days*60*60*24) def _normalize_timestr(timestr): if isinstance(timestr, (int, long, float)): return timestr timestr = normalize(timestr) for item in 'milliseconds', 'millisecond', 'millis': timestr = timestr.replace(item, 'ms') for item in 'seconds', 'second', 'secs', 'sec': timestr = timestr.replace(item, 's') for item in 'minutes', 'minute', 'mins', 'min': timestr = timestr.replace(item, 'm') for item in 'hours', 'hour': timestr = timestr.replace(item, 'h') for item in 'days', 'day': timestr = timestr.replace(item, 'd') # 1) 'ms' -> 'x' to ease processing later # 2) 'd' -> 'p' because float('1d') returns 1.0 in Jython (bug submitted) return timestr.replace('ms','x').replace('d','p') def secs_to_timestr(secs, compact=False): """Converts time in seconds to a string representation. Returned string is in format like '1 day 2 hours 3 minutes 4 seconds 5 milliseconds' with following rules. - Time parts having zero value are not included (e.g. '3 minutes 4 seconds' instead of '0 days 0 hours 3 minutes 4 seconds') - Hour part has a maximun of 23 and minutes and seconds both have 59 (e.g. '1 minute 40 seconds' instead of '100 seconds') If compact has value 'True', short suffixes are used. (e.g. 1d 2h 3min 4s 5ms) """ return _SecsToTimestrHelper(secs, compact).get_value() class _SecsToTimestrHelper: def __init__(self, float_secs, compact): self._compact = compact self._ret = [] self._sign, millis, secs, mins, hours, days \ = self._secs_to_components(float_secs) self._add_item(days, 'd', 'day') self._add_item(hours, 'h', 'hour') self._add_item(mins, 'min', 'minute') self._add_item(secs, 's', 'second') self._add_item(millis, 'ms', 'millisecond') def get_value(self): if len(self._ret) > 0: return self._sign + ' '.join(self._ret) return '0s' if self._compact else '0 seconds' def _add_item(self, value, compact_suffix, long_suffix): if value == 0: return if self._compact: suffix = compact_suffix else: suffix = ' %s%s' % (long_suffix, plural_or_not(value)) self._ret.append('%d%s' % (value, suffix)) def _secs_to_components(self, float_secs): if float_secs < 0: sign = '- ' float_secs = abs(float_secs) else: sign = '' int_secs, millis = _float_secs_to_secs_and_millis(float_secs) secs = int_secs % 60 mins = int(int_secs / 60) % 60 hours = int(int_secs / (60*60)) % 24 days = int(int_secs / (60*60*24)) return sign, millis, secs, mins, hours, days def format_time(timetuple_or_epochsecs, daysep='', daytimesep=' ', timesep=':', millissep=None, gmtsep=None): """Returns a timestamp formatted from given time using separators. Time can be given either as a timetuple or seconds after epoch. Timetuple is (year, month, day, hour, min, sec[, millis]), where parts must be integers and millis is required only when millissep is not None. Notice that this is not 100% compatible with standard Python timetuples which do not have millis. Seconds after epoch can be either an integer or a float. """ if isinstance(timetuple_or_epochsecs, (int, long, float)): timetuple = _get_timetuple(timetuple_or_epochsecs) else: timetuple = timetuple_or_epochsecs daytimeparts = ['%02d' % t for t in timetuple[:6]] day = daysep.join(daytimeparts[:3]) time_ = timesep.join(daytimeparts[3:6]) millis = millissep and '%s%03d' % (millissep, timetuple[6]) or '' return day + daytimesep + time_ + millis + _diff_to_gmt(gmtsep) def _diff_to_gmt(sep): if not sep: return '' if time.altzone == 0: sign = '' elif time.altzone > 0: sign = '-' else: sign = '+' minutes = abs(time.altzone) / 60.0 hours, minutes = divmod(minutes, 60) return '%sGMT%s%s%02d:%02d' % (sep, sep, sign, hours, minutes) def get_time(format='timestamp', time_=None): """Return the given or current time in requested format. If time is not given, current time is used. How time is returned is is deternined based on the given 'format' string as follows. Note that all checks are case insensitive. - If 'format' contains word 'epoch' the time is returned in seconds after the unix epoch. - If 'format' contains any of the words 'year', 'month', 'day', 'hour', 'min' or 'sec' only selected parts are returned. The order of the returned parts is always the one in previous sentence and order of words in 'format' is not significant. Parts are returned as zero padded strings (e.g. May -> '05'). - Otherwise (and by default) the time is returned as a timestamp string in format '2006-02-24 15:08:31' """ if time_ is None: time_ = time.time() format = format.lower() # 1) Return time in seconds since epoc if 'epoch' in format: return int(time_) timetuple = time.localtime(time_) parts = [] for i, match in enumerate('year month day hour min sec'.split()): if match in format: parts.append('%.2d' % timetuple[i]) # 2) Return time as timestamp if not parts: return format_time(timetuple, daysep='-') # Return requested parts of the time elif len(parts) == 1: return parts[0] else: return parts def parse_time(timestr): """Parses the time string and returns its value as seconds since epoch. Time can be given in four different formats: 1) Numbers are interpreted as time since epoch directly. It is possible to use also ints and floats, not only strings containing numbers. 2) Valid timestamp ('YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss'). 3) 'NOW' (case-insensitive) is the current time rounded down to the closest second. 4) Format 'NOW - 1 day' or 'NOW + 1 hour 30 min' is the current time plus/minus the time specified with the time string. """ try: ret = int(timestr) except ValueError: pass else: if ret < 0: raise ValueError("Epoch time must be positive (got %s)" % timestr) return ret try: return timestamp_to_secs(timestr, (' ', ':', '-', '.')) except ValueError: pass normtime = timestr.lower().replace(' ', '') now = int(time.time()) if normtime == 'now': return now if normtime.startswith('now'): if normtime[3] == '+': return now + timestr_to_secs(normtime[4:]) if normtime[3] == '-': return now - timestr_to_secs(normtime[4:]) raise ValueError("Invalid time format '%s'" % timestr) def get_timestamp(daysep='', daytimesep=' ', timesep=':', millissep='.'): return format_time(_get_timetuple(), daysep, daytimesep, timesep, millissep) def timestamp_to_secs(timestamp, seps=('', ' ', ':', '.'), millis=False): try: secs = _timestamp_to_millis(timestamp, seps) / 1000.0 except (ValueError, OverflowError): raise ValueError("Invalid timestamp '%s'" % timestamp) if millis: return round(secs, 3) return int(round(secs)) def secs_to_timestamp(secs, seps=None, millis=False): if not seps: seps = ('', ' ', ':', '.' if millis else None) ttuple = time.localtime(secs)[:6] if millis: millis = (secs - int(secs)) * 1000 ttuple = ttuple + (int(millis),) return format_time(ttuple, *seps) def get_start_timestamp(daysep='', daytimesep=' ', timesep=':', millissep=None): return format_time(START_TIME, daysep, daytimesep, timesep, millissep) def get_elapsed_time(start_time, end_time=None, seps=('', ' ', ':', '.')): """Returns the time between given timestamps in milliseconds. If 'end_time' is not given current timestamp is got with get_timestamp using given 'seps'. 'seps' is a tuple containing 'daysep', 'daytimesep', 'timesep' and 'millissep' used in given timestamps. """ if start_time == 'N/A' or end_time == 'N/A': return 0 if not end_time: end_time = get_timestamp(*seps) start_millis = _timestamp_to_millis(start_time, seps) end_millis = _timestamp_to_millis(end_time, seps) # start/end_millis can be long but we want to return int when possible return int(end_millis - start_millis) def elapsed_time_to_string(elapsed_millis): """Converts elapsed time in millisecods to format 'hh:mm:ss.mil'""" elapsed_millis = round(elapsed_millis) if elapsed_millis < 0: pre = '-' elapsed_millis = abs(elapsed_millis) else: pre = '' millis = elapsed_millis % 1000 secs = int(elapsed_millis / 1000) % 60 mins = int(elapsed_millis / 60000) % 60 hours = int(elapsed_millis / 3600000) return '%s%02d:%02d:%02d.%03d' % (pre, hours, mins, secs, millis) def _timestamp_to_millis(timestamp, seps): Y, M, D, h, m, s, millis = _split_timestamp(timestamp, seps) secs = time.mktime((Y, M, D, h, m, s, 0, 0, time.daylight)) return int(round(1000*secs + millis)) def _split_timestamp(timestamp, seps): for sep in seps: if sep: timestamp = timestamp.replace(sep, '') timestamp = timestamp.ljust(17, '0') years = int(timestamp[:4]) mons = int(timestamp[4:6]) days = int(timestamp[6:8]) hours = int(timestamp[8:10]) mins = int(timestamp[10:12]) secs = int(timestamp[12:14]) millis = int(timestamp[14:17]) return years, mons, days, hours, mins, secs, millis
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from StringIO import StringIO try: import xml.etree.cElementTree as ET except ImportError: try: import cElementTree as ET except ImportError: try: import xml.etree.ElementTree as ET # Raises ImportError due to missing expat on IronPython by default ET.parse(StringIO('<test/>')) except ImportError: try: import elementtree.ElementTree as ET except ImportError: raise ImportError('No valid ElementTree XML parser module found') def get_root(path, string=None, node=None): # This should NOT be changed to 'if not node:'. See chapter Truth Testing # from http://effbot.org/zone/element.htm#the-element-type if node is not None: return node source = _get_source(path, string) try: return ET.parse(source).getroot() finally: if hasattr(source, 'close'): source.close() def _get_source(path, string): if not path: return StringIO(string) # ElementTree 1.2.7 preview (first ET with IronPython support) doesn't # handler non-ASCII chars correctly if an open file given to it. if sys.platform == 'cli': return path # ET.parse doesn't close files it opens, which causes serious problems # with Jython 2.5(.1) on Windows: http://bugs.jython.org/issue1598 return open(path, 'rb')
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from abstractxmlwriter import AbstractXmlWriter from htmlutils import html_escape, html_attr_escape from unic import unic class HtmlWriter(AbstractXmlWriter): def __init__(self, output): """'output' is an open file object. Given 'output' must have been opened with 'wb' to be able to write into it with UTF-8 encoding. 'self.output.name' is later used by serializers """ self.output = output def start(self, name, attrs=None, newline=True): self._start(name, attrs, close=False, newline=newline) def start_and_end(self, name, attrs=None, newline=True): self._start(name, attrs, close=True, newline=newline) def content(self, content=None, escape=True): """Given content doesn't need to be a string""" if content is not None: if escape: content = self._escape_content(content) self._write(content) def end(self, name, newline=True): elem = '</%s>' % name if newline: elem += '\n' self._write(elem) def element(self, name, content=None, attrs=None, escape=True, newline=True): self.start(name, attrs, newline=False) self.content(content, escape) self.end(name, newline) def start_many(self, names, newline=True): for name in names: self.start(name, newline=newline) def end_many(self, names, newline=True): for name in names: self.end(name, newline) def _start(self, name, attrs, close=False, newline=True): elem = '<%s' % name elem = self._add_attrs(elem, attrs) elem += (close and ' />' or '>') if newline: elem += '\n' self._write(elem) def _add_attrs(self, elem, attrs): if not attrs: return elem attrs = attrs.items() attrs.sort() attrs = [ '%s="%s"' % (name, html_attr_escape(value)) for name, value in attrs ] return '%s %s' % (elem, ' '.join(attrs)) def _escape_content(self, content): return html_escape(unic(content)) def _write(self, text): self.output.write(text.encode('UTF-8'))
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from unic import unic def html_escape(text, formatting=False): # TODO: Remove formatting attribute after RIDE does not use it anymore if formatting: return html_format(text) return _HtmlEscaper().format(text) def html_format(text): return _HtmlFormatter().format(text) def html_attr_escape(attr): for name, value in [('&', '&amp;'), ('"', '&quot;'), ('<', '&lt;'), ('>', '&gt;')]: attr = attr.replace(name, value) for wspace in ['\n', '\r', '\t']: attr = attr.replace(wspace, ' ') return attr class _Formatter(object): def format(self, text): text = self._html_escape(unic(text)) for line in text.splitlines(): self.add_line(line) return self.get_result() def _html_escape(self, text): for name, value in [('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;')]: text = text.replace(name, value) return text class _HtmlEscaper(_Formatter): def __init__(self): self._lines = [] self._line_formatter = _UrlFormatter() def add_line(self, line): self._lines.append(self._line_formatter.format(line)) def get_result(self): return '\n'.join(self._lines) class _HtmlFormatter(_Formatter): _hr_re = re.compile('^-{3,} *$') def __init__(self): self._result = _Formatted() self._table = _TableFormatter() self._line_formatter = _LineFormatter() def add_line(self, line): if self._add_table_row(line): return if self._table.is_started(): self._result.add(self._table.end(), join_after=False) if self._is_hr(line): self._result.add('<hr />\n', join_after=False) return self._result.add(self._line_formatter.format(line)) def _add_table_row(self, row): if self._table.is_table_row(row): self._table.add_row(row) return True return False def _is_hr(self, line): return bool(self._hr_re.match(line)) def get_result(self): if self._table.is_started(): self._result.add(self._table.end()) return self._result.get_result() class _Formatted(object): def __init__(self): self._result = [] self._joiner = '' def add(self, line, join_after=True): self._result.extend([self._joiner, line]) self._joiner = '\n' if join_after else '' def get_result(self): return ''.join(self._result) class _UrlFormatter(object): _formatting = False _image_exts = ('.jpg', '.jpeg', '.png', '.gif', '.bmp') _url = re.compile(''' ( (^|\ ) ["'([]* ) # begin of line or space and opt. any char "'([ (\w{3,9}://[\S]+?) # url (protocol is any alphanum 3-9 long string) (?= [])"'.,!?:;]* ($|\ ) ) # opt. any char ])"'.,!?:; and end of line or space ''', re.VERBOSE) def format(self, line): return self._format_url(line) def _format_url(self, line): return self._url.sub(self._repl_url, line) if ':' in line else line def _repl_url(self, match): pre = match.group(1) url = match.group(3).replace('"', '&quot;') if self._format_as_image(url): tmpl = '<img src="%s" title="%s" style="border: 1px solid gray" />' else: tmpl = '<a href="%s">%s</a>' return pre + tmpl % (url, url) def _format_as_image(self, url): return self._formatting and url.lower().endswith(self._image_exts) class _LineFormatter(_UrlFormatter): _formatting = True _bold = re.compile(''' ( # prefix (group 1) (^|\ ) # begin of line or space ["'(]* _? # optionally any char "'( and optional begin of italic ) # \* # start of bold ([^\ ].*?) # no space and then anything (group 3) \* # end of bold (?= # start of postfix (non-capturing group) _? ["').,!?:;]* # optional end of italic and any char "').,!?:; ($|\ ) # end of line or space ) ''', re.VERBOSE) _italic = re.compile(''' ( (^|\ ) ["'(]* ) # begin of line or space and opt. any char "'( _ # start of italic ([^\ _].*?) # no space or underline and then anything _ # end of italic (?= ["').,!?:;]* ($|\ ) ) # opt. any char "').,!?:; and end of line or space ''', re.VERBOSE) def format(self, line): return self._format_url(self._format_italic(self._format_bold(line))) def _format_bold(self, line): return self._bold.sub('\\1<b>\\3</b>', line) if '*' in line else line def _format_italic(self, line): return self._italic.sub('\\1<i>\\3</i>', line) if '_' in line else line class _TableFormatter(object): _is_table_line = re.compile('^\s*\| (.* |)\|\s*$') _line_splitter = re.compile(' \|(?= )') def __init__(self): self._rows = [] self._line_formatter = _LineFormatter() def is_table_row(self, row): return bool(self._is_table_line.match(row)) def is_started(self): return bool(self._rows) def add_row(self, text): text = text.strip()[1:-1] # remove outer whitespace and pipes cells = [cell.strip() for cell in self._line_splitter.split(text)] self._rows.append(cells) def end(self): ret = self._format_table(self._rows) self._rows = [] return ret def _format_table(self, rows): maxlen = max(len(row) for row in rows) table = ['<table border="1" class="doc">'] for row in rows: row += [''] * (maxlen - len(row)) # fix ragged tables table.append('<tr>') table.extend(['<td>%s</td>' % self._line_formatter.format(cell) for cell in row]) table.append('</tr>') table.append('</table>\n') return '\n'.join(table)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re _ESCAPE_RE = re.compile(r'(\\+)([^\\]{0,2})') # escapes and nextchars _SEQS_TO_BE_ESCAPED = ('\\', '${', '@{', '%{', '&{', '*{' , '=') def escape(item): if not isinstance(item, basestring): return item for seq in _SEQS_TO_BE_ESCAPED: item = item.replace(seq, '\\' + seq) return item def unescape(item): if not isinstance(item, basestring): return item result = [] unprocessed = item while True: res = _ESCAPE_RE.search(unprocessed) # If no escapes found append string to result and exit loop if res is None: result.append(unprocessed) break # Split string to pre match, escapes, nextchars and unprocessed parts # (e.g. '<pre><esc><nc><unproc>') where nextchars contains 0-2 chars # and unprocessed may contain more escapes. Pre match part contains # no escapes can is appended directly to result. result.append(unprocessed[:res.start()]) escapes = res.group(1) nextchars = res.group(2) unprocessed = unprocessed[res.end():] # Append every second escape char to result result.append('\\' * (len(escapes) / 2)) # Handle '\n', '\r' and '\t'. Note that both '\n' and '\n ' are # converted to '\n' if len(escapes) % 2 == 0 or len(nextchars) == 0 \ or nextchars[0] not in ['n','r','t']: result.append(nextchars) elif nextchars[0] == 'n': if len(nextchars) == 1 or nextchars[1] == ' ': result.append('\n') else: result.append('\n' + nextchars[1]) elif nextchars[0] == 'r': result.append('\r' + nextchars[1:]) else: result.append('\t' + nextchars[1:]) return ''.join(result)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement import getopt # optparse not supported by Jython 2.2 import os import re import sys import glob import string import codecs import textwrap from robot.errors import DataError, Information, FrameworkError from misc import plural_or_not from unic import unic from encoding import decode_output, decode_from_file_system ESCAPES = dict( space = ' ', apos = "'", quot = '"', lt = '<', gt = '>', pipe = '|', star = '*', comma = ',', slash = '/', semic = ';', colon = ':', quest = '?', hash = '#', amp = '&', dollar = '$', percent = '%', at = '@', exclam = '!', paren1 = '(', paren2 = ')', square1 = '[', square2 = ']', curly1 = '{', curly2 = '}', bslash = '\\' ) class ArgumentParser: _opt_line_re = re.compile(''' ^\s{,4} # max 4 spaces in the beginning of the line ((-\S\s)*) # all possible short options incl. spaces (group 1) --(\S{2,}) # required long option (group 3) (\s\S+)? # optional value (group 4) (\s\*)? # optional '*' telling option allowed multiple times (group 5) ''', re.VERBOSE) _usage_line_re = re.compile(''' ^usage:.* \[options\]\s* (.*?) # arguments (group 1) \s*$ ''', re.VERBOSE | re.IGNORECASE) def __init__(self, usage, version=None, arg_limits=None): """Available options and tool name are read from the usage. Tool name is got from the first row of the usage. It is either the whole row or anything before first ' -- '. See for example 'runner.py' and 'rebot.py' for examples. """ if not usage: raise FrameworkError('Usage cannot be empty') self._usage = usage self._name = usage.splitlines()[0].split(' -- ')[0].strip() self._version = version self._arg_limits = arg_limits self._short_opts = '' self._long_opts = [] self._multi_opts = [] self._toggle_opts = [] self._names = [] self._short_to_long = {} self._expected_args = () self._parse_usage(usage) def parse_args(self, args_list, unescape=None, argfile=None, pythonpath=None, help=None, version=None, check_args=False): """Parse given arguments and return options and positional arguments. Arguments must be given as a list and are typically sys.argv[1:]. Options are retuned as a dictionary where long options are keys. Value is a string for those options that can be given only one time (if they are given multiple times the last value is used) or None if the option is not used at all. Value for options that can be given multiple times (denoted with '*' in the usage) is a list which contains all the given values and is empty if options are not used. Options not taken arguments have value False when they are not set and True otherwise. Positional arguments are returned as a list in the order they are given. 'unescape' option can be used to automatically unescape problematic characters given in an escaped format. Given value must be the name of the long option used for escaping. Typically usage is having '--escape name:value *' in usage doc and specifying 'enescape="escape"' when calling this method. 'argfile' can be used to automatically read arguments from specified file. Given value must be the name of the long option used for giving the argument file. Typical usage is '--argumentfile path *' in usage doc and calling this method with 'argfile="argumentfile"'. If 'argfile' is used, it can always be given multiple times and thus it is recommended to use '*' to denote that. Special value 'stdin' can be used to read arguments from stdin instead of a file. 'pythonpath' can be used to specify option(s) containing extra paths to be added into 'sys.path'. Value can be either a string containing the name of the long option used for this purpose or a list containing all such long options (i.e. the latter format allows aliases). 'help' and 'version' make it possible to automatically generate help and version messages. Version is generated based on the tool name and version -- see __init__ for information how to set them. Help contains the whole usage given to __init__. Possible <VERSION> text in the usage is replaced with the given version. Possible <--ESCAPES--> is replaced with available escapes so that they are wrapped to multiple lines but take the same amount of horizontal space as <---ESCAPES--->. The numer of hyphens can be used to contrl the horizontal space. Both help and version are wrapped to Information exception. If 'check_args' is True, this method will automatically check that correct number of arguments, as parsed from the usage line, are given. If the last argument in the usage line ends with the character 's', the maximum number of arguments is infinite. Possible errors in processing arguments are reported using DataError. """ args_list = [decode_from_file_system(a) for a in args_list] if argfile: args_list = self._add_args_from_file(args_list, argfile) opts, args = self._parse_args(args_list) if unescape: opts, args = self._unescape_opts_and_args(opts, args, unescape) if help and opts[help]: self._raise_help() if version and opts[version]: self._raise_version() if pythonpath: sys.path = self._get_pythonpath(opts[pythonpath]) + sys.path if check_args: self._check_args(args) return opts, args def _parse_args(self, args): args = [self._lowercase_long_option(a) for a in args] try: opts, args = getopt.getopt(args, self._short_opts, self._long_opts) except getopt.GetoptError, err: raise DataError(err.args[0]) return self._process_opts(opts), self._glob_args(args) def _lowercase_long_option(self, opt): if not opt.startswith('--'): return opt if '=' not in opt: return opt.lower() opt, value = opt.split('=', 1) return '%s=%s' % (opt.lower(), value) def _check_args(self, args): if not self._arg_limits: raise FrameworkError('No argument information specified.') minargs, maxargs = self._arg_limits if minargs <= len(args) <= maxargs: return minend = plural_or_not(minargs) if minargs == maxargs: exptxt = "%d argument%s" % (minargs, minend) elif maxargs != sys.maxint: exptxt = "%d to %d arguments" % (minargs, maxargs) else: exptxt = "at least %d argument%s" % (minargs, minend) raise DataError("Expected %s, got %d." % (exptxt, len(args))) def _unescape_opts_and_args(self, opts, args, escape_opt): try: escape_strings = opts[escape_opt] except KeyError: raise FrameworkError("No escape option '%s' in given options") escapes = self._get_escapes(escape_strings) for name, value in opts.items(): if name != escape_opt: opts[name] = self._unescape(value, escapes) return opts, [self._unescape(arg, escapes) for arg in args] def _add_args_from_file(self, args, argfile_opt): argfile_opts = ['--'+argfile_opt] for sopt, lopt in self._short_to_long.items(): if lopt == argfile_opt: argfile_opts.append('-'+sopt) while True: try: index = self._get_argfile_index(args, argfile_opts) path = args[index+1] except IndexError: break args[index:index+2] = self._get_args_from_file(path) return args def _get_argfile_index(self, args, argfile_opts): for opt in argfile_opts: if opt in args: return args.index(opt) raise IndexError def _get_args_from_file(self, path): if path.upper() != 'STDIN': content = self._read_argfile(path) else: content = decode_output(sys.__stdin__.read()) return self._process_argfile(content) def _read_argfile(self, path): try: with codecs.open(path, encoding='UTF-8') as f: content = f.read() except (IOError, UnicodeError), err: raise DataError("Opening argument file '%s' failed: %s" % (path, err)) if content.startswith(codecs.BOM_UTF8.decode('UTF-8')): content = content[1:] return content def _process_argfile(self, content): args = [] for line in content.splitlines(): line = line.strip() if line.startswith('-'): args.extend(line.split(' ', 1)) elif line and not line.startswith('#'): args.append(line) return args def _get_escapes(self, escape_strings): escapes = {} for estr in escape_strings: try: name, value = estr.split(':', 1) except ValueError: raise DataError("Invalid escape string syntax '%s'. " "Expected: what:with" % estr) try: escapes[value] = ESCAPES[name.lower()] except KeyError: raise DataError("Invalid escape '%s'. Available: %s" % (name, self._get_available_escapes())) return escapes def _unescape(self, value, escapes): if value in [None, True, False]: return value if isinstance(value, list): return [self._unescape(item, escapes) for item in value] for esc_name, esc_value in escapes.items(): value = value.replace(esc_name, esc_value) return value def _process_opts(self, opt_tuple): opts = self._init_opts() for name, value in opt_tuple: name = self._get_name(name) if name in self._multi_opts: opts[name].append(value) elif name in self._toggle_opts: opts[name] = not opts[name] else: opts[name] = value return opts def _glob_args(self, args): temp = [] for path in args: paths = sorted(glob.glob(path)) if paths: temp.extend(paths) else: temp.append(path) return temp def _init_opts(self): opts = {} for name in self._names: if name in self._multi_opts: opts[name] = [] elif name in self._toggle_opts: opts[name] = False else: opts[name] = None return opts def _get_name(self, name): name = name.lstrip('-') try: return self._short_to_long[name] except KeyError: return name def _parse_usage(self, usage): for line in usage.splitlines(): if not self._parse_opt_line(line) and not self._arg_limits: self._parse_usage_line(line) def _parse_usage_line(self, line): res = self._usage_line_re.match(line) if res: args = res.group(1).split() if not args: self._arg_limits = (0, 0) else: maxargs = args[-1].endswith('s') and sys.maxint or len(args) self._arg_limits = (len(args), maxargs) def _parse_opt_line(self, line): res = self._opt_line_re.match(line) if not res: return False long_opt = res.group(3).lower() if long_opt in self._names: self._raise_option_multiple_times_in_usage('--' + long_opt) self._names.append(long_opt) short_opts = [ opt[1] for opt in res.group(1).split() ] for sopt in short_opts: if self._short_to_long.has_key(sopt): self._raise_option_multiple_times_in_usage('-' + sopt) self._short_to_long[sopt] = long_opt # options allowed multiple times if res.group(5): self._multi_opts.append(long_opt) # options with arguments if res.group(4): long_opt += '=' short_opts = [ sopt + ':' for sopt in short_opts ] else: self._toggle_opts.append(long_opt) self._long_opts.append(long_opt) self._short_opts += (''.join(short_opts)) return True def _get_pythonpath(self, paths): if isinstance(paths, basestring): paths = [paths] temp = [] for path in self._split_pythonpath(paths): temp.extend(glob.glob(path)) return [os.path.abspath(path) for path in temp if path] def _split_pythonpath(self, paths): # paths may already contain ':' as separator tokens = ':'.join(paths).split(':') if os.sep == '/': return tokens # Fix paths split like 'c:\temp' -> 'c', '\temp' ret = [] drive = '' for item in tokens: item = item.replace('/', '\\') if drive and item.startswith('\\'): ret.append('%s:%s' % (drive, item)) drive = '' continue if drive: ret.append(drive) drive = '' if len(item) == 1 and item in string.letters: drive = item else: ret.append(item) if drive: ret.append(drive) return ret def _get_available_escapes(self): names = sorted(ESCAPES.keys(), key=str.lower) return ', '.join('%s (%s)' % (n, ESCAPES[n]) for n in names) def _raise_help(self): msg = self._usage if self._version: msg = msg.replace('<VERSION>', self._version) def replace_escapes(res): escapes = 'Available escapes: ' + self._get_available_escapes() lines = textwrap.wrap(escapes, width=len(res.group(2))) indent = ' ' * len(res.group(1)) return '\n'.join(indent + line for line in lines) msg = re.sub('( *)(<-+ESCAPES-+>)', replace_escapes, msg) raise Information(msg) def _raise_version(self): if not self._version: raise FrameworkError('Version not set') raise Information('%s %s' % (self._name, self._version)) def _raise_option_multiple_times_in_usage(self, opt): raise FrameworkError("Option '%s' multiple times in usage" % opt)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os.path from robot.variables import Variables from robot.errors import DataError, FrameworkError from robot import utils PRE = '<!-- ' POST = ' -->' class Namespace(Variables): def __init__(self, **kwargs): Variables.__init__(self, ['$']) for key, value in kwargs.items(): self['${%s}' % key] = value class Template: def __init__(self, path=None, template=None, functions=None): if path is None and template is None: raise FrameworkError("Either 'path' or 'template' must be given") if template is None: tfile = open(path) template = tfile.read() tfile.close() self.parent_dir = os.path.dirname(utils.abspath(path)) else: self.parent_dir = None self._template = template self._functions = functions or utils.NormalizedDict() # True means handlers for more than single line self._handlers = { 'INCLUDE': (self._handle_include, False), 'IMPORT': (self._handle_import, False), 'CALL': (self._handle_call, False), 'IF': (self._handle_if, True), 'FOR': (self._handle_for, True), 'FUNCTION': (self._handle_function, True) } def generate(self, namespace, output=None): self._namespace = namespace return self._process(self._template, output) def _process(self, template, output=None): result = Result(output) lines = template.splitlines() while lines: line = lines.pop(0) try: result.add(self._process_line(line.strip(), lines)) except ValueError: result.add(self._handle_variables(line)) return result.get_result() def _process_line(self, line, lines): if not line.startswith(PRE) and line.endswith(POST): raise ValueError name, expression = line[len(PRE):-len(POST)].split(' ', 1) try: handler, multiline = self._handlers[name] except KeyError: raise ValueError if multiline: block_lines = self._get_multi_line_block(name, lines) return handler(expression, block_lines) return handler(expression) def _get_multi_line_block(self, name, lines): """Returns string containing lines before END matching given name. Removes the returned lines from given 'lines'. """ block_lines = [] endline = '%sEND %s%s' % (PRE, name, POST) while True: try: line = lines.pop(0) except IndexError: raise DataError('Invalid template: No END for %s' % name) if line.strip() == endline: break block_lines.append(line) return block_lines def _handle_variables(self, template): return self._namespace.replace_string(template) def _handle_include(self, path): included_file = open(self._get_full_path(path)) include = included_file.read() included_file.close() return self._handle_variables(include) def _handle_import(self, path): imported_file = open(self._get_full_path(path)) self._process(imported_file.read()) imported_file.close() return None def _handle_for(self, expression, block_lines): block = '\n'.join(block_lines) result = [] var_name, _, value_list = expression.split(' ', 2) namespace = self._namespace.copy() for value in namespace.replace_scalar(value_list): namespace[var_name] = value temp = Template(template=block, functions=self._functions) ret = temp.generate(namespace) if ret: result.append(ret) if not result: return None return '\n'.join(result) def _handle_if(self, expression, block_lines): expression = self._handle_variables(expression) if_block, else_block = self._get_if_and_else_blocks(block_lines) result = eval(expression) and if_block or else_block if not result: return None return self._process('\n'.join(result)) def _get_if_and_else_blocks(self, block_lines): else_line = PRE + 'ELSE' + POST if_block = [] else_block = [] block = if_block for line in block_lines: if line.strip() == else_line: block = else_block else: block.append(line) return if_block, else_block def _handle_call(self, expression): func_tokens = expression.split() name = func_tokens[0] args = func_tokens[1:] namespace = self._namespace.copy() try: func_args, func_body = self._functions[name] except KeyError: raise DataError("Non-existing function '%s', available: %s" % (name, self._functions.keys())) for key, value in zip(func_args, args): namespace[key] = namespace.replace_string(value) temp = Template(template=func_body, functions=self._functions) return temp.generate(namespace) def _handle_function(self, signature, block_lines): signature_tokens = signature.split() name = signature_tokens[0] args = signature_tokens[1:] self._functions[name] = (args, '\n'.join(block_lines)) def _get_full_path(self, path): if self.parent_dir is None: raise FrameworkError('Parent directory is None. Probably template ' 'was string and other files was referred. ' 'That is not supported.') abs_path = os.path.join(self.parent_dir, path) if os.path.exists(abs_path): return abs_path else: raise DataError("File '%s' does not exist." % abs_path) class Result: def __init__(self, output=None): self._output = output self._result = [] def add(self, text): if text is not None: if self._output is None: self._result.append(text) else: self._output.write(text.encode('UTF-8') + '\n') def get_result(self): if not self._result: return None return '\n'.join(self._result)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import etreewrapper class DomWrapper(object): def __init__(self, path=None, string=None, node=None): """Initialize by giving 'path' to an xml file or xml as a 'string'. Alternative initialization by giving dom 'node' ment to be used only internally. 'path' may actually also be an already opened file object (or anything accepted by ElementTree.parse). """ node = etreewrapper.get_root(path, string, node) self.source = path self.name = node.tag self.attrs = dict(node.items()) self.text = node.text or '' self.children = [DomWrapper(path, node=child) for child in list(node)] def get_nodes(self, path): """Returns a list of descendants matching given 'path'. Path must be a string in format 'child_name/grandchild_name/etc'. No slash is allowed at the beginning or end of the path string. Returns an empty list if no matching descendants found and raises AttributeError if path is invalid. """ if not isinstance(path, basestring) \ or path == '' or path[0] == '/' or path[-1] == '/': raise AttributeError("Invalid path '%s'" % path) matches = [] for child in self.children: matches += child._get_matching_elements(path.split('/')) return matches def _get_matching_elements(self, tokens): if self.name != tokens[0]: return [] elif len(tokens) == 1: return [self] else: matches = [] for child in self.children: matches += child._get_matching_elements(tokens[1:]) return matches def get_node(self, path): """Similar as get_nodes but checks that exactly one node is found. Node is returned as is (i.e. not in a list) and AttributeError risen if no match or more than one match found. """ nodes = self.get_nodes(path) if len(nodes) == 0: raise AttributeError("No nodes matching path '%s' found" % path) if len(nodes) > 1: raise AttributeError("Multiple nodes matching path '%s' found" % path) return nodes[0] def get_attr(self, name, default=None): """Helper for getting node's attributes. Otherwise equivalent to 'node.attrs.get(name, default)' but raises an AttributeError if no value found and no default given. """ ret = self.attrs.get(name, default) if ret is None: raise AttributeError("No attribute '%s' found" % name) return ret def __getattr__(self, name): """Syntactic sugar for get_nodes (e.g. dom.elem[0].subelem). Differs from get_nodes so that if not matching nodes are found an AttributeError is risen instead of returning an empty list. """ nodes = self.get_nodes(name) if not nodes: raise AttributeError("No nodes matching path '%s' found" % name) return nodes def __getitem__(self, name): """Syntactic sugar for get_node (e.g. dom['elem/subelem'])""" try: return self.get_node(name) except AttributeError: raise IndexError("No node '%s' found" % name) def __repr__(self): """Return node name. Mainly for debugging purposes.""" return self.name
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import urllib from encoding import decode_from_file_system if os.sep == '\\': _CASE_INSENSITIVE_FILESYSTEM = True else: try: _CASE_INSENSITIVE_FILESYSTEM = os.listdir('/tmp') == os.listdir('/TMP') except OSError: _CASE_INSENSITIVE_FILESYSTEM = False def normpath(path): """Returns path in normalized and absolute format. On case-insensitive file systems the path is also case normalized. If that is not desired, abspath should be used instead. """ path = abspath(path) if _CASE_INSENSITIVE_FILESYSTEM: path = path.lower() return path def abspath(path): """Replacement for os.path.abspath with some bug fixes and enhancements. 1) Converts non-Unicode paths to Unicode using file system encoding 2) At least Jython 2.5.1 on Windows returns wrong path with 'c:'. 3) Python until 2.6.5 and at least Jython 2.5.1 don't handle non-ASCII characters in the working directory: http://bugs.python.org/issue3426 """ if not isinstance(path, unicode): path = decode_from_file_system(path) if os.sep == '\\' and len(path) == 2 and path[1] == ':': return path + '\\' return os.path.normpath(os.path.join(os.getcwdu(), path)) def get_link_path(target, base): """Returns a relative path to a target from a base. If base is an existing file, then its parent directory is considered. Otherwise, base is assumed to be a directory. Rationale: os.path.relpath is not available before Python 2.6 """ pathname = _get_pathname(target, base) url = urllib.pathname2url(pathname.encode('UTF-8')) if os.path.isabs(pathname): pre = url.startswith('/') and 'file:' or 'file:///' url = pre + url # Want consistent url on all platforms/interpreters return url.replace('%5C', '/').replace('%3A', ':').replace('|', ':') def _get_pathname(target, base): target = abspath(target) base = abspath(base) if os.path.isfile(base): base = os.path.dirname(base) if base == target: return os.path.basename(target) base_drive, base_path = os.path.splitdrive(base) # if in Windows and base and link on different drives if os.path.splitdrive(target)[0] != base_drive: return target common_len = len(_common_path(base, target)) if base_path == os.sep: return target[common_len:] if common_len == len(base_drive) + len(os.sep): common_len -= len(os.sep) dirs_up = os.sep.join([os.pardir] * base[common_len:].count(os.sep)) return os.path.join(dirs_up, target[common_len + len(os.sep):]) def _common_path(p1, p2): """Returns the longest path common to p1 and p2. Rationale: as os.path.commonprefix is character based, it doesn't consider path separators as such, so it may return invalid paths: commonprefix(('/foo/bar/', '/foo/baz.txt')) -> '/foo/ba' (instead of /foo) """ while p1 and p2: if p1 == p2: return p1 if len(p1) > len(p2): p1 = os.path.dirname(p1) else: p2 = os.path.dirname(p2) return ''
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A module to handle different character widths on the console. Some East Asian characters have width of two on console, and combining characters themselves take no extra space. See issue 604 [1] for more details. It also contains `generate_wild_chars.py` script that was originally used to create the East Asian wild character map. Big thanks for xieyanbo for the script and the original patch. Note that Python's `unicodedata` module is not used here because importing it takes several seconds on Jython. [1] http://code.google.com/p/robotframework/issues/detail?id=604 """ def get_char_width(char): char = ord(char) if _char_in_map(char, _COMBINING_CHARS): return 0 if _char_in_map(char, _EAST_ASIAN_WILD_CHARS): return 2 return 1 def _char_in_map(char, map): for begin, end in map: if char < begin: break if begin <= char <= end: return True return False _COMBINING_CHARS = [(768,879)] _EAST_ASIAN_WILD_CHARS = [ (888, 889), (896, 899), (909, 909), (1316, 1328), (1368, 1368), (1416, 1416), (1420, 1424), (1481, 1487), (1516, 1519), (1526, 1535), (1541, 1541), (1565, 1565), (1631, 1631), (1867, 1868), (1971, 1983), (2044, 2304), (2363, 2363), (2383, 2383), (2390, 2391), (2420, 2426), (2436, 2436), (2446, 2446), (2450, 2450), (2481, 2481), (2484, 2485), (2491, 2491), (2502, 2502), (2506, 2506), (2512, 2518), (2521, 2523), (2532, 2533), (2556, 2560), (2571, 2574), (2578, 2578), (2609, 2609), (2615, 2615), (2619, 2619), (2627, 2630), (2634, 2634), (2639, 2640), (2643, 2648), (2655, 2661), (2679, 2688), (2702, 2702), (2729, 2729), (2740, 2740), (2747, 2747), (2762, 2762), (2767, 2767), (2770, 2783), (2789, 2789), (2802, 2816), (2829, 2830), (2834, 2834), (2865, 2865), (2874, 2875), (2886, 2886), (2890, 2890), (2895, 2901), (2905, 2907), (2916, 2917), (2931, 2945), (2955, 2957), (2966, 2968), (2973, 2973), (2977, 2978), (2982, 2983), (2988, 2989), (3003, 3005), (3012, 3013), (3022, 3023), (3026, 3030), (3033, 3045), (3068, 3072), (3085, 3085), (3113, 3113), (3130, 3132), (3145, 3145), (3151, 3156), (3162, 3167), (3173, 3173), (3185, 3191), (3201, 3201), (3213, 3213), (3241, 3241), (3258, 3259), (3273, 3273), (3279, 3284), (3288, 3293), (3300, 3301), (3315, 3329), (3341, 3341), (3369, 3369), (3387, 3388), (3401, 3401), (3407, 3414), (3417, 3423), (3429, 3429), (3447, 3448), (3457, 3457), (3479, 3481), (3516, 3516), (3519, 3519), (3528, 3529), (3532, 3534), (3543, 3543), (3553, 3569), (3574, 3584), (3644, 3646), (3677, 3712), (3717, 3718), (3723, 3724), (3727, 3731), (3744, 3744), (3750, 3750), (3753, 3753), (3770, 3770), (3775, 3775), (3783, 3783), (3791, 3791), (3803, 3803), (3807, 3839), (3949, 3952), (3981, 3983), (4029, 4029), (4053, 4095), (4251, 4253), (4295, 4303), (4350, 4447), (4516, 4519), (4603, 4607), (4686, 4687), (4697, 4697), (4703, 4703), (4750, 4751), (4790, 4791), (4801, 4801), (4807, 4807), (4881, 4881), (4887, 4887), (4956, 4958), (4990, 4991), (5019, 5023), (5110, 5120), (5752, 5759), (5790, 5791), (5874, 5887), (5909, 5919), (5944, 5951), (5973, 5983), (6001, 6001), (6005, 6015), (6111, 6111), (6123, 6127), (6139, 6143), (6170, 6175), (6265, 6271), (6316, 6399), (6430, 6431), (6445, 6447), (6461, 6463), (6466, 6467), (6511, 6511), (6518, 6527), (6571, 6575), (6603, 6607), (6619, 6621), (6685, 6685), (6689, 6911), (6989, 6991), (7038, 7039), (7084, 7085), (7099, 7167), (7225, 7226), (7243, 7244), (7297, 7423), (7656, 7677), (7959, 7959), (7967, 7967), (8007, 8007), (8015, 8015), (8026, 8026), (8030, 8030), (8063, 8063), (8133, 8133), (8149, 8149), (8176, 8177), (8191, 8191), (8294, 8297), (8307, 8307), (8341, 8351), (8375, 8399), (8434, 8447), (8529, 8530), (8586, 8591), (9002, 9002), (9193, 9215), (9256, 9279), (9292, 9311), (9887, 9887), (9918, 9919), (9925, 9984), (9994, 9995), (10060, 10060), (10067, 10069), (10079, 10080), (10134, 10135), (10175, 10175), (10189, 10191), (11086, 11087), (11094, 11263), (11359, 11359), (11390, 11391), (11500, 11512), (11559, 11567), (11623, 11630), (11633, 11647), (11672, 11679), (11695, 11695), (11711, 11711), (11727, 11727), (11743, 11743), (11826, 12350), (12353, 19903), (19969, 42239), (42541, 42559), (42593, 42593), (42613, 42619), (42649, 42751), (42894, 43002), (43053, 43071), (43129, 43135), (43206, 43213), (43227, 43263), (43349, 43358), (43361, 43519), (43576, 43583), (43599, 43599), (43611, 43611), (43617, 55295), (63745, 64255), (64264, 64274), (64281, 64284), (64317, 64317), (64322, 64322), (64434, 64466), (64833, 64847), (64913, 64913), (64969, 65007), (65023, 65023), (65041, 65055), (65064, 65135), (65277, 65278), (65281, 65376), (65472, 65473), (65481, 65481), (65489, 65489), (65497, 65497), (65502, 65511), (65520, 65528), (65535, 65535), ]
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from UserDict import UserDict _WHITESPACE_REGEXP = re.compile('\s+') def normalize(string, ignore=[], caseless=True, spaceless=True): if spaceless: string = _WHITESPACE_REGEXP.sub('', string) if caseless: string = string.lower() ignore = [ ign.lower() for ign in ignore ] for ign in ignore: string = string.replace(ign, '') return string def normalize_tags(tags): """Removes duplicates (normalized) and empty tags and sorts tags""" ret = [] dupes = NormalizedDict({'': 1}) for tag in tags: if not dupes.has_key(tag): ret.append(tag) dupes[tag] = 1 ret.sort(lambda x, y: cmp(normalize(x), normalize(y))) return ret class NormalizedDict(UserDict): def __init__(self, initial={}, ignore=[], caseless=True, spaceless=True): UserDict.__init__(self) self._keys = {} self._normalize = lambda s: normalize(s, ignore, caseless, spaceless) for key, value in initial.items(): self[key] = value def update(self, dict=None, **kwargs): if dict: UserDict.update(self, dict) for key in dict: self._add_key(key) if kwargs: self.update(kwargs) def _add_key(self, key): nkey = self._normalize(key) self._keys.setdefault(nkey, key) return nkey def __setitem__(self, key, value): nkey = self._add_key(key) self.data[nkey] = value set = __setitem__ def __getitem__(self, key): return self.data[self._normalize(key)] def __delitem__(self, key): nkey = self._normalize(key) del self.data[nkey] del self._keys[nkey] def get(self, key, default=None): try: return self.__getitem__(key) except KeyError: return default def has_key(self, key): return self.data.has_key(self._normalize(key)) __contains__ = has_key def keys(self): return self._keys.values() def __iter__(self): return self._keys.itervalues() def items(self): return [ (key, self[key]) for key in self.keys() ] def copy(self): copy = UserDict.copy(self) copy._keys = self._keys.copy() return copy def __str__(self): return str(dict(self.items()))
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os from unic import unic def decode_output(string): """Decodes string from console encoding to Unicode.""" if _output_encoding: return unic(string, _output_encoding) return string def encode_output(string, errors='replace'): """Encodes string from Unicode to console encoding.""" # http://ironpython.codeplex.com/workitem/29487 if sys.platform == 'cli': return string return string.encode(_output_encoding, errors) def decode_from_file_system(string): """Decodes path from file system to Unicode.""" encoding = sys.getfilesystemencoding() if sys.platform.startswith('java'): # http://bugs.jython.org/issue1592 from java.lang import String string = String(string) return unic(string, encoding) if encoding else unic(string) def _get_output_encoding(): # Jython is buggy on Windows: http://bugs.jython.org/issue1568 if os.sep == '\\' and sys.platform.startswith('java'): return 'cp437' # Default DOS encoding encoding = _get_encoding_from_std_streams() if encoding: return encoding if os.sep == '/': return _read_encoding_from_unix_env() return 'cp437' # Default DOS encoding def _get_encoding_from_std_streams(): # Stream may not have encoding attribute if it is intercepted outside RF # in Python. Encoding is None if process's outputs are redirected. return getattr(sys.__stdout__, 'encoding', None) \ or getattr(sys.__stderr__, 'encoding', None) \ or getattr(sys.__stdin__, 'encoding', None) def _read_encoding_from_unix_env(): for name in 'LANG', 'LC_CTYPE', 'LANGUAGE', 'LC_ALL': try: # Encoding can be in format like `UTF-8` or `en_US.UTF-8` encoding = os.environ[name].split('.')[-1] 'testing that encoding is valid'.encode(encoding) except (KeyError, LookupError): pass else: return encoding return 'ascii' _output_encoding = _get_output_encoding()
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unic import unic """Convenience functions for testing both in unit and higher levels. Benefits: - Integrates 100% with unittest (see example below) - Can be easily used without unittest (using unittest.TestCase when you only need convenient asserts is not so nice) - Saved typing and shorter lines because no need to have 'self.' before asserts. These are static functions after all so that is OK. - All 'equals' methods (by default) report given values even if optional message given. This behavior can be controlled with the optional values argument. Drawbacks: - unittest is not able to filter as much non-interesting traceback away as with its own methods because AssertionErrors occur outside Most of the functions are copied more or less directly from unittest.TestCase which comes with the following license. Further information about unittest in general can be found from http://pyunit.sourceforge.net/. This module can be used freely in same terms as unittest. ----[unittest licence]------------------------------------------------ Copyright (c) 1999-2003 Steve Purcell This module is free software, and you may redistribute it and/or modify it under the same terms as Python itself, so long as this copyright message and disclaimer are retained in their original form. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. ----[example usage]--------------------------------------------------- import unittest from robot.util.asserts import * class MyTests(unittest.TestCase): def test_old_style(self): self.assertEquals(1, 2, 'my msg') def test_new_style(self): assert_equals(1, 2, 'my msg') ----[example output]-------------------------------------------------- FF ====================================================================== FAIL: test_old_style (__main__.MyTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "example.py", line 7, in test_old_style self.assertEquals(1, 2, 'my msg') AssertionError: my msg ====================================================================== FAIL: test_new_style (__main__.MyTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "example.py", line 10, in test_new_style assert_equals(1, 2, 'my msg') File "/path/to/robot/asserts.py", line 142, in fail_unless_equal _report_unequality_failure(first, second, msg, values, '!=') File "/path/to/robot/src/robot/asserts.py", line 209, in _report_unequality_failure raise _report_failure(msg) File "/path/to/robot/src/robot/asserts.py", line 200, in _report_failure raise AssertionError(msg) AssertionError: my msg: 1 != 2 ---------------------------------------------------------------------- Ran 2 tests in 0.000s FAILED (failures=2) """ def fail(msg=None): """Fail test immediately with the given message.""" _report_failure(msg) def error(msg=None): """Error test immediately with the given message.""" _report_error(msg) def fail_if(expr, msg=None): """Fail the test if the expression is True.""" if expr: _report_failure(msg) def fail_unless(expr, msg=None): """Fail the test unless the expression is True.""" if not expr: _report_failure(msg) def fail_if_none(obj, msg=None, values=True): """Fail the test if given object is None.""" _msg = 'is None' if obj is None: if msg is None: msg = _msg elif values is True: msg = '%s: %s' % (msg, _msg) _report_failure(msg) def fail_unless_none(obj, msg=None, values=True): """Fail the test if given object is not None.""" _msg = '%r is not None' % obj if obj is not None: if msg is None: msg = _msg elif values is True: msg = '%s: %s' % (msg, _msg) _report_failure(msg) def fail_unless_raises(exc_class, callable_obj, *args, **kwargs): """Fail unless an exception of class exc_class is thrown by callable_obj. callable_obj is invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. """ try: callable_obj(*args, **kwargs) except exc_class: return else: if hasattr(exc_class,'__name__'): exc_name = exc_class.__name__ else: exc_name = str(exc_class) _report_failure('%s not raised' % exc_name) def fail_unless_raises_with_msg(exc_class, expected_msg, callable_obj, *args, **kwargs): """Similar to fail_unless_raises but also checks the exception message.""" try: callable_obj(*args, **kwargs) except exc_class, err: assert_equal(expected_msg, unic(err), 'Correct exception but wrong message') else: if hasattr(exc_class,'__name__'): exc_name = exc_class.__name__ else: exc_name = str(exc_class) _report_failure('%s not raised' % exc_name) def fail_unless_equal(first, second, msg=None, values=True): """Fail if given objects are unequal as determined by the '==' operator.""" if not first == second: _report_unequality_failure(first, second, msg, values, '!=') def fail_if_equal(first, second, msg=None, values=True): """Fail if given objects are equal as determined by the '==' operator.""" if first == second: _report_unequality_failure(first, second, msg, values, '==') def fail_unless_almost_equal(first, second, places=7, msg=None, values=True): """Fail if the two objects are unequal after rounded to given places. Unequality is determined by object's difference rounded to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). """ if round(second - first, places) != 0: extra = 'within %r places' % places _report_unequality_failure(first, second, msg, values, '!=', extra) def fail_if_almost_equal(first, second, places=7, msg=None, values=True): """Fail if the two objects are unequal after rounded to given places. Equality is determined by object's difference rounded to to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). """ if round(second-first, places) == 0: extra = 'within %r places' % places _report_unequality_failure(first, second, msg, values, '==', extra) # Synonyms for assertion methods assert_equal = assert_equals = fail_unless_equal assert_not_equal = assert_not_equals = fail_if_equal assert_almost_equal = assert_almost_equals = fail_unless_almost_equal assert_not_almost_equal = assert_not_almost_equals = fail_if_almost_equal assert_raises = fail_unless_raises assert_raises_with_msg = fail_unless_raises_with_msg assert_ = assert_true = fail_unless assert_false = fail_if assert_none = fail_unless_none assert_not_none = fail_if_none # Helpers def _report_failure(msg): if msg is None: raise AssertionError() raise AssertionError(msg) def _report_error(msg): if msg is None: raise Exception() raise Exception(msg) def _report_unequality_failure(obj1, obj2, msg, values, delim, extra=None): if not msg: msg = _get_default_message(obj1, obj2, delim) elif values: msg = '%s: %s' % (msg, _get_default_message(obj1, obj2, delim)) if values and extra: msg += ' ' + extra _report_failure(msg) def _get_default_message(obj1, obj2, delim): if delim == '!=' and unicode(obj1) == unicode(obj2): return '%s (%s) != %s (%s)' % (obj1, _type_name(obj1), obj2, _type_name(obj2)) return '%s %s %s' % (obj1, delim, obj2) def _type_name(val): known_types = {int: 'number', long: 'number', float: 'number', str: 'string', unicode: 'string', bool: 'boolean'} return known_types.get(type(val), type(val).__name__)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from normalizing import normalize _match_pattern_tokenizer = re.compile('(\*|\?)') def eq(str1, str2, ignore=[], caseless=True, spaceless=True): str1 = normalize(str1, ignore, caseless, spaceless) str2 = normalize(str2, ignore, caseless, spaceless) return str1 == str2 def eq_any(str_, str_list, ignore=[], caseless=True, spaceless=True): str_ = normalize(str_, ignore, caseless, spaceless) for s in str_list: if str_ == normalize(s, ignore, caseless, spaceless): return True return False def matches(string, pattern, ignore=[], caseless=True, spaceless=True): string = normalize(string, ignore, caseless, spaceless) pattern = normalize(pattern, ignore, caseless, spaceless) regexp = _get_match_regexp(pattern) return re.match(regexp, string, re.DOTALL) is not None def _get_match_regexp(pattern): regexp = [] for token in _match_pattern_tokenizer.split(pattern): if token == '*': regexp.append('.*') elif token == '?': regexp.append('.') else: regexp.append(re.escape(token)) return '^%s$' % ''.join(regexp) def matches_any(string, patterns, ignore=[], caseless=True, spaceless=True): for pattern in patterns: if matches(string, pattern, ignore, caseless, spaceless): return True return False
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unic import unic from misc import seq2str2 from charwidth import get_char_width _MAX_ASSIGN_LENGTH = 200 _MAX_ERROR_LINES = 40 _MAX_ERROR_LINE_LENGTH = 78 _ERROR_CUT_EXPLN = (' [ Message content over the limit has been removed. ]') def cut_long_message(msg): lines = msg.splitlines() lengths = _count_line_lenghts(lines) if sum(lengths) <= _MAX_ERROR_LINES: return msg start = _prune_excess_lines(lines, lengths) end = _prune_excess_lines(lines, lengths, True) return '\n'.join(start + [_ERROR_CUT_EXPLN] + end) def _prune_excess_lines(lines, lengths, from_end=False): if from_end: lines.reverse() lengths.reverse() ret = [] total = 0 limit = _MAX_ERROR_LINES/2 for line, length in zip(lines[:limit], lengths[:limit]): if total + length >= limit: ret.append(_cut_long_line(line, total, from_end)) break total += length ret.append(line) if from_end: ret.reverse() return ret def _cut_long_line(line, used, from_end): available_lines = _MAX_ERROR_LINES/2 - used available_chars = available_lines * _MAX_ERROR_LINE_LENGTH - 3 if len(line) > available_chars: if not from_end: line = line[:available_chars] + '...' else: line = '...' + line[-available_chars:] return line def _count_line_lenghts(lines): return [ _count_virtual_line_length(line) for line in lines ] def _count_virtual_line_length(line): length = len(line) / _MAX_ERROR_LINE_LENGTH if not len(line) % _MAX_ERROR_LINE_LENGTH == 0 or len(line) == 0: length += 1 return length def format_assign_message(variable, value, cut_long=True): value = unic(value) if variable.startswith('$') else seq2str2(value) if cut_long and len(value) > _MAX_ASSIGN_LENGTH: value = value[:_MAX_ASSIGN_LENGTH] + '...' return '%s = %s' % (variable, value) def get_console_length(text): return sum(get_char_width(char) for char in text) def pad_console_length(text, width, cut_left=False): if width < 5: width = 5 diff = get_console_length(text) - width if diff <= 0: return _pad_width(text, width) if cut_left: return _pad_width('...'+_lose_width_left(text, diff+3), width) return _pad_width(_lose_width_right(text, diff+3)+'...', width) def _pad_width(text, width): more = width - get_console_length(text) return text + ' ' * more def _lose_width_right(text, diff): return _lose_width(text, diff, -1, slice(None, -1)) def _lose_width_left(text, diff): return _lose_width(text, diff, 0, slice(1, None)) def _lose_width(text, diff, index, slice): lost = 0 while lost < diff: lost += get_console_length(text[index]) text = text[slice] return text
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argumentparser import ArgumentParser from connectioncache import ConnectionCache from domwrapper import DomWrapper from encoding import decode_output, encode_output, decode_from_file_system from error import (get_error_message, get_error_details, ErrorDetails, RERAISED_EXCEPTIONS) from escaping import escape, unescape from htmlutils import html_format, html_escape, html_attr_escape from htmlwriter import HtmlWriter from importing import simple_import, import_ from match import eq, eq_any, matches, matches_any from misc import plural_or_not, printable_name, seq2str, seq2str2 from normalizing import normalize, normalize_tags, NormalizedDict from robotpath import normpath, abspath, get_link_path from robottime import (get_timestamp, get_start_timestamp, format_time, get_time, get_elapsed_time, elapsed_time_to_string, timestr_to_secs, secs_to_timestr, secs_to_timestamp, timestamp_to_secs, parse_time) from text import (cut_long_message, format_assign_message, pad_console_length, get_console_length) from unic import unic, safe_repr from xmlwriter import XmlWriter import sys is_jython = sys.platform.startswith('java') del sys
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unic import unic def printable_name(string, code_style=False): """Generates and returns printable name from the given string. Examples: 'simple' -> 'Simple' 'name with spaces' -> 'Name With Spaces' 'more spaces' -> 'More Spaces' 'Cases AND spaces' -> 'Cases AND Spaces' '' -> '' If 'code_style' is True: 'mixedCAPSCamel' -> 'Mixed CAPS Camel' 'camelCaseName' -> 'Camel Case Name' 'under_score_name' -> 'Under Score Name' 'under_and space' -> 'Under And Space' 'miXed_CAPS_nAMe' -> 'MiXed CAPS NAMe' '' -> '' """ if code_style: string = string.replace('_', ' ') parts = string.split() if len(parts) == 0: return '' elif len(parts) == 1 and code_style: parts = _splitCamelCaseString(parts[0]) parts = [ part[0].upper() + part[1:] for part in parts if part != '' ] return ' '.join(parts) def _splitCamelCaseString(string): parts = [] current_part = [] string = ' ' + string + ' ' # extra spaces make going through string easier for i in range(1, len(string)-1): # on 1st/last round prev/next is ' ' and char is 1st/last real char prev, char, next = string[i-1:i+2] if _isWordBoundary(prev, char, next): parts.append(''.join(current_part)) current_part = [ char ] else: current_part.append(char) parts.append(''.join(current_part)) # append last part return parts def _isWordBoundary(prev, char, next): if char.isupper(): return (prev.islower() or next.islower()) and prev.isalnum() if char.isdigit(): return prev.isalpha() return prev.isdigit() def plural_or_not(item): count = item if isinstance(item, (int, long)) else len(item) return '' if count == 1 else 's' def seq2str(sequence, quote="'", sep=', ', lastsep=' and '): """Returns sequence in format 'item 1', 'item 2' and 'item 3'""" quote_elem = lambda string: quote + unic(string) + quote if len(sequence) == 0: return '' if len(sequence) == 1: return quote_elem(sequence[0]) elems = [quote_elem(s) for s in sequence[:-2]] elems.append(quote_elem(sequence[-2]) + lastsep + quote_elem(sequence[-1])) return sep.join(elems) def seq2str2(sequence): """Returns sequence in format [ item 1 | item 2 | ... ] """ if not sequence: return '[ ]' return '[ %s ]' % ' | '.join(unic(item) for item in sequence)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os.path import sys import re import traceback from unic import unic from robot.errors import DataError, TimeoutError, RemoteError RERAISED_EXCEPTIONS = (KeyboardInterrupt, SystemExit, MemoryError) if sys.platform.startswith('java'): from java.io import StringWriter, PrintWriter from java.lang import Throwable, OutOfMemoryError RERAISED_EXCEPTIONS += (OutOfMemoryError,) _java_trace_re = re.compile('^\s+at (\w.+)') _ignored_java_trace = ('org.python.', 'robot.running.', 'robot$py.', 'sun.reflect.', 'java.lang.reflect.') _ignore_trace_until = (os.path.join('robot','running','handlers.py'), '<lambda>') _generic_exceptions = ('AssertionError', 'AssertionFailedError', 'Exception', 'Error', 'RuntimeError', 'RuntimeException', 'DataError', 'TimeoutError', 'RemoteError') def get_error_message(): """Returns error message of the last occurred exception. This method handles also exceptions containing unicode messages. Thus it MUST be used to get messages from all exceptions originating outside the framework. """ return ErrorDetails().message def get_error_details(): """Returns error message and details of the last occurred exception. """ dets = ErrorDetails() return dets.message, dets.traceback class ErrorDetails(object): """This class wraps the last occurred exception It has attributes message, traceback and error, where message contains type and message of the original error, traceback it's contains traceback (or stack trace in case of Java exception) and error contains the original error instance This class handles also exceptions containing unicode messages. Thus it MUST be used to get messages from all exceptions originating outside the framework. """ def __init__(self): exc_type, exc_value, exc_traceback = sys.exc_info() if exc_type in RERAISED_EXCEPTIONS: raise exc_value if _is_java_exception(exc_value): self.message = _get_java_message(exc_type, exc_value) self.traceback = _get_java_details(exc_value) else: self.message = _get_python_message(exc_type, exc_value) self.traceback = _get_python_details(exc_value, exc_traceback) self.error = exc_value def _is_java_exception(exc): return sys.platform.startswith('java') and isinstance(exc, Throwable) def _get_name(exc_type): try: return exc_type.__name__ except AttributeError: return unic(exc_type) def _get_java_message(exc_type, exc_value): exc_name = _get_name(exc_type) # OOME.getMessage and even toString seem to throw NullPointerException if exc_type is OutOfMemoryError: exc_msg = str(exc_value) else: exc_msg = exc_value.getMessage() return _format_message(exc_name, exc_msg, java=True) def _get_java_details(exc_value): # OOME.printStackTrace seems to throw NullPointerException if isinstance(exc_value, OutOfMemoryError): return '' output = StringWriter() exc_value.printStackTrace(PrintWriter(output)) lines = [ line for line in output.toString().splitlines() if line and not _is_ignored_stacktrace_line(line) ] details = '\n'.join(lines) msg = unic(exc_value.getMessage() or '') if msg: details = details.replace(msg, '', 1) return details def _is_ignored_stacktrace_line(line): res = _java_trace_re.match(line) if res is None: return False location = res.group(1) for entry in _ignored_java_trace: if location.startswith(entry): return True return False def _get_python_message(exc_type, exc_value): # If exception is a "string exception" without a message exc_value is None if exc_value is None: return unic(exc_type) name = _get_name(exc_type) try: msg = unicode(exc_value) except UnicodeError: # Happens if message is Unicode and version < 2.6 msg = ' '.join(unic(a) for a in exc_value.args) return _format_message(name, msg) def _get_python_details(exc_value, exc_tb): if isinstance(exc_value, (DataError, TimeoutError)): return '' if isinstance(exc_value, RemoteError): return exc_value.traceback tb = traceback.extract_tb(exc_tb) for row, (path, _, func, _) in enumerate(tb): if path.endswith(_ignore_trace_until[0]) and func == _ignore_trace_until[1]: tb = tb[row+1:] break details = 'Traceback (most recent call last):\n' \ + ''.join(traceback.format_list(tb)) return details.strip() def _format_message(name, message, java=False): message = unic(message or '') if java: message = _clean_up_java_message(message, name) name = name.split('.')[-1] # Use only last part of the name if message == '': return name if name in _generic_exceptions: return message return '%s: %s' % (name, message) def _clean_up_java_message(msg, name): # Remove possible stack trace from messages lines = msg.splitlines() while lines: if _java_trace_re.match(lines[-1]): lines.pop() else: break msg = '\n'.join(lines) # Remove possible exception name from the message tokens = msg.split(':', 1) if len(tokens) == 2 and tokens[0] == name: msg = tokens[1] return msg.strip()
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from threading import Event if sys.platform.startswith('java'): from java.lang import Thread, Runnable else: from stoppablethread import Thread Runnable = object class ThreadedRunner(Runnable): def __init__(self, runnable, args=None, kwargs=None, notifier=None): self._runnable = lambda: runnable(*(args or ()), **(kwargs or {})) self._notifier = Event() self._result = None self._error = None self._traceback = None self._thread = None def run(self): try: self._result = self._runnable() except: self._error, self._traceback = sys.exc_info()[1:] self._notifier.set() __call__ = run def run_in_thread(self, timeout): self._thread = Thread(self) self._thread.setDaemon(True) self._thread.start() self._notifier.wait(timeout) return self._notifier.isSet() def get_result(self): if self._error: raise self._error, None, self._traceback return self._result def stop_thread(self): self._thread.stop()
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from xml.sax.saxutils import XMLGenerator from xml.sax.xmlreader import AttributesImpl from abstractxmlwriter import AbstractXmlWriter class XmlWriter(AbstractXmlWriter): def __init__(self, path): self.path = path self._output = open(path, 'wb') self._writer = XMLGenerator(self._output, encoding='UTF-8') self._writer.startDocument() self.closed = False def _start(self, name, attrs): self._writer.startElement(name, AttributesImpl(attrs)) def _content(self, content): self._writer.characters(content) def _end(self, name): self._writer.endElement(name) # Workaround for http://ironpython.codeplex.com/workitem/29474 if sys.platform == 'cli': def _escape(self, content): return AbstractXmlWriter._escape(self, content).encode('UTF-8')
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unic import unic _ILLEGAL_CHARS_IN_XML = u'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e' \ + u'\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\ufffe' class AbstractXmlWriter: def start(self, name, attributes={}, newline=True): self._start(name, self._escape_attrs(attributes)) if newline: self.content('\n') def _start(self, name, attrs): raise NotImplementedError def _escape_attrs(self, attrs): return dict((n, self._escape(v)) for n, v in attrs.items()) def _escape(self, content): content = unic(content) for char in _ILLEGAL_CHARS_IN_XML: # Avoid bug http://ironpython.codeplex.com/workitem/29402 if char in content: content = content.replace(char, '') return content def content(self, content): if content is not None: self._content(self._escape(content)) def _content(self, content): raise NotImplementedError def end(self, name, newline=True): self._end(name) if newline: self.content('\n') def _end(self, name): raise NotImplementedError def element(self, name, content=None, attributes={}, newline=True): self.start(name, attributes, newline=False) self.content(content) self.end(name, newline) def close(self): self._close() self.closed = True def _close(self): self._writer.endDocument() self._output.close()
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import inspect from robot.errors import DataError from error import get_error_message, get_error_details from robotpath import normpath, abspath def simple_import(path_to_module): err_prefix = "Importing '%s' failed: " % path_to_module if not os.path.exists(path_to_module): raise DataError(err_prefix + 'File does not exist') try: return _import_module_by_path(path_to_module) except: raise DataError(err_prefix + get_error_message()) def _import_module_by_path(path): moddir, modname = _split_path_to_module(path) sys.path.insert(0, moddir) try: module = __import__(modname) if hasattr(module, '__file__'): impdir = os.path.dirname(module.__file__) if normpath(impdir) != normpath(moddir): del sys.modules[modname] module = __import__(modname) return module finally: sys.path.pop(0) def _split_path_to_module(path): moddir, modfile = os.path.split(abspath(path)) modname = os.path.splitext(modfile)[0] return moddir, modname def import_(name, type_='test library'): """Imports Python class/module or Java class with given name. 'name' can also be a path to the library and in that case the directory containing the lib is automatically put into sys.path and removed there afterwards. 'type_' is used in error message if importing fails. Class can either live in a module/package or be 'standalone'. In the former case tha name is something like 'MyClass' and in the latter it could be 'your.package.YourLibrary'). Python classes always live in a module but if the module name is exactly same as the class name the former also works in Python. Example: If you have a Python class 'MyLibrary' in a module 'mymodule' it must be imported with name 'mymodule.MyLibrary'. If the name of the module is also 'MyLibrary' then it is possible to use only name 'MyLibrary'. """ if '.' not in name or os.path.exists(name): code, module = _non_dotted_import(name, type_) else: code, module = _dotted_import(name, type_) source = _get_module_source(module) return code, source def _non_dotted_import(name, type_): try: if os.path.exists(name): module = _import_module_by_path(name) else: module = __import__(name) except: _raise_import_failed(type_, name) try: code = getattr(module, module.__name__) if not inspect.isclass(code): raise AttributeError except AttributeError: code = module return code, module def _dotted_import(name, type_): parentname, libname = name.rsplit('.', 1) try: try: module = __import__(parentname, fromlist=[str(libname)]) except ImportError: # Hack to support standalone Jython: # http://code.google.com/p/robotframework/issues/detail?id=515 if not sys.platform.startswith('java'): raise __import__(name) module = __import__(parentname, fromlist=[str(libname)]) except: _raise_import_failed(type_, name) try: code = getattr(module, libname) except AttributeError: _raise_no_lib_in_module(type_, parentname, libname) if not (inspect.ismodule(code) or inspect.isclass(code)): _raise_invalid_type(type_, code) return code, module def _get_module_source(module): source = getattr(module, '__file__', None) return abspath(source) if source else '<unknown>' def _raise_import_failed(type_, name): error_msg, error_details = get_error_details() msg = ["Importing %s '%s' failed: %s" % (type_, name, error_msg), "PYTHONPATH: %s" % sys.path, error_details] if sys.platform.startswith('java'): from java.lang import System msg.insert(-1, 'CLASSPATH: %s' % System.getProperty('java.class.path')) raise DataError('\n'.join(msg)) def _raise_no_lib_in_module(type_, modname, libname): raise DataError("%s module '%s' does not contain '%s'." % (type_.capitalize(), modname, libname)) def _raise_invalid_type(type_, code): raise DataError("Imported %s should be a class or module, got %s." % (type_, type(code).__name__))
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import utils # Return codes from Robot and Rebot. # RC below 250 is the number of failed critical tests and exactly 250 # means that number or more such failures. INFO_PRINTED = 251 # --help or --version DATA_ERROR = 252 # Invalid data or cli args STOPPED_BY_USER = 253 # KeyboardInterrupt or SystemExit FRAMEWORK_ERROR = 255 # Unexpected error class RobotError(Exception): """Base class for Robot Framework errors. Do not raise this method but use more specific errors instead. """ def __init__(self, message=''): Exception.__init__(self, message) def __unicode__(self): # Needed to handle exceptions w/ Unicode correctly on Python 2.5 return unicode(self.args[0]) if self.args else u'' class FrameworkError(RobotError): """Can be used when the core framework goes to unexpected state. It is good to explicitly raise a FrameworkError if some framework component is used incorrectly. This is pretty much same as 'Internal Error' and should of course never happen. """ class DataError(RobotError): """Used when the provided test data is invalid. DataErrors are not be caught by keywords that run other keywords (e.g. `Run Keyword And Expect Error`). Libraries should thus use this exception with care. """ class TimeoutError(RobotError): """Used when a test or keyword timeout occurs. This exception is handled specially so that execution of the current test is always stopped immediately and it is not caught by keywords executing other keywords (e.g. `Run Keyword And Expect Error`). Libraries should thus NOT use this exception themselves. """ class Information(RobotError): """Used by argument parser with --help or --version.""" class ExecutionFailed(RobotError): """Used for communicating failures in test execution.""" def __init__(self, message, timeout=False, syntax=False, exit=False, cont=False, exit_for_loop=False): RobotError.__init__(self, utils.cut_long_message(message)) self.timeout = timeout self.syntax = syntax self.exit = exit self.cont = cont self.exit_for_loop = exit_for_loop @property def dont_cont(self): return self.timeout or self.syntax or self.exit # Python 2.6 property decorators would have nice `setter` attribute: # http://docs.python.org/library/functions.html#property cont = property(lambda self: self._cont and not self.dont_cont, lambda self, cont: setattr(self, '_cont', cont)) def can_continue(self, teardown=False, templated=False, dry_run=False): if dry_run: return True if self.dont_cont and not (teardown and self.syntax): return False if teardown or templated: return True return self.cont def get_errors(self): return [self] class HandlerExecutionFailed(ExecutionFailed): def __init__(self): details = utils.ErrorDetails() timeout = isinstance(details.error, TimeoutError) syntax = isinstance(details.error, DataError) exit = bool(getattr(details.error, 'ROBOT_EXIT_ON_FAILURE', False)) cont = bool(getattr(details.error, 'ROBOT_CONTINUE_ON_FAILURE', False)) exit_for_loop = bool(getattr(details.error, 'ROBOT_EXIT_FOR_LOOP', False)) ExecutionFailed.__init__(self, details.message, timeout, syntax, exit, cont, exit_for_loop) self.full_message = details.message self.traceback = details.traceback class ExecutionFailures(ExecutionFailed): def __init__(self, errors): msg = self._format_message([unicode(e) for e in errors]) ExecutionFailed.__init__(self, msg, **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), 'cont': all(err.cont for err in errors), 'exit_for_loop': all(err.exit_for_loop for err in errors)} def get_errors(self): return self._errors class UserKeywordExecutionFailed(ExecutionFailures): def __init__(self, run_errors=None, teardown_errors=None): no_errors = ExecutionFailed('', cont=True, exit_for_loop=True) ExecutionFailures.__init__(self, [run_errors or no_errors, teardown_errors or no_errors]) if run_errors and not teardown_errors: self._errors = run_errors.get_errors() else: self._errors = [self] def _format_message(self, messages): run_msg, td_msg = messages 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 RemoteError(RobotError): """Used by Remote library to report remote errors.""" def __init__(self, message, traceback): RobotError.__init__(self, message) self.traceback = traceback
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot import utils from logger import LOGGER from loggerhelper import IsLogged def DebugFile(path): if path == 'NONE': LOGGER.info('No debug file') return None try: LOGGER.info('Debug file: %s' % path) return _DebugFileWriter(path) except: LOGGER.error("Opening debug file '%s' failed and writing to debug file " "is disabled. Error: %s" % (path, utils.get_error_message())) return None class _DebugFileWriter: _separators = {'SUITE': '=', 'TEST': '-', 'KW': '~'} def __init__(self, path): self._indent = 0 self._kw_level = 0 self._separator_written_last = False self._file = open(path, 'wb') self._is_logged = IsLogged('DEBUG') def start_suite(self, suite): self._separator('SUITE') self._start('SUITE', suite.longname) self._separator('SUITE') def end_suite(self, suite): self._separator('SUITE') self._end('SUITE', suite.longname, suite.elapsedtime) self._separator('SUITE') if self._indent == 0: LOGGER.output_file('Debug', self._file.name) self.close() def start_test(self, test): self._separator('TEST') self._start('TEST', test.name) self._separator('TEST') def end_test(self, test): self._separator('TEST') self._end('TEST', test.name, test.elapsedtime) self._separator('TEST') def start_keyword(self, kw): if self._kw_level == 0: self._separator('KW') self._start(self._get_kw_type(kw), kw.name, kw.args) self._kw_level += 1 def end_keyword(self, kw): self._end(self._get_kw_type(kw), kw.name, kw.elapsedtime) self._kw_level -= 1 def log_message(self, msg): if self._is_logged(msg.level): self._write(msg.message) def close(self): if not self._file.closed: self._file.close() def _get_kw_type(self, kw): if kw.type in ['setup','teardown']: return kw.type.upper() return 'KW' def _start(self, type_, name, args=''): args = ' ' + utils.seq2str2(args) self._write('+%s START %s: %s%s' % ('-'*self._indent, type_, name, args)) self._indent += 1 def _end(self, type_, name, elapsed): self._indent -= 1 self._write('+%s END %s: %s (%s)' % ('-'*self._indent, type_, name, elapsed)) def _separator(self, type_): self._write(self._separators[type_] * 78, True) def _write(self, text, separator=False): if self._separator_written_last and separator: return self._file.write(utils.unic(text).encode('UTF-8').rstrip() + '\n') self._file.flush() self._separator_written_last = separator
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from robot import utils from loggerhelper import AbstractLogger, AbstractLoggerProxy, Message from filelogger import FileLogger from monitor import CommandLineMonitor class Logger(AbstractLogger): """A global logger proxy to which new loggers may be registered. Whenever something is written to LOGGER in code, all registered loggers are notified. Messages are also cached and cached messages written to new loggers when they are registered. Tools using Robot Framework's internal modules should register their own loggers at least to get notifications about errors and warnings. A shortcut to get errors/warnings into console is using 'register_console_logger'. """ def __init__(self): self._loggers = LoggerCollection() self._message_cache = [] self._register_console_logger() self._console_logger_disabled = False def disable_message_cache(self): self._message_cache = None def disable_automatic_console_logger(self): if not self._console_logger_disabled: self._console_logger_disabled = True return self._loggers.remove_first_regular_logger() def register_logger(self, *loggers): for log in loggers: logger = self._loggers.register_regular_logger(log) self._relay_cached_messages_to(logger) def register_context_changing_logger(self, logger): log = self._loggers.register_context_changing_logger(logger) self._relay_cached_messages_to(log) def _relay_cached_messages_to(self, logger): if self._message_cache: for msg in self._message_cache: logger.message(msg) def unregister_logger(self, *loggers): for log in loggers: self._loggers.unregister_logger(log) def register_console_logger(self, width=78, colors='AUTO'): self.disable_automatic_console_logger() self._register_console_logger(width, colors) def _register_console_logger(self, width=78, colors='AUTO'): monitor = CommandLineMonitor(width, colors) self._loggers.register_regular_logger(monitor) def register_file_logger(self, path=None, level='INFO'): if not path: path = os.environ.get('ROBOT_SYSLOG_FILE', 'NONE') level = os.environ.get('ROBOT_SYSLOG_LEVEL', level) if path.upper() == 'NONE': return try: logger = FileLogger(path, level) except: self.error("Opening syslog file '%s' failed: %s" % (path, utils.get_error_message())) else: self.register_logger(logger) def message(self, msg): """Messages about what the framework is doing, warnings, errors, ...""" for logger in self._loggers.all_loggers(): logger.message(msg) if self._message_cache is not None: self._message_cache.append(msg) def log_message(self, msg): """Log messages written (mainly) by libraries""" for logger in self._loggers.all_loggers(): logger.log_message(msg) if msg.level == 'WARN': msg.linkable = True self.message(msg) def warn(self, msg, log=False): method = self.log_message if log else self.message method(Message(msg, 'WARN')) def output_file(self, name, path): """Finished output, report, log, summary, debug, or xunit file""" for logger in self._loggers.all_loggers(): logger.output_file(name, path) def close(self): for logger in self._loggers.all_loggers(): logger.close() self._loggers = LoggerCollection() self._message_cache = [] def start_suite(self, suite): for logger in self._loggers.starting_loggers(): logger.start_suite(suite) def end_suite(self, suite): for logger in self._loggers.ending_loggers(): logger.end_suite(suite) def start_test(self, test): for logger in self._loggers.starting_loggers(): logger.start_test(test) def end_test(self, test): for logger in self._loggers.ending_loggers(): logger.end_test(test) def start_keyword(self, keyword): for logger in self._loggers.starting_loggers(): logger.start_keyword(keyword) def end_keyword(self, keyword): for logger in self._loggers.ending_loggers(): logger.end_keyword(keyword) def __iter__(self): return iter(self._loggers) class LoggerCollection(object): def __init__(self): self._regular_loggers = [] self._context_changing_loggers = [] def register_regular_logger(self, logger): self._regular_loggers.append(_LoggerProxy(logger)) return self._regular_loggers[-1] def register_context_changing_logger(self, logger): self._context_changing_loggers.append(_LoggerProxy(logger)) return self._context_changing_loggers[-1] def remove_first_regular_logger(self): return self._regular_loggers.pop(0) def unregister_logger(self, logger): self._regular_loggers = [proxy for proxy in self._regular_loggers if proxy.logger is not logger] self._context_changing_loggers = [proxy for proxy in self._context_changing_loggers if proxy.logger is not logger] def starting_loggers(self): return self.all_loggers() def ending_loggers(self): return self._regular_loggers + self._context_changing_loggers def all_loggers(self): return self._context_changing_loggers + self._regular_loggers def __iter__(self): return iter(self.all_loggers()) class _LoggerProxy(AbstractLoggerProxy): _methods = ['message', 'log_message', 'output_file', 'close', 'start_suite', 'end_suite', 'start_test', 'end_test', 'start_keyword', 'end_keyword'] LOGGER = Logger()
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module to configure Python's standard `logging` module. After this module is imported, messages logged with `logging` module are, by default, propagated to Robot's log file. """ import logging from robot.api import logger class RobotHandler(logging.Handler): def emit(self, record): method = self._get_logger_method(record.levelno) method(record.getMessage()) def _get_logger_method(self, level): if level >= logging.WARNING: return logger.warn if level <= logging.DEBUG: return logger.debug return logger.info class NullStream(object): def write(self, message): pass def close(self): pass def flush(self): pass logging.basicConfig(level=logging.NOTSET, stream=NullStream()) logging.getLogger().addHandler(RobotHandler())
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os.path from robot import utils from robot.errors import DataError from robot.common import BaseTestSuite, BaseTestCase, BaseKeyword from robot.output import LOGGER from robot.output.loggerhelper import IsLogged, Message def process_outputs(paths, settings): if not paths: raise DataError('No output files given.') if len(paths) == 1: return process_output(paths[0], log_level=settings['LogLevel'], settings=settings) suite = CombinedTestSuite(settings) exec_errors = CombinedExecutionErrors() for path in paths: subsuite, suberrors = process_output(path, log_level=settings['LogLevel']) suite.add_suite(subsuite) exec_errors.add(suberrors) return suite, exec_errors def process_output(path, log_level=None, settings=None): """Process one output file and return TestSuite and ExecutionErrors""" if not os.path.isfile(path): raise DataError("Output file '%s' does not exist." % path) LOGGER.info("Processing output file '%s'." % path) try: root = utils.etreewrapper.get_root(path) except: raise DataError("Opening XML file '%s' failed: %s" % (path, utils.get_error_message())) suite = TestSuite(_get_suite_node(root, path), log_level=log_level, settings=settings) errors = ExecutionErrors(_get_errors_node(root)) return suite, errors def _get_suite_node(root, path): if root.tag != 'robot': raise DataError("File '%s' is not Robot Framework output file." % path) node = root.find('suite') node.set('generator', root.get('generator', 'notset').split()[0].lower()) node.set('path', path) return node def _get_errors_node(root): return root.find('errors') class _MissingStatus: """If XML was fixed for example by fixml.py, status tag may be missing""" text = 'Could not find status.' get = lambda self, name, default: name == 'status' and 'FAIL' or 'N/A' class _BaseReader: def __init__(self, node): self.doc = self._get_doc(node) stnode = node.find('status') if stnode is None: stnode = _MissingStatus() self.status = stnode.get('status','').upper() if self.status not in ['PASS','FAIL', 'NOT_RUN']: raise DataError("Item '%s' has invalid status '%s'" % (self.name, self.status)) self.message = stnode.text or '' self.starttime = stnode.get('starttime', 'N/A') self.endtime = stnode.get('endtime', 'N/A') self.elapsedtime = utils.get_elapsed_time(self.starttime, self.endtime) def _get_doc(self, node): docnode = node.find('doc') if docnode is not None: return docnode.text or '' return '' class _TestAndSuiteReader(_BaseReader): def __init__(self, node, log_level=None): _BaseReader.__init__(self, node) self.keywords = [Keyword(kw, log_level) for kw in node.findall('kw')] if self.keywords and self.keywords[0].type == 'setup': self.setup = self.keywords.pop(0) if self.keywords and self.keywords[-1].type == 'teardown': self.teardown = self.keywords.pop(-1) class _SuiteReader(_TestAndSuiteReader): def __init__(self, node, log_level=None): _TestAndSuiteReader.__init__(self, node, log_level) del(self.keywords) for metanode in node.findall('metadata/item'): self.metadata[metanode.get('name')] = metanode.text def _get_texts(self, node, path): return [item.text for item in node.findall(path)] class _TestReader(_TestAndSuiteReader): def __init__(self, node, log_level=None): _TestAndSuiteReader.__init__(self, node, log_level) self.tags = [tag.text for tag in node.findall('tags/tag')] self.timeout = node.get('timeout', '') class _KeywordReader(_BaseReader): def __init__(self, node, log_level=None): _BaseReader.__init__(self, node) del(self.message) self.args = [(arg.text or '') for arg in node.findall('arguments/arg')] self.type = node.get('type', 'kw') self.timeout = node.get('timeout', '') self.keywords = [] self.messages = [] self.children = [] log_filter = IsLogged(log_level or 'TRACE') for child in node: if child.tag == 'kw': kw = Keyword(child, log_level) self.keywords.append(kw) self.children.append(kw) elif child.tag == 'msg' and log_filter(child.get('level', 'INFO')): msg = MessageFromXml(child) self.messages.append(msg) self.children.append(msg) class TestSuite(BaseTestSuite, _SuiteReader): def __init__(self, node, parent=None, log_level=None, settings=None): BaseTestSuite.__init__(self, node.get('name'), node.get('source', None), parent) _SuiteReader.__init__(self, node, log_level=log_level) self._set_times_from_settings(settings) for snode in node.findall('suite'): snode.set('generator', node.get('generator')) snode.set('path', node.get('path')) TestSuite(snode, parent=self, log_level=log_level) for tnode in node.findall('test'): TestCase(tnode, parent=self, log_level=log_level) self.set_status() if node.get('generator') == 'robot' and \ self.teardown and self.teardown.status == 'FAIL': self.suite_teardown_failed() def _set_times_from_settings(self, settings): starttime, endtime = self._times_from_settings(settings) if not self.starttime or starttime != 'N/A': self.starttime = starttime if not self.endtime or endtime != 'N/A': self.endtime = endtime self.elapsedtime = utils.get_elapsed_time(self.starttime, self.endtime) def _times_from_settings(self, settings): if not settings: return 'N/A', 'N/A' return (self._get_time(settings['StartTime']), self._get_time(settings['EndTime'])) def _get_time(self, timestamp): if not timestamp or utils.eq(timestamp, 'N/A'): return 'N/A' try: secs = utils.timestamp_to_secs(timestamp, seps=list(' :.-_'), millis=True) except ValueError: return 'N/A' return utils.secs_to_timestamp(secs, millis=True) def set_status(self): BaseTestSuite.set_status(self) if self.starttime == 'N/A' or self.endtime == 'N/A': subitems = self.suites + self.tests + [self.setup, self.teardown] self.elapsedtime = sum(item.elapsedtime for item in subitems if item is not None ) def _set_critical_tags(self, critical): BaseTestSuite._set_critical_tags(self, critical) self.set_status() def _filter_by_tags(self, incls, excls): ret = BaseTestSuite._filter_by_tags(self, incls, excls) self.starttime = self.endtime = 'N/A' self.set_status() return ret def _filter_by_names(self, suites, tests): ret = BaseTestSuite._filter_by_names(self, suites, tests) self.starttime = self.endtime = 'N/A' self.set_status() return ret def remove_keywords(self, how): should_remove = ShouldRemoveCallable(how) if not should_remove: return self._remove_fixture_keywords(should_remove) for suite in self.suites: suite.remove_keywords(how) for test in self.tests: test.remove_keywords(should_remove) def _remove_fixture_keywords(self, should_remove): critical_failures = self.critical_stats.failed != 0 for kw in self.setup, self.teardown: if should_remove(kw, critical_failures): kw.remove_data() class CombinedTestSuite(TestSuite): def __init__(self, settings): BaseTestSuite.__init__(self, name='') self.starttime = self.endtime = None self._set_times_from_settings(settings) def add_suite(self, suite): self.suites.append(suite) suite.parent = self self._add_suite_to_stats(suite) self.status = self.critical_stats.failed == 0 and 'PASS' or 'FAIL' if self.starttime == 'N/A' or self.endtime == 'N/A': self.elapsedtime += suite.elapsedtime class TestCase(BaseTestCase, _TestReader): def __init__(self, node, parent, log_level=None): BaseTestCase.__init__(self, node.get('name'), parent) _TestReader.__init__(self, node, log_level=log_level) self.set_criticality(parent.critical) def remove_keywords(self, should_remove): if should_remove(self, (self.status != 'PASS')): for kw in self.keywords + [self.setup, self.teardown]: if kw is not None: kw.remove_data() def contains_warnings(self): return any(kw.contains_warnings() for kw in self.keywords) class Keyword(BaseKeyword, _KeywordReader): def __init__(self, node, log_level=None): self._init_data() BaseKeyword.__init__(self, node.get('name')) _KeywordReader.__init__(self, node, log_level) def _init_data(self): self.messages = [] self.keywords = [] self.children = [] def remove_data(self): self._init_data() def contains_warnings(self): return any(msg.level == 'WARN' for msg in self.messages) or \ any(kw.contains_warnings() for kw in self.keywords) def __str__(self): return self.name def __repr__(self): return "'%s'" % self.name def serialize(self, serializer): serializer.start_keyword(self) for child in self.children: child.serialize(serializer) serializer.end_keyword(self) class MessageFromXml(Message): def __init__(self, node): Message.__init__(self, node.text, level=node.get('level', 'INFO'), html=node.get('html', 'no') == 'yes', timestamp=node.get('timestamp', 'N/A'), linkable=node.get('linkable', 'no') == 'yes') def serialize(self, serializer): serializer.message(self) def __str__(self): return '%s %s %s' % (self.timestamp, self.level, self.message) def __repr__(self): lines = self.message.split('\n') msg = len(lines) > 1 and lines[0] + '...' or lines[0] return "'%s %s'" % (self.level, msg.replace("'",'"')) class ExecutionErrors: def __init__(self, node): if node is None: self.messages = [] else: self.messages = [MessageFromXml(msg) for msg in node.findall('msg')] def serialize(self, serializer): serializer.start_errors() for msg in self.messages: msg.serialize(serializer) serializer.end_errors() class CombinedExecutionErrors(ExecutionErrors): def __init__(self): self.messages = [] def add(self, other): self.messages += other.messages def ShouldRemoveCallable(how): def _removes_all(item, critical_failures): return item is not None def _removes_passed_not_containing_warnings(item, critical_failures): if item is None: return False if critical_failures: return False return not item.contains_warnings() how = how.upper() if how == 'ALL': return _removes_all return _removes_passed_not_containing_warnings if how == 'PASSED' else None
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from loggerhelper import AbstractLogger class FileLogger(AbstractLogger): def __init__(self, path, level): AbstractLogger.__init__(self, level) self._writer = self._get_writer(path) def _get_writer(self, path): # Hook for unittests return open(path, 'wb') def message(self, msg): if self._is_logged(msg.level): entry = '%s | %s | %s\n' % (msg.timestamp, msg.level.ljust(5), msg.message) self._writer.write(entry.replace('\n', os.linesep).encode('UTF-8')) def start_suite(self, suite): self.info("Started test suite '%s'" % suite.name) def end_suite(self, suite): self.info("Ended test suite '%s'" % suite.name) def start_test(self, test): self.info("Started test case '%s'" % test.name) def end_test(self, test): self.info("Ended test case '%s'" % test.name) def start_keyword(self, kw): self.debug("Started keyword '%s'" % kw.name) def end_keyword(self, kw): self.debug("Ended keyword '%s'" % kw.name) def output_file(self, name, path): self.info('%s: %s' % (name, path)) def close(self): self._writer.close()
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # 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/ 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 def Highlighter(stream): if os.sep == '/': return UnixHighlighter(stream) return DosHighlighter(stream) if windll else NoHighlighting(stream) class UnixHighlighter(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(UnixHighlighter): 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)]
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot import utils from robot.errors import DataError from robot.version import get_full_version from loggerhelper import IsLogged class XmlLogger: def __init__(self, path, log_level='TRACE', generator='Robot'): self._log_message_is_logged = IsLogged(log_level) self._error_message_is_logged = IsLogged('WARN') self._writer = None self._writer_args = (path, {'generator': get_full_version(generator), 'generated': utils.get_timestamp()}) self._errors = [] def _get_writer(self, path, attrs={}): try: writer = utils.XmlWriter(path) except: raise DataError("Opening output file '%s' for writing failed: %s" % (path, utils.get_error_message())) writer.start('robot', attrs) return writer def _close_writer(self, writer): if not writer.closed: writer.end('robot') writer.close() def close(self): self.start_errors() for msg in self._errors: self._write_message(msg) self.end_errors() self._close_writer(self._writer) def message(self, msg): if self._error_message_is_logged(msg.level): self._errors.append(msg) def log_message(self, msg): if self._log_message_is_logged(msg.level): self._write_message(msg) def set_log_level(self, level): return self._log_message_is_logged.set_level(level) def _write_message(self, msg): attrs = {'timestamp': msg.timestamp, 'level': msg.level} if msg.html: attrs['html'] = 'yes' if msg.linkable: attrs['linkable'] = 'yes' self._writer.element('msg', msg.message, attrs) def start_keyword(self, kw): attrs = {'name': kw.name, 'type': kw.type, 'timeout': kw.timeout} self._writer.start('kw', attrs) self._writer.element('doc', kw.doc) self._write_list('arg', [utils.unic(a) for a in kw.args], 'arguments') def end_keyword(self, kw): self._write_status(kw) self._writer.end('kw') def start_test(self, test): attrs = {'name': test.name, 'timeout': str(test.timeout)} self._writer.start('test', attrs) self._writer.element('doc', test.doc) def end_test(self, test): self._write_list('tag', test.tags, 'tags') self._write_status(test, test.message, extra_attrs={'critical': test.critical}) self._writer.end('test') def start_suite(self, suite): if not self._writer: self._writer = self._get_writer(*self._writer_args) del self._writer_args self._start_suite(suite) def _start_suite(self, suite, extra_attrs=None): attrs = extra_attrs is not None and extra_attrs or {} attrs['name'] = suite.name if suite.source: attrs['source'] = suite.source self._writer.start('suite', attrs) self._writer.element('doc', suite.doc) self._writer.start('metadata') for name, value in suite.get_metadata(): self._writer.element('item', value, {'name': name}) self._writer.end('metadata') def end_suite(self, suite): self._write_status(suite, suite.message) self._writer.end('suite') def start_statistics(self, stats): self._writer.start('statistics') def end_statistics(self, stats): self._writer.end('statistics') def start_total_stats(self, total_stats): self._writer.start('total') def end_total_stats(self, total_stats): self._writer.end('total') def start_tag_stats(self, tag_stats): self._writer.start('tag') def end_tag_stats(self, tag_stats): self._writer.end('tag') def start_suite_stats(self, tag_stats): self._writer.start('suite') def end_suite_stats(self, tag_stats): self._writer.end('suite') def total_stat(self, stat): self._stat(stat) def suite_stat(self, stat): self._stat(stat, stat.long_name, attrs={'name': stat.name}) def tag_stat(self, stat): self._stat(stat, attrs={'info': self._get_tag_stat_info(stat), 'links': self._get_tag_links(stat), 'doc': stat.doc, 'combined': stat.combined}) def _get_tag_links(self, stat): return ':::'.join(':'.join([title, url]) for url, title in stat.links) def _stat(self, stat, name=None, attrs=None): name = name or stat.name attrs = attrs or {} attrs['pass'] = str(stat.passed) attrs['fail'] = str(stat.failed) self._writer.element('stat', name, attrs) def _get_tag_stat_info(self, stat): if stat.critical: return 'critical' if stat.non_critical: return 'non-critical' if stat.combined: return 'combined' return '' def start_errors(self): self._writer.start('errors') def end_errors(self): self._writer.end('errors') def _write_list(self, tag, items, container=None): if container: self._writer.start(container) for item in items: self._writer.element(tag, item) if container: self._writer.end(container) def _write_status(self, item, message=None, extra_attrs=None): attrs = {'status': item.status, 'starttime': item.starttime, 'endtime': item.endtime} if extra_attrs: attrs.update(extra_attrs) self._writer.element('status', message, attrs)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from robot import utils from highlighting import Highlighter, NoHighlighting from loggerhelper import IsLogged class CommandLineMonitor: def __init__(self, width=78, colors='AUTO'): self._width = width self._highlighter = StatusHighlighter(colors) self._is_logged = IsLogged('WARN') self._started = False def start_suite(self, suite): if not self._started: self._write_separator('=') self._started = True self._write_info(suite.longname, suite.doc, start_suite=True) self._write_separator('=') def end_suite(self, suite): self._write_info(suite.longname, suite.doc) self._write_status(suite.status) self._write_message(suite.get_full_message()) self._write_separator('=') def start_test(self, test): self._write_info(test.name, test.doc) def end_test(self, test): self._write_status(test.status) self._write_message(test.message) self._write_separator('-') def message(self, msg): if self._is_logged(msg.level): self._write_with_highlighting('[ ', msg.level, ' ] ' + msg.message, stream=sys.__stderr__) def output_file(self, name, path): self._write('%-8s %s' % (name+':', path)) def _write_info(self, name, doc, start_suite=False): maxwidth = self._width if not start_suite: maxwidth -= len(' | PASS |') info = self._get_info(name, doc, maxwidth) self._write(info, newline=start_suite) def _get_info(self, name, doc, maxwidth): if utils.get_console_length(name) > maxwidth: return utils.pad_console_length(name, maxwidth, cut_left=True) info = name if not doc else '%s :: %s' % (name, doc.splitlines()[0]) return utils.pad_console_length(info, maxwidth) def _write_status(self, status): self._write_with_highlighting(' | ', status, ' |') def _write_message(self, message): if message: self._write(message.strip()) def _write_separator(self, sep_char): self._write(sep_char * self._width) def _write(self, message, newline=True, stream=sys.__stdout__): if newline: message += '\n' stream.write(utils.encode_output(message).replace('\t', ' '*8)) stream.flush() def _write_with_highlighting(self, before, highlighted, after, newline=True, stream=sys.__stdout__): self._write(before, newline=False, stream=stream) self._highlighter.start(highlighted, stream) self._write(highlighted, newline=False, stream=stream) self._highlighter.end() self._write(after, newline=newline, stream=stream) class StatusHighlighter: def __init__(self, colors): self._current = None self._highlighters = { sys.__stdout__: self._get_highlighter(sys.__stdout__, colors), sys.__stderr__: self._get_highlighter(sys.__stderr__, colors) } def start(self, message, stream=sys.__stdout__): self._current = self._highlighters[stream] {'PASS': self._current.green, 'FAIL': self._current.red, 'ERROR': self._current.red, 'WARN': self._current.yellow}[message]() def end(self): self._current.reset() def _get_highlighter(self, stream, colors): auto = hasattr(stream, 'isatty') and stream.isatty() enable = {'AUTO': auto, 'ON': True, 'FORCE': True, # compatibility with 2.5.5 and earlier 'OFF': False}.get(colors.upper(), auto) return Highlighter(stream) if enable else NoHighlighting(stream)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from robot.output.loggerhelper import Message, LEVELS from robot import utils class StdoutLogSplitter(object): """Splits messages logged through stdout (or stderr) into Message objects""" _split_from_levels = re.compile('^(?:\*' '(%s|HTML)' # Level '(:\d+(?:\.\d+)?)?' # Optional timestamp '\*)' % '|'.join(LEVELS), re.MULTILINE) def __init__(self, output): self._messages = list(self._get_messages(output.strip())) def _get_messages(self, output): for level, timestamp, msg in self._split_output(output): if timestamp: timestamp = self._format_timestamp(timestamp[1:]) yield Message(msg.strip(), level, timestamp=timestamp) def _split_output(self, output): tokens = self._split_from_levels.split(output) tokens = self._add_initial_level_and_time_if_needed(tokens) for i in xrange(0, len(tokens), 3): yield tokens[i:i+3] def _add_initial_level_and_time_if_needed(self, tokens): if self._output_started_with_level(tokens): return tokens[1:] return ['INFO', None] + tokens def _output_started_with_level(self, tokens): return tokens[0] == '' def _format_timestamp(self, millis): return utils.format_time(float(millis)/1000, millissep='.') def __iter__(self): return iter(self._messages)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import sys from robot import utils from robot.errors import DataError from loggerhelper import AbstractLoggerProxy from logger import LOGGER if utils.is_jython: from java.lang import Object from java.util import HashMap class Listeners: _start_attrs = ['doc', 'starttime', 'longname'] _end_attrs = _start_attrs + ['endtime', 'elapsedtime', 'status', 'message'] def __init__(self, listeners): self._listeners = self._import_listeners(listeners) self._running_test = False self._setup_or_teardown_type = None def __nonzero__(self): return bool(self._listeners) def _import_listeners(self, listener_data): listeners = [] for name, args in listener_data: try: listeners.append(_ListenerProxy(name, args)) except: message, details = utils.get_error_details() if args: name += ':' + ':'.join(args) LOGGER.error("Taking listener '%s' into use failed: %s" % (name, message)) LOGGER.info("Details:\n%s" % details) return listeners def start_suite(self, suite): for li in self._listeners: if li.version == 1: li.call_method(li.start_suite, suite.name, suite.doc) else: attrs = self._get_start_attrs(suite, 'metadata') attrs.update({'tests' : [t.name for t in suite.tests ], 'suites': [s.name for s in suite.suites], 'totaltests': suite.get_test_count()}) li.call_method(li.start_suite, suite.name, attrs) def end_suite(self, suite): for li in self._listeners: if li.version == 1: li.call_method(li.end_suite, suite.status, suite.get_full_message()) else: attrs = self._get_end_attrs(suite) attrs.update({'statistics': suite.get_stat_message()}) li.call_method(li.end_suite, suite.name, attrs) def start_test(self, test): self._running_test = True for li in self._listeners: if li.version == 1: li.call_method(li.start_test, test.name, test.doc, test.tags) else: attrs = self._get_start_attrs(test, 'tags') li.call_method(li.start_test, test.name, attrs) def end_test(self, test): self._running_test = False for li in self._listeners: if li.version == 1: li.call_method(li.end_test, test.status, test.message) else: attrs = self._get_end_attrs(test, 'tags') li.call_method(li.end_test, test.name, attrs) def start_keyword(self, kw): for li in self._listeners: if li.version == 1: li.call_method(li.start_keyword, kw.name, kw.args) else: attrs = self._get_start_attrs(kw, 'args', '-longname') attrs['type'] = self._get_keyword_type(kw, start=True) li.call_method(li.start_keyword, kw.name, attrs) def end_keyword(self, kw): for li in self._listeners: if li.version == 1: li.call_method(li.end_keyword, kw.status) else: attrs = self._get_end_attrs(kw, 'args', '-longname', '-message') attrs['type'] = self._get_keyword_type(kw, start=False) li.call_method(li.end_keyword, kw.name, attrs) def _get_keyword_type(self, kw, start=True): # When running setup or teardown, only the top level keyword has type # set to setup/teardown but we want to pass that type also to all # start/end_keyword listener methods called below that keyword. if kw.type == 'kw': return self._setup_or_teardown_type or 'Keyword' kw_type = self._get_setup_or_teardown_type(kw) self._setup_or_teardown_type = kw_type if start else None return kw_type def _get_setup_or_teardown_type(self, kw): return '%s %s' % (('Test' if self._running_test else 'Suite'), kw.type.title()) def log_message(self, msg): for li in self._listeners: if li.version == 2: li.call_method(li.log_message, self._create_msg_dict(msg)) def message(self, msg): for li in self._listeners: if li.version == 2: li.call_method(li.message, self._create_msg_dict(msg)) def _create_msg_dict(self, msg): return {'timestamp': msg.timestamp, 'message': msg.message, 'level': msg.level, 'html': 'yes' if msg.html else 'no'} def output_file(self, name, path): for li in self._listeners: li.call_method(getattr(li, '%s_file' % name.lower()), path) def close(self): for li in self._listeners: li.call_method(li.close) def _get_start_attrs(self, item, *names): return self._get_attrs(item, self._start_attrs, names) def _get_end_attrs(self, item, *names): return self._get_attrs(item, self._end_attrs, names) def _get_attrs(self, item, defaults, extras): names = self._get_attr_names(defaults, extras) return dict((n, self._get_attr_value(item, n)) for n in names) def _get_attr_names(self, defaults, extras): names = list(defaults) for name in extras: if name.startswith('-'): names.remove(name[1:]) else: names.append(name) return names def _get_attr_value(self, item, name): value = getattr(item, name) return self._take_copy_of_mutable_value(value) def _take_copy_of_mutable_value(self, value): if isinstance(value, (dict, utils.NormalizedDict)): return dict(value) if isinstance(value, list): return list(value) return value class _ListenerProxy(AbstractLoggerProxy): _methods = ['start_suite', 'end_suite', 'start_test', 'end_test', 'start_keyword', 'end_keyword', 'log_message', 'message', 'output_file', 'summary_file', 'report_file', 'log_file', 'debug_file', 'xunit_file', 'close'] def __init__(self, name, args): listener = self._import_listener(name, args) AbstractLoggerProxy.__init__(self, listener) self.name = name self.version = self._get_version(listener) self.is_java = utils.is_jython and isinstance(listener, Object) self._failed = [] def _import_listener(self, name, args): listener, source = utils.import_(name, 'listener') if not inspect.ismodule(listener): listener = listener(*args) elif args: raise DataError("Listeners implemented as modules do not take arguments") LOGGER.info("Imported listener '%s' with arguments %s (source %s)" % (name, utils.seq2str2(args), source)) return listener def _get_version(self, listener): try: return int(getattr(listener, 'ROBOT_LISTENER_API_VERSION', 1)) except ValueError: return 1 def call_method(self, method, *args): if method in self._failed: return if self.is_java: args = [self._to_map(a) if isinstance(a, dict) else a for a in args] try: method(*args) except: self._failed.append(method) self._report_error(method) def _report_error(self, method): message, details = utils.get_error_details() LOGGER.error("Method '%s' of listener '%s' failed and is disabled: %s" % (method.__name__, self.name, message)) LOGGER.info("Details:\n%s" % details) def _to_map(self, dictionary): map = HashMap() for key, value in dictionary.iteritems(): map.put(key, value) return map
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from output import Output from logger import LOGGER from monitor import CommandLineMonitor from xmllogger import XmlLogger from loggerhelper import LEVELS, Message from readers import process_output, process_outputs # Hooks to output. Set by Output. # Use only if no other way available (e.g. from BuiltIn library) OUTPUT = None def TestSuite(outpath): """Factory method for getting test suite from an xml output file. If you want statistics get suite first and say Statistics(suite). """ suite, errors = process_output(outpath) def write_to_file(path=None): """Write processed suite (incl. statistics and errors) back to xml. If path is not given the suite is written into the same file as it originally was read from. """ from robot.result import RobotTestOutput if path is None: path = outpath suite.set_status() testoutput = RobotTestOutput(suite, errors) testoutput.serialize_output(path, suite) suite.write_to_file = write_to_file return suite
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.common.statistics import Statistics from loggerhelper import AbstractLogger from logger import LOGGER from xmllogger import XmlLogger from listeners import Listeners from debugfile import DebugFile from stdoutlogsplitter import StdoutLogSplitter class Output(AbstractLogger): def __init__(self, settings): AbstractLogger.__init__(self) self._xmllogger = XmlLogger(settings['Output'], settings['LogLevel']) self._register_loggers(settings['Listeners'], settings['DebugFile']) self._settings = settings self._set_global_output() def _register_loggers(self, listeners, debugfile): LOGGER.register_context_changing_logger(self._xmllogger) for logger in Listeners(listeners), DebugFile(debugfile): if logger: LOGGER.register_logger(logger) LOGGER.disable_message_cache() def _set_global_output(self): # This is a hack. Hopefully we get rid of it at some point. from robot import output output.OUTPUT = self def close(self, suite): stats = Statistics(suite, self._settings['SuiteStatLevel'], self._settings['TagStatInclude'], self._settings['TagStatExclude'], self._settings['TagStatCombine'], self._settings['TagDoc'], self._settings['TagStatLink']) stats.serialize(self._xmllogger) self._xmllogger.close() LOGGER.unregister_logger(self._xmllogger) LOGGER.output_file('Output', self._settings['Output']) def start_suite(self, suite): LOGGER.start_suite(suite) def end_suite(self, suite): LOGGER.end_suite(suite) def start_test(self, test): LOGGER.start_test(test) def end_test(self, test): LOGGER.end_test(test) def start_keyword(self, kw): LOGGER.start_keyword(kw) def end_keyword(self, kw): LOGGER.end_keyword(kw) def log_output(self, output): for msg in StdoutLogSplitter(output): self.message(msg) def message(self, msg): LOGGER.log_message(msg) def set_log_level(self, level): return self._xmllogger.set_log_level(level)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot import utils from robot.errors import DataError LEVELS = { "NONE" : 100, "ERROR" : 60, "FAIL" : 50, "WARN" : 40, "INFO" : 30, "DEBUG" : 20, "TRACE" : 10, } 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): self.write(msg, 'FAIL') 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(object): def __init__(self, message, level='INFO', html=False, timestamp=None, linkable=False): self.message = self._get_message(message) self.level, self.html = self._get_level_and_html(level, html) self.timestamp = self._get_timestamp(timestamp) self.linkable = linkable def _get_message(self, msg): if not isinstance(msg, basestring): msg = utils.unic(msg) return msg.replace('\r\n', '\n') def _get_level_and_html(self, level, html): level = level.upper() if level == 'HTML': return 'INFO', True if level not in LEVELS: raise DataError("Invalid log level '%s'" % level) return level, html def _get_timestamp(self, timestamp): if timestamp: return timestamp return utils.get_timestamp(daysep='', daytimesep=' ', timesep=':', millissep='.') def get_timestamp(self, sep=' '): return self.timestamp.replace(' ', sep) @property def time(self): if ' ' not in self.timestamp: return self.timestamp return self.timestamp.split()[1] 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 def __init__(self, logger): self.logger = logger default = lambda *args: None for name in self._methods: try: method = getattr(logger, name) except AttributeError: method = getattr(logger, self._toCamelCase(name), default) setattr(self, name, method) def _toCamelCase(self, name): parts = name.split('_') return ''.join([parts[0]] + [part.capitalize() for part in parts[1:]])
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.errors import DataError class BaseLibrary: def get_handler(self, name): try: return self.handlers[name] except KeyError: raise DataError("No keyword handler with name '%s' found" % name) def has_handler(self, name): return self.handlers.has_key(name) def __len__(self): return len(self.handlers)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot.errors import DataError class UserErrorHandler: """Created if creating handlers fail -- running raises DataError. The idea is not to raise DataError at processing time and prevent all tests in affected test case file from executing. Instead UserErrorHandler is created and if it is ever run DataError is raised then. """ type = 'error' def __init__(self, name, error): self.name = self.longname = name self.doc = self.shortdoc = '' self._error = error self.timeout = '' def init_keyword(self, varz): pass def run(self, *args): raise DataError(self._error)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class BaseKeyword: def __init__(self, name='', args=None, doc='', timeout='', type='kw'): self.name = name self.args = args or [] self.doc = doc self.timeout = timeout self.type = type self.status = 'NOT_RUN' def serialize(self, serializer): serializer.start_keyword(self) serializer.end_keyword(self)
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from model import BaseTestSuite, BaseTestCase from keyword import BaseKeyword from handlers import UserErrorHandler from libraries import BaseLibrary from statistics import Statistics
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import random from statistics import Stat from robot import utils from robot.errors import DataError class _TestAndSuiteHelper: def __init__(self, name, parent=None): self.name = name self.doc = '' self.parent = parent self.setup = None self.teardown = None self.status = 'NOT_RUN' self.message = '' # TODO: Is this property and other html/serialize stuff here used anymore? @property def htmldoc(self): return utils.html_format(self.doc) # TODO: Replace with simple @property in 2.7. # Cannot do that now because Mabot assigns longname. _longname = None longname = property(lambda self: self._longname or self.get_long_name(), lambda self, name: setattr(self, '_longname', name)) # TODO: Is separator still used? def get_long_name(self, separator='.'): """Returns long name. If separator is None, list of names is returned.""" names = self.parent and self.parent.get_long_name(separator=None) or [] names.append(self.name) if separator: return separator.join(names) return names def _set_teardown_fail_msg(self, message): if self.message == '': self.message = message else: self.message += '\n\nAlso ' + message[0].lower() + message[1:] def __str__(self): return self.name def __repr__(self): return repr(self.name) class BaseTestSuite(_TestAndSuiteHelper): """Base class for TestSuite used in runtime and by rebot.""" def __init__(self, name, source=None, parent=None): _TestAndSuiteHelper.__init__(self, name, parent) self.source = source is not None and utils.abspath(source) or None self.metadata = utils.NormalizedDict() self.suites = [] self.tests = [] self.critical = _Critical() self.critical_stats = Stat() self.all_stats = Stat() if parent: parent.suites.append(self) def set_name(self, name): if name: self.name = name elif not self.parent and self.name == '': # MultiSourceSuite self.name = ' & '.join([suite.name for suite in self.suites]) def set_critical_tags(self, critical, non_critical): if critical is not None or non_critical is not None: self.critical.set(critical, non_critical) self._set_critical_tags(self.critical) def _set_critical_tags(self, critical): self.critical = critical for suite in self.suites: suite._set_critical_tags(critical) for test in self.tests: test.set_criticality(critical) def set_doc(self, doc): if doc: self.doc = doc def set_metadata(self, metalist): for name, value in metalist: self.metadata[name] = value def get_metadata(self, html=False): names = sorted(self.metadata.keys()) values = [self.metadata[n] for n in names] if html: values = [utils.html_format(v) for v in values] return zip(names, values) def get_test_count(self): count = len(self.tests) for suite in self.suites: count += suite.get_test_count() return count def get_full_message(self, html=False): """Returns suite's message including statistics message""" stat_msg = self.get_stat_message(html) if not self.message: return stat_msg if not html: return '%s\n\n%s' % (self.message, stat_msg) return '%s<br /><br />%s' % (utils.html_escape(self.message), stat_msg) def get_stat_message(self, html=False): ctotal, cend, cpass, cfail = self._get_counts(self.critical_stats) atotal, aend, apass, afail = self._get_counts(self.all_stats) msg = ('%%d critical test%%s, %%d passed, %(cfail)s%%d failed%(end)s\n' '%%d test%%s total, %%d passed, %(afail)s%%d failed%(end)s') if html: msg = msg.replace(' ', '&nbsp;').replace('\n', '<br />') msg = msg % {'cfail': '<span%s>' % (cfail and ' class="fail"' or ''), 'afail': '<span%s>' % (afail and ' class="fail"' or ''), 'end': '</span>'} else: msg = msg % {'cfail': '', 'afail': '', 'end': ''} return msg % (ctotal, cend, cpass, cfail, atotal, aend, apass, afail) def _get_counts(self, stat): total = stat.passed + stat.failed ending = utils.plural_or_not(total) return total, ending, stat.passed, stat.failed def set_status(self): """Sets status and statistics based on subsuite and test statuses. Can/should be used when statuses have been changed somehow. """ self.status = self._set_stats() def _set_stats(self): self.critical_stats = Stat() self.all_stats = Stat() for suite in self.suites: suite.set_status() self._add_suite_to_stats(suite) for test in self.tests: self._add_test_to_stats(test) return self._get_status() def _get_status(self): return 'PASS' if not self.critical_stats.failed else 'FAIL' def _add_test_to_stats(self, test): self.all_stats.add_test(test) if test.critical == 'yes': self.critical_stats.add_test(test) def _add_suite_to_stats(self, suite): self.critical_stats.add_stat(suite.critical_stats) self.all_stats.add_stat(suite.all_stats) def suite_teardown_failed(self, message=None): if message: self._set_teardown_fail_msg(message) self.critical_stats.fail_all() self.all_stats.fail_all() self.status = self._get_status() sub_message = 'Teardown of the parent suite failed.' for suite in self.suites: suite.suite_teardown_failed(sub_message) for test in self.tests: test.suite_teardown_failed(sub_message) def set_tags(self, tags): if tags: for test in self.tests: test.tags = utils.normalize_tags(test.tags + tags) for suite in self.suites: suite.set_tags(tags) def filter(self, suites=None, tests=None, includes=None, excludes=None, zero_tests_ok=False): self.filter_by_names(suites, tests, zero_tests_ok) self.filter_by_tags(includes, excludes, zero_tests_ok) def filter_by_names(self, suites=None, tests=None, zero_tests_ok=False): if not (suites or tests): return suites = [([], name.split('.')) for name in suites or []] tests = tests or [] if not self._filter_by_names(suites, tests) and not zero_tests_ok: self._raise_no_tests_filtered_by_names(suites, tests) def _filter_by_names(self, suites, tests): suites = self._filter_suite_names(suites) self.suites = [suite for suite in self.suites if suite._filter_by_names(suites, tests)] if not suites: self.tests = [test for test in self.tests if tests == [] or any(utils.matches_any(name, tests, ignore=['_']) for name in [test.name, test.get_long_name()])] else: self.tests = [] return bool(self.suites or self.tests) def _filter_suite_names(self, suites): try: return [self._filter_suite_name(p, s) for p, s in suites] except StopIteration: return [] def _filter_suite_name(self, parent, suite): if utils.matches(self.name, suite[0], ignore=['_']): if len(suite) == 1: raise StopIteration('Match found') return (parent + [suite[0]], suite[1:]) return ([], parent + suite) def _raise_no_tests_filtered_by_names(self, suites, tests): tests = utils.seq2str(tests, lastsep=' or ') suites = utils.seq2str(['.'.join(p + s) for p, s in suites], lastsep=' or ') if not suites: msg = 'test cases named %s.' % tests elif not tests: msg = 'test suites named %s.' % suites else: msg = 'test cases %s in suites %s.' % (tests, suites) raise DataError("Suite '%s' contains no %s" % (self.name, msg)) def filter_by_tags(self, includes=None, excludes=None, zero_tests_ok=False): if not (includes or excludes): return includes = includes or [] excludes = excludes or [] if not self._filter_by_tags(includes, excludes) and not zero_tests_ok: self._raise_no_tests_filtered_by_tags(includes, excludes) def _filter_by_tags(self, incls, excls): self.suites = [suite for suite in self.suites if suite._filter_by_tags(incls, excls)] self.tests = [test for test in self.tests if test.is_included(incls, excls)] return bool(self.suites or self.tests) def _raise_no_tests_filtered_by_tags(self, incls, excls): incl = utils.seq2str(incls) excl = utils.seq2str(excls) msg = "Suite '%s' with " % self.name if incl: msg += 'includes %s ' % incl if excl: msg += 'and ' if excl: msg += 'excludes %s ' % excl raise DataError(msg + 'contains no test cases.') def set_runmode(self, runmode): runmode = runmode.upper() if runmode == 'EXITONFAILURE': self._run_mode_exit_on_failure = True elif runmode == 'SKIPTEARDOWNONEXIT': self._run_mode_skip_teardowns_on_exit = True elif runmode == 'DRYRUN': self._run_mode_dry_run = True elif runmode == 'RANDOM:TEST': random.shuffle(self.tests) elif runmode == 'RANDOM:SUITE': random.shuffle(self.suites) elif runmode == 'RANDOM:ALL': random.shuffle(self.suites) random.shuffle(self.tests) else: return for suite in self.suites: suite.set_runmode(runmode) def set_options(self, settings): self.set_tags(settings['SetTag']) self.filter(settings['SuiteNames'], settings['TestNames'], settings['Include'], settings['Exclude'], settings['RunEmptySuite']) self.set_name(settings['Name']) self.set_doc(settings['Doc']) self.set_metadata(settings['Metadata']) self.set_critical_tags(settings['Critical'], settings['NonCritical']) self._return_status_rc = not settings['NoStatusRC'] if 'RunMode' in settings: map(self.set_runmode, settings['RunMode']) if 'RemoveKeywords' in settings: self.remove_keywords(settings['RemoveKeywords']) def serialize(self, serializer): serializer.start_suite(self) if self.setup is not None: self.setup.serialize(serializer) if self.teardown is not None: self.teardown.serialize(serializer) for suite in self.suites: suite.serialize(serializer) for test in self.tests: test.serialize(serializer) serializer.end_suite(self) @property def return_code(self): rc = min(self.critical_stats.failed, 250) return rc if self._return_status_rc else 0 class BaseTestCase(_TestAndSuiteHelper): def __init__(self, name, parent): _TestAndSuiteHelper.__init__(self, name, parent) self.critical = 'yes' if parent: parent.tests.append(self) def suite_teardown_failed(self, message): self.status = 'FAIL' self._set_teardown_fail_msg(message) def set_criticality(self, critical): self.critical = 'yes' if critical.are_critical(self.tags) else 'no' def is_included(self, incl_tags, excl_tags): """Returns True if this test case is included but not excluded. If no 'incl_tags' are given all tests are considered to be included. """ included = not incl_tags or self._matches_any_tag_rule(incl_tags) excluded = self._matches_any_tag_rule(excl_tags) return included and not excluded def _matches_any_tag_rule(self, tag_rules): """Returns True if any of tag_rules matches self.tags Matching equals supporting AND, & and NOT boolean operators and simple pattern matching. NOT is 'or' operation meaning if any of the NOTs is matching, False is returned. """ return any(self._matches_tag_rule(rule) for rule in tag_rules) def _matches_tag_rule(self, tag_rule): if 'NOT' not in tag_rule: return self._matches_tag(tag_rule) nots = tag_rule.split('NOT') should_match = nots.pop(0) return self._matches_tag(should_match) \ and not any(self._matches_tag(n) for n in nots) def _matches_tag(self, tag): """Returns True if given tag matches any tag from self.tags. Note that given tag may be ANDed combination of multiple tags (e.g. tag1&tag2) and then all of them must match some tag from self.tags. """ for item in tag.split('&'): if not any(utils.matches(t, item, ignore=['_']) for t in self.tags): return False return True def __cmp__(self, other): if self.status != other.status: return -1 if self.status == 'FAIL' else 1 if self.critical != other.critical: return -1 if self.critical == 'yes' else 1 try: return cmp(self.longname, other.longname) except AttributeError: return cmp(self.name, other.name) def serialize(self, serializer): serializer.start_test(self) if self.setup is not None: self.setup.serialize(serializer) for kw in self.keywords: kw.serialize(serializer) if self.teardown is not None: self.teardown.serialize(serializer) serializer.end_test(self) class _Critical: def __init__(self, tags=None, nons=None): self.set(tags, nons) def set(self, tags, nons): self.tags = utils.normalize_tags(tags or []) self.nons = utils.normalize_tags(nons or []) def is_critical(self, tag): return utils.matches_any(tag, self.tags) def is_non_critical(self, tag): return utils.matches_any(tag, self.nons) def are_critical(self, tags): for tag in tags: if self.is_non_critical(tag): return False for tag in tags: if self.is_critical(tag): return True return not self.tags
Python
# Copyright 2008-2011 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from robot import utils class Statistics: def __init__(self, suite, suite_stat_level=-1, tag_stat_include=None, tag_stat_exclude=None, tag_stat_combine=None, tag_doc=None, tag_stat_link=None): self.tags = TagStatistics(tag_stat_include, tag_stat_exclude, tag_stat_combine, tag_doc, tag_stat_link) self.suite = SuiteStatistics(suite, self.tags, suite_stat_level) self.total = TotalStatistics(self.suite) self.tags.sort() def serialize(self, serializer): serializer.start_statistics(self) self.total.serialize(serializer) self.tags.serialize(serializer) self.suite.serialize(serializer) serializer.end_statistics(self) class Stat: def __init__(self, name=''): self.name = name self.passed = 0 self.failed = 0 def add_stat(self, other): self.passed += other.passed self.failed += other.failed def add_test(self, test): if test.status == 'PASS': self.passed += 1 else: self.failed += 1 def fail_all(self): self.failed += self.passed self.passed = 0 def __cmp__(self, other): return cmp(self.name, other.name) def __nonzero__(self): return self.failed == 0 class SuiteStat(Stat): type = 'suite' def __init__(self, suite): Stat.__init__(self, suite.name) self.long_name = suite.get_long_name() def serialize(self, serializer): serializer.suite_stat(self) class TagStat(Stat): type = 'tag' def __init__(self, name, doc='', links=[], critical=False, non_critical=False, combined=''): Stat.__init__(self, name) self.doc = doc self.links = links self.critical = critical self.non_critical = non_critical self.combined = combined self.tests = [] def add_test(self, test): Stat.add_test(self, test) self.tests.append(test) def __cmp__(self, other): if self.critical != other.critical: return cmp(other.critical, self.critical) if self.non_critical != other.non_critical: return cmp(other.non_critical, self.non_critical) if bool(self.combined) != bool(other.combined): return cmp(bool(other.combined), bool(self.combined)) return cmp(self.name, other.name) def serialize(self, serializer): serializer.tag_stat(self) class TotalStat(Stat): type = 'total' def __init__(self, name, suite_stat): Stat.__init__(self, name) self.passed = suite_stat.passed self.failed = suite_stat.failed def serialize(self, serializer): serializer.total_stat(self) class SuiteStatistics: def __init__(self, suite, tag_stats, suite_stat_level=-1): self.all = SuiteStat(suite) self.critical = SuiteStat(suite) self.suites = [] self._process_suites(suite, tag_stats) self._process_tests(suite, tag_stats) self._suite_stat_level = suite_stat_level def _process_suites(self, suite, tag_stats): for subsuite in suite.suites: substat = SuiteStatistics(subsuite, tag_stats) self.suites.append(substat) self.all.add_stat(substat.all) self.critical.add_stat(substat.critical) def _process_tests(self, suite, tag_stats): for test in suite.tests: self.all.add_test(test) if test.critical == 'yes': self.critical.add_test(test) tag_stats.add_test(test, suite.critical) def serialize(self, serializer): serializer.start_suite_stats(self) self._serialize(serializer, self._suite_stat_level) serializer.end_suite_stats(self) def _serialize(self, serializer, max_suite_level, suite_level=1): self.all.serialize(serializer) if max_suite_level < 0 or max_suite_level > suite_level: for suite in self.suites: suite._serialize(serializer, max_suite_level, suite_level+1) class TagStatistics: def __init__(self, include=None, exclude=None, combine=None, docs=None, links=None): self.stats = utils.NormalizedDict() self._include = include or [] self._exclude = exclude or [] self._combine = combine or [] info = TagStatInfo(docs or [], links or []) self._get_doc = info.get_doc self._get_links = info.get_links def add_test(self, test, critical): self._add_tags_statistics(test, critical) self._add_combined_statistics(test) def _add_tags_statistics(self, test, critical): for tag in test.tags: if not self._is_included(tag): continue if tag not in self.stats: self.stats[tag] = TagStat(tag, self._get_doc(tag), self._get_links(tag), critical.is_critical(tag), critical.is_non_critical(tag)) self.stats[tag].add_test(test) def _is_included(self, tag): if self._include and not utils.matches_any(tag, self._include): return False return not utils.matches_any(tag, self._exclude) def _add_combined_statistics(self, test): for pattern, name in self._combine: name = name or pattern if name not in self.stats: self.stats[name] = TagStat(name, self._get_doc(name), self._get_links(name), combined=pattern) if test.is_included([pattern], []): self.stats[name].add_test(test) def serialize(self, serializer): serializer.start_tag_stats(self) for stat in sorted(self.stats.values()): stat.serialize(serializer) serializer.end_tag_stats(self) def sort(self): for stat in self.stats.values(): stat.tests.sort() class TotalStatistics: def __init__(self, suite): self.critical = TotalStat('Critical Tests', suite.critical) self.all = TotalStat('All Tests', suite.all) def serialize(self, serializer): serializer.start_total_stats(self) self.critical.serialize(serializer) self.all.serialize(serializer) serializer.end_total_stats(self) class TagStatInfo: def __init__(self, docs, links): self._docs = [TagStatDoc(*doc) for doc in docs] self._links = [TagStatLink(*link) for link in links] def get_doc(self, tag): return ' & '.join(doc.text for doc in self._docs if doc.matches(tag)) def get_links(self, tag): return [link.get_link(tag) for link in self._links if link.matches(tag)] class TagStatDoc: def __init__(self, pattern, doc): self.text = doc self._pattern = pattern def matches(self, tag): return utils.matches(tag, self._pattern) class TagStatLink: _match_pattern_tokenizer = re.compile('(\*|\?)') def __init__(self, pattern, link, title): self._regexp = self._get_match_regexp(pattern) self._link = link self._title = title.replace('_', ' ') def matches(self, tag): return self._regexp.match(tag) is not None def get_link(self, tag): match = self._regexp.match(tag) if not match: return None link, title = self._replace_groups(self._link, self._title, match) return link, title def _replace_groups(self, link, title, match): for index, group in enumerate(match.groups()): placefolder = '%' + str(index+1) link = link.replace(placefolder, group) title = title.replace(placefolder, group) return link, title def _get_match_regexp(self, pattern): regexp = [] open_parenthesis = False for token in self._match_pattern_tokenizer.split(pattern): if token == '': continue if token == '?': if not open_parenthesis: regexp.append('(') open_parenthesis = True regexp.append('.') continue if open_parenthesis: regexp.append(')') open_parenthesis = False if token == '*': regexp.append('(.*)') continue regexp.append(re.escape(token)) if open_parenthesis: regexp.append(')') return re.compile('^%s$' % ''.join(regexp), re.IGNORECASE)
Python
#!/usr/bin/env python """pt2html.py -- Creates HTML version of Python Tutorial Usage: pt2html.py """ import sys import os import shutil import time sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'userguide')) import ug2html # This also initializes docutils and pygments def create_tutorial(): from docutils.core import publish_cmdline print 'Creating Python Tutorial ...' os.chdir(os.path.dirname(os.path.abspath(__file__))) description = 'Python Tutorial for Robot Framework Library Developers' arguments = ''' --time --stylesheet-path=../userguide/src/userguide.css PythonTutorial.rst PythonTutorial.html '''.split('\n')[1:-1] publish_cmdline(writer_name='html', description=description, argv=arguments) path = arguments[-1] print os.path.abspath(path) return path if __name__ == '__main__': create_tutorial()
Python
def simple_keyword(): """Log a message""" print 'You have used the simplest keyword.' def greet(name): """Logs a friendly greeting to person given as argument""" print 'Hello %s!' % name def multiply_by_two(number): """Returns the given number multiplied by two The result is always a floating point number. This keyword fails if the given `number` cannot be converted to number. """ return float(number) * 2 def numbers_should_be_equal(first, second): print '*DEBUG* Got arguments %s and %s' % (first, second) if float(first) != float(second): raise AssertionError('Given numbers are unequal!')
Python
#!/usr/bin/env python """ug2html.py -- Creates HTML version of Robot Framework User Guide Usage: ug2html.py [ cr(eate) | dist | zip ] create .. Creates the user guide so that it has relative links to images, library docs, etc. This version is stored in the version control and distributed with the source distribution. dist .... Creates the user guide under 'robotframework-userguide-<version>' directory and also copies all needed images and other link targets there. The created output directory can thus be distributed independently. zip ..... Uses 'dist' to create a stand-alone distribution and then packages it into 'robotframework-userguide-<version>.zip' Version number to use is got automatically from 'src/robot/version.py' file created by 'package.py'. """ import os import sys import shutil # First part of this file is Pygments configuration and actual # documentation generation follows it. # # # Pygments configuration # ---------------------- # # This code is from 'external/rst-directive.py' file included in Pygments 0.9 # distribution. For more details see http://pygments.org/docs/rstdirective/ # """ The Pygments MoinMoin Parser ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This fragment is a Docutils_ 0.4 directive that renders source code (to HTML only, currently) via Pygments. To use it, adjust the options below and copy the code into a module that you import on initialization. The code then automatically registers a ``sourcecode`` directive that you can use instead of normal code blocks like this:: .. sourcecode:: python My code goes here. If you want to have different code styles, e.g. one with line numbers and one without, add formatters with their names in the VARIANTS dict below. You can invoke them instead of the DEFAULT one by using a directive option:: .. sourcecode:: python :linenos: My code goes here. Look at the `directive documentation`_ to get all the gory details. .. _Docutils: http://docutils.sf.net/ .. _directive documentation: http://docutils.sourceforge.net/docs/howto/rst-directives.html :copyright: 2007 by Georg Brandl. :license: BSD, see LICENSE for more details. """ # Options # ~~~~~~~ # Set to True if you want inline CSS styles instead of classes INLINESTYLES = False from pygments.formatters import HtmlFormatter # The default formatter DEFAULT = HtmlFormatter(noclasses=INLINESTYLES) # Add name -> formatter pairs for every variant you want to use VARIANTS = { # 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True), } from docutils import nodes from docutils.parsers.rst import directives from pygments import highlight from pygments.lexers import get_lexer_by_name, TextLexer def pygments_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): try: lexer = get_lexer_by_name(arguments[0]) except ValueError: # no lexer found - use the text one instead of an exception lexer = TextLexer() # take an arbitrary option if more than one is given formatter = options and VARIANTS[options.keys()[0]] or DEFAULT # possibility to read the content from an external file filtered = [ line for line in content if line.strip() ] if len(filtered) == 1: path = filtered[0].replace('/', os.sep) if os.path.isfile(path): content = open(path).read().splitlines() parsed = highlight(u'\n'.join(content), lexer, formatter) return [nodes.raw('', parsed, format='html')] pygments_directive.arguments = (1, 0, 1) pygments_directive.content = 1 pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS]) directives.register_directive('sourcecode', pygments_directive) # # Create the user guide using docutils # # This code is based on rst2html.py distributed with docutils # try: import locale locale.setlocale(locale.LC_ALL, '') except: pass def create_userguide(): from docutils.core import publish_cmdline print 'Creating user guide ...' ugdir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ugdir, '..', '..', 'src', 'robot')) from version import get_version print 'Version:', get_version() vfile = open(os.path.join(ugdir, 'src', 'version.txt'), 'w') vfile.write('.. |version| replace:: %s\n' % get_version()) vfile.close() description = 'HTML generator for Robot Framework User Guide.' arguments = ''' --time --stylesheet-path=src/userguide.css src/RobotFrameworkUserGuide.txt RobotFrameworkUserGuide.html '''.split('\n')[1:-1] os.chdir(ugdir) publish_cmdline(writer_name='html', description=description, argv=arguments) os.unlink(vfile.name) ugpath = os.path.abspath(arguments[-1]) print ugpath return ugpath, get_version(sep='-') # # Create user guide distribution directory # def create_distribution(): import re from urlparse import urlparse ugpath, version = create_userguide() # we are in doc/userguide after this outdir = 'robotframework-userguide-%s' % version tools = os.path.join(outdir, 'tools') templates = os.path.join(outdir, 'templates') libraries = os.path.join(outdir, 'libraries') images = os.path.join(outdir, 'images') print 'Creating distribution directory ...' if os.path.exists(outdir): print 'Removing previous user guide distribution' shutil.rmtree(outdir) for dirname in [outdir, tools, templates, libraries, images]: print "Creating output directory '%s'" % dirname os.mkdir(dirname) def replace_links(res): if not res.group(5): return res.group(0) scheme, _, path, _, _, fragment = urlparse(res.group(5)) if scheme or (fragment and not path): return res.group(0) replaced_link = '%s %s="%%s/%s"' % (res.group(1), res.group(4), os.path.basename(path)) if path.startswith('../../tools'): copy(path, tools) copy_tool_images(path) replaced_link = replaced_link % 'tools' elif path.startswith('../../templates'): copy(path, templates) replaced_link = replaced_link % 'templates' elif path.startswith('../libraries'): copy(path, libraries) replaced_link = replaced_link % 'libraries' elif path.startswith('src/'): copy(path, images) replaced_link = replaced_link % 'images' else: raise ValueError('Invalid link target: %s' % path) print "Modified link '%s' -> '%s'" % (res.group(0), replaced_link) return replaced_link def copy(source, dest): print "Copying '%s' -> '%s'" % (source, dest) shutil.copy(source, dest) def copy_tool_images(path): indir = os.path.dirname(path) for line in open(os.path.splitext(path)[0]+'.txt').readlines(): if line.startswith('.. figure::'): copy(os.path.join(indir, line.strip().split()[-1]), tools) link_regexp = re.compile(''' (<(a|img)\s+.*?) (\s+(href|src)="(.*?)"|>) ''', re.VERBOSE | re.DOTALL | re.IGNORECASE) content = open(ugpath).read() content = link_regexp.sub(replace_links, content) outfile = open(os.path.join(outdir, os.path.basename(ugpath)), 'wb') outfile.write(content) outfile.close() print os.path.abspath(outfile.name) return outdir # # Create a zip distribution package # def create_zip(): ugdir = create_distribution() zip_distribution(ugdir) def zip_distribution(dirpath): """Generic zipper. Used also by qs2html.py """ from zipfile import ZipFile, ZIP_DEFLATED print 'Creating zip package ...' zippath = os.path.normpath(dirpath) + '.zip' zipfile = ZipFile(zippath, 'w', compression=ZIP_DEFLATED) for root, _, files in os.walk(dirpath): for name in files: path = os.path.join(root, name) print "Adding '%s'" % path zipfile.write(path) zipfile.close() print 'Removing distribution directory', dirpath shutil.rmtree(dirpath) print os.path.abspath(zippath) if __name__ == '__main__': actions = { 'create': create_userguide, 'cr': create_userguide, 'dist': create_distribution, 'zip': create_zip } try: actions[sys.argv[1]](*sys.argv[2:]) except (KeyError, IndexError, TypeError): print __doc__
Python
#!/usr/bin/env python """Usage: check_test_times.py inpath [outpath] Reads result of a test run from Robot output file and checks that no test took longer than 3 minutest to execute. If outpath is not given, the result is written over the original file. """ import sys from robot.output import TestSuite def check_tests(inpath, outpath=None): if not outpath: outpath = inpath suite = TestSuite(inpath) _check_execution_times(suite) suite.write_to_file(outpath) def _check_execution_times(suite): for test in suite.tests: if test.status == 'PASS' and test.elapsedtime > 1000 * 60 * 3: test.status = 'FAIL' test.message = 'Test execution time was too long: %s' % test.elapsedtime for suite in suite.suites: _check_execution_times(suite) if __name__ == '__main__': try: check_tests(*sys.argv[1:]) except TypeError: print __doc__
Python
"""Robot Framework test library example that calls C code. This example uses Python's standard `ctypes` module, which requires that the C code is compiled into a shared library. It is also possible to execute this file from the command line to test the C code manually. """ from ctypes import CDLL, c_char_p LIBRARY = CDLL('./liblogin.so') # On Windows we'd use '.dll' def check_user(username, password): """Validates user name and password using imported shared C library.""" if not LIBRARY.validate_user(c_char_p(username), c_char_p(password)): raise AssertionError('Wrong username/password combination') if __name__ == '__main__': import sys try: check_user(*sys.argv[1:]) except TypeError: print 'Usage: %s username password' % sys.argv[0] except AssertionError, err: print err else: print 'Valid password'
Python
class CheckMultipleItemsLibrary: def items_should_not_contain(self, value, *items): """Checks that none of the given 'items' contains the given 'value'.""" items_containing_value = [ item for item in items if value in item ] if items_containing_value: message = "Items '%s' contains '%s'" message = message % (', '.join(items_containing_value), value) raise AssertionError(message)
Python
#!/usr/bin/env python import sys import os import tempfile DATABASE_FILE = os.path.join(tempfile.gettempdir(), 'robotframework-quickstart-db.txt') class DataBase(object): def __init__(self, dbfile): """This class reads ands writes user data in a 'database'. dbfile can be either or string or already opened file object. In the former case, dbfile is considered to be path. If a file object is given it must be opened in a mode that allows both reading and writing. """ self._dbfile, self._users = self._read_users(dbfile) def _read_users(self, dbfile): users = {} if isinstance(dbfile, basestring): if not os.path.isfile(dbfile): return open(dbfile, 'w'), users else: dbfile = open(dbfile, 'r+') for row in dbfile.read().splitlines(): user = User(*row.split('\t')) users[user.username] = user return dbfile, users def create_user(self, username, password): try: user = User(username, password) except ValueError, err: return 'Creating user failed: %s' % err self._users[user.username] = user return 'SUCCESS' def login(self, username, password): if self._is_valid_user(username, password): self._users[username].status = 'Active' return 'Logged In' return 'Access Denied' def _is_valid_user(self, username, password): return username in self._users and \ self._users[username].password == password def change_password(self, username, old_pwd, new_pwd): try: if not self._is_valid_user(username, old_pwd): raise ValueError('Access Denied') self._users[username].password = new_pwd except ValueError, err: return 'Changing password failed: %s' % err else: return 'SUCCESS' def close(self): self._dbfile.seek(0) self._dbfile.truncate() for user in self._users.values(): user.serialize(self._dbfile) self._dbfile.close() class User(object): def __init__(self, username, password, status='Inactive'): self.username = username self.password = password self.status = status def _get_password(self): return self._password def _set_password(self, password): self._validate_password(password) self._password = password password = property(_get_password, _set_password) def _validate_password(self, password): if not (6 < len(password) < 13): raise ValueError('Password must be 7-12 characters long') has_lower = has_upper = has_number = has_invalid = False for char in password: if char.islower(): has_lower = True elif char.isupper(): has_upper = True elif char.isdigit(): has_number = True else: has_invalid = True break if has_invalid or not (has_lower and has_upper and has_number): raise ValueError('Password must be a combination of lowercase ' 'and uppercase letters and numbers') def serialize(self, dbfile): dbfile.write('%s\t%s\t%s\n' % (self.username, self.password, self.status)) def login(username, password): db = DataBase(DATABASE_FILE) print db.login(username, password) db.close() def create_user(username, password): db = DataBase(DATABASE_FILE) print db.create_user(username, password) db.close() def change_password(username, old_pwd, new_pwd): db = DataBase(DATABASE_FILE) print db.change_password(username, old_pwd, new_pwd) db.close() def help(): print 'Usage: %s { create | login | change-password | help }' \ % os.path.basename(sys.argv[0]) if __name__ == '__main__': actions = {'create': create_user, 'login': login, 'change-password': change_password, 'help': help} try: action = sys.argv[1] except IndexError: action = 'help' args = sys.argv[2:] try: actions[action](*args) except (KeyError, TypeError): help()
Python
#!/usr/bin/env python """qs2html.py -- Creates HTML version of Robot Framework Quick Start Guide Usage: qs2html.py [ cr(eate) | dist | zip ] create .. Creates the HTML version of the Quick Start Guide. dist .... Creates the Quick Start Guide and copies it and all its dependencies under directory named 'robotframework-quickstart-<date>'. zip ..... Uses 'dist' to create the Quick Start Guide distribution and then packages it into 'robotframework-quickstart-<date>.zip'. """ import sys import os import shutil import time sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'userguide')) import ug2html # This also initializes docutils and pygments def create_quickstart(): from docutils.core import publish_cmdline print 'Creating Quick Start Guide ...' qsdir = os.path.dirname(os.path.abspath(__file__)) description = 'Quick Start Guide for Robot Framework' arguments = ''' --time --stylesheet-path=../userguide/src/userguide.css quickstart.rst quickstart.html '''.split('\n')[1:-1] os.chdir(qsdir) publish_cmdline(writer_name='html', description=description, argv=arguments) qspath = arguments[-1] print os.path.abspath(qspath) return qspath def create_distribution(): qspath = create_quickstart() # we are in doc/quickstart after this outdir = 'robotframework-quickstart-%d%02d%02d' % time.localtime()[:3] files = { '': [qspath], 'testlibs': ['LoginLibrary.py'], 'sut': ['login.py', 'test_login.py'] } print 'Creating distribution directory ...' if os.path.exists(outdir): print 'Removing previous distribution' shutil.rmtree(outdir) os.mkdir(outdir) for dirname, files in files.items(): dirpath = os.path.join(outdir, dirname) if not os.path.exists(dirpath): print "Creating output directory '%s'" % dirpath os.mkdir(dirpath) for name in files: source = os.path.join(dirname, name) print "Copying '%s' -> '%s'" % (source, dirpath) shutil.copy(source, dirpath) return outdir def create_zip(): qsdir = create_distribution() ug2html.zip_distribution(qsdir) if __name__ == '__main__': actions = { 'create': create_quickstart, 'cr': create_quickstart, 'dist': create_distribution, 'zip': create_zip } try: actions[sys.argv[1]](*sys.argv[2:]) except (KeyError, IndexError, TypeError): print __doc__
Python
import os import sys import subprocess class LoginLibrary: def __init__(self): self._sut_path = os.path.join(os.path.dirname(__file__), '..', 'sut', 'login.py') self._status = '' def create_user(self, username, password): self._run_command('create', username, password) def change_password(self, username, old_pwd, new_pwd): self._run_command('change-password', username, old_pwd, new_pwd) def attempt_to_login_with_credentials(self, username, password): self._run_command('login', username, password) def status_should_be(self, expected_status): if expected_status != self._status: raise AssertionError("Expected status to be '%s' but was '%s'" % (expected_status, self._status)) def _run_command(self, command, *args): if not sys.executable: raise RuntimeError("Could not find Jython installation") command = [sys.executable, self._sut_path, command] + list(args) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self._status = process.communicate()[0].strip()
Python
#!/usr/bin/env python """Usage: lib2html.py [ library | all ] Libraries: BuiltIn (bu) Collections (co) Dialogs (di) OperatingSystem (op) Screenshot (sc) String (st) Telnet (te) """ import sys import tempfile import os import re ROOT = os.path.normpath(os.path.join(os.path.abspath(__file__),'..','..','..')) LIBRARIES = {} for line in __doc__.splitlines(): res = re.search('(\w+) \((\w\w)\)', line) if res: name, alias = res.groups() LIBRARIES[name.lower()] = LIBRARIES[alias] = name sys.path.insert(0, os.path.join(ROOT,'tools','libdoc')) sys.path.insert(0, os.path.join(ROOT,'src')) from libdoc import LibraryDoc, create_html_doc def create_libdoc(name): ipath = os.path.join(ROOT,'src','robot','libraries',name+'.py') opath = os.path.join(ROOT,'doc','libraries',name+'.html') create_html_doc(LibraryDoc(ipath), opath) print opath if __name__ == '__main__': try: name = sys.argv[1].lower() if name == 'all': for name in sorted(set(LIBRARIES.values())): create_libdoc(name) else: create_libdoc(LIBRARIES[name]) except (IndexError, KeyError): print __doc__
Python
import os import sys from distutils.sysconfig import get_python_lib def egg_preinstall(temp_robot_path, scripts): """Updates platform specific startup scripts. Run as part of the easy_install egg creation procedure. This is the only way to get the scripts updated when the easy_install is used. Updates the scripts before the egg is created and therefore the created egg cannot be used at any other machine unless the Python and Jython installations are exactly equal. """ major, minor = sys.version_info[0:2] version = os.path.basename(temp_robot_path) version = version.replace('-', '_').replace('_', '-', 1) egg_name = '%s-py%s.%s.egg' % (version, major, minor) robot_dir = os.path.join(_find_easy_install_dir() or get_python_lib(), egg_name, 'robot') _update_scripts(scripts, temp_robot_path, robot_dir) def generic_install(script_names, script_dir, robot_dir): """Updates given startup scripts. Run as part of the generic installation procedure from 'setup.py' after running 'python setyp.py install'. """ _update_scripts(script_names, script_dir, robot_dir) def windows_binary_install(): """Updates start-up scripts. Executed as the last part of Windows binary installation started by running 'robotframework-<version>.win32.exe'. """ scripts = ['pybot.bat','jybot.bat', 'rebot.bat'] script_dir = os.path.join(sys.prefix, 'Scripts') robot_dir = _get_installation_dir() python_exe = os.path.join(sys.prefix, 'python.exe') # sys.executable doesn't work here try: _update_scripts(scripts, script_dir, robot_dir, python_exe) print '\nInstallation was successful. Happy Roboting!' except Exception, err: print '\nRunning post-install script failed: %s' % err print 'Robot Framework start-up scripts may not work correctly.' def windows_binary_uninstall(): """Deletes Jython compiled files ('*$py.class') This function is executed as part of the Windows binary uninstallation started from 'Add/Remove Programs'. Uninstaller deletes files only if installer has created them and also deletes directories only if they are empty. Thus compiled files created by Jython must be deleted separately. """ for base, dirs, files in os.walk(_get_installation_dir()): for name in files: if name.endswith('$py.class'): path = os.path.join(base, name) try: os.remove(path) except Exception, err: print "Failed to remove Jython compiled file '%s': %s" \ % (path, str(err)) def _find_easy_install_dir(): """Returns the installation directory that easy_install will actually use. This is a workaround because: 1. distutils.sysconfig.get_python_lib() is not aware of easy_install way of managing installation paths. 2. easy_install doesn't pass its install_dir as a command line argument to the setup script. """ try: import inspect f = inspect.currentframe() try: while True: if f is None: return instance = f.f_locals.get("self") if instance and hasattr(instance, "install_dir"): return getattr(instance, "install_dir") f = f.f_back finally: del f except Exception, err: print "Failed to retrieve easy_install_dir: %s" % str(err) def _get_installation_dir(): """Returns installation location. Works also with easy_install.""" try: import robot except ImportError: # Workaround for Windows installer problem with Python 2.6.1 # http://code.google.com/p/robotframework/issues/detail?id=196 class FakeModule: def __getattr__(self, name): raise RuntimeError('Fake module set by robot_postinstall.py') sys.modules['urllib'] = FakeModule() import robot return os.path.dirname(os.path.abspath(robot.__file__)) def _update_scripts(scripts, script_dir, robot_dir, python_exe=sys.executable): print 'Creating Robot Framework runner scripts...' print 'Installation directory:', robot_dir if os.name != 'java': jython_exe, how_found = _find_jython() print 'Python executable:', python_exe print 'Jython executable: %s (%s)' % (jython_exe, how_found) else: jython_exe = python_exe print 'Jython executable:', jython_exe for script in scripts: path = os.path.join(script_dir, script) content = _read(path) for pattern, replace in [ ('[ROBOT_DIR]', robot_dir), ('[PYTHON_EXECUTABLE]', python_exe), ('[JYTHON_EXECUTABLE]', jython_exe) ]: content = content.replace(pattern, replace) _write(path, content) name = os.path.splitext(os.path.basename(script))[0].capitalize() print '%s script: %s' % (name, path) def _read(path): reader = open(path) content = reader.read() reader.close() return content def _write(path, content): os.chmod(path, 0755) writer = open(path, 'w') writer.write(content) writer.close() def _find_jython(): """Tries to find path to Jython and returns it and how it was found. First Jython is searched from PATH, then checked is JYTHON_HOME set and finally Jython installation directory is searched from the system. """ jyexe, search_dirs = _get_platform_jython_search_items() env1, env2 = os.sep == '/' and ('$','') or ('%','%') if _jython_in_path(jyexe): return jyexe, 'in %sPATH%s' % (env1, env2) elif _is_jython_dir(os.environ.get('JYTHON_HOME','notset'), jyexe): jyexe = os.path.join(os.environ['JYTHON_HOME'], jyexe) return jyexe, 'from %sJYTHON_HOME%s' % (env1, env2) return _search_jython_from_dirs(search_dirs, jyexe) def _get_platform_jython_search_items(): """Returns Jython executable and a list of dirs where to search it""" if os.name == 'nt': return 'jython.bat', ['C:\\', 'D:\\'] elif sys.platform.count('cygwin'): return 'jython.bat', ['/cygdrive/c', '/cygdrive/d'] else: return 'jython', ['/usr/local','/opt'] def _jython_in_path(jyexe): out = os.popen('%s --version 2>&1' % jyexe ) found = out.read().startswith('Jython 2.') out.close() return found def _search_jython_from_dirs(search_dirs, jyexe, recursions=1, raise_unless_found=False): excl_dirs = ['WINNT','RECYCLER'] # no need to search from these for dir in search_dirs: try: dirs = [ os.path.join(dir,item) for item in os.listdir(dir) if item not in excl_dirs ] except: # may not have rights to read the dir etc. continue dirs = [ item for item in dirs if os.path.isdir(item) ] matches = [ item for item in dirs if _is_jython_dir(item, jyexe) ] if len(matches) > 0: # if multiple matches, the last one probably the latest version return os.path.join(dir, matches[-1], jyexe), 'found from system' if recursions > 0: try: return _search_jython_from_dirs(dirs, jyexe, recursions-1, True) except ValueError: pass if raise_unless_found: raise ValueError, 'not found' return jyexe, 'default value' def _is_jython_dir(dir, jyexe): if not os.path.basename(os.path.normpath(dir)).lower().startswith('jython'): return False try: items = os.listdir(dir) except: # may not have rights to read the dir etc. return False return jyexe in items and 'jython.jar' in items if __name__ == '__main__': # This is executed when run as a post-install script for Windows binary # distribution. Executed both when installed and when uninstalled from # Add/Remove Programs. For more details see # 5.3 Creating Windows Installers # http://docs.python.org/dist/postinstallation-script.html # # If installation is done using 'easy_install', this script is not run # automatically. It is possible to run this script manually without # arguments to update start-up scripts in that case. if len(sys.argv) < 2 or sys.argv[1] == '-install': windows_binary_install() elif sys.argv[1] == '-remove': windows_binary_uninstall()
Python
#coding=utf8 import datetime import urllib2,re import PyRSS2Gen ''' Created on 2010-5-20 @author: Fred <me@fengsage.cn> ''' REG_BLOG_PAGE = u'<a href=([/,"]?/[^>]*/blog/index/\d*["]?)>' REG_BLOG_TITLE = u'<div class="tit"><a href="(/[^>]*/blog/item/[^>]*.html)" target="_blank">' REG_ARTICLE_TITLE = u'<div class="tit">([^>,/,<]*)</div>' REG_ARTICLE_CONTENT = u'<td><div id="blog_text" class="[^>]*" [\s\S]*?</div></td>' REG_ARTICLE_CATAGORY = u'<a href="/[^>]*/blog/category/[^>]*>([^>]*)</a>' REG_ARTICLE_DATETIME = u'<div class="date">([^>,/,<]*)</div>' class BaiduMove(object): BAIDU_HOME = 'http://hi.baidu.com/%s' author = 'Fred' blog_id = '' def __init__(self,author,blog_id): self.author = author self.blog_id = blog_id def readPage(self,url): #模拟浏览器 header = { 'Host':'hi.baidu.com',\ 'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9',\ 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\ 'Accept-Language':'zh-cn,zh;q=0.5'} req = urllib2.Request(url,None,header) try: response = urllib2.urlopen(req) except: print 'open exception' return 0 html_content = response.read().replace('&nbsp;','').decode('gbk') #百度空间需要gbk来解码 return html_content #根据表达式返回列表 def findList(self,content,reg): link_list = re.findall(reg,content) return link_list #页面采集 def articleList(self): article_list = [] blog_content = self.readPage(self.BAIDU_HOME%(self.blog_id+'/blog')) blog_page_url = self.findList(blog_content,REG_BLOG_PAGE) if blog_page_url==[]: print '您的博客ID输入错误!或该博客文章数过少' return 0 min_page = int(blog_page_url[0].replace('"','').replace('/%s/blog/index/'%self.blog_id,'')) #第一页 max_page = int(blog_page_url[-1].replace('"','').replace('/%s/blog/index/'%self.blog_id,'')) #最大页 if min_page == max_page-1: max_page = int(blog_page_url[-2].replace('"','').replace('/%s/blog/index/'%self.blog_id,'')) #最大页 print '博客%s共%s页'%(self.blog_id,max_page+1) for page_index in range(0,max_page+1): page_url = self.BAIDU_HOME%(self.blog_id+'/blog/index/'+str(page_index)) print '第%d页%s分析...'%(page_index+1,page_url) page_content = self.readPage(page_url) article_url = self.findList(page_content, REG_BLOG_TITLE) for article in article_url: article_url = self.BAIDU_HOME%(article[1:]) article_list.append(article_url) print '共发现%s篇博文'%len(article_list) return article_list #文章采集 def articleBody(self,url): print '读取%s'%url article_html = self.readPage(url).replace('\n','') # print article_html #获取博文标题 article_title = self.findList(article_html, REG_ARTICLE_TITLE)[0] article_title = re.sub('&#(\d+);', '-', article_title) # ''.join([unichr(int(x)) for x in re.findall(r'&#(\d+);', article_title)]) #获取博文时间 article_date = self.findList(article_html, REG_ARTICLE_DATETIME)[0] #获取博文分类 article_category = self.findList(article_html, REG_ARTICLE_CATAGORY)[0].replace(u'类别:','') #获取博文正文 article_content = self.findList(article_html, REG_ARTICLE_CONTENT)[0]\ .replace('id="blog_text" class="cnt"','')[12:][:-11] # print article_content article = {'article_url':url,\ 'article_title':article_title,\ 'article_date':article_date,\ 'article_category':article_category,\ 'article_content':article_content,\ 'article_author':self.author} return article def rss_item(self,articleList): rss_item = [] article_url_list = articleList for article_url in article_url_list: acticle_body = self.articleBody(article_url) rss_item.append( PyRSS2Gen.RSSItem( title = self.formatString(acticle_body.get('article_title')), link = self.formatString(acticle_body.get('article_url')), description = self.formatString(acticle_body.get('article_content')), categories = [acticle_body.get('article_category')], guid = PyRSS2Gen.Guid(acticle_body.get('article_url')), pubDate = acticle_body.get('article_date'), author = self.formatString(acticle_body.get('article_author')))) return rss_item #输出RSS def articleToRSS(self,filename,cut=1): articleList = self.articleList() if cut>1: print '生成%d份文件'%cut #计算分割范围,140/5=28,184/5=36 articleCount = len(articleList) articlePage = articleCount/cut #切割文件 for i in range(0,cut): print '分割范围%d-%d'%(articlePage*i,articlePage*(i+1)) if i != (cut-1): rss_item = self.rss_item(articleList[articlePage*i:articlePage*(i+1)]) else: rss_item = self.rss_item(articleList[articlePage*i:articleCount]) rss = PyRSS2Gen.RSS2( title = "百度空间搬家工具", link = "http://fengsageblog.appspot.com", description = "百度空间搬家工具", copyright = '百度空间搬家工具 ad@fengsage.cn', lastBuildDate = datetime.datetime.now(), items = rss_item ) rss.write_xml(open(filename+"_%d.xml"%i, "w"),'utf-8') print '搬家结束' #字符转义 def formatString(self,str): format_str = '<![CDATA['+str+']]>' return format_str if __name__=='__main__': baidu = BaiduMove('fred','429263181') baidu.articleToRSS('Hibaidu_fred',10) # print baidu.articleBody('http://hi.baidu.com/429263181/blog/item/ffc01946d29129016b63e5c6.html')
Python
"""PyRSS2Gen - A Python library for generating RSS 2.0 feeds.""" __name__ = "PyRSS2Gen" __version__ = (1, 0, 0) __author__ = "Andrew Dalke <dalke@dalkescientific.com>" _generator_name = __name__ + "-" + ".".join(map(str, __version__)) import datetime # Could make this the base class; will need to add 'publish' class WriteXmlMixin: def write_xml(self, outfile, encoding = "iso-8859-1"): from xml.sax import saxutils handler = saxutils.XMLGenerator(outfile, encoding) handler.startDocument() self.publish(handler) handler.endDocument() def to_xml(self, encoding = "iso-8859-1"): try: import cStringIO as StringIO except ImportError: import StringIO f = StringIO.StringIO() self.write_xml(f, encoding) return f.getvalue() def _element(handler, name, obj, d = {}): if isinstance(obj, basestring) or obj is None: # special-case handling to make the API easier # to use for the common case. handler.startElement(name, d) if obj is not None: handler.ignorableWhitespace(obj) handler.endElement(name) else: # It better know how to emit the correct XML. obj.publish(handler) def _opt_element(handler, name, obj): if obj is None: return _element(handler, name, obj) def _format_date(dt): """convert a datetime into an RFC 822 formatted date Input date must be in GMT. """ # Looks like: # Sat, 07 Sep 2002 00:00:01 GMT # Can't use strftime because that's locale dependent # # Isn't there a standard way to do this for Python? The # rfc822 and email.Utils modules assume a timestamp. The # following is based on the rfc822 module. return "%s, %02d %s %04d %02d:%02d:%02d GMT" % ( ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()], dt.day, ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][dt.month-1], dt.year, dt.hour, dt.minute, dt.second) ## # A couple simple wrapper objects for the fields which # take a simple value other than a string. class IntElement: """implements the 'publish' API for integers Takes the tag name and the integer value to publish. (Could be used for anything which uses str() to be published to text for XML.) """ element_attrs = {} def __init__(self, name, val): self.name = name self.val = val def publish(self, handler): handler.startElement(self.name, self.element_attrs) handler.characters(str(self.val)) handler.endElement(self.name) class DateElement: """implements the 'publish' API for a datetime.datetime Takes the tag name and the datetime to publish. Converts the datetime to RFC 2822 timestamp (4-digit year). """ def __init__(self, name, dt): self.name = name self.dt = dt def publish(self, handler): _element(handler, self.name, _format_date(self.dt)) #### class Category: """Publish a category element""" def __init__(self, category, domain = None): self.category = category self.domain = domain def publish(self, handler): d = {} if self.domain is not None: d["domain"] = self.domain _element(handler, "category", self.category, d) class Cloud: """Publish a cloud""" def __init__(self, domain, port, path, registerProcedure, protocol): self.domain = domain self.port = port self.path = path self.registerProcedure = registerProcedure self.protocol = protocol def publish(self, handler): _element(handler, "cloud", None, { "domain": self.domain, "port": str(self.port), "path": self.path, "registerProcedure": self.registerProcedure, "protocol": self.protocol}) class Image: """Publish a channel Image""" element_attrs = {} def __init__(self, url, title, link, width = None, height = None, description = None): self.url = url self.title = title self.link = link self.width = width self.height = height self.description = description def publish(self, handler): handler.startElement("image", self.element_attrs) _element(handler, "url", self.url) _element(handler, "title", self.title) _element(handler, "link", self.link) width = self.width if isinstance(width, int): width = IntElement("width", width) _opt_element(handler, "width", width) height = self.height if isinstance(height, int): height = IntElement("height", height) _opt_element(handler, "height", height) _opt_element(handler, "description", self.description) handler.endElement("image") class Guid: """Publish a guid Defaults to being a permalink, which is the assumption if it's omitted. Hence strings are always permalinks. """ def __init__(self, guid, isPermaLink = 1): self.guid = guid self.isPermaLink = isPermaLink def publish(self, handler): d = {} if self.isPermaLink: d["isPermaLink"] = "true" else: d["isPermaLink"] = "false" _element(handler, "guid", self.guid, d) class TextInput: """Publish a textInput Apparently this is rarely used. """ element_attrs = {} def __init__(self, title, description, name, link): self.title = title self.description = description self.name = name self.link = link def publish(self, handler): handler.startElement("textInput", self.element_attrs) _element(handler, "title", self.title) _element(handler, "description", self.description) _element(handler, "name", self.name) _element(handler, "link", self.link) handler.endElement("textInput") class Enclosure: """Publish an enclosure""" def __init__(self, url, length, type): self.url = url self.length = length self.type = type def publish(self, handler): _element(handler, "enclosure", None, {"url": self.url, "length": str(self.length), "type": self.type, }) class Source: """Publish the item's original source, used by aggregators""" def __init__(self, name, url): self.name = name self.url = url def publish(self, handler): _element(handler, "source", self.name, {"url": self.url}) class SkipHours: """Publish the skipHours This takes a list of hours, as integers. """ element_attrs = {} def __init__(self, hours): self.hours = hours def publish(self, handler): if self.hours: handler.startElement("skipHours", self.element_attrs) for hour in self.hours: _element(handler, "hour", str(hour)) handler.endElement("skipHours") class SkipDays: """Publish the skipDays This takes a list of days as strings. """ element_attrs = {} def __init__(self, days): self.days = days def publish(self, handler): if self.days: handler.startElement("skipDays", self.element_attrs) for day in self.days: _element(handler, "day", day) handler.endElement("skipDays") class RSS2(WriteXmlMixin): """The main RSS class. Stores the channel attributes, with the "category" elements under ".categories" and the RSS items under ".items". """ rss_attrs = {"version": "2.0"} element_attrs = {} def __init__(self, title, link, description, language = None, copyright = None, managingEditor = None, webMaster = None, pubDate = None, # a datetime, *in* *GMT* lastBuildDate = None, # a datetime categories = None, # list of strings or Category generator = _generator_name, docs = "http://blogs.law.harvard.edu/tech/rss", cloud = None, # a Cloud ttl = None, # integer number of minutes image = None, # an Image rating = None, # a string; I don't know how it's used textInput = None, # a TextInput skipHours = None, # a SkipHours with a list of integers skipDays = None, # a SkipDays with a list of strings items = None, # list of RSSItems ): self.title = title self.link = link self.description = description self.language = language self.copyright = copyright self.managingEditor = managingEditor self.webMaster = webMaster self.pubDate = pubDate self.lastBuildDate = lastBuildDate if categories is None: categories = [] self.categories = categories self.generator = generator self.docs = docs self.cloud = cloud self.ttl = ttl self.image = image self.rating = rating self.textInput = textInput self.skipHours = skipHours self.skipDays = skipDays if items is None: items = [] self.items = items def publish(self, handler): handler.startElement("rss", self.rss_attrs) handler.startElement("channel", self.element_attrs) _element(handler, "title", self.title) _element(handler, "link", self.link) _element(handler, "description", self.description) self.publish_extensions(handler) _opt_element(handler, "language", self.language) _opt_element(handler, "copyright", self.copyright) _opt_element(handler, "managingEditor", self.managingEditor) _opt_element(handler, "webMaster", self.webMaster) pubDate = self.pubDate if isinstance(pubDate, datetime.datetime): pubDate = DateElement("pubDate", pubDate) _opt_element(handler, "pubDate", pubDate) lastBuildDate = self.lastBuildDate if isinstance(lastBuildDate, datetime.datetime): lastBuildDate = DateElement("lastBuildDate", lastBuildDate) _opt_element(handler, "lastBuildDate", lastBuildDate) for category in self.categories: if isinstance(category, basestring): category = Category(category) category.publish(handler) _opt_element(handler, "generator", self.generator) _opt_element(handler, "docs", self.docs) if self.cloud is not None: self.cloud.publish(handler) ttl = self.ttl if isinstance(self.ttl, int): ttl = IntElement("ttl", ttl) _opt_element(handler, "tt", ttl) if self.image is not None: self.image.publish(handler) _opt_element(handler, "rating", self.rating) if self.textInput is not None: self.textInput.publish(handler) if self.skipHours is not None: self.skipHours.publish(handler) if self.skipDays is not None: self.skipDays.publish(handler) for item in self.items: item.publish(handler) handler.endElement("channel") handler.endElement("rss") def publish_extensions(self, handler): # Derived classes can hook into this to insert # output after the three required fields. pass class RSSItem(WriteXmlMixin): """Publish an RSS Item""" element_attrs = {} def __init__(self, title = None, # string link = None, # url as string description = None, # string author = None, # email address as string categories = None, # list of string or Category comments = None, # url as string enclosure = None, # an Enclosure guid = None, # a unique string pubDate = None, # a datetime source = None, # a Source ): if title is None and description is None: raise TypeError( "must define at least one of 'title' or 'description'") self.title = title self.link = link self.description = description self.author = author if categories is None: categories = [] self.categories = categories self.comments = comments self.enclosure = enclosure self.guid = guid self.pubDate = pubDate self.source = source # It sure does get tedious typing these names three times... def publish(self, handler): handler.startElement("item", self.element_attrs) _opt_element(handler, "title", self.title) _opt_element(handler, "link", self.link) self.publish_extensions(handler) _opt_element(handler, "description", self.description) _opt_element(handler, "author", self.author) for category in self.categories: if isinstance(category, basestring): category = Category(category) category.publish(handler) _opt_element(handler, "comments", self.comments) if self.enclosure is not None: self.enclosure.publish(handler) _opt_element(handler, "guid", self.guid) pubDate = self.pubDate if isinstance(pubDate, datetime.datetime): pubDate = DateElement("pubDate", pubDate) else: pubDate = pubDate _opt_element(handler, "pubDate", pubDate) if self.source is not None: self.source.publish(handler) handler.endElement("item") def publish_extensions(self, handler): # Derived classes can hook into this to insert # output after the title and link elements pass
Python
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """A simple wrapper for Django templates. The main purpose of this module is to hide all of the package import pain you normally have to go through to get Django to work. We expose the Django Template and Context classes from this module, handling the import nonsense on behalf of clients. Typical usage: from google.appengine.ext.webapp import template print template.render('templates/index.html', {'foo': 'bar'}) Django uses a global setting for the directory in which it looks for templates. This is not natural in the context of the webapp module, so our load method takes in a complete template path, and we set these settings on the fly automatically. Because we have to set and use a global setting on every method call, this module is not thread safe, though that is not an issue for applications. Django template documentation is available at: http://www.djangoproject.com/documentation/templates/ """ import md5 import os try: from django import v0_96 except ImportError: pass import django import django.conf try: django.conf.settings.configure( DEBUG=False, TEMPLATE_DEBUG=False, TEMPLATE_LOADERS=( 'django.template.loaders.filesystem.load_template_source', ), ) except (EnvironmentError, RuntimeError): pass import django.template import django.template.loader from google.appengine.ext import webapp def render(template_path, template_dict, debug=False): """Renders the template at the given path with the given dict of values. Example usage: render("templates/index.html", {"name": "Bret", "values": [1, 2, 3]}) Args: template_path: path to a Django template template_dict: dictionary of values to apply to the template """ t = load(template_path, debug) return t.render(Context(template_dict)) template_cache = {} def load(path, debug=False): """Loads the Django template from the given path. It is better to use this function than to construct a Template using the class below because Django requires you to load the template with a method if you want imports and extends to work in the template. """ abspath = os.path.abspath(path) if not debug: template = template_cache.get(abspath, None) else: template = None if not template: directory, file_name = os.path.split(abspath) new_settings = { 'TEMPLATE_DIRS': (directory,), 'TEMPLATE_DEBUG': debug, 'DEBUG': debug, } old_settings = _swap_settings(new_settings) try: template = django.template.loader.get_template(file_name) finally: _swap_settings(old_settings) if not debug: template_cache[abspath] = template def wrap_render(context, orig_render=template.render): URLNode = django.template.defaulttags.URLNode save_urlnode_render = URLNode.render old_settings = _swap_settings(new_settings) try: URLNode.render = _urlnode_render_replacement return orig_render(context) finally: _swap_settings(old_settings) URLNode.render = save_urlnode_render template.render = wrap_render return template def _swap_settings(new): """Swap in selected Django settings, returning old settings. Example: save = _swap_settings({'X': 1, 'Y': 2}) try: ...new settings for X and Y are in effect here... finally: _swap_settings(save) Args: new: A dict containing settings to change; the keys should be setting names and the values settings values. Returns: Another dict structured the same was as the argument containing the original settings. Original settings that were not set at all are returned as None, and will be restored as None by the 'finally' clause in the example above. This shouldn't matter; we can't delete settings that are given as None, since None is also a legitimate value for some settings. Creating a separate flag value for 'unset' settings seems overkill as there is no known use case. """ settings = django.conf.settings old = {} for key, value in new.iteritems(): old[key] = getattr(settings, key, None) setattr(settings, key, value) return old def create_template_register(): """Used to extend the Django template library with custom filters and tags. To extend the template library with a custom filter module, create a Python module, and create a module-level variable named "register", and register all custom filters to it as described at http://www.djangoproject.com/documentation/templates_python/ #extending-the-template-system: templatefilters.py ================== register = webapp.template.create_template_register() def cut(value, arg): return value.replace(arg, '') register.filter(cut) Then, register the custom template module with the register_template_library function below in your application module: myapp.py ======== webapp.template.register_template_library('templatefilters') """ return django.template.Library() def register_template_library(package_name): """Registers a template extension module to make it usable in templates. See the documentation for create_template_register for more information.""" if not django.template.libraries.get(package_name, None): django.template.add_to_builtins(package_name) Template = django.template.Template Context = django.template.Context def _urlnode_render_replacement(self, context): """Replacement for django's {% url %} block. This version uses WSGIApplication's url mapping to create urls. Examples: <a href="{% url MyPageHandler "overview" %}"> {% url MyPageHandler implicit_args=False %} {% url MyPageHandler "calendar" %} {% url MyPageHandler "jsmith","calendar" %} """ args = [arg.resolve(context) for arg in self.args] try: app = webapp.WSGIApplication.active_instance handler = app.get_registered_handler_by_name(self.view_name) return handler.get_url(implicit_args=True, *args) except webapp.NoUrlFoundError: return ''
Python
# -*- coding: utf-8 -*- from google.appengine.ext import webapp from google.appengine.ext.webapp import template import logging,os from functools import wraps import gmemsess class BaseRequestHandler(webapp.RequestHandler): def render(self,template_file,template_values={}): """ Helper method to render the appropriate template """ path = os.path.join(os.path.dirname(__file__), template_file) self.response.out.write(template.render(path, template_values)) def param(self, name, **kw): return self.request.get(name, **kw) def checkLogin(method): ''' 检查用户是否登录 ''' @wraps(method) def wrapper(self, *args, **kwargs): if not getUsername(self): self.redirect('/') else: return method(self, *args, **kwargs) return wrapper #def requires_admin(method): # from google.appengine.api import users # @wraps(method) # def wrapper(self, *args, **kwargs): # if not self.is_login: # self.redirect(users.create_login_url(self.request.uri)) # return # elif not (self.is_admin # or self.author): # return self.error(403) # else: # return method(self, *args, **kwargs) # return wrapper def getUsername(self): sess = gmemsess.Session(self) return sess['username'] def getUserKey(self): sess = gmemsess.Session(self) return sess['user_key']
Python
# -*- coding: utf-8 -*- #!/usr/bin/env python import datetime def today_str(): return today().strftime("%Y-%m-%d") def today(): return datetime.datetime.utcnow() + datetime.timedelta(hours=+8) if __name__=="__main__": print today_str()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging,urllib,urllib2 from google.appengine.api import urlfetch ''' Created on 2010-7-15 @author: Fred ''' FETION_API = 'http://sms.jkgc.net/send.php' SEND_SUCCESS = 200 SEND_FAILTURE = 400 class TmpFetion(): ''' 封装一个简单的飞信功能 ''' mobile_no = '' passwd = '' def __init__(self,mobile_no,passwd): self.mobile_no = mobile_no self.passwd = passwd def send_msg(self,send_to,content): form_fields = { "phone": self.mobile_no, "fetion_password": self.passwd, "tophone": send_to, "message": content.encode('utf8') } form_data = urllib.urlencode(form_fields) # urlfetch.fetch(url=FETION_API,payload=form_data,method=urlfetch.POST) # request_data = urllib.urlencode([('phone', self.mobile_no),('fetion_password',self.passwd),('tophone',send_to),('message',content.encode('utf-8'))]) # logging.info('**%s**%s**%s**%s**'%(self.mobile_no,self.passwd,send_to,content)) request = urllib2.Request(FETION_API,data=form_data) i = 1 for i in range(3): try: logging.info('*************%d'%i) # print i res = urllib2.urlopen(request) return except: i = i+1 # return res # logging.info('***********'+res.read()) if __name__=="__main__": tmp = TmpFetion('15958127591','sd145914sd1!') tmp.send_msg('15958127591', u'哈哈哈哈哈')
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- #MIT License #By : cocobear.cn@gmail.com #Ver:0.2 import urllib import urllib2 import sys,re import binascii import hashlib import socket import os import time import exceptions import logging from hashlib import md5 from hashlib import sha1 from uuid import uuid1 from threading import RLock from threading import Thread #from select import select from Queue import Queue import select FetionOnline = "400" FetionBusy = "600" FetionAway = "100" FetionHidden = "0" FetionOffline = "365" FetionVer = "2008" #"SIPP" USED IN HTTP CONNECTION FetionSIPP= "SIPP" FetionNavURL = "nav.fetion.com.cn" FetionConfigURL = "http://nav.fetion.com.cn/nav/getsystemconfig.aspx" FetionConfigXML = """<config><user mobile-no="%s" /><client type="PC" version="3.5.2540" platform="W6.1" /><servers version="0" /><service-no version="0" /><parameters version="0" /><hints version="0" /><http-applications version="0" /><client-config version="0" /><services version="0" /></config>""" FetionLoginXML = """<args><device type="PC" version="1" client-version="3.5.2540" /><caps value="simple-im;im-session;temp-group;personal-group;im-relay;xeno-im;direct-sms;sms2fetion" /><events value="contact;permission;system-message;personal-group;compact" /><user-info attributes="all" /><presence><basic value="%s" desc="" /></presence></args>""" proxy_info = False d_print = '' #uncomment below line if you need proxy """ proxy_info = {'user' : '', 'pass' : '', 'host' : '218.249.83.87', 'port' : 8080 } """ class PyFetionException(Exception): """Base class for all exceptions """ def __init__(self, code, msg): self.args = (code,msg) class PyFetionSocketError(PyFetionException): """any socket error""" def __init__(self,e,msg=''): if msg: self.args = (e,msg) self.code = e self.msg = msg elif type(e) is int: self.args = (e,socket.errorTab[e]) self.code = e self.msg = socket.errorTab[e] else: args = e.args d_print(('args',),locals()) try: msg = socket.errorTab[e.errno] except: msg = '' self.args = (e.errno,msg) self.code = e.errno self.msg = msg class PyFetionAuthError(PyFetionException): """Authentication error. Your password error. """ class PyFetionSupportError(PyFetionException): """Support error. Your phone number don't support fetion. """ class PyFetionRegisterError(PyFetionException): """RegisterError. """ class SIPC(): global FetionVer global FetionSIPP global FetionLoginXML _header = '' #body = '' _content = '' code = '' ver = "SIP-C/2.0" Q = 1 I = 1 queue = Queue() def __init__(self,args=[]): self.__seq = 1 if args: [self.sid, self._domain,self.login_type, self._http_tunnel,\ self._ssic, self._sipc_proxy, self.presence, self._lock] = args if self.login_type == "HTTP": guid = str(uuid1()) self.__exheaders = { 'Cookie':'ssic=%s' % self._ssic, 'Content-Type':'application/oct-stream', 'Pragma':'xz4BBcV%s' % guid, } else: self.__tcp_init() def init_ack(self,type): self._content = "%s 200 OK\r\n" % self.ver self._header = [('F',self.sid), ('I',self.I), ('Q','%s %s' % (self.Q,type)), ] def init(self,type): self._content = '%s %s %s\r\n' % (type,self._domain,self.ver) self._header = [('F',self.sid), ('I',self.I), ('Q','%s %s' % (self.Q,type)), ] def recv(self,timeout=False): if self.login_type == "HTTP": time.sleep(10) return self.get_offline_msg() pass else: if timeout: infd,outfd,errfd = select([self.__sock,],[],[],timeout) else: infd,outfd,errfd = select([self.__sock,],[],[]) if len(infd) != 0: ret = self.__tcp_recv() num = len(ret) d_print(('num',),locals()) if num == 0: return ret if num == 1: return ret[0] for r in ret: self.queue.put(r) d_print(('r',),locals()) if not self.queue.empty(): return self.queue.get() else: return "TimeOut" def get_code(self,response): cmd = '' try: self.code =int(re.search("%s (\d{3})" % self.ver,response).group(1)) self.msg =re.search("%s \d{3} (.*)\r" % self.ver,response).group(1) except AttributeError,e: try: cmd = re.search("(.+?) %s" % self.ver,response).group(1) d_print(('cmd',),locals()) except AttributeError,e: pass return cmd return self.code def get(self,cmd,arg,*extra): body = '' if extra: body = extra[0] if cmd == "REG": body = FetionLoginXML % self.presence self.init('R') if arg == 1: pass if arg == 2: nonce = re.search('nonce="(.*)"',extra[0]).group(1) cnonce = self.__get_cnonce() if FetionVer == "2008": response=self.__get_response_sha1(nonce,cnonce) elif FetionVer == "2006": response=self.__get_response_md5(nonce,cnonce) salt = self.__get_salt() d_print(('nonce','cnonce','response','salt'),locals()) #If this step failed try to uncomment this lines #del self._header[2] #self._header.insert(2,('Q','2 R')) if FetionVer == "2008": self._header.insert(3,('A','Digest algorithm="SHA1-sess",response="%s",cnonce="%s",salt="%s",ssic="%s"' % (response,cnonce,salt,self._ssic))) elif FetionVer == "2006": self._header.insert(3,('A','Digest response="%s",cnonce="%s"' % (response,cnonce))) #If register successful 200 code get if arg == 3: return self.code if cmd == "CatMsg": self.init('M') self._header.append(('T',arg)) self._header.append(('C','text/plain')) self._header.append(('K','SaveHistory')) self._header.append(('N',cmd)) if cmd == "SendMsg": self.init('M') self._header.append(('C','text/plain')) self._header.append(('K','SaveHistory')) if cmd == "SendSMS": self.init('M') self._header.append(('T',arg)) self._header.append(('N',cmd)) if cmd == "SendCatSMS": self.init('M') self._header.append(('T',arg)) self._header.append(('N',cmd)) if cmd == "NUDGE": self.init('IN') self._header.append(('T',arg)) body = "<is-composing><state>nudge</state></is-composing>" if cmd == "ALIVE": self.init('R') if cmd == "DEAD": self.init('R') self._header.append(('X','0')) if cmd == "ACK": body = '' if arg == 'M': self.Q = extra[1] self.I = extra[2] self.init_ack(arg) del self._header[0] self._header.insert(0,('F',extra[0])) if cmd == "IN": body ="<is-composing><state>fetion-show:\xe5\x9b\xa70x000101010000010001000000000000010000000</state></is-composing>" self.init('IN') self._header.insert(3,('T',arg)) if cmd == "BYE": body = '' self.init('B') if cmd == "SetPresence": self.init('S') self._header.insert(3,('N',cmd)) body = '<args><presence><basic value="%s" /></presence></args>' % arg if cmd == "PGPresence": self.init('SUB') self._header.append(('N',cmd)) self._header.append(('X','0')) body = '<args><subscription><groups /></subscription></args>' if cmd == "PGSetPresence": self.init('S') self._header.insert(3,('N',cmd)) body = '<args><groups /></args>' if cmd == "compactlist": self.init('SUB') self._header.append(('N',cmd)) body = '<args><subscription><contacts><contact uri="%s" type="3" />'% arg for i in extra[0]: body += '<contact uri="%s" type="3" />' % i body += '</contacts></subscription></args>' if cmd == "StartChat": if arg == '': self.init('S') self._header.append(('N',cmd)) else: self.init('R') self._header.append(('A','TICKS auth="%s"' % arg)) self._header.append(('K','text/html-fragment')) self._header.append(('K','multiparty')) self._header.append(('K','nudge')) self._header.append(('K','share-background')) self._header.append(('K','fetion-show')) if cmd == "InviteBuddy": self.init('S') self._header.append(('N',cmd)) body = '<args><contacts><contact uri="%s" /></contacts></args>'%arg if cmd == "PGGetGroupList": self.init('S') self._header.insert(3,('N',cmd)) body = '<args><group-list version="1" attributes="name;identity" /></args>' if cmd == "SSSetScheduleSms": self.init('S') self._header.insert(3,('N',cmd)) body = '<args><schedule-sms send-time="%s"><message>%s</message><receivers><receiver uri="%s" /></receivers></schedule-sms></args>' % (extra[0],arg,extra[1]) if cmd == "GetOfflineMessages": self.init('S') self._header.insert(3,('N',cmd)) if cmd == "INFO": self.init('S') self._header.insert(3,('N',arg)) if arg == "GetPersonalInfo": body = '<args><personal attributes="all" /><services version="" attributes="all" /><config attributes="all" /><quota attributes="all" /></args>' elif arg == "GetContactList": body = '<args><contacts><buddy-lists /><buddies attributes="all" /><mobile-buddies attributes="all" /><chat-friends /><blacklist /><allow-list /></contacts></args>' elif arg == "GetContactsInfo": body = '<args><contacts attributes="all">' for i in extra[0]: body += '<contact uri="%s" />' % i body += '</contacts></args>' elif arg == "AddBuddy": tag = "sip" if len(extra[0]) == 11: tag = "tel" body = '<args><contacts><buddies><buddy uri="%s:%s" buddy-lists="" desc="%s" addbuddy-phrase-id="0" /></buddies></contacts></args>' % (tag,extra[0],extra[1]) elif arg == "AddMobileBuddy": body = '<args><contacts><mobile-buddies><mobile-buddy uri="tel:%s" buddy-lists="1" desc="%s" invite="0" /></mobile-buddies></contacts></args>' % (extra[0],extra[1]) elif arg == "DeleteBuddy": body = '<args><contacts><buddies><buddy uri="%s" /></buddies></contacts></args>' % extra[0] #general SIPC info if len(body) != 0: self._header.append(('L',len(body))) for k in self._header: self._content = self._content + k[0] + ": " + str(k[1]) + "\r\n" self._content+="\r\n" self._content+= body if self.login_type == "HTTP": #IN TCP CONNECTION "SIPP" SHOULD NOT BEEN SEND self._content+= FetionSIPP return self._content def ack(self): """ack message from server""" content = self._content d_print(('content',),locals()) self.__tcp_send(content) def send(self): content = self._content response = '' if self._lock: d_print("acquire lock ") self._lock.acquire() d_print("acquire lock ok ") d_print(('content',),locals()) if self.login_type == "HTTP": #First time t SHOULD SET AS 'i' #Otherwise 405 code get if self.__seq == 1: t = 'i' else: t = 's' url = self._http_tunnel+"?t=%s&i=%s" % (t,self.__seq) ret = http_send(url,content,self.__exheaders) if not ret: raise PyFetionSocketError(405,'http stoped') response = ret.read() self.__seq+=1 response = self.__sendSIPP() i = 0 while response == FetionSIPP and i < 5: response = self.__sendSIPP() i += 1 ret = self.__split(response) num = len(ret) d_print(('num',),locals()) for rs in ret: code = self.get_code(rs) d_print(('rs',),locals()) try: int(code) d_print(('code',),locals()) response = rs except exceptions.ValueError: self.queue.put(rs) continue else: self.__tcp_send(content) while response is '': try: ret = self.__tcp_recv() except socket.error,e: raise PyFetionSocketError(e) num = len(ret) d_print(('num',),locals()) for rs in ret: code = self.get_code(rs) d_print(('rs',),locals()) try: int(code) d_print(('code',),locals()) response = rs except exceptions.ValueError: self.queue.put(rs) continue if self._lock: self._lock.release() d_print("release lock") return response def __sendSIPP(self): body = FetionSIPP url = self._http_tunnel+"?t=s&i=%s" % self.__seq ret = http_send(url,body,self.__exheaders) if not ret: raise PyFetionSocketError(405,'Http error') response = ret.read() d_print(('response',),locals()) self.__seq+=1 return response def __tcp_init(self): try: self.__sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) except socket.error,e: s = None raise PyFetionSocketError(e) (host,port) = tuple(self._sipc_proxy.split(":")) port = int(port) try: self.__sock.connect((host,port)) except socket.error,e: self.__sock.close() raise PyFetionSocketError(e) def close(self): self.__sock.close() def __tcp_send(self,msg): try: self.__sock.send(msg) except socket.error,e: self.__sock.close() raise PyFetionSocketError(e) def __tcp_recv(self): """read bs bytes first,if there's still more data, read left data. get length from header : L: 1022 """ total_data = [] bs = 1024 try: data = self.__sock.recv(bs) total_data.append(data) while True and data: if not re.search("L: (\d+)",data) and not data[-4:] == '\r\n\r\n': data = self.__sock.recv(bs) total_data.append(data) elif not re.search("L: (\d+)",data) and data[-4:] == '\r\n\r\n': return total_data else: break while re.search("L: (\d+)",data): n = len(data) L = int(re.findall("L: (\d+)",data)[-1]) p = data.rfind('\r\n\r\n') abc = data data = '' p1 = data.rfind(str(L)) if p < p1: d_print("rn before L") left = L + n - (p1 + len(str(L))) + 4 else: left = L - (n - p -4) if left == L: d_print("It happened!") break d_print(('n','L','p','left',),locals()) #if more bytes then last L #come across another command: BN etc. #read until another L come if left < 0: d_print(('abc',),locals()) d = '' left = 0 while True: d = self.__sock.recv(bs) data += d if re.search("L: (\d+)",d): break d_print("read left bytes") d_print(('data',),locals()) total_data.append(data) #read left bytes in last L while left: data = self.__sock.recv(left) n = len(data) left = left - n if not data: break total_data.append(data) except socket.error,e: #self.__sock.close() raise PyFetionSocketError(e) return self.__split(''.join(total_data)) #return ''.join(total_data) def __split(self,data): c = [] d = [] #remove string "SIPP" if self.login_type == "HTTP": data = data[:-4] L = re.findall("L: (\d+)",data) L = [int(i) for i in L] d_print(('data',),locals()) b = data.split('\r\n\r\n') for i in range(len(b)): if b[i].startswith(self.ver) and "L:" not in b[i]: d.append(b[i]+'\r\n\r\n') del b[i] break c.append(b[0]) d_print(('L','b',),locals()) for i in range(0,len(L)): c.append(b[i+1][:L[i]]) c.append(b[i+1][L[i]:]) d_print(('c',),locals()) #remove last empty string if c[-1] == '': c.pop() c.reverse() while c: s = c.pop() s += '\r\n\r\n' if c: s += c.pop() d.append(s) d_print(('d',),locals()) return d def __get_salt(self): return self.__hash_passwd()[:8] def __get_cnonce(self): return md5(str(uuid1())).hexdigest().upper() def __get_response_md5(self,nonce,cnonce): #nonce = "3D8348924962579418512B8B3966294E" #cnonce= "9E169DCA9CBD85F1D1A89A893E00917E" key = md5("%s:%s:%s" % (self.sid,self._domain,self.passwd)).digest() h1 = md5("%s:%s:%s" % (key,nonce,cnonce)).hexdigest().upper() h2 = md5("REGISTER:%s" % self.sid).hexdigest().upper() response = md5("%s:%s:%s" % (h1,nonce,h2)).hexdigest().upper() #d_print(('nonce','cnonce','key','h1','h2','response'),locals()) return response def __get_response_sha1(self,nonce,cnonce): #nonce = "3D8348924962579418512B8B3966294E" #cnonce= "9E169DCA9CBD85F1D1A89A893E00917E" hash_passwd = self.__hash_passwd() hash_passwd_str = binascii.unhexlify(hash_passwd[8:]) key = sha1("%s:%s:%s" % (self.sid,self._domain,hash_passwd_str)).digest() h1 = md5("%s:%s:%s" % (key,nonce,cnonce)).hexdigest().upper() h2 = md5("REGISTER:%s" % self.sid).hexdigest().upper() response = md5("%s:%s:%s" % (h1,nonce,h2)).hexdigest().upper() return response def __hash_passwd(self): #salt = '%s%s%s%s' % (chr(0x77), chr(0x7A), chr(0x6D), chr(0x03)) salt = 'wzm\x03' src = salt+sha1(self.passwd).digest() return "777A6D03"+sha1(src).hexdigest().upper() def http_send(url,body='',exheaders='',login=False): global proxy_info conn = '' headers = { 'User-Agent':'IIC2.0/PC 3.2.0540', } headers.update(exheaders) if proxy_info: proxy_support = urllib2.ProxyHandler(\ {"http":"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info}) opener = urllib2.build_opener(proxy_support) else: opener = urllib2.build_opener() urllib2.install_opener(opener) request = urllib2.Request(url,headers=headers,data=body) #add retry for GAE. #PyFetion will get 405 code sometimes, we should re-send the request. retry = 5 while retry: try: conn = urllib2.urlopen(request) except urllib2.URLError, e: if hasattr(e,'code'): code = e.code msg = e.read() else: code = e.reason.errno msg = e.reason.strerror d_print(('code','msg'),locals()) if code == 401 or code == 400: if login: raise PyFetionAuthError(code,msg) if code == 404 or code == 500: raise PyFetionSupportError(code,msg) if code == 405: retry = retry - 1 continue raise PyFetionSocketError(code,msg) break return conn class on_cmd_I(Thread,SIPC): #if there is invitation SIP method [I] def __init__(self,fetion,response,args): self.fetion = fetion self.response = response self.args = args self.begin = time.time() self.Q = 4 self.I = 4 self.from_uri = '' Thread.__init__(self) def run(self): running = True try: self.from_uri = re.findall('F: (.*)',self.response)[0] credential = re.findall('credential="(.+?)"',self.response)[0] sipc_proxy = re.findall('address="(.+?);',self.response)[0] except: d_print("find tag error") return self.from_uri = self.from_uri.rstrip() self.fetion._ack('I',self.from_uri) self.args[5] = sipc_proxy #no lock self.args[7] = None #SIPC(self.args) SIPC.__init__(self,self.args) self.get("StartChat",credential) response = self.send() self.deal_msg(response) while running: if not self.queue.empty(): response = self.queue.get() else: response = self.recv() if len(response) == 0: d_print("User Left converstion") self.fetion.session.pop(self.from_uri) return self.deal_msg(response) #self._bye() def deal_msg(self,response): try: Q = re.findall('Q: (-?\d+) M',response) I = re.findall('I: (-?\d+)',response) except: d_print("NO Q") return False for i in range(len(Q)): self.Q = Q[i] self.fetion.queue.put(response) self._ack('M') self._ack('IN') return True def _ack(self,cmd): """ack message from uri""" self.get("ACK",cmd,self.from_uri,self.Q,self.I) self.response = self.ack() self.deal_msg(self.response) def _send_msg(self,msg): msg = msg.replace('<','&lt;') self.get("SendMsg",'',msg) self.send() def _bye(self): """say bye to this session""" self.get("BYE",'') self.send() class PyFetion(SIPC): __log = '' __sipc_url = '' _ssic = '' _lock = RLock() _sipc_proxy = '' _domain = '' _http_tunnel = '' mobile_no = '' passwd = '' queue = Queue() sid = '' login_type = '' receving = False presence = '' debug = False contactlist = {} session = {} def __init__(self,mobile_no,passwd,login_type="TCP",debug=False): self.mobile_no = mobile_no self.passwd = passwd self.login_type = login_type if debug == True: logging.basicConfig(level=logging.DEBUG,format='%(message)s') self.__log = logging elif debug == "FILE": logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(thread)d %(message)s', filename='./PyFetion.log', filemode='w') self.__log = logging global d_print #replace global function with self method d_print = self.__print self.__sipc_url = "https://uid.fetion.com.cn/ssiportal/SSIAppSignIn.aspx" self._sipc_proxy = "221.176.31.45:8080" self._http_tunnel= "http://221.176.31.45/ht/sd.aspx" #uncomment this line for getting configuration from server everytime #It's very slow sometimes, so default use fixed configuration #self.__set_system_config() def login(self,presence=FetionOnline): if not self.__get_uri(): return False self.presence = presence try: self.__register(self._ssic,self._domain) except PyFetionRegisterError,e: d_print("Register Failed!") return False #self.get_personal_info() if not self.get_contactlist(): d_print("get contactlist error") return False self.get("compactlist",self.__uri,self.contactlist.keys()) response = self.send() code = self.get_code(response) if code != 200: return False #self.get("PGGetGroupList",self.__uri) #response = self.send() self.get_offline_msg() self.receving = True return True def logout(self): self.get("DEAD",'') self.send() self.receving = False def start_chat(self,who): self.get("StartChat",'') response = self.send() try: credential = re.findall('credential="(.+?)"',response)[0] sipc_proxy = re.findall('address="(.+?);',response)[0] except: d_print("find tag error") return False args = [self.sid,self._domain,self.login_type,self._http_tunnel,self._ssic,sipc_proxy,self.presence,None] _SIPC = SIPC(args) _SIPC.get("StartChat",credential) response = _SIPC.send() _SIPC.get("InviteBuddy",who) response = _SIPC.send() code = _SIPC.get_code(response) if code != 200: return False response = _SIPC.recv() try: type = re.findall('<event type="(.+?)"',response)[0] except : return False if type == "UserEntered": return FetionHidden elif type == "UserFailed": return FetionOnline def set_presence(self,presence): """set status of fetion""" if self.presence == presence: return True self.get("SetPresence",presence) response = self.send() code = self.get_code(response) if code == 200: self.presence = presence d_print("set presence ok.") return True return False #self.get("PGSetPresence",presence) #response = self.send() def get_offline_msg(self): """get offline message from server""" self.get("GetOfflineMessages",'') response = self.send() return response def add(self,who): """add friend who should be mobile number or fetion number""" my_info = self.get_info() try: nick_name = re.findall('nickname="(.*?)" ',my_info)[0] except IndexError: nick_name = " " #code = self._add(who,nick_name,"AddMobileBuddy") code = self._add(who,nick_name) if code == 522: code = self._add(who,nick_name,"AddMobileBuddy") if code == 404 or code == 400 : d_print("Not Found") return False if code == 521: d_print("Aleady added.") return True if code == 200: return True return False def delete(self,who): if who.isdigit() and len(who) == 11: who = "tel:" + who else: who = self.get_uri(who) if not who: return False self.get("INFO","DeleteBuddy",who) response = self.send() code = self.get_code(response) if code == 404 or code == 400 : d_print("Not Found") return False if code == 200: return True return False def _add(self,who,nick_name,type="AddBuddy"): self.get("INFO",type,who,nick_name) response = self.send() code = self.get_code(response) return code def get_personal_info(self): """get detail information of me""" self.get("INFO","GetPersonalInfo") response = self.send() return response def get_info(self,who=None): """get contact info. who should be uri. string or list """ alluri = [] if who == None: return self.get_personal_info() if type(who) is not list: alluri.append(who) else: alluri = who self.get("INFO","GetContactsInfo",alluri) response = self.send() return response def set_info(self,info): contacts = re.findall('<contact (.+?)</contact>',info) contacts += re.findall('<presence (.+?)</presence>',info) for contact in contacts: #print contacts uri = '' nickname = '' mobile_no = '' try: (uri,mobile_no,nickname) = re.findall('uri="(.+?)".+?mobile-no="(.*?)".+?nickname="(.*?)"',contact)[0] except: try: (uri,nickname) = re.findall('uri="(.+?)".+?nickname="(.*?)"',contact)[0] except: continue #print uri,nickname,mobile_no if uri == self.__uri: continue if self.contactlist[uri][0] == '': self.contactlist[uri][0] = nickname if self.contactlist[uri][1] == '': self.contactlist[uri][1] = mobile_no def get_contactlist(self): """get contact list contactlist is a dict: {uri:[name,mobile-no,status,type]} """ buddy_list = '' allow_list = '' chat_friends = '' need_info = [] self.get("INFO","GetContactList") response = self.send() code = self.get_code(response) if code != 200: return False d = re.findall('<buddy-lists>(.*?)<allow-list>',response)[0] try: buddy_list = re.findall('uri="(.+?)" user-id="\d+" local-name="(.*?)"',d) except: return False try: d = re.findall('<chat-friends>(.*?)</chat-friends>',d)[0] chat_friends = re.findall('uri="(.+?)" user-id="\d+"',d) except: pass for uri in chat_friends: if uri not in self.contactlist: l = ['']*4 need_info.append(uri) self.contactlist[uri] = l self.contactlist[uri][0] = '' self.contactlist[uri][2] = FetionHidden self.contactlist[uri][3] = 'A' #buddy_list [(uri,local_name),...] for p in buddy_list: l = ['']*4 #set uri self.contactlist[p[0]] = l #set local-name self.contactlist[p[0]][0] = p[1] #set default status self.contactlist[p[0]][2] = FetionHidden #self.contactlist[p[0]][2] = FetionOffline if p[0].startswith("tel"): self.contactlist[p[0]][3] = 'T' self.contactlist[p[0]][2] = FetionHidden #set mobile_no self.contactlist[p[0]][1] = p[0][4:] #if no local-name use mobile-no as name if p[1] == '': self.contactlist[p[0]][0] = self.contactlist[p[0]][1] else: self.contactlist[p[0]][3] = 'B' if self.contactlist[p[0]][0] == '': need_info.append(p[0]) """ try: s = re.findall('<allow-list>(.+?)</allow-list>',response)[0] allow_list = re.findall('uri="(.+?)"',s) except: pass #allow_list [uri,...] for uri in allow_list: if uri not in self.contactlist: l = ['']*4 need_info.append(uri) self.contactlist[uri] = l self.contactlist[uri][0] = '' self.contactlist[uri][2] = FetionHidden self.contactlist[uri][3] = 'A' """ ret = self.get_info(need_info) self.set_info(ret) return True def get_uri(self,who): """get uri from fetion number""" if who in self.__uri: return self.__uri if who.startswith("sip"): return who for uri in self.contactlist: if who in uri: return uri return None def send_msg(self,msg,to=None,flag="CatMsg"): """more info at send_sms function. if someone's fetion is offline, msg will send to phone, the same as send_sms. """ if not to: to = self.__uri #Fetion now can use mobile number(09.02.23) #like tel: 13888888888 #but not in sending to PC elif flag != "CatMsg" and to.startswith("tel:"): pass elif flag == "CatMsg" and to.startswith("tel:"): return False elif flag != "CatMsg" and len(to) == 11 and to.isdigit(): to = "tel:"+to else: to = self.get_uri(to) if not to: return False msg = msg.replace('<','&lt;') self.get(flag,to,msg) try: response = self.send() except PyFetionSocketError,e: d_print(('e',),locals()) return False code = self.get_code(response) if code == 280: d_print("Send sms OK!") elif code == 200: d_print("Send msg OK!") else: d_print(('code',),locals()) return False return True def send_sms(self,msg,to=None,long=True): """send sms to someone, if to is None, send self. if long is True, send long sms.(Your phone should support.) to can be mobile number or fetion number """ if long: return self.send_msg(msg,to,"SendCatSMS") else: return self.send_msg(msg,to,"SendSMS") def send_schedule_sms(self,msg,time,to=None): if not to: to = self.__uri elif len(to) == 11 and to.isdigit(): to = "tel:"+to else: to = self.get_uri(to) if not to: return False msg = msg.replace('<','&lt;') self.get("SSSetScheduleSms",msg,time,to) response = self.send() code = self.get_code(response) if code == 486: d_print("Busy Here") return None if code == 200: id = re.search('id="(\d+)"',response).group(1) d_print(('id',),locals(),"schedule_sms id") return id def alive(self): """send keepalive message""" self.get("ALIVE",'') response = self.send() code = self.get_code(response) if code == 200: d_print("keepalive message send ok.") return True return False def receive(self): """response from server""" threads = [] while self.receving: if not self.queue.empty(): response = self.queue.get() else: try: response = self.recv(5) except PyFetionSocketError,e: yield ["NetworkError",e.msg] continue if response =="TimeOut": continue elif len(response) == 0: d_print("logout") return elif response.startswith("BN"): try: type = re.findall('<event type="(.+?)"',response)[0] except IndexError: d_print("Didn't find type") d_print(('response',),locals()) if type == "ServiceResult": self.set_info(response) if type == "deregistered" or type=="disconnect": self.receving = False yield [type] if type == "PresenceChanged": self.set_info(response) ret = re.findall('<presence uri="(.+?)">.+?value="(.+?)".+?type="sms">(\d+)\.',response) if not ret: ret = re.findall('<presence uri="(.+?)">.+?value="(.+?)"',response) #remove self uri event = [i for i in ret if i[0] != self.__uri] event = list(set(event)) for e in event: if len(e) == 3 and e[2] == FetionOffline: self.contactlist[e[0]][2] = e[2] else: self.contactlist[e[0]][2] = e[1] yield [type,event] if type == "UpdateBuddy" or type == "UpdateMobileBuddy": uri = re.findall('uri="(.+?)"',response)[0] l = ['']*4 self.contactlist[uri] = l if type == "UpdateBuddy": ret = self.get_info(uri) self.set_info(ret) else: self.contactlist[uri][3] = 'T' self.contactlist[uri][2] = FetionHidden self.contactlist[uri][1] = uri[4:] self.contactlist[uri][0] = uri[4:] elif response.startswith("M"): try: from_uri = re.findall('F: (.*)',response)[0].strip() msg = re.findall('\r\n\r\n(.*)',response,re.S)[0] except: d_print("Message without content") continue #if from PC remove <Font> try: msg = re.findall('<Font .+?>(.+?)</Font>',msg,re.S)[0] except: pass #from phone or PC try: XI = re.findall('XI: (.*)',response)[0] type = "PC" except: type = "PHONE" #ack this message try: Q = re.findall('Q: (-?\d+) M',response)[0] I = re.findall('I: (-?\d+)',response)[0] self._ack('M',from_uri,Q,I) except: pass yield ["Message",from_uri,msg,type] elif response.startswith("I"): try: from_uri = re.findall('F: (.*)',response)[0].rstrip() except: pass args = [self.sid,self._domain,self.login_type,self._http_tunnel,self._ssic,self._sipc_proxy,self.presence,None] t = on_cmd_I(self,response,args) t.setDaemon(True) t.start() self.session[from_uri] = t #print self.session def _ack(self,cmd,from_uri,Q=0,I=0): """ack message """ self.get("ACK",cmd,from_uri,Q,I) self.ack() def __register(self,ssic,domain): SIPC.__init__(self) response = '' for step in range(1,3): self.get("REG",step,response) response = self.send() code = self.get_code(response) if code == 200: d_print("register successful.") else: raise PyFetionRegisterError(code,response) def __get_system_config(self): global FetionConfigURL global FetionConfigXML url = FetionConfigURL body = FetionConfigXML % self.mobile_no d_print(('url','body'),locals()) config_data = http_send(url,body).read() sipc_url = re.search("<ssi-app-sign-in>(.*)</ssi-app-sign-in>",config_data).group(1) sipc_proxy = re.search("<sipc-proxy>(.*)</sipc-proxy>",config_data).group(1) http_tunnel = re.search("<http-tunnel>(.*)</http-tunnel>",config_data).group(1) d_print(('sipc_url','sipc_proxy','http_tunnel'),locals()) self.__sipc_url = sipc_url self._sipc_proxy = sipc_proxy self._http_tunnel= http_tunnel def __get_uri(self): url = self.__sipc_url+"?mobileno="+self.mobile_no+"&pwd="+urllib.quote(self.passwd) d_print(('url',),locals()) ret = http_send(url,login=True) header = str(ret.info()) body = ret.read() try: ssic = re.search("ssic=(.*);",header).group(1) sid = re.search("sip:(.*)@",body).group(1) uri = re.search('uri="(.*)" mobile-no',body).group(1) status = re.search('user-status="(\d+)"',body).group(1) except: return False domain = "fetion.com.cn" d_print(('ssic','sid','uri','status','domain'),locals(),"Get SID OK") self.sid = sid self.__uri = uri self._ssic = ssic self._domain = domain return True def __print(self,vars=(),namespace=[],msg=''): """if only sigle variable ,arg should like this ('var',)""" if not self.__log: return if vars and not namespace and not msg: msg = vars if vars and namespace: for var in vars: if var in namespace: self.__log.debug("%s={%s}" % (var,str(namespace[var]))) if msg: self.__log.debug("%s" % msg) if __name__ == "__main__": fetion = PyFetion('15958127591','sd145914sd1!','HTTP') fetion.login(FetionOnline) fetion.send_sms('ssssssss') fetion.logout()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- #MIT License #By : cocobear.cn@gmail.com #Ver:0.2 import urllib import urllib2 import sys,re import binascii import hashlib import socket import os import time import exceptions import logging from hashlib import md5 from hashlib import sha1 from uuid import uuid1 from threading import RLock from threading import Thread #from select import select from Queue import Queue import select FetionOnline = "400" FetionBusy = "600" FetionAway = "100" FetionHidden = "0" FetionOffline = "365" FetionVer = "2008" #"SIPP" USED IN HTTP CONNECTION FetionSIPP= "SIPP" FetionNavURL = "nav.fetion.com.cn" FetionConfigURL = "http://nav.fetion.com.cn/nav/getsystemconfig.aspx" FetionConfigXML = """<config><user mobile-no="%s" /><client type="PC" version="3.5.2540" platform="W6.1" /><servers version="0" /><service-no version="0" /><parameters version="0" /><hints version="0" /><http-applications version="0" /><client-config version="0" /><services version="0" /></config>""" FetionLoginXML = """<args><device type="PC" version="1" client-version="3.5.2540" /><caps value="simple-im;im-session;temp-group;personal-group;im-relay;xeno-im;direct-sms;sms2fetion" /><events value="contact;permission;system-message;personal-group;compact" /><user-info attributes="all" /><presence><basic value="%s" desc="" /></presence></args>""" proxy_info = False d_print = '' #uncomment below line if you need proxy """ proxy_info = {'user' : '', 'pass' : '', 'host' : '218.249.83.87', 'port' : 8080 } """ class PyFetionException(Exception): """Base class for all exceptions """ def __init__(self, code, msg): self.args = (code,msg) class PyFetionSocketError(PyFetionException): """any socket error""" def __init__(self,e,msg=''): if msg: self.args = (e,msg) self.code = e self.msg = msg elif type(e) is int: self.args = (e,socket.errorTab[e]) self.code = e self.msg = socket.errorTab[e] else: args = e.args d_print(('args',),locals()) try: msg = socket.errorTab[e.errno] except: msg = '' self.args = (e.errno,msg) self.code = e.errno self.msg = msg class PyFetionAuthError(PyFetionException): """Authentication error. Your password error. """ class PyFetionSupportError(PyFetionException): """Support error. Your phone number don't support fetion. """ class PyFetionRegisterError(PyFetionException): """RegisterError. """ class SIPC(): global FetionVer global FetionSIPP global FetionLoginXML _header = '' #body = '' _content = '' code = '' ver = "SIP-C/2.0" Q = 1 I = 1 queue = Queue() def __init__(self,args=[]): self.__seq = 1 if args: [self.sid, self._domain,self.login_type, self._http_tunnel,\ self._ssic, self._sipc_proxy, self.presence, self._lock] = args if self.login_type == "HTTP": guid = str(uuid1()) self.__exheaders = { 'Cookie':'ssic=%s' % self._ssic, 'Content-Type':'application/oct-stream', 'Pragma':'xz4BBcV%s' % guid, } else: self.__tcp_init() def init_ack(self,type): self._content = "%s 200 OK\r\n" % self.ver self._header = [('F',self.sid), ('I',self.I), ('Q','%s %s' % (self.Q,type)), ] def init(self,type): self._content = '%s %s %s\r\n' % (type,self._domain,self.ver) self._header = [('F',self.sid), ('I',self.I), ('Q','%s %s' % (self.Q,type)), ] def recv(self,timeout=False): if self.login_type == "HTTP": time.sleep(10) return self.get_offline_msg() pass else: if timeout: infd,outfd,errfd = select([self.__sock,],[],[],timeout) else: infd,outfd,errfd = select([self.__sock,],[],[]) if len(infd) != 0: ret = self.__tcp_recv() num = len(ret) d_print(('num',),locals()) if num == 0: return ret if num == 1: return ret[0] for r in ret: self.queue.put(r) d_print(('r',),locals()) if not self.queue.empty(): return self.queue.get() else: return "TimeOut" def get_code(self,response): cmd = '' try: self.code =int(re.search("%s (\d{3})" % self.ver,response).group(1)) self.msg =re.search("%s \d{3} (.*)\r" % self.ver,response).group(1) except AttributeError,e: try: cmd = re.search("(.+?) %s" % self.ver,response).group(1) d_print(('cmd',),locals()) except AttributeError,e: pass return cmd return self.code def get(self,cmd,arg,*extra): body = '' if extra: body = extra[0] if cmd == "REG": body = FetionLoginXML % self.presence self.init('R') if arg == 1: pass if arg == 2: nonce = re.search('nonce="(.*)"',extra[0]).group(1) cnonce = self.__get_cnonce() if FetionVer == "2008": response=self.__get_response_sha1(nonce,cnonce) elif FetionVer == "2006": response=self.__get_response_md5(nonce,cnonce) salt = self.__get_salt() d_print(('nonce','cnonce','response','salt'),locals()) #If this step failed try to uncomment this lines #del self._header[2] #self._header.insert(2,('Q','2 R')) if FetionVer == "2008": self._header.insert(3,('A','Digest algorithm="SHA1-sess",response="%s",cnonce="%s",salt="%s",ssic="%s"' % (response,cnonce,salt,self._ssic))) elif FetionVer == "2006": self._header.insert(3,('A','Digest response="%s",cnonce="%s"' % (response,cnonce))) #If register successful 200 code get if arg == 3: return self.code if cmd == "CatMsg": self.init('M') self._header.append(('T',arg)) self._header.append(('C','text/plain')) self._header.append(('K','SaveHistory')) self._header.append(('N',cmd)) if cmd == "SendMsg": self.init('M') self._header.append(('C','text/plain')) self._header.append(('K','SaveHistory')) if cmd == "SendSMS": self.init('M') self._header.append(('T',arg)) self._header.append(('N',cmd)) if cmd == "SendCatSMS": self.init('M') self._header.append(('T',arg)) self._header.append(('N',cmd)) if cmd == "NUDGE": self.init('IN') self._header.append(('T',arg)) body = "<is-composing><state>nudge</state></is-composing>" if cmd == "ALIVE": self.init('R') if cmd == "DEAD": self.init('R') self._header.append(('X','0')) if cmd == "ACK": body = '' if arg == 'M': self.Q = extra[1] self.I = extra[2] self.init_ack(arg) del self._header[0] self._header.insert(0,('F',extra[0])) if cmd == "IN": body ="<is-composing><state>fetion-show:\xe5\x9b\xa70x000101010000010001000000000000010000000</state></is-composing>" self.init('IN') self._header.insert(3,('T',arg)) if cmd == "BYE": body = '' self.init('B') if cmd == "SetPresence": self.init('S') self._header.insert(3,('N',cmd)) body = '<args><presence><basic value="%s" /></presence></args>' % arg if cmd == "PGPresence": self.init('SUB') self._header.append(('N',cmd)) self._header.append(('X','0')) body = '<args><subscription><groups /></subscription></args>' if cmd == "PGSetPresence": self.init('S') self._header.insert(3,('N',cmd)) body = '<args><groups /></args>' if cmd == "compactlist": self.init('SUB') self._header.append(('N',cmd)) body = '<args><subscription><contacts><contact uri="%s" type="3" />'% arg for i in extra[0]: body += '<contact uri="%s" type="3" />' % i body += '</contacts></subscription></args>' if cmd == "StartChat": if arg == '': self.init('S') self._header.append(('N',cmd)) else: self.init('R') self._header.append(('A','TICKS auth="%s"' % arg)) self._header.append(('K','text/html-fragment')) self._header.append(('K','multiparty')) self._header.append(('K','nudge')) self._header.append(('K','share-background')) self._header.append(('K','fetion-show')) if cmd == "InviteBuddy": self.init('S') self._header.append(('N',cmd)) body = '<args><contacts><contact uri="%s" /></contacts></args>'%arg if cmd == "PGGetGroupList": self.init('S') self._header.insert(3,('N',cmd)) body = '<args><group-list version="1" attributes="name;identity" /></args>' if cmd == "SSSetScheduleSms": self.init('S') self._header.insert(3,('N',cmd)) body = '<args><schedule-sms send-time="%s"><message>%s</message><receivers><receiver uri="%s" /></receivers></schedule-sms></args>' % (extra[0],arg,extra[1]) if cmd == "GetOfflineMessages": self.init('S') self._header.insert(3,('N',cmd)) if cmd == "INFO": self.init('S') self._header.insert(3,('N',arg)) if arg == "GetPersonalInfo": body = '<args><personal attributes="all" /><services version="" attributes="all" /><config attributes="all" /><quota attributes="all" /></args>' elif arg == "GetContactList": body = '<args><contacts><buddy-lists /><buddies attributes="all" /><mobile-buddies attributes="all" /><chat-friends /><blacklist /><allow-list /></contacts></args>' elif arg == "GetContactsInfo": body = '<args><contacts attributes="all">' for i in extra[0]: body += '<contact uri="%s" />' % i body += '</contacts></args>' elif arg == "AddBuddy": tag = "sip" if len(extra[0]) == 11: tag = "tel" body = '<args><contacts><buddies><buddy uri="%s:%s" buddy-lists="" desc="%s" addbuddy-phrase-id="0" /></buddies></contacts></args>' % (tag,extra[0],extra[1]) elif arg == "AddMobileBuddy": body = '<args><contacts><mobile-buddies><mobile-buddy uri="tel:%s" buddy-lists="1" desc="%s" invite="0" /></mobile-buddies></contacts></args>' % (extra[0],extra[1]) elif arg == "DeleteBuddy": body = '<args><contacts><buddies><buddy uri="%s" /></buddies></contacts></args>' % extra[0] #general SIPC info if len(body) != 0: self._header.append(('L',len(body))) for k in self._header: self._content = self._content + k[0] + ": " + str(k[1]) + "\r\n" self._content+="\r\n" self._content+= body if self.login_type == "HTTP": #IN TCP CONNECTION "SIPP" SHOULD NOT BEEN SEND self._content+= FetionSIPP return self._content def ack(self): """ack message from server""" content = self._content d_print(('content',),locals()) self.__tcp_send(content) def send(self): content = self._content response = '' if self._lock: d_print("acquire lock ") self._lock.acquire() d_print("acquire lock ok ") d_print(('content',),locals()) if self.login_type == "HTTP": #First time t SHOULD SET AS 'i' #Otherwise 405 code get if self.__seq == 1: t = 'i' else: t = 's' url = self._http_tunnel+"?t=%s&i=%s" % (t,self.__seq) ret = http_send(url,content,self.__exheaders) if not ret: raise PyFetionSocketError(405,'http stoped') response = ret.read() self.__seq+=1 response = self.__sendSIPP() i = 0 while response == FetionSIPP and i < 5: response = self.__sendSIPP() i += 1 ret = self.__split(response) num = len(ret) d_print(('num',),locals()) for rs in ret: code = self.get_code(rs) d_print(('rs',),locals()) try: int(code) d_print(('code',),locals()) response = rs except exceptions.ValueError: self.queue.put(rs) continue else: self.__tcp_send(content) while response is '': try: ret = self.__tcp_recv() except socket.error,e: raise PyFetionSocketError(e) num = len(ret) d_print(('num',),locals()) for rs in ret: code = self.get_code(rs) d_print(('rs',),locals()) try: int(code) d_print(('code',),locals()) response = rs except exceptions.ValueError: self.queue.put(rs) continue if self._lock: self._lock.release() d_print("release lock") return response def __sendSIPP(self): body = FetionSIPP url = self._http_tunnel+"?t=s&i=%s" % self.__seq ret = http_send(url,body,self.__exheaders) if not ret: raise PyFetionSocketError(405,'Http error') response = ret.read() d_print(('response',),locals()) self.__seq+=1 return response def __tcp_init(self): try: self.__sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) except socket.error,e: s = None raise PyFetionSocketError(e) (host,port) = tuple(self._sipc_proxy.split(":")) port = int(port) try: self.__sock.connect((host,port)) except socket.error,e: self.__sock.close() raise PyFetionSocketError(e) def close(self): self.__sock.close() def __tcp_send(self,msg): try: self.__sock.send(msg) except socket.error,e: self.__sock.close() raise PyFetionSocketError(e) def __tcp_recv(self): """read bs bytes first,if there's still more data, read left data. get length from header : L: 1022 """ total_data = [] bs = 1024 try: data = self.__sock.recv(bs) total_data.append(data) while True and data: if not re.search("L: (\d+)",data) and not data[-4:] == '\r\n\r\n': data = self.__sock.recv(bs) total_data.append(data) elif not re.search("L: (\d+)",data) and data[-4:] == '\r\n\r\n': return total_data else: break while re.search("L: (\d+)",data): n = len(data) L = int(re.findall("L: (\d+)",data)[-1]) p = data.rfind('\r\n\r\n') abc = data data = '' p1 = data.rfind(str(L)) if p < p1: d_print("rn before L") left = L + n - (p1 + len(str(L))) + 4 else: left = L - (n - p -4) if left == L: d_print("It happened!") break d_print(('n','L','p','left',),locals()) #if more bytes then last L #come across another command: BN etc. #read until another L come if left < 0: d_print(('abc',),locals()) d = '' left = 0 while True: d = self.__sock.recv(bs) data += d if re.search("L: (\d+)",d): break d_print("read left bytes") d_print(('data',),locals()) total_data.append(data) #read left bytes in last L while left: data = self.__sock.recv(left) n = len(data) left = left - n if not data: break total_data.append(data) except socket.error,e: #self.__sock.close() raise PyFetionSocketError(e) return self.__split(''.join(total_data)) #return ''.join(total_data) def __split(self,data): c = [] d = [] #remove string "SIPP" if self.login_type == "HTTP": data = data[:-4] L = re.findall("L: (\d+)",data) L = [int(i) for i in L] d_print(('data',),locals()) b = data.split('\r\n\r\n') for i in range(len(b)): if b[i].startswith(self.ver) and "L:" not in b[i]: d.append(b[i]+'\r\n\r\n') del b[i] break c.append(b[0]) d_print(('L','b',),locals()) for i in range(0,len(L)): c.append(b[i+1][:L[i]]) c.append(b[i+1][L[i]:]) d_print(('c',),locals()) #remove last empty string if c[-1] == '': c.pop() c.reverse() while c: s = c.pop() s += '\r\n\r\n' if c: s += c.pop() d.append(s) d_print(('d',),locals()) return d def __get_salt(self): return self.__hash_passwd()[:8] def __get_cnonce(self): return md5(str(uuid1())).hexdigest().upper() def __get_response_md5(self,nonce,cnonce): #nonce = "3D8348924962579418512B8B3966294E" #cnonce= "9E169DCA9CBD85F1D1A89A893E00917E" key = md5("%s:%s:%s" % (self.sid,self._domain,self.passwd)).digest() h1 = md5("%s:%s:%s" % (key,nonce,cnonce)).hexdigest().upper() h2 = md5("REGISTER:%s" % self.sid).hexdigest().upper() response = md5("%s:%s:%s" % (h1,nonce,h2)).hexdigest().upper() #d_print(('nonce','cnonce','key','h1','h2','response'),locals()) return response def __get_response_sha1(self,nonce,cnonce): #nonce = "3D8348924962579418512B8B3966294E" #cnonce= "9E169DCA9CBD85F1D1A89A893E00917E" hash_passwd = self.__hash_passwd() hash_passwd_str = binascii.unhexlify(hash_passwd[8:]) key = sha1("%s:%s:%s" % (self.sid,self._domain,hash_passwd_str)).digest() h1 = md5("%s:%s:%s" % (key,nonce,cnonce)).hexdigest().upper() h2 = md5("REGISTER:%s" % self.sid).hexdigest().upper() response = md5("%s:%s:%s" % (h1,nonce,h2)).hexdigest().upper() return response def __hash_passwd(self): #salt = '%s%s%s%s' % (chr(0x77), chr(0x7A), chr(0x6D), chr(0x03)) salt = 'wzm\x03' src = salt+sha1(self.passwd).digest() return "777A6D03"+sha1(src).hexdigest().upper() def http_send(url,body='',exheaders='',login=False): global proxy_info conn = '' headers = { 'User-Agent':'IIC2.0/PC 3.2.0540', } headers.update(exheaders) if proxy_info: proxy_support = urllib2.ProxyHandler(\ {"http":"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info}) opener = urllib2.build_opener(proxy_support) else: opener = urllib2.build_opener() urllib2.install_opener(opener) request = urllib2.Request(url,headers=headers,data=body) #add retry for GAE. #PyFetion will get 405 code sometimes, we should re-send the request. retry = 5 while retry: try: conn = urllib2.urlopen(request) except urllib2.URLError, e: if hasattr(e,'code'): code = e.code msg = e.read() else: code = e.reason.errno msg = e.reason.strerror d_print(('code','msg'),locals()) if code == 401 or code == 400: if login: raise PyFetionAuthError(code,msg) if code == 404 or code == 500: raise PyFetionSupportError(code,msg) if code == 405: retry = retry - 1 continue raise PyFetionSocketError(code,msg) break return conn class on_cmd_I(Thread,SIPC): #if there is invitation SIP method [I] def __init__(self,fetion,response,args): self.fetion = fetion self.response = response self.args = args self.begin = time.time() self.Q = 4 self.I = 4 self.from_uri = '' Thread.__init__(self) def run(self): running = True try: self.from_uri = re.findall('F: (.*)',self.response)[0] credential = re.findall('credential="(.+?)"',self.response)[0] sipc_proxy = re.findall('address="(.+?);',self.response)[0] except: d_print("find tag error") return self.from_uri = self.from_uri.rstrip() self.fetion._ack('I',self.from_uri) self.args[5] = sipc_proxy #no lock self.args[7] = None #SIPC(self.args) SIPC.__init__(self,self.args) self.get("StartChat",credential) response = self.send() self.deal_msg(response) while running: if not self.queue.empty(): response = self.queue.get() else: response = self.recv() if len(response) == 0: d_print("User Left converstion") self.fetion.session.pop(self.from_uri) return self.deal_msg(response) #self._bye() def deal_msg(self,response): try: Q = re.findall('Q: (-?\d+) M',response) I = re.findall('I: (-?\d+)',response) except: d_print("NO Q") return False for i in range(len(Q)): self.Q = Q[i] self.fetion.queue.put(response) self._ack('M') self._ack('IN') return True def _ack(self,cmd): """ack message from uri""" self.get("ACK",cmd,self.from_uri,self.Q,self.I) self.response = self.ack() self.deal_msg(self.response) def _send_msg(self,msg): msg = msg.replace('<','&lt;') self.get("SendMsg",'',msg) self.send() def _bye(self): """say bye to this session""" self.get("BYE",'') self.send() class PyFetion(SIPC): __log = '' __sipc_url = '' _ssic = '' _lock = RLock() _sipc_proxy = '' _domain = '' _http_tunnel = '' mobile_no = '' passwd = '' queue = Queue() sid = '' login_type = '' receving = False presence = '' debug = False contactlist = {} session = {} def __init__(self,mobile_no,passwd,login_type="TCP",debug=False): self.mobile_no = mobile_no self.passwd = passwd self.login_type = login_type if debug == True: logging.basicConfig(level=logging.DEBUG,format='%(message)s') self.__log = logging elif debug == "FILE": logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(thread)d %(message)s', filename='./PyFetion.log', filemode='w') self.__log = logging global d_print #replace global function with self method d_print = self.__print self.__sipc_url = "https://uid.fetion.com.cn/ssiportal/SSIAppSignIn.aspx" self._sipc_proxy = "221.176.31.45:8080" self._http_tunnel= "http://221.176.31.45/ht/sd.aspx" #uncomment this line for getting configuration from server everytime #It's very slow sometimes, so default use fixed configuration #self.__set_system_config() def login(self,presence=FetionOnline): if not self.__get_uri(): return False self.presence = presence try: self.__register(self._ssic,self._domain) except PyFetionRegisterError,e: d_print("Register Failed!") return False #self.get_personal_info() if not self.get_contactlist(): d_print("get contactlist error") return False self.get("compactlist",self.__uri,self.contactlist.keys()) response = self.send() code = self.get_code(response) if code != 200: return False #self.get("PGGetGroupList",self.__uri) #response = self.send() self.get_offline_msg() self.receving = True return True def logout(self): self.get("DEAD",'') self.send() self.receving = False def start_chat(self,who): self.get("StartChat",'') response = self.send() try: credential = re.findall('credential="(.+?)"',response)[0] sipc_proxy = re.findall('address="(.+?);',response)[0] except: d_print("find tag error") return False args = [self.sid,self._domain,self.login_type,self._http_tunnel,self._ssic,sipc_proxy,self.presence,None] _SIPC = SIPC(args) _SIPC.get("StartChat",credential) response = _SIPC.send() _SIPC.get("InviteBuddy",who) response = _SIPC.send() code = _SIPC.get_code(response) if code != 200: return False response = _SIPC.recv() try: type = re.findall('<event type="(.+?)"',response)[0] except : return False if type == "UserEntered": return FetionHidden elif type == "UserFailed": return FetionOnline def set_presence(self,presence): """set status of fetion""" if self.presence == presence: return True self.get("SetPresence",presence) response = self.send() code = self.get_code(response) if code == 200: self.presence = presence d_print("set presence ok.") return True return False #self.get("PGSetPresence",presence) #response = self.send() def get_offline_msg(self): """get offline message from server""" self.get("GetOfflineMessages",'') response = self.send() return response def add(self,who): """add friend who should be mobile number or fetion number""" my_info = self.get_info() try: nick_name = re.findall('nickname="(.*?)" ',my_info)[0] except IndexError: nick_name = " " #code = self._add(who,nick_name,"AddMobileBuddy") code = self._add(who,nick_name) if code == 522: code = self._add(who,nick_name,"AddMobileBuddy") if code == 404 or code == 400 : d_print("Not Found") return False if code == 521: d_print("Aleady added.") return True if code == 200: return True return False def delete(self,who): if who.isdigit() and len(who) == 11: who = "tel:" + who else: who = self.get_uri(who) if not who: return False self.get("INFO","DeleteBuddy",who) response = self.send() code = self.get_code(response) if code == 404 or code == 400 : d_print("Not Found") return False if code == 200: return True return False def _add(self,who,nick_name,type="AddBuddy"): self.get("INFO",type,who,nick_name) response = self.send() code = self.get_code(response) return code def get_personal_info(self): """get detail information of me""" self.get("INFO","GetPersonalInfo") response = self.send() return response def get_info(self,who=None): """get contact info. who should be uri. string or list """ alluri = [] if who == None: return self.get_personal_info() if type(who) is not list: alluri.append(who) else: alluri = who self.get("INFO","GetContactsInfo",alluri) response = self.send() return response def set_info(self,info): contacts = re.findall('<contact (.+?)</contact>',info) contacts += re.findall('<presence (.+?)</presence>',info) for contact in contacts: #print contacts uri = '' nickname = '' mobile_no = '' try: (uri,mobile_no,nickname) = re.findall('uri="(.+?)".+?mobile-no="(.*?)".+?nickname="(.*?)"',contact)[0] except: try: (uri,nickname) = re.findall('uri="(.+?)".+?nickname="(.*?)"',contact)[0] except: continue #print uri,nickname,mobile_no if uri == self.__uri: continue if self.contactlist[uri][0] == '': self.contactlist[uri][0] = nickname if self.contactlist[uri][1] == '': self.contactlist[uri][1] = mobile_no def get_contactlist(self): """get contact list contactlist is a dict: {uri:[name,mobile-no,status,type]} """ buddy_list = '' allow_list = '' chat_friends = '' need_info = [] self.get("INFO","GetContactList") response = self.send() code = self.get_code(response) if code != 200: return False d = re.findall('<buddy-lists>(.*?)<allow-list>',response)[0] try: buddy_list = re.findall('uri="(.+?)" user-id="\d+" local-name="(.*?)"',d) except: return False try: d = re.findall('<chat-friends>(.*?)</chat-friends>',d)[0] chat_friends = re.findall('uri="(.+?)" user-id="\d+"',d) except: pass for uri in chat_friends: if uri not in self.contactlist: l = ['']*4 need_info.append(uri) self.contactlist[uri] = l self.contactlist[uri][0] = '' self.contactlist[uri][2] = FetionHidden self.contactlist[uri][3] = 'A' #buddy_list [(uri,local_name),...] for p in buddy_list: l = ['']*4 #set uri self.contactlist[p[0]] = l #set local-name self.contactlist[p[0]][0] = p[1] #set default status self.contactlist[p[0]][2] = FetionHidden #self.contactlist[p[0]][2] = FetionOffline if p[0].startswith("tel"): self.contactlist[p[0]][3] = 'T' self.contactlist[p[0]][2] = FetionHidden #set mobile_no self.contactlist[p[0]][1] = p[0][4:] #if no local-name use mobile-no as name if p[1] == '': self.contactlist[p[0]][0] = self.contactlist[p[0]][1] else: self.contactlist[p[0]][3] = 'B' if self.contactlist[p[0]][0] == '': need_info.append(p[0]) """ try: s = re.findall('<allow-list>(.+?)</allow-list>',response)[0] allow_list = re.findall('uri="(.+?)"',s) except: pass #allow_list [uri,...] for uri in allow_list: if uri not in self.contactlist: l = ['']*4 need_info.append(uri) self.contactlist[uri] = l self.contactlist[uri][0] = '' self.contactlist[uri][2] = FetionHidden self.contactlist[uri][3] = 'A' """ ret = self.get_info(need_info) self.set_info(ret) return True def get_uri(self,who): """get uri from fetion number""" if who in self.__uri: return self.__uri if who.startswith("sip"): return who for uri in self.contactlist: if who in uri: return uri return None def send_msg(self,msg,to=None,flag="CatMsg"): """more info at send_sms function. if someone's fetion is offline, msg will send to phone, the same as send_sms. """ if not to: to = self.__uri #Fetion now can use mobile number(09.02.23) #like tel: 13888888888 #but not in sending to PC elif flag != "CatMsg" and to.startswith("tel:"): pass elif flag == "CatMsg" and to.startswith("tel:"): return False elif flag != "CatMsg" and len(to) == 11 and to.isdigit(): to = "tel:"+to else: to = self.get_uri(to) if not to: return False msg = msg.replace('<','&lt;') self.get(flag,to,msg) try: response = self.send() except PyFetionSocketError,e: d_print(('e',),locals()) return False code = self.get_code(response) if code == 280: d_print("Send sms OK!") elif code == 200: d_print("Send msg OK!") else: d_print(('code',),locals()) return False return True def send_sms(self,msg,to=None,long=True): """send sms to someone, if to is None, send self. if long is True, send long sms.(Your phone should support.) to can be mobile number or fetion number """ if long: return self.send_msg(msg,to,"SendCatSMS") else: return self.send_msg(msg,to,"SendSMS") def send_schedule_sms(self,msg,time,to=None): if not to: to = self.__uri elif len(to) == 11 and to.isdigit(): to = "tel:"+to else: to = self.get_uri(to) if not to: return False msg = msg.replace('<','&lt;') self.get("SSSetScheduleSms",msg,time,to) response = self.send() code = self.get_code(response) if code == 486: d_print("Busy Here") return None if code == 200: id = re.search('id="(\d+)"',response).group(1) d_print(('id',),locals(),"schedule_sms id") return id def alive(self): """send keepalive message""" self.get("ALIVE",'') response = self.send() code = self.get_code(response) if code == 200: d_print("keepalive message send ok.") return True return False def receive(self): """response from server""" threads = [] while self.receving: if not self.queue.empty(): response = self.queue.get() else: try: response = self.recv(5) except PyFetionSocketError,e: yield ["NetworkError",e.msg] continue if response =="TimeOut": continue elif len(response) == 0: d_print("logout") return elif response.startswith("BN"): try: type = re.findall('<event type="(.+?)"',response)[0] except IndexError: d_print("Didn't find type") d_print(('response',),locals()) if type == "ServiceResult": self.set_info(response) if type == "deregistered" or type=="disconnect": self.receving = False yield [type] if type == "PresenceChanged": self.set_info(response) ret = re.findall('<presence uri="(.+?)">.+?value="(.+?)".+?type="sms">(\d+)\.',response) if not ret: ret = re.findall('<presence uri="(.+?)">.+?value="(.+?)"',response) #remove self uri event = [i for i in ret if i[0] != self.__uri] event = list(set(event)) for e in event: if len(e) == 3 and e[2] == FetionOffline: self.contactlist[e[0]][2] = e[2] else: self.contactlist[e[0]][2] = e[1] yield [type,event] if type == "UpdateBuddy" or type == "UpdateMobileBuddy": uri = re.findall('uri="(.+?)"',response)[0] l = ['']*4 self.contactlist[uri] = l if type == "UpdateBuddy": ret = self.get_info(uri) self.set_info(ret) else: self.contactlist[uri][3] = 'T' self.contactlist[uri][2] = FetionHidden self.contactlist[uri][1] = uri[4:] self.contactlist[uri][0] = uri[4:] elif response.startswith("M"): try: from_uri = re.findall('F: (.*)',response)[0].strip() msg = re.findall('\r\n\r\n(.*)',response,re.S)[0] except: d_print("Message without content") continue #if from PC remove <Font> try: msg = re.findall('<Font .+?>(.+?)</Font>',msg,re.S)[0] except: pass #from phone or PC try: XI = re.findall('XI: (.*)',response)[0] type = "PC" except: type = "PHONE" #ack this message try: Q = re.findall('Q: (-?\d+) M',response)[0] I = re.findall('I: (-?\d+)',response)[0] self._ack('M',from_uri,Q,I) except: pass yield ["Message",from_uri,msg,type] elif response.startswith("I"): try: from_uri = re.findall('F: (.*)',response)[0].rstrip() except: pass args = [self.sid,self._domain,self.login_type,self._http_tunnel,self._ssic,self._sipc_proxy,self.presence,None] t = on_cmd_I(self,response,args) t.setDaemon(True) t.start() self.session[from_uri] = t #print self.session def _ack(self,cmd,from_uri,Q=0,I=0): """ack message """ self.get("ACK",cmd,from_uri,Q,I) self.ack() def __register(self,ssic,domain): SIPC.__init__(self) response = '' for step in range(1,3): self.get("REG",step,response) response = self.send() code = self.get_code(response) if code == 200: d_print("register successful.") else: raise PyFetionRegisterError(code,response) def __get_system_config(self): global FetionConfigURL global FetionConfigXML url = FetionConfigURL body = FetionConfigXML % self.mobile_no d_print(('url','body'),locals()) config_data = http_send(url,body).read() sipc_url = re.search("<ssi-app-sign-in>(.*)</ssi-app-sign-in>",config_data).group(1) sipc_proxy = re.search("<sipc-proxy>(.*)</sipc-proxy>",config_data).group(1) http_tunnel = re.search("<http-tunnel>(.*)</http-tunnel>",config_data).group(1) d_print(('sipc_url','sipc_proxy','http_tunnel'),locals()) self.__sipc_url = sipc_url self._sipc_proxy = sipc_proxy self._http_tunnel= http_tunnel def __get_uri(self): url = self.__sipc_url+"?mobileno="+self.mobile_no+"&pwd="+urllib.quote(self.passwd) d_print(('url',),locals()) ret = http_send(url,login=True) header = str(ret.info()) body = ret.read() try: ssic = re.search("ssic=(.*);",header).group(1) sid = re.search("sip:(.*)@",body).group(1) uri = re.search('uri="(.*)" mobile-no',body).group(1) status = re.search('user-status="(\d+)"',body).group(1) except: return False domain = "fetion.com.cn" d_print(('ssic','sid','uri','status','domain'),locals(),"Get SID OK") self.sid = sid self.__uri = uri self._ssic = ssic self._domain = domain return True def __print(self,vars=(),namespace=[],msg=''): """if only sigle variable ,arg should like this ('var',)""" if not self.__log: return if vars and not namespace and not msg: msg = vars if vars and namespace: for var in vars: if var in namespace: self.__log.debug("%s={%s}" % (var,str(namespace[var]))) if msg: self.__log.debug("%s" % msg) if __name__ == "__main__": fetion = PyFetion('15958127591','sd145914sd1!','HTTP') fetion.login(FetionOnline) fetion.send_sms('ssssssss') fetion.logout()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging,urllib,urllib2 from google.appengine.api import urlfetch ''' Created on 2010-7-15 @author: Fred ''' FETION_API = 'http://sms.jkgc.net/send.php' SEND_SUCCESS = 200 SEND_FAILTURE = 400 class TmpFetion(): ''' 封装一个简单的飞信功能 ''' mobile_no = '' passwd = '' def __init__(self,mobile_no,passwd): self.mobile_no = mobile_no self.passwd = passwd def send_msg(self,send_to,content): form_fields = { "phone": self.mobile_no, "fetion_password": self.passwd, "tophone": send_to, "message": content.encode('utf8') } form_data = urllib.urlencode(form_fields) # urlfetch.fetch(url=FETION_API,payload=form_data,method=urlfetch.POST) # request_data = urllib.urlencode([('phone', self.mobile_no),('fetion_password',self.passwd),('tophone',send_to),('message',content.encode('utf-8'))]) # logging.info('**%s**%s**%s**%s**'%(self.mobile_no,self.passwd,send_to,content)) request = urllib2.Request(FETION_API,data=form_data) i = 1 for i in range(3): try: logging.info('*************%d'%i) # print i res = urllib2.urlopen(request) return except: i = i+1 # return res # logging.info('***********'+res.read()) if __name__=="__main__": tmp = TmpFetion('15958127591','sd145914sd1!') tmp.send_msg('15958127591', u'哈哈哈哈哈')
Python
# -*- coding: utf-8 -*- #!/usr/bin/env python from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from base import * from weather.model import * class MainPage(BaseRequestHandler): def get(self): self.render('template/weather/admin.html') class AddCity(BaseRequestHandler): def get(self): list = City.all() self.render('template/weather/admin_city.html',{'list':list}) def post(self): name = self.request.get('name') url = self.request.get('url') remark = self.request.get('remark') if name and url: city = City() city.name = name city.url = url city.remark = remark city.put() self.redirect('/console/add_city') class DelCity(BaseRequestHandler): def post(self): keys = self.request.get_all('list') for k in keys: City.get(k).delete() self.redirect('/console/add_city') application = webapp.WSGIApplication( [('/console/', MainPage), ('/console/add_city', AddCity), ('/console/deletecity',DelCity), ],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
# -*- coding: utf-8 -*- #!/usr/bin/env python import logging,datetime import urllib,urllib2 WETHER_API = u'http://www.google.com/ig/api?hl=zh-cn&weather=%s' WETHER_MESSAGE = u'今天%s,气温%s-%s.明天%s,气温%s-%s.http://sms.fengsage.com' class WeatherCollect(): city = '' url = '' def __init__(self,url,city=''): self.city = city self.url = url def __read_page(self): #模拟浏览器 header = { 'Host':'www.google.com',\ 'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9',\ 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\ 'Accept-Language':'zh-cn,zh;q=0.5'} req = urllib2.Request(self.url,None,header) try: response = urllib2.urlopen(req) except: print 'open exception' return 0 # print response.read() html_content = response.read() # print html_content return html_content def get_weather(self): global WETHER_MESSAGE import re xml = self.__read_page() # try: td_condition = re.findall(u'<condition data="([^>]*)"/>', xml)[1].decode('utf-8') #雨 td_low = re.findall(u'<low data="([^>]*)"/>', xml)[0] #当天最低气温 td_high = re.findall(u'<high data="([^>]*)"/>', xml)[0] #当天最高气温 # td_wind = re.findall('<wind_condition data="([^>]*)"/>', xml)[0] #风向 tm_condition = re.findall(u'<condition data="([^>]*)"/>', xml)[2].decode('utf-8') #雨 tm_low = re.findall(u'<low data="([^>]*)"/>', xml)[1] #明天最低气温 tm_high = re.findall(u'<high data="([^>]*)"/>', xml)[1] #明天最高气温 msg = WETHER_MESSAGE%(td_condition,td_low,td_high,tm_condition,tm_low,tm_high) # msg = WETHER_MESSAGE%(td_m_condition,td_high,td_n_condition,td_low,tm_m_condition,tm_high,tm_n_condition,tm_low) return msg # except : # return None if __name__=="__main__": w = WeatherCollect('http://www.google.com/ig/api?hl=zh-cn&weather=jiaxing') print w.get_weather()
Python
# -*- coding: utf-8 -*- #!/usr/bin/env python from google.appengine.ext import db class User(db.Model): ''' 客户实体,不使用google用户 ''' username = db.StringProperty(multiline=False) password = db.StringProperty(multiline=False) mobile_no = db.StringProperty(multiline=False) mobile_pwd = db.StringProperty(multiline=False) create_date = db.DateTimeProperty(auto_now_add=True) last_login = db.DateTimeProperty() last_ip = db.StringProperty(multiline=False) running = db.BooleanProperty() class City(db.Model): ''' 城市列表 ''' name = db.StringProperty(multiline=False) url = db.StringProperty(multiline=False) remark = db.StringProperty() class SendUsers(db.Model): ''' 发送列表 ''' name = db.StringProperty(multiline=False) number = db.StringProperty(multiline=False) city = db.ReferenceProperty(City) user = db.ReferenceProperty(User) class WeatherStore(db.Model): ''' 每天保存天气 ''' message = db.StringProperty(multiline=False) date = db.StringProperty(multiline=False) city = db.ReferenceProperty(City) class FetionLog(db.Model): ''' 发送日志 ''' sendname = db.StringProperty(multiline=False) senddate = db.DateTimeProperty() username = db.StringProperty(multiline=False) #所属用户 weather = db.ReferenceProperty(WeatherStore) #天气记录 status = db.StringProperty(multiline=False)
Python
# -*- coding: utf-8 -*- #!/usr/bin/env python from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import logging from sms.TmpFetion import TmpFetion from weather.model import * from base import * from util import * import gmemsess from weather.weather_collect import WeatherCollect def makeWeather(city,date): query = WeatherStore.all().filter('date =',date).filter('city =',city.key()) if query.count()>0: logging.info('*************find weather *************') return query[0] else: logging.info('*************not find weather*************') wc = WeatherCollect(city.url) msg = wc.get_weather() logging.info('*************weather message %s *************'%msg) if msg: wether = WeatherStore() wether.date = today_str() wether.city = city wether.message = msg wether.put() return wether return u'程序异常,稍后重发!' class MainPage(BaseRequestHandler): def get(self): self.render('template/weather/index.html') class Login(BaseRequestHandler): def post(self): msg = '' username = self.request.get('username') password = self.request.get('password') if username and password: query = User.all().filter('username =', username) if query.count()>0: query = query[0] if query.password != password: msg = u'密码输入错误,请重试!' else: query.last_ip = self.request.remote_addr query.last_login = today() query.put() sess = gmemsess.Session(self) sess['username'] = username sess['user_key'] = query.key() sess.save() logging.info('%s Login success!'%username) self.redirect('/admin') else: msg = u'您输入的用户名密码不正确!' else: msg = u'用户名或密码不能为空!' self.render('template/weather/index.html',{'msg':msg}) class AdminPage(BaseRequestHandler): @checkLogin def get(self): user = User.get(getUserKey(self)) self.render('template/weather/user.html',{'user':user}) class Registe(BaseRequestHandler): def post(self): msg = '' username = self.request.get('username') password = self.request.get('password') repassword = self.request.get('repassword') if username.strip() and password == repassword: query = User.all().filter('username =', username) if query.count()==0: user = User() user.username = username user.password = password user.running = False user.put() logging.info("%s Regist success!"%username) msg = u'注册成功,请在右侧登录!' else: msg = u'该用户已经注册,请重新注册' else: msg = u'字段不能为空,两次密码必须一致' self.render('template/weather/index.html',{'msg':msg}) class ActiveFetion(BaseRequestHandler): @checkLogin def post(self): msg = '' mobile_no = self.request.get('mobile_no') mobile_pwd = self.request.get('mobile_pwd') status = self.request.get('status') # logging.info('************'+mobile_no+'**********'+mobile_pwd) if mobile_no and mobile_pwd: user = User.get(getUserKey(self)) user.mobile_no = mobile_no user.mobile_pwd = mobile_pwd if status == "True" : user.running = False else: user.running = True user.put() self.redirect('/admin') else: msg = u'手机号码和飞信密码不能为空' self.render('template/weather/user.html',{'msg':msg}) class TestFetion(BaseRequestHandler): @checkLogin def get(self): msg = '' user = User.get(getUserKey(self)) if not user.running: msg = u'请先激活' self.render('template/weather/user.html',{'msg':msg}) if user.mobile_no and user.mobile_pwd: fetion = TmpFetion(user.mobile_no,user.mobile_pwd) fetion.send_msg(user.mobile_no, u'收到本消息,说明服务启用正常!') self.redirect('/admin') else: msg = u'请先填写您的手机号和飞信密码!' self.render('template/weather/user.html',{'msg':msg}) class SendList(BaseRequestHandler): @checkLogin def get(self): user = User.get(getUserKey(self)) if not user.running: msg = u'您的飞信尚未激活!请先激活飞信' self.render('template/weather/user.html',{'msg':msg}) else: citys = City.all() list = user.sendusers_set # logging.info('*****************'+str(list.count())) self.render('template/weather/sender.html',{'list':list,'citys':citys}) @checkLogin def post(self): msg = '' name = self.request.get('name') number = self.request.get('number') city = self.request.get('city') #检查此号码是否已经存在 if name and number and city : query = SendUsers.all().filter('user =', getUserKey(self)).filter('number =', number) if query.count()>0: msg = u'该号码已添加,请勿重复添加' else: sender = SendUsers() sender.name = name sender.number = number sender.city = City.get(city) sender.user = User.get(getUserKey(self)) sender.put() self.redirect('/admin/sendusers') else: msg = u'手机号码和城市拼音不能为空' self.render('template/weather/sender.html',{'msg':msg}) class DeleteSenders(BaseRequestHandler): @checkLogin def post(self): keys = self.request.get_all('list') for k in keys: query = SendUsers.get(k) if query.user.username == getUsername(self): query.delete() self.redirect('/admin/sendusers') class QuickFetion(BaseRequestHandler): @checkLogin def get(self): send_list = User.get(getUserKey(self)).sendusers_set for s in send_list: log = FetionLog() log.sendname = s.name log.senddate = datetime.datetime.now() log.username = s.user.username log.weather = WeatherStore.all().filter('date =',today_str()).filter('city =',s.city.key())[0] try: fetion = TmpFetion(s.user.mobile_no,s.user.mobile_pwd) fetion.send_msg(s.number,makeWeather(s.city,today_str()).message) log.status = 'success' except: log.status = 'failture' log.put() self.redirect('/admin/sendusers') class AutoWeather(BaseRequestHandler): ''' 每天定时采集天气情况 ''' def get(self): logging.info('***************start auto weather %s***************'%today_str()) citys = City.all() for c in citys: makeWeather(c,today_str()) logging.info('***************end auto weather***************') class AutoFetion(BaseRequestHandler): import datetime def get(self): senders = SendUsers.all() logging.info('***************start auto fetion***************') for s in senders: if s.user.running: log = FetionLog() log.sendname = s.name log.senddate = datetime.datetime.now() log.username = s.user.username log.weather = makeWeather(s.city,today_str()) try: fetion = TmpFetion(s.user.mobile_no,s.user.mobile_pwd) fetion.send_msg(s.number,makeWeather(s.city,today_str()).message) log.status = 'success' except: log.status = 'failture' log.put() logging.info('***************end auto fetion***************') application = webapp.WSGIApplication( [('/', MainPage), ('/regist',Registe), ('/login',Login), ('/admin',AdminPage), ('/admin/active',ActiveFetion), ('/admin/test',TestFetion), ('/admin/sendusers',SendList), ('/admin/deletesenders',DeleteSenders), ('/admin/quickSend',QuickFetion), ('/autofetion',AutoFetion), ('/autoweather',AutoWeather) ],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main() # weather = Weather('hangzhou123213') # print weather.get_weather()
Python
# gmemsess.py - memcache-backed session Class for Google Appengine # Version 1.4 # Copyright 2008 Greg Fawcett <greg@vig.co.nz> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import random from google.appengine.api import memcache _sidChars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' _defaultTimeout=30*60 # 30 min _defaultCookieName='gsid' #---------------------------------------------------------------------- class Session(dict): """A secure lightweight memcache-backed session Class for Google Appengine.""" #---------------------------------------------------------- def __init__(self,rh,name=_defaultCookieName,timeout=_defaultTimeout): """Create a session object. Keyword arguments: rh -- the parent's request handler (usually self) name -- the cookie name (defaults to "gsid") timeout -- the number of seconds the session will last between requests (defaults to 1800 secs - 30 minutes) """ self.rh=rh # request handler self._timeout=timeout self._name=name self._new=True self._invalid=False dict.__init__(self) if name in rh.request.str_cookies: self._sid=rh.request.str_cookies[name] data=memcache.get(self._sid) if data!=None: self.update(data) # memcache timeout is absolute, so we need to reset it on each access memcache.set(self._sid,data,self._timeout) self._new=False return # Create a new session ID # There are about 10^14 combinations, so guessing won't work self._sid=random.choice(_sidChars)+random.choice(_sidChars)+\ random.choice(_sidChars)+random.choice(_sidChars)+\ random.choice(_sidChars)+random.choice(_sidChars)+\ random.choice(_sidChars)+random.choice(_sidChars) # Added path so session works with any path rh.response.headers.add_header('Set-Cookie','%s=%s; path=/;'%(name,self._sid)) #---------------------------------------------------------- def save(self): """Save session data.""" if not self._invalid: memcache.set(self._sid,self.copy(),self._timeout) #---------------------------------------------------------- def is_new(self): """Returns True if session was created during this request.""" return self._new #---------------------------------------------------------- def get_id(self): """Returns session id string.""" return self._sid #---------------------------------------------------------- def invalidate(self): """Delete session data and cookie.""" self.rh.response.headers.add_header('Set-Cookie', '%s=; expires=Sat, 1-Jan-2000 00:00:00 GMT;'%(self._name)) memcache.delete(self._sid) self.clear() self._invalid=True
Python
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """A simple wrapper for Django templates. The main purpose of this module is to hide all of the package import pain you normally have to go through to get Django to work. We expose the Django Template and Context classes from this module, handling the import nonsense on behalf of clients. Typical usage: from google.appengine.ext.webapp import template print template.render('templates/index.html', {'foo': 'bar'}) Django uses a global setting for the directory in which it looks for templates. This is not natural in the context of the webapp module, so our load method takes in a complete template path, and we set these settings on the fly automatically. Because we have to set and use a global setting on every method call, this module is not thread safe, though that is not an issue for applications. Django template documentation is available at: http://www.djangoproject.com/documentation/templates/ """ import md5 import os try: from django import v0_96 except ImportError: pass import django import django.conf try: django.conf.settings.configure( DEBUG=False, TEMPLATE_DEBUG=False, TEMPLATE_LOADERS=( 'django.template.loaders.filesystem.load_template_source', ), ) except (EnvironmentError, RuntimeError): pass import django.template import django.template.loader from google.appengine.ext import webapp def render(template_path, template_dict, debug=False): """Renders the template at the given path with the given dict of values. Example usage: render("templates/index.html", {"name": "Bret", "values": [1, 2, 3]}) Args: template_path: path to a Django template template_dict: dictionary of values to apply to the template """ t = load(template_path, debug) return t.render(Context(template_dict)) template_cache = {} def load(path, debug=False): """Loads the Django template from the given path. It is better to use this function than to construct a Template using the class below because Django requires you to load the template with a method if you want imports and extends to work in the template. """ abspath = os.path.abspath(path) if not debug: template = template_cache.get(abspath, None) else: template = None if not template: directory, file_name = os.path.split(abspath) new_settings = { 'TEMPLATE_DIRS': (directory,), 'TEMPLATE_DEBUG': debug, 'DEBUG': debug, } old_settings = _swap_settings(new_settings) try: template = django.template.loader.get_template(file_name) finally: _swap_settings(old_settings) if not debug: template_cache[abspath] = template def wrap_render(context, orig_render=template.render): URLNode = django.template.defaulttags.URLNode save_urlnode_render = URLNode.render old_settings = _swap_settings(new_settings) try: URLNode.render = _urlnode_render_replacement return orig_render(context) finally: _swap_settings(old_settings) URLNode.render = save_urlnode_render template.render = wrap_render return template def _swap_settings(new): """Swap in selected Django settings, returning old settings. Example: save = _swap_settings({'X': 1, 'Y': 2}) try: ...new settings for X and Y are in effect here... finally: _swap_settings(save) Args: new: A dict containing settings to change; the keys should be setting names and the values settings values. Returns: Another dict structured the same was as the argument containing the original settings. Original settings that were not set at all are returned as None, and will be restored as None by the 'finally' clause in the example above. This shouldn't matter; we can't delete settings that are given as None, since None is also a legitimate value for some settings. Creating a separate flag value for 'unset' settings seems overkill as there is no known use case. """ settings = django.conf.settings old = {} for key, value in new.iteritems(): old[key] = getattr(settings, key, None) setattr(settings, key, value) return old def create_template_register(): """Used to extend the Django template library with custom filters and tags. To extend the template library with a custom filter module, create a Python module, and create a module-level variable named "register", and register all custom filters to it as described at http://www.djangoproject.com/documentation/templates_python/ #extending-the-template-system: templatefilters.py ================== register = webapp.template.create_template_register() def cut(value, arg): return value.replace(arg, '') register.filter(cut) Then, register the custom template module with the register_template_library function below in your application module: myapp.py ======== webapp.template.register_template_library('templatefilters') """ return django.template.Library() def register_template_library(package_name): """Registers a template extension module to make it usable in templates. See the documentation for create_template_register for more information.""" if not django.template.libraries.get(package_name, None): django.template.add_to_builtins(package_name) Template = django.template.Template Context = django.template.Context def _urlnode_render_replacement(self, context): """Replacement for django's {% url %} block. This version uses WSGIApplication's url mapping to create urls. Examples: <a href="{% url MyPageHandler "overview" %}"> {% url MyPageHandler implicit_args=False %} {% url MyPageHandler "calendar" %} {% url MyPageHandler "jsmith","calendar" %} """ args = [arg.resolve(context) for arg in self.args] try: app = webapp.WSGIApplication.active_instance handler = app.get_registered_handler_by_name(self.view_name) return handler.get_url(implicit_args=True, *args) except webapp.NoUrlFoundError: return ''
Python