Robot Framework
run.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 # Copyright 2008-2015 Nokia Networks
4 # Copyright 2016- Robot Framework Foundation
5 #
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
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
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.
17 
18 
32 
33 import sys
34 
35 # Allows running as a script. __name__ check needed with multiprocessing:
36 # https://github.com/robotframework/robotframework/issues/1137
37 if 'robot' not in sys.modules and __name__ == '__main__':
38  import pythonpathsetter
39 
40 from robot.conf import RobotSettings
41 from robot.model import ModelModifier
42 from robot.output import LOGGER, pyloggingconf
43 from robot.reporting import ResultWriter
44 from robot.running.builder import TestSuiteBuilder
45 from robot.utils import Application, text
46 
47 
48 USAGE = """Robot Framework -- A generic automation framework
49 
50 Version: <VERSION>
51 
52 Usage: robot [options] paths
53  or: python -m robot [options] paths
54  or: python path/to/robot [options] paths
55 
56 Robot Framework is a generic open source automation framework for acceptance
57 testing, acceptance test-driven development (ATDD) and robotic process
58 automation (RPA). It has simple, easy-to-use syntax that utilizes the
59 keyword-driven automation approach. Keywords adding new capabilities are
60 implemented in libraries using Python. New higher level
61 keywords can also be created using Robot Framework's own syntax.
62 
63 The easiest way to execute Robot Framework is using the `robot` command created
64 as part of the normal installation. Alternatively it is possible to execute
65 the `robot` module directly like `python -m robot`, where `python` can be
66 replaced with any supported Python interpreter. Yet another alternative
67 is running the `robot` directory like `python path/to/robot`.
68 
69 Tests (or tasks in RPA terminology) are created in files typically having the
70 `*.robot` extension. Files automatically create test (or task) suites and
71 directories with these files create higher level suites. When Robot Framework
72 is executed, paths to these files or directories are given to it as arguments.
73 
74 By default Robot Framework creates an XML output file and a log and a report in
75 HTML format, but this can be configured using various options listed below.
76 Outputs in HTML format are for human consumption and XML output for integration
77 with other systems. XML outputs can also be combined and otherwise further
78 post-processed with the Rebot tool that is an integral part of Robot Framework.
79 Run `rebot --help` for more information.
80 
81 Robot Framework is open source software released under Apache License 2.0.
82 For more information about the framework and the rich ecosystem around it
83 see http://robotframework.org/.
84 
85 Options
86 =======
87 
88  --rpa Turn on the generic automation mode. Mainly affects
89  terminology so that "test" is replaced with "task"
90  in logs and reports. By default the mode is got
91  from test/task header in data files.
92  --language lang * Activate localization. `lang` can be a name or a code
93  of a built-in language, or a path or a module name of
94  a custom language file.
95  -F --extension value Parse only files with this extension when executing
96  a directory. Has no effect when running individual
97  files or when using resource files. If more than one
98  extension is needed, separate them with a colon.
99  Examples: `--extension txt`, `--extension robot:txt`
100  Only `*.robot` files are parsed by default.
101  -N --name name Set the name of the top level suite. By default the
102  name is created based on the executed file or
103  directory.
104  -D --doc documentation Set the documentation of the top level suite.
105  Simple formatting is supported (e.g. *bold*). If the
106  documentation contains spaces, it must be quoted.
107  If the value is path to an existing file, actual
108  documentation is read from that file.
109  Examples: --doc "Very *good* example"
110  --doc doc_from_file.txt
111  -M --metadata name:value * Set metadata of the top level suite. Value can
112  contain formatting and be read from a file similarly
113  as --doc. Example: --metadata Version:1.2
114  -G --settag tag * Sets given tag(s) to all executed tests.
115  -t --test name * Select tests by name or by long name containing also
116  parent suite name like `Parent.Test`. Name is case
117  and space insensitive and it can also be a simple
118  pattern where `*` matches anything, `?` matches any
119  single character, and `[chars]` matches one character
120  in brackets.
121  --task name * Alias to --test. Especially applicable with --rpa.
122  -s --suite name * Select suites by name. When this option is used with
123  --test, --include or --exclude, only tests in
124  matching suites and also matching other filtering
125  criteria are selected. Name can be a simple pattern
126  similarly as with --test and it can contain parent
127  name separated with a dot. For example, `-s X.Y`
128  selects suite `Y` only if its parent is `X`.
129  -i --include tag * Select tests by tag. Similarly as name with --test,
130  tag is case and space insensitive and it is possible
131  to use patterns with `*`, `?` and `[]` as wildcards.
132  Tags and patterns can also be combined together with
133  `AND`, `OR`, and `NOT` operators.
134  Examples: --include foo --include bar*
135  --include fooANDbar*
136  -e --exclude tag * Select test cases not to run by tag. These tests are
137  not run even if included with --include. Tags are
138  matched using same rules as with --include.
139  -R --rerunfailed output Select failed tests from an earlier output file to be
140  re-executed. Equivalent to selecting same tests
141  individually using --test.
142  -S --rerunfailedsuites output Select failed suites from an earlier output
143  file to be re-executed.
144  --runemptysuite Executes suite even if it contains no tests. Useful
145  e.g. with --include/--exclude when it is not an error
146  that no test matches the condition.
147  --skip tag * Tests having given tag will be skipped. Tag can be
148  a pattern.
149  --skiponfailure tag * Tests having given tag will be skipped if they fail.
150  Tag can be a pattern
151  -v --variable name:value * Set variables in the test data. Only scalar
152  variables with string value are supported and name is
153  given without `${}`. See --variablefile for a more
154  powerful variable setting mechanism.
155  Examples:
156  --variable str:Hello => ${str} = `Hello`
157  -v hi:Hi_World -E space:_ => ${hi} = `Hi World`
158  -v x: -v y:42 => ${x} = ``, ${y} = `42`
159  -V --variablefile path * Python or YAML file file to read variables from.
160  Possible arguments to the variable file can be given
161  after the path using colon or semicolon as separator.
162  Examples: --variablefile path/vars.yaml
163  --variablefile environment.py:testing
164  -d --outputdir dir Where to create output files. The default is the
165  directory where tests are run from and the given path
166  is considered relative to that unless it is absolute.
167  -o --output file XML output file. Given path, similarly as paths given
168  to --log, --report, --xunit, and --debugfile, is
169  relative to --outputdir unless given as an absolute
170  path. Other output files are created based on XML
171  output files after the test execution and XML outputs
172  can also be further processed with Rebot tool. Can be
173  disabled by giving a special value `NONE`.
174  Default: output.xml
175  -l --log file HTML log file. Can be disabled by giving a special
176  value `NONE`. Default: log.html
177  Examples: `--log mylog.html`, `-l NONE`
178  -r --report file HTML report file. Can be disabled with `NONE`
179  similarly as --log. Default: report.html
180  -x --xunit file xUnit compatible result file. Not created unless this
181  option is specified.
182  -b --debugfile file Debug file written during execution. Not created
183  unless this option is specified.
184  -T --timestampoutputs When this option is used, timestamp in a format
185  `YYYYMMDD-hhmmss` is added to all generated output
186  files between their basename and extension. For
187  example `-T -o output.xml -r report.html -l none`
188  creates files like `output-20070503-154410.xml` and
189  `report-20070503-154410.html`.
190  --splitlog Split the log file into smaller pieces that open in
191  browsers transparently.
192  --logtitle title Title for the generated log file. The default title
193  is `<SuiteName> Log`.
194  --reporttitle title Title for the generated report file. The default
195  title is `<SuiteName> Report`.
196  --reportbackground colors Background colors to use in the report file.
197  Given in format `passed:failed:skipped` where the
198  `:skipped` part can be omitted. Both color names and
199  codes work.
200  Examples: --reportbackground green:red:yellow
201  --reportbackground #00E:#E00
202  --maxerrorlines lines Maximum number of error message lines to show in
203  report when tests fail. Default is 40, minimum is 10
204  and `NONE` can be used to show the full message.
205  --maxassignlength characters Maximum number of characters to show in log
206  when variables are assigned. Zero or negative values
207  can be used to avoid showing assigned values at all.
208  Default is 200.
209  -L --loglevel level Threshold level for logging. Available levels: TRACE,
210  DEBUG, INFO (default), WARN, NONE (no logging). Use
211  syntax `LOGLEVEL:DEFAULT` to define the default
212  visible log level in log files.
213  Examples: --loglevel DEBUG
214  --loglevel DEBUG:INFO
215  --suitestatlevel level How many levels to show in `Statistics by Suite`
216  in log and report. By default all suite levels are
217  shown. Example: --suitestatlevel 3
218  --tagstatinclude tag * Include only matching tags in `Statistics by Tag`
219  in log and report. By default all tags are shown.
220  Given tag can be a pattern like with --include.
221  --tagstatexclude tag * Exclude matching tags from `Statistics by Tag`.
222  This option can be used with --tagstatinclude
223  similarly as --exclude is used with --include.
224  --tagstatcombine tags:name * Create combined statistics based on tags.
225  These statistics are added into `Statistics by Tag`.
226  If the optional `name` is not given, name of the
227  combined tag is got from the specified tags. Tags are
228  matched using the same rules as with --include.
229  Examples: --tagstatcombine requirement-*
230  --tagstatcombine tag1ANDtag2:My_name
231  --tagdoc pattern:doc * Add documentation to tags matching the given
232  pattern. Documentation is shown in `Test Details` and
233  also as a tooltip in `Statistics by Tag`. Pattern can
234  use `*`, `?` and `[]` as wildcards like --test.
235  Documentation can contain formatting like --doc.
236  Examples: --tagdoc mytag:Example
237  --tagdoc "owner-*:Original author"
238  --tagstatlink pattern:link:title * Add external links into `Statistics by
239  Tag`. Pattern can use `*`, `?` and `[]` as wildcards
240  like --test. Characters matching to `*` and `?`
241  wildcards can be used in link and title with syntax
242  %N, where N is index of the match (starting from 1).
243  Examples: --tagstatlink mytag:http://my.domain:Title
244  --tagstatlink "bug-*:http://url/id=%1:Issue Tracker"
245  --expandkeywords name:<pattern>|tag:<pattern> *
246  Matching keywords will be automatically expanded in
247  the log file. Matching against keyword name or tags
248  work using same rules as with --removekeywords.
249  Examples: --expandkeywords name:BuiltIn.Log
250  --expandkeywords tag:expand
251  --removekeywords all|passed|for|wuks|name:<pattern>|tag:<pattern> *
252  Remove keyword data from the generated log file.
253  Keywords containing warnings are not removed except
254  in the `all` mode.
255  all: remove data from all keywords
256  passed: remove data only from keywords in passed
257  test cases and suites
258  for: remove passed iterations from for loops
259  while: remove passed iterations from while loops
260  wuks: remove all but the last failing keyword
261  inside `BuiltIn.Wait Until Keyword Succeeds`
262  name:<pattern>: remove data from keywords that match
263  the given pattern. The pattern is matched
264  against the full name of the keyword (e.g.
265  'MyLib.Keyword', 'resource.Second Keyword'),
266  is case, space, and underscore insensitive,
267  and may contain `*`, `?` and `[]` wildcards.
268  Examples: --removekeywords name:Lib.HugeKw
269  --removekeywords name:myresource.*
270  tag:<pattern>: remove data from keywords that match
271  the given pattern. Tags are case and space
272  insensitive and patterns can contain `*`,
273  `?` and `[]` wildcards. Tags and patterns
274  can also be combined together with `AND`,
275  `OR`, and `NOT` operators.
276  Examples: --removekeywords foo
277  --removekeywords fooANDbar*
278  --flattenkeywords for|while|iteration|name:<pattern>|tag:<pattern> *
279  Flattens matching keywords in the generated log file.
280  Matching keywords get all log messages from their
281  child keywords and children are discarded otherwise.
282  for: flatten FOR loops fully
283  while: flatten WHILE loops fully
284  iteration: flatten FOR/WHILE loop iterations
285  foritem: deprecated alias for `iteration`
286  name:<pattern>: flatten matched keywords using same
287  matching rules as with
288  `--removekeywords name:<pattern>`
289  tag:<pattern>: flatten matched keywords using same
290  matching rules as with
291  `--removekeywords tag:<pattern>`
292  --listener class * A class for monitoring test execution. Gets
293  notifications e.g. when tests start and end.
294  Arguments to the listener class can be given after
295  the name using a colon or a semicolon as a separator.
296  Examples: --listener MyListenerClass
297  --listener path/to/Listener.py:arg1:arg2
298  --nostatusrc Sets the return code to zero regardless of failures
299  in test cases. Error codes are returned normally.
300  --dryrun Verifies test data and runs tests so that library
301  keywords are not executed.
302  -X --exitonfailure Stops test execution if any test fails.
303  --exitonerror Stops test execution if any error occurs when parsing
304  test data, importing libraries, and so on.
305  --skipteardownonexit Causes teardowns to be skipped if test execution is
306  stopped prematurely.
307  --randomize all|suites|tests|none Randomizes the test execution order.
308  all: randomizes both suites and tests
309  suites: randomizes suites
310  tests: randomizes tests
311  none: no randomization (default)
312  Use syntax `VALUE:SEED` to give a custom random seed.
313  The seed must be an integer.
314  Examples: --randomize all
315  --randomize tests:1234
316  --prerunmodifier class * Class to programmatically modify the suite
317  structure before execution.
318  --prerebotmodifier class * Class to programmatically modify the result
319  model before creating reports and logs.
320  --console type How to report execution on the console.
321  verbose: report every suite and test (default)
322  dotted: only show `.` for passed test, `s` for
323  skipped tests, and `F` for failed tests
324  quiet: no output except for errors and warnings
325  none: no output whatsoever
326  -. --dotted Shortcut for `--console dotted`.
327  --quiet Shortcut for `--console quiet`.
328  -W --consolewidth chars Width of the console output. Default is 78.
329  -C --consolecolors auto|on|ansi|off Use colors on console output or not.
330  auto: use colors when output not redirected (default)
331  on: always use colors
332  ansi: like `on` but use ANSI colors also on Windows
333  off: disable colors altogether
334  -K --consolemarkers auto|on|off Show markers on the console when top level
335  keywords in a test case end. Values have same
336  semantics as with --consolecolors.
337  -P --pythonpath path * Additional locations (directories, ZIPs) where to
338  search libraries and other extensions when they are
339  imported. Multiple paths can be given by separating
340  them with a colon (`:`) or by using this option
341  several times. Given path can also be a glob pattern
342  matching multiple paths.
343  Examples: --pythonpath libs/
344  --pythonpath /opt/libs:libraries.zip
345  -A --argumentfile path * Text file to read more arguments from. Use special
346  path `STDIN` to read contents from the standard input
347  stream. File can have both options and input files
348  or directories, one per line. Contents do not need to
349  be escaped but spaces in the beginning and end of
350  lines are removed. Empty lines and lines starting
351  with a hash character (#) are ignored.
352  Example file:
353  | --include regression
354  | --name Regression Tests
355  | # This is a comment line
356  | tests.robot
357  | path/to/test/directory/
358  Examples:
359  --argumentfile argfile.txt --argumentfile STDIN
360  -h -? --help Print usage instructions.
361  --version Print version information.
362 
363 Options that are marked with an asterisk (*) can be specified multiple times.
364 For example, `--test first --test third` selects test cases with name `first`
365 and `third`. If an option accepts a value but is not marked with an asterisk,
366 the last given value has precedence. For example, `--log A.html --log B.html`
367 creates log file `B.html`. Options accepting no values can be disabled by
368 using the same option again with `no` prefix added or dropped. The last option
369 has precedence regardless of how many times options are used. For example,
370 `--dryrun --dryrun --nodryrun --nostatusrc --statusrc` would not activate the
371 dry-run mode and would return a normal return code.
372 
373 Long option format is case-insensitive. For example, --SuiteStatLevel is
374 equivalent to but easier to read than --suitestatlevel. Long options can
375 also be shortened as long as they are unique. For example, `--logti Title`
376 works while `--lo log.html` does not because the former matches only --logtitle
377 but the latter matches --log, --loglevel and --logtitle.
378 
379 Environment Variables
380 =====================
381 
382 ROBOT_OPTIONS Space separated list of default options to be placed
383  in front of any explicit options on the command line.
384 ROBOT_SYSLOG_FILE Path to a file where Robot Framework writes internal
385  information about parsing test case files and running
386  tests. Can be useful when debugging problems. If not
387  set, or set to a special value `NONE`, writing to the
388  syslog file is disabled.
389 ROBOT_SYSLOG_LEVEL Log level to use when writing to the syslog file.
390  Available levels are the same as with --loglevel
391  command line option and the default is INFO.
392 ROBOT_INTERNAL_TRACES When set to any non-empty value, Robot Framework's
393  internal methods are included in error tracebacks.
394 
395 Examples
396 ========
397 
398 # Simple test run using `robot` command without options.
399 $ robot tests.robot
400 
401 # Using options.
402 $ robot --include smoke --name "Smoke Tests" path/to/tests.robot
403 
404 # Executing `robot` module using Python.
405 $ python -m robot path/to/tests
406 
407 # Executing multiple test case files and using case-insensitive long options.
408 $ robot --SuiteStatLevel 2 --Metadata Version:3 tests/*.robot more/tests.robot
409 
410 # Setting default options and syslog file before running tests.
411 $ export ROBOT_OPTIONS="--outputdir results --suitestatlevel 2"
412 $ export ROBOT_SYSLOG_FILE=/tmp/syslog.txt
413 $ robot tests.robot
414 """
415 
416 
417 class RobotFramework(Application):
418 
419  def __init__(self):
420  Application.__init__(self, USAGE, arg_limits=(1,), env_options='ROBOT_OPTIONS',
421  logger=LOGGER)
422 
423  def main(self, datasources, **options):
424  try:
425  settings = RobotSettings(options)
426  except:
427  LOGGER.register_console_logger(stdout=options.get('stdout'),
428  stderr=options.get('stderr'))
429  raise
430  LOGGER.register_console_logger(**settings.console_output_config)
431  LOGGER.info(f'Settings:\n{settings}')
432  if settings.pythonpath:
433  sys.path = settings.pythonpath + sys.path
434  builder = TestSuiteBuilder(settings.suite_names,
435  included_extensions=settings.extension,
436  rpa=settings.rpa,
437  lang=settings.languages,
438  allow_empty_suite=settings.run_empty_suite)
439  suite = builder.build(*datasources)
440  settings.rpa = suite.rpa
441  if settings.pre_run_modifiers:
442  suite.visit(ModelModifier(settings.pre_run_modifiers,
443  settings.run_empty_suite, LOGGER))
444  suite.configure(**settings.suite_config)
445  with pyloggingconf.robot_handler_enabled(settings.log_level):
446  old_max_error_lines = text.MAX_ERROR_LINES
447  old_max_assign_length = text.MAX_ASSIGN_LENGTH
448  text.MAX_ERROR_LINES = settings.max_error_lines
449  text.MAX_ASSIGN_LENGTH = settings.max_assign_length
450  try:
451  result = suite.run(settings)
452  finally:
453  text.MAX_ERROR_LINES = old_max_error_lines
454  text.MAX_ASSIGN_LENGTH = old_max_assign_length
455  LOGGER.info("Tests execution ended. Statistics:\n%s"
456  % result.suite.stat_message)
457  if settings.log or settings.report or settings.xunit:
458  writer = ResultWriter(settings.output if settings.log
459  else result)
460  writer.write_results(settings.get_rebot_settings())
461  return result.return_code
462 
463  def validate(self, options, arguments):
464  return self._filter_options_without_value_filter_options_without_value(options), arguments
465 
466  def _filter_options_without_value(self, options):
467  return dict((name, value) for name, value in options.items()
468  if value not in (None, []))
469 
470 
471 
498 def run_cli(arguments=None, exit=True):
499  if arguments is None:
500  arguments = sys.argv[1:]
501  return RobotFramework().execute_cli(arguments, exit=exit)
502 
503 
504 
557 def run(*tests, **options):
558  return RobotFramework().execute(*tests, **options)
559 
560 
561 if __name__ == '__main__':
562  run_cli(sys.argv[1:])
A class to create log, report, output XML and xUnit files.
Definition: resultwriter.py:40
def _filter_options_without_value(self, options)
Definition: run.py:466
def main(self, datasources, **options)
Definition: run.py:423
def __init__(self)
Definition: run.py:419
def validate(self, options, arguments)
Definition: run.py:463
def run_cli(arguments=None, exit=True)
Command line execution entry point for running tests.
Definition: run.py:498
def run(*tests, **options)
Programmatic entry point for running tests.
Definition: run.py:557