OperatingSystem - Documentation

Version: 2.1.2

Introduction

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).

Starting from Robot Framework 2.0.2, all keywords expecting paths as arguments accept a forward slash as a path separator regardless the operating system. This only works if an argument is only a path, not if a path is part of an argument, like it often is with Run and Start Process keywords. In these cases, and with earlier versions, built-in variable ${/} can be used to keep the test data platform independent.

Example usage:

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

Shortcuts

Keywords

Keyword Arguments Documentation
Append To File 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.
Copy Directory 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.
Copy File 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.
Count Directories In Directory path, pattern=None, pattern_type=DEPRECATED Returns the number of subdirectories in the given directory.

The arguments pattern and pattern_type have 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 Files In Directory path, pattern=None, pattern_type=DEPRECATED Returns the number of files in the given directory.

The arguments pattern and pattern_type have 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 Items In Directory path, pattern=None, pattern_type=DEPRECATED Returns the number of all items in the given directory.

The arguments pattern and pattern_type have 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.
Create Directory 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.
Create File path, content=, mode=DEPRECATED Creates a file to the given path with the given content.

Old mode argument is deprecated in Robot Framework 2.1 and will be replaced with encoding in 2.2. Use new Append To File keyword if there is a need to append to a file, and use File Should Not Exist if you want to avoid overwriting existing files.

In Robot Framework 2.1 this keyword always uses UTF-8 encoding and Create File With Encoding can be used if other encodings are needed. Earlier versions used more limiting ASCII encoding.

If the directory where to create file does not exist it, and possible intermediate missing directories, are created.
Create File With Encoding path, content=, encoding=UTF-8 Writes the given contend to the specified file.

Use Append To File if you want to append to an existing file.

If the directory where to create file does not exist it, and possible intermediate missing directories, are created.

This is a temporary keyword added in Robot Framework 2.1 and will be deprecated in 2.2 when Create File gets encoding argument.
Directory Should Be Empty path, msg=None Fails unless the specified directory is empty.

The default error message can be overridden with the msg argument.
Directory Should Exist 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 pattern similarly as with File Should Exist keyword. The default error message can be overridden with the msg argument.
Directory Should Not Be Empty path, msg=None Fails if the specified directory is empty.

The default error message can be overridden with the msg argument.
Directory Should Not Exist 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 pattern similarly as with File Should Exist keyword. The default error message can be overridden with the msg argument.
Empty Directory path Deletes all the content (incl. subdirectories) from the given directory.
Environment Variable Should Be Set name, msg=None Fails if the specified environment variable is not set.

The default error message can be overridden with the msg argument.
Environment Variable Should Not Be Set name, msg=None Fails if the specified environment variable is set.

The default error message can be overridden with the msg argument.
File Should Be Empty path, msg=None Fails unless the specified file is empty.

The default error message can be overridden with the msg argument.
File Should Exist 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 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

Pattern matching is implemented with the Python 'fnmatch' module. For more information, see http://docs.python.org/lib/module-fnmatch.html

The default error message can be overridden with the msg argument.
File Should Not Be Empty path, msg=None Fails if the specified directory is empty.

The default error message can be overridden with the msg argument.
File Should Not Exist 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 pattern similarly as with File Should Exist keyword. The default error message can be overridden with the msg argument.
Get Environment Variable 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}.
Get File path, encoding=UTF-8 Returns the contents of a specified file.

This keyword reads the specified file and returns the contents. 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.
Get File Size path Returns and logs file size as an integer in bytes
Get Modified Time 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']
Grep File path, pattern, pattern_type=DEPRECATED, 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 mached lines is automatically logged. Possible trailing newline is never returned.

Starting from Robot Framework 2.1 the pattern is, by default, considered to be a similar glob pattern as with File Should Exist keyword. A line matches if it contains the pattern anywhere in it i.e. it does not need to match the pattern fully. Using other pattern types has been deprecated and that functionality will be removed in 2.2 version.

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.

Examples:
${errors} = Grep File /var/log/myapp.log ERROR
${ret} = Grep File ${CURDIR}/file.txt [Ww]ildc??d ex*ple
Join Path 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'
Join Paths 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']
List Directories In Directory path, pattern=None, pattern_type=DEPRECATED, absolute=False A wrapper for List Directory that returns only directories.
List Directory path, pattern=None, pattern_type=DEPRECATED, absolute=False Returns items from 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. By default pattern is considered to be a simple glob pattern where '*' and '?' can be used as wildcards (e.g. '*.txt' or 'file.???'). Using other pattern types has been deprecated in Robot Framework 2.1.

Examples (using also other List Directory variants):
@{items} = List Directory ${TEMPDIR}
@{files} = List Files In Directory /tmmp *.txt absolute
${count} = Count Files In Directory ${CURDIR} ???
List Files In Directory path, pattern=None, pattern_type=DEPRECATED, absolute=False A wrapper for List Directory that returns only files.
Log File 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.
Move Directory 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.
Move File 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.
Normalize Path 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'
Read Process Output mode=DEPRECATED Waits for the process to finish and returns its output.

In Robot Framework versions prior to 2.0.2 it was possible to read either the standard output, standard error or both. As mentioned in the documentation of Start Process, the standard error is nowadays automatically redirected to the standard output. This keyword thus always returns all the output and mode argument is ignored.  As explained in Run keyword, it is still possible to redirect the standard error, or output, using e.g. '2>stderr.txt' after 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.
Remove Directory 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.
Remove Environment Variable name Deletes the specified environment variable.

Does nothing if the environment variable is not set.
Remove File 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 pattern similarly as with File Should Exist keyword. If the path is a pattern, all files matching it are removed.
Remove Files *paths Uses Remove File to remove multiple files one-by-one.

Example:
Remove Files ${TEMPDIR}${/}foo.txt ${TEMPDIR}${/}bar.txt ${TEMPDIR}${/}zap.txt
Run command, return_mode=DEPRECATED 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 return code of execution is needed, either Run And Return RC or Run And Return RC And Output can be used. return_mode argument for this keyword is deprecated and will be removed in Robot Framework 2.2 version.

Starting from Robot Framework 2.0.2, the standard error stream is automatically redirected to the standard output stream by adding '2>&1' after the executed command. The automatic redirection of the standard error 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 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.

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
Run And Return Rc command Runs the given command in the system and returns the returnn 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 comand.
Run And Return Rc And Output 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
Set Environment Variable name, value Sets an environment variable to a specified value.

Starting from Robot Framework 2.1.1, values are converted to strings automatically.
Set Modified Time 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 subtraced from NOW
Set Modified Time /path/file NOW + 1h 2min 3s # 1h 2min 3s added to NOW
Should Exist path, msg=None Fails unless the given path (file or directory) exists.

The path can be given as an exact path or as a pattern similarly as with File Should Exist keyword. The default error message can be overridden with the msg argument.
Should Not Exist path, msg=None Fails if the given path (file or directory) exists.

The path can be given as an exact path or as a pattern similarly as with File Should Exist keyword. The default error message can be overridden with the msg argument.
Split Extension 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. Starting from Robot Framework 2.0.2, 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} = ''
Split Path 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'
Start Process 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.

Starting from Robot Framework 2.0.2, 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
Stop All Processes 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.
Stop Process 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.
Switch Process 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
Touch 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.
Wait Until Created 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 pattern similarly as with File Should Exist keyword. If the path is a pattern, the keyword returns when an item matching to the pattern 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.
Wait Until Removed 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 pattern similarly as with File Should Exist keyword. 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.