Table of Contents 目录
Robot Framework is a Python-based, extensible keyword-driven automation
framework for acceptance testing, acceptance test driven development (ATDD),
behavior driven development (BDD) and robotic process automation (RPA). It
can be used in distributed, heterogeneous environments, where automation
requires using different technologies and interfaces.
Robot Framework是一个基于Python的、可扩展的关键字驱动的自动化框架,用于验收测试、验收测试驱动开发(ATDD)、行为驱动开发(BDD)和机器人流程自动化(RPA)。它可以用于分布式异构环境,其中自动化需要使用不同的技术和接口。
The framework has a rich ecosystem around it consisting of various generic
libraries and tools that are developed as separate projects. For more
information about Robot Framework and the ecosystem, see
http://robotframework.org.
该框架周围有一个丰富的生态系统,由作为单独项目开发的各种通用库和工具组成。有关机器人框架和生态系统的更多信息,请参阅http://robotframework.org。
Robot Framework is open source software released under the Apache License
2.0. Its development is sponsored by the Robot Framework Foundation.
Robot Framework是在Apache License 2.0下发布的开源软件。它的开发由机器人框架基金会赞助。
Note 注意
The official RPA support was added in Robot Framework 3.1.
This User Guide still talks mainly about creating tests, test data,
and test libraries, but same concepts apply also when creating
tasks.
RPA支持是在Robot Framework 3.1中添加的。本用户指南仍然主要讨论创建测试、测试数据和测试库,但在创建任务时也适用相同的概念。
Robot Framework is a generic, application and technology independent
framework. It has a highly modular architecture illustrated in the
diagram below.
Robot Framework是一个通用的、独立于应用和技术的框架。它具有高度模块化的架构,如下图所示。
The test data is in simple, easy-to-edit tabular format. When
Robot Framework is started, it processes the data, executes test
cases and generates logs and reports. The core framework does not
know anything about the target under test, and the interaction with it
is handled by libraries. Libraries can either use application
interfaces directly or use lower level test tools as drivers.
测试数据采用简单、易于编辑的表格格式。当Robot Framework启动时,它处理数据,执行测试用例并生成日志和报告。核心框架不知道任何关于被测目标的信息,与它的交互由库处理。库可以直接使用应用程序接口,也可以使用低级测试工具作为驱动程序。
Following screenshots show examples of the test data and created
reports and logs.
以下屏幕截图显示了测试数据以及创建的报告和日志的示例。
The number one place to find more information about Robot Framework
and the rich ecosystem around it is http://robotframework.org.
Robot Framework itself is hosted on GitHub.
要了解有关Robot Framework及其丰富生态系统的更多信息,请访问http://robotframework.org。Robot Framework本身托管在GitHub上。
There are several Robot Framework mailing lists where to ask and
search for more information. The mailing list archives are open for
everyone (including the search engines) and everyone can also join
these lists freely. Only list members can send mails, though, and to
prevent spam new users are moderated which means that it might take a
little time before your first message goes through. Do not be afraid
to send question to mailing lists but remember How To Ask Questions
The Smart Way.
有几个Robot Framework邮件列表,可以在其中询问和搜索更多信息。邮件列表档案对所有人开放(包括搜索引擎),每个人都可以自由加入这些列表。只有列表成员可以发送邮件,但是,为了防止垃圾邮件,新用户会受到审核,这意味着在您的第一封邮件通过之前可能需要一点时间。不要害怕把问题发送到邮件列表,但要记住如何以聪明的方式提问。
Robot Framework is open source software provided under the Apache License
2.0. Robot Framework documentation such as this User Guide use the
Creative Commons Attribution 3.0 Unported license. Most libraries and tools
in the larger ecosystem around the framework are also open source, but they
may use different licenses.
Robot Framework是Apache License 2.0下提供的开源软件。本用户指南等机器人框架文档使用知识共享归因3.0未移植许可证。围绕框架的更大生态系统中的大多数库和工具也是开源的,但它们可能使用不同的许可证。
The full Robot Framework copyright notice is included below:
完整的Robot Framework版权声明如下:
Copyright 2008-2015 Nokia Networks Copyright 2016- Robot Framework Foundation 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.
These instructions cover installing Robot Framework
and its preconditions on different operating systems. If you already have
Python installed, you can install Robot Framework using
the standard package manager pip:
这些说明涵盖了在不同操作系统上安装Robot Framework及其先决条件。如果你已经安装了Python,你可以使用标准的包管理器pip安装Robot Framework:
pip install robotframework
Robot Framework is implemented using Python, and a precondition to install it
is having Python or its alternative implementation PyPy
installed. Another recommended precondition is having the pip package manager
available.
Robot Framework是使用Python实现的,安装它的先决条件是安装Python或其替代实现PyPy。另一个推荐的先决条件是有pip包管理器可用。
Robot Framework requires Python 3.8 or newer. The latest version that supports
Python 3.6 and 3.7 is Robot Framework 6.1.1. If you need to use Python 2,
Jython or IronPython,
you can use Robot Framework 4.1.3.
Robot Framework需要Python 3.8或更高版本。支持Python 3.6和3.7的最新版本是Robot Framework 6.1.1。如果你需要使用Python 2、Jython或IronPython,你可以使用Robot Framework 4.1.3。
On Linux you should have suitable Python installation with pip available
by default. If not, you need to consult your distributions documentation
to learn how to install them. This is also true if you want to use some other
Python version than the one provided by your distribution by default.
在Linux上,你应该有合适的Python安装,默认情况下pip可用。如果没有,您需要查阅发行版文档以了解如何安装它们。如果您想使用其他Python版本而不是您的发行版默认提供的版本,也是如此。
To check what Python version you have installed, you can run python --version
command in a terminal:
要检查您安装的Python版本,您可以在终端中运行python --version
命令:
$ python --version Python 3.10.13
Notice that if your distribution provides also older Python 2, running python
may use that. To use Python 3, you can use python3
command or even more version
specific command like python3.8
. You need to use these version specific variants
also if you have multiple Python 3 versions installed and need to pinpoint which
one to use:
请注意,如果您的发行版还提供较旧的Python 2,则运行python
可能会使用它。要使用Python 3,您可以使用python3
命令或更多版本特定的命令,如python3.8
。如果您安装了多个Python 3版本,并且需要确定使用哪个版本,则也需要使用这些特定于版本的变体:用途:
$ python3.11 --version Python 3.11.7 $ python3.12 --version Python 3.12.1
Installing Robot Framework directly under the system provided Python
has a risk that possible problems can affect the whole Python installation
used also by the operating system itself. Nowadays
Linux distributions typically use user installs by default to avoid such
problems, but users can also themselves decide to use virtual environments.
直接在提供Python的系统下安装Robot Framework存在风险,可能的问题可能会影响操作系统本身使用的整个Python安装。如今,Linux发行版通常默认使用用户安装来避免此类问题,但用户也可以自己决定使用虚拟环境。
On Windows Python is not available by default, but it is easy to install.
The recommended way to install it is using the official Windows installers available
at http://python.org. For other alternatives, such as installing from the
Microsoft Store, see the official Python documentation.
在Windows上,Python默认不可用,但它很容易安装。推荐的安装方法是使用官方的Windows安装程序,网址是http://python.org。有关其他替代方案,如从Microsoft Store安装,请参阅官方Python文档。
When installing Python on Windows, it is recommended to add Python to PATH
to make it and tools like pip and Robot Framework easier to execute from
the command line. When using the official installer, you just need
to select the Add Python 3.x to PATH
checkbox on the first dialog.
在Windows上安装Python时,建议将Python添加到PATH中,以使其以及pip和Robot Framework等工具更容易从命令行执行。当使用官方安装程序时,你只需要在第一个对话框中选择Add Python 3.x to PATH
复选框。
To make sure Python installation has been successful and Python has been
added to PATH
, you can open the command prompt and execute python --version
:
要确保Python安装成功,并且Python已添加到PATH
中,您可以打开命令提示符并执行python --version
:
C:\>python --version Python 3.10.9
If you install multiple Python versions on Windows, the version that is used
when you execute python
is the one first in PATH
. If you need to use others,
the easiest way is using the py launcher:
如果你在Windows上安装了多个Python版本,那么当你执行Python
时,使用的版本是PATH
中的第一个版本。如果你需要使用其他的,最简单的方法是使用py启动器:
C:\>py --version Python 3.10.9 C:\>py -3.12 --version Python 3.12.1
MacOS does not provide Python 3 compatible Python version by default, so it
needs to be installed separately. The recommended approach is using the official
macOS installers available at http://python.org. If you are using a package
manager like Homebrew, installing Python via it is
possible as well.
MacOS默认情况下不提供Python 3兼容的Python版本,因此需要单独安装。推荐的方法是使用官方macOS安装程序,可从http://python.org获得。如果你使用的是像Homebrew这样的包管理器,也可以通过它安装Python。
You can validate Python installation on macOS using python --version
like on
other operating systems.
您可以在macOS上使用python --版本验证Python安装,就
像在其他操作系统上一样。
PyPy is an alternative Python implementation. Its main advantage over the
standard Python implementation is that it can be faster and use less memory,
but this depends on the context where and how it is used. If execution speed
is important, at least testing PyPy is probably a good idea.
PyPy是一个替代的Python实现。与标准Python实现相比,它的主要优点是速度更快,占用的内存更少,但这取决于使用它的上下文以及使用方式。如果执行速度很重要,至少测试PyPy可能是个好主意。
Installing PyPy is a straightforward procedure and you can find both installers
and installation instructions at http://pypy.org. To validate that PyPy installation
was successful, run pypy --version
or pypy3 --version
.
安装PyPy是一个简单的过程,您可以在http://pypy.org上找到安装程序和安装说明。要验证PyPy安装是否成功,请运行pypy --version
或pypy 3--version
。
Note 注意
Using Robot Framework with PyPy is officially supported only on Linux.
在PyPy中使用Robot Framework仅在Linux上得到官方支持。
PATH
PATH
The PATH environment variable lists directories where commands executed in
a system are searched from. To make using Python, pip and Robot Framework easier
from the command line, it is recommended to add the Python installation directory
as well as the directory where commands like pip
and robot
are installed
into PATH
.
PATH环境变量列出了在系统中执行的命令的搜索目录。为了使从命令行使用Python,pip和Robot Framework更容易,建议将Python安装目录以及pip
和robot
等命令的安装目录添加到PATH
中。
When using Python on Linux or macOS, Python and tools installed with it should be
automatically in PATH
. If you nevertheless need to update PATH
, you
typically need to edit some system wide or user specific configuration file.
Which file to edit and how depends on the operating system and you need to
consult its documentation for more details.
在Linux或macOS上使用Python时,Python和随其安装的工具应自动位于PATH
中。如果您仍然需要更新PATH
,您通常需要编辑一些系统范围或用户特定的配置文件。编辑哪个文件以及如何编辑取决于操作系统,您需要查阅其文档以了解更多详细信息。
On Windows the easiest way to make sure PATH
is configured correctly is
setting the Add Python 3.x to PATH
checkbox when running the installer.
To manually modify PATH
on Windows, follow these steps:
在Windows上,确保PATH
配置正确的最简单方法是在运行安装程序时设置Add Python 3.x to PATH
复选框。要在Windows上手动修改PATH
,请执行以下步骤:
Environment Variables
under Settings
. There are variables affecting
the whole system and variables affecting only the current user. Modifying
the former will require admin rights, but modifying the latter is typically
enough.设置
下找到环境变量
。有影响整个系统的变量,也有只影响当前用户的变量。修改前者需要管理员权限,但修改后者通常就足够了。PATH
(often written like Path
) and click Edit
. If you are
editing user variables and PATH
does not exist, click New
instead.PATH
(通常写为Path
),然后单击Edit
。如果正在编辑用户变量,但PATH
不存在,请单击“新建
”。PATH
.PATH
。Ok
to save the changes.OK
”退出对话框以保存更改。These instructions cover installing Robot Framework using pip, the standard
Python package manager. If you are using some other package manager like
Conda, you can use it instead but need to study its
documentation for instructions.
这些说明涵盖了使用标准Python包管理器pip安装Robot Framework。如果你正在使用其他的包管理器,比如Conda,你可以使用它,但是需要学习它的文档来获得说明。
When installing Python, you typically get pip installed automatically. If
that is not the case, you need to check the documentation of that Python
installation for instructions how to install it separately.
安装Python时,通常会自动安装pip。如果不是这种情况,您需要查看Python安装的文档,以了解如何单独安装它。
pip
commandpip
命令Typically you use pip by running the pip
command, but on Linux you may need
to use pip3
or even more Python version specific variant like pip3.8
instead. When running pip
or any of its variants, the pip version that is
found first in PATH will be used. If you have multiple Python versions
installed, you may need to pinpoint which exact version you want to use.
This is typically easiest done by running python -m pip
and substituting
python
with the Python version you want to use.
通常,您可以通过运行pip
命令来使用pip,但在Linux上,您可能需要使用pip 3
或更多Python版本特定的变体,如pip3.8
。当运行pip
或其任何变体时,将使用在PATH中首先找到的pip版本。如果您安装了多个Python版本,则可能需要确定要使用的确切版本。这通常是最简单的,通过运行python -m pip
并将python
替换为您想要使用的Python版本。
To make sure you have pip available, you can run pip --version
or equivalent.
为了确保pip可用,您可以运行pip --版本
或等效版本。
Examples on Linux: Linux上的示例:
$ pip --version pip 23.2.1 from ... (python 3.10) $ python3.12 -m pip --version pip 23.3.1 from ... (python 3.12)
Examples on Windows: Windows上的示例:
C:\> pip --version pip 23.2.1 from ... (python 3.10) C:\> py -m 3.12 -m pip --version pip 23.3.2 from ... (python 3.12)
In the subsequent sections pip is always run using the pip
command. You may
need to use some of the other approaches explained above in your environment.
在后续章节中,pip始终使用pip
命令运行。您可能需要在您的环境中使用上面解释的其他一些方法。
The easiest way to use pip is by letting it find and download packages it
installs from the Python Package Index (PyPI), but it can also install
packages downloaded from the PyPI separately. The most common usages are
shown below and pip documentation has more information and examples.
使用pip最简单的方法是让它从Python包索引(PyPI)中找到并下载它安装的包,但它也可以单独安装从PyPI下载的包。最常见的用法如下所示,pip文档有更多的信息和示例。
# Install the latest version (does not upgrade) pip install robotframework # Upgrade to the latest stable version pip install --upgrade robotframework # Upgrade to the latest version even if it is a pre-release pip install --upgrade --pre robotframework # Install a specific version pip install robotframework==7.0 # Install separately downloaded package (no network connection needed) pip install robotframework-7.0-py3-none-any.whl # Install latest (possibly unreleased) code directly from GitHub pip install https://github.com/robotframework/robotframework/archive/master.zip # Uninstall pip uninstall robotframework
Another installation alternative is getting Robot Framework source code
and installing it using the provided setup.py
script. This approach is
recommended only if you do not have pip available for some reason.
另一种安装方法是获取Robot Framework源代码,并使用提供的setup.py
脚本安装它。只有当您由于某种原因没有pip可用时,才推荐使用此方法。
You can get the source code by downloading a source distribution as a zip
package from PyPI and extracting it. An alternative is cloning the GitHub
repository and checking out the needed release tag.
你可以通过从PyPI下载一个zip包的源代码发行版并解压缩它来获得源代码。另一种方法是克隆GitHub仓库并检查所需的release标签。
Once you have the source code, you can install it with the following command:
一旦你有了源代码,你可以用下面的命令安装它:
python setup.py install
The setup.py
script accepts several arguments allowing, for example,
installation into a non-default location that does not require administrative
rights. It is also used for creating different distribution packages. Run
python setup.py --help
for more details.setup.py
脚本接受多个参数,例如,允许安装到不需要管理权限的非默认位置。它还用于创建不同的分发包。运行python setup.py--help
获取更多细节。
To make sure that the correct Robot Framework version has been installed, run
the following command:
要确保已安装正确的Robot Framework版本,请运行以下命令:
$ robot --version Robot Framework 7.0 (Python 3.10.3 on linux)
If running these commands fails with a message saying that the command is
not found or recognized, a good first step is double-checking the PATH
configuration.
如果运行这些命令失败,并显示一条消息说找不到或无法识别该命令,那么最好的第一步是仔细检查PATH配置。
If you have installed Robot Framework under multiple Python versions,
running robot
will execute the one first in PATH. To select explicitly,
you can run python -m robot
and substitute python
with the right Python
version.
如果你已经安装了多个Python版本的Robot Framework,运行robot
将执行PATH中的第一个版本。要显式地选择,可以运行python -m robot
并将python
替换为正确的Python版本。
$ python3.12 -m robot --version Robot Framework 7.0 (Python 3.12.1 on linux) C:\>py -3.11 -m robot --version Robot Framework 7.0 (Python 3.11.7 on win32)
Python virtual environments allow Python packages to be installed in
an isolated location for a particular system or application, rather than
installing all packages into the same global location. They have
two main use cases:
Python虚拟环境允许将Python包安装在特定系统或应用程序的隔离位置,而不是将所有包安装到同一个全局位置。它们有两个主要用例:
There are several demo projects that introduce Robot Framework and help getting
started with it.
有几个演示项目介绍了Robot Framework,并帮助您开始使用它。
This section covers Robot Framework's overall test data syntax. The following
sections will explain how to actually create test cases, test suites and so on.
Although this section mostly uses term test, the same rules apply also
when creating tasks.
本节介绍Robot Framework的整体测试数据语法。下面的部分将解释如何实际创建测试用例,测试套件等等。虽然这一部分主要使用术语测试,但在创建任务时也适用相同的规则。
The hierarchical structure for arranging test cases is built as follows:
用于安排测试用例的层次结构构建如下:
In addition to this, there are:
除此之外,还有:
Test case files, test suite initialization files and resource files are
all created using Robot Framework test data syntax. Test libraries and
variable files are created using "real" programming languages, most
often Python.
测试用例文件、测试套件初始化文件和资源文件都使用Robot Framework测试数据语法创建。测试库和变量文件是使用“真实的”编程语言创建的,最常见的是Python。
Robot Framework data is defined in different sections, often also
called tables, listed below:
Robot Framework数据定义在不同的部分中,通常也称为表,如下所示:
Section 部分 | Used for 用于 |
---|---|
Settings 设定值 | |
Variables 变量 | Defining variables that can be used
elsewhere in the test data. 定义可以在测试数据的其他地方使用的变量。 |
Test Cases 测试案例 | Creating test cases from available
keywords. 从可用的关键字创建测试用例。 |
Tasks 任务 | Creating tasks using available
keywords. Single file can only contain
either tests or tasks. 使用可用关键字创建任务。单个文件只能包含测试或任务。 |
Keywords 关键词 | Creating user keywords from existing
lower-level keywords 从现有的较低级别关键字创建用户关键字 |
Comments 评论 | Additional comments or data. Ignored by
Robot Framework. 其他评论或数据。被Robot Framework忽略。 |
Different sections are recognized by their header row. The recommended
header format is *** Settings ***
, but the header is case-insensitive,
surrounding spaces are optional, and the number of asterisk characters can
vary as long as there is at least one asterisk in the beginning. For example,
also *settings
would be recognized as a section header.
不同的节通过其标题行识别。推荐的标题格式为 * Settings *,
但标题不区分大小写,周围的空格是可选的,星号字符的数量可以变化,只要开头至少有一个星号。例如,* 设置也
将被识别为节标题。
Robot Framework supports also singular headers like *** Setting ***,
but that
support was deprecated in Robot Framework 6.0. There is a visible deprecation
warning starting from Robot Framework 7.0 and singular headers will eventually
not be supported at all.
Robot Framework还支持单个标题,如 * 设置 *,
但该支持在Robot Framework 6.0中被弃用。从Robot Framework 7.0开始有一个可见的弃用警告,并且最终将完全不支持单数标题。
The header row can contain also other data than the actual section header.
The extra data must be separated from the section header using the data
format dependent separator, typically two or more spaces. These extra headers
are ignored at parsing time, but they can be used for documenting
purposes. This is especially useful when creating test cases using the
data-driven style.
标题行还可以包含实际节标题以外的其他数据。额外的数据必须使用数据格式相关的分隔符(通常为两个或多个空格)与节标题分隔开。这些额外的标头在解析时会被忽略,但它们可以用于文档编制目的。这在使用数据驱动风格创建测试用例时特别有用。
Possible data before the first section is ignored.
忽略第一部分之前的可能数据。
Note 注意
Section headers can be localized. See the Translations appendix for
supported translations.
节标题可以本地化。有关支持的翻译,请参见翻译附录。
The most common approach to create Robot Framework data is using the
space separated format where pieces of the data, such as keywords
and their arguments, are separated from each others with two or more spaces.
An alternative is using the pipe separated format where the separator is
the pipe character surrounded with spaces (|).
创建Robot Framework数据的最常见方法是使用空格分隔格式,其中数据片段(如关键字及其参数)用两个或多个空格彼此分隔。另一种方法是使用管道分隔格式,其中分隔符是用空格包围的管道字符(|).
Suite files typically use the .robot extension, but what files are
parsed can be configured. Resource files can use the .robot
extension as well, but using the dedicated .resource extension is
recommended and may be mandated in the future. Files containing non-ASCII
characters must be saved using the UTF-8 encoding.
套件文件通常使用.robot扩展名,但可以配置解析哪些文件。资源文件也可以使用.robot扩展名,但建议使用专用的.resource扩展名,将来可能会强制使用。包含非ASCII字符的文件必须使用UTF-8编码保存。
Robot Framework supports also reStructuredText files so that normal
Robot Framework data is embedded into code blocks. Only files with
the .robot.rst extension are parsed by default. If you would
rather use just .rst or .rest extension, that needs to be
configured separately.
Robot Framework还支持reStructuredText文件,以便将正常Robot Framework数据嵌入到代码块中。默认情况下,仅解析扩展名为.robot.rst的文件。如果您只想使用.rst或.rest扩展名,则需要单独配置。
Robot Framework data can also be created in the JSON format that is targeted
more for tool developers than normal Robot Framework users. Only JSON files
with the custom .rbt extension are parsed by default.
Robot Framework数据也可以以JSON格式创建,该格式更多地针对工具开发人员而不是普通Robot Framework用户。默认情况下,仅解析具有自定义.rbt扩展名的JSON文件。
Earlier Robot Framework versions supported data also in HTML and TSV formats.
The TSV format still works if the data is compatible with the space separated
format, but the support for the HTML format has been removed altogether.
If you encounter such data files, you need to convert them to the plain text
format to be able to use them with Robot Framework 3.2 or newer. The easiest
way to do that is using the Tidy tool, but you must use the version included
with Robot Framework 3.1 because newer versions do not understand the HTML
format at all.
早期的Robot Framework版本也支持HTML和TSV格式的数据。如果数据与空格分隔格式兼容,TSV格式仍然有效,但对HTML格式的支持已完全删除。如果遇到此类数据文件,则需要将其转换为纯文本格式,以便能够在Robot Framework 3.2或更高版本中使用它们。最简单的方法是使用Tidy工具,但您必须使用Robot Framework 3.1中包含的版本,因为较新的版本根本无法理解HTML格式。
When Robot Framework parses data, it first splits the data to lines and then
lines to tokens such as keywords and arguments. When using the space
separated format, the separator between tokens is two or more spaces or
alternatively one or more tab characters. In addition to the normal ASCII
space, any Unicode character considered to be a space (e.g. no-break space)
works as a separator. The number of spaces used as separator can vary, as
long as there are at least two, making it possible to align the data nicely
in settings and elsewhere when it makes the data easier to understand.
当Robot Framework解析数据时,它首先将数据拆分为行,然后将行拆分为关键字和参数等标记。当使用空格分隔格式时,标记之间的分隔符是两个或多个空格,或者一个或多个制表符。除了正常的ASCII空格之外,任何被认为是空格的Unicode字符(例如,无中断空格)都可以用作分隔符。用作分隔符的空格数量可以变化,只要至少有两个,就可以在设置和其他地方很好地对齐数据,使数据更容易理解。
*** Settings ***
Documentation Example using the space separated format.
Library OperatingSystem
*** Variables ***
${MESSAGE} Hello, world!
*** Test Cases ***
My Test
[Documentation] Example test.
Log ${MESSAGE}
My Keyword ${CURDIR}
Another Test
Should Be Equal ${MESSAGE} Hello, world!
*** Keywords ***
My Keyword
[Arguments] ${path}
Directory Should Exist ${path}
Because tabs and consecutive spaces are considered separators, they must
be escaped if they are needed in keyword arguments or elsewhere
in the actual data. It is possible to use special escape syntax like
\t
for tab and \xA0
for no-break space as well as built-in variables
${SPACE}
and ${EMPTY}
. See the Escaping section for details.
由于制表符和连续空格被视为分隔符,因此如果关键字参数或实际数据中的其他地方需要它们,则必须对其进行转义。可以使用特殊的转义语法,如\t
表示制表符,\xA0
表示不间断空格,以及内置变量${SPACE}
和${EMPTY}
。详情请参见“逃逸”部分。
Tip 尖端
Although using two spaces as a separator is enough, it is recommended
to use four spaces to make the separator easier to recognize.
虽然使用两个空格作为分隔符就足够了,但建议使用四个空格,以使分隔符更容易识别。
Note 注意
Prior to Robot Framework 3.2, non-ASCII spaces used in the data
were converted to ASCII spaces during parsing. Nowadays all data
is preserved as-is.
在Robot Framework 3.2之前,数据中使用的非ASCII空格在解析期间被转换为ASCII空格。如今,所有数据都按原样保存。
The biggest problem of the space delimited format is that visually
separating keywords from arguments can be tricky. This is a problem
especially if keywords take a lot of arguments and/or arguments
contain spaces. In such cases the pipe delimited variant can
work better because it makes the separator more visible.
空格分隔格式的最大问题是,在视觉上将关键字与参数分开可能很棘手。这是一个问题,特别是如果关键字需要很多参数和/或参数包含空格。在这种情况下,管道分隔变量可以更好地工作,因为它使分隔符更加可见。
One file can contain both space separated and pipe separated lines.
Pipe separated lines are recognized by the mandatory leading pipe character,
but the pipe at the end of the line is optional. There must always be at
least one space or tab on both sides of the pipe except at the beginning and
at the end of the line. There is no need to align the pipes, but that often
makes the data easier to read.
一个文件可以同时包含空格分隔行和竖线分隔行。用竖线分隔的线由强制性的前导竖线字符识别,但行尾的竖线是可选的。管道的两侧必须始终至少有一个空格或制表符,但行的开头和结尾除外。不需要对齐管道,但这通常会使数据更容易读取。
| *** Settings *** |
| Documentation | Example using the pipe separated format.
| Library | OperatingSystem
| *** Variables *** |
| ${MESSAGE} | Hello, world!
| *** Test Cases *** | | |
| My Test | [Documentation] | Example test. |
| | Log | ${MESSAGE} |
| | My Keyword | ${CURDIR} |
| Another Test | Should Be Equal | ${MESSAGE} | Hello, world!
| *** Keywords *** | | |
| My Keyword | [Arguments] | ${path} |
| | Directory Should Exist | ${path} |
When using the pipe separated format, consecutive spaces or tabs inside
arguments do not need to be escaped. Similarly empty columns do not need
to be escaped except if they are at the end. Possible pipes surrounded by
spaces in the actual test data must be escaped with a backslash, though:
当使用管道分隔格式时,参数中的连续空格或制表符不需要转义。同样,空列也不需要转义,除非它们位于末尾。但是,在实际测试数据中,可能被空格包围的管道必须用反斜杠进行转义:
| *** Test Cases *** | | | |
| Escaping Pipe | ${file count} = | Execute Command | ls -1 *.txt \| wc -l |
| | Should Be Equal | ${file count} | 42 |
Note 注意
Preserving consecutive spaces and tabs in arguments is new
in Robot Framework 3.2. Prior to it non-ASCII spaces used in
the data were also converted to ASCII spaces.
在参数中保留连续的空格和制表符是Robot Framework 3.2中的新功能。在此之前,数据中使用的非ASCII空格也被转换为ASCII空格。
reStructuredText (reST) is an easy-to-read plain text markup syntax that
is commonly used for documentation of Python projects, including Python itself
as well as this User Guide. reST documents are most often compiled to HTML,
but also other output formats are supported. Using reST with Robot Framework
allows you to mix richly formatted documents and test data in a concise text
format that is easy to work with using simple text editors, diff tools, and
source control systems.
reStructuredText(reST)是一种易于阅读的纯文本标记语法,通常用于Python项目的文档,包括Python本身以及本用户指南。reST文档通常编译为HTML,但也支持其他输出格式。将reST与Robot Framework结合使用,可以将格式丰富的文档和测试数据以简洁的文本格式混合在一起,使用简单的文本编辑器、diff工具和源代码控制系统就可以轻松使用。
Note 注意
Using reStructuredText files with Robot Framework requires the
Python docutils module to be installed.
在Robot Framework中使用reStructuredText文件需要安装Pythondocutils模块。
When using Robot Framework with reStructuredText files, normal Robot Framework
data is embedded to so called code blocks. In standard reST code blocks are
marked using the code
directive, but Robot Framework supports also
code-block
or sourcecode
directives used by the Sphinx tool.
当使用带有reStructuredText文件的Robot Framework时,正常的Robot Framework数据被嵌入到所谓的代码块中。在标准的reST中,代码块使用code指令标记,但Robot Framework也支持Sphinx工具使用的代码块
或源代码
reStructuredText example
------------------------
This text is outside code blocks and thus ignored.
.. code:: robotframework
*** Settings ***
Documentation Example using the reStructuredText format.
Library OperatingSystem
*** Variables ***
${MESSAGE} Hello, world!
*** Test Cases ***
My Test
[Documentation] Example test.
Log ${MESSAGE}
My Keyword ${CURDIR}
Another Test
Should Be Equal ${MESSAGE} Hello, world!
Also this text is outside code blocks and ignored. Code blocks not
containing Robot Framework data are ignored as well.
.. code:: robotframework
# Both space and pipe separated formats are supported.
| *** Keywords *** | | |
| My Keyword | [Arguments] | ${path} |
| | Directory Should Exist | ${path} |
.. code:: python
# This code block is ignored.
def example():
print('Hello, world!')
Robot Framework supports reStructuredText files using .robot.rst,
.rst and .rest extensions. To avoid parsing unrelated
reStructuredText files, only files with the .robot.rst extension
are parsed by default when executing a directory. Parsing files with
other extensions can be enabled by using either --parseinclude
or --extension option.
Robot Framework支持使用.robot.rst、.rst和.rest扩展名的reStructuredText文件。为了避免解析不相关的reStructuredText文件,在执行目录时,默认情况下只解析扩展名为.robot.rst的文件。可以使用--parseinclude或--extension选项启用解析具有其他扩展名的文件。
When Robot Framework parses reStructuredText files, errors below level
SEVERE
are ignored to avoid noise about possible non-standard directives
and other such markup. This may hide also real errors, but they can be seen
when processing files using reStructuredText tooling normally.
当Robot Framework解析reStructuredText文件时,将忽略SEVERE
级别以下的错误,以避免可能的非标准指令和其他此类标记的干扰。这可能也会隐藏真实的错误,但在正常使用reStructuredText工具处理文件时,可以看到这些错误。
Note 注意
Parsing .robot.rst files automatically is new in
Robot Framework 6.1.
自动解析.robot.rst文件是Robot Framework 6.1中的新功能。
Robot Framework supports data also in the JSON format. This format is designed
more for tool developers than for regular Robot Framework users and it is not
meant to be edited manually. Its most important use cases are:
Robot Framework也支持JSON格式的数据。此格式更多地是为工具开发人员而不是常规Robot Framework用户设计的,并且不意味着手动编辑。它最重要的用例是:
Note 注意
The JSON data support is new in Robot Framework 6.1 and it can be
enhanced in future Robot Framework versions. If you have an enhancement
idea or believe you have encountered a bug, please submit an issue
or start a discussion thread on the #devel
channel on our Slack.
JSON数据支持是Robot Framework 6.1中的新功能,可以在未来的Robot Framework版本中进行增强。如果你有一个增强的想法或认为你遇到了一个错误,请提交一个问题或在我们的Slack上的#devel
频道上开始讨论。
A suite structure can be serialized into JSON by using the TestSuite.to_json
method. When used without arguments, it returns JSON data as a string, but
it also accepts a path or an open file where to write JSON data along with
configuration options related to JSON formatting:
可以使用TestSuite.to_json方法将套件结构序列化为JSON。当不带参数使用时,它将JSON数据作为字符串返回,但它也接受一个路径或一个打开的文件,在其中写入JSON数据沿着与JSON格式相关的配置选项:
from robot.running import TestSuite
# Create suite based on data on the file system.
suite = TestSuite.from_file_system('/path/to/data')
# Get JSON data as a string.
data = suite.to_json()
# Save JSON data to a file with custom indentation.
suite.to_json('data.rbt', indent=2)
If you would rather work with Python data and then convert that to JSON
or some other format yourself, you can use TestSuite.to_dict instead.
如果您更愿意使用Python数据,然后自己将其转换为JSON或其他格式,则可以使用TestSuite.to_dict。
A suite can be constructed from JSON data using the TestSuite.from_json
method. It works both with JSON strings and paths to JSON files:
可以使用TestSuite.from_json方法从JSON数据构造套件。它可以处理JSON字符串和JSON文件的路径:
from robot.running import TestSuite
# Create suite from JSON data in a file.
suite = TestSuite.from_json('data.rbt')
# Create suite from a JSON string.
suite = TestSuite.from_json('{"name": "Suite", "tests": [{"name": "Test"}]}')
# Execute suite. Notice that log and report needs to be created separately.
suite.run(output='example.xml')
If you have data as a Python dictionary, you can use TestSuite.from_dict
instead. Regardless of how a suite is recreated, it exists only in memory and
original data files on the file system are not recreated.
如果你有数据作为Python字典,你可以使用TestSuite.from_dict。无论如何重新创建套件,它都只存在于内存中,而不会重新创建文件系统上的原始数据文件。
As the above example demonstrates, the created suite can be executed using
the TestSuite.run method. It may, however, be easier to execute a JSON file
directly as explained in the following section.
正如上面的示例所示,可以使用TestSuite.run方法执行创建的套件。但是,直接执行JSON文件可能更容易,如下节所述。
When executing tests or tasks using the robot
command, JSON files with
the custom .rbt extension are parsed automatically. This includes
running individual JSON files like robot tests.rbt
and running directories
containing .rbt files. If you would rather use the standard
.json extension, you need to configure which files are parsed.
当使用robot
命令执行测试或任务时,会自动解析具有自定义.rbt扩展名的JSON文件。这包括运行单独的JSON文件,如机器人测试.rbt
和运行包含.rbt文件的目录。如果您更愿意使用标准的.json扩展名,则需要配置解析哪些文件。
Suite source in the data got from TestSuite.to_json
and TestSuite.to_dict
is in absolute format. If a suite is recreated later on a different machine,
the source may thus not match the directory structure on that machine. To
avoid that, it is possible to use the TestSuite.adjust_source method to
make the suite source relative before getting the data and add a correct root
directory after the suite is recreated:
从TestSuite.to_json
和TestSuite.to_dict
获取的数据中的套件源为绝对格式。如果稍后在不同的机器上重新创建套件,则源可能因此与该机器上的目录结构不匹配。为了避免这种情况,可以使用TestSuite.adjust_source方法在获取数据之前使套件源相对化,并在套件重新创建后添加正确的根目录:
from robot.running import TestSuite
# Create a suite, adjust source and convert to JSON.
suite = TestSuite.from_file_system('/path/to/data')
suite.adjust_source(relative_to='/path/to')
suite.to_json('data.rbt')
# Recreate suite elsewhere and adjust source accordingly.
suite = TestSuite.from_json('data.rbt')
suite.adjust_source(root='/new/path/to')
Imports, variables and keywords created in suite files are included in the
generated JSON along with tests and tasks. The exact JSON structure is documented
in the running.json schema file.
在套件文件中创建的导入、变量和关键字将与测试和任务一起沿着在生成的JSON中。确切的JSON结构记录在running.json模式文件中。
When Robot Framework parses the test data files, it ignores:
当Robot Framework解析测试数据文件时,它会忽略:
#
), when it is the first
character of a cell. This means that hash marks can be used to enter
comments in the test data.#
)是单元格的第一个字符时,它后面的所有字符。这意味着可以使用哈希标记在测试数据中输入注释。When Robot Framework ignores some data, this data is not available in
any resulting reports and, additionally, most tools used with Robot
Framework also ignore them. To add information that is visible in
Robot Framework outputs, place it to the documentation or other metadata of
test cases or suites, or log it with the BuiltIn keywords Log or
Comment.
当Robot Framework忽略某些数据时,这些数据在任何生成的报告中都不可用,此外,与Robot Framework一起使用的大多数工具也会忽略它们。要添加在Robot Framework输出中可见的信息,请将其放置到测试用例或套件的文档或其他元数据中,或者使用内置关键字Log或Comment将其记录下来。
The escape character in Robot Framework test data is the backslash
(\) and additionally built-in variables ${EMPTY}
and ${SPACE}
can often be used for escaping. Different escaping mechanisms are
discussed in the sections below.
Robot Framework测试数据中的转义字符是反斜杠(\),此外,内置变量${EMPTY}
和${SPACE}
通常可用于转义。不同的逃逸机制将在下面的章节中讨论。
The backslash character can be used to escape special characters
so that their literal values are used.
反斜杠字符可用于转义特殊字符,以便使用它们的文字值。
Character 字符 | Meaning 意义 | Examples 示例 |
---|---|---|
\$ |
Dollar sign, never starts a scalar variable. 美元符号,从不启动标量变量。 |
\${notvar} |
\@ |
At sign, never starts a list variable. 在sign时,从不启动列表变量。 |
\@{notvar} |
\& |
Ampersand, never starts a dictionary variable. 和号,从不启动字典变量。 |
\&{notvar} |
\% |
Percent sign, never starts an environment variable. 百分比符号,从不启动环境变量。 |
\%{notvar} |
\# |
Hash sign, never starts a comment. 散列符号,从不开始评论。 |
\# not comment |
\= |
Equal sign, never part of named argument syntax. 等号,从不作为命名参数语法的一部分。 |
not\=named |
\| |
Pipe character, not a separator in the pipe separated format. 管道字符,而不是管道分隔格式中的分隔符。 |
ls -1 *.txt \| wc -l |
\\ |
Backslash character, never escapes anything. 反斜杠字符,从不转义任何字符。 |
c:\\temp, \\${var} |
The backslash character also allows creating special escape sequences that are
recognized as characters that would otherwise be hard or impossible to create
in the test data.
反斜杠字符还允许创建特殊的转义序列,这些转义序列被识别为在测试数据中很难或不可能创建的字符。
Sequence 序列 | Meaning 意义 | Examples 示例 |
---|---|---|
\n |
Newline character. 换行符。 | first line\n2nd line |
\r |
Carriage return character 回车字符 |
text\rmore text |
\t |
Tab character. 制表符。 | text\tmore text |
\xhh |
Character with hex value hh .十六进制值为 hh 的字符。 |
null byte: \x00, ä: \xE4 |
\uhhhh |
Character with hex value hhhh .十六进制值 为hhhh 的字符。 |
snowman: \u2603 |
\Uhhhhhhhh |
Character with hex value hhhhhhhh .十六进制值为 hhhhhhhh 的字符。 |
love hotel: \U0001f3e9 |
Note 注意
All strings created in the test data, including characters like
\x02
, are Unicode and must be explicitly converted to
byte strings if needed. This can be done, for example, using
Convert To Bytes or Encode String To Bytes keywords
in BuiltIn and String libraries, respectively, or with
something like value.encode('UTF-8')
in Python code.
在测试数据中创建的所有字符串(包括\x02
这样的字符)都是Unicode,如果需要,必须显式转换为字节字符串。例如,可以分别使用BuiltIn和String库中的Convert To String或Encode String To String关键字,或者使用Python代码中的value.encode('UTF-8')
。
Note 注意
If invalid hexadecimal values are used with \x
, \u
or \U
escapes, the end result is the original value without
the backslash character. For example, \xAX
(not hex) and
\U00110000
(too large value) result with xAX
and U00110000
, respectively. This behavior may change in
the future, though.
如果在\x
、\u
或\U
转义中使用了无效的十六进制值,则最终结果是不带反斜杠字符的原始值。例如,\xAX
(非十六进制)和\U00110000
(太大的值)的结果分别为xAX
和U 00110000
。不过,这种行为在未来可能会改变。
Note 注意
Built-in variable ${\n}
can be used if operating system
dependent line terminator is needed (\r\n
on Windows and
\n
elsewhere).
如果需要依赖于操作系统的行终止符,则可以使用内置变量${\n}
(Windows上为\r\n
,其他地方为\n
When using the space separated format, the number of spaces used as
a separator can vary and thus empty values cannot be recognized unless they
are escaped. Empty cells can be escaped either with the backslash character
or with built-in variable ${EMPTY}
. The latter is typically recommended
as it is easier to understand.
当使用空格分隔格式时,用作分隔符的空格数可能会有所不同,因此除非对空值进行转义,否则无法识别空值。空单元格可以使用反斜杠字符或内置变量${EMPTY}
进行转义。后者通常被推荐,因为它更容易理解。
*** Test Cases ***
Using backslash
Do Something first arg \
Do Something \ second arg
Using ${EMPTY}
Do Something first arg ${EMPTY}
Do Something ${EMPTY} second arg
When using the pipe separated format, empty values need to be escaped
only when they are at the end of the row:
当使用管道分隔格式时,空值仅在位于行末尾时才需要转义:
| *** Test Cases *** | | | |
| Using backslash | Do Something | first arg | \ |
| | Do Something | | second arg |
| | | | |
| Using ${EMPTY} | Do Something | first arg | ${EMPTY} |
| | Do Something | | second arg |
Spaces, especially consecutive spaces, as part of arguments for keywords or
needed otherwise are problematic for two reasons:
空格,特别是连续空格,作为关键字参数的一部分或需要其他方式是有问题的,原因有两个:
In these cases spaces need to be escaped. Similarly as when escaping empty
values, it is possible to do that either by using the backslash character or
by using the built-in variable ${SPACE}
.
在这些情况下,空格需要转义。与转义空值时类似,可以通过使用反斜杠字符或使用内置变量${SPACE}来
执行此操作。
Escaping with backslash 使用反斜杠转义 | Escaping with ${SPACE} 使用 ${SPACE} 逃离 |
Notes 注意到 |
---|---|---|
\ leading space 前导空间 | ${SPACE}leading space |
|
trailing space \ 尾随空格\ | trailing space${SPACE} |
Backslash must be after the space. 反斜杠必须在空格之后。 |
\ \ | ${SPACE} |
Backslash needed on both sides. 两边都需要反斜杠。 |
consecutive \ \ spaces 连续空间 | consecutive${SPACE * 3}spaces |
Using extended variable syntax. 使用扩展变量语法。 |
As the above examples show, using the ${SPACE}
variable often makes the
test data easier to understand. It is especially handy in combination with
the extended variable syntax when more than one space is needed.
正如上面的示例所示,使用${SPACE}
变量通常会使测试数据更容易理解。当需要多个空格时,它与扩展变量语法结合使用特别方便。
If there is more data than readily fits a row, it is possible to split it
and start continuing rows with ellipsis (...
). Ellipses can be indented
to match the indentation of the starting row and they must always be followed
by the normal test data separator.
如果有更多的数据比容易适合一行,它是可能的分裂它,并开始与省略号(..
).椭圆可以缩进以匹配起始行的缩进,并且后面必须始终跟有正常的测试数据分隔符。
In most places split lines have exact same semantics as lines that are not
split. Exceptions to this rule are suite, test and keyword documentation
as well suite metadata. With them split values are automatically
joined together with the newline character to ease creating multiline
values.
在大多数情况下,分割线与未分割的线具有完全相同的语义。遵循这一规则的是套件、测试和关键字文档以及套件元数据。使用它们,分割值会自动与换行符连接在一起,以轻松创建多行值。
The ...
syntax allows also splitting variables in the Variable section.
When long scalar variables (e.g. ${STRING}
) are split to multiple rows,
the final value is got by concatenating the rows together. The separator is
a space by default, but that can be changed by starting the value with
SEPARATOR=<sep>
.
那个...
语法还允许在Variable部分中拆分变量。当长标量变量(例如${STRING}
)被拆分为多行时,最终值是通过将行连接在一起获得的。默认情况下,分隔符是一个空格,但可以通过以SEPARATOR=<sep>
开头的值来更改。
Splitting lines is illustrated in the following two examples containing
exactly same data without and with splitting.
在以下两个示例中说明了分割行,这两个示例包含完全相同的数据(不进行分割和进行分割)。
*** Settings ***
Documentation Here we have documentation for this suite.\nDocumentation is often quite long.\n\nIt can also contain multiple paragraphs.
Default Tags default tag 1 default tag 2 default tag 3 default tag 4 default tag 5
*** Variables ***
${STRING} This is a long string. It has multiple sentences. It does not have newlines.
${MULTILINE} This is a long multiline string.\nThis is the second line.\nThis is the third and the last line.
@{LIST} this list is quite long and items in it can also be long
&{DICT} first=This value is pretty long. second=This value is even longer. It has two sentences.
*** Test Cases ***
Example
[Tags] you probably do not have this many tags in real life
Do X first argument second argument third argument fourth argument fifth argument sixth argument
${var} = Get X first argument passed to this keyword is pretty long second argument passed to this keyword is long too
*** Settings ***
Documentation Here we have documentation for this suite.
... Documentation is often quite long.
...
... It can also contain multiple paragraphs.
Default Tags default tag 1 default tag 2 default tag 3
... default tag 4 default tag 5
*** Variables ***
${STRING} This is a long string.
... It has multiple sentences.
... It does not have newlines.
${MULTILINE} SEPARATOR=\n
... This is a long multiline string.
... This is the second line.
... This is the third and the last line.
@{LIST} this list is quite long and
... items in it can also be long
&{DICT} first=This value is pretty long.
... second=This value is even longer. It has two sentences.
*** Test Cases ***
Example
[Tags] you probably do not have this many
... tags in real life
Do X first argument second argument third argument
... fourth argument fifth argument sixth argument
${var} = Get X
... first argument passed to this keyword is pretty long
... second argument passed to this keyword is long too
Robot Framework localization efforts were started in Robot Framework 6.0
that allowed translation of section headers, settings,
Given/When/Then prefixes used in Behavior Driven Development (BDD), and
true and false strings used in automatic Boolean argument conversion.
The plan is to extend localization support in the future, for example,
to log and report and possibly also to control structures.
Robot Framework的本地化工作始于Robot Framework 6.0,它允许翻译节头、设置、行为驱动开发(BDD)中使用的Given/When/Then前缀以及自动布尔参数转换中使用的true和false字符串。计划是在未来扩展本地化支持,例如,日志和报告,也可能是控制结构。
This section explains how to activate languages, what built-in languages
are supported, how to create custom language files and how new translations
can be contributed.
本节介绍如何激活语言,支持哪些内置语言,如何创建自定义语言文件以及如何贡献新的翻译。
The main mechanism to activate languages is specifying them from the command line
using the --language option. When enabling built-in languages,
it is possible to use either the language name like Finnish
or the language
code like fi
. Both names and codes are case and space insensitive and also
the hyphen (-
) is ignored. To enable multiple languages, the
--language option needs to be used multiple times:
激活语言的主要机制是使用--language选项从命令行指定语言。当启用内置语言时,可以使用语言名称(如芬兰语)
或语言代码(如fi
)。名称和代码都不区分大小写和空格,连字符(-
)也被忽略。要启用多种语言,需要多次使用--language选项:
robot --language Finnish testit.robot robot --language pt --language ptbr testes.robot
The same --language option is also used when activating
custom language files. With them the value can be either a path to the file or,
if the file is in the module search path, the module name:
激活自定义语言文件时也使用相同的--language选项。使用它们,值可以是文件的路径,或者如果文件在模块搜索路径中,则是模块名称:
robot --language Custom.py tests.robot robot --language MyLang tests.robot
For backwards compatibility reasons, and to support partial translations,
English is always activated automatically. Future versions may allow disabling
it.
出于向后兼容性的原因,并支持部分翻译,英语总是自动激活。未来的版本可能允许禁用它。
It is also possible to enable languages directly in data files by having
a line Language: <value>
(case-insensitive) before any of the section
headers. The value after the colon is interpreted the same way as with
the --language option:
也可以在数据文件中直接启用语言,方法是在任何节标题之前添加一行Language:<value>
(不区分大小写)。冒号后面的值的解释方式与--language选项相同:
Language: Finnish *** Asetukset *** Dokumentaatio Example using Finnish.
If there is a need to enable multiple languages, the Language:
line
can be repeated. These configuration lines cannot be in comments so something like
# Language: Finnish
has no effect.
如果需要启用多种语言,可以重复Language:
行。这些配置行不能出现在注释中,因此类似#Language:Finnish
的内容无效。
Due to technical limitations, the per-file language configuration affects also
parsing subsequent files as well as the whole execution. This
behavior is likely to change in the future and should not be relied upon.
If you use per-file configuration, use it with all files or enable languages
globally with the --language option.
由于技术限制,每个文件的语言配置也会影响后续文件的解析以及整个执行。这种行为将来可能会改变,不应依赖。如果使用按文件配置,请将其用于所有文件或使用--language选项全局启用语言。
The following languages are supported out-of-the-box. Click the language name
to see the actual translations:
开箱即用支持以下语言。点击语言名称查看实际翻译:
All these translations have been provided by the awesome Robot Framework
community. If a language you are interested in is not included, you can
consider contributing it!
所有这些翻译都是由令人敬畏的机器人框架社区提供的。如果您感兴趣的语言没有包含在内,您可以考虑贡献它!
If a language you would need is not available as a built-in language, or you
want to create a totally custom language for some specific need, you can easily
create a custom language file. Language files are Python files that contain
one or more language definitions that are all loaded when the language file
is taken into use. Language definitions are created by extending the
robot.api.Language
base class and overriding class attributes as needed:
如果您需要的语言无法作为内置语言提供,或者您想要为某些特定需求创建完全自定义的语言,则可以轻松创建自定义语言文件。语言文件是包含一个或多个语言定义的Python文件,这些语言定义在使用语言文件时全部加载。通过扩展robot.API.Language
基类并根据需要重写类属性来创建语言定义:
from robot.api import Language
class Example(Language):
test_cases_header = 'Validations'
tags_setting = 'Labels'
given_prefixes = ['Assuming']
true_strings = ['OK', '\N{THUMBS UP SIGN}']
Assuming the above code would be in file example.py, a path to that
file or just the module name example
could be used when the language file
is activated.
假设上述代码位于文件example.py中,则在激活语言文件时可以使用该文件的路径或仅使用模块名称示例
。
The above example adds only some of the possible translations. That is fine
because English is automatically enabled anyway. Most values must be specified
as strings, but BDD prefixes and true/false strings allow more than one value
and must be given as lists. For more examples, see Robot Framework's internal
languages module that contains the Language
class as well as all built-in
language definitions.
上面的例子只添加了一些可能的翻译。这很好,因为无论如何都会自动启用英语。大多数值必须指定为字符串,但是BDD前缀和true/false字符串允许多个值,并且必须以列表的形式给出。有关更多示例,请参见Robot Framework的内部语言模块,该模块包含Language
类以及所有内置语言定义。
If you want to add translation for a new language or enhance existing, head
to Crowdin that we use for collaboration. For more details, see the
separate Localization project, and for questions and free discussion join
the #localization
channel on our Slack.
如果您想添加新语言的翻译或增强现有的翻译,请前往我们用于协作的Crowdin。有关更多详细信息,请参阅单独的本地化项目,如有疑问和免费讨论,请加入我们Slack上的#localization
频道。
Robot Framework syntax creates a simple programming language, and similarly as with
other languages, it is important to think about the coding style. Robot Framework
syntax is pretty flexible on purpose, but there are some generally recommended
conventions:
Robot Framework语法创建了一种简单的编程语言,与其他语言类似,考虑编码风格很重要。Robot Framework语法非常灵活,但有一些通常推荐的约定:
${EXAMPLE}
and local variables
using lower-case letters like ${example}
.${EXAMPLE}
;局部变量使用小写字母,如${example}
。One case where there currently is no strong convention is keyword capitalization.
Robot Framework itself typically uses title-case like Example Keyword in
documentation and elsewhere, and this style is often used in Robot Framework data
as well. It does not work too well with longer, sentence-like keywords such as
Log into system as an admin, though.
目前没有强有力的约定的一种情况是关键字大写。Robot Framework本身通常在文档和其他地方使用标题大小写(如Example Keyword),这种风格也经常在Robot Framework数据中使用。它不太好用较长的,类似广告的关键字,如登录到系统作为管理员,虽然。
Teams and organizations using Robot Framework should generally have their own coding
standards. The community developed Robot Framework Style Guide is an excellent
starting point that can be amended as needed. It is also possible to enforce these
conventions by using the Robocop linter and the Robotidy code formatter.
使用Robot Framework的团队和组织通常应该有自己的编码标准。社区开发的机器人框架样式指南是一个很好的起点,可以根据需要进行修改。也可以通过使用Robocoplinter和Robottidy代码格式化器来强制执行这些约定。
This section describes the overall test case syntax. Organizing test
cases into test suites using suite files and suite
directories is discussed in the next section.
本节描述了整个测试用例语法。使用套件文件和套件目录将测试用例组织成测试套件将在下一节中讨论。
When using Robot Framework for other automation purposes than test
automation, it is recommended to create tasks instead of tests.
The task syntax is for most parts identical to the test syntax,
and the differences are explained in the Creating tasks section.
当将Robot Framework用于测试自动化以外的其他自动化目的时,建议创建任务而不是测试。任务语法的大部分与测试语法相同,创建任务一节中解释了它们的区别。
Test cases are constructed in test case sections from the available
keywords. Keywords can be imported from test libraries or resource
files, or created in the keyword section of the test case file
itself.
测试用例在测试用例部分中从可用的关键字中构造。关键字可以从测试库或资源文件中导入,或者在测试用例文件本身的关键字部分中创建。
The first column in the test case section contains test case names. A
test case starts from the row with something in this column and
continues to the next test case name or to the end of the section. It is
an error to have something between the section headers and the first
test.
测试用例部分的第一列包含测试用例名称。测试用例从该列中包含内容的行开始,并继续到下一个测试用例名称或部分的末尾。在节头和第一个测试之间存在某些内容是错误的。
The second column normally has keyword names. An exception to this rule
is setting variables from keyword return values, when the second and
possibly also the subsequent columns contain variable names and a keyword
name is located after them. In either case, columns after the keyword name
contain possible arguments to the specified keyword.
第二列通常包含关键字名称。此规则的一个例外是从关键字返回值设置变量,当第二列以及可能的后续列包含变量名称并且关键字名称位于它们之后时。在这两种情况下,关键字名称之后的列都包含指定关键字的可能参数。
*** Test Cases ***
Valid Login
Open Login Page
Input Username demo
Input Password mode
Submit Credentials
Welcome Page Should Be Open
Setting Variables
Do Something first argument second argument
${value} = Get Some Value
Should Be Equal ${value} Expected value
Note 注意
Although test case names can contain any character, using ?
and
especially *
is not generally recommended because they are
considered to be wildcards when selecting test cases.
For example, trying to run only a test with name Example *
like --test 'Example *'
will actually run any test starting with
Example.
尽管测试用例名称可以包含任何字符,但使用?
尤其是*
,一般不推荐使用,因为在选择测试用例时,它们被认为是通配符。例如,尝试只运行名为Example *like--test 'Example *'的测试,
实际上将运行任何以Example开头的测试。
Test cases can also have their own settings. Setting names are always
in the second column, where keywords normally are, and their values
are in the subsequent columns. Setting names have square brackets around
them to distinguish them from keywords. The available settings are listed
below and explained later in this section.
测试用例也可以有自己的设置。设置名称始终位于第二列中,关键字通常位于第二列中,其值位于后续列中。设置名称周围有方括号,以将其与关键字区分开来。下面列出了可用的设置,并在本节后面进行了说明。
Note 注意
Setting names are case-insensitive, but the format used above is
recommended. Settings used to be also space-insensitive, but that was
deprecated in Robot Framework 3.1 and trying to use something like
[T a g s]
causes an error in Robot Framework 3.2. Possible spaces
between brackets and the name (e.g. [ Tags ]
) are still allowed.
设置名称不区分大小写,但建议使用上述格式。设置过去也是不区分空格的,但在Robot Framework 3.1中不推荐使用,并且尝试使用类似[T a g s]的
内容会导致Robot Framework 3.2中的错误。仍然允许在括号和名称之间使用空格(例如[ Tags ]
)。
Example test case with settings:
带有设置的测试用例示例:
*** Test Cases ***
Test With Settings
[Documentation] Another dummy test
[Tags] dummy owner-johndoe
Log Hello, world!
The earlier examples have already demonstrated keywords taking
different arguments, and this section discusses this important
functionality more thoroughly. How to actually implement user
keywords and library keywords with different arguments is
discussed in separate sections.
前面的示例已经演示了采用不同参数的关键字,本节将更全面地讨论这一重要功能。如何使用不同的参数实际实现用户关键字和库关键字将在单独的部分中讨论。
Keywords can accept zero or more arguments, and some arguments may
have default values. What arguments a keyword accepts depends on its
implementation, and typically the best place to search this
information is keyword's documentation. In the examples in this
section the documentation is expected to be generated using the
Libdoc tool, but the same information is available on
documentation generated by generic documentation tools such as
pydoc.
关键字可以接受零个或多个参数,并且某些参数可能具有默认值。关键字接受什么参数取决于它的实现,通常搜索此信息的最佳位置是关键字的文档。在本节的示例中,文档预计将使用Libdoc工具生成,但在由通用文档工具(如 pydoc )生成的文档中也可以获得相同的信息。
Most keywords have a certain number of arguments that must always be
given. In the keyword documentation this is denoted by specifying the
argument names separated with a comma like first, second,
third
. The argument names actually do not matter in this case, except
that they should explain what the argument does, but it is important
to have exactly the same number of arguments as specified in the
documentation. Using too few or too many arguments will result in an
error.
大多数关键字都有一定数量的参数,必须始终给出。在关键字documentation中,这是通过指定参数名来表示的,参数名之间用逗号分隔,如first,second,third
。在这种情况下,参数名称实际上并不重要,除了它们应该解释参数的作用,但是重要的是要有与文档中指定的参数数量完全相同的参数。使用太少或太多的参数将导致错误。
The test below uses keywords Create Directory and Copy
File from the OperatingSystem library. Their arguments are
specified as path
and source, destination
, which means
that they take one and two arguments, respectively. The last keyword,
No Operation from BuiltIn, takes no arguments.
下面的测试使用OperatingSystem库中的关键字Create Directory和Copy File。它们的参数被指定为path
和source、destination
,这意味着它们分别接受一个和两个参数。最后一个关键字NoOperation fromBuiltIn不带参数。
*** Test Cases ***
Example
Create Directory ${TEMPDIR}/stuff
Copy File ${CURDIR}/file.txt ${TEMPDIR}/stuff
No Operation
Arguments often have default values which can either be given or
not. In the documentation the default value is typically separated
from the argument name with an equal sign like name=default
value
. It is possible that all the arguments have default
values, but there cannot be any positional arguments after arguments
with default values.
参数通常有默认值,可以给定也可以不给定。在文档中,默认值通常与参数名用等号分隔,如name=default value
。可能所有参数都有默认值,但在具有默认值的参数之后不能有任何位置参数。
Using default values is illustrated by the example below that uses
Create File keyword which has arguments path, content=,
encoding=UTF-8
. Trying to use it without any arguments or more than
three arguments would not work.
下面的示例说明了如何使用默认值,该示例使用Create File关键字,其参数为path,content=,encoding=UTF-8
。尝试在没有任何参数或超过三个参数的情况下使用它将不起作用。
*** Test Cases ***
Example
Create File ${TEMPDIR}/empty.txt
Create File ${TEMPDIR}/utf-8.txt Hyvä esimerkki
Create File ${TEMPDIR}/iso-8859-1.txt Hyvä esimerkki ISO-8859-1
It is also possible that a keyword accepts any number of arguments.
These so called varargs can be combined with mandatory arguments
and arguments with default values, but they are always given after
them. In the documentation they have an asterisk before the argument
name like *varargs
.
关键字也可以接受任意数量的参数。这些所谓的varargs可以与强制参数和具有默认值的参数组合,但它们总是在它们之后给出。在文档中,它们在参数名之前有一个星号,如*varargs
。
For example, Remove Files and Join Paths keywords from
the OperatingSystem library have arguments *paths
and base, *parts
,
respectively. The former can be used with any number of arguments, but
the latter requires at least one argument.
例如,OperatingSystem库中的Remove Files和Join Paths关键字分别具有参数*paths
和base,*parts
。前者可以与任意数量的参数一起使用,但后者需要至少一个参数。
*** Test Cases ***
Example
Remove Files ${TEMPDIR}/f1.txt ${TEMPDIR}/f2.txt ${TEMPDIR}/f3.txt
@{paths} = Join Paths ${TEMPDIR} f1.txt f2.txt f3.txt f4.txt
The named argument syntax makes using arguments with default values more
flexible, and allows explicitly labeling what a certain argument value means.
Technically named arguments work exactly like keyword arguments in Python.
命名参数语法使得使用带有默认值的参数更加灵活,并允许显式地标记某个参数值的含义。从技术上讲,命名参数的工作方式与Python中的关键字参数完全相同。
It is possible to name an argument given to a keyword by prefixing the value
with the name of the argument like arg=value
. This is especially
useful when multiple arguments have default values, as it is
possible to name only some the arguments and let others use their defaults.
For example, if a keyword accepts arguments arg1=a, arg2=b, arg3=c
,
and it is called with one argument arg3=override
, arguments
arg1
and arg2
get their default values, but arg3
gets value override
. If this sounds complicated, the named arguments
example below hopefully makes it more clear.
可以通过在值前面加上参数名称来命名关键字的参数,如arg=value
。当多个参数有默认值时,这特别有用,因为可以只命名一些参数,让其他参数使用它们的默认值。例如,如果关键字接受参数arg1=a、arg2=B、arg3=c
,并且使用一个参数arg3=override
调用该关键字,则参数arg1
和arg2将
获得其默认值,但arg3
将获得值override
。如果这听起来很复杂,下面的命名参数示例可能会让它更清楚。
The named argument syntax is both case and space sensitive. The former
means that if you have an argument arg
, you must use it like
arg=value
, and neither Arg=value
nor ARG=value
works. The latter means that spaces are not allowed before the =
sign, and possible spaces after it are considered part of the given value.
命名参数语法对大小写和空格都敏感。前者意味着如果你有一个参数arg
,你必须像arg=value那样
使用它,而Arg=value
和ARG=value都
不起作用。后者意味着在=
号之前不允许有空格,而在=号之后可能的空格被认为是给定值的一部分。
When the named argument syntax is used with user keywords, the argument
names must be given without the ${}
decoration. For example, user
keyword with arguments ${arg1}=first, ${arg2}=second
must be used
like arg2=override
.
当命名参数语法与用户关键字一起使用时,参数名称必须不带${}
装饰。例如,参数为${arg 1}=first、${arg 2}=second的
user关键字必须像arg 2 =override一样
使用。
Using normal positional arguments after named arguments like, for example,
| Keyword | arg=value | positional |
, does not work.
The relative order of the named arguments does not matter.
在命名参数之后使用普通的位置参数,例如,|关键字|arg=值|位置|
,不起作用。命名参数的相对顺序无关紧要。
It is possible to use variables in both named argument names and values.
If the value is a single scalar variable, it is passed to the keyword as-is.
This allows using any objects, not only strings, as values also when using
the named argument syntax. For example, calling a keyword like arg=${object}
will pass the variable ${object}
to the keyword without converting it to
a string.
可以在命名参数名称和值中使用变量。如果值是单个标量变量,则按原样传递给关键字。这允许在使用命名参数语法时使用任何对象(不仅是字符串)作为值。例如,调用像arg=${object}这样
的关键字会将变量${object}
传递给关键字,而不会将其转换为字符串。
If variables are used in named argument names, variables are resolved before
matching them against argument names.
如果变量用于命名的参数名称中,则在将变量与参数名称进行匹配之前解析变量。
The named argument syntax requires the equal sign to be written literally
in the keyword call. This means that variable alone can never trigger the
named argument syntax, not even if it has a value like foo=bar
. This is
important to remember especially when wrapping keywords into other keywords.
If, for example, a keyword takes a variable number of arguments like
@{args}
and passes all of them to another keyword using the same @{args}
syntax, possible named=arg
syntax used in the calling side is not recognized.
This is illustrated by the example below.
命名参数语法要求在关键字调用中按字面意思写入等号。这意味着单独的变量永远不会触发命名参数语法,即使它有一个像foo=bar这样的
值。这一点很重要,尤其是在将关键字包装到其他关键字中时。例如,如果一个关键字接受可变数量的参数(例如@{args})
,并使用相同的@{args}
语法将所有参数传递给另一个关键字,则无法识别调用端使用的可能的named=arg
语法。下面的例子说明了这一点。
*** Test Cases ***
Example
Run Program shell=True # This will not come as a named argument to Run Process
*** Keywords ***
Run Program
[Arguments] @{args}
Run Process program.py @{args} # Named arguments are not recognized from inside @{args}
If keyword needs to accept and pass forward any named arguments, it must be
changed to accept free named arguments. See free named argument examples
for a wrapper keyword version that can pass both positional and named
arguments forward.
如果关键字需要接受并传递任何命名参数,则必须将其更改为接受自由命名参数。有关可以向前传递位置参数和命名参数的包装器关键字版本,请参见自由命名参数示例。
The named argument syntax is used only when the part of the argument
before the equal sign matches one of the keyword's arguments. It is possible
that there is a positional argument with a literal value like foo=quux
,
and also an unrelated argument with name foo
. In this case the argument
foo
either incorrectly gets the value quux
or, more likely,
there is a syntax error.
仅当参数等号之前的部分与关键字的参数之一匹配时,才使用命名参数语法。可能有一个位置参数的字面值为foo=quux
,还有一个不相关的参数名为foo
。在这种情况下,参数foo
要么错误地获取了值quux
,要么更有可能是语法错误。
In these rare cases where there are accidental matches, it is possible to
use the backslash character to escape the syntax like foo\=quux
.
Now the argument will get a literal value foo=quux
. Note that escaping
is not needed if there are no arguments with name foo
, but because it
makes the situation more explicit, it may nevertheless be a good idea.
在这些偶然匹配的罕见情况下,可以使用反斜杠字符来转义语法,如foo\=quux
。现在参数将得到一个文本值foo=quux
。请注意,如果没有名为foo
的参数,则不需要转义,但因为它使情况更加明确,所以它可能仍然是一个好主意。
As already explained, the named argument syntax works with keywords. In
addition to that, it also works when importing libraries.
如前所述,命名参数语法适用于关键字。除此之外,它还可以在导入库时工作。
Naming arguments is supported by user keywords and by most test libraries.
The only exceptions are Python keywords explicitly using positional-only arguments.
用户关键字和大多数测试库都支持参数。唯一的例外是Python关键字显式使用仅位置参数。
The following example demonstrates using the named arguments syntax with
library keywords, user keywords, and when importing the Telnet test library.
下面的示例演示如何将命名参数语法与库关键字、用户关键字一起使用,以及如何在导入测试库时使用。
*** Settings ***
Library Telnet prompt=$ default_log_level=DEBUG
*** Test Cases ***
Example
Open connection 10.0.0.42 port=${PORT} alias=example
List files options=-lh
List files path=/tmp options=-l
*** Keywords ***
List files
[Arguments] ${path}=. ${options}=
Execute command ls ${options} ${path}
Robot Framework supports free named arguments, often also called free
keyword arguments or kwargs, similarly as Python supports **kwargs.
What this means is that a keyword can receive all arguments that use
the named argument syntax (name=value
) and do not match any arguments
specified in the signature of the keyword.
Robot框架支持自由命名参数,通常也称为自由关键字参数或Kwargs,类似于Python支持 **Kwargs。这意味着关键字可以接收所有使用命名参数语法(name=value
)的参数,并且不匹配关键字签名中指定的任何参数。
Free named arguments are supported by same keyword types than normal named
arguments. How keywords specify that they accept free named arguments
depends on the keyword type. For example, Python based keywords simply use
**kwargs
and user keywords use &{kwargs}
.
自由命名参数受与普通命名参数相同的关键字类型支持。关键字如何指定它们接受自由命名参数取决于关键字类型。例如,基于Python的关键字使用**kwargs
,用户关键字使用&{kwargs}
。
Free named arguments support variables similarly as named arguments. In practice that means that variables
can be used both in names and values, but the escape sign must always be
visible literally. For example, both foo=${bar}
and ${foo}=${bar}
are
valid, as long as the variables that are used exist. An extra limitation is
that free argument names must always be strings.
自由命名参数支持与命名参数类似的变量。在实践中,这意味着变量可以在名称和值中使用,但转义符号必须始终可见。例如,foo=${bar}
和${foo}=${bar}
都是有效的,只要使用的变量存在。一个额外的限制是自由参数名称必须总是字符串。
As the first example of using free named arguments, let's take a look at
Run Process keyword in the Process library. It has a signature
command, *arguments, **configuration
, which means that it takes the command
to execute (command
), its arguments as variable number of arguments
(*arguments
) and finally optional configuration parameters as free named
arguments (**configuration
). The example below also shows that variables
work with free keyword arguments exactly like when using the named argument
syntax.
作为使用自由命名参数的第一个示例,让我们看看Process库中的Run Process关键字。它有一个签名命令,*arguments,**configuration
,这意味着它需要执行命令(命令
),其参数作为变量数量的参数(*arguments
),最后可选的配置参数作为自由命名参数(**configuration
)。下面的示例还显示了变量与自由关键字参数的工作方式与使用命名参数语法时完全相同。
*** Test Cases ***
Free Named Arguments
Run Process program.py arg1 arg2 cwd=/home/user
Run Process program.py argument shell=True env=${ENVIRON}
See Free keyword arguments (**kwargs) section under Creating test
libraries for more information about using the free named arguments syntax
in your custom test libraries.
有关在自定义测试库中使用自由命名参数语法的更多信息,请参见创建测试库下的自由关键字参数(**kwargs)部分
As the second example, let's create a wrapper user keyword for running the
program.py
in the above example. The wrapper keyword Run Program
accepts all positional and named arguments and passes them forward to
Run Process along with the name of the command to execute.
作为第二个示例,让我们创建一个包装器user关键字,用于运行上面示例中的program.py
。包装器关键字Run Program接受所有位置参数和命名参数,并将它们与要执行的命令的名称沿着传递给Run Process。
*** Test Cases ***
Free Named Arguments
Run Program arg1 arg2 cwd=/home/user
Run Program argument shell=True env=${ENVIRON}
*** Keywords ***
Run Program
[Arguments] @{args} &{config}
Run Process program.py @{args} &{config}
Starting from Robot Framework 3.1, keywords can accept argument that must
always be named using the named argument syntax. If, for example,
a keyword would accept a single named-only argument example
, it would
always need to be used like example=value
and using just value
would
not work. This syntax is inspired by the keyword-only arguments
syntax supported by Python 3.
从Robot Framework 3.1开始,关键字可以接受必须始终使用命名参数语法命名的参数。例如,如果一个关键字接受一个仅命名的参数example
,它总是需要像example=value那样
使用,而只使用value
是行不通的。这种语法受到Python 3支持的仅关键字参数语法的启发。
For most parts named-only arguments work the same way as named arguments.
The main difference is that libraries implemented with Python 2 using
the static library API do not support this syntax.
在大多数情况下,仅命名参数的工作方式与命名参数相同。主要区别是使用静态库API用Python 2实现的库不支持此语法。
As an example of using the named-only arguments with user keywords, here
is a variation of the Run Program in the above free named argument
examples that only supports configuring shell
:
作为使用带有用户关键字的仅命名参数的示例,下面是上述自由命名参数示例中的Run Program的变体,仅支持配置shell
:
*** Test Cases ***
Named-only Arguments
Run Program arg1 arg2 # 'shell' is False (default)
Run Program argument shell=True # 'shell' is True
*** Keywords ***
Run Program
[Arguments] @{args} ${shell}=False
Run Process program.py @{args} shell=${shell}
A totally different approach to specify arguments is embedding them
into keyword names. This syntax is supported by both test library keywords
and user keywords.
一种完全不同的指定参数的方法是将它们嵌入到关键字名称中。测试库关键字和用户关键字都支持此语法。
A test case fails if any of the keyword it uses fails. Normally this means that
execution of that test case is stopped, possible test teardown is executed,
and then execution continues from the next test case. It is also possible to
use special continuable failures if stopping test execution is not desired.
如果测试用例使用的任何关键字失败,则测试用例失败。通常这意味着停止执行该测试用例,执行可能的测试拆卸,然后从下一个测试用例继续执行。如果不希望停止测试执行,也可以使用特殊的可持续故障。
The error message assigned to a failed test case is got directly from the
failed keyword. Often the error message is created by the keyword itself, but
some keywords allow configuring them.
分配给失败测试用例的错误消息直接从failed关键字获得。错误消息通常由关键字本身创建,但有些关键字允许配置它们。
In some circumstances, for example when continuable failures are used,
a test case can fail multiple times. In that case the final error message
is got by combining the individual errors. Very long error messages are
automatically cut from the middle to keep reports easier to read, but
full error messages are always visible in log files as messages of
the failed keywords.
在某些情况下,例如当使用可持续的失败时,测试用例可能会失败多次。在这种情况下,最终的错误信息是通过合并各个错误得到的。很长的错误消息会自动从中间剪切,以使报告更易于阅读,但完整的错误消息在日志文件中始终可见,作为失败关键字的消息。
By default error messages are normal text, but
they can contain HTML formatting. This
is enabled by starting the error message with marker string *HTML*
.
This marker will be removed from the final error message shown in reports
and logs. Using HTML in a custom message is shown in the second example below.
默认情况下,错误消息是普通文本,但它们可以包含HTML格式。这是通过以标记字符串*HTML*
开始错误消息来启用的。此标记将从报告和日志中显示的最终错误消息中删除。在自定义消息中使用HTML如下面的第二个示例所示。
*** Test Cases ***
Normal Error
Fail This is a rather boring example...
HTML Error
${number} = Get Number
Should Be Equal ${number} 42 *HTML* Number is not my <b>MAGIC</b> number.
The test case name comes directly from the Test Case section: it is
exactly what is entered into the test case column. Test cases in one
test suite should have unique names. Pertaining to this, you can also
use the automatic variable ${TEST_NAME}
within the test
itself to refer to the test name. It is available whenever a test is
being executed, including all user keywords, as well as the test setup
and the test teardown.
测试用例名称直接来自测试用例部分:它就是输入到测试用例列中的内容。一个测试套件中的测试用例应该有唯一的名称。与此相关,您还可以使用测试本身内的自动变量${TEST_NAME}
它在执行测试时可用,包括所有用户关键字,以及测试设置和测试拆除。
Starting from Robot Framework 3.2, possible variables in the test case name
are resolved so that the final name will contain the variable value. If
the variable does not exist, its name is left unchanged.
从Robot Framework 3.2开始,测试用例名称中可能的变量被解析,以便最终名称将包含变量值。如果变量不存在,则其名称保持不变。
*** Variables ***
${MAX AMOUNT} ${5000000}
*** Test Cases ***
Amount cannot be larger than ${MAX AMOUNT}
# ...
The [Documentation] setting allows setting free form
documentation for a test case. That text is shown in the command line
output and in the resulting logs and reports.
If documentation gets long, it can be split into multiple rows.
It is possible to use simple HTML formatting and variables can
be used to make the documentation dynamic. Possible non-existing
variables are left unchanged.
[Documentation]设置允许为测试用例设置自由格式的文档。该文本显示在命令行输出以及生成的日志和报告中。如果文档很长,可以将其拆分为多行。可以使用简单的HTML格式和变量来使文档动态化。可能不存在的变量保持不变。
*** Test Cases ***
Simple
[Documentation] Simple and short documentation.
No Operation
Multiple lines
[Documentation] First row of the documentation.
...
... Documentation continues here. These rows form
... a paragraph when shown in HTML outputs.
No Operation
Formatting
[Documentation]
... This list has:
... - *bold*
... - _italics_
... - link: http://robotframework.org
No Operation
Variables
[Documentation] Executed at ${HOST} by ${USER}
No Operation
It is important that test cases have clear and descriptive names, and
in that case they normally do not need any documentation. If the logic
of the test case needs documenting, it is often a sign that keywords
in the test case need better names and they are to be enhanced,
instead of adding extra documentation. Finally, metadata, such as the
environment and user information in the last example above, is often
better specified using tags.
重要的是测试用例有清晰的描述性名称,在这种情况下,它们通常不需要任何文档。如果测试用例的逻辑需要文档化,这通常意味着测试用例中的关键字需要更好的名称,并且需要增强,而不是添加额外的文档。最后,元数据(如上面最后一个示例中的环境和用户信息)通常可以使用标记更好地指定。
Using tags in Robot Framework is a simple, yet powerful mechanism for
classifying test cases and also user keywords. Tags are free text and
Robot Framework itself has no special meaning for them except for the
reserved tags discussed below. Tags can be used at least for the following
purposes:
在Robot Framework中使用标签是一种简单但功能强大的机制,用于对测试用例和用户关键字进行分类。标签是自由文本,除了下面讨论的保留标签外,Robot Framework本身对它们没有特殊意义。标签至少可用于以下目的:
There are multiple ways how to specify tags for test cases explained below:
有多种方法可以为下面解释的测试用例指定标签:
-tag
syntax.-tag
语法删除使用Test Tags设置的标签。Example: 范例:
*** Settings ***
Test Tags requirement: 42 smoke
*** Variables ***
${HOST} 10.0.1.42
*** Test Cases ***
No own tags
[Documentation] Test has tags 'requirement: 42' and 'smoke'.
No Operation
Own tags
[Documentation] Test has tags 'requirement: 42', 'smoke' and 'not ready'.
[Tags] not ready
No Operation
Own tags with variable
[Documentation] Test has tags 'requirement: 42', 'smoke' and 'host: 10.0.1.42'.
[Tags] host: ${HOST}
No Operation
Remove common tag
[Documentation] Test has only tag 'requirement: 42'.
[Tags] -smoke
No Operation
Remove common tag using a pattern
[Documentation] Test has only tag 'smoke'.
[Tags] -requirement: *
No Operation
Set Tags and Remove Tags keywords
[Documentation] This test has tags 'smoke', 'example' and 'another'.
Set Tags example another
Remove Tags requirement: *
As the example shows, tags can be created using variables, but otherwise they
preserve the exact name used in the data. When tags are compared, for example,
to collect statistics, to select test to be executed, or to remove duplicates,
comparisons are case, space and underscore insensitive.
如示例所示,可以使用变量创建标记,但除此之外,它们将保留数据中使用的确切名称。当比较标记时,例如,为了收集统计数据,选择要执行的测试,或者删除重复项,比较是不区分大小写、空格和下划线的。
As demonstrated by the above examples, removing tags using -tag
syntax supports
simple patterns like -requirement: *
. Tags starting with a hyphen have no
special meaning otherwise than with the [Tags] setting. If there is
a need to set a tag starting with a hyphen with [Tags], it is possible
to use the escaped format like \-tag
.
正如上面的例子所展示的,使用-tag
语法删除标记支持简单的模式,如-requirement:*
。以连字符开头的标签除了在[Tags]设置中没有特殊意义。如果需要设置一个以连字符和[Tags]开头的标签,可以使用转义格式,如\-tag
。
Note 注意
The Test Tags setting is new in Robot Framework 6.0.
Earlier versions support Force Tags and Default Tags
settings discussed in the next section.
测试标记设置是Robot Framework 6.0中的新功能。早期版本支持下一节中讨论的强制标记和默认标记设置。
Note 注意
The -tag
syntax for removing common tags is new in Robot Framework 7.0.
用于删除公共标记的-tag
语法是Robot Framework 7.0中的新语法。
Prior to Robot Framework 6.0, tags could be specified to tests in the Setting section
using two different settings:
在Robot Framework 6.0之前,可以使用两种不同的设置为设置部分中的测试指定标记:
Both of these settings still work, but they are considered deprecated.
A visible deprecation warning will be added in the future, most likely
in Robot Framework 8.0, and eventually these settings will be removed.
Tools like Tidy can be used to ease transition.
这两种设置仍然有效,但已被弃用。未来将添加可见的弃用警告,最有可能是在Robot Framework 8.0中,最终这些设置将被删除。像Tidy这样的工具可以用来简化过渡。
Updating Force Tags requires only renaming it to Test Tags.
The Default Tags setting will be removed altogether, but the -tag
functionality introduced in Robot Framework 7.0 provides same underlying
functionality. The following examples demonstrate the needed changes.
更新力标记只需要将其重命名为测试标记。默认标签设置将被完全删除,但Robot Framework 7.0中引入的-tag
功能提供了相同的底层功能。以下示例说明了所需的更改。
Old syntax: 旧语法:
*** Settings ***
Force Tags all
Default Tags default
*** Test Cases ***
Common only
[Documentation] Test has tags 'all' and 'default'.
No Operation
No default
[Documentation] Test has only tag 'all'.
[Tags]
No Operation
Own and no default
[Documentation] Test has tags 'all' and 'own'.
[Tags] own
No Operation
New syntax: 新语法:
*** Settings ***
Test Tags all default
*** Test Cases ***
Common only
[Documentation] Test has tags 'all' and 'default'.
No Operation
No default
[Documentation] Test has only tag 'all'.
[Tags] -default
No Operation
Own and no default
[Documentation] Test has tags 'all' and 'own'.
[Tags] own -default
No Operation
Users are generally free to use whatever tags that work in their context.
There are, however, certain tags that have a predefined meaning for Robot
Framework itself, and using them for other purposes can have unexpected
results. All special tags Robot Framework has and will have in the future
have the robot:
prefix. To avoid problems, users should thus not use any
tag with this prefixes unless actually activating the special functionality.
The current reserved tags are listed below, but more such tags are likely
to be added in the future.
用户通常可以自由使用在其上下文中工作的任何标签。然而,某些标签对Robot框架本身具有预定义的含义,将它们用于其他目的可能会产生意想不到的结果。Robot Framework拥有的所有特殊标签以及将来将会拥有的所有特殊标签都有robot:
前缀。为了避免出现问题,用户不应该使用任何带有此前缀的标签,除非实际激活特殊功能。下面列出了当前保留的标签,但将来可能会添加更多这样的标签。
robot:continue-on-failure
and robot:recursive-continue-on-failure
robot:continue-on-failure
和robot:recursive-continue-on-failure
robot:stop-on-failure
and robot:recursive-stop-on-failure
robot:stop-on-failure
和robot:recursive-stop-on-failure
robot:skip-on-failure
robot:skip
robot:exclude
robot:private
robot:no-dry-run
robot:exit
robot:flatten
As of RobotFramework 4.1, reserved tags are suppressed by default in
tag statistics. They will be shown when they are explicitly
included via the --tagstatinclude robot:*
command line option.
从RobotFramework 4.1开始,默认情况下保留标记在标记统计中被抑制。当它们通过--tagstatinclude robot:*
命令行选项显式包含时,将显示它们。
Robot Framework has similar test setup and teardown functionality as many
other test automation frameworks. In short, a test setup is something
that is executed before a test case, and a test teardown is executed
after a test case. In Robot Framework setups and teardowns are just
normal keywords with possible arguments.
Robot Framework具有与许多其他测试自动化框架类似的测试设置和拆卸功能。简而言之,测试设置是在测试用例之前执行的,而测试拆卸是在测试用例之后执行的。在Robot Framework中,setup和teardown只是普通的关键字,可能有参数。
A setup and a teardown are always a single keyword. If they need to take care
of multiple separate tasks, it is possible to create higher-level user
keywords for that purpose. An alternative solution is executing multiple
keywords using the BuiltIn keyword Run Keywords.
设置和拆卸始终是一个关键字。如果他们需要处理多个单独的任务,可以为此目的创建更高级别的用户关键字。另一种解决方案是使用内置关键字Run Keywords执行多个关键字。
The test teardown is special in two ways. First of all, it is executed also
when a test case fails, so it can be used for clean-up activities that must be
done regardless of the test case status. In addition, all the keywords in the
teardown are also executed even if one of them fails. This continue on failure
functionality can be used also with normal keywords, but inside teardowns it is
on by default.
测试拆卸在两个方面是特殊的。首先,它也会在测试用例失败时执行,因此它可以用于无论测试用例状态如何都必须完成的清理活动。此外,teardown中的所有关键字也会被执行,即使其中一个失败。这个失败时继续功能也可以用于普通关键字,但是在teardowns中,它默认是打开的。
The easiest way to specify a setup or a teardown for test cases in a
test case file is using the Test Setup and Test
Teardown settings in the Setting section. Individual test cases can
also have their own setup or teardown. They are defined with the
[Setup] or [Teardown] settings in the test case
section and they override possible Test Setup and
Test Teardown settings. Having no keyword after a
[Setup] or [Teardown] setting means having no
setup or teardown. It is also possible to use value NONE
to indicate that
a test has no setup/teardown.
为测试用例文件中的测试用例指定设置或拆除的最简单方法是使用设置部分中的测试设置和测试拆除设置。单个测试用例也可以有自己的设置或拆卸。它们是用测试用例部分中的[Setup]或[Teardown]设置定义的,它们覆盖可能的测试设置和测试拆卸设置。在[Setup]或[Teardown]设置之后没有关键字意味着没有设置或拆卸。也可以使用值NONE
来指示测试没有设置/拆卸。
*** Settings ***
Test Setup Open Application App A
Test Teardown Close Application
*** Test Cases ***
Default values
[Documentation] Setup and teardown from setting section
Do Something
Overridden setup
[Documentation] Own setup, teardown from setting section
[Setup] Open Application App B
Do Something
No teardown
[Documentation] Default setup, no teardown at all
Do Something
[Teardown]
No teardown 2
[Documentation] Setup and teardown can be disabled also with special value NONE
Do Something
[Teardown] NONE
Using variables
[Documentation] Setup and teardown specified using variables
[Setup] ${SETUP}
Do Something
[Teardown] ${TEARDOWN}
The name of the keyword to be executed as a setup or a teardown can be a
variable. This facilitates having different setups or teardowns in
different environments by giving the keyword name as a variable from
the command line.
要作为设置或拆除执行的关键字的名称可以是一个变量。通过在命令行中将关键字名称作为变量,这有助于在不同的环境中进行不同的设置或拆卸。
Note 注意
Test suites can have a setup and teardown of their
own. A suite setup is executed before any test cases or sub test
suites in that test suite, and similarly a suite teardown is
executed after them.
测试套件可以有自己的设置和拆卸。套件设置在该测试套件中的任何测试用例或子测试套件之前执行,类似地,套件拆卸在它们之后执行。
Test templates convert normal keyword-driven test cases into
data-driven tests. Whereas the body of a keyword-driven test case
is constructed from keywords and their possible arguments, test cases with
template contain only the arguments for the template keyword.
Instead of repeating the same keyword multiple times per test and/or with all
tests in a file, it is possible to use it only per test or just once per file.
测试模板将普通的关键字驱动的测试用例转换为数据驱动的测试。关键字驱动的测试用例的主体是由关键字及其可能的参数构成的,而带有模板的测试用例只包含模板关键字的参数。不是在每个测试和/或文件中的所有测试中多次重复相同的关键字,而是可以只在每个测试或每个文件中使用一次。
Template keywords can accept both normal positional and named arguments, as
well as arguments embedded to the keyword name. Unlike with other settings,
it is not possible to define a template using a variable.
模板关键字可以接受普通的位置参数和命名参数,也可以接受嵌入到关键字名称中的参数。与其他设置不同,无法使用变量定义模板。
How a keyword accepting normal positional arguments can be used as a template
is illustrated by the following example test cases. These two tests are
functionally fully identical.
下面的示例测试用例说明了如何将接受正常位置参数的关键字用作模板。这两个测试在功能上完全相同。
*** Test Cases ***
Normal test case
Example keyword first argument second argument
Templated test case
[Template] Example keyword
first argument second argument
As the example illustrates, it is possible to specify the
template for an individual test case using the [Template]
setting. An alternative approach is using the Test Template
setting in the Setting section, in which case the template is applied
for all test cases in that test case file. The [Template]
setting overrides the possible template set in the Setting section, and
an empty value for [Template] means that the test has no
template even when Test Template is used. It is also possible
to use value NONE
to indicate that a test has no template.
如示例所示,可以使用[Template]设置为单个测试用例指定模板。另一种方法是使用设置部分中的测试模板设置,在这种情况下,模板将应用于该测试用例文件中的所有测试用例。[Template]设置会覆盖设置部分中设置的可能模板,[Template]的空值表示即使使用了测试模板,测试也没有模板。也可以使用值NONE
来指示测试没有模板。
If a templated test case has multiple data rows in its body, the template
is applied for all the rows one by one. This
means that the same keyword is executed multiple times, once with data
on each row. Templated tests are also special so that all the rounds
are executed even if one or more of them fails. It is possible to use this
kind of continue on failure mode with normal tests too, but with
the templated tests the mode is on automatically.
如果模板化的测试用例在其主体中有多个数据行,则模板将逐个应用于所有行。这意味着同一个关键字会被执行多次,每一行上都有数据。模板化测试也很特殊,即使其中一个或多个失败,也会执行所有轮次。在正常测试中也可以使用这种继续失败模式,但是在模板化测试中,模式是自动打开的。
*** Settings ***
Test Template Example keyword
*** Test Cases ***
Templated test case
first round 1 first round 2
second round 1 second round 2
third round 1 third round 2
Using keywords with default values or accepting variable number of arguments,
as well as using named arguments and free named arguments, work with templates
exactly like they work otherwise. Using variables in arguments is also
supported normally.
使用带有默认值的关键字或接受可变数量的参数,以及使用命名参数和自由命名参数,与模板的工作方式完全相同。通常也支持在参数中使用变量。
Templates support a variation of
the embedded argument syntax. With templates this syntax works so
that if the template keyword has variables in its name, they are considered
placeholders for arguments and replaced with the actual arguments
used with the template. The resulting keyword is then used without positional
arguments. This is best illustrated with an example:
模板支持嵌入参数语法的变体。对于模板,这种语法的工作原理是,如果模板关键字在其名称中包含变量,则它们被视为参数的占位符,并被模板使用的实际参数替换。然后使用结果关键字而不使用位置参数。最好用一个例子来说明这一点:
*** Test Cases ***
Normal test case with embedded arguments
The result of 1 + 1 should be 2
The result of 1 + 2 should be 3
Template with embedded arguments
[Template] The result of ${calculation} should be ${expected}
1 + 1 2
1 + 2 3
*** Keywords ***
The result of ${calculation} should be ${expected}
${result} = Calculate ${calculation}
Should Be Equal ${result} ${expected}
When embedded arguments are used with templates, the number of arguments in
the template keyword name must match the number of arguments it is used with.
The argument names do not need to match the arguments of the original keyword,
though, and it is also possible to use different arguments altogether:
当嵌入参数与模板一起使用时,模板关键字名称中的参数数量必须与它一起使用的参数数量相匹配。参数名称不需要与原始关键字的参数匹配,也可以使用不同的参数:
*** Test Cases ***
Different argument names
[Template] The result of ${foo} should be ${bar}
1 + 1 2
1 + 2 3
Only some arguments
[Template] The result of ${calculation} should be 3
1 + 2
4 - 1
New arguments
[Template] The ${meaning} of ${life} should be 42
result 21 * 2
The main benefit of using embedded arguments with templates is that
argument names are specified explicitly. When using normal arguments,
the same effect can be achieved by naming the columns that contain
arguments. This is illustrated by the data-driven style example in
the next section.
在模板中使用嵌入式参数的主要好处是参数名被显式指定。当使用普通参数时,通过命名包含参数的列可以达到相同的效果。下一节中的数据驱动样式示例对此进行了说明。
FOR
loopsFOR
循环的模板If templates are used with FOR loops, the template is applied for
all the steps inside the loop. The continue on failure mode is in use
also in this case, which means that all the steps are executed with
all the looped elements even if there are failures.
如果模板与FOR循环一起使用,则模板将应用于循环内的所有步骤。在这种情况下,也使用继续故障模式,这意味着即使存在故障,也使用所有循环元件执行所有步骤。
*** Test Cases ***
Template with FOR loop
[Template] Example keyword
FOR ${item} IN @{ITEMS}
${item} 2nd arg
END
FOR ${index} IN RANGE 42
1st arg ${index}
END
IF/ELSE
structuresIF/ELSE
结构模板IF/ELSE structures can be also used together with templates.
This can be useful, for example, when used together with FOR loops to
filter executed arguments.
IF/ELSE结构也可以与模板一起使用。例如,当与FOR循环一起使用以过滤执行的参数时,这可能很有用。
*** Test Cases ***
Template with FOR and IF
[Template] Example keyword
FOR ${item} IN @{ITEMS}
IF ${item} < 5
${item} 2nd arg
END
END
There are several different ways in which test cases may be written. Test
cases that describe some kind of workflow may be written either in
keyword-driven or behavior-driven style. Data-driven style can be used to test
the same workflow with varying input data.
编写测试用例有几种不同的方式。描述某种工作流的测试用例可以以关键字驱动或行为驱动的风格编写。数据驱动样式可以用于测试具有不同输入数据的相同工作流。
Workflow tests, such as the Valid Login test described
earlier, are constructed from several keywords and their possible
arguments. Their normal structure is that first the system is taken
into the initial state (Open Login Page in the Valid
Login example), then something is done to the system (Input
Name, Input Password, Submit Credentials), and
finally it is verified that the system behaved as expected
(Welcome Page Should Be Open).
工作流测试(如前面描述的Valid Login测试)是由几个关键字及其可能的参数构造的。它们的正常结构是,首先系统进入初始状态(在有效登录示例中打开登录页面),然后对系统进行操作(输入名称,输入密码,提交凭据),最后验证系统是否按预期运行(欢迎页面应该打开)。
Another style to write test cases is the data-driven approach where
test cases use only one higher-level keyword, often created as a
user keyword, that hides the actual test workflow. These tests are
very useful when there is a need to test the same scenario with
different input and/or output data. It would be possible to repeat the
same keyword with every test, but the test template functionality
allows specifying the keyword to use only once.
编写测试用例的另一种风格是数据驱动方法,其中测试用例仅使用一个更高级别的关键字,通常作为用户关键字创建,隐藏实际的测试工作流。当需要使用不同的输入和/或输出数据测试相同的场景时,这些测试非常有用。可以在每个测试中重复使用相同的关键字,但是测试模板功能允许指定关键字仅使用一次。
*** Settings ***
Test Template Login with invalid credentials should fail
*** Test Cases *** USERNAME PASSWORD
Invalid User Name invalid ${VALID PASSWORD}
Invalid Password ${VALID USER} invalid
Invalid User Name and Password invalid invalid
Empty User Name ${EMPTY} ${VALID PASSWORD}
Empty Password ${VALID USER} ${EMPTY}
Empty User Name and Password ${EMPTY} ${EMPTY}
Tip 尖端
Naming columns like in the example above makes tests easier to
understand. This is possible because on the header row other
cells except the first one are ignored.
像上面的例子中那样的列使测试更容易理解。这是可能的,因为在标题行上,除了第一个单元格之外的其他单元格都被忽略。
The above example has six separate tests, one for each invalid
user/password combination, and the example below illustrates how to
have only one test with all the combinations. When using test
templates, all the rounds in a test are executed even if there are
failures, so there is no real functional difference between these two
styles. In the above example separate combinations are named so it is
easier to see what they test, but having potentially large number of
these tests may mess-up statistics. Which style to use depends on the
context and personal preferences.
上面的示例有六个独立的测试,每个测试对应一个无效的用户/密码组合,下面的示例说明了如何对所有组合只进行一个测试。当使用测试模板时,即使有失败,测试中的所有回合也会执行,因此这两种风格之间没有真实的功能差异。在上面的示例中,单独的组合被命名,因此更容易看到它们测试的内容,但是潜在的大量这些测试可能会混淆统计数据。使用哪种风格取决于上下文和个人喜好。
*** Test Cases ***
Invalid Password
[Template] Login with invalid credentials should fail
invalid ${VALID PASSWORD}
${VALID USER} invalid
invalid whatever
${EMPTY} ${VALID PASSWORD}
${VALID USER} ${EMPTY}
${EMPTY} ${EMPTY}
It is also possible to write test cases as requirements that also non-technical
project stakeholders must understand. These executable requirements are a
corner stone of a process commonly called Acceptance Test Driven Development
(ATDD) or Specification by Example.
也可以编写测试用例作为非技术项目涉众必须理解的需求。这些可执行的需求是一个过程的基石,通常称为验收测试驱动开发(ATDD)或规范的例子。
One way to write these requirements/tests is Given-When-Then style
popularized by Behavior Driven Development (BDD). When writing test cases in
this style, the initial state is usually expressed with a keyword starting with
word Given, the actions are described with keyword starting with
When and the expectations with a keyword starting with Then.
Keyword starting with And or But may be used if a step has more
than one action.
编写这些需求/测试的一种方法是由行为驱动开发(BDD)推广的Given-When-Then风格。当以这种风格编写测试用例时,初始状态通常用以Given开头的关键字表示,动作用以When开头的关键字描述,期望用以Then开头的关键字描述。如果步骤具有多个操作,则可以使用以And或But开头的关键字。
*** Test Cases ***
Valid Login
Given login page is open
When valid username and password are inserted
and credentials are submitted
Then welcome page should be open
Prefixes Given, When, Then, And and But
are dropped when matching keywords are searched, if no match with the full name
is found. This works for both user keywords and library keywords. For example,
Given login page is open in the above example can be implemented as
user keyword either with or without the word Given. Ignoring prefixes
also allows using the same keyword with different prefixes. For example
Welcome page should be open could also used as And welcome page
should be open.
如果未找到与全名匹配的关键字,则在搜索匹配关键字时删除前缀Given、When、Then、And和But。这对用户关键字和库关键字都有效。例如,在上面的例子中,Given登录页面是打开的,可以实现为带有或不带有Given这个词的用户关键字。忽略前缀还允许使用具有不同前缀的相同关键字。例如,欢迎页面应该打开也可以用作和欢迎页面应该打开。
Note 注意
These prefixes can be localized. See the Translations appendix
for supported translations.
这些前缀可以本地化。有关支持的翻译,请参见翻译附录。
When writing concrete examples it is useful to be able to pass actual data to
keyword implementations. User keywords support this by allowing embedding
arguments into keyword name.
在编写具体示例时,能够将实际数据传递给关键字实现是很有用的。用户关键字通过允许将参数嵌入到关键字名称中来支持这一点。
In addition to test automation, Robot Framework can be used for other
automation purposes, including robotic process automation (RPA).
It has always been possible, but Robot Framework 3.1 added official
support for automating tasks, not only tests. For most parts creating
tasks works the same way as creating tests and the only real difference
is in terminology. Tasks can also be organized into suites exactly like
test cases.
除了测试自动化,Robot Framework还可以用于其他自动化目的,包括机器人流程自动化(RPA)。这一直是可能的,但Robot Framework 3.1增加了对自动化任务的官方支持,而不仅仅是测试。在大多数情况下,创建任务的工作方式与创建测试的工作方式相同,唯一真实的区别在于术语。任务也可以像测试用例一样组织成套件。
Tasks are created based on the available keywords exactly like test cases,
and the task syntax is in general identical to the test case syntax.
The main difference is that tasks are created in Task sections
instead of Test Case sections:
任务是基于可用的关键字创建的,就像测试用例一样,任务语法通常与测试用例语法相同。主要区别在于任务是在任务部分而不是测试用例部分中创建的:
*** Tasks ***
Process invoice
Read information from PDF
Validate information
Submit information to backend system
Validate information is visible in web UI
It is an error to have both tests and tasks in same file.
将测试和任务放在同一个文件中是错误的。
Robot Framework test cases are created in test case files, which can
be organized into directories. These files and directories create a
hierarchical test suite structure. Same concepts apply also when
creating tasks, but the terminology differs.
Robot Framework测试用例在测试用例文件中创建,这些文件可以组织到目录中。这些文件和目录创建了一个层次化的测试套件结构。创建任务时也适用相同的概念,但术语不同。
Robot Framework test cases are created using test case sections in
suite files, also known as test case files. Such a file automatically creates
a test suite from
all the test cases it contains. There is no upper limit for how many
test cases there can be, but it is recommended to have less than ten,
unless the data-driven approach is used, where one test case consists of
only one high-level keyword.
Robot Framework测试用例是使用套件文件(也称为测试用例文件)中的测试用例部分创建的。这样一个文件自动地从它包含的所有测试用例中创建一个测试套件。测试用例的数量没有上限,但建议少于10个,除非使用数据驱动方法,其中一个测试用例仅由一个高级关键字组成。
The following settings in the Setting section can be used to customize the suite:
设置部分中的以下设置可用于自定义套件:
Note 注意
Setting names are case-insensitive, but the format used above is recommended.
设置名称不区分大小写,但建议使用上述格式。
Test case files can be organized into directories, and these
directories create higher-level test suites. A test suite created from
a directory cannot have any test cases directly, but it contains
other test suites with test cases, instead. These directories can then be
placed into other directories creating an even higher-level suite. There
are no limits for the structure, so test cases can be organized
as needed.
测试用例文件可以组织到目录中,这些目录创建更高级别的测试套件。从目录中创建的测试套件不能直接包含任何测试用例,但它包含其他测试套件和测试用例。然后,这些目录可以放置到其他目录中,从而创建更高级别的套件。对结构没有限制,因此可以根据需要组织测试用例。
When a test directory is executed, the files and directories it
contains are processed recursively as follows:
当执行测试目录时,它包含的文件和目录将被递归处理,如下所示:
If a file or directory that is processed does not contain any test
cases, it is silently ignored (a message is written to the syslog)
and the processing continues.
如果被处理的文件或目录不包含任何测试用例,则会默默忽略它(将消息写入系统日志),并继续处理。
A test suite created from a directory can have similar settings as a suite
created from a test case file. Because a directory alone cannot have that
kind of information, it must be placed into a special test suite initialization
file. An initialization file name must always be of the format
__init__.ext, where the extension must be one of the supported
file formats (typically __init__.robot).
The name format is borrowed from Python, where files named in this manner
denote that a directory is a module.
从目录创建的测试套件可以具有与从测试用例文件创建的套件类似的设置。由于单独的目录无法包含此类信息,因此必须将其放入特殊的测试套件初始化文件中。初始化文件名必须始终为__init__. ext格式,其中扩展名必须是支持的文件格式之一(通常为__init__.robot)。名称格式借用自Python,其中以这种方式命名的文件表示目录是一个模块。
Starting from Robot Framework 6.1, it is also possible to define a suite
initialization file for automatically created suite when starting the test
execution by giving multiple paths.
从Robot Framework 6.1开始,还可以通过给定多个路径,在开始执行测试时为自动创建的套件定义套件初始化文件。
Initialization files have the same structure and syntax as test case files,
except that they cannot have test case sections and not all settings are
supported. Variables and keywords created or imported in initialization files
are not available in the lower level test suites. If you need to share
variables or keywords, you can put them into resource files that can be
imported both by initialization and test case files.
测试用例文件具有与测试用例文件相同的结构和语法,只是它们不能具有测试用例节,并且不支持所有设置。在初始化文件中创建或导入的变量和关键字在较低级别的测试套件中不可用。如果您需要共享变量或关键字,您可以将它们放入可以由初始化和测试用例文件导入的资源文件中。
The main usage for initialization files is specifying test suite related
settings similarly as in suite files, but setting some test case
related settings is also possible. How to use different settings in the
initialization files is explained below.
初始化文件的主要用途是指定测试套件相关的设置,类似于套件文件,但也可以设置一些测试用例相关的设置。下面将解释如何在初始化文件中使用不同的设置。
*** Settings ***
Documentation Example suite
Suite Setup Do Something ${MESSAGE}
Test Tags example
Library SomeLibrary
*** Variables ***
${MESSAGE} Hello, world!
*** Keywords ***
Do Something
[Arguments] ${args}
Some Keyword ${arg}
Another Keyword
The test suite name is constructed from the file or directory name by default.
The name is created so that the extension is ignored, possible underscores are
replaced with spaces, and names fully in lower case are title cased. For
example, some_tests.robot becomes Some Tests and
My_test_directory becomes My test directory.
默认情况下,测试套件名称是从文件或目录名称构造的。创建名称时,扩展名将被忽略,可能的下划线将被替换为空格,完全小写的名称将采用标题大小写。例如,some_tests.robot将变为Some Tests,My_test_directory将变为My test目录。
The file or directory name can contain a prefix to control the execution
order of the suites. The prefix is separated from the base name by two
underscores and, when constructing the actual test suite name, both
the prefix and underscores are removed. For example files
01__some_tests.robot and 02__more_tests.robot create test
suites Some Tests and More Tests, respectively, and
the former is executed before the latter.
文件名或目录名可以包含前缀,以控制套件的执行顺序。前缀与基本名称之间用两个下划线分隔,在构造实际的测试套件名称时,前缀和下划线都被删除。例如,文件01__some_tests.robot和02__more_tests.robot分别创建测试套件Some Tests和More Tests,前者在后者之前执行。
Starting from Robot Framework 6.1, it is also possible to give a custom name
to a suite by using the Name setting in the Setting section:
从Robot Framework 6.1开始,还可以通过使用设置部分中的名称设置为套件提供自定义名称:
*** Settings ***
Name Custom suite name
The name of the top-level suite can be overridden from the command line with
the --name option.
可以在命令行中使用--name选项覆盖顶级套件的名称。
The documentation for a test suite is set using the Documentation
setting in the Settings section. It can be used both in suite files
and in suite initialization files. Suite documentation has exactly
the same characteristics regarding to where it is shown and how it can
be created as test case documentation. For details about the syntax
see the Documentation formatting appendix.
测试套件的文档是使用设置部分中的文档设置来设置的。它可以在套件文件和套件初始化文件中使用。套件文档在显示位置和如何创建测试用例文档方面具有完全相同的特性。有关语法的详细信息,请参见文档格式附录。
*** Settings ***
Documentation An example suite documentation with *some* _formatting_.
... Long documentation can be split into multiple lines.
The documentation of the top-level suite can be overridden from
the command line with the --doc option.
可以使用--doc选项从命令行覆盖顶级套件的文档。
In addition to documentation, suites can also have free metadata. This metadata
is defined as name-value pairs in the Settings section using the Metadata
setting. It is shown in reports and logs similarly as documentation.
除了文档之外,套件还可以有免费的元数据。此元数据在“设置”部分中使用“元数据”设置定义为名称-值对。它显示在报告和日志中,类似于文档。
Name of the metadata is the first argument given to the Metadata setting
and the remaining arguments specify its value. The value is handled similarly as
documentation, which means that it supports HTML formatting and variables, and
that longer values can be split into multiple rows.
元数据的名称是提供给元数据设置的第一个参数,其余参数指定其值。该值的处理方式与文档类似,这意味着它支持HTML格式和变量,并且可以将较长的值拆分为多行。
*** Settings ***
Metadata Version 2.0
Metadata Robot Framework http://robotframework.org
Metadata Platform ${PLATFORM}
Metadata Longer Value
... Longer metadata values can be split into multiple
... rows. Also *simple* _formatting_ is supported.
The free metadata of the top-level suite can be set from
the command line with the --metadata option.
顶级套件的自由元数据可以通过命令行中的--metadata选项进行设置。
Not only test cases but also test suites can have a setup and
a teardown. A suite setup is executed before running any of the suite's
test cases or child test suites, and a suite teardown is executed after
them. All test suites can have a setup and a teardown; with suites created
from a directory they must be specified in a suite initialization file.
不仅测试用例,而且测试套件都可以有一个设置和一个拆卸。在运行套件的任何测试用例或子测试套件之前,执行套件设置,并在它们之后执行套件拆卸。所有的测试套件都可以有一个设置和一个拆卸;对于从目录中创建的套件,它们必须在套件初始化文件中指定。
Similarly as with test cases, a suite setup and teardown are keywords
that may take arguments. They are defined in the Setting section with
Suite Setup and Suite Teardown settings,
respectively. Keyword names and possible arguments are located in
the columns after the setting name.
与测试用例类似,套件设置和拆卸是可以带参数的关键字。它们分别在“设置”部分的“套件设置”和“套件拆卸”设置中定义。关键字名称和可能的参数位于设置名称之后的列中。
If a suite setup fails, all test cases in it and its child test suites
are immediately assigned a fail status and they are not actually
executed. This makes suite setups ideal for checking preconditions
that must be met before running test cases is possible.
如果一个套件设置失败了,它和它的子测试套件中的所有测试用例都会立即被分配一个失败状态,并且它们不会被实际执行。这使得套件设置非常适合于检查在运行测试用例之前必须满足的先决条件。
A suite teardown is normally used for cleaning up after all the test
cases have been executed. It is executed even if the setup of the same
suite fails. If the suite teardown fails, all test cases in the
suite are marked failed, regardless of their original execution status.
Note that all the keywords in suite teardowns are executed even if one
of them fails.
套件拆卸通常用于在所有测试用例执行之后进行清理。即使同一套件的设置失败,也会执行该命令。如果套件拆卸失败,套件中的所有测试用例都标记为失败,而不管它们的原始执行状态如何。请注意,即使其中一个失败,也会执行套件拆卸中的所有关键字。
The name of the keyword to be executed as a setup or a teardown can be
a variable. This facilitates having different setups or teardowns
in different environments by giving the keyword name as a variable
from the command line.
要作为设置或拆除执行的关键字的名称可以是一个变量。通过在命令行中将关键字名称作为变量,这有助于在不同的环境中进行不同的设置或拆卸。
Test libraries contain those lowest-level keywords, often called
library keywords, which actually interact with the system under
test. All test cases always use keywords from some library, often
through higher-level user keywords. This section explains how to
take test libraries into use and how to use the keywords they
provide. Creating test libraries is described in a separate
section.
测试库包含那些最低级别的关键字,通常称为库关键字,它们实际上与被测系统交互。所有的测试用例总是使用一些库中的关键字,通常是通过更高级别的用户关键字。本节解释如何使用测试库以及如何使用它们提供的关键字。创建测试库将在单独的一节中描述。
Test libraries are typically imported using the Library setting,
but it is also possible to use the Import Library keyword.
测试库通常使用Library设置导入,但也可以使用ImportLibrary关键字。
Library
setting库
设置Test libraries are normally imported using the Library
setting in the Setting section and having the library name in the
subsequent column. Unlike most of the other data, the library name
is both case- and space-sensitive. If a library is in a package,
the full name including the package name must be used.
测试库通常使用“设置”部分中的“库”设置导入,并在随后的列中使用库名称。与大多数其他数据不同,库名称对大小写和空格都很敏感。如果库在包中,则必须使用包括包名称在内的全名。
In those cases where the library needs arguments, they are listed in
the columns after the library name. It is possible to use default
values, variable number of arguments, and named arguments in test
library imports similarly as with arguments to keywords. Both the
library name and arguments can be set using variables.
在库需要参数的情况下,这些参数列在库名称后面的列中。可以在测试库导入中使用默认值、可变数量的参数和命名参数,这与关键字的参数类似。库名称和参数都可以使用变量设置。
*** Settings ***
Library OperatingSystem
Library my.package.TestLibrary
Library MyLibrary arg1 arg2
Library ${LIBRARY}
It is possible to import test libraries in suite files,
resource files and suite initialization files. In all these
cases, all the keywords in the imported library are available in that
file. With resource files, those keywords are also available in other
files using them.
可以在套件文件、资源文件和套件初始化文件中导入测试库。在所有这些情况下,导入库中的所有关键字都可以在该文件中使用。对于资源文件,这些关键字也可以在使用它们的其他文件中使用。
Import Library
keyword导入库
关键字Another possibility to take a test library into use is using the
keyword Import Library from the BuiltIn library. This keyword
takes the library name and possible arguments similarly as the
Library setting. Keywords from the imported library are
available in the test suite where the Import Library keyword was
used. This approach is useful in cases where the library is not
available when the test execution starts and only some other keywords
make it available.
使用测试库的另一种可能性是使用关键字从内置库导入库。此关键字采用与Library设置类似的库名称和可能的参数。导入库中的关键字在使用了ImportLibrary关键字的测试套件中可用。这种方法在测试执行开始时库不可用并且只有一些其他关键字使其可用的情况下很有用。
*** Test Cases ***
Example
Do Something
Import Library MyLibrary arg1 arg2
KW From MyLibrary
Libraries to import can be specified either by using the library name
or the path to the library. These approaches work the same way regardless
if the library is imported using the Library setting or the
Import Library keyword.
可以使用库名称或库的路径指定要导入的库。无论库是使用Library设置还是使用Import Library关键字导入的,这些方法的工作方式都是相同的。
The most common way to specify a test library to import is using its
name, like it has been done in all the examples in this section. In
these cases Robot Framework tries to find the class or module
implementing the library from the module search path. Libraries that
are installed somehow ought to be in the module search path automatically,
but with other libraries the search path may need to be configured separately.
指定要导入的测试库的最常见方法是使用其名称,就像本节中所有示例中所做的那样。在这些情况下,Robot Framework会尝试从模块搜索路径中查找实现库的类或模块。以某种方式安装的库应该自动在模块搜索路径中,但对于其他库,搜索路径可能需要单独配置。
The biggest benefit of this approach is that when the module search
path has been configured, often using a custom start-up script,
normal users do not need to think where libraries actually are
installed. The drawback is that getting your own, possible
very simple, libraries into the search path may require some
additional configuration.
这种方法的最大好处是,当模块搜索路径已经配置好(通常使用自定义启动脚本)时,普通用户不需要考虑库实际安装的位置。缺点是,要将您自己的库(可能非常简单)放入搜索路径中,可能需要一些额外的配置。
Another mechanism for specifying the library to import is using a
path to it in the file system. This path is considered relative to the
directory where current test data file is situated similarly as paths
to resource and variable files. The main benefit of this approach
is that there is no need to configure the module search path.
指定要导入的库的另一种机制是在文件系统中使用库的路径。该路径被视为相对于当前测试数据文件所在的目录,类似于资源和变量文件的路径。这种方法的主要好处是不需要配置模块搜索路径。
If the library is a file, the path to it must contain extension,
i.e. .py. If a library is implemented
as a directory, the path to it must have a trailing forward slash (/
)
if the path is relative. With absolute paths the trailing slash is optional.
Following examples demonstrate these different usages.
如果库是一个文件,则它的路径必须包含扩展名,即.py。如果一个库是作为一个目录实现的,那么如果路径是相对的,那么它的路径后面必须有一个正斜杠(/
)。对于绝对路径,尾部斜线是可选的。下面的例子展示了这些不同的用法。
*** Settings ***
Library PythonLibrary.py
Library relative/path/PythonDirLib/ possible arguments
Library ${RESOURCES}/Example.class
A limitation of this approach is that libraries implemented as Python classes must
be in a module with the same name as the class.
这种方法的一个局限性是,作为Python类实现的库必须位于与类同名的模块中。
The library name is shown in test logs before keyword names, and if
multiple keywords have the same name, they must be used so that the
keyword name is prefixed with the library name. The library name
is got normally from the module or class name implementing it, but
there are some situations where changing it is desirable:
库名称显示在测试日志中关键字名称之前,如果多个关键字具有相同的名称,则必须使用它们,以便关键字名称以库名称为前缀。库名称通常从实现它的模块或类名获得,但在某些情况下需要更改它:
The basic syntax for specifying the new name is having the text
AS
(case-sensitive) after the library name and then
having the new name after that. The specified name is shown in
logs and must be used in the test data when using keywords' full name
(LibraryName.Keyword Name).
指定新名称的基本语法是在库名称之后加上文本AS
(区分大小写),然后再加上新名称。指定的名称显示在日志中,并且在使用关键字的全名(LibraryName. KeywordName)时必须在测试数据中使用。
*** Settings ***
Library packagename.TestLib AS TestLib
Library ${LIBRARY} AS MyName
Possible arguments to the library are placed between the
original library name and the AS
marker. The following example
illustrates how the same library can be imported several times with
different arguments:
库的可能参数放置在原始库名称和AS
标记之间。下面的示例说明了如何使用不同的参数多次导入同一个库:
*** Settings ***
Library SomeLibrary localhost 1234 AS LocalLib
Library SomeLibrary server.domain 8080 AS RemoteLib
*** Test Cases ***
Example
LocalLib.Some Keyword some arg second arg
RemoteLib.Some Keyword another arg whatever
LocalLib.Another Keyword
Setting a custom name to a test library works both when importing a
library in the Setting section and when using the Import Library keyword.
在“设置”部分中导入库和使用“导入库”关键字时,都可以为测试库设置自定义名称。
Note 注意
Prior to Robot Framework 6.0 the marker to use when giving a custom name
to a library was WITH NAME
instead of AS
. The old syntax continues
to work, but it is considered deprecated and will eventually be removed.
在Robot Framework 6.0之前,为库提供自定义名称时使用的标记是WITH NAME
而不是AS
。旧的语法继续工作,但它被认为是过时的,最终将被删除。
Some test libraries are distributed with Robot Framework and these
libraries are called standard libraries. The BuiltIn library is special,
because it is taken into use automatically and thus its keywords are always
available. Other standard libraries need to be imported in the same way
as any other libraries, but there is no need to install them.
一些测试库是随Robot Framework发布的,这些库被称为标准库。BuiltIn库是特殊的,因为它是自动使用的,因此它的关键字总是可用的。其他标准库需要以与任何其他库相同的方式导入,但不需要安装它们。
The available normal standard libraries are listed below with links to their
documentations:
下面列出了可用的常规标准库及其文档链接:
In addition to the normal standard libraries listed above, there is
also Remote library that is totally different than the other standard
libraries. It does not have any keywords of its own but it works as a
proxy between Robot Framework and actual test library implementations.
These libraries can be running on other machines than the core
framework and can even be implemented using languages not supported by
Robot Framework natively.
除了上面列出的标准库之外,还有一个与其他标准库完全不同的远程库。它本身没有任何关键字,但它可以作为Robot Framework和实际测试库实现之间的代理。这些库可以在核心框架之外的其他机器上运行,甚至可以使用Robot Framework本机不支持的语言实现。
See separate Remote library interface section for more information
about this concept.
有关此概念的更多信息,请参见单独的远程库接口部分。
Any test library that is not one of the standard libraries is, by
definition, an external library. The Robot Framework open source community
has implemented several generic libraries, such as SeleniumLibrary and
SwingLibrary, which are not packaged with the core framework. A list of
publicly available libraries can be found from http://robotframework.org.
根据定义,任何不是标准库的测试库都是外部库。Robot Framework开源社区已经实现了几个通用库,如SeleniumLibrary和SwingLibrary,它们没有与核心框架打包在一起。可以从http://robotframework.org找到公开可用的库列表。
Generic and custom libraries can obviously also be implemented by teams using
Robot Framework. See Creating test libraries section for more information
about that topic.
通用和自定义库显然也可以由使用Robot Framework的团队实现。有关该主题的更多信息,请参见创建测试库部分。
Different external libraries can have a totally different mechanism
for installing them and taking them into use. Sometimes they may also require
some other dependencies to be installed separately. All libraries
should have clear installation and usage documentation and they should
preferably automate the installation process.
不同的外部库可以有完全不同的机制来安装和使用它们。有时候,它们可能还需要单独安装一些其他依赖项。所有库都应该有清晰的安装和使用文档,并且最好能够自动化安装过程。
Variables are an integral feature of Robot Framework, and they can be
used in most places in test data. Most commonly, they are used in
arguments for keywords in Test Case and Keyword sections, but
also all settings allow variables in their values. A normal keyword
name cannot be specified with a variable, but the BuiltIn keyword
Run Keyword can be used to get the same effect.
变量是Robot Framework不可或缺的特性,它们可以在测试数据中的大多数地方使用。最常见的是,它们用于测试用例和关键字部分中关键字的参数中,但所有设置都允许在其值中使用变量。普通的关键字名称不能用变量来指定,但是BuiltIn关键字Run Keyword可以用来获得相同的效果。
Robot Framework has its own variables that can be used as scalars, lists
or dictionaries using syntax ${SCALAR}
, @{LIST}
and &{DICT}
,
respectively. In addition to this, environment variables can be used
directly with syntax %{ENV_VAR}
.
Robot Framework有自己的变量,可以分别使用语法${SCALAR}
、@{LIST}
和&{DICT}
用作标量、列表或字典。除此之外,环境变量可以直接与语法%{ENV_VAR}一起
使用。
Variables are useful, for example, in these cases:
变量是有用的,例如,在这些情况下:
${RESOURCES}
instead of c:\resources
, or ${HOST}
instead of 10.0.0.1:8080
). Because variables can be set from the
command line when tests are started, changing system-specific
variables is easy (for example, --variable HOST:10.0.0.2:1234
--variable RESOURCES:/opt/resources
). This also facilitates
localization testing, which often involves running the same tests
with different strings.${RESOURCES}
而不是c:\resources
,或${HOST}
而不是10.0.0.1:8080
)。因为可以在测试开始时从命令行设置变量,所以更改系统特定的变量很容易(例如,--variable HOST:10.0.0.2:1234--variable RESOURCES:/opt/resources
)。这也方便了本地化测试,本地化测试通常涉及使用不同的字符串运行相同的测试。${URL}
is shorter than
http://long.domain.name:8080/path/to/service?foo=1&bar=2&zap=42
.${URL}
比www.example.com短http://long.domain.name:8080/path/to/service? foo=1& bar=2& zap=42
.If a non-existent variable is used in the test data, the keyword using
it fails. If the same syntax that is used for variables is needed as a
literal string, it must be escaped with a backslash as in \${NAME}
.
如果在测试数据中使用了不存在的变量,则使用该变量的关键字将失败。如果需要将用于变量的相同语法作为文字字符串,则必须使用反斜杠对其进行转义,如\${NAME}
中所示。
This section explains how to use variables, including the normal scalar
variable syntax ${var}
, how to use variables in list and dictionary
contexts like @{var}
and &{var}
, respectively, and how to use environment
variables like %{var}
. Different ways how to create variables are discussed
in the subsequent sections.
本节解释如何使用变量,包括普通标量变量语法${var}
,如何分别在列表和字典上下文中使用变量,如@{var}
和&{var}
,以及如何使用环境变量,如%{var}
。如何创建变量的不同方法将在后续部分中讨论。
Robot Framework variables, similarly as keywords, are
case-insensitive, and also spaces and underscores are
ignored. However, it is recommended to use capital letters with
global variables (for example, ${PATH}
or ${TWO WORDS}
)
and small letters with local variables that are only available in certain
test cases or user keywords (for example, ${my var}
). Much more
importantly, though, case should be used consistently.
Robot Framework变量与关键字类似,不区分大小写,空格和下划线也会被忽略。但是,建议在全局变量中使用大写字母(例如,${PATH}
或${TWO WORDS}
),在局部变量中使用小写字母(仅在某些测试用例或用户关键字中可用,例如,${my var}
)。但更重要的是,应该始终如一地使用case。
Variable name consists of the variable type identifier ($
, @
, &
, %
),
curly braces ({
, }
) and the actual variable name between the braces.
Unlike in some programming languages where similar variable syntax is
used, curly braces are always mandatory. Variable names can basically have
any characters between the curly braces. However, using only alphabetic
characters from a to z, numbers, underscore and space is recommended, and
it is even a requirement for using the extended variable syntax.
变量名由变量类型标识符($
,@
,,%
)、大括号({
,}
)和大括号之间的实际变量名组成。与使用类似变量语法的某些编程语言不同,花括号始终是强制性的。变量名基本上可以在花括号之间包含任何字符。但是,建议只使用从a到z的字母字符、数字、下划线和空格,甚至是使用扩展变量语法的要求。
The most common way to use variables in Robot Framework test data is using
the scalar variable syntax like ${var}
. When this syntax is used, the
variable name is replaced with its value as-is. Most of the time variable
values are strings, but variables can contain any object, including numbers,
lists, dictionaries, or even custom objects.
在Robot Framework测试数据中使用变量的最常见方式是使用标量变量语法,如${var}
。当使用此语法时,变量名将被替换为它的值。大多数时候,变量值是字符串,但变量可以包含任何对象,包括数字、列表、字典,甚至是自定义对象。
The example below illustrates the usage of scalar variables. Assuming
that the variables ${GREET}
and ${NAME}
are available
and assigned to strings Hello
and world
, respectively,
both the example test cases are equivalent.
下面的例子说明了标量变量的用法。假设变量${GREET}
和${NAME}
是可用的,并且分别被分配给字符串Hello
和world
,那么这两个示例测试用例是等效的。
*** Test Cases ***
Constants
Log Hello
Log Hello, world!!
Variables
Log ${GREET}
Log ${GREET}, ${NAME}!!
When a scalar variable is used alone without any text or other variables
around it, like in ${GREET}
above, the variable is replaced with
its value as-is and the value can be any object. If the variable is not used
alone, like ${GREER}, ${NAME}!!
above, its value is first converted into
a string and then concatenated with the other data.
当标量变量单独使用时,周围没有任何文本或其他变量,如上面的${GREET}
中,变量将被替换为其值,并且值可以是任何对象。如果变量不是单独使用,如${GREER}、${NAME}!!
在上面的示例中,它的值首先被转换为字符串,然后与其他数据连接。
Note 注意
Variable values are used as-is without conversions also when
passing arguments to keywords using the named arguments
syntax like argname=${var}
.
当使用命名参数语法(如argname=${var})
将参数传递给关键字时,变量值也按原样使用,不进行转换。
The example below demonstrates the difference between having a
variable in alone or with other content. First, let us assume
that we have a variable ${STR}
set to a string Hello,
world!
and ${OBJ}
set to an instance of the following Python
object:
下面的示例演示了单独或与其他内容一起使用变量之间的区别。首先,让我们假设我们有一个变量${STR}
设置为字符串Hello,world!
并将${OBJ}
设置为以下Python对象的实例:
class MyObj:
def __str__():
return "Hi, terra!"
With these two variables set, we then have the following test data:
有了这两个变量,我们就有了以下测试数据:
*** Test Cases ***
Objects
KW 1 ${STR}
KW 2 ${OBJ}
KW 3 I said "${STR}"
KW 4 You said "${OBJ}"
Finally, when this test data is executed, different keywords receive
the arguments as explained below:
最后,当这个测试数据被执行时,不同的关键字接收参数,如下所述:
Hello, world!
Hello,world!
${OBJ}
${OBJ}
的对象I said "Hello, world!"
我说“你好,世界!"
You said "Hi, terra!"
你说“嗨,泰拉!"
Note 注意
Converting variables to Unicode obviously fails if the variable
cannot be represented as Unicode. This can happen, for example,
if you try to use byte sequences as arguments to keywords so that
you catenate the values together like ${byte1}${byte2}
.
A workaround is creating a variable that contains the whole value
and using it alone in the cell (e.g. ${bytes}
) because then
the value is used as-is.
如果变量不能表示为Unicode,那么将变量转换为Unicode显然会失败。例如,如果您尝试使用字节序列作为关键字的参数,以便将值串联在一起(如${byte 1}${byte 2}),则
可能会发生这种情况。解决方法是创建一个包含整个值的变量,并在单元格中单独使用它(例如,${bytes}
),因为这样值就可以按原样使用。
When a variable is used as a scalar like ${EXAMPLE}
, its value is be
used as-is. If a variable value is a list or list-like, it is also possible
to use it as a list variable like @{EXAMPLE}
. In this case the list is expanded
and individual items are passed in as separate arguments. This is easiest to explain
with an example. Assuming that a variable @{USER}
has value ['robot', 'secret']
,
the following two test cases are equivalent:
当一个变量被用作标量时,如${EXAMPLE}
,它的值将按原样使用。如果变量值是列表或类似列表的,也可以将其用作列表变量,如@{EXAMPLE}
。在这种情况下,列表被展开,各个项作为单独的参数传入。这是最容易解释的一个例子。假设变量@{USER}
的值为“robot”,“secret”]
,则以下两个测试用例是等效的:
*** Test Cases ***
Constants
Login robot secret
List Variable
Login @{USER}
Robot Framework stores its own variables in one internal storage and allows
using them as scalars, lists or dictionaries. Using a variable as a list
requires its value to be a Python list or list-like object. Robot Framework
does not allow strings to be used as lists, but other iterable objects such
as tuples or dictionaries are accepted.
Robot Framework将自己的变量存储在一个内部存储器中,并允许将它们用作标量,列表或字典。使用变量作为列表要求其值是Python列表或类似列表的对象。Robot Framework不允许将字符串用作列表,但接受其他可迭代对象,如元组或字典。
Starting from Robot Framework 4.0, list expansion can be used in combination with
list item access making these usages possible:
从Robot Framework 4.0开始,列表扩展可以与列表项访问结合使用,使以下用途成为可能:
*** Test Cases ***
Nested container
${nested} = Evaluate [['a', 'b', 'c'], {'key': ['x', 'y']}]
Log Many @{nested}[0] # Logs 'a', 'b' and 'c'.
Log Many @{nested}[1][key] # Logs 'x' and 'y'.
Slice
${items} = Create List first second third
Log Many @{items}[1:] # Logs 'second' and 'third'.
It is possible to use list variables with other arguments, including
other list variables.
可以将列表变量与其他参数一起使用,包括其他列表变量。
*** Test Cases ***
Example
Keyword @{LIST} more args
Keyword ${SCALAR} @{LIST} constant
Keyword @{LIST} @{ANOTHER} @{ONE MORE}
List variables can be used only with some of the settings. They can
be used in arguments to imported libraries and variable files, but
library and variable file names themselves cannot be list
variables. Also with setups and teardowns list variable can not be used
as the name of the keyword, but can be used in arguments. With tag related
settings they can be used freely. Using scalar variables is possible in
those places where list variables are not supported.
列表变量只能与某些设置一起使用。它们可以在导入库和变量文件的参数中使用,但库和变量文件名本身不能是列表变量。另外在setups和teardowns中列表变量不能用作关键字的名称,但可以用在参数中。通过与标签相关的设置,它们可以自由使用。在不支持列表变量的地方可以使用标量变量。
*** Settings ***
Library ExampleLibrary @{LIB ARGS} # This works
Library ${LIBRARY} @{LIB ARGS} # This works
Library @{LIBRARY AND ARGS} # This does not work
Suite Setup Some Keyword @{KW ARGS} # This works
Suite Setup ${KEYWORD} @{KW ARGS} # This works
Suite Setup @{KEYWORD AND ARGS} # This does not work
Default Tags @{TAGS} # This works
As discussed above, a variable containing a list can be used as a list
variable to pass list items to a keyword as individual arguments.
Similarly a variable containing a Python dictionary or a dictionary-like
object can be used as a dictionary variable like &{EXAMPLE}
. In practice
this means that the dictionary is expanded and individual items are passed as
named arguments to the keyword. Assuming that a variable &{USER}
has
value {'name': 'robot', 'password': 'secret'}
, the following two test cases
are equivalent.
如上所述,包含列表的变量可以用作列表变量,以将列表项作为单独的参数传递给关键字。类似地,包含Python字典或类似字典的对象的变量可以用作字典变量,如&{EXAMPLE}
。在实践中,这意味着字典被展开,单个项作为命名参数传递给关键字。假设变量&{USER}
的值为“name”:“robot”,“password”:“secret”}
,则以下两个测试用例是等效的。
*** Test Cases ***
Constants
Login name=robot password=secret
Dict Variable
Login &{USER}
Starting from Robot Framework 4.0, dictionary expansion can be used in combination with
dictionary item access making usages like &{nested}[key]
possible.
从Robot Framework 4.0开始,字典扩展可以与字典项访问结合使用,使&{nested}[key]
等用法成为可能。
It is possible to use dictionary variables with other arguments, including
other dictionary variables. Because named argument syntax requires positional
arguments to be before named argument, dictionaries can only be followed by
named arguments or other dictionaries.
可以将字典变量与其他参数一起使用,包括其他字典变量。因为命名参数语法要求位置参数在命名参数之前,所以字典后面只能跟命名参数或其他字典。
*** Test Cases ***
Example
Keyword &{DICT} named=arg
Keyword positional @{LIST} &{DICT}
Keyword &{DICT} &{ANOTHER} &{ONE MORE}
Dictionary variables cannot generally be used with settings. The only exception
are imports, setups and teardowns where dictionaries can be used as arguments.
字典变量通常不能与设置一起使用。唯一的例外是导入、设置和拆卸,其中字典可以用作参数。
*** Settings ***
Library ExampleLibrary &{LIB ARGS}
Suite Setup Some Keyword &{KW ARGS} named=arg
It is possible to access items of subscriptable variables, e.g. lists and dictionaries,
using special syntax like ${var}[item]
or ${var}[nested][item]
.
Starting from Robot Framework 4.0, it is also possible to use item access together with
list expansion and dictionary expansion by using syntax @{var}[item]
and
&{var}[item]
, respectively.
可以使用特殊的语法,如${var}[item]
或${var}[nested][item]
来访问可订阅变量的项,例如列表和字典。从Robot Framework 4.0开始,还可以分别使用语法@{var}[item]
和&{var}[item]
将项访问与列表扩展和字典扩展一起使用。
Note 注意
Prior to Robot Framework 3.1 the normal item access syntax was @{var}[item]
with lists and &{var}[item]
with dictionaries. Robot Framework 3.1 introduced
the generic ${var}[item]
syntax along with some other nice enhancements and
the old item access syntax was deprecated in Robot Framework 3.2.
在Robot Framework 3.1之前,正常的项访问语法是@{var}[item]
(列表)和&{var}[item]
(字典)。Robot Framework 3.1引入了通用的${var}[item]
语法沿着以及一些其他很好的增强功能,旧的项访问语法在Robot Framework 3.2中被弃用。
It is possible to access a certain item of a variable containing a sequence
(e.g. list, string or bytes) with the syntax ${var}[index]
, where index
is the index of the selected value. Indices start from zero, negative indices
can be used to access items from the end, and trying to access an item with
too large an index causes an error. Indices are automatically converted to
integers, and it is also possible to use variables as indices.
可以使用语法${var}[index]
访问包含序列(例如列表、字符串或字节)的变量的某个项,其中index
是所选值的索引。索引从零开始,负索引可用于从末尾访问项,尝试访问索引过大的项会导致错误。索引自动转换为整数,也可以使用变量作为索引。
*** Test Cases ***
Positive index
Login ${USER}[0] ${USER}[1]
Title Should Be Welcome ${USER}[0]!
Negative index
Keyword ${SEQUENCE}[-1]
Index defined as variable
Keyword ${SEQUENCE}[${INDEX}]
Sequence item access supports also the same "slice" functionality as Python
with syntax like ${var}[1:]
. With this syntax you do not get a single
item but a slice of the original sequence. Same way as with Python you can
specify the start index, the end index, and the step:
序列项访问也支持与Python相同的“切片”功能,语法为${var}[1:]
。使用这种语法,你得到的不是单个项,而是原始序列的一个片段。和Python一样,你可以指定开始索引、结束索引和步骤:
*** Test Cases ***
Start index
Keyword ${SEQUENCE}[1:]
End index
Keyword ${SEQUENCE}[:4]
Start and end
Keyword ${SEQUENCE}[2:-1]
Step
Keyword ${SEQUENCE}[::2]
Keyword ${SEQUENCE}[1:-1:10]
Note 注意
The slice syntax is new in Robot Framework 3.1. It was extended to work
with list expansion like @{var}[1:]
in Robot Framework 4.0.
切片语法是Robot Framework 3.1中的新语法。它被扩展为在Robot Framework 4.0中使用列表扩展,如@{var}[1:]
。
Note 注意
Prior to Robot Framework 3.2, item and slice access was only supported
with variables containing lists, tuples, or other objects considered
list-like. Nowadays all sequences, including strings and bytes, are
supported.
在Robot Framework 3.2之前,仅支持包含列表、元组或其他被视为类似列表的对象的变量的项和切片访问。现在支持所有序列,包括字符串和字节。
It is possible to access a certain value of a dictionary variable
with the syntax ${NAME}[key]
, where key
is the name of the
selected value. Keys are considered to be strings, but non-strings
keys can be used as variables. Dictionary values accessed in this
manner can be used similarly as scalar variables.
可以使用语法${NAME}[key]
访问字典变量的某个值,其中key
是所选值的名称。键被认为是字符串,但非字符串键可以用作变量。以这种方式访问的字典值可以类似地用作标量变量。
If a key is a string, it is possible to access its value also using
attribute access syntax ${NAME.key}
. See Creating dictionary variables
for more details about this syntax.
如果键是字符串,则也可以使用属性访问语法${NAME.key}
访问其值。有关此语法的更多详细信息,请参见创建字典变量。
*** Test Cases ***
Dictionary variable item
Login ${USER}[name] ${USER}[password]
Title Should Be Welcome ${USER}[name]!
Key defined as variable
Log Many ${DICT}[${KEY}] ${DICT}[${42}]
Attribute access
Login ${USER.name} ${USER.password}
Title Should Be Welcome ${USER.name}!
Also nested subscriptable variables can be accessed using the same
item access syntax like ${var}[item1][item2]
. This is especially useful
when working with JSON data often returned by REST services. For example,
if a variable ${DATA}
contains [{'id': 1, 'name': 'Robot'},
{'id': 2, 'name': 'Mr. X'}]
, this tests would pass:
嵌套的下标变量也可以使用相同的项访问语法来访问,如${var}[item 1][item 2]
。这在处理通常由REST服务返回的JSON数据时特别有用。例如,如果变量${DATA}
包含['id':1,'name':'Robot'},'id':2,'name':'Mr. X'}]
,则此测试将通过:
*** Test Cases ***
Nested item access
Should Be Equal ${DATA}[0][name] Robot
Should Be Equal ${DATA}[1][id] ${2}
Robot Framework allows using environment variables in the test data using
the syntax %{ENV_VAR_NAME}
. They are limited to string values. It is
possible to specify a default value, that is used if the environment
variable does not exists, by separating the variable name and the default
value with an equal sign like %{ENV_VAR_NAME=default value}
.
Robot Framework允许使用语法%{ENV_VAR_NAME}
在测试数据中使用环境变量。它们仅限于字符串值。可以指定一个默认值,如果环境变量不存在,可以使用等号分隔变量名和默认值,如%{ENV_VAR_NAME=default value}
。
Environment variables set in the operating system before the test execution are
available during it, and it is possible to create new ones with the keyword
Set Environment Variable or delete existing ones with the
keyword Delete Environment Variable, both available in the
OperatingSystem library. Because environment variables are global,
environment variables set in one test case can be used in other test
cases executed after it. However, changes to environment variables are
not effective after the test execution.
在测试执行之前在操作系统中设置的环境变量在测试期间可用,并且可以使用关键字Set Environment Variable创建新的环境变量或使用关键字Delete Environment Variable删除现有的环境变量,这两个都在OperatingSystem库中可用。因为环境变量是全局的,所以在一个测试用例中设置的环境变量可以在之后执行的其他测试用例中使用,但是在测试执行之后对环境变量的更改是无效的。
*** Test Cases ***
Environment variables
Log Current user: %{USER}
Run %{JAVA_HOME}${/}javac
Environment variables with defaults
Set port %{APPLICATION_PORT=8080}
Note 注意
Support for specifying the default value is new in Robot Framework 3.2.
Robot Framework 3.2中新增了对指定默认值的支持。
Variables can spring into existence from different sources.
变量可以从不同的来源出现。
The most common source for variables are Variable sections in suite files
and resource files. Variable sections are convenient, because they
allow creating variables in the same place as the rest of the test
data, and the needed syntax is very simple. Their main disadvantages are
that values are always strings and they cannot be created dynamically.
If either of these is a problem, variable files can be used instead.
变量最常见的来源是套件文件和资源文件中的Variable部分。变量部分很方便,因为它们允许在与其余测试数据相同的地方创建变量,并且所需的语法非常简单。它们的主要缺点是值总是字符串,并且不能动态创建。如果这两种情况都有问题,可以使用变量文件。
The simplest possible variable assignment is setting a string into a
scalar variable. This is done by giving the variable name (including
${}
) in the first column of the Variable section and the value in
the second one. If the second column is empty, an empty string is set
as a value. Also an already defined variable can be used in the value.
最简单的变量赋值是将字符串设置为标量变量。这是通过在变量部分的第一列中给出变量名(包括${}
)并在第二列中给出值来完成的。如果第二列为空,则将空字符串设置为值。也可以在值中使用已经定义的变量。
*** Variables ***
${NAME} Robot Framework
${VERSION} 2.0
${ROBOT} ${NAME} ${VERSION}
It is also possible, but not obligatory,
to use the equals sign =
after the variable name to make assigning
variables slightly more explicit.
也可以在变量名后使用等号=
,使变量的赋值更加明确,但这不是必须的。
*** Variables ***
${NAME} = Robot Framework
${VERSION} = 2.0
If a scalar variable has a long value, it can be split into multiple rows
by using the ...
syntax. By default rows are concatenated together using
a space, but this can be changed by using a having separator
configuration
option after the last value:
如果一个标量变量有一个长值,它可以通过使用.
语法.默认情况下,行使用空格连接在一起,但这可以通过在最后一个值之后使用具有分隔符
配置选项来更改:
*** Variables ***
${EXAMPLE} This value is joined
... together with a space.
${MULTILINE} First line.
... Second line.
... Third line.
... separator=\n
The separator
option is new in Robot Framework 7.0, but also older versions
support configuring the separator. With them the first value can contain a
special SEPARATOR
marker:分隔符
选项是Robot Framework 7.0中的新选项,但旧版本也支持配置分隔符。使用它们,第一个值可以包含一个特殊的SEPARATOR
标记:
*** Variables ***
${MULTILINE} SEPARATOR=\n
... First line.
... Second line.
... Third line.
Both the separator
option and the SEPARATOR
marker are case-sensitive.
Using the separator
option is recommended, unless there is a need to
support also older versions.分隔符
选项和SEPARATOR
标记都区分大小写。建议使用分隔符
选项,除非需要支持旧版本。
Creating list variables is as easy as creating scalar variables. Again, the
variable name is in the first column of the Variable section and
values in the subsequent columns. A list variable can have any number
of values, starting from zero, and if many values are needed, they
can be split into several rows.
创建列表变量和创建标量变量一样简单。同样,变量名位于Variable部分的第一列,值位于后续列。一个列表变量可以有任意数量的值,从零开始,如果需要很多值,可以将它们分成几行。
*** Variables ***
@{NAMES} Matti Teppo
@{NAMES2} @{NAMES} Seppo
@{NOTHING}
@{MANY} one two three four
... five six seven
Dictionary variables can be created in the Variable section similarly as
list variables. The difference is that items need to be created using
name=value
syntax or existing dictionary variables. If there are multiple
items with same name, the last value has precedence. If a name contains
a literal equal sign, it can be escaped with a backslash like \=
.
字典变量可以在变量部分中创建,类似于列表变量。不同之处在于,需要使用name=value
语法或现有的字典变量来创建项。如果有多个项目具有相同的名称,则最后一个值具有优先级。如果一个名字包含一个相等的符号,它可以用一个反斜杠转义,比如\=
。
*** Variables ***
&{USER 1} name=Matti address=xxx phone=123
&{USER 2} name=Teppo address=yyy phone=456
&{MANY} first=1 second=${2} ${3}=third
&{EVEN MORE} &{MANY} first=override empty=
... =empty key\=here=value
Dictionary variables have two extra properties
compared to normal Python dictionaries. First of all, values of these
dictionaries can be accessed like attributes, which means that it is possible
to use extended variable syntax like ${VAR.key}
. This only works if the
key is a valid attribute name and does not match any normal attribute
Python dictionaries have. For example, individual value &{USER}[name]
can
also be accessed like ${USER.name}
(notice that $
is needed in this
context), but using ${MANY.3}
is not possible.
与普通Python字典相比,字典变量有两个额外的属性。首先,这些字典的值可以像属性一样访问,这意味着可以使用扩展变量语法,如${VAR.key}
。只有当键是一个有效的属性名,并且不匹配Python字典中的任何普通属性时,这才有效。例如,单个值&{USER}[name]
也可以像${USER.name}一样
访问(注意在此上下文中需要$
),但使用${MANY.3}
是不可能的。
Tip 尖端
With nested dictionary variables keys are accessible like
${VAR.nested.key}
. This eases working with nested data structures.
对于嵌套字典变量,可以像${VAR.nested.key}一样
访问键。这简化了使用嵌套数据结构的工作。
Another special property of dictionary variables is
that they are ordered. This means that if these dictionaries are iterated,
their items always come in the order they are defined. This can be useful
if dictionaries are used as list variables with FOR loops or otherwise.
When a dictionary is used as a list variable, the actual value contains
dictionary keys. For example, @{MANY}
variable would have value ['first',
'second', 3]
.
字典变量的另一个特殊属性是它们是有序的。这意味着如果这些字典被迭代,它们的项总是按照定义的顺序出现。如果字典被用作带有FOR循环或其他方式的列表变量,这可能很有用。当字典用作列表变量时,实际值包含字典键。例如,@{MANY}
变量将具有值“first”,“second”,3]
。
Starting from Robot Framework 7.0, it is possible to create the variable name
dynamically based on another variable:
从Robot Framework 7.0开始,可以基于另一个变量动态创建变量名:
*** Variables ***
${X} Y
${${X}} Z # Name is created based on '${X}'.
*** Test Cases ***
Dynamically created name
Should Be Equal ${Y} Z
Variable files are the most powerful mechanism for creating different
kind of variables. It is possible to assign variables to any object
using them, and they also enable creating variables dynamically. The
variable file syntax and taking variable files into use is explained
in section Resource and variable files.
变量文件是创建不同类型变量的最强大的机制。可以使用它们将变量分配给任何对象,并且它们还可以动态创建变量。在资源和变量文件一节中解释了变量文件的语法和如何使用变量文件。
Variables can be set from the command line either individually with
the --variable (-v) option or using a variable file with the
--variablefile (-V) option. Variables set from the command line
are globally available for all executed test data files, and they also
override possible variables with the same names in the Variable section and in
variable files imported in the test data.
变量可以在命令行中单独使用--variable(-v)选项设置,也可以使用带有--variablefile(-V)选项的变量文件设置。从命令行设置的变量对于所有执行的测试数据文件都是全局可用的,并且它们还覆盖在变量部分和在测试数据中导入的变量文件中具有相同名称的可能变量。
The syntax for setting individual variables is --variable
name:value, where name
is the name of the variable without
${}
and value
is its value. Several variables can be
set by using this option several times. Only scalar variables can be
set using this syntax and they can only get string values.
设置单个变量的语法是--variable name:value,其中name
是不带${}的
变量的名称,value
是它的值。多次使用此选项可以设置多个变量。只有标量变量可以使用此语法设置,并且它们只能获取字符串值。
--variable EXAMPLE:value
--variable HOST:localhost:7272 --variable USER:robot
In the examples above, variables are set so that
在上面的例子中,变量被设置为
${EXAMPLE}
gets the value value
${EXAMPLE}
获取value值
${HOST}
and ${USER}
get the values
localhost:7272
and robot
${HOST}
和${USER}
获取值localhost:7272
和robot
The basic syntax for taking variable files into use from the command line
is --variablefile path/to/variables.py, and Taking variable files into
use section has more details. What variables actually are created depends on
what variables there are in the referenced variable file.
从命令行使用变量文件的基本语法是--variablefile path/to/variables.py,使用变量文件一节有更多的细节。实际创建的变量取决于引用的变量文件中有哪些变量。
If both variable files and individual variables are given from the command line,
the latter have higher priority.
如果变量文件和单个变量都是从命令行给出的,则后者具有更高的优先级。
Return values from keywords can also be set into variables. This
allows communication between different keywords even in different test
libraries.
关键字的返回值也可以设置为变量。这允许不同关键字之间的通信,即使在不同的测试库中。
Variables set in this manner are otherwise similar to any other
variables, but they are available only in the local scope
where they are created. Thus it is not possible, for example, to set
a variable like this in one test case and use it in another. This is
because, in general, automated test cases should not depend on each
other, and accidentally setting a variable that is used elsewhere
could cause hard-to-debug errors. If there is a genuine need for
setting a variable in one test case and using it in another, it is
possible to use BuiltIn keywords as explained in the next section.
以这种方式设置的变量在其他方面与任何其他变量类似,但它们仅在创建它们的局部范围内可用。因此,例如,在一个测试用例中设置这样的变量并在另一个测试用例中使用它是不可能的。这是因为,一般来说,自动化测试用例不应该相互依赖,并且意外地设置在其他地方使用的变量可能会导致难以调试的错误。如果确实需要在一个测试用例中设置一个变量,并在另一个测试用例中使用它,那么可以使用BuiltIn关键字,如下一节所述。
Any value returned by a keyword can be assigned to a scalar variable.
As illustrated by the example below, the required syntax is very simple:
关键字返回的任何值都可以赋给标量变量。如下面的例子所示,所需的语法非常简单:
*** Test Cases ***
Returning
${x} = Get X an argument
Log We got ${x}!
In the above example the value returned by the Get X keyword
is first set into the variable ${x}
and then used by the Log
keyword. Having the equals sign =
after the variable name is
not obligatory, but it makes the assignment more explicit. Creating
local variables like this works both in test case and user keyword level.
在上面的示例中,Get X关键字返回的值首先设置为变量${x}
,然后由Log关键字使用。在变量名后使用等号=
不是强制性的,但它使赋值更加明确。像这样创建局部变量在测试用例和用户关键字级别都有效。
Notice that although a value is assigned to a scalar variable, it can
be used as a list variable if it has a list-like value and as a dictionary
variable if it has a dictionary-like value.
请注意,尽管值被分配给标量变量,但如果它具有类似列表的值,则可以将其用作列表变量,如果它具有类似字典的值,则可以将其用作字典变量。
*** Test Cases ***
Example
${list} = Create List first second third
Length Should Be ${list} 3
Log Many @{list}
Starting from Robot Framework 6.1, when working with variables that support
item assignment such as lists or dictionaries, it is possible to set their values
by specifying the index or key of the item using the syntax ${var}[item]
where the item
part can itself contain a variable:
从Robot Framework 6.1开始,当使用支持列表或字典等项赋值的变量时,可以通过使用语法${var}[item]指定
项的索引或键来设置它们的值,其中项
部分本身可以包含变量:
*** Test Cases ***
Item assignment to list
${list} = Create List one two three four
${list}[0] = Set Variable first
${list}[${1}] = Set Variable second
${list}[2:3] = Evaluate ['third']
${list}[-1] = Set Variable last
Log Many @{list} # Logs 'first', 'second', 'third' and 'last'
Item assignment to dictionary
${dict} = Create Dictionary first_name=unknown
${dict}[first_name] = Set Variable John
${dict}[last_name] = Set Variable Doe
Log ${dictionary} # Logs {'first_name': 'John', 'last_name': 'Doe'}
Starting from Robot Framework 7.0, it is possible to create the name of the assigned
variable dynamically based on another variable:
从Robot Framework 7.0开始,可以根据另一个变量动态创建分配变量的名称:
*** Test Cases ***
Dynamically created name
${x} = Set Variable y
${${x}} = Set Variable z # Name is created based on '${x}'.
Should Be Equal ${y} z
If a keyword returns a list or any list-like object, it is possible to
assign it to a list variable:
如果一个关键字返回一个列表或任何类似列表的对象,可以将其分配给一个列表变量:
*** Test Cases ***
Example
@{list} = Create List first second third
Length Should Be ${list} 3
Log Many @{list}
Because all Robot Framework variables are stored in the same namespace, there is
not much difference between assigning a value to a scalar variable or a list
variable. This can be seen by comparing the last two examples above. The main
differences are that when creating a list variable, Robot Framework
automatically verifies that the value is a list or list-like, and the stored
variable value will be a new list created from the return value. When
assigning to a scalar variable, the return value is not verified and the
stored value will be the exact same object that was returned.
由于所有Robot Framework变量都存储在同一个命名空间中,因此将值分配给标量变量或列表变量之间没有太大区别。通过比较上面的最后两个示例可以看出这一点。主要区别在于,当创建列表变量时,Robot Framework会自动验证该值是否为列表或类似列表,存储的变量值将是从返回值创建的新列表。当分配给标量变量时,不会验证返回值,并且存储的值将与返回的对象完全相同。
If a keyword returns a dictionary or any dictionary-like object, it is possible
to assign it to a dictionary variable:
如果一个关键字返回一个字典或任何类似字典的对象,可以将其分配给一个字典变量:
*** Test Cases ***
Example
&{dict} = Create Dictionary first=1 second=${2} ${3}=third
Length Should Be ${dict} 3
Do Something &{dict}
Log ${dict.first}
Because all Robot Framework variables are stored in the same namespace, it would
also be possible to assign a dictionary into a scalar variable and use it
later as a dictionary when needed. There are, however, some actual benefits
in creating a dictionary variable explicitly. First of all, Robot Framework
verifies that the returned value is a dictionary or dictionary-like similarly
as it verifies that list variables can only get a list-like value.
由于所有Robot Framework变量都存储在同一个命名空间中,因此也可以将字典分配给标量变量,并在以后需要时将其用作字典。然而,显式创建字典变量有一些实际的好处。首先,Robot Framework验证返回值是否是字典或类似字典的值,就像它验证列表变量只能获得类似列表的值一样。
A bigger benefit is that the value is converted into a special dictionary
that it uses also when creating dictionary variables in the Variable section.
Values in these dictionaries can be accessed using attribute access like
${dict.first}
in the above example. These dictionaries are also ordered, but
if the original dictionary was not ordered, the resulting order is arbitrary.
一个更大的好处是,该值被转换为一个特殊的字典,当在Variable部分创建字典变量时也会使用该字典。这些字典中的值可以使用属性访问来访问,如上面示例中的${dict.first}
。这些字典也是有序的,但是如果原始字典没有排序,那么结果的顺序是任意的。
If a keyword returns a list or a list-like object, it is possible to assign
individual values into multiple scalar variables or into scalar variables and
a list variable.
如果关键字返回一个列表或类似列表的对象,则可以将单个值分配给多个标量变量或标量变量和列表变量。
*** Test Cases ***
Assign multiple
${a} ${b} ${c} = Get Three
${first} @{rest} = Get Three
@{before} ${last} = Get Three
${begin} @{middle} ${end} = Get Three
Assuming that the keyword Get Three returns a list [1, 2, 3]
,
the following variables are created:
假设关键字Get Three返回列表[1,2,3]
,则创建以下变量:
${a}
, ${b}
and ${c}
with values 1
, 2
, and 3
, respectively.1
、2
和3
的${a}
、${B}
和${c}
。${first}
with value 1
, and @{rest}
with value [2, 3]
.1的
${first}
和值为[2,3]
的@{rest}
。@{before}
with value [1, 2]
and ${last}
with value 3
.@{before}
的值为[1,2]
,${last}
的值为3
。${begin}
with value 1
, @{middle}
with value [2]
and ${end} with
value 3
.${开始}
的值为1
,@{中间}
的值为[2]
,${结束}的值为3
。It is an error if the returned list has more or less values than there are
scalar variables to assign. Additionally, only one list variable is allowed
and dictionary variables can only be assigned alone.
如果返回的列表中的值多于或少于要分配的标量变量,则为错误。此外,只允许一个列表变量,字典变量只能单独赋值。
To make it easier to understand what happens during execution,
the beginning of value that is assigned is automatically logged.
The default is to show 200 first characters, but this can be changed
by using the --maxassignlength command line option when
running tests. If the value is zero or negative, the whole assigned
value is hidden.
为了更容易理解执行过程中发生的情况,会自动记录所分配值的开头。默认值是显示前200个字符,但是可以在运行测试时使用--maxassignlength命令行选项来更改。如果该值为零或负数,则隐藏整个赋值。
--maxassignlength 1000
--maxassignlength 0
The reason the value is not logged fully is that it could be really
big. If you always want to see a certain value fully, it is possible
to use the BuiltIn Log keyword to log it after the assignment.
没有完全记录该值的原因是它可能非常大。如果您总是希望完整地查看某个值,则可以在赋值后使用BuiltInLog
Note 注意
The --maxassignlength option is new in Robot Framework 5.0.
--maxassignlength 选项是Robot Framework 5.0中的新选项。
VAR
syntaxVAR
语法Starting from Robot Framework 7.0, it is possible to create variables inside
tests and user keywords using the VAR
syntax. The VAR
marker is case-sensitive
and it must be followed by a variable name and value. Other than the mandatory
VAR
, the overall syntax is mostly the same as when creating variables
in the Variable section.
从Robot Framework 7.0开始,可以使用VAR
语法在测试和用户关键字中创建变量。VAR
标记区分大小写,并且后面必须跟有变量名和值。除了强制的VAR之外
,整体语法与在Variable部分中创建变量时基本相同。
The new syntax is aims to make creating variables simpler and more uniform. It is
especially indented to replace the BuiltIn keywords Set Variable,
Set Test Variable, Set Suite Variable and Set Global Variable,
but it can be used instead of Catenate, Create List and
Create Dictionary as well.
新的语法旨在使创建变量更简单,更统一。它特别缩进以替换内置关键字Set Variable,Set Test Variable,Set Suite Variable和Set Global Variable,但它也可以用来代替Catenate,Create List和Create Dictionary。
In simple cases scalar variables are created by just giving a variable name
and its value. The value can be a hard-coded string or it can itself contain
a variable. If the value is long, it is possible to split it into multiple
columns and rows. In that case parts are joined together with a space by default,
but the separator to use can be specified with the separator
configuration
option. It is possible to have an optional =
after the variable name the same
way as when creating variables based on return values from keywords and in
the Variable section.
在简单的情况下,标量变量只需要给出一个变量名和它的值就可以创建。该值可以是硬编码的字符串,也可以本身包含变量。如果值很长,则可以将其拆分为多个列和行。在这种情况下,默认情况下,部件通过空格连接在一起,但可以使用分隔符
配置选项指定要使用的分隔符。可以在变量名后面加上一个可选的=
,就像根据关键字的返回值和Variable部分创建变量一样。
*** Test Cases ***
Scalar examples
VAR ${simple} variable
VAR ${equals} = this works too
VAR ${variable} value contains ${simple}
VAR ${sentence} This is a bit longer variable value
... that is split into multiple rows.
... These parts are joined with a space.
VAR ${multiline} This is another longer value.
... This time there is a custom separator.
... As the result this becomes a multiline string.
... separator=\n
List and dictionary variables are created similarly as scalar variables.
When creating dictionaries, items must be specified using the name=value
syntax.
列表和字典变量的创建方式与标量变量类似。创建字典时,必须使用name=value
语法指定项。
*** Test Cases ***
List examples
VAR @{two items} Robot Framework
VAR @{empty list}
VAR @{lot of stuff}
... first item
... second item
... third item
... fourth item
... last item
Dictionary examples
VAR &{two items} name=Robot Framework url=http://robotframework.org
VAR &{empty dict}
VAR &{lot of stuff}
... first=1
... second=2
... third=3
... fourth=4
... last=5
Variables created with the VAR
syntax are are available only within the test
or user keyword where they are created. That can, however, be altered by using
the scope
configuration option. Supported values are LOCAL
(default),
TEST
(available within the current test), TASK
(alias for TEST
), SUITE
(available within the current suite) and GLOBAL
(available globally).
Although Robot Framework variables are case-insensitive, it is recommended to
use capital letters with non-local variable names.
使用VAR
语法创建的变量仅在创建它们的test或user关键字中可用。但是,这可以通过使用范围
配置选项进行更改。支持的值包括LOCAL
(默认)、TEST
(在当前测试中可用)、ASK
(TEST
的别名)、SUITE
(在当前套件中可用)和GLOBAL
(在全球可用)。虽然Robot Framework变量不区分大小写,但建议在非局部变量名称中使用大写字母。
*** Variables ***
${SUITE} this value is overridden
*** Test Cases ***
Scope example
VAR ${local} local value
VAR ${TEST} test value scope=TEST
VAR ${SUITE} suite value scope=SUITE
VAR ${GLOBAL} global value scope=GLOBAL
Should Be Equal ${local} local value
Should Be Equal ${TEST} test value
Should Be Equal ${SUITE} suite value
Should Be Equal ${GLOBAL} global value
Keyword
Should Be Equal ${TEST} new test value
Should Be Equal ${SUITE} new suite value
Should Be Equal ${GLOBAL} new global value
Scope example, part 2
Should Be Equal ${SUITE} new suite value
Should Be Equal ${GLOBAL} new global value
*** Keywords ***
Keyword
Should Be Equal ${TEST} test value
Should Be Equal ${SUITE} suite value
Should Be Equal ${GLOBAL} global value
VAR ${TEST} new ${TEST} scope=TEST
VAR ${SUITE} new ${SUITE} scope=SUITE
VAR ${GLOBAL} new ${GLOBAL} scope=GLOBAL
Should Be Equal ${TEST} new test value
Should Be Equal ${SUITE} new suite value
Should Be Equal ${GLOBAL} new global value
The VAR
syntax works with IF/ELSE structures which makes it easy to create
variables conditionally. In simple cases using inline IF can be convenient.VAR
语法与IF/ELSE结构一起工作,这使得有条件地创建变量变得容易。在简单的情况下,使用内联IF可能很方便。
*** Test Cases ***
IF/ELSE example
IF "${ENV}" == "devel"
VAR ${address} 127.0.0.1
VAR ${name} demo
ELSE
VAR ${address} 192.168.1.42
VAR ${name} robot
END
Inline IF
IF "${ENV}" == "devel" VAR ${name} demo ELSE VAR ${name} robot
If there is a need, variable name can also be created dynamically based on
another variable.
如果有需要,变量名也可以根据另一个变量动态创建。
*** Test Cases ***
Dynamic name
VAR ${x} y # Normal assignment.
VAR ${${x}} z # Name created dynamically.
Should Be Equal ${y} z
Note 注意
The VAR
syntax is recommended over these keywords when using
Robot Framework 7.0 or newer.
使用Robot Framework 7.0或更高版本时,建议使用VAR
语法而不是这些关键字。
The BuiltIn library has keywords Set Test Variable,
Set Suite Variable and Set Global Variable which can
be used for setting variables dynamically during the test
execution. If a variable already exists within the new scope, its
value will be overwritten, and otherwise a new variable is created.
BuiltIn库有关键字Set Test Variable、Set Suite Variable和Set Global Variable,可用于在测试执行期间动态设置变量。如果新范围内已存在变量,则其值将被覆盖,否则将创建新变量。
Variables set with Set Test Variable keyword are available
everywhere within the scope of the currently executed test case. For
example, if you set a variable in a user keyword, it is available both
in the test case level and also in all other user keywords used in the
current test. Other test cases will not see variables set with this
keyword. It is an error to call Set Test Variable
outside the scope of a test (e.g. in a Suite Setup or Teardown).
使用Set Test Variable关键字设置的变量在当前执行的测试用例范围内的任何地方都可用。例如,如果您在用户关键字中设置了一个变量,则它在测试用例级别和当前测试中使用的所有其他用户关键字中都可用。其他测试用例不会看到使用此关键字设置的变量。在测试范围之外调用设置测试变量是错误的(例如,在套件设置或拆卸中)。
Variables set with Set Suite Variable keyword are available
everywhere within the scope of the currently executed test
suite. Setting variables with this keyword thus has the same effect as
creating them using the Variable section 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.
使用Set Suite Variable关键字设置的变量在当前执行的测试套件范围内的任何地方都可用。因此,使用此关键字设置变量与使用测试数据文件中的Variable部分创建变量或从变量文件导入变量具有相同的效果。其他测试套件,包括可能的子测试套件,将不会看到使用此关键字设置的变量。
Variables set with Set Global Variable keyword are globally
available in all test cases and suites executed after setting
them. Setting variables with this keyword thus has the same effect as
creating from the command line using the options --variable or
--variablefile. Because this keyword can change variables
everywhere, it should be used with care.
使用Set Global Variable关键字设置的变量在设置后执行的所有测试用例和套件中全局可用。因此,使用此关键字设置变量与使用选项--variable或--variablefile从命令行创建变量具有相同的效果。因为这个关键字可以在任何地方改变变量,所以应该小心使用。
Note 注意
Set Test/Suite/Global Variable keywords set named
variables directly into test, suite or global variable scope
and return nothing. On the other hand, another BuiltIn keyword
Set Variable sets local variables using return values.
Set Test/Suite/Global Variable关键字将命名变量直接设置到test、suite或global变量范围内,并不返回任何内容。另一方面,另一个内置关键字Set Variable使用返回值设置局部变量。
Robot Framework provides some built-in variables that are available
automatically.
Robot Framework提供了一些自动可用的内置变量。
Built-in variables related to the operating system ease making the test data
operating-system-agnostic.
与操作系统相关的内置变量使测试数据与操作系统无关变得容易。
Variable 可变 | Explanation 解释 |
---|---|
${CURDIR} 联系我们 | An absolute path to the directory where the test data
file is located. This variable is case-sensitive. 测试数据文件所在目录的绝对路径。此变量区分大小写。 |
${TEMPDIR} 联系我们 | An absolute path to the system temporary directory. In UNIX-like
systems this is typically /tmp, and in Windows
c:\Documents and Settings\<user>\Local Settings\Temp. 系统临时目录的绝对路径。在类UNIX系统中,这通常是/tmp,在Windowsc:\Documents and Settings\<user>\Local Settings\Temp中。 |
${EXECDIR} 联系我们 | An absolute path to the directory where test execution was
started from. 测试执行启动目录的绝对路径。 |
${/} | The system directory path separator. / in UNIX-like
systems and \ in Windows.系统目录路径分隔符。 / 在类UNIX系统中,\在Windows中。 |
${:} | The system path element separator. : in UNIX-like
systems and ; in Windows.系统路径元素分隔符。 : 在类UNIX系统中; 在Windows中。 |
${\n} 我的天 | The system line separator. \n in UNIX-like systems
and \r\n in Windows. 系统行分隔符。\n在类UNIX系统中,\r\n在Windows中。 |
*** Test Cases ***
Example
Create Binary File ${CURDIR}${/}input.data Some text here${\n}on two lines
Set Environment Variable CLASSPATH ${TEMPDIR}${:}${CURDIR}${/}foo.jar
The variable syntax can be used for creating both integers and
floating point numbers, as illustrated in the example below. This is
useful when a keyword expects to get an actual number, and not a
string that just looks like a number, as an argument.
变量语法可用于创建整数和浮点数,如下例所示。当关键字期望获得一个实际的数字,而不是一个看起来像数字的字符串作为参数时,这很有用。
*** Test Cases ***
Example 1A
Connect example.com 80 # Connect gets two strings as arguments
Example 1B
Connect example.com ${80} # Connect gets a string and an integer
Example 2
Do X ${3.14} ${-1e-4} # Do X gets floating point numbers 3.14 and -0.0001
It is possible to create integers also from binary, octal, and
hexadecimal values using 0b
, 0o
and 0x
prefixes, respectively.
The syntax is case insensitive.
也可以分别使用0b
、0o
和0x
前缀从二进制、八进制和十六进制值创建整数。语法不区分大小写。
*** Test Cases ***
Example
Should Be Equal ${0b1011} ${11}
Should Be Equal ${0o10} ${8}
Should Be Equal ${0xff} ${255}
Should Be Equal ${0B1010} ${0XA}
Also Boolean values and Python None
can
be created using the variable syntax similarly as numbers.
布尔值和PythonNone
也可以使用变量语法创建,类似于数字。
*** Test Cases ***
Boolean
Set Status ${true} # Set Status gets Boolean true as an argument
Create Y something ${false} # Create Y gets a string and Boolean false
None
Do XYZ ${None} # Do XYZ gets Python None as an argument
These variables are case-insensitive, so for example ${True}
and
${true}
are equivalent.
这些变量不区分大小写,例如${True}
和${true}
是等价的。
It is possible to create spaces and empty strings using variables
${SPACE}
and ${EMPTY}
, respectively. These variables are
useful, for example, when there would otherwise be a need to escape
spaces or empty cells with a backslash. If more than one space is
needed, it is possible to use the extended variable syntax like
${SPACE * 5}
. In the following example, Should Be
Equal keyword gets identical arguments but those using variables are
easier to understand than those using backslashes.
可以分别使用变量${SPACE}
和${EMPTY}
创建空格和空字符串。这些变量很有用,例如,当需要用反斜杠转义空格或空单元格时。如果需要多个空格,可以使用扩展变量语法,如${SPACE * 5}
。在下面的示例中,Should Be Equal关键字获取相同的参数,但使用变量的参数比使用反斜杠的参数更容易理解。
*** Test Cases ***
One space
Should Be Equal ${SPACE} \ \
Four spaces
Should Be Equal ${SPACE * 4} \ \ \ \ \
Ten spaces
Should Be Equal ${SPACE * 10} \ \ \ \ \ \ \ \ \ \ \
Quoted space
Should Be Equal "${SPACE}" " "
Quoted spaces
Should Be Equal "${SPACE * 2}" " \ "
Empty
Should Be Equal ${EMPTY} \
There is also an empty list variable @{EMPTY}
and an empty dictionary
variable &{EMPTY}
. Because they have no content, they basically
vanish when used somewhere in the test data. They are useful, for example,
with test templates when the template keyword is used without
arguments or when overriding list or dictionary variables in different
scopes. Modifying the value of @{EMPTY}
or &{EMPTY}
is not possible.
还有一个空列表变量@{EMPTY}
和一个空字典变量&{EMPTY}
。因为它们没有内容,所以当在测试数据中的某个地方使用时,它们基本上就消失了。例如,当template关键字不带参数使用时,或者当重写不同范围中的列表或字典变量时,它们对测试模板很有用。无法修改@{EMPTY}
或&{EMPTY}
的值。
*** Test Cases ***
Template
[Template] Some keyword
@{EMPTY}
Override
Set Global Variable @{LIST} @{EMPTY}
Set Suite Variable &{DICT} &{EMPTY}
Note 注意
${SPACE}
represents the ASCII space (\x20
) and other spaces
should be specified using the escape sequences like \xA0
(NO-BREAK SPACE) and \u3000
(IDEOGRAPHIC SPACE).${SPACE}
表示ASCII空格(\x20
),其他空格应使用转义序列指定,如\xA0
(NO-BREAK SPACE)和\u3000
(IDEOGRAPHIC SPACE)。
Some automatic variables can also be used in the test data. These
variables can have different values during the test execution and some
of them are not even available all the time. Altering the value of
these variables does not affect the original values, but some values
can be changed dynamically using keywords from the BuiltIn library.
一些自动变量也可以用于测试数据。这些变量在测试执行期间可以有不同的值,其中一些甚至不是一直可用的。更改这些变量的值不会影响原始值,但可以使用BuiltIn库中的关键字动态更改某些值。
Variable 可变 | Explanation 解释 | Available 可用 |
---|---|---|
${TEST NAME} ${测试名称} | The name of the current test case. 当前测试用例的名称。 |
Test case 测试用例 |
@{TEST TAGS} @{测试标签} | Contains the tags of the current test case in
alphabetical order. Can be modified dynamically using
Set Tags and Remove Tags keywords. 按字母顺序包含当前测试用例的标记。可以使用Set Tags和Remove Tags关键字动态修改。 |
Test case 测试用例 |
${TEST DOCUMENTATION} ${测试文件} | The documentation of the current test case. Can be set
dynamically using using Set Test Documentation
keyword. 当前测试用例的文档。可以使用Set Test Documentation关键字动态设置。 |
Test case 测试用例 |
${TEST STATUS} ${测试状态} | The status of the current test case, either PASS or
FAIL. 当前测试用例的状态,通过或未通过。 |
Test teardown 测试拆卸 |
${TEST MESSAGE} ${测试消息} | The message of the current test case. 当前测试用例的消息。 |
Test teardown 测试拆卸 |
${PREV TEST NAME} ${上一个测试名称} | The name of the previous test case, or an empty string
if no tests have been executed yet. 前一个测试用例的名称,如果尚未执行任何测试,则为空字符串。 |
Everywhere 到处 |
${PREV TEST STATUS} ${上一个测试状态} | The status of the previous test case: either PASS,
FAIL, or an empty string when no tests have been
executed. 前一个测试用例的状态:PASS、FAIL或空字符串(当没有执行测试时)。 |
Everywhere 到处 |
${PREV TEST MESSAGE} ${上一条测试消息} | The possible error message of the previous test case. 上一个测试用例的可能错误消息。 |
Everywhere 到处 |
${SUITE NAME} ${套房名称} | The full name of the current test suite. 当前测试套件的全名。 |
Everywhere 到处 |
${SUITE SOURCE} ${套件源} | An absolute path to the suite file or directory. 套件文件或目录的绝对路径。 |
Everywhere 到处 |
${SUITE DOCUMENTATION} ${套房文件} | The documentation of the current test suite. Can be
set dynamically using using Set Suite
Documentation keyword. 当前测试套件的文档。可以使用Set Suite Documentation关键字动态设置。 |
Everywhere 到处 |
&{SUITE METADATA} &{套件元数据} | The free metadata of the current test suite. Can be
set using Set Suite Metadata keyword. 当前测试套件的自由元数据。可以使用Set Suite Metadata关键字进行设置。 |
Everywhere 到处 |
${SUITE STATUS} ${套房状态} | The status of the current test suite, either PASS or
FAIL. 当前测试套件的状态,通过或失败。 |
Suite teardown 套房拆卸 |
${SUITE MESSAGE} ${套房消息} | The full message of the current test suite, including
statistics. 当前测试套件的完整消息,包括统计信息。 |
Suite teardown 套房拆卸 |
${KEYWORD STATUS} ${关键字状态} | The status of the current keyword, either PASS or
FAIL. 当前关键字的状态,PASS或FAIL。 |
User keyword teardown 用户关键字拆卸 |
${KEYWORD MESSAGE} ${关键字消息} | The possible error message of the current keyword. 当前关键字的可能错误消息。 |
User keyword teardown 用户关键字拆卸 |
${LOG LEVEL} 联系我们 | Current log level. 当前日志级别。 |
Everywhere 到处 |
${OUTPUT DIR} 联系我们 | An absolute path to the output directory as
a string. 以字符串形式表示的输出目录的绝对路径。 |
Everywhere 到处 |
${OUTPUT FILE} ${输出文件} | An absolute path to the output file as a string or
a string NONE if the output file is not created.输出文件的绝对路径,以字符串形式表示,如果未创建输出文件,则为字符串 NONE 。 |
Everywhere 到处 |
${LOG FILE} 联系我们 | An absolute path to the log file as a string or
a string NONE if the log file is not created.以字符串形式表示的日志文件的绝对路径,如果未创建日志文件,则为字符串 NONE 。 |
Everywhere 到处 |
${REPORT FILE} ${报告文件} | An absolute path to the report file as a string or
a string NONE if the report file is not created.以字符串形式显示的报表文件的绝对路径,如果未创建报表文件,则为字符串 NONE 。 |
Everywhere 到处 |
${DEBUG FILE} ${调试文件} | An absolute path to the debug file as a string or
a string NONE if the debug file is not created.调试文件的绝对路径,以字符串形式显示;如果未创建调试文件,则以字符串 NONE形式显示 。 |
Everywhere 到处 |
&{OPTIONS} {选项}(& O) | A dictionary exposing command line options. The
dictionary keys match the command line options and
can be accessed both like
New in RF 5.0. More options can be exposed later. |
Everywhere 到处 |
Suite related variables ${SUITE SOURCE}
, ${SUITE NAME}
, ${SUITE DOCUMENTATION}
and &{SUITE METADATA}
as well as options related to command line options like
${LOG FILE}
and &{OPTIONS}
are available already when libraries and variable
files are imported. Possible variables in these automatic variables are not yet
resolved at the import time, though.
导入库和变量文件时,与套件相关的变量${SUITE SOURCE}
、${SUITE NAME}
、${SUITE DOCUMENTATION}
和&{SUITE METADATA}
以及与命令行选项相关的选项(如${SUITE FILE}
和&{OPTIONS})
已经可用。但是,这些自动变量中的可能变量在导入时尚未解析。
Variables coming from different sources have different priorities and
are available in different scopes.
来自不同来源的变量具有不同的优先级,并且在不同的作用域中可用。
Variables from the command line
命令行中的变量
Variables set in the command line have the highest priority of all variables that can be set before the actual test execution starts. They override possible variables created in Variable sections in test case files, as well as in resource and variable files imported in the test data.
在命令行中设置的变量在实际测试执行开始之前可以设置的所有变量中具有最高的优先级。它们覆盖测试用例文件中的Variable部分以及测试数据中导入的资源和变量文件中创建的可能变量。Individually set variables (--variable option) override the variables set using variable files (--variablefile option). If you specify same individual variable multiple times, the one specified last will override earlier ones. This allows setting default values for variables in a start-up script and overriding them from the command line. Notice, though, that if multiple variable files have same variables, the ones in the file specified first have the highest priority.
单独设置的变量(--variable选项)覆盖使用变量文件(--variablefile选项)设置的变量。如果您多次指定同一个变量,最后指定的变量将覆盖前面的变量。这允许在启动脚本中设置变量的默认值,并从命令行覆盖它们。但请注意,如果多个变量文件具有相同的变量,则首先指定的文件中的变量具有最高优先级。
Variable section in a test case file
测试用例文件中的变量节
Variables created using the Variable section in a test case file are available for all the test cases in that file. These variables override possible variables with same names in imported resource and variable files.
使用测试用例文件中的Variable部分创建的变量可用于该文件中的所有测试用例。这些变量将覆盖导入的资源和变量文件中具有相同名称的可能变量。Variables created in the Variable sections are available in all other sections in the file where they are created. This means that they can be used also in the Setting section, for example, for importing more variables from resource and variable files.
在Variable部分中创建的变量在创建它们的文件的所有其他部分中可用。这意味着它们也可以在设置部分中使用,例如,从资源和变量文件导入更多变量。
Imported resource and variable files
导入的资源和变量文件
Variables imported from the resource and variable files have the lowest priority of all variables created in the test data. Variables from resource files and variable files have the same priority. If several resource and/or variable file have same variables, the ones in the file imported first are taken into use.
从资源和变量文件导入的变量在测试数据中创建的所有变量中具有最低的优先级。来自资源文件和变量文件的变量具有相同的优先级。如果多个资源和/或变量文件具有相同的变量,则使用首先导入的文件中的变量。If a resource file imports resource files or variable files, variables in its own Variable section have a higher priority than variables it imports. All these variables are available for files that import this resource file.
如果资源文件导入资源文件或变量文件,则其自身Variable节中的变量的优先级高于其导入的变量。所有这些变量都可用于导入此资源文件的文件。Note that variables imported from resource and variable files are not available in the Variable section of the file that imports them. This is due to the Variable section being processed before the Setting section where the resource files and variable files are imported.
请注意,从资源和变量文件导入的变量在导入它们的文件的Variable部分中不可用。这是由于Variable节在导入资源文件和变量文件的Setting节之前处理。
Variables set during test execution
测试执行期间设置的变量
Variables set during the test execution either using return values from keywords or using Set Test/Suite/Global Variable keywords always override possible existing variables in the scope where they are set. In a sense they thus have the highest priority, but on the other hand they do not affect variables outside the scope they are defined.
在测试执行期间使用关键字的返回值或使用Set Test/Suite/Global Variable关键字设置的变量总是覆盖设置它们的范围中可能存在的变量。在某种意义上,它们具有最高的优先级,但另一方面,它们不会影响它们定义的范围之外的变量。
Built-in variables 内置变量
Built-in variables like${TEMPDIR}
and${TEST_NAME}
have the highest priority of all variables. They cannot be overridden using Variable section or from command line, but even they can be reset during the test execution. An exception to this rule are number variables, which are resolved dynamically if no variable is found otherwise. They can thus be overridden, but that is generally a bad idea. Additionally${CURDIR}
is special because it is replaced already during the test data processing time.
内置变量,如${TEMPSTATE}
和${TEST_NAME},
在所有变量中具有最高的优先级。它们不能使用变量部分或命令行重写,但即使它们也可以在测试执行期间重置。此规则的一个例外是数字变量,如果没有找到其他变量,则会动态解析。因此,它们可以被覆盖,但这通常是一个坏主意。此外,${CURE}
很特殊,因为它在测试数据处理期间已经被替换。
Depending on where and how they are created, variables can have a
global, test suite, test case or local scope.
根据变量创建的位置和方式,变量可以具有全局、测试套件、测试用例或局部作用域。
Global variables are available everywhere in the test data. These
variables are normally set from the command line with the
--variable and --variablefile options, but it is also
possible to create new global variables or change the existing ones
by using the VAR syntax or the Set Global Variable keyword anywhere in
the test data. Additionally also built-in variables are global.
全局变量在测试数据中随处可见。这些变量通常通过命令行中的--variable和--variablefile选项进行设置,但也可以通过在测试数据中的任何位置使用VAR语法或Set Global Variable关键字来创建新的全局变量或更改现有变量。此外,内置变量也是全局的。
It is recommended to use capital letters with all global variables.
建议对所有全局变量使用大写字母。
Variables with the test suite scope are available anywhere in the
test suite where they are defined or imported. They can be created
in Variable sections, imported from resource and variable files,
or set during the test execution using the VAR syntax or the
Set Suite Variable keyword.
具有测试套件范围的变量在定义或导入它们的测试套件中的任何地方都可用。它们可以在Variable部分中创建,从资源和变量文件导入,或者在测试执行期间使用VAR语法或SetSuiteVariable关键字进行设置。
The test suite scope is not recursive, which means that variables
available in a higher-level test suite are not available in
lower-level suites. If necessary, resource and variable files can
be used for sharing variables.
测试套件范围不是递归的,这意味着在高级别测试套件中可用的变量在低级别套件中不可用。如果需要,可以使用资源和变量文件来共享变量。
Since these variables can be considered global in the test suite where
they are used, it is recommended to use capital letters also with them.
由于这些变量在使用它们的测试套件中可以被认为是全局的,因此建议也使用大写字母。
Variables with the test case scope are visible in a test case and in
all user keywords the test uses. Initially there are no variables in
this scope, but it is possible to create them by using the VAR syntax or
the Set Test Variable keyword anywhere in a test case.
Trying to create test variables in suite setup or suite teardown causes
and error.
具有测试用例范围的变量在测试用例和测试使用的所有用户关键字中可见。最初,在这个范围内没有变量,但是可以在测试用例的任何地方使用VAR语法或SetTestVariable关键字来创建它们。尝试在套件安装或套件拆卸原因和错误中创建测试变量。
Also variables in the test case scope are to some extend global. It is
thus generally recommended to use capital letters with them too.
测试用例作用域中的变量在某种程度上也是全局的。因此,通常建议也使用大写字母。
Test cases and user keywords have a local variable scope that is not
seen by other tests or keywords. Local variables can be created using
return values from executed keywords and with the VAR syntax,
and user keywords also get them as arguments.
测试用例和用户关键字具有其他测试或关键字看不到的局部变量范围。局部变量可以使用执行关键字的返回值和VAR语法创建,用户关键字也可以将它们作为参数获取。
It is recommended to use lower-case letters with local variables.
建议在局部变量中使用小写字母。
Extended variable syntax allows accessing attributes of an object assigned
to a variable (for example, ${object.attribute}
) and even calling
its methods (for example, ${obj.getName()}
). It works both with
scalar and list variables, but is mainly useful with the former.
扩展变量语法允许访问分配给变量的对象的属性(例如,${object.attribute}
),甚至调用其方法(例如,${obj.getName()}
)。它既适用于标量变量,也适用于列表变量,但主要适用于前者。
Extended variable syntax is a powerful feature, but it should
be used with care. Accessing attributes is normally not a problem, on
the contrary, because one variable containing an object with several
attributes is often better than having several variables. On the
other hand, calling methods, especially when they are used with
arguments, can make the test data pretty complicated to understand.
If that happens, it is recommended to move the code into a test library.
扩展变量语法是一个强大的特性,但应该小心使用。相反,多个属性通常不是问题,因为一个变量包含一个具有多个属性的对象通常比多个变量更好。另一方面,调用方法,特别是当它们与参数一起使用时,可能会使测试数据变得非常复杂,难以理解。如果发生这种情况,建议将代码移动到测试库中。
The most common usages of extended variable syntax are illustrated
in the example below. First assume that we have the following variable file
and test case:
扩展变量语法的最常见用法在下面的示例中说明。首先假设我们有以下变量文件和测试用例:
class MyObject:
def __init__(self, name):
self.name = name
def eat(self, what):
return '%s eats %s' % (self.name, what)
def __str__(self):
return self.name
OBJECT = MyObject('Robot')
DICTIONARY = {1: 'one', 2: 'two', 3: 'three'}
*** Test Cases ***
Example
KW 1 ${OBJECT.name}
KW 2 ${OBJECT.eat('Cucumber')}
KW 3 ${DICTIONARY[2]}
When this test data is executed, the keywords get the arguments as
explained below:
当执行此测试数据时,关键字获取参数,如下所述:
Robot
机器人
Robot eats Cucumber
机器人吃黄瓜
two
2
The extended variable syntax is evaluated in the following order:
扩展变量语法按以下顺序计算:
{
until
the first occurrence of a character that is not an alphanumeric character
or a space. For example, base variables of ${OBJECT.name}
and ${DICTIONARY[2]}
) are OBJECT
and DICTIONARY
,
respectively.
例如,${DICTION.name}
和${DICTIONARY[2]}
)的基变量分别为OBBLOG
和DICTIONARY
。Many standard Python objects, including strings and numbers, have
methods that can be used with the extended variable syntax either
explicitly or implicitly. Sometimes this can be really useful and
reduce the need for setting temporary variables, but it is also easy
to overuse it and create really cryptic test data. Following examples
show few pretty good usages.
许多标准Python对象,包括字符串和数字,都有方法可以显式或隐式地与扩展变量语法一起使用。有时候,这确实很有用,可以减少设置临时变量的需要,但也很容易过度使用它,并创建真正神秘的测试数据。下面的例子展示了一些很好的用法。
*** Test Cases ***
String
${string} = Set Variable abc
Log ${string.upper()} # Logs 'ABC'
Log ${string * 2} # Logs 'abcabc'
Number
${number} = Set Variable ${-2}
Log ${number * 10} # Logs -20
Log ${number.__abs__()} # Logs 2
Note that even though abs(number)
is recommended over
number.__abs__()
in normal Python code, using
${abs(number)}
does not work. This is because the variable name
must be in the beginning of the extended syntax. Using __xxx__
methods in the test data like this is already a bit questionable, and
it is normally better to move this kind of logic into test libraries.