How to use rebot method in Robotframework

Best Python code snippet using robotframework

Run Robotframework automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Source: Github

1#!/usr/bin/env python
3#  Copyright 2008-2015 Nokia Networks
4#  Copyright 2016-     Robot Framework Foundation
6#  Licensed under the Apache License, Version 2.0 (the "License");
7#  you may not use this file except in compliance with the License.
8#  You may obtain a copy of the License at
12#  Unless required by applicable law or agreed to in writing, software
13#  distributed under the License is distributed on an "AS IS" BASIS,
14#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15#  See the License for the specific language governing permissions and
16#  limitations under the License.
18"""Module implementing the command line entry point for post-processing outputs.
20This module can be executed from the command line using the following
23    python -m robot.rebot
24    python path/to/robot/
26Instead of ``python`` it is possible to use also other Python interpreters.
27This module is also used by the installed ``rebot`` start-up script.
29This module also provides :func:`rebot` and :func:`rebot_cli` functions
30that can be used programmatically. Other code is for internal usage.
33import sys
35# Allows running as a script. __name__ check needed with multiprocessing:
37if 'robot' not in sys.modules and __name__ == '__main__':
38    import pythonpathsetter
40from robot304.conf import RebotSettings
41from robot304.errors import DataError
42from robot304.reporting import ResultWriter
43from robot304.output import LOGGER
44from robot304.utils import Application
45from import RobotFramework
48USAGE = """Rebot -- Robot Framework report and log generator
50Version:  <VERSION>
52Usage:  rebot [options] robot_outputs
53   or:  python -m robot.rebot [options] robot_outputs
54   or:  python path/to/robot/ [options] robot_outputs
55   or:  java -jar robotframework.jar rebot [options] robot_outputs
57Rebot can be used to generate logs and reports in HTML format. It can also
58produce new XML output files which can be further processed with Rebot or
59other tools.
61The easiest way to execute Rebot is using the `rebot` script created as part
62of the normal installation. Alternatively it is possible to execute the
63`robot.rebot` module directly using `python -m robot.rebot`, where `python`
64can be replaced with any supported Python interpreter like `jython`, `ipy` or
65`python3`. Yet another alternative is running the `robot/` script like
66`python path/to/robot`. Finally, there is a standalone JAR distribution.
68Inputs to Rebot are XML output files generated by Robot Framework test runs or
69earlier Rebot executions. When more than one input file is given, a new top
70level test suite containing suites in the given files is created by default.
71This allows combining multiple outputs together to create higher level reports.
72An exception is that if --merge is used, results are combined by adding suites
73and tests in subsequent outputs into the first suite structure. If same test
74is found from multiple outputs, the last one replaces the earlier ones.
76For more information about Rebot and other built-in tools, see
77 For more details
78about Robot Framework in general, go to
83 -R --merge               When combining results, merge outputs together
84                          instead of putting them under a new top level suite.
85                          Example: rebot --merge orig.xml rerun.xml
86 -N --name name           Set the name of the top level test suite. Underscores
87                          in the name are converted to spaces. Default name is
88                          created from the name of the executed data source.
89 -D --doc documentation   Set the documentation of the top level test suite.
90                          Underscores in the documentation are converted to
91                          spaces and it may also contain simple HTML formatting
92                          (e.g. *bold* and http://url/).
93 -M --metadata name:value *  Set metadata of the top level suite. Underscores
94                          in the name and value are converted to spaces. Value
95                          can contain same HTML formatting as --doc.
96                          Example: --metadata version:1.2
97 -G --settag tag *        Sets given tag(s) to all executed test cases.
98 -t --test name *         Select test cases by name or long name. Name is case
99                          and space insensitive and it can also be a simple
100                          pattern where `*` matches anything and `?` matches
101                          any char. If using `*` and `?` in the console is
102                          problematic, see --escape and --argumentfile.
103 -s --suite name *        Select test suites by name. When this option is used
104                          with --test, --include or --exclude, only test cases
105                          in matching suites and also matching other filtering
106                          criteria are selected. Given name can be a simple
107                          pattern similarly as with --test.
108 -i --include tag *       Select test cases to by tag. Similarly as name with
109                          --test, tag is case and space insensitive and it is
110                          possible to use patterns with `*` and `?` as
111                          wildcards. Tags and patterns can also be combined
112                          together with `AND`, `OR`, and `NOT` operators.
113                          Examples: --include foo --include bar*
114                                    --include fooANDbar*
115 -e --exclude tag *       Select test cases not to be included by tag. These
116                          tests are not selected even if included with
117                          --include. Tags are matched using the rules explained
118                          with --include.
119    --processemptysuite   Processes output also if the top level test suite is
120                          empty. Useful e.g. with --include/--exclude when it
121                          is not an error that no test matches the condition.
122 -c --critical tag *      Tests having given tag are considered critical. If no
123                          critical tags are set, all tags are critical. Tags
124                          can be given as a pattern like  with --include.
125 -n --noncritical tag *   Tests with given tag are not critical even if they
126                          have a tag set with --critical. Tag can be a pattern.
127 -d --outputdir dir       Where to create output files. The default is the
128                          directory where Rebot is run from and the given path
129                          is considered relative to that unless it is absolute.
130 -o --output file         XML output file. Not created unless this option is
131                          specified. Given path, similarly as paths given to
132                          --log, --report and --xunit, is relative to
133                          --outputdir unless given as an absolute path.
134 -l --log file            HTML log file. Can be disabled by giving a special
135                          name `NONE`. Default: log.html
136                          Examples: `--log mylog.html`, `-l none`
137 -r --report file         HTML report file. Can be disabled with `NONE`
138                          similarly as --log. Default: report.html
139 -x --xunit file          xUnit compatible result file. Not created unless this
140                          option is specified.
141    --xunitskipnoncritical  Mark non-critical tests on xUnit output as skipped.
142 -T --timestampoutputs    When this option is used, timestamp in a format
143                          `YYYYMMDD-hhmmss` is added to all generated output
144                          files between their basename and extension. For
145                          example `-T -o output.xml -r report.html -l none`
146                          creates files like `output-20070503-154410.xml` and
147                          `report-20070503-154410.html`.
148    --splitlog            Split log file into smaller pieces that open in
149                          browser transparently.
150    --logtitle title      Title for the generated test log. The default title
151                          is `<Name Of The Suite> Test Log`. Underscores in
152                          the title are converted into spaces in all titles.
153    --reporttitle title   Title for the generated test report. The default
154                          title is `<Name Of The Suite> Test Report`.
155    --reportbackground colors  Background colors to use in the report file.
156                          Either `all_passed:critical_passed:failed` or
157                          `passed:failed`. Both color names and codes work.
158                          Examples: --reportbackground green:yellow:red
159                                    --reportbackground #00E:#E00
160 -L --loglevel level      Threshold for selecting messages. Available levels:
161                          TRACE (default), DEBUG, INFO, WARN, NONE (no msgs).
162                          Use syntax `LOGLEVEL:DEFAULT` to define the default
163                          visible log level in log files.
164                          Examples: --loglevel DEBUG
165                                    --loglevel DEBUG:INFO
166    --suitestatlevel level  How many levels to show in `Statistics by Suite`
167                          in log and report. By default all suite levels are
168                          shown. Example:  --suitestatlevel 3
169    --tagstatinclude tag *  Include only matching tags in `Statistics by Tag`
170                          and `Test Details` in log and report. By default all
171                          tags set in test cases are shown. Given `tag` can
172                          also be a simple pattern (see e.g. --test).
173    --tagstatexclude tag *  Exclude matching tags from `Statistics by Tag` and
174                          `Test Details`. This option can be used with
175                          --tagstatinclude similarly as --exclude is used with
176                          --include.
177    --tagstatcombine tags:name *  Create combined statistics based on tags.
178                          These statistics are added into `Statistics by Tag`
179                          and matching tests into `Test Details`. If optional
180                          `name` is not given, name of the combined tag is got
181                          from the specified tags. Tags are combined using the
182                          rules explained in --include.
183                          Examples: --tagstatcombine requirement-*
184                                    --tagstatcombine tag1ANDtag2:My_name
185    --tagdoc pattern:doc *  Add documentation to tags matching given pattern.
186                          Documentation is shown in `Test Details` and also as
187                          a tooltip in `Statistics by Tag`. Pattern can contain
188                          characters `*` (matches anything) and `?` (matches
189                          any char). Documentation can contain formatting
190                          similarly as with --doc option.
191                          Examples: --tagdoc mytag:My_documentation
192                                    --tagdoc regression:*See*_http://info.html
193                                    --tagdoc owner-*:Original_author
194    --tagstatlink pattern:link:title *  Add external links into `Statistics by
195                          Tag`. Pattern can contain characters `*` (matches
196                          anything) and `?` (matches any char). Characters
197                          matching to wildcard expressions can be used in link
198                          and title with syntax %N, where N is index of the
199                          match (starting from 1). In title underscores are
200                          automatically converted to spaces.
201                          Examples: --tagstatlink mytag:http://my.domain:Link
202                          --tagstatlink bug-*:http://tracker/id=%1:Bug_Tracker
203    --removekeywords all|passed|for|wuks|name:<pattern>|tag:<pattern> *
204                          Remove keyword data from all generated outputs.
205                          Keywords containing warnings are not removed except
206                          in `all` mode.
207                          all:     remove data from all keywords
208                          passed:  remove data only from keywords in passed
209                                   test cases and suites
210                          for:     remove passed iterations from for loops
211                          wuks:    remove all but the last failing keyword
212                                   inside `BuiltIn.Wait Until Keyword Succeeds`
213                          name:<pattern>:  remove data from keywords that match
214                                   the given pattern. The pattern is matched
215                                   against the full name of the keyword (e.g.
216                                   'MyLib.Keyword', 'resource.Second Keyword'),
217                                   is case, space, and underscore insensitive,
218                                   and may contain `*` and `?` as wildcards.
219                                   Examples: --removekeywords name:Lib.HugeKw
220                                             --removekeywords name:myresource.*
221                          tag:<pattern>:  remove data from keywords that match
222                                   the given pattern. Tags are case and space
223                                   insensitive and it is possible to use
224                                   patterns with `*` and `?` as wildcards.
225                                   Tags and patterns can also be combined
226                                   together with `AND`, `OR`, and `NOT`
227                                   operators.
228                                   Examples: --removekeywords foo
229                                             --removekeywords fooANDbar*
230    --flattenkeywords for|foritem|name:<pattern>|tag:<pattern> *
231                          Flattens matching keywords in all generated outputs.
232                          Matching keywords get all log messages from their
233                          child keywords and children are discarded otherwise.
234                          for:     flatten for loops fully
235                          foritem: flatten individual for loop iterations
236                          name:<pattern>:  flatten matched keywords using same
237                                   matching rules as with
238                                   `--removekeywords name:<pattern>`
239                          tag:<pattern>:  flatten matched keywords using same
240                                   matching rules as with
241                                   `--removekeywords tag:<pattern>`
242    --starttime timestamp  Set starting time of test execution when creating
243                          reports. Timestamp must be given in format
244                          `2007-10-01 15:12:42.268` where all separators are
245                          optional (e.g. `20071001151242268` is ok too) and
246                          parts from milliseconds to hours can be omitted if
247                          they are zero (e.g. `2007-10-01`). This can be used
248                          to override starttime of the suite when reports are
249                          created from a single suite or to set starttime for
250                          combined suite, which is otherwise set to `N/A`.
251    --endtime timestamp   Same as --starttime but for ending time. If both
252                          options are used, elapsed time of the suite is
253                          calculated based on them. For combined suites,
254                          it is otherwise calculated by adding elapsed times
255                          of combined test suites together.
256    --nostatusrc          Sets the return code to zero regardless of failures
257                          in test cases. Error codes are returned normally.
258    --prerebotmodifier class *  Class to programmatically modify the result
259                          model before creating outputs.
260 -C --consolecolors auto|on|ansi|off  Use colors on console output or not.
261                          auto: use colors when output not redirected (default)
262                          on:   always use colors
263                          ansi: like `on` but use ANSI colors also on Windows
264                          off:  disable colors altogether
265                          Note that colors do not work with Jython on Windows.
266 -P --pythonpath path *   Additional locations to add to the module search path
267                          that is used when importing Python based extensions.
268 -E --escape what:with *  Escape characters which are problematic in console.
269                          `what` is the name of the character to escape and
270                          `with` is the string to escape it with. Note that
271                          all given arguments, incl. data sources, are escaped
272                          so escape characters ought to be selected carefully.
273                          <---------------------ESCAPES----------------------->
274                          Examples:
275                          --escape space:_ --metadata X:Value_with_spaces
276                          -E space:SP -E quot:Q -v var:QhelloSPworldQ
277 -A --argumentfile path *  Text file to read more arguments from. File can have
278                          both options and data sources one per line. Contents
279                          do not need to be escaped but spaces in the beginning
280                          and end of lines are removed. Empty lines and lines
281                          starting with a hash character (#) are ignored.
282                          Example file:
283                          |  --include regression
284                          |  --name Regression Tests
285                          |  # This is a comment line
286                          |  my_tests.html
287                          |  path/to/test/directory/
288 -h -? --help             Print usage instructions.
289 --version                Print version information.
291Options that are marked with an asterisk (*) can be specified multiple times.
292For example, `--test first --test third` selects test cases with name `first`
293and `third`. If an option accepts a value but is not marked with an asterisk,
294the last given value has precedence. For example, `--log A.html --log B.html`
295creates log file `B.html`. Options accepting no values can be disabled by
296using the same option again with `no` prefix added or dropped. The last option
297has precedence regardless of how many times options are used. For example,
298`--merge --merge --nomerge --nostatusrc --statusrc` would not activate the
299merge mode and would return normal status rc.
301Long option format is case-insensitive. For example, --SuiteStatLevel is
302equivalent to but easier to read than --suitestatlevel. Long options can
303also be shortened as long as they are unique. For example, `--logti Title`
304works while `--lo log.html` does not because the former matches only --logtitle
305but the latter matches both --log and --logtitle.
307Environment Variables
310REBOT_OPTIONS             Space separated list of default options to be placed
311                          in front of any explicit options on the command line.
312ROBOT_SYSLOG_FILE         Path to a file where Robot Framework writes internal
313                          information about processed files. Can be useful when
314                          debugging problems. If not set, or set to special
315                          value `NONE`, writing to the syslog file is disabled.
316ROBOT_SYSLOG_LEVEL        Log level to use when writing to the syslog file.
317                          Available levels are the same as for --loglevel
318                          command line option and the default is INFO.
323# Simple Rebot run that creates log and report with default names.
324$ rebot output.xml
326# Using options. Note that this is one long command split into multiple lines.
327$ rebot --log smoke_log.html --report smoke_report.html --include smoke
328        --ReportTitle Smoke_Tests --ReportBackground green:yellow:red
329        --TagStatCombine tag1ANDtag2 path/to/myoutput.xml
331# Executing `robot.rebot` module using Python and creating combined outputs.
332$ python -m robot.rebot --name Combined outputs/*.xml
334# Running `robot/` script with Jython.
335$ jython path/robot/ -N Project_X -l none -r x.html output.xml
339class Rebot(RobotFramework):
341    def __init__(self):
342        Application.__init__(self, USAGE, arg_limits=(1,),
343                             env_options='REBOT_OPTIONS', logger=LOGGER)
345    def main(self, datasources, **options):
346        settings = RebotSettings(options)
347        LOGGER.register_console_logger(**settings.console_output_config)
348        LOGGER.disable_message_cache()
349        rc = ResultWriter(*datasources).write_results(settings)
350        if rc < 0:
351            raise DataError('No outputs created.')
352        return rc
355def rebot_cli(arguments, exit=True):
356    """Command line execution entry point for post-processing outputs.
358    :param arguments: Command line options and arguments as a list of strings.
359    :param exit: If ``True``, call ``sys.exit`` with the return code denoting
360        execution status, otherwise just return the rc. New in RF 3.0.1.
362    Entry point used when post-processing outputs from the command line, but
363    can also be used by custom scripts. Especially useful if the script itself
364    needs to accept same arguments as accepted by Rebot, because the script can
365    just pass them forward directly along with the possible default values it
366    sets itself.
368    Example::
370        from robot import rebot_cli
372        rebot_cli(['--name', 'Example', '--log', 'NONE', 'o1.xml', 'o2.xml'])
374    See also the :func:`rebot` function that allows setting options as keyword
375    arguments like ``name="Example"`` and generally has a richer API for
376    programmatic Rebot execution.
377    """
378    return Rebot().execute_cli(arguments, exit=exit)
381def rebot(*outputs, **options):
382    """Programmatic entry point for post-processing outputs.
384    :param outputs: Paths to Robot Framework output files similarly
385        as when running the ``rebot`` command on the command line.
386    :param options: Options to configure processing outputs. Accepted
387        options are mostly same as normal command line options to the ``rebot``
388        command. Option names match command line option long names without
389        hyphens so that, for example, ``--name`` becomes ``name``.
391    The semantics related to passing options are exactly the same as with the
392    :func:`` function. See its documentation for more details.
394    Examples::
396        from robot import rebot
398        rebot('path/to/output.xml')
399        with open('stdout.txt', 'w') as stdout:
400            rebot('o1.xml', 'o2.xml', name='Example', log=None, stdout=stdout)
402    Equivalent command line usage::
404        rebot path/to/output.xml
405        rebot --name Example --log NONE o1.xml o2.xml > stdout.txt
406    """
407    return Rebot().execute(*outputs, **options)
410if __name__ == '__main__':
411    rebot_cli(sys.argv[1:])
Full Screen

Source: Github

1import env
2import os
3import sys
4from subprocess import call
5import start_mongod
9Credits for Selenium2Library project for creating the original version
14    '--outputdir', '%(outdir)s',
15    '--escape', 'space:SP',
16    '--report', 'none',
17    '--log', 'none',
18    #'--suite', 'Acceptance.Keywords.Textfields',
19    '--loglevel', 'DEBUG',
20    '--pythonpath', '%(pythonpath)s',
23    '--outputdir', '%(outdir)s',
24    '--name', 'AcceptanceSPTests',
25    '--escape', 'space:SP',
26    '--critical', 'regression',
27    '--noncritical', 'inprogress',
29ARG_VALUES = {'outdir': env.RESULTS_DIR, 'pythonpath': env.SRC_DIR}
31mongo_db_name1 = 'test'
32mongo_db_name2 = 'admin'
33mongo_db_collection = 'test2013'
34mongo_db_document = {"firstName": "John", "lastName": "Smith", "age": 25}
37def acceptance_tests(interpreter, args):
38    runner = {'python': 'pybot', 'jython': 'jybot', 'ipy': 'ipybot'}[interpreter]
39    mongo_db = start_mongod.MongoTemporaryInstance()
40    mongo_db.start_mongodb()
41    mongo_db.mongo_create_db(mongo_db_name1, mongo_db_collection, mongo_db_document)
42    mongo_db.mongo_create_db(mongo_db_name2, mongo_db_collection, mongo_db_document)
43    if os.sep == '\\':
44        runner += '.bat'
45    execute_tests(runner, args)
46    mongo_db.shutdown()
47    return process_output()
50def execute_tests(runner, args):
51    if not os.path.exists(env.RESULTS_DIR):
52        os.mkdir(env.RESULTS_DIR)
53    command = [runner] + [arg % ARG_VALUES for arg in ROBOT_ARGS] + args + [env.ACCEPTANCE_TEST_DIR]
54    print ''
55    print 'Starting test execution with command:\n' + ' '.join(command)
56    syslog = os.path.join(env.RESULTS_DIR, 'syslog.txt')
57    call(command, shell=os.sep == '\\', env=dict(os.environ, ROBOT_SYSLOG_FILE=syslog))
60def process_output():
61    print
62    if _has_robot_27():
63        call(['python', os.path.join(env.RESOURCES_DIR, ''),
64             os.path.join(env.RESULTS_DIR, 'output.xml')])
65    rebot = 'rebot' if os.sep == '/' else 'rebot.bat'
66    rebot_cmd = [rebot] + [arg % ARG_VALUES for arg in REBOT_ARGS] + \
67                [os.path.join(ARG_VALUES['outdir'], 'output.xml')]
68    rc = call(rebot_cmd, env=os.environ)
69    if rc == 0:
70        print 'All critical tests passed'
71    else:
72        print '%d critical test%s failed' % (rc, 's' if rc != 1 else '')
73    return rc
76def _has_robot_27():
77    try:
78        from robot.result import ExecutionResult
79    except:
80        return False
81    return True
84def _exit(rc):
85    sys.exit(rc)
88def _help():
89    print 'Usage:  python python|jython [options]'
90    print
91    print 'See README.txt for details.'
92    return 255
95if __name__ == '__main__':
96    if not len(sys.argv) > 1:
97        _exit(_help())
98    interpreter = sys.argv[1]
99    args = sys.argv[2:]
100    _exit(acceptance_tests(interpreter, args))
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Robotframework on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)